SensESP 2.7.2
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
moving_average.cpp
Go to the documentation of this file.
1#include "moving_average.h"
2
3namespace sensesp {
4
5// MovingAverage
6
10 sample_size_{sample_size},
11 multiplier_{multiplier} {
12 buf_.resize(sample_size_, 0);
13 initialized_ = false;
15}
16
18 // So the first value to be included in the average doesn't default to 0.0
19 if (!initialized_) {
20 buf_.assign(sample_size_, input);
21 output = input;
22 initialized_ = true;
23 } else {
24 // Subtract 1/nth of the oldest value and add 1/nth of the newest value
25 output += -multiplier_ * buf_[ptr_] / sample_size_;
26 output += multiplier_ * input / sample_size_;
27
28 // Save the most recent input, then advance to the next storage location.
29 // When storage location n is reached, start over again at 0.
30 buf_[ptr_] = input;
31 ptr_ = (ptr_ + 1) % sample_size_;
32 }
33 notify();
34}
35
37 root["multiplier"] = multiplier_;
38 root["sample_size"] = sample_size_;
39}
40
41static const char SCHEMA[] PROGMEM = R"({
42 "type": "object",
43 "properties": {
44 "sample_size": { "title": "Number of samples in average", "type": "integer" },
45 "multiplier": { "title": "Multiplier", "type": "number" }
46 }
47 })";
48
50
52 String expected[] = {"multiplier", "sample_size"};
53 for (auto str : expected) {
54 if (!config.containsKey(str)) {
55 return false;
56 }
57 }
58 multiplier_ = config["multiplier"];
59 int n_new = config["sample_size"];
60 // need to reset the ring buffer if size changes
61 if (sample_size_ != n_new) {
62 buf_.assign(sample_size_, 0);
63 ptr_ = 0;
64 initialized_ = false;
65 sample_size_ = n_new;
66 }
67 return true;
68}
69
70} // namespace sensesp
virtual void load_configuration()
Construct a new transform based on a single function.
virtual void set_input(float input, uint8_t inputChannel=0) override
virtual void get_configuration(JsonObject &doc) override
virtual String get_config_schema() override
virtual bool set_configuration(const JsonObject &config) override
MovingAverage(int sample_size, float multiplier=1.0, String config_path="")
const uint8_t PAGE_css_bootstrap[] PROGMEM