Hi all, Had a bit of a problem with the 'while' instruction for a while. This sketch may help others who may have had problems.
int a;//attach middle leg of potentiometer to AO outer legs to 5v and 0v
void setup() {
Serial.begin(9600);
}
void loop() {
while (a<250 && a>100){
a = analogRead(A0);//must look at this variable to get out of while loop
Serial.println(300);//otherwise stuck for ever in while loop
Serial.println(a);
delay (5000);
}
a = analogRead(A0);//when a <250 and >100 while loop takes over
Serial.println(a);
delay (5000);
}
You might find do {} - while() could work better with the first pass forced.
int a;//attach middle leg of potentiometer to AO outer legs to 5v and 0v
void setup() {
Serial.begin(9600);
}
void loop() {
while (a<250 && a>100){
a = analogRead(A0);//must look at this variable to get out of while loop
Serial.println(300);//otherwise stuck for ever in while loop
Serial.println(a);
delay (5000);
}
a = analogRead(A0);//when a <250 and >100 while loop takes over
Serial.println(a);
delay (5000);
}
looks like there's really no need for a while loop in this code since the code inside and outside your while really just report the value of "a"
It looks like your sketch is equivalent to:
void loop()
{
int a = analogRead(A0);
if (a>100 && a<250)
Serial.println(300);
Serial.println(a);
delay (5000);
}
Not really, your sketch is too clean and doesnt spam Serial.println(a); multiple times
Sure it does! Every 5 seconds, just like the original. ![]()
Yes in this case but you might want to do something special in the while loop that only applies for values 100 -250. It could be anything. It could be something on a digital line for instance.
Hi Guys, The print is just there to check that the code works. You could have a digital out when the while statement is valid or just about anything else you like.