#include <DHT.h>
#include <LiquidCrystal_I2C.h>
#define SOIL_MOISTURE_PIN A0
#define RAIN_SENSOR_PIN A1
#define DHT_TYPE DHT22
#define DHT_PIN 7
#define BUZZER_PIN 8 // Connect the buzzer to digital pin 8
const int relayPin = 4;
const int buzzerThreshold = 70; // Adjust this threshold based on your needs
const float temperatureThreshold = 35.0;
const int soilMoistureThreshold = 50;
const int readInterval = 1000;
DHT dht(DHT_PIN, DHT_TYPE);
LiquidCrystal_I2C lcd(0x27, 20, 4);
void setup() {
Serial.begin(9600);
dht.begin();
lcd.init();
lcd.backlight();
pinMode(relayPin, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
static unsigned long lastReadTime = 0;
if (millis() - lastReadTime >= readInterval) {
float temperature, humidity;
float soilMoisture, rainSensor;
temperature = dht.readTemperature();
humidity = dht.readHumidity();
soilMoisture = analogRead(SOIL_MOISTURE_PIN);
rainSensor = analogRead(RAIN_SENSOR_PIN);
soilMoisture = map(soilMoisture, 0, 1023, 0, 100);
rainSensor = map(rainSensor, 0, 1023, 0, 100);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Temperature: ");
lcd.print(temperature);
lcd.print("C");
lcd.setCursor(0, 2);
lcd.print("Soil Moisture: ");
lcd.print(soilMoisture);
lcd.print("%");
lcd.setCursor(0, 3);
lcd.print("Rain Sensor: ");
lcd.print(rainSensor);
lcd.print("%");
if (temperature > temperatureThreshold || soilMoisture < soilMoistureThreshold) {
digitalWrite(relayPin, LOW); // Turn on the relay
if (soilMoisture < buzzerThreshold) {
beepBuzzer(); // Activate the buzzer
} else {
noTone(BUZZER_PIN); // Turn off the buzzer
}
} else {
digitalWrite(relayPin, HIGH); // Turn off the relay
noTone(BUZZER_PIN); // Turn off the buzzer
}
lastReadTime = millis(); // Update last read time
}
}
void beepBuzzer() {
// Function to make the buzzer beep continuously
tone(BUZZER_PIN, 1000); // You can adjust the frequency (1000 Hz in this case)
delay(500); // Adjust the delay between beeps (500 milliseconds in this case)
noTone(BUZZER_PIN);
delay(500);
}