Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.6 KiB

  1. // -----------------------------------------------------------------------------
  2. // Stream Injector
  3. // -----------------------------------------------------------------------------
  4. #pragma once
  5. class MedianFilter {
  6. public:
  7. MedianFilter(unsigned char size) {
  8. _size = size;
  9. _data = new double[_size+1];
  10. reset();
  11. }
  12. virtual void reset() {
  13. _data[0] = _data[_size];
  14. _pointer = 1;
  15. for (unsigned char i=_pointer; i<=_size; i++) _data[i] = 0;
  16. }
  17. virtual void add(double value) {
  18. if (_pointer <= _size) {
  19. _data[_pointer] = value;
  20. ++_pointer;
  21. }
  22. }
  23. virtual double average(bool do_reset = false) {
  24. double sum = 0;
  25. if (_pointer > 2) {
  26. for (unsigned char i = 1; i<_pointer-1; i++) {
  27. double previous = _data[i-1];
  28. double current = _data[i];
  29. double next = _data[i+1];
  30. if (previous > current) std::swap(previous, current);
  31. if (current > next) std::swap(current, next);
  32. if (previous > current) std::swap(previous, current);
  33. sum += current;
  34. }
  35. sum /= (_pointer - 1);
  36. }
  37. if (do_reset) reset();
  38. return sum;
  39. }
  40. virtual unsigned char count() {
  41. return _pointer - 1;
  42. }
  43. private:
  44. double *_data;
  45. unsigned char _size = 0;
  46. unsigned char _pointer = 0;
  47. };