from machine import Pin, I2C
from umqtt.simple import MQTTClient
import dht
import ssd1306
import network
import time
def connect_wifi():
ssid = "Wokwi-GUEST"
password = ""
# ssid = 'Wokwi-GUEST'
# password = ''
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
print("Connecting to Wi-Fi...")
while not wlan.isconnected():
time.sleep(1)
print("Connected to Wi-Fi!", wlan.ifconfig())
# Cấu hình cảm biến DHT22
d = dht.DHT22(Pin(12,Pin.IN))
# Cấu hình OLED
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Kết nối MQTT broker
clientId = "clientId-5TaYvvBm0G"
server = "mqtt-dashboard.com"
client = MQTTClient(clientId, server)
def connect_mqtt():
try:
client.connect()
print("Ket noi thanh cong!")
except Exception as e:
print("Khong the ket noi!", e)
def loop():
while True:
try:
d.measure()
temperature = d.temperature()
humidity = d.humidity()
# Gửi dữ liệu lên broker
print("Gui du lieu len broker")
client.publish("py_iot/nhietdo", str(temperature))
client.publish("py_iot/doam", str(humidity))
# Hiển thị dữ liệu lên OLED
oled.fill(0)
oled.text("Temp: {:.1f}C".format(temperature), 10, 20)
oled.text("Humi: {}%".format(humidity), 10, 30)
oled.show()
time.sleep(5)
except Exception as e:
print("Gui du lieu that bai:", e)
if __name__ == "__main__":
connect_wifi()
connect_mqtt()
loop()