Saturday, October 31, 2009

Luck at DSPic

void main()
{
unsigned int i=0;

for (i=10;i>=0; i--)
{
display (i);
...
..
}

display("task completed");

}

Do you think the last line of code (red one) will ever be executed ?
If yes... think again..

The problem occurred when Soumya and myself were programming DSPic for IMU. The program wouldn't come out of the loop. We flagged and traced each and every line. Ultimately we tried writing the following just before the brace close of the for loop and it worked.

if (i==0) break;

We tried figuring out what was stopping the for loop from exiting by itself when all the i iterations were done. We realized that when the i=0 iteration has completed, i-- is executed. i should have become -1 but since i is unsigned int, it becomes 255. Now i>=0 is checked which is obviously true so the loop is executed 256 times more. This cycle goes on indefinitely. To overcome the issue, we decided to run the loop from i=11 to i=1 not letting i attaining sub 0 value anymore and it worked.

Great discovery at 2 in the night once again in TMRS lab.

No comments: