微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将浮点值存储在数组中,并分析最后 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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。