I have a single servo that is being moved by code without issues. I want to expand my system to move 1 of 3 servos randomly. I don't understand the syntax to use a variable to determine which servo to move
first I declared the servo objects
Servo myservo1; //Crete object to ctrl first servo
Servo myservo2; //Crete object to ctrl second servo
Servo myservo3; //Crete object to ctrl third servo
int activeServo = random(1, 4); //randomize next servo to move
myservo1.write(90); //move the servo
and the single servo will move without issue.
how do i write the servo write command to use the active servo variable?
myservo+activeServo.write(90); //This does not work but illustrates what i am trying to do.
I realize I could use a Switch Case or series of If statements but i want the system to be expandable to many more servos
It sounds like you need an array of servos.
Take what you need from this example
//sweep 2 servos at different speeds
//servo details are held in an array
#include <Servo.h>
Servo servo[2]; //array of servos
const byte servo_pin[] = {11 , 12}; //pins for servos
unsigned long servoDelay[] = {100, 80}; //delays between moving
unsigned long servoPrevTime[] = {0, 0}; //times of previous moves
int servoStep[] = {1, 2}; //step values
int servoPos[] = {90, 90}; //start positions
void setup()
{
for (int i = 0; i < 2; i++)
{
servo[i].attach(servo_pin[i]);
}
}
void loop()
{
for (int currentServo = 0; currentServo < 2; currentServo++)
{
if ((millis() - servoPrevTime[currentServo]) > servoDelay[currentServo])
{
servoPos[currentServo] += servoStep[currentServo];
if (servoPos[currentServo] > 180)
{
servoPos[currentServo] = 180;
servoStep[currentServo] = servoStep[currentServo] * -1;
}
else if (servoPos[currentServo] < 0)
{
servoPos[currentServo] = 0;
servoStep[currentServo] = servoStep[currentServo] * -1;
}
servo[currentServo].write(servoPos[currentServo]);
servoPrevTime[currentServo] = millis();
}
}
}