Domanda

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;
}
È stato utile?

Soluzione

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top