Waiting in a while

Hello everybody!
I've been struggling wit ha problem for quite a while, and hope someone can help me.

I've successfully created a interrupt that sets a flag (char) high with a certain frequency. Now I want my program to wait in a while loop until the flag is set to 1.

[...]
while(timeflag == 0){}
timeflag = 0;
[...]

But it doesn't get out of the while loop.
If I insert an operation:

[...]
while(timeflag == 0){
digitalWrite(9,HIGH); //someting
}
timeflag = 0;
[...]

it works... So I assume this means that it's somehow jumping over the condition. I tried to insert one or more NOP's (no operation) but it doesn't do the trick.

Can you guys help?

  • Oliver

Post your whole program but please read the advice in the sticky posts at the top of this forum for advice on how to do it.

Have you declared timeflag as

volatile{/tt]?

Here's the code:

//GLOBAL
int msec = 0;
char sec = 0;
char minutes = 0;
char hours = 0;
char timeflag = 0;
char toggler = 0;

void setup(){
  
  //set pins as outputs
  pinMode(9, OUTPUT);

cli();//stop interrupts

//set timer1 interrupt
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register
  OCR1A = 15624;//Count up till
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  //Prescaling 1
  TCCR1B |=  (1 << CS10);  
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);


sei();//allow interrupts

}//end setup

ISR(TIMER1_COMPA_vect){
//Timing
  msec++;
  if(msec == 1000){
    msec = 0;
    timeflag = 1;
    sec++;
    if(sec == 60){
      sec = 0;
      minutes++;
      if(minutes == 60){
        hours++;
      }
    }
  }
}

void loop(){

  while(timeflag == 0){} //wait for flag
  timeflag = 0;
  if(toggler == 0){
      toggler = 1;
      digitalWrite(9,HIGH);
   }else {
      toggler = 0;
      digitalWrite(9,LOW);
   }
}

Hackscribble:
Have you declared timeflag as

volatile{/tt]?

[/quote]

No I've note tried with a volatile? How do a do that in arduino?
"volatile int timeflag;"?

That's right. But it would be clearer to declare timeflag as a boolean and then set it true and false.

volatile boolean timeflag = false;
// then, in the ISR ...
timeflag = true;
// then, in loop() ...
while (!timeflag) // while timeflag is not true
{
}
timeflag = false;

You should also try declaring all the other variables you use in the ISR as volatile: msec, sec, minutes and hours.

olivert:
No I've note tried with a volatile? How do a do that in arduino?
"volatile int timeflag;"?

Same as in C++.

IT WORKS! (Using volatile)
Thanks a lot!