#include <DHT.h>
#include <Servo.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define SERVO_PIN 9 // Digital pin connected to the servo
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
DHT dht(DHTPIN, DHTTYPE);
Servo servo;
void setup() {
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
// Clear the buffer
display.clearDisplay();
// Set text size, color, and display text
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
Serial.begin(9600);
dht.begin();
servo.attach(SERVO_PIN);
}
void loop() {
// Read temperature in Celsius
float temperatureC = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if any reads failed
if (isnan(temperatureC)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.print(" °C\t");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// Check temperature conditions and control servo
if (temperatureC >= 16) {
// Turn on servo
servo.write(90);
Serial.println("Servo turned on");
} else if (temperatureC <= 21) {
// Turn off servo
servo.write(0);
Serial.println("Servo turned off");
}
delay(500);
}