Joined: 28 Jun 2005 Posts: 200 Location: Ashburton / Mid Canterbury / New Zealand
Posted: Thu Jul 15, 2021 9:56 pm Post subject: Rolling average to smooth sensor jitter
Hi.
Just a function to smooth sensor jitter. Code pretty dirty but gives the general idea. Improvements welcome.
Code:
Sub GetBatteryVoltage() 'Calculate an rolling average.. Loads data into an array and fills it. Once filled starts overwriting the oldest data with the newest 'Between reads of sensor, Code reads the array and averages the data in it 'Data saggy at the start of filling as array is empty
Local Result asWord Local Average asWord Local X asbyte
Result=0
Average=0
X=0
If BattReadIndex = NumOfBattReadings then
BattReadIndex =0'Wraps around to the beginning of array: End if
Result=BattVolt 'BattVolt = Getadc(1)
BattReadings(BattReadIndex)= Result 'Store it in the array
BattReadIndex = BattReadIndex +1'Advance to the next position in the array:
Result=0
For X =0to NumOfBattReadings 'Read the array
Result=Result+BattReadings(X) Next X
Average= Result/NumOfBattReadings 'Calculate the average:
BatteryVoltage=Average
Joined: 05 Jan 2006 Posts: 1570 Location: Basel, Switzerland
Posted: Fri Jul 16, 2021 9:05 am Post subject:
Hi,
I've been using this code to smooth sensor values for several years.
Code:
Const _smoothing_factor =3'Nr.values for avg
Dim Pressure_accumulator(2)AsLong Dim Temp_long AsLong Dim Accumulator_temp AsLong Dim Sensor_value AsWord Dim Accumulator AsLong
'smooth raw value
Temp_long = Pressure_accumulator(temp_byte)'Load value into temp var.
Accumulator = Temp_long 'This is the old average on LONG form Shift Accumulator , Right , _smoothing_factor 'Accumulator sum divided by 2^smoothing factor
Pressure_raw(temp_byte)= Accumulator
Temp_long = Temp_long - Accumulator 'Subtract old value
Temp_long = Temp_long + Sensor_value 'Add new
Pressure_accumulator(temp_byte)= Temp_long 'Save accumulator for next time
This code avoids using a divide which is slow on AVR's.
This function is more a weighted average, where younger values have more weight in the result.
Regards
Ian Dobson _________________ Walking on water and writing software to specification is easy if they're frozen.
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You cannot download files in this forum