I am trying to make my servo motor rotate 90 degrees and then back to its original position when I push a button. The problem is that when I push the button, I have to push it again for it to move back to its original position. Any help is much appreciated!
#include <Servo.h>
Servo myServo;
const int switchPin = 8;
int buttonState = 0;
int lastButtonState = 0;
int buttonPushCounter = 0;
void setup() {
// put your setup code here, to run once:
myServo.attach(4);
myServo.write(0);
Serial.begin(9600);
}
void push(){
myServo.write(90);
delay(250);
myServo.write(-90);
}
void loop() {
// put your main code here, to run repeatedly:
buttonState = digitalRead(switchPin);
// 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++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
// if the current state is LOW then the button went from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
// turns on the LED every four button pushes 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) {
push();
}
}