Multiple servos, only one responding

Hi there, I’m attempting to control 5 x SG90 servos with the following test code:

Servo myservo0;
Servo myservo1;
Servo myservo2;
Servo myservo3;
Servo myservo4;

void setup() {


}

void loop() {
    
myservo0.attach(A0); myservo0.write(0); delay(1000); myservo0.detach();
myservo1.attach(A1); myservo1.write(0); delay(1000); myservo1.detach();
myservo2.attach(A2); myservo2.write(0); delay(1000); myservo2.detach();
myservo3.attach(A3); myservo3.write(0); delay(1000); myservo3.detach();
myservo4.attach(A4); myservo4.write(0); delay(1000); myservo4.detach();

myservo0.attach(A0); myservo0.write(180); delay(1000); myservo0.detach();
myservo1.attach(A1); myservo1.write(180); delay(1000); myservo1.detach();
myservo2.attach(A2); myservo2.write(180); delay(1000); myservo2.detach();
myservo3.attach(A3); myservo3.write(180); delay(1000); myservo3.detach();
myservo4.attach(A4); myservo4.write(180); delay(1000); myservo4.detach();


delay(5000);

}

The problem I have is that only one servo ever responds (the last in series on pin A4). I’m guessing I’m missing something fundamental here but my searches are coming up empty.

Thank you.

What device are you running that on?
Are all your pins PWM enabled?

By your symptom description I suspect you are using a Photon or Electron for which the docs tell us this
https://docs.particle.io/reference/device-os/firmware/photon/#attach-

The reference docs should be the first place to search answers to such “issues” :wink:

1 Like

I’d recommend following @ScruffR’s advice to use PWM compatible pins. Calling the attach() and detach() methods repetitively isn’t necessary.

Also, here’s some more code to iterate over the servos:

#include "Particle.h"

SYSTEM_MODE(SEMI_AUTOMATIC);
SYSTEM_THREAD(ENABLED);

// Servo array and pins array
Servo servos[5];
uint16_t pins[5] = {A0, A1, A2, A4, A5};

void setup() {
  // Attach all servos
  for (int i = 0; i < 5; ++i) {
    servos[i].attach(pins[i]);
  }
}

void loop() {
  // Set all servos to 0
  for (Servo s : servos) {
    s.write(0);
    delay(1s);
  }

  // Set all servos to 180
  for (Servo s : servos) {
    s.write(180);
    delay(1s);
  }
}
1 Like

Thank you, on a Photon so was using incorrect pins. Thanks.

1 Like