⏰ IoT Digital Clock with RTC and Weather Information
This system displays the current time from an RTC module and real-time weather information on an OLED display using ESP32.
The DS3231 RTC ensures accurate time even if the ESP32 is restarted.
⚡ Hardware Required
- ESP32
- DS3231 RTC module (I²C)
- OLED SSD1306 display (I²C, 128x64)
- Jumper wires
- Breadboard
🔌 Connections
| Device | ESP32 Pin | Notes |
|---|---|---|
| OLED SDA | GPIO 21 | I²C Data |
| OLED SCL | GPIO 22 | I²C Clock |
| DS3231 SDA | GPIO 21 | I²C Data (shared with OLED) |
| DS3231 SCL | GPIO 22 | I²C Clock (shared with OLED) |
| VCC | 3.3V | Power |
| GND | GND | Ground |
🖥️ Full Code Example
c
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "RTClib.h"
// OLED
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// RTC
RTC_DS3231 rtc;
// Wi-Fi
const char* ssid = "YOUR_WIFI";
const char* password = "YOUR_PASS";
// OpenWeatherMap API
const String apiKey = "YOUR_API_KEY";
const String city = "YOUR_CITY";
const String countryCode = "YOUR_COUNTRY_CODE";
// Function to get weather info
String getWeather() {
HTTPClient http;
String weatherInfo = "";
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&appid=" + apiKey + "&units=metric";
http.begin(url);
int httpCode = http.GET();
if(httpCode > 0){
String payload = http.getString();
StaticJsonDocument<1024> doc;
deserializeJson(doc, payload);
float temp = doc["main"]["temp"];
const char* description = doc["weather"][0]["description"];
weatherInfo = String(temp) + "C " + String(description);
}
http.end();
return weatherInfo;
}
void setup() {
Serial.begin(115200);
// OLED
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // Set to compile time
}
// Wi-Fi
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
}
void loop() {
// Get current time from RTC
DateTime now = rtc.now();
char timeStr[9];
snprintf(timeStr, sizeof(timeStr), "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
// Get weather info every 10 minutes
static unsigned long lastWeatherUpdate = 0;
static String weather = "";
if(millis() - lastWeatherUpdate > 600000){ // 10 min
weather = getWeather();
lastWeatherUpdate = millis();
}
// Display on OLED
display.clearDisplay();
display.setCursor(0,0);
display.setTextSize(2);
display.println(timeStr);
display.setTextSize(1);
display.setCursor(0,40);
display.println(weather);
display.display();
delay(1000);
}