3

The following code prints some text once and waits for the interrupt to continue printing. The while loop is used to wait till the interrupt occurs. My issue is that the code works fine when a delay is added inside the while loop, but fails when there's no delay. what is the reason for it? The same issue happens in Atmel studio for ATSAM3X8E.

int a = 0;
int thisByte = 33; 

void setup()
{ 

    Serial.begin(9600); 
    attachInterrupt(0, keyPadISR, LOW);                                                         
    Serial.println("ASCII Table ~ Character Map"); 
}

void loop()
{ 
    // This is a dummy code to say program is running
    Serial.write(thisByte);    
    Serial.print(", dec: "); 
    Serial.print(thisByte);      
    Serial.print(", hex: "); 
    Serial.print(thisByte, HEX);     
    Serial.print(", oct: "); 
    Serial.print(thisByte, OCT);     
    Serial.print(", bin: "); 
    Serial.println(thisByte, BIN);   

    while(a != 10)
    {
        // Program does not work if u delete this delay(1).
        delay(1);
    }

    thisByte++;  
} 


// This is the key pad interrupt
void keyPadISR()
{  
    a = 10;
}
4
  • Does "no delay" include using a line like delay(0);? Commented Nov 21, 2013 at 5:33
  • Are you getting a compile or runtime error? I could understand the runtime error because you'd be stuck in an infinite loop. Commented Nov 21, 2013 at 5:34
  • delay(0) works fine, but when I leave the loop empty it doesn't work. Also delay(0) does not work in atmel studio for the ATSAM3X8E. Commented Nov 21, 2013 at 5:36
  • @KepaniHaole It happens during runtime. The infinite loop condition does not occur if the interrupt changes the value of a. Commented Nov 21, 2013 at 5:42

1 Answer 1

4

The compiler doesn't know that the ISR that changes the value of a is ever run, and so has optimized the entire loop out due to its evaluation of the loop condition. You must declare a as volatile in order to tell the compiler that its value must be checked each time.

volatile int a = 0;
Sign up to request clarification or add additional context in comments.

1 Comment

If you happen to also be looking for C++11 correctness you may wish to use a sig_atomic_t variable. Though realistically, the volatile will be just fine on most platforms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.