View previous topic :: View next topic |
Author |
Message |
davie1_1
Joined: 14 Sep 2003 Posts: 2
|
Addition Loop Error |
Posted: Mon Jul 25, 2005 11:31 pm |
|
|
Hi All,
I keep getting an wrong addition total from the folloing loop:
int32 pos_peak;
pos_peak = 0;
for(i=32; i!=0; i--){
pos_peak += 50000;
}
The total should be 1,600,000 but I get 2148283648. Stepping through it I get the correct result but at full speed it's always wrong. Can someone tell me why and how to fix it? Is it the ADDWFC instruction?
Thanks,
David P |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Jul 25, 2005 11:59 pm |
|
|
Here's a full test program. I tested this with the MPLAB 7.20 simulator
(with UART1 writing to the Output Window), and also with the
PicDem2-Plus board writing to a terminal window on the PC.
Both displayed this:
Code: | #include <16F877.H>
#fuses XT, NOWDT, NOPROTECT, BROWNOUT, PUT, NOLVP
#use delay(clock = 4000000)
#use rs232(baud = 9600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)
//====================================
void main()
{
int32 pos_peak;
int8 i;
pos_peak = 0;
for(i=32; i!=0; i--)
{
pos_peak += 50000;
}
printf("result = %lu \n\r", pos_peak);
while(1);
} |
|
|
|
Ttelmah Guest
|
|
Posted: Tue Jul 26, 2005 4:37 am |
|
|
The 'error' result, is suspiciously close to 2^31 away from the real result (in fact 800000 away from it). If the sum was subtracting not adding, I'd say there was a confusion between a signed/unsigned integer somewhere...
Best Wishes |
|
|
davie1_1
Joined: 14 Sep 2003 Posts: 2
|
|
Posted: Sat Jul 30, 2005 12:48 pm |
|
|
for some reason I added i++ after the loop and now I get the correct answer in full speed. If I remove the i++ it does it again. I don't know why this would be but increment is a single instruction so I'll leave it.
David P |
|
|
|