MG90S Servo Motor Rotation

Hello, I'm using arduino nano and I wish to have a push button that when it is pressed at the first time, it will rotate 90 degrees. And for the 2nd time, it will go back to 0 degrees. I'm having trouble with this.

#include <Servo.h>
int servoPin = 3;
int button = 4;
int buttonread = 0;
int status = 0;
Servo Servo1;
void setup() {
Servo1.attach(servoPin);
pinMode(button, INPUT);
}
void loop{
buttonread = digitalRead(button);
if(buttonread != 0){
if(status == 0){
rotate();
delay(500);
}else{
rotate1();
delay(500);
}
}
void rotate(){
Servo1.attach(servoPin);
Servo1.write(90);
delay(500);
Servo1.detach();
status = 90;
delay(1000);
}
void rotate1(){
Servo1.attach(servoPin);
Servo1.write(0);
delay(500);
Servo1.detach();
status = 0;
delay(1000);
}

"I'm having trouble" is not really a very useful problem report. What does it do or not do?

It's conventional to test the result of a digitalRead against LOW or HIGH rather than "!=0". And it's pointless to keep continuously attaching and detaching the servo. But who knows if either of those have anything to do with whatever the trouble is?

Details of how the servo is powered and how the button is wired might also help.

Steve

There is three issue in your code:

  1. You MUST use pull-up for the button => See Arduino Button Pull-up
  2. You SHOULD detect button pressed and released => See Arduino Detect Button Press and Released
  3. You MUST NOT use delay when reading the button => See Avoid using delay function