from machine import Pin, I2C
import time
import dht
import ssd1306
import network
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather1"
# Khởi tạo cảm biến DHT
dht_sensor = dht.DHT22(Pin(15))
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Khởi tạo OLED
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Khởi tạo LED
led_green = Pin(2, Pin.OUT)
led_red = Pin(0, Pin.OUT)
led_yellow = Pin(4, Pin.OUT)
# Ngưỡng
temp_threshold_low = 10
temp_threshold_high = 50
humidity_threshold_low = 40
humidity_threshold_high = 100
# Chạy vòng lặp chính
prev_weather = ""
while True:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Hiển thị lên OLED
oled.fill(0)
oled.text('Temp: {} C'.format(temperature), 0, 0)
oled.text('Humidity: {}%'.format(humidity), 0, 10)
oled.show()
# Điều khiển LED
if temperature < temp_threshold_low:
led_red.on() # Nhiệt độ dưới ngưỡng
led_green.off()
led_yellow.off()
elif temperature > temp_threshold_low and temperature < temp_threshold_high:
led_red.off()
led_green.on()
led_yellow.off
else:
# Nhiệt độ trên ngưỡng
led_green.off()
# Nháy LED đỏ
for _ in range(5):
led_red.on()
time.sleep(0.5)
led_red.off()
time.sleep(0.5)
if humidity < humidity_threshold_low:
led_yellow.on() # Độ ẩm dưới ngưỡng
led_green.off()
led_red.off()
elif humidity > humidity_threshold_low and humidity < humidity_threshold_high:
led_red.off()
led_green.on()
led_yellow.off
else:
# Độ ẩm trên ngưỡng
led_yellow.off()
# Nháy LED vàng
for _ in range(5):
led_yellow.on()
time.sleep(0.5)
led_yellow.off()
time.sleep(0.5)
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
})
if message != prev_weather:
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
time.sleep(2) # Đợi 2 giây trước khi đọc lại