9 years, 6 months ago.

I cannot get out of while loop.

I started using mbed yesterday. I wrote a program that was intended to get out of while loop when the "i" become ten. but it does not work as I think. It does not stop writting when i is ten or more, Please tell me how to correct it. (Sorry for my poor English)

/////////////////////////////////

include the mbed library with this snippet

#include "mbed.h"
 
Serial pc(USBTX, USBRX); 
AnalogIn adc_in(p18);
LocalFileSystem local("local"); 
Ticker ticker;
   int i;
    unsigned short a[3504];
    float v;
    FILE *fp;
 
void int_timer () {
    // 1ms
    v=adc_in.read()*1023;
    pc.printf("%d",v);
    i++;
} 
int main(){
    ticker.attach(int_timer,1);
    i=1;
    while(i<=10){
    }
    ticker.detach();
    pc.printf("owari");
    return 0;
    }

1 Answer

9 years, 6 months ago.

This is a well known issue. The problem is that the compiler does not understand that the value i is incremented somewhere outside the while loop and it optimises the code to not re-read the value i all the time. Solution is to declare i as ''volatile''.

volatile int i;

Accepted Answer

It is new to me. The program work successfully with "volatile int". Thank you for your answer.

posted by Hirokazu Ishida 01 Oct 2014

As a simple rule any variable that is changed in an interrupt and read in the main loop should be declared as volatile. If you don't do this it will sometimes work and sometimes not work, you are at the mercy of how the compiler decided to optimize things.

posted by Andy A 02 Oct 2014