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

Arduino温度监控系统如何禁用开机sendMailNormalValue告警

温度监控系统代码修改方案

修改思路

  • 新增全局布尔变量hasTriggeredLowAlarm,初始值为false,用于记录系统运行后是否触发过低于6℃的告警,只有该标记为true时,温度回升才触发恢复通知
  • 发送低温告警时将hasTriggeredLowAlarm设为true,标记已进入过告警状态
  • 温度回升至6℃以上时,仅当hasTriggeredLowAlarm为true时才发送恢复通知,发送完成后重置标记为false,避免重复发送
  • 修复原代码中低温告警分支错误更新正常温度计时器的问题,补充温度等于6℃的边界判断,避免临界值频繁跳变触发通知

修改后完整代码

#include <OneWire.h>
#include <DallasTemperature.h>

// GPIO where the DS18B20 is connected to
const int oneWireBus = 5;     

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);
//========================================
float t;
int period = 30000;
unsigned long time_now = 0;
bool DisplayFirstTime = true;
// 新增状态标记:是否已经触发过低温告警
bool hasTriggeredLowAlarm = false;

int period1 = 30000;
unsigned long time_now1 = 0;

void sendMailBelowValue(){
  
}
  
void sendMailNormalValue(){
  
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  sensors.begin(); // 补充传感器初始化,原代码遗漏
}

void loop() {
  // put your main code here, to run repeatedly:
  sensors.requestTemperatures(); 
  t = sensors.getTempCByIndex(0);
  float p=t-2;
  // Check if any reads failed and exit early (to try again).
  if (isnan(t)) {
    Serial.println("Failed to read from sensor !");
    delay(500);
    return;
  }

  if (t > 6) {
    // 只有曾经触发过低告警才发恢复通知
    if(hasTriggeredLowAlarm && millis() > time_now + period){
      time_now = millis();
      sendMailNormalValue();
      hasTriggeredLowAlarm = false; // 发送后重置标记
      Serial.print ("You got message");
    }
  } else { // 温度小于等于6℃触发告警
    if(millis() > time_now1 + period1 || DisplayFirstTime){
      DisplayFirstTime = false;
      time_now1 = millis(); // 修复原代码错误更新time_now的问题
      sendMailBelowValue();
      hasTriggeredLowAlarm = true; // 标记已触发过低告警
    }
  }
}

补充说明

原代码还遗漏了sensors.begin()初始化传感器的调用,已经补充到setup函数中,避免传感器读取失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:18:03