"""
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, I2C
import ssd1306
# MQTT服务器参数
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
# 初始化DHT22传感器
sensor = dht.DHT22(Pin(15))
# ESP32 I2C配置
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
# 蜂鸣器和LED引脚配置
buzzer_pin = Pin(27,Pin.OUT)#蜂鸣器连接到GPIO27
led_pin =Pin(0,Pin.OUT)#LED连接到GPIO0
led_pin.off() #初始时关闭led
#设定温度报警阈值
A=TEMP_THRESHOLD_HIGH=30.0 #最高温度阈值
B=TEMP_THRESHOLD_LOW=15.0 #最低为温度阈值
C=HUMIDITY_THRESHOLD_HIGH=80.0 #最高湿度阈值
D=HUMIDITY_THRESHOLD_LOW=30.0 #最低湿度阈值
# OLED显示屏配置
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# 连接WiFi
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!")
# 连接MQTT服务器
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:
print("Measuring weather conditions... ", end="")
sensor.measure() #调用sensor.measure()方法来获取最新的温度和湿度值。
temp = sensor.temperature()
humidity = sensor.humidity() #测量温度和湿度
if(temp >=A or temp<=B) or (humidity >= C or humidity <=D): # 条件判断
buzzer_pin.on() #蜂鸣报警
time.sleep(1)
led_pin.on()
time.sleep(2) # 蜂鸣器和LED保持2秒
buzzer_pin.off()#关闭蜂鸣器
#构建和发送MQTT消息,将当前的温度和湿度值打包成一个JSON字符串,
#并使用ujson.dumps()方法将其转换为JSON格式。
#然后,它检查这个新的消息是否与上一次发送的消息不同。
#如果不同,它将发送新的MQTT消息,并更新prev_weather变量。
message = ujson.dumps({
"temp": temp,
"humidity": humidity,
})
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
try:
client.publish(MQTT_TOPIC, message)
except Exception as e:
print("MQTT publish failed:",e) #if...发送MQTT消息的代码
prev_weather = message
#OLED显示
oled.fill(0) # 清除屏幕
oled.text('temp:{:.1f}'.format(temp),10,10)
oled.text('humidity:{:.1f}'.format(humidity),0,0)
oled.show() #如果消息有更新,程序会在OLED屏幕上显示当前的温度和湿度
else:
print("No change")
time.sleep(1) # 等待一段时间再次测量