From 6736b36470e8dfd5dd13db75f0bfe2662974ff98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Xose=20P=C3=A9rez?= Date: Tue, 5 Dec 2017 23:55:59 +0100 Subject: [PATCH] Small improvement in MedianFilter --- code/espurna/libs/MedianFilter.h | 32 +++++++++++++++----------------- code/espurna/power.ino | 8 ++++---- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/code/espurna/libs/MedianFilter.h b/code/espurna/libs/MedianFilter.h index 1284a3b2..944fe894 100644 --- a/code/espurna/libs/MedianFilter.h +++ b/code/espurna/libs/MedianFilter.h @@ -1,5 +1,5 @@ // ----------------------------------------------------------------------------- -// Stream Injector +// Median Filter // ----------------------------------------------------------------------------- #pragma once @@ -16,27 +16,25 @@ class MedianFilter { if (_data) delete _data; } + virtual void add(double value) { + _data->push_back(value); + } + + virtual unsigned char count() { + return _data->size(); + } + virtual void reset() { double last = _data->empty() ? 0 : _data->back(); _data->clear(); add(last); } - virtual void add(double value) { - _data->push_back(value); - } - - virtual double median(bool do_reset = false) { + virtual double result(bool do_reset = false) { double sum = 0; - if (_data->size() == 1) { - sum = _data->back(); - - } else if (_data->size() == 2) { - sum = _data->front(); - - } else if (_data->size() > 2) { + if (_data->size() > 2) { for (unsigned char i = 1; i <= _data->size() - 2; i++) { @@ -54,6 +52,10 @@ class MedianFilter { sum /= (_data->size() - 2); + } else if (_data->size() > 0) { + + sum = _data->front(); + } if (do_reset) reset(); @@ -62,10 +64,6 @@ class MedianFilter { } - virtual unsigned char count() { - return _data->size(); - } - private: std::vector *_data; diff --git a/code/espurna/power.ino b/code/espurna/power.ino index 8c68b4ac..d16845f1 100644 --- a/code/espurna/power.ino +++ b/code/espurna/power.ino @@ -199,11 +199,11 @@ void _powerRead() { void _powerReport() { // Get the fitered values - _power_current = _filter_current.median(true); + _power_current = _filter_current.result(true); #if POWER_HAS_ACTIVE - _power_apparent = _filter_apparent.median(true); - _power_voltage = _filter_voltage.median(true); - _power_active = _filter_active.median(true); + _power_apparent = _filter_apparent.result(true); + _power_voltage = _filter_voltage.result(true); + _power_active = _filter_active.result(true); if (_power_active > _power_apparent) _power_apparent = _power_active; _power_reactive = (_power_apparent > _power_active) ? sqrt(_power_apparent * _power_apparent - _power_active * _power_active) : 0; _power_factor = (_power_apparent > 0) ? _power_active / _power_apparent : 1;