【问题标题】:Store the float value in array, and analyzing last 20 values to check in C++将浮点值存储在数组中,并分析最后 20 个值以在 C++ 中检查
【发布时间】:2021-06-21 10:24:55
【问题描述】:

我正在使用带有 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); 
}

【问题讨论】:

    标签: arrays loops c++11 arduino


    【解决方案1】:

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

    //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
    }
    
    

    【讨论】:

    • 我有一个错误'size_t' in namespace 'std' does not name a type。你能检查一下这些行会在哪里吗static constexpr std::size_t max_histogram_count = 20; static std::array&lt;float, max_histogram_count&gt; histogram{};
    • @Dilux 这只是一个示例用法;我已经添加了标题以使其完整。
    • @Dilux 如果此答案满足您的问题,请将其标记为已接受。
    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 2020-03-15
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多