Pages: [1]   Go Down
Author Topic: SOLVED:Checking variable for while loop, updated from Interrupt  (Read 429 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Jr. Member
**
Karma: 0
Posts: 66
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I am using a TIMER1 overflow interrupt,
I have written a quick code to test to see if i can update a variable with the interrupt as its being checked by a while statement.

Code:
   
    #include "TimerOne.h"
    
    byte FLAG = 0;
    void setup()
    {
      Serial.begin(9600);
      pinMode(6, OUTPUT);
      Timer1.initialize(1000000);        
      Timer1.attachInterrupt(callback);  
      Timer1.stop();
      
    }
    
    void callback()
    {
      digitalWrite(6, HIGH);
      delay(10);
      digitalWrite(6, LOW);
      FLAG = 1;
      Timer1.stop();
     }
    
    void loop()
    {
      Serial.println("SEND MESSAGE");
      Timer1.start();
      Serial.println("RECEIVING");
      while(FLAG == 0);
      FLAG = 0;
      delay(10000);      
    }
    

It doesn't notice the interrupt change in the FLAG status with :   while(FLAG == 0);

It does notice the flag change however if i put something in the while loop to check eg:

while(FLAG ==0){
Serial.println(FLAG, DEC);
}

Does anyone know why this is happening?
Doesn't  " while(FLAG == 0);" continuously check the state of FLAG anyways?

« Last Edit: August 18, 2011, 12:19:06 pm by btsp » Logged

Bristol, UK
Offline Offline
Edison Member
*
Karma: 1
Posts: 1197
Exhibitor at UK Maker Faire
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Any variable that's shared between interrupt code and the main code must be declared 'volatile':

Code:
volatile byte FLAG = 0;
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 631
Posts: 50115
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
      delay(10);
In an interrupt handler? I don't think so!
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 66
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

thanks the volatile byte worked.

yes i know putting a delay in there is bad, in my actual program there is nothing like that.

thanks again
Logged

Pages: [1]   Go Up
Jump to: