/*
  https://www.youtube.com/@maker101io

  In this section, we add the Servo library and then define 9 servo motors as an array. 
  We specify the pin numbers to which the servo motors are connected as an array. 
  We specify the start and end positions, we also set the delay time between the loop.
*/

#include <Servo.h>

Servo servos[9];  // Define servo objects as an array

int servoPins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10};  // Define servo pin numbers as an array
int startPos = 5;  // Servo start position
int endPos = 175;  // Servo end position
int delayTime = 5;  // Delay time

void setup() {
  for (int i = 0; i < 9; i++) {
    servos[i].attach(servoPins[i]);  // Connect servo objects to pins
    servos[i].write(startPos);  // Set servo start position
    delay(10);
  }
}

/*
  There are two loops in the loop() function. In the first loop, we move the servo motors in 
  increasing order within a certain angle range. In the second loop, we move the servo motors in 
  the opposite direction in descending order in the same angle range. In the transition between the 
  two loops, we control each servo motor in turn.
*/

void loop() {
  for (int pos = startPos; pos <= endPos; pos++) {
    for (Servo &servo : servos) {
      servo.write(pos);
      delay(delayTime);
    }
  }

  for (int pos = endPos; pos >= startPos; pos--) {
    for (Servo &servo : servos) {
      servo.write(pos);
      delay(delayTime);
    }
  }
}

/*
  
  'for (Servo &servo : servos)'

  This expression uses a "range-based for loop" feature in C++. 
  This is used to traverse an array or other range.

  - 'Servo &servo:' This specifies the type of each element in the loop. 
  So in this loop, each element of the servos array is an object of type Servo.

  - ': servos:' This specifies the range to be travelled in the loop. 
  Each element of the servos array will be assigned to the variable servo in turn.

  This statement allows to navigate through the array by assigning each Servo object in 
  turn to a reference named servo. This avoids rewriting the same operations for each servo motor 
  and makes the code cleaner.
*/
