import machine
import time
from machine import Pin, I2C
# I2C configuration
i2c = I2C(0, scl=Pin(9), sda=Pin(8), freq=400000)
# LCD configuration
LCD_ADDR = 0x27 # Adjust this based on your LCD address
LCD_WIDTH = 16 # Adjust this based on your LCD columns
# Moisture sensor configuration
moisture_sensor_pin = 26 # Adjust this based on your sensor connection
adc = machine.ADC(Pin(moisture_sensor_pin))
def read_moisture():
# Read analog value from the soil moisture sensor
return adc.read()
def display_lcd(message):
# Send the message to the LCD
i2c.writeto(LCD_ADDR, bytearray([0x80])) # Set cursor to the beginning of the first line
i2c.writeto(LCD_ADDR, message.encode())
def main():
try:
while True:
moisture_value = read_moisture()
moisture_percentage = (moisture_value - 100) / 900 * 100
moisture_percentage = max(0, min(100, moisture_percentage))
display_message = "Moisture: {:.2f}%".format(moisture_percentage)
print(display_message)
# Display on LCD
display_lcd(display_message)
# Add a delay to avoid constant readings
time.sleep(2)
except KeyboardInterrupt:
print("Program terminated by user.")
if __name__ == "__main__":
main()