Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
11 years, 2 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
11 years, 2 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;