I'm trying to make a single button activate 2 servos (moving each of them from position "0" to "90" and then staying). Then when the button is pushed, moving them from "90" to "0" and rinsing and repeating for each button press.
I have my project up and running as follows: Pull down resistor on the button, software debounce function, 2 tower hobby servo motors (not continuous)
Here is my working (somewhat) code:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
Servo myservo2; // create 2nd servo object to control a 2nd servo
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
// Variables will change:
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
int buttonPushCounter = 0; // counter for the number of button presses
boolean currentButton = LOW;
void setup() {
// attach the Servo to pins
myservo.attach(9);
myservo2.attach(10);
// tell servo to go to position in variable 'pos'
myservo.write(0);
myservo2.write(0);
delay(15);
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
}
boolean debounce(boolean last)
{
boolean current = digitalRead(buttonPin);
if (last != current)
{
delay(5);
current = digitalRead(buttonPin);
}
return current;
}
void loop() {
// read the pushbutton input pin:
buttonState = debounce(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// went from off to on:
buttonPushCounter++;
}
else {
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}
// moves the servo every other button push by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 2 == 0) {
//move to position 90
myservo.write(90);
myservo2.write(90);
delay(15);
} else {
//OR: move back to position 0
myservo.write(0);
myservo2.write(0);
delay(15);
}
}
Everything works as I had hoped except one servo keeps making a little noise after each move. It just vibrates quietly for a second or two and then usually stops.
Anyone have any clue why this is happening based on my code?
Also, does anyone see anything that can be cleaned up in the code or made better? Thank you,
I appreciate all the help I can get as I am completely new to both Arduino and coding.
Thanks,
Chris