Inserting a variable for 'Servo.write'

I'm using the 'Servo.h' library to control multiple servos (for model railway signals). I've declared the servos as 'Servo Sig1' (then 2, 3 &4) and attached them to the relevant pins.

However, in the code when I want to write to a specific servo, I need the servo to be inserted as a variable dependent upon a button pressed.

i.e.
Sig1.write(angle) //where 'angle' is a variable

My problem is that if I try to insert the variable for the 'Sig1', I get an error. For example:

Sig(sigNo).write(angle)

How should I write this to allow me to insert any one of 4 servos (Sig1, Sig2, Sig3 or Sig4) without causing an error?

Use an array of Servo objects then you can refer to them by number like this

#include <Servo.h>

Servo servos[3];
const byte servoPins[] = {10, 11, 12};

void setup()
{
  Serial.begin(115200);
  for (int s = 0 ; s < 3; s++)
  {
    servos[s].attach(servoPins[s]);
  }
  servos[0].write(180);
  servos[1].write(90);
  servos[2].write(0);
}

void loop()
{
}

Use an array:
`Servo Sig[4];'

Then use Sig[0] in place of Sig1, Sig[1] in place of Sig2, Sig[2] in place of Sig3 and Sig[3] in place of Sig4. The number in the square brackets can be a variable.

Thanks very much - I can see how that would work so will give it a try.

Thank you very much - so simple really! I'll give it a whirl and update with the result.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.