Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
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?

share|improve this question
2  
Is it ever triggering the if() and printing? If it is, what's outside this code? and does it dump it right back into the while(){}? Maybe put a Serial.println() after the while(){} to prove you aren't misdiagnosing the unseen code. – Dave X May 17 at 16:08
    
I've printed the value of i and it's 1 after my switch goes high. I even used i++; to see if it increases, but it only increases once and after that it just prints out the lat and lng every time the switch goes high. Edit: nothing outside the while loop gets executed after i is set to 1. – Keilara May 17 at 16:44
    
Then it is getting out of the while loop. Your problem is in the unseen, surrounding code. – Dave X May 17 at 16:55
    
All right, I'll look into the whole code and tell you what I find by tomorrow. – Keilara May 17 at 17:24
    
If you want i to maintain its state outside of the posted code, perhaps you should move the i=0; statement outside of its current scope. – Dave X May 17 at 17:27
up vote 0 down vote accepted

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;.

share|improve this answer

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)'

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.