[?] while-loop not exiting despite changes in conditon

Go To Last Post
9 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Not sure why the while-loop didn't stop despite the condition changed in an interrupt function.

uchar counterByTheSec = 0;

sei();
TCNT1 = 0;
while(globalFlag==0x00){
  if(TCNT1>6000){
    counterByTheSec++;
    TCNT1 = 0;
  }else{
    if(counterByTheSec > 9) break;
  }
}
cli();

The "globalFlag" is defined as extern uchar & its used in another file. The interrupt will be called & globalFlag will be set to 0x01 in less than 3 secs but the while-loop just continues despite the condition is already false & it just exit after 10 secs. I did a debugWire & did verified that the globalFlag was indeed 0x01 but the while-loop just go on & on. I am missing something :?

Once an engineer, forever an engineer

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Oh yeah, I'm using AVR167 coding in AS6.

Once an engineer, forever an engineer

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

MacTuxLin wrote:
I am missing something :?
Yes, a "volatile".

Stefan Ernst

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

(sigh) I solved it after adding a delay_ms(1); but why?

Once an engineer, forever an engineer

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm sorry, "volatile" ?

Once an engineer, forever an engineer

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

MacTuxLin wrote:
I'm sorry, "volatile" ?
[TUT][C]Optimization and the importance of volatile in GCC

Stefan Ernst

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Ah, got it now. Thanks a lot Stefan.

Once an engineer, forever an engineer

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

MacTuxLin wrote:
I'm sorry, "volatile" ?
FAQ #1.

In short, if a variable is changed by more than one 'thread', it must be declared volatile. This prevents the compiler from performing certain optimisations concerning that variable.

Specifically, every time the variable is referenced in your code, the compiler is forced to access the variable (be it a read or a write).

Without volatile, the compiler might conclude that the variable never changes (in the current compilation unit), and optimise away some or all of the references.

Also, have a look at this.

JJ

"Experience is what enables you to recognise a mistake the second time you make it."

"Good judgement comes from experience.  Experience comes from bad judgement."

"Wisdom is always wont to arrive late, and to be a little approximate on first possession."

"When you hear hoofbeats, think horses, not unicorns."

"Fast.  Cheap.  Good.  Pick two."

"Read a lot.  Write a lot."

"We see a lot of arses on handlebars around here." - [J Ekdahl]

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks for the explanation & link (doc) JJ. Yeap, added to one of my "post-it" on the side of my screen....

Once an engineer, forever an engineer