int i=0;
while(i == 0){
if(digitalRead(saveSwitch) == HIGH){
Serial.print("New coordinates saved \n");
lat1 = gps.location.lat();
Serial.print("Latitude");
Serial.println(lat1);
lng1 = gps.location.lng();
Serial.print("Longitude");
Serial.println(lng1);
i = 1;
}
}
Why isn't leaving the while loop?
2 Answers 2
Why isn't leaving the while loop?
There's a good chance that the code is leaving the while
loop, repeatedly. However, if the code that's shown is in (eg) the loop()
function, i
will be reset to 0 each time the function runs, which will cause the while
loop to start again.
As noted in Dave X's comment, you can move int i=0;
to a higher scope. Moving it to file scope, for example, will allow it to retain its value through repeated function calls. For example, if the code shown is in loop()
, you could put int i=0;
just before void loop() {
.
Note, having generically-named variables like i
declared at a high level is a bad idea, a blunder, a programming faux pas. An alternative is to leave its declaration within loop()
but add the static
keyword so that i
is allocated only once, rather than being reallocated and reinitialized at each execution of loop()
. For example: static int i=0;
.
Instead of setting i=1, you could use a 'break' command to break out of the while loop. That way you don't need 'i' at all, you can just do 'while(true)'
i
to maintain its state outside of the posted code, perhaps you should move thei=0;
statement outside of its current scope.