from machine import ADC, Pin # Import ADC for reading analog sensor and Pin for GPIO control
import time # Import time for delays
from gpio_lcd import GpioLcd # Import library to control 16x2 LCD
# Initialize the LCD with appropriate GPIO pins connected to RS, Enable, D4–D7
lcd = GpioLcd(rs_pin=Pin(16),
enable_pin=Pin(17),
d4_pin=Pin(18),
d5_pin=Pin(19),
d6_pin=Pin(20),
d7_pin=Pin(21),
num_lines=2,
num_columns=16)
# Initialize soil moisture sensor using analog pin GP28 (ADC2)
sensor = ADC(28)
# Initialize pump (represented by an LED) connected to digital pin GP15
pump = Pin(15, Pin.OUT)
# Set a threshold value to decide when soil is considered "dry"
# You may need to adjust this value after checking actual sensor readings
threshold = 30000
# Infinite loop to continuously read sensor values and control the pump
while True:
# Read the analog value from the soil moisture sensor (0–65535)
value = sensor.read_u16()
print("Value:", value) # Print the sensor reading to the serial monitor
# Clear the LCD before updating to avoid leftover characters
lcd.clear()
# Display the raw moisture value on the first row of the LCD
lcd.move_to(0, 0)
lcd.putstr(f"Moisture: {value:5d}")
# Check if soil is dry based on threshold value
if value < threshold:
pump.value(1) # Turn ON pump (or LED)
print("Soil dry - Pump ON") # Print status in console
lcd.move_to(0, 1)
lcd.putstr("Status: Pump ON ") # Display pump status on second row
else:
pump.value(0) # Turn OFF pump (or LED)
print("Soil wet - Pump OFF") # Print status in console
lcd.move_to(0, 1)
lcd.putstr("Status: Pump OFF") # Display pump status on second row
# Wait for 2 seconds before the next reading
time.sleep(2)