#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h> // Include the library for the DHT sensor
// Define constants for the DHT sensor
#define DHTPIN 15 // DHT22 sensor is connected to GPIO 15
#define DHTTYPE DHT22 // DHT22 type
#define RELAY_PIN 12 // Relay control pin (change to your desired GPIO pin)
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
LiquidCrystal_I2C lcd(0x27, 12, 3);
const int ledPin = 13; // LED pin
void setup() {
Wire.begin(23, 22); // Initialize the I2C communication with SDA pin 23 and SCL pin 22.
Serial.begin(9600); // Initialize the serial communication at a baud rate of 9600 bits per second.
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(RELAY_PIN, OUTPUT); // Set relay pin as output
dht.begin(); // Initialize the DHT sensor
}
void loop() {
float temp = dht.readTemperature(); // Read temperature from DHT22
float hum = dht.readHumidity(); // Read humidity from DHT22
int soilMoisture = analogRead(34); // Read soil moisture value from pin 34
// Use the ternary operator to determine the moisture status based on the value of 'soilMoisture'.
String msg = soilMoisture < 300 ? "DRY" : soilMoisture > 600 ? "WET" : "OK";
lcd.clear();
lcd.print("Moist:");
lcd.print(soilMoisture, 1); // Print soil moisture with one decimal
lcd.print(": ");
lcd.print(msg);
// Control the relay based on soil moisture level
if (soilMoisture <= 300) {
digitalWrite(ledPin, HIGH); // Turn on the LED (motor) if the soil is dry (i < 300)
digitalWrite(RELAY_PIN, HIGH); // Activate the relay (turn on irrigation)
} else {
digitalWrite(ledPin, LOW); // Turn off the LED (motor)
digitalWrite(RELAY_PIN, LOW); // Deactivate the relay (turn off irrigation)
}
lcd.setCursor(0, 1); // Set cursor to the first column and second row
lcd.print("T:"); // Print "T:" (Temperature)
lcd.print(temp); // Print temperature with one decimal
lcd.print(" H:"); // Print " H:" (Humidity)
lcd.print(hum); // Print humidity with one decimal
delay(500); // Delay for half a second
}