title: Breaking a while loop in Arduino
body: <p>I have a program that moves a stepper motor to the right, left and have a stop button that stops the motor. In one part of my program, a motor gradually lowers a speed and stops after a certain period of time <code>iv</code>.
  The problem is that in this part of a program (when a motor gradually lowers a speed and then stops) I can’t stop the motor upon pressing a stop button. I understand that I need to break a <code>while</code> loop somehow, but using a <code>break</code> statement doesn't wort for me.</p>
  
  <p>Do you have some ideas?</p>
  
  <p>Here is my function:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>/* --- STEPPER MOTOR ---*/
  const int motor_step = 3;
  const int motor_dir = 4;        
  int stepSpeed = 0;
  int stepMaxSpeed = 1000;        
  int fadeAmount = 100;           
  int fadeDelay = 10;
  
  /* ---- STOP BUTTON ---- */
  int buttonStop = 5;             
  int stateStop=0;
  
  void setup() {
    .
    .
    .
    stateStop = digitalRead(buttonStop);
  }
  void loop () {
    .
    .
    .
    myfunc();
  }
  
  
  void myfunc() {
    if(stateStop == HIGH) {noTone(motor_step); stepSpeed = 0;}
  
    elapsedMillis te;
    unsigned int iv = 1500;
  
    while (te &lt; iv) {
       if(stepSpeed == stepMaxSpeed) {
         stepSpeed = stepSpeed+0;
         tone(motor_step,stepSpeed);
         digitalWrite(motor_dir,HIGH); 
       }
       else {
         stepSpeed = stepSpeed + fadeAmount;
         tone(motor_step,stepSpeed);
         digitalWrite(motor_dir,HIGH);
         delay(fadeDelay);
       }
       if(stateStop == HIGH) { stepSpeed = 0; break;}
     }
     if(stepSpeed == stepMaxSpeed) {
       while(stepSpeed&gt;0){
         stepSpeed = stepSpeed-fadeAmount;
         tone(motor_step,stepSpeed);
         digitalWrite(motor_dir,HIGH);
         delay(fadeDelay);
         if(stateStop == HIGH) { stepSpeed = 0; break;}
       }
     }
     stepSpeed = 0;
     noTone(motor_step);
     digitalWrite(enable,LOW); // enable changed from HIGH
  }
  </code></pre>