#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#define DHTPIN 2 // Pin connected to the DHT22 sensor
#define OLED_RESET 4 // Reset pin for the OLED display
#define Buzzer 3
Adafruit_SSD1306 display(OLED_RESET);
void setup() {
tone(Buzzer, 1000);
// Initialize the OLED display
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.display();
delay(2000);
display.clearDisplay();
noTone(Buzzer);
}
void loop() {
// Read temperature and humidity values from the DHT22 sensor
float temperature = readTemperature();
float humidity = readHumidity();
// Display temperature and humidity on the OLED display
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Temperature: ");
display.print(temperature);
display.println(" C");
display.print("Humidity: ");
display.print(humidity);
display.println(" %");
display.display();
delay(200); // Delay between readings
}
float readTemperature() {
// Request temperature data from the DHT22 sensor
pinMode(DHTPIN, OUTPUT);
digitalWrite(DHTPIN, LOW);
delay(20);
digitalWrite(DHTPIN, HIGH);
delayMicroseconds(40);
pinMode(DHTPIN, INPUT);
// Wait for the DHT22 sensor to respond
while (digitalRead(DHTPIN) == LOW)
;
while (digitalRead(DHTPIN) == HIGH)
;
// Read the temperature value from the DHT22 sensor
int data[5];
for (int i = 0; i < 5; i++) {
data[i] = readByte();
}
// Calculate the temperature
float temperature = ((data[2] & 0x7F) << 8 | data[3]) / 10.0;
if (data[2] >> 7)
temperature = -temperature;
return temperature;
}
float readHumidity() {
// Request humidity data from the DHT22 sensor
pinMode(DHTPIN, OUTPUT);
digitalWrite(DHTPIN, LOW);
delay(20);
digitalWrite(DHTPIN, HIGH);
delayMicroseconds(40);
pinMode(DHTPIN, INPUT);
// Wait for the DHT22 sensor to respond
while (digitalRead(DHTPIN) == LOW)
;
while (digitalRead(DHTPIN) == HIGH)
;
// Read the humidity value from the DHT22 sensor
int data[5];
for (int i = 0; i < 5; i++) {
data[i] = readByte();
}
// Calculate the humidity
float humidity = (data[0] << 8 | data[1]) / 10.0;
return humidity;
}
int readByte() {
int value = 0;
for (int i = 0; i < 8; i++) {
while (digitalRead(DHTPIN) == LOW)
;
delayMicroseconds(30);
if (digitalRead(DHTPIN) == HIGH)
value |= (1 << (7 - i));
while (digitalRead(DHTPIN) == HIGH)
;
}
return value;
}