PIC24F while loop

Discussion in 'Embedded Systems and Microcontrollers' started by hansng, Mar 26, 2012.

  1. hansng

    Thread Starter New Member

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

    I wonder why this code is not working:
    Code ( (Unknown Language)):
    1. waitForHostReady = 1;
    2. while(waitForHostReady);
    while this one is working:
    Code ( (Unknown Language)):
    1. waitForHostReady = 1;
    2. while(waitForHostReady)
    3.     __delay_us(0);
    Here is how I define the variable:
    Code ( (Unknown Language)):
    1. 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:
    Code ( (Unknown Language)):
    1. void ISR(void) {
    2.     if(waitForHostReady)
    3.         waitForHostReady = 0;
    4. }
    Does this have to do with the interrupt?
     
  2. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    7,386
    1,605
    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;
     
    hansng likes this.
  3. hansng

    Thread Starter New Member

    Mar 26, 2012
    3
    0
    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.
     
  4. hansng

    Thread Starter New Member

    Mar 26, 2012
    3
    0
    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?
     
Loading...