0

我是 Arduino 的绝对初学者,但我目前正在从事物联网项目。目标是查看温度和湿度是否在几分钟内发生剧烈变化。

我正在使用 ESP 8266、DHT11 和 BLYNK 应用程序。

我有以下代码,在其中我延迟了两次温度读数之间的时间,以计算它们之间的差异。我知道 delay() 不是一个好的工作方式,所以我尝试用 millis() 计时器重写它。但它不工作!tempA 与 tempB 保持一致。

有人能告诉我,它应该是什么样子吗?

unsigned long previousMillis = 0;
    const long interval = 5000;

    void tempChange()
    {
      float tempA;
      float tempB;
      float tempDiff;
      unsigned long currentMillis = millis();

      tempA = dht.readTemperature();

      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        tempB = dht.readTemperature();
      }

      Serial.print(tempA);
      Serial.print("    ");
      Serial.println(tempB);
    }


    void setup()
    {
      dht.begin();
      timer.setInterval(5000L, tempChange);
      }


    void loop()
    {
      Blynk.run();
      timer.run();
    }

如果您知道任何更好的方法,记录随时间的变化,我愿意接受。这只是我想出的最好(或最坏)的想法。

谢谢!

4

1 回答 1

2

问题是您两次读取相同的值。首先,您阅读它并将其分配给tempA,然后您对tempB. tempA等于,tempB因为它是相同的读数!

您要做的是在全局变量中跟踪先前的温度,然后每次调用时tempChange(),读取传感器的值并获取差异。然后,将上次温度的值更改为下一次调用的实际温度。

//Create a global variable to keep track of the previous temperature
float previousTemp = dht.readTemperature();

//Call this every "interval" milliseconds
void tempChange()
{
   //Get current temperature and calculate temperature difference
   float currentTemp = dht.readTemperature();
   float tempDiff = currentTemp-previousTemp;

   //Keep track of previous temp
   previousTemp = currentTemp

   //Print results
   Serial.println(previousTemp + " " + currentTemp);
   Serial.println("Change: " + tempDiff);
}

此外,您不需要millis()在调用函数时检查间隔,因为您已经在每“间隔”毫秒调用它。

于 2021-02-27T20:13:29.303 回答