from machine import Pin, SoftI2C, ADC, Timer
import dht
import time
from lcd_api import LcdApi
from i2c_lcd import I2cLcd



led = Pin(5, Pin.OUT)
sensor = dht.DHT22(Pin(14))
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)

soil_sensor_pin = ADC(Pin(34))

#def read_soil_humidity():
#    analog_value = soil_sensor_pin.read()
#    soil_humidity_value = map(analog_value, 0, 4095, 0, 100)
#    return soil_humidity_value



while True:
    sensor.measure()
    t = sensor.temperature()
    h = sensor.humidity()

    # Đọc giá trị độ ẩm đất
    #soil_humidity_value = read_soil_humidity()
    
    lcd.clear()
    lcd.putstr("Temp: " + str(t) + "C  Humidity: " + str(h) + "%")


    time.sleep(2)

    # Kiểm tra và hiển thị cảnh báo nếu có
    if t > 32:
        lcd.clear()
        lcd.putstr("ALERT! High Temperature")
        alert = True
    elif h > 60:
        lcd.clear()
        lcd.putstr("ALERT! High Humidity")
        alert = True
    elif t < 20: 
        lcd.clear()
        lcd.putstr("ALERT! Low Temperature")
        alert = True
    elif h < 40:
        lcd.clear()
        lcd.putstr("ALERT! Low Humidity")
        alert = True
    else:
        alert = False

    if alert:
        led.on()
    else:
        led.off()

    time.sleep(2)
soilsensorBreakout