Hi, I guess keeping the last N values and simply averaging them is out of the question (uses too much RAM?). Another approach would be to do the following: Add the first N samples. Lets make it 16. Since your values are all 0 to 15, this sum will fit into a byte - lets call it Sum. The average at this point is then Avg ~= Sum div 16. When you receive the next byte, you calculate your new average by NewAvg = ((Sum-PrevAvg)+NewSample) div 16. You simply keep in applying this formula for each new sample. The only storage spave you need is for the Sum. This is of course not a true average, but it performs a low pass function on your data and will thus minimize the effect of noise spikes. Hope this helps. Niki > Anybody got a good averaging algorithm? > > I've got a stream of numbers from 0 to 15 coming out of a PIC '620 > comparator representing temperature of an appliance. When I turn on > the flourescent lamp on my bench, the program picks up a spike, and > the relay in this thing fires momentarily, because it reads the > noise. "NO PROBLEM" I sez, and sat down to write an averaging > algoritm. > > This ought to be so easy. The first "Algorithm" anybody learns in > kindy-garden Math 1 is how to average numbers. I've been checking > out verious ways of averaging a stream of data, though, and don't > have one that satisfies on a PIC with Two byte arithmetic and no > floating point math. > > Try this. Make a spreadsheet with 300 or 400 random integers between > 0 and 16. Take the arithmetic average of all of 'em, probably > around 8. Then try to simulate a PIC program processing each number > in succession that would get near the average, without floating point > math. I tried a half dozen ways this morning. > > One trick I worked out is that the average of N numbers, given the > NTH piece of data is being processed now, is (N-1)*(old average)/N > plus (Nth piece of data)/N. If you pick 256 data points, given the > old average AVG and the new data point DATA, > > NEWAVG = {(AVG*255)+DATA}/256 > > That oughta work! Not so fast. Using only integer values,no > floating point math, the average climbs slowly toward zero and stays > there. PICs can probably do floating point math, but there's gotta > be an easier way! > > > Best Regards, > > Lawrence Lile >