How to make two servo motors go opposite direction

Hello, I need help with how to make two servos go in the opposite directions with one button. So far, this sketch below only makes two servos go in the same direction. Please let me know how you guys can fix this or any suggestions. Thanks.


#include <Servo.h>
#include <ezButton.h>

// constants won't change
const int BUTTON_PIN = 7; // Arduino pin connected to button's pin
const int SERVO_PIN1 = 9; // Arduino pin connected to servo motor's pin
const int SERVO_PIN2 = 8; // Arduino pin connected to servo motor's pin

ezButton button(BUTTON_PIN); // create ezButton object that attach to pin 7;
Servo Myservo1; // create servo object to control a servo
Servo Myservo2; // create servo object to control a servo

int angle = 0; // the current angle of servo motor or the original angle at zero

void setup() {
Serial.begin(9600); // initialize serial
button.setDebounceTime(20); // set debounce time to 20 milliseconds
Myservo1.attach(SERVO_PIN1); // attaches the servo on pin 9 to the servo object
Myservo2.attach(SERVO_PIN2); // attaches the servo on pin 8 to the servo object

}

void loop() {
button.loop(); // MUST call the loop() function first

if(button.isPressed()) {
Serial.println("The button is pressed");
if(angle == 0)
angle = 35;
else
if(angle == 35)
angle = 0;

Myservo1.write(angle);
Myservo2.write(angle);
}
}

That ensures that both servos move together. Why would you think otherwise? The variable angle is being sent to both servos.

The code preceding this makes little sense either.

You need two variables like angle1 and angle2 and set them to different values
This will toggle between the two angles you want.

if( angle1 == 0) {
 angle1 = 35;
 angle2 = 0;
}
else {
angle1 = 0;
angle2 = 35;
}

Now send each angle to a different servo.

Then you need a delay to give the servos chance to get to where they are going before your loop function repeats and sends them back.

1 Like

Set the servos to rest normally at 90°

Make 1 servo go 90° + angle.
Make 2 servo go 90° - angle.

Adjust the above as needed.

This might do what you want:

Myservo1.write(angle);
Myservo2.write(35 - angle);

@Grumpy_Mike Thank you so much for your help! It works better as expected! At first, I thought there is something wrong with both servos show some flicking and jerking after I uploaded the code to Arduino nano. I realized it's the power source that shows weak and not enough to generate power so I connected it to the portable power bank. It works really well! Thanks again for your help! You are AWESOME!

@johnwasser Thank you for your time to help out. Your suggestion didn't work. I tried that. However, I found the solution that solve the issue. Thanks again!

@LarryD, thank you for your time to help out. I have tried your suggestion and it didn't work. However, I found the solution that solves the issue. Thanks again!