from machine import Pin, I2C
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
from time import sleep
import dht
# LCD configuration
I2C_ADDR = 0x27
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
lcd.backlight_on()
# LED pins for temperature ranges
green_led = Pin(2, Pin.OUT) # Green LED (temp <= 25)
yellow_led = Pin(3, Pin.OUT) # Yellow LED (25 < temp < 40)
red_led = Pin(4, Pin.OUT) # Red LED (temp >= 40)
# DHT22 sensor on pin 5
sensor = dht.DHT22(Pin(5))
def led_control(temperature):
""" Control LEDs based on temperature """
green_led.off()
yellow_led.off()
red_led.off()
if temperature <= 25:
green_led.on() # Turn on green LED
elif 25 < temperature < 40:
yellow_led.on() # Turn on yellow LED
else:
red_led.on() # Turn on red LED
while True:
try:
sleep(2) # Give time between sensor readings
sensor.measure() # Measure temperature and humidity
temp = sensor.temperature()
humidity = sensor.humidity()
# Control the LEDs based on the temperature
led_control(temp)
# Display on LCD
lcd.clear()
lcd.putstr(f"Temp: {temp:.1f}C")
lcd.move_to(0, 1)
lcd.putstr(f"Humidity: {humidity:.1f}%")
except OSError as e:
lcd.clear()
lcd.putstr('Sensor Error')
print("Error reading from DHT sensor:", e)