In the EWMA filter ( GitHub - jonnieZG/EWMA: Exponentially Weighted Moving Average Filter )
is it possible to change the EWMA parameters inside the loop() ? Bellow is the original code.
#include <Arduino.h>
#include <Ewma.h>
Ewma adcFilter1(0.1); // Less smoothing - faster to detect changes, but more prone to noise
Ewma adcFilter2(0.01); // More smoothing - less prone to noise, but slower to detect changes
void setup()
{
Serial.begin(115200);
pinMode(A0, INPUT);
}
void loop()
{
int raw = analogRead(A0);
float filtered1 = adcFilter1.filter(raw);
float filtered2 = adcFilter2.filter(raw);
Serial.printf("Raw=%d, Filter1=%.3f, Filter2=%.3f", raw, filtered1, filtered2);
delay(100);
}
My question is if is possible use the statement like
Ewma adcFilter1(0.1);
INSIDE the loop then change the parameter in the runtime.
By your answer is OK . Right?
DaveX
June 12, 2023, 3:55am
4
You probably don't do that -- it would make another Ewma object that would expire at the end of loop.
You can adjust the alpha within the loop. I'm not sure how you'd like to change it but something like this completely untested code should work:
#include <Arduino.h>
#include <Ewma.h>
Ewma adcFilter1(0.1); // Less smoothing - faster to detect changes, but more prone to noise
Ewma adcFilter2(0.01); // More smoothing - less prone to noise, but slower to detect changes
void setup()
{
Serial.begin(115200);
pinMode(A0, INPUT);
pinmode(A4, INPUT);
pinmode(A5, INPUT);
}
void loop()
{
int raw = analogRead(A0);
adcFilter1.alpha = analogRead(A4)/1023.0;
adcFilter2.alpha = analogRead(A5)/1023.0;
float filtered1 = adcFilter1.filter(raw);
float filtered2 = adcFilter2.filter(raw);
Serial.printf("Raw=%d, Filter1=%.3f, Filter2=%.3f", raw, filtered1, filtered2);
delay(100);
}
I will put it inside the setup. It should work better. The program may ask the user to adjust the filter weight. After this the program restart from setup. It seems better.
DaveX
June 12, 2023, 7:53pm
6
Any user-based changes will be lost at the restart.
If you ask and update in setup, any changes during that power cycle will persist throughout that powercycle.
gcjr
June 13, 2023, 9:48am
7
why not just implement the filter directly?
K can be changed at run-time, we modified K in speakerphones for depending if samp > avg
const byte PinInp = A1;
float avg;
float K = 1.0 / 8;
// -----------------------------------------------------------------------------
void loop()
{
float samp = analogRead (PinInp);
avg += (samp - avg) * K;
Serial.println (avg);
delay (200);
}
void setup()
{
Serial.begin(115200);
avg = analogRead (PinInp);
}
2 Likes
Using libraries to abstract even simple software patterns is a huge help when making complex projects. It's rarely a good idea to implement things like filters directly.
1 Like
system
Closed
December 14, 2023, 4:20pm
9
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.