Ticker won't run in empty while(1) loop

27 Apr 2012

Hi, I read a previous post where a Ticker had been set, the main program runs in an empty loop with a simple ; since an empty loop can't sustain a ticker. I've found it will only run with a 'wait'. In my example below, removing the 'wait' means the program never stops (i.e. all leds don't show). Is there a better 'do tasks' command than havin to use 'wait' to put in my while(1) {} ?

Ticker itimer;
int i=0;

void inc_i()
{
    i++;
}
int main() {
   
    myled1=0;myled2=0;myled3=0;myled4=0;
    itimer.attach_us(&inc_i,2000);
    while (i<100)
    { 
        myled2=!myled2;
        wait_ms(1);  //won't work without it!!
    }
    itimer.detach();
    myled1=1;myled2=1;myled3=1;myled4=1;
}

Thanks in advance, Sam

27 Apr 2012

This may be caused by a compiler optimization. The compiler doesnt see that 'i' gets updated in the Ticker function and removes the instructions. Try using the volatile directive:

volatile int i = 0;
01 May 2012

Works like a charm! Thank you! Sam