Reputation: 433
I'm trying to store the average light level (using the light sensor) from the past few seconds to use in a comparison to call another function if the current light level is about 25% of the average.
My problem is I'm not entirely sure how to go about storing the average.
I'm assuming you would do something along the lines of
while(sensorUpdateTime + sampleTime < CurrentTime)
average += currentValue / updatesSampleRate;
I'm just kind of at a loss on how to store the average.
Upvotes: 2
Views: 753
Reputation: 10820
The average is just a particular case of the low pass filter. It will introduce a delay but if there is no problem you can use it. You have here a pseudo-code for a low pass filter implementation. You just modify the alfa
parameter. You can apply this for the last N values.
Upvotes: 0
Reputation: 12367
If you sample rate is quite constant, you can store values in an array and do "circular" updates ( use array[sampleNumber % array.length] to find oldest value to expunge.
Then you just substract expunged value out of kept sum, and add new value.
This way you have average over past array.length sensor readings. And you can also get variance - just keep sum of squarer sensor values, and then:
sigma = sqr( MX2 - MX )
Upvotes: 1