Averaging is not working

General discussion on mikroC PRO for AVR.
Post Reply
Author
Message
rrsquez
Posts: 117
Joined: 23 Feb 2011 21:35

Averaging is not working

#1 Post by rrsquez » 12 Nov 2015 19:44

Hello. I have a problem getting my code to average properly. Attached is a code snippet to keep it simple.

I merely add 16 ADC sample values and divide by 16. The result I get is 4.7175 volts, but it should be 0.484 volts. This 4.7174 is actually 75.48 if I omit the "divide by 16" line of code. This makes my result 75.48/0.484 = 155.95. Oddly enough, it should have been "16" (sample count). This means my for loop is running approximately 10 times too many times (155.95/16 = 9.75).

I believe I did the "for" loop in my code correctly, so I don't know what is wrong with this code. Here is the code that matters:
for (i = 0; i < 16; i++)
{ mylong += LTC2400(); // Read the ADC value, add to average }
mylong >>= 4; // divide by 16 (sample count)


My LTC2400() function returns an ADC count value. I multiply by the ADC resolution prior to reporting the value. This function works correctly with individual calls. The result is 32 bits.

Realizing this compiler has problems with 32 bit words, I tried converting everything to floating point. I got exactly the same result (off by 15.95 x).

Would someone please look at my code and tell me what I did wrong?

Thank you, Richard V
Attachments
Averaging Problem.zip
(645 Bytes) Downloaded 136 times

aCkO
Posts: 1119
Joined: 14 Feb 2011 04:07
Location: Bar, Montenegro

Re: Averaging is not working

#2 Post by aCkO » 12 Nov 2015 20:45

Your code works fine in both variants. You should probably do a little more debugging of LTC2400 function. Try printing the samples as you read them. I just replaced LTC2400 with:

Code: Select all

long LTC2400()
{
   return 1624034;
}
and tried it in simulator.

Regards

Post Reply

Return to “mikroC PRO for AVR General”