Hi. question for "if" and "loop"

Hi i have problem. it can be easy for you guys.

here is the my code

void setup()
{
pinMode(3, OUTPUT);
pinMode(7, OUTPUT);
pinMode(9, OUTPUT);
Serial.begin(9600);
Serial.println("speed 0 to 255");
}

void loop()
{
if(Serial.available()){
int speed=Serial.parseInt();
if(speed>=0 && speed<=255){
Serial.println("current speed:" + String(speed));

for(int i=0; i<=speed; i+=2){
digitalWrite(3,HIGH);
digitalWrite(7,LOW);
analogWrite(9,i);
Serial.println(i);
delay(100);
}

for(int i=0; i<=speed; i+=2){
digitalWrite(3,HIGH);
digitalWrite(7,HIGH);
analogWrite(9,i);
Serial.println(i);
delay(100);
}
}
}
}

It works well, but i made the program that

if i make input "60", "speed" will go from 0 to 60 and from 60 to 0 intinetly

but in my case,

after executing from 0 to 60 and from 60 to 0 once,

i should make input again

what i want is if i input "60", it would make loop without asking more

can you help me?

k_river:
after executing from 0 to 60 and from 60 to 0 once, i should make input again
what i want is if i input "60", it would make loop without asking more
can you help me?

It sounds like you want it to repeat 0 to 60 and 60 to 0 until you enter a different number. To do that, end the "if (Serial.available())" before the 0 to 60 and 60 to 0 part.

void setup()
{
  pinMode(3, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(9, OUTPUT);
  Serial.begin(9600);
  Serial.println("speed 0 to 255");
}


void loop()
{
  static int speed = 0;  // 'static' means the variable will hold the value across calls to loop()


  // If there is any input, get the new value for 'speed'
  if (Serial.available()) {
    speed = Serial.parseInt();
    while (Serial.available())
      Serial.read(); // Flush any input after the number
  }
  
  if (speed >= 0 && speed <= 255) 
  {
    Serial.print("Current speed: ");
    Serial.println(speed);


    for (int i = 0; i <= speed; i += 2) 
    {
      digitalWrite(3, HIGH);
      digitalWrite(7, LOW);
      analogWrite(9, i);
      Serial.println(i);
      delay(100);
    }


    for (int i = 0; i <= speed; i += 2) 
    {
      digitalWrite(3, HIGH);
      digitalWrite(7, HIGH);
      analogWrite(9, speed - i);  // 'i' is counting up but we want the speed to count down.
      Serial.println(speed - i);  // 'i' is counting up but we want the speed to count down.
      delay(100);
    }
  }
}