#include <EEPROM.h>
#include <LiquidCrystal.h>
#include <DHT.h>
// Initialize the LCD with the appropriate pins
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
// Define the DHT22 sensor pin and type
#define DHTPIN 13
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
long duration, inches;
int set_val, percentage;
bool state, pump;
void setup() {
// Initialize the LCD with 16 columns and 2 rows
lcd.begin(16, 2);
lcd.print("WATER LEVEL:");
lcd.setCursor(0, 1);
lcd.print("PUMP:OFF MANUAL");
// Configure pin modes
pinMode(8, OUTPUT); // Ultrasonic trigger pin
pinMode(9, INPUT); // Ultrasonic echo pin
pinMode(10, INPUT_PULLUP);// Set button pin
pinMode(11, INPUT_PULLUP);// Mode switch pin
pinMode(12, OUTPUT); // Pump control pin
// Initialize the DHT sensor
dht.begin();
// Read the set value from EEPROM, max it to 150 if it exceeds
set_val = EEPROM.read(0);
if (set_val > 150) set_val = 150;
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(8, LOW);
delayMicroseconds(2);
digitalWrite(8, HIGH);
delayMicroseconds(10);
digitalWrite(8, LOW);
duration = pulseIn(9, HIGH);
// Convert the duration to inches
inches = microsecondsToInches(duration);
// Calculate the percentage of water level
percentage = (set_val - inches) * 100 / set_val;
if (percentage < 0) percentage = 0;
// Update the LCD with the water level percentage
lcd.setCursor(12, 0);
lcd.print(percentage);
lcd.print("% ");
// Control the pump based on water level and mode
if (percentage < 30 && digitalRead(11)) pump = 1;
if (percentage > 99) pump = 0;
digitalWrite(12, !pump);
// Update the LCD with the pump status
lcd.setCursor(5, 1);
if (pump == 1) lcd.print("ON ");
else lcd.print("OFF");
// Update the LCD with the mode status
lcd.setCursor(9, 1);
if (!digitalRead(11)) lcd.print("MANUAL");
else lcd.print("AUTO ");
// Set the water level value when button is pressed in auto mode
if (!digitalRead(10) && !state && digitalRead(11)) {
state = 1;
set_val = inches;
EEPROM.write(0, set_val);
}
// Toggle the pump when button is pressed in manual mode
if (!digitalRead(10) && !state && !digitalRead(11)) {
state = 1;
pump = !pump;
}
// Reset the state when the button is released
if (digitalRead(10)) state = 0;
// Read temperature and humidity from DHT22
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
lcd.setCursor(0, 0);
lcd.print("DHT22 ERROR ");
return;
}
// Display temperature and humidity on the LCD
lcd.setCursor(0, 0);
lcd.print("Temp:");
lcd.print(t);
lcd.print("C");
lcd.setCursor(0, 1);
lcd.print("Hum:");
lcd.print(h);
lcd.print("%");
delay(500); // Wait for 500 milliseconds before next loop iteration
}
// Convert microseconds to inches
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}