Arduino - 毫秒而不是延迟不工作

问题描述

我绝对是 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();
    }

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

谢谢!

解决方法

问题在于您两次读取相同的值。首先,您阅读它并将其分配给 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() 检查间隔,因为您已经每隔“间隔”毫秒调用一次。