#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Define constants for I2C LCD and DHT22 sensor
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (or AM2302) sensor
#define LCD_ADDR 0x27 // I2C address of the LCD (check your LCD's datasheet)
#define LCD_COLS 20 // Number of columns on the LCD
#define LCD_ROWS 4 // Number of rows on the LCD
// Define pin for soil moisture sensor and LED (adjust as needed)
const int SOIL_MOISTURE_PIN = 5;
const int PUMP_LED_PIN = 2; // Replace with the LED pin connected to the pump
// Variables for sensor readings
float temp, humidity;
int soilMoisture;
// LiquidCrystal_I2C object for LCD control
LiquidCrystal_I2C lcd(LCD_ADDR, LCD_COLS, LCD_ROWS);
// DHT object for temperature and humidity readings
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600); // Optional for serial communication debugging
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on LCD backlight
lcd.setCursor(0, 0); // Set cursor position (0, 0)
lcd.print("Initializing...");
dht.begin(); // Start DHT sensor
pinMode(SOIL_MOISTURE_PIN, INPUT); // Set soil moisture pin as input
pinMode(PUMP_LED_PIN, OUTPUT); // Set LED pin as output
}
void loop() {
// Read temperature and humidity from DHT sensor
temp = dht.readTemperature();
humidity = dht.readHumidity();
// Check if any reads failed and exit early (to avoid NaN)
if (isnan(temp) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Read soil moisture value
soilMoisture = analogRead(SOIL_MOISTURE_PIN);
// Calculate soil moisture percentage with adjusted range (1% to 100%)
int soilMoisturePercent = map(soilMoisture, 0, 1023, 1, 100);
// Control pump based on soil moisture threshold
bool pumpStatus = soilMoisturePercent < 80; // Turn pump on if below 80%
digitalWrite(PUMP_LED_PIN, pumpStatus); // LED on when pump is on (direct logic)
// Display readings on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temp);
lcd.print("°C");
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print("%");
lcd.setCursor(0, 2);
lcd.print("Soil Moisture: ");
lcd.print(soilMoisturePercent);
lcd.print("%");
lcd.setCursor(0, 3);
lcd.print("Pump: ");
lcd.print(pumpStatus ? "ON" : "OFF");
delay(2000); // Update readings every 2 seconds
}