Pasi T Mustalahti wrote: > PTM: Q&D solution: > TEMP = (TEMP + NW)/2 > This needs 8 bit + carry to handle 0..255 values. > This function works if the sloshing makes small differences to both sides > of the right one and the time period is rather short, about 1/20 sek. > > If this still give odd values, you can make even: > TEMP = (TEMP + NV - TEMP/D) > VAL =TEMP / D > There TEMP is a 16 bit register for the summ > NV = nev measured value (0..255) > D is 2,4,8,16... (2^n) static > VAL is the value that is shown in the display. > This gives you totally wrong values from the first D*5 times (I tried > this) but after that you get every time a bit better approximation. > D is selected as a 2^n to get the program easier. > > You can even make a try with QBasic: > > '-------------------------------------------------- > 'PTMUSTA@UTU.FI > 'Demonstrating running averages > 'shareware ;) > '-------------------------------------------------- > CLS > NV = 3 > D = 4 > FOR i = 1 TO D * 6 > 'here we simulate random slosh > NVU = NV + (RND(1) - .5) / 10 > 'running average value > TEMP = (TEMP + NVU - TEMP / D) > DISPLAY = TEMP / D > PRINT i;"New=";NVU;"Displ=";DISPLAY;"err=";(DISPLAY-NV)/NV;"%" > NEXT I'm planning on using something similar to this running average algorithm in my current project which is to read current drawn by a 40HP AC motor. The value read fluctuates wildly sometimes (nature of the machinery) and needs to be damped. I don't know much about PICs but the algorithm can be easily implemented on 68HC11 because of 16 bit arithmetic instructions. Maybe somebody could implement it in PIC code. What I would do in your case would be:- LEVEL = 0 ; tank level value read by sensor (0 - 255) N = 16 ; number of readings to average over (2, 4, 8, 16,.... 256) RAVG = 0 ; running average value of tank level (0 - 255) over N readings RTOTAL = 0 ; running total after N readings :LOOP LEVEL = read new tank level value RAVG = (RTOTAL + LEVEL) / N RTOTAL = RTOTAL + LEVEL - RAVG END LOOP I get the running average first then the running total, I save on one divide operation. N value is chosen based on the frequency of the fluctuation in relation to your sampling rate. Choosing N=256 would really damp slow fluctuations and has one additional bonus in that you only have to take the hi order byte of the 16 bit value for (RTOTAL + LEVEL) / N to get RAVG. For any other N values you would have to do some shift right operations. And for N=256, RTOTAL has max of (2^16) - 1. I've not implemented this Q&D solution (as you put it) yet. I'm not sure whether it's going to work. -------------- seetho