How to make a servo motor rotate 90 degrees then back to its original position

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();
    }
    
  } 



Servo.write() takes values from 0 to 180.

1 Like

Servo position is not relative to its current positon, but an absolute position determined by the feedback potentiometer inside the servo. 90 degrees will always place the servo in the same rotational position, regardless of its previous position.

1 Like

So try changing write(-90) to write(0). Does that do what you want?

Steve

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.