Hey all,
Been kicking around a project for a while and couldn't find a solution but here it is.
My problem was that I was trying to operate 2 servos from one push button and have them move in opposite directions.
If this has been posted elsewhere, my bad.
Here is my code. Tested and working..
[code]
/*
* Code (Partly) by Greg TEdford with help from many others.
* 19th October 2020..
*/
/* pushbutton attached to pin 2 from +5V
10K resistor attached to pin 2 from ground
servoLeft attached to pin 9
servoLeft moves from 0 to 50 on first push of button
servoLeft moves back to zero on second push.
servoRight attached to pin 10
servoRight moves from 0 to -50 on first push
servoRight moves from -50 to 0 on second push
*/
#include <Servo.h>
Servo myservoRight;
Servo myservoLeft;
int posL = 0;
int posR = 0;
byte switchPin = 2; // switch is connected to pin 2
byte buttonPresses = 0; // how many times the button has been pressed
byte lastPressCount = 0; // to keep track of last press count
void setup() {
myservoLeft.attach(9);
myservoLeft.write(0);
myservoRight.attach(10);
myservoRight.write(180);
pinMode(switchPin, INPUT); // Set the switch pin as input
digitalWrite(switchPin, LOW); // set pullup resistor
Serial.begin(9600); // Set up serial communication at 9600bps
}
void loop(){
if (digitalRead(switchPin) == HIGH) // check if button was pressed
{
buttonPresses++; // increment buttonPresses count
delay(500); // debounce switch
if (buttonPresses > 2){
buttonPresses = 1;
}
Serial.print ("Button press count = "); // out to serial
Serial.println(buttonPresses, DEC);
if (lastPressCount != buttonPresses) // only do output if the count has changed
{
if (buttonPresses == 1){
for (posL = 0; posL <= 50; posL += 1)
myservoLeft.write(posL);
delay(15);
for (posR = 0; posR <= 80; posR +=1)
myservoRight.write(180-posR);
delay(15);
}
if (buttonPresses == 2){
for (posL = 50; posL >= 0; posL -= 1)
myservoLeft.write(posL);
delay(15);
for (posR = 80; posR >= 0; posR -= 1)
myservoRight.write(180-posR);
delay(15);
} } }
lastPressCount = buttonPresses; // track last press count
}
[/code]
Hope this helps others.
The 80 in the code was to get the arms to match movement. Feel free to modify this figure to match your needs.
Hasta la vista baby....