Multiple for loops executing at the same time.

Greetings to everyone! :slight_smile:

How can I execute 2 dual for loops at the same time? Basically I want Servo 1 and Servo 2 to function at the same time. My current problem is The Servo 1 will execute 1st and then Servo 2 will follow. I hope anyone can get my problem. Here's the code:

Thank you in Advance. :slight_smile:

#include <Servo.h>

Servo myservo1; // 20 degrees initial value
Servo myservo2; // 180 degrees initial value
// twelve servo objects can be created on most boards

int pos, pos1;    // variable to store the servo position

void setup() {
  myservo1.attach(9); 
  myservo2.attach(8);
}

void loop() {
  // Servo 1
  for (pos = 20; pos <= 90; pos++) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo1.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 90; pos >= 20; pos--) { // goes from 180 degrees to 0 degrees
    myservo1.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  
  //Servo 2
  for (pos1 = 180; pos >= 110; pos--) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo2.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos1 = 110; pos <= 180; pos++) { // goes from 180 degrees to 0 degrees
    myservo2.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Hello, no it's not possible to run multiple for loops at the same time. However, if you understand that loop() is basically an infinite for loop, and that you can replace your finite for loops with if statements and some variables, then you will be able to do what you want.

Read the directions on how to use the servo library more closely, the answer is right there.