Help with While loops

Hi all,

Ok so my problem is that I have an if statemt, and when that if statment is true, i would like to go into a while loop, however I dont want to stay in that while loop. I just want to be in that while loop for as long as the if statment is true and then proceed with the rest of my code. Please take a look at my code:

digitalWrite(SLEEP, LOW);
 
  // switch off the power to stepper
  Serial.print("SLEEPING..");

while (digitalRead(SLEEP)==LOW) { 
    for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) { 
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);         
    // wait for 30 milliseconds to see the dimming effect    
    delay(30);                            
  } 

  // fade out from max to min in increments of 5 points:
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) { 
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);         
    // wait for 30 milliseconds to see the dimming effect    
    delay(30);                            
  } 
delay(10000);
digitalWrite(SLEEP, HIGH);
   Serial.println("AWAKE!!!");                // Switch on the power to stepper
  delay(1000);

So basically my code puts the stepper motor to sleep and while the stepper motor is in sleep mode, i would like to have an LED fading in and out, but then after sometime or after the user gets the motor out of sleep mode i want the LED to stop fading in out.

Please help!!!

Thanks! :slight_smile:

That's what while loops do? (loops until condition is false).

You seem to be missing an end-curly bracket "}" for the while loop btw.

And the big Delay() will make it unresponsive for the hole dalay, so first you will see a fade-in and a fade-out, and then the delay(10000). If you intended it to fade in and out while you waited the 10 seconds, you need to not use Delay(10000). Look into the blink without delay example. Basically assign the millis() timer value to a variable, then calculate time spent and have that as a condition in your while-loop instead.

e.g
(pseudo-code)

long sleepTimer = (long)millis();

turn off stepper

while(millis() - sleepTimer < 10000)
{
  fade in
  fade out
}

wake up stepper

[edit]blink without delay link: http://arduino.cc/en/Tutorial/BlinkWithoutDelay
Hope this helps[/edit]