"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
from machine import Pin, SoftI2C
import ssd1306
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
led_green = Pin(2, Pin.OUT)
led_red = Pin(4, Pin.OUT)
led_yellow = Pin(5, Pin.OUT)
sensor = dht.DHT22(Pin(15))
temp_nguong = 30
humidity_nguong = 60
def blink(led, times, delay):
for _ in range(times):
led.on()
time.sleep(delay)
led.off()
time.sleep(delay)
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!")
prev_weather = ""
while True:
# Do nhiet do, do am
print("Measuring weather conditions... ", end="")
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
message = ujson.dumps({
"temp": temp,
"humidity": humidity,
})
# Gui du lieu len MQTT
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print("No change")
# Hien thi nhiet do, do am ra Oled
oled.fill(0)
oled.text("Temp: {:.1f} C".format(temp), 0, 0)
oled.text("Humidity: {:.1f}%".format(humidity), 0, 10)
oled.show()
# Dieu khien 3 Led
if temp < temp_nguong:
led_red.on() # Nhiệt độ dưới ngưỡng, LED đỏ sáng
led_green.off()
elif temp >= temp_nguong:
blink(led_red, 3, 0.5) # Nhiệt độ vượt ngưỡng, LED đỏ nháy
led_green.off()
else:
led_red.off()
if humidity < humidity_nguong:
led_yellow.on() # Độ ẩm dưới ngưỡng, LED vàng sáng
led_green.off()
elif humidity >= humidity_nguong:
blink(led_yellow, 3, 0.5) # Độ ẩm vượt ngưỡng, LED vàng nháy
led_green.off()
else:
led_yellow.off()
# Nếu cả nhiệt độ và độ ẩm đều trong ngưỡng bình thường, LED xanh bật
if temp < temp_nguong and humidity < humidity_nguong:
led_green.on()
led_red.off()
led_yellow.off()
time.sleep(1) # Delay before the next measurement