#include <DHT.h>
#include <LiquidCrystal_I2C.h>
// Define pins for DHT22 sensor and Soil Sensor
#define DHT22_PIN 13 // GPIO13 connected to DHT22 sensor
#define SOIL_SENSOR_PIN 34 // GPIO34 connected to Soil Moisture sensor (analog)
// Initialize the LCD (I2C address 0x27 and 16 columns, 2 rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
DHT dht22(DHT22_PIN, DHT22);
void setup() {
// Initialize serial communication for debugging
Serial.begin(115200);
Serial.println("DHT22 and LCD initialization...");
// Initialize I2C on GPIO 16 (SDA) and GPIO 17 (SCL)
Wire.begin(16, 17);
dht22.begin(); // Initialize the DHT sensor
lcd.init(); // Initialize the LCD I2C display
lcd.backlight(); // Turn on the LCD backlight
}
void loop() {
// Read humidity and temperature from DHT22 sensor
float humidity = dht22.readHumidity();
float temperature_C = dht22.readTemperature(); // Temperature in Celsius
// Read soil moisture sensor value
int soilMoistureValue = analogRead(SOIL_SENSOR_PIN);
String soilStatus = soilMoistureValue < 2165 ? "WET" : soilMoistureValue > 3135 ? "DRY" : "OK";
// Debugging output for temperature, humidity, and soil status
Serial.print("Temperature: ");
Serial.print(temperature_C);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("Soil Moisture: ");
Serial.print(soilMoistureValue);
Serial.print(" (");
Serial.print(soilStatus);
Serial.println(")");
lcd.clear();
// Check whether the DHT22 readings are successful
if (isnan(temperature_C) || isnan(humidity)) {
lcd.setCursor(0, 0);
lcd.print("Sensor Error");
Serial.println("Failed to read from DHT22 sensor.");
} else {
// Display temperature and humidity on LCD (fit on Line 1)
lcd.setCursor(0, 0);
lcd.print("Tmp:");
lcd.print(temperature_C, 1); // Print temperature with 1 decimal place
lcd.print("C Hu:");
lcd.print(humidity, 0); // Print humidity as an integer
lcd.print("%");
// Display soil status on LCD (Line 2)
lcd.setCursor(0, 1);
lcd.print("Soil: ");
lcd.print(soilStatus);
}
// Wait 2 seconds between readings
delay(2000);
}