You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Raspberry Pi Pico-W温湿度报警代码if-else逻辑异常求助

温湿度报警器滞回逻辑修复方案

问题分析

当前代码的逻辑缺陷在于:

  • 触发报警使用或条件(温度≥31℃ 或 湿度≥62%)
  • 关闭报警也使用或条件(温度<30℃ 或 湿度<60%)

这就导致,当温度触发报警后(比如31℃),只要湿度降到60%以下(哪怕温度还在30.8℃的滞回区间内),就会触发关闭逻辑,不符合你预期的“温度到31℃触发,30℃才关闭”的滞回要求。另外,湿度的滞回逻辑不完整:触发阈值是62%,但关闭阈值设为60%,没有留出合理的滞回区间,应该调整为58%(60%-2%)。

修复后的代码

新增变量跟踪报警激活状态,并修改关闭逻辑为与条件,确保只有当温湿度都回到各自的关闭阈值以下时,才关闭报警:

from machine import Pin, I2C
import utime as time
from dth import DHT11, InvalidChecksum, InvalidPulseCount

pin = Pin(16, Pin.OUT, Pin.PULL_DOWN)
sensor1 = DHT11(pin)

pwr = Pin(22, Pin.OUT, Pin.PULL_DOWN)
alarm1 = Pin(21, Pin.OUT, Pin.PULL_DOWN)
alarm2 = Pin(20, Pin.OUT, Pin.PULL_DOWN)

# 报警阈值
alarm1temp = 30
alarm1hum = 60

alarm2temp = 35
alarm2hum = 80

# 滞回值
temphys = 1
humhys = 2

# 报警状态跟踪
alarm1_active = False
alarm2_active = False

temp = 0
hum = 0
retrys = 5
pwr.on()

while True:
    time.sleep(2)
    retrycounter = 0
    while retrycounter <= retrys:
        try:
            new_temp = sensor1.temperature
            new_hum = sensor1.humidity
            temp = new_temp
            hum = new_hum
            break
        except:
            print("Error reading data. Try: " + str(retrycounter))
            time.sleep(1)
            if retrycounter > retrys - 1:
                temp = alarm2temp + 1
            retrycounter += 1
            
    print("Temperature: {}".format(temp))
    print("Humidity: {}".format(hum))
    
    # Alarm 1 逻辑
    if not alarm1_active:
        # 未激活时,满足任一触发阈值则打开
        if temp >= (alarm1temp + temphys) or hum >= (alarm1hum + humhys):
            alarm1.on()
            alarm1_active = True
            print("Alarm 1 On")
    else:
        # 已激活时,必须温湿度都低于关闭阈值才关闭
        if temp < alarm1temp and hum < (alarm1hum - humhys):
            alarm1.off()
            alarm1_active = False
            print("Alarm 1 Off")
    
    # Alarm 2 逻辑
    if not alarm2_active:
        if temp >= (alarm2temp + temphys) or hum >= (alarm2hum + humhys):
            alarm2.on()
            alarm2_active = True
            print("Alarm 2 On")
    else:
        if temp < alarm2temp and hum < (alarm2hum - humhys):
            alarm2.off()
            alarm2_active = False
            print("Alarm 2 Off")

逻辑说明

  1. 状态跟踪:新增alarm1_active和alarm2_active变量,记录报警当前是否处于激活状态。
  2. 触发逻辑:报警未激活时,只要温度达到30+1=31℃或湿度达到60+2=62%,立即激活报警。
  3. 关闭逻辑:报警已激活时,只有当温度低于30℃并且湿度低于60-2=58%时,才关闭报警。这样保证了温度触发报警后,必须降到30℃以下才会关闭,不会因为湿度波动误关报警。
  4. 湿度滞回修正:湿度的关闭阈值调整为alarm1hum - humhys,和触发阈值的alarm1hum + humhys对应,形成完整的滞回区间(58%-62%)。

内容的提问来源于stack exchange,提问作者BDMan32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 14:19:53