from machine import Pin, I2C
import ssd1306
import dht
import time
# Khởi tạo I2C cho OLED
# GP4 là SDA, GP5 là SCL
i2c = I2C(0, scl=Pin(5), sda=Pin(4), freq=400000)
# OLED 128x64 địa chỉ I2C mặc định của Wokwi thường là 0x3C
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Cảm biến DHT22 nối vào GP16
sensor = dht.DHT22(Pin(16))
while True:
try:
# Đọc dữ liệu từ cảm biến
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
# Xóa màn hình để vẽ nội dung mới
oled.fill(0)
# Hiển thị tiêu đề và giá trị đo được
oled.text("Temp & Humidity", 0, 0)
oled.text("Nhiet do:", 0, 18)
oled.text("{:.1f} C".format(temp), 0, 28)
oled.text("Do am:", 0, 44)
oled.text("{:.1f} %".format(hum), 0, 54)
oled.show()
except Exception:
# Nếu đọc cảm biến lỗi thì hiện thông báo
oled.fill(0)
oled.text("Doc cam bien loi", 0, 24)
oled.show()
time.sleep(2)