#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RTClib.h>
#include <DHT.h>
// OLED display configuration
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// RTC module configuration
RTC_DS3231 rtc;
// Temperature and humidity sensor configuration (DHT22)
#define DHTPIN 2 // Pin to which the data pin of DHT is connected
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize OLED display with I2C address 0x3C or 0x3D
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
// Clear the display immediately after initialization to avoid showing the splash screen
display.clearDisplay();
display.display();
// Initialize RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
// Initialize temperature and humidity sensor
dht.begin();
}
void loop() {
// Get the current date and time
DateTime now = rtc.now();
// Get the temperature and humidity
float temperatureC = dht.readTemperature();
float humidity = dht.readHumidity();
// Clear the display
display.clearDisplay();
// Centering the text
// Display day of the week
String dayText = dayOfTheWeek(now.dayOfTheWeek());
int16_t x1, y1;
uint16_t w, h;
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.getTextBounds(dayText, 0, 0, &x1, &y1, &w, &h);
display.setCursor((SCREEN_WIDTH - w) / 2, 0);
display.print(dayText);
// Display date in DD/MM/YYYY format
String dateText = String(now.day()) + "/" + String(now.month()) + "/" + String(now.year());
display.getTextBounds(dateText, 0, 0, &x1, &y1, &w, &h);
display.setCursor((SCREEN_WIDTH - w) / 2, 10);
display.print(dateText);
// Display time in HH:MM:SS format
String timeText = String(now.hour()) + ":" + String(now.minute()) + ":" + String(now.second());
display.setTextSize(2);
display.getTextBounds(timeText, 0, 0, &x1, &y1, &w, &h);
display.setCursor((SCREEN_WIDTH - w) / 2, 25);
display.print(timeText);
// Display temperature and humidity
String tempHumText = "Temp: " + String(int(temperatureC)) + " C Hum: " + String(int(humidity)) + " %";
display.setTextSize(1);
display.getTextBounds(tempHumText, 0, 0, &x1, &y1, &w, &h);
display.setCursor((SCREEN_WIDTH - w) / 2, 50);
display.print(tempHumText);
// Display everything on the screen
display.display();
delay(1000);
}
String dayOfTheWeek(uint8_t day) {
switch(day) {
case 0: return "Sunday";
case 1: return "Monday";
case 2: return "Tuesday";
case 3: return "Wednesday";
case 4: return "Thursday";
case 5: return "Friday";
case 6: return "Saturday";
default: return "";
}
}