A simple smooth filter [code example]

Here is a simple smooth filter that can smooth a jittery input signal:

template<typename T>
static T minmax(T val, T min, T max)
{
	return val < min ? min : val > max ? max : val;
}

class SmoothFilter
{

private:

	float _coef;
	float _res;

public:

	SmoothFilter() = delete;
	SmoothFilter(float coef)
		: _coef(minmax(coef,0.f,0.99f)), _res(0) 
	{}

	float operator()(float val)
	{
		_res = val * (1.f - _coef) + _res * _coef;
		return _res;
	}
};

SmoothFilter sf1(0.65);
SmoothFilter sf2(0.8);
SmoothFilter sf3(0.95);

#define INPUTPIN 14

void setup() 
{
	Serial.begin(115200);
	pinMode(INPUTPIN, INPUT);
}
void loop() 
{
	float input = analogRead(INPUTPIN);
	Serial.print(input);  
	Serial.print(",");
	Serial.print(sf1(input) + 100);
	Serial.print(",");
	Serial.print(sf2(input) + 200);
	Serial.print(",");
	Serial.println(sf3(input) + 300);
	delay(100);
}

Blue - input signal
Red - 0.65 smoothing
Green - 0.8 smoothing
Orange - 0.95 smoothing

1 Like

Interesting idea for the overloading of operator ()

(Since everything is hardcoded as float may be you can just inline your constrain function with a float inside the class)

There is arduino function (a macro) to constrain as well, I was thinking of templating filter as well at first hence minmax template.

OK

Yes there is but it’s a macro

#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))

➜ which poses the risk of multiple evaluation of the arguments, I don’t like it. I like your function better

Good example

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.