PIC24F while loop

Thread Starter

hansng

Joined Mar 26, 2012
3
I am having problem on while loop.

I wonder why this code is not working:
Rich (BB code):
waitForHostReady = 1;
while(waitForHostReady);
while this one is working:
Rich (BB code):
waitForHostReady = 1;
while(waitForHostReady)
	__delay_us(0);
Here is how I define the variable:
Rich (BB code):
unsigned char waitForHostReady = 0;
Also, I use interrupt to change the variable value to 1 to break the while loop. Here is the simplified code:
Rich (BB code):
void ISR(void) {
	if(waitForHostReady)
		waitForHostReady = 0;
}
Does this have to do with the interrupt?
 

ErnieM

Joined Apr 24, 2011
8,377
You don't mention your compiler but the better it is the more likely you are to see this. C does not merely translate your code to machine language but in some cases tries to out think your logic.

Try defining waitForHostReady as volatile. That will force C not to make assumptions about it's value.
volatile unsigned char waitForHostReady = 0;
 

Thread Starter

hansng

Joined Mar 26, 2012
3
ErnieM, thanks for your suggestion, will try that out soon.

By the way, I am using MPLAB C30 C Compiler. Sorry that I didn't mention earlier.
 

Thread Starter

hansng

Joined Mar 26, 2012
3
ErnieM, as you suggested, I tried using the volatile and it works!

Thank you so much!

By the way, could anyone briefly explain how does volatile help in this situation?
 
Top