Running 1 Servo After Another

For a project, I want to have a situation where 1 servo moves when a rotary encoder is turned in one direction, and then another separate servo moves after the first. I have managed to do this fine, but cannot get the second servo to stop moving? If I introduce a “servo.detach();” in to my code, the second servo does not move at all. Here’s my code -

servo 1 is moving an arrow
servo 2 is moving an expired sign

#include <Encoder.h>
#include <Servo.h>

Servo servoarrow; //servo for arrow
Servo servoexpired; //servo for “expired” sign

Encoder myEnc(5, 6);

void setup() {
servoarrow.attach(10); // attaches the servo on pin 9 to the servo object
servoarrow.write(0);

Serial.begin(9600);
Serial.println(“Basic Encoder Test:”);
pinMode(13, OUTPUT);
}

long oldPosition = -999;

void loop() {
long newPosition = myEnc.read();
if(newPosition>oldPosition){

Serial.println(newPosition);
servoarrow.write(0);
for(int i=300;i>-1;i–){
servoarrow.write(i);
delay(10);
digitalWrite(13, HIGH);
}

oldPosition = newPosition;

Serial.println(newPosition);

}
else{
oldPosition = newPosition;
servoexpired.write(0);
for(int i=100;i>-1;i–){
servoarrow.detach();
servoexpired.attach(9);
servoexpired.write(i);
delay(10);
digitalWrite(13, LOW);
servoexpired.detach();
Serial.println(newPosition);
}
}

}

Thanks, I couldn't work out how to get the code like that! Thank you.

Thanks, I couldn't work out how to get the code like that! Thank you.

Read the directions for using the forum.

jc_282:
I have managed to do this fine, but cannot get the second servo to stop moving?

If I understand your requirement correctly the logic of your program is wrong.

I believe you want the second servo to move after the movement of the first servo completes.

The way it is programmed now the second servo moves if the encoder is not moved or if the encoder is rotated backwards (to a lower position).

The code to move the second servo should follow the code for the first servo within the same IF clause.

And if I have mis-interpreted the requirement please explain it more clearly.

...R

Robin2:
If I understand your requirement correctly the logic of your program is wrong.

I believe you want the second servo to move after the movement of the first servo completes.

The way it is programmed now the second servo moves if the encoder is not moved or if the encoder is rotated backwards (to a lower position).

The code to move the second servo should follow the code for the first servo within the same IF clause.

And if I have mis-interpreted the requirement please explain it more clearly.

...R

Thanks Robin, I will try that one! It doesn't help that I've got a dodgy encoder, but what you say makes sense. Fingers crossed that works. Thank you :slight_smile: