import machine
import ssd1306
import time
import dht
# 设置 GPIO21 和 GPIO22 为 I2C 引脚
i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21))
# 初始化 OLED 显示屏
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# 初始化 DHT22 传感器(假设连接到 GPIO4)
sensor = dht.DHT22(machine.Pin(4))
# 初始化 LED(连接到 GPIO14)
led_pin = machine.Pin(14, machine.Pin.OUT)
# 初始化蜂鸣器(假设通过限流电阻连接到 GPIO25,使用 PWM)
buzzer_pin = machine.Pin(25)
buzzer = machine.PWM(buzzer_pin)
counter = 0
threshold = 24 # 初始阈值
# 假设两个按钮分别连接到 GPIO18 和 GPIO19,一个用于增加阈值,一个用于减少阈值
increase_button = machine.Pin(18, machine.Pin.IN, machine.Pin.PULL_UP)
decrease_button = machine.Pin(19, machine.Pin.IN, machine.Pin.PULL_UP)
# 假设复位休眠按钮连接到 GPIO20
reset_button = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP)
while True:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
oled.fill(0)
oled.text("Counter: {}".format(counter), 0, 0)
oled.text("Temp: {}C".format(temperature), 0, 20)
oled.text("Humidity: {}%".format(humidity), 0, 40)
oled.text("Threshold: {}".format(threshold), 0, 50)
oled.show()
time.sleep(1)
counter += 1
if temperature > threshold:
for _ in range(2):
buzzer.duty(512) # 设置 PWM 占空比,可根据实际情况调整
time.sleep(0.5)
buzzer.duty(0)
time.sleep(0.5)
led_pin.value(1)
else:
buzzer.duty(0)
led_pin.value(0)
if not increase_button.value():
threshold += 1
oled.fill(0)
oled.text("Counter: {}".format(counter), 0, 0)
oled.text("Temp: {}C".format(temperature), 0, 20)
oled.text("Humidity: {}%".format(humidity), 0, 40)
oled.text("Threshold: {}".format(threshold), 0, 50)
oled.show()
time.sleep(0.5)
if not decrease_button.value():
if threshold > 0:
threshold -= 1
oled.fill(0)
oled.text("Counter: {}".format(counter), 0, 0)
oled.text("Temp: {}C".format(temperature), 0, 20)
oled.text("Humidity: {}%".format(humidity), 0, 40)
oled.text("Threshold: {}".format(threshold), 0, 50)
oled.show()
time.sleep(0.5)
if not reset_button.value():
machine.deepsleep()