#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Pin configuration
#define DHT_PIN 4 // DHT22 sensor pin
#define DHT_TYPE DHT22
#define TRIG_PIN 18 // Ultrasonic sensor Trigger pin
#define ECHO_PIN 19 // Ultrasonic sensor Echo pin
#define RELAY_PIN 25 // Relay to control the pump
#define BUZZER_PIN 26 // Buzzer pin
// Sensor initialization
DHT dht(DHT_PIN, DHT_TYPE);
LiquidCrystal_I2C lcd(0x27, 20, 4);
// Variables
float temperature = 0.0;
float waterLevel = 0.0; // In liters
const float tankHeight = 20.0; // Tank height in cm (example)
bool pumpStatus = false;
bool buzzerStatus = false;
void setup() {
// Initialize components
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW); // Pump OFF
noTone(BUZZER_PIN); // Ensure buzzer is OFF
lcd.begin(20, 4); // 20 columns, 4 rows
lcd.backlight();
dht.begin();
lcd.setCursor(0, 0);
lcd.print("Irrigation System");
delay(2000);
lcd.clear();
}
void loop() {
// Read sensors
temperature = dht.readTemperature();
waterLevel = getWaterLevel();
// Display data on LCD
displayData();
// Control pump and buzzer
controlPumpAndBuzzer();
delay(1000); // Delay for readability
}
float getWaterLevel() {
// Measure distance using ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
float duration = pulseIn(ECHO_PIN, HIGH);
float distance = (duration * 0.034) / 2; // Distance in cm (round trip divided by 2)
// Convert distance to water height
float waterHeight = tankHeight - distance; // Water height in cm
// Ensure water height does not go negative
if (waterHeight < 0) waterHeight = 0;
// Convert water height to volume (liters)
float tankCapacity = 2.0; // 2L max capacity
return (waterHeight / tankHeight) * tankCapacity; // Approx. water volume
}
void displayData() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print("C");
lcd.setCursor(0, 1);
lcd.print("Water: ");
lcd.print(waterLevel, 1);
lcd.print(" L");
lcd.setCursor(0, 2);
lcd.print("Pump: ");
lcd.print(pumpStatus ? "ON " : "OFF");
lcd.setCursor(0, 3);
lcd.print(buzzerStatus ? "Refill Tank!" : "Tank OK ");
}
void controlPumpAndBuzzer() {
// Buzzer logic
if (waterLevel <= 0.3) {
buzzerStatus = true;
tone(BUZZER_PIN, 1500); // Sound buzzer at 1500 Hz
pumpStatus = false;
digitalWrite(RELAY_PIN, LOW); // Ensure pump is OFF
} else if (waterLevel >= 1.0) {
buzzerStatus = false;
noTone(BUZZER_PIN); // Turn off buzzer
}
// Pump logic
if (!buzzerStatus) {
if (temperature >= 40.0) { // Turn pump ON at 40°C or above
pumpStatus = true;
digitalWrite(RELAY_PIN, HIGH);
} else if (temperature <= 35.0) { // Turn pump OFF at 35°C or below
pumpStatus = false;
digitalWrite(RELAY_PIN, LOW);
}
}
}