#include <DHT.h>
// Pin connections
#define DHTPIN 4
#define SERVO_PIN 18
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// Servo positions
int closePos = 1638; // Servo closed
int openPos = 4915; // Servo open
float limitTemp = 30.0; // Temperature limit
void setup() {
Serial.begin(115200);
dht.begin();
// Attach servo using ESP32 PWM
ledcAttach(SERVO_PIN, 50, 16);
// Servo start position
ledcWrite(SERVO_PIN, closePos);
Serial.println("Smart Agriculture Started");
}
void loop() {
// Read DHT sensor
float temp = dht.readTemperature();
float hum = dht.readHumidity();
// Display values
Serial.print("Temp: ");
Serial.print(temp);
Serial.println(" C");
Serial.print("Humidity: ");
Serial.print(hum);
Serial.println(" %");
// Servo control based on temperature
if (temp > limitTemp) {
ledcWrite(SERVO_PIN, openPos);
Serial.println("Servo OPEN");
} else {
ledcWrite(SERVO_PIN, closePos);
Serial.println("Servo CLOSED");
}
Serial.println("---------------");
delay(2000);
}