将浮点值存储在数组中,并分析最后 20 个值以在 C++ 中检查

问题描述

我正在使用带 Arduino 的 DS18B20 温度传感器。我需要将最后 20 个读取值存储在数组中,并通知或中断以打开 LED 特定阈值。如何处理上述场景?您可以使用我的初始代码添加其余代码

#include <OneWire.h> 
#include <Dallastemperature.h>
 
#define ONE_WIRE_BUS 10 
 
OneWire oneWire(ONE_WIRE_BUS); 
 
Dallastemperature sensors(&oneWire);
/********************************************************************/ 
void setup(void) 
{ 
 // start serial port 
 Serial.begin(9600); 
 sensors.begin(); 
} 
void loop(void) 
{ 
  readTempSensor();
       delay(100); 
} 

float readTempSensor(){
 float Temp = 0;
 float TmpArray[20]; 
 
 sensors.requestTemperatures();
 Temp = sensors.getTempCByIndex(0);
 
 Serial.print("T: "); 
 Serial.println(Temp); 
}

解决方法

您可以使用 std::array<float,20> 并跟踪索引,并在必要时对其进行修改:

//cstddef shouldn't be required due to the inclusion of <array>,//but if it still throws an error,uncomment the following line
//#include <cstddef>
#include <array>

static constexpr std::size_t max_histogram_count = 20;
static std::array<float,max_histogram_count> histogram{};

void readTempSensor() {
    static std::size_t histogramIndex = 0;

    sensors.requestTemperatures();
    const auto curTemp = sensors.getTempCByIndex(0);
    histogram[histogramIndex++] = curTemp;

    for(const auto& h : histogram) {
        Serial.print("T: ");
        Serial.println(h);
    }

    histogramIndex %= max_histogram_count;
}

void analyzeTemperature() {
    //...Do things with histogram array
}