Home > Back-end >  While loop is not stopping in arduino
While loop is not stopping in arduino

Time:03-01

I am applying a while loop, but the loop does not stop. Also, the serialmonitor stops writing values. Why is that? Also the stop command is not working. Below is my code

while (x <= Y) //Y is a constant integer, x is defined formulaically earlier 
  {
    digitalWrite(SPin, HIGH);
    //motor running code  
    digitalWrite(dir1,HIGH);
    digitalWrite(dir2,LOW);
    analogWrite(speedPin,mSpeed);
    Serial.println(x);
    delay(50);
  }

CodePudding user response:

You need to update the variable "x". for example if you want to repeat the loop 250 times just add 1 to x every loop.

 while (x <= y) {
    digitalWrite(solenoidPin, HIGH);//Switch Solenoid ON
    //motor running code  
    digitalWrite(dir1,HIGH);
    digitalWrite(dir2,LOW);
    analogWrite(speedPin,mSpeed);
    Serial.println(x);
    delay(50); 
    x = x 1; //this makes it so that every time the loop repeats x goes up
  }

if you are using a value from an input you must read that input during the while loop (C doesn't automatically update variables):

while (x <= y) {
    digitalWrite(solenoidPin, HIGH);//Switch Solenoid ON
    //motor running code  
    digitalWrite(dir1,HIGH);
    digitalWrite(dir2,LOW);
    analogWrite(speedPin,mSpeed);
    Serial.println(x);
    delay(50); 
    x = analogWrite(youranalogpin);
  }

However if you want to force-stop the loop you can use:

break;

use this only inside a if-condition, or else the loop will never work. Example:

while (x <= y) {
  if(stop /*== true*/)
    break;
}

Remember that every value must be read and stored

  • Related