#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// --- Configuration ---
// I2C Address (0x27 is common, check if yours is 0x3F if it doesn't work)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Pin Definitions
const int SOIL_PIN = 34; // Soil Sensor Analog Output
const int LED_R = 25; // RGB LED Red Pin
const int LED_G = 33; // RGB LED Green Pin
const int LED_B = 32; // RGB LED Blue Pin
// Moisture thresholds based on your calibration values
// Raw values are typically 0 (wettest) to 4095 (driest) on ESP32
const int WET_THRESHOLD_MAX = 2165; // Raw value below this is considered WET
const int DRY_THRESHOLD_MIN = 3135; // Raw value above this is considered DRY
// --- Setup ---
void setup() {
// Initialize I2C communication (SDA=23, SCL=22 are standard ESP32 pins)
Wire.begin(23, 22);
Serial.begin(9600);
// Set LED pins as outputs
pinMode(LED_R, OUTPUT);
pinMode(LED_G, OUTPUT);
pinMode(LED_B, OUTPUT);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.print("Soil Monitor");
lcd.setCursor(0, 1);
lcd.print("Ready...");
delay(1000);
}
// --- Main Loop ---
void loop() {
// Read the raw analog value from the soil sensor
int16_t rawValue = analogRead(SOIL_PIN);
String msg;
// --- Logic for State Determination and LED Control ---
// DRY State (Raw Value >= 3135) - Set RED
if (rawValue >= DRY_THRESHOLD_MIN) {
msg = "DRY";
analogWrite(LED_R, 255); // Red ON
analogWrite(LED_G, 0);
analogWrite(LED_B, 0);
}
// WET State (Raw Value <= 2165) - Set BLUE
else if (rawValue <= WET_THRESHOLD_MAX) {
msg = "WET";
analogWrite(LED_R, 0);
analogWrite(LED_G, 0);
analogWrite(LED_B, 255); // Blue ON
}
// OK State (Ideal, between 2165 and 3135) - Set GREEN
else {
msg = "OK";
analogWrite(LED_R, 0);
analogWrite(LED_G, 255); // Green ON
analogWrite(LED_B, 0);
}
// --- Display Status on LCD ---
// Clear the display for fresh data
lcd.clear();
// Line 1: Show Raw ADC Value for easy calibration
lcd.print("Value: ");
lcd.print(rawValue);
// Line 2: Show Moisture Status (DRY, WET, or OK)
lcd.setCursor(0, 1);
lcd.print("Soil: ");
lcd.print(msg); // Prints "DRY", "WET", or "OK"
// Debugging output to Serial Monitor
Serial.print("Value: ");
Serial.print(rawValue);
Serial.print(" | Status: ");
Serial.println(msg);
delay(1000); // Wait for 1 second before the next reading
}