Low Pass Filter

Monkey Forums/Monkey Programming/Low Pass Filter

Anatol(Posted March) [#1]
Hi. I'm just sharing a very simple low pass filter. That's useful if you're using the raw accelerometer data which tends to have enough noise to produce quite a jittery result.

Strict

Class LowPassFilter
  
  Field value:Float
  Field alpha:Float
  
  ' dt : time interval
  ' rc : time constant
  Method New( startValue:Float = 0, dt:Float = 0.05, rc:Float = 0.3 )
    value = startValue
    alpha = dt / ( rc + dt )
  End
  
  Method Update:Float( input:Float )
    value = ( alpha * input ) + ( 1.0 - alpha ) * value
    Return value
  End
  
End


Depending on dt and rc values the filter may slightly delay movement, but for my purposes it works really well with the default values above.

To use it simply do something like this:
lowPassFilter = New LowPassFilter()

' and in the Update loop e.g.:
Local filteredAccelX := lowPassFilter.Update( AccelX() )
sprite.Rotation = -filteredAccelX * 90


In this case the filter smoothes out the rotation of a sprite which is controlled by the accelerometer x value. Do the same with the raw data and the sprite will look like it had a caffeine overdose.


Anatol(Posted March) [#2]
Oops. Should've gone to the Monkey Code forum. Sorry, I noticed that one too late.


Gerry Quinn(Posted March) [#3]
I use the same function for my framerate recorder. Though I always called it a moving average :D