from machine import I2C, Pin
from utime import ticks_ms, ticks_diff, sleep_ms
from pico_i2c_lcd import I2cLcd
from dht import DHT22
# =========================
# CONFIGURAÇÃO
# =========================
i2c = I2C(0, scl=Pin(9), sda=Pin(8), freq=400000)
sensor = DHT22(Pin(16))
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# =========================
# MENSAGEM INICIAL
# =========================
lcd.move_to(0, 0)
lcd.putstr("Inicializando")
lcd.move_to(0, 1)
lcd.putstr("Sensor DHT22")
from utime import sleep
sleep(2)
# Layout fixo (não apaga mais)
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Temp: C")
lcd.move_to(0, 1)
lcd.putstr("Umid: %")
# =========================
# CONTROLE
# =========================
ultima_temp = None
ultima_umid = None
tempo = ticks_ms()
# =========================
# LOOP PRINCIPAL
# =========================
while True:
agora = ticks_ms()
# Atualiza a cada 2 segundos (DHT22 precisa disso)
if ticks_diff(agora, tempo) > 2000:
try:
sensor.measure()
temperatura = round(sensor.temperature(), 1)
umidade = round(sensor.humidity(), 1)
# Atualiza TEMPERATURA se mudou
if temperatura != ultima_temp:
lcd.move_to(6, 0)
lcd.putstr(" ") # limpa área
lcd.move_to(6, 0)
lcd.putstr(f"{temperatura}C")
ultima_temp = temperatura
# Atualiza UMIDADE se mudou
if umidade != ultima_umid:
lcd.move_to(6, 1)
lcd.putstr(" ")
lcd.move_to(6, 1)
lcd.putstr(f"{umidade}%")
ultima_umid = umidade
except Exception:
lcd.move_to(0, 0)
lcd.putstr("ERRO SENSOR ")
lcd.move_to(0, 1)
lcd.putstr("Verifique DHT ")
tempo = agora
sleep_ms(1)