#include <DHT.h>
#define DHTPIN 2 // Pin connected to the DHT22
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define PUMPPIN 7 // Pin for Relay (controls the water pump)
#define BUZZERPIN 9 // Pin for Buzzer (alert)
DHT dht(DHTPIN, DHTTYPE);
int humidityThreshold = 40; // Humidity threshold below which pump and alert will activate
void setup() {
Serial.begin(9600);
// Initialize DHT sensor
dht.begin();
// Initialize Relay and Buzzer pins
pinMode(PUMPPIN, OUTPUT);
pinMode(BUZZERPIN, OUTPUT);
// Ensure pump and buzzer are off initially
digitalWrite(PUMPPIN, LOW);
digitalWrite(BUZZERPIN, LOW);
Serial.println("Smart Irrigation System Initialized.");
}
void loop() {
// Read humidity
float humidity = dht.readHumidity();
// Check if reading is valid
if (isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print humidity to serial monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// Check if humidity is below threshold (indicating dry soil)
if (humidity < humidityThreshold) {
Serial.println("Soil is too dry. Activating pump and buzzer...");
// Turn on the pump (via relay) and buzzer
digitalWrite(PUMPPIN, HIGH);
digitalWrite(BUZZERPIN, HIGH);
} else {
Serial.println("Soil moisture is sufficient. Pump and alert are off.");
// Turn off the pump and buzzer
digitalWrite(PUMPPIN, LOW);
digitalWrite(BUZZERPIN, LOW);
}
// Wait before checking again
delay(2000);
}