From 48ded57153176f4fff4cfb8e5b1751b85e25842d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20S=C3=A1nchez=20Corral?= Date: Thu, 24 Aug 2023 12:52:15 +0200 Subject: [PATCH] Fixed filterArrayWithNoise Also fixed small bugs and unhandled errors in GenericMovingAverage. --- src/averages/GenericMovingAverage.tpp | 16 +++++++++++----- src/util/generate_data.cpp | 9 +++------ 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/averages/GenericMovingAverage.tpp b/src/averages/GenericMovingAverage.tpp index 18a884c..e32216b 100644 --- a/src/averages/GenericMovingAverage.tpp +++ b/src/averages/GenericMovingAverage.tpp @@ -37,15 +37,16 @@ T GenericMovingAverage::getFilterOutput() { using sum_t = typename conditional::value, int, T>::type; sum_t _sum = 0; - for (uint16_t i = 0; i < _values.size(); i++) + for (uint16_t i = 0; i < _index; i++) // Iterate up to _index { _sum += _values[i]; } - returnValue = _sum / _values.size(); + returnValue = _sum / (_index > 0 ? _index : 1); // Divide by _index if greater than 0, else divide by 1 } return returnValue; } + /// @brief Get the last value added to the buffer /// @tparam T: The type of the values to be stored /// @return T: The last value added to the buffer @@ -53,7 +54,11 @@ T GenericMovingAverage::getFilterOutput() template T GenericMovingAverage::getLastValue() { - return _values.at(_index); + if(_values.size() > 0) + { + return _values.at(_index); + } + return 0; } /// @brief Get the buffer status @@ -64,11 +69,11 @@ template g_buf_status_t GenericMovingAverage::getBufferStatus() { g_buf_status_t returnValue; - if(_index != _index % _bufSize) + if(_values.size() == _bufSize) { returnValue = g_buf_status_t::BUFFER_FULL; } - else if(_index == 0) + else if(_values.empty()) { returnValue = g_buf_status_t::BUFFER_EMPTY; } @@ -78,6 +83,7 @@ g_buf_status_t GenericMovingAverage::getBufferStatus() } return returnValue; } + /// @brief Clear the buffer /// @tparam T: The type of the values to be stored /// @details Clear the buffer and reset the index and count. diff --git a/src/util/generate_data.cpp b/src/util/generate_data.cpp index a92f338..883ffe6 100644 --- a/src/util/generate_data.cpp +++ b/src/util/generate_data.cpp @@ -20,12 +20,9 @@ vector generate_data::filterArrayNoise(vector origin, GenericMovingAverage { filter->push(noiseValue); - if (filter->getBufferStatus() == g_buf_status_t::BUFFER_FULL) - { - auto lastValue = filter->getLastValue(); - auto bufVal = filter->getFilterOutput(); - result.push_back(bufVal); - } + // Always add the filtered value to the result + auto bufVal = filter->getFilterOutput(); + result.push_back(bufVal); } return result;