문제

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;
}
도움이 되었습니까?

해결책

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top