from machine import Pin, I2C, Timer
import ssd1306
import network
import time
import dht
import ujson
from umqtt.simple import MQTTClient
# ESP32 Pin assignment 初始化ic2
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
#蜂鸣器初始化
buzzer_pin = Pin(2, Pin.OUT)
#屏幕的初始化与屏幕参数
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
sensor = dht.DHT22(Pin(15))
#用于屏幕上读取湿度与温度
def draw_screen(temp, humidity):
oled.fill(0)
oled.text("Temp: {:.1f}°C".format(temp), 0, 0)
oled.text("Humidity: {:.1f}%".format(humidity), 0, 10)
oled.show()
#用于蜂鸣器发出声音长度
def beep_alarm(duration=0.5):
buzzer_pin.on()
time.sleep(duration)
buzzer_pin.off()
#用于网络连接
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 = ""
threshold_temp = 30
threshold_humidity = 80
#用于持续测量天气温湿度
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
# 触发蜂鸣器
if temp > threshold_temp or humidity > threshold_humidity:
print("Alarm! Temperature or humidity exceeded threshold.")
beep_alarm(duration=1)
#将温湿度数据转化为字符串
message = ujson.dumps({
"temp": temp,
"humidity": humidity,
})
#如果数据变化,则会更新
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
draw_screen(temp, humidity)
#条件语句,用于检测温度等变量是否超过阈值
if temp > threshold_temp or humidity > threshold_humidity:
beep_alarm()
else:
print("No change")
time.sleep(1)