diff --git a/README.md b/README.md index c01e7ea..e317dfb 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,10 @@ Implemented are the following [trigger functions](https://en.wikipedia.org/wiki/ * [Rising edge trigger](https://en.wikipedia.org/wiki/Signal_edge) * [Falling edge trigger](https://en.wikipedia.org/wiki/Signal_edge) +### [sma.hh](sma.hh) + +The [simple moving average](https://en.wikipedia.org/wiki/Moving_average#Simple_moving_average) gives us the mean of the last N data points. + ### [const.hh](const.hh) Some constants we need diff --git a/sma.hh b/sma.hh new file mode 100644 index 0000000..1067fe7 --- /dev/null +++ b/sma.hh @@ -0,0 +1,61 @@ +/* +Simple moving average + +Copyright 2019 Ahmet Inan +*/ + +#pragma once + +namespace DSP { + +template +class SMA1 +{ + TYPE hist_inp[NUM]; + TYPE hist_avg; + int hist_pos; +public: + SMA1() : hist_avg(0), hist_pos(0) + { + } + TYPE abs_dev() + { + TYPE sum(abs(hist_inp[0] - hist_avg)); + for (int i = 1; i < NUM; ++i) + sum += abs(hist_inp[i] - hist_avg); + return sum / NUM; + } + TYPE operator () (TYPE input) + { + hist_inp[hist_pos] = input; + if (++hist_pos >= NUM) + hist_pos = 0; + TYPE hist_sum(hist_inp[0]); + for (int i = 1; i < NUM; ++i) + hist_sum += hist_inp[i]; + return hist_avg = hist_sum / NUM; + } +}; + +template +class SMA2 +{ + TYPE hist_inp[NUM]; + TYPE hist_sum; + int hist_pos; +public: + SMA2() : hist_sum(0), hist_pos(0) + { + } + TYPE operator () (TYPE input) + { + hist_sum += input - hist_inp[hist_pos]; + hist_inp[hist_pos] = input; + if (++hist_pos >= NUM) + hist_pos = 0; + return hist_sum / NUM; + } +}; + +} +