My current Arduino project is a self-balancing robot, which requires repeatedly reading angle and acceleration values from an MPU-6050 gyro.
These values can be quite ‘noisy’ – fluctuating considerably when vibration is added into the system – so I found myself in need of some simple code that helps smooth out the values…
Here’s the class I wrote –
FilteredFloat, a simple Complementary Filter:
(See my earlier article on how to put this code into its own header file, to make it even easier to use in your projects.)
After creating an instance of the object, just repeatedly call
set(...) which each new reading value. The code will calculate a ‘running current value’ by combining the previous ‘set’ value and the new one, which you can retrieve using
smooth_value = F * old_value + (1.0 - F) * new_value
To apply more averaging try increasing the ‘smoothing’ value in the constructor (up to a value nearing 1.0). A smoothing of zero will result in no smoothing at all.