I would like to use a pushbutton to make two servos rotate.
~ Ideally after pressing the push button once, the two Arduinos would rotate 180 degrees from their starting point (Servo 1 rotating in one direction and Servo 2 rotating in the opposite direction), and then both servos would stop once that rotation is complete.
~ And then after pressing the push button once more, the servos would rotate (in opposing directions from one another) back to their original position.
This code below successfully prompts two servos to rotate in opposite directions, however after hours of attempting to integrate a pushbutton into the code, I couldn't get the code to successfully compile or upload to my Arduino Uno. I would like to modify the code so that it allows me to control the servos with the push button, in the way I mentioned above.
#include <Servo.h>
#include <mechButton.h>
#define SERVO1_PIN 3
#define SERVO2_PIN 9
#define BTN_PIN 2
Servo servo1; // A servo object.
Servo servo2; // The other servo object.
mechButton ourButton(BTN_PIN); // A denbounced button object.
bool pointOut; // A boolean for saving servo state.
void setup(void) {
servo1.attach(SERVO1_PIN); // Standard servo attach.
servo2.attach(SERVO2_PIN); // Attach the other one.
ourButton.setCallback(btnClicked); // Set the callback for the button.
pointOut = true; // We'll default the servo to false.
servo1.write(180); // And send them to that state.
servo2.write(0); // This one as well.
}
// When the button changes state, it calls this.
void btnClicked(void) {
if (!ourButton.trueFalse()) { // If the button is false (grounded)..
if (pointOut) { // If pointOut is false..
servo1.write(0); // Servo one moves to 0 deg.
servo2.write(180); // Servo two moves to 180 deg.
} else { // else, pointOut is true..
servo1.write(180); // Servo one moves to 180 deg.
servo2.write(0); // Servo two moves to 0 deg.
}
pointOut = !pointOut; // Flip our boolean for the next press.
}
}
void loop(void) {
idle(); // Idle runs stuff in the background, like the button code.
}
You will need to install LC_baseTools to get this to compile. (Tools menu ==>> Manage Lirbraries..) Search for LC_baseTools.