Servo with a button

Hey im doing a project in class. We are going to manually spin the motor some degrees and then whenever the button is released the servo will move back to the 0 position. I am new to arduino and im not sure why this code is not working.

Servo myservo; // create servo object to control a servo

int pos = 0; // variable to store the servo position
int button1 = 4; //button pin, connect to ground to move servo
int press1 = 0;

void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(button1, INPUT);
digitalWrite(4, HIGH); //enable pullups to make pin high
}

void loop() {
press1 = digitalRead(button1);
if (press1 == HIGH)
{
for (pos >0; pos >= 0; pos -=1)
{
myservo.write(pos);
delay(5);
}
}
}

int button1 = 4; //button pin, connect to ground to move servo
if(press1 == HIGH)

Those two lines are contradictory.

for (pos >0; pos >= 0; pos -=1)

Is not right. See. https://www.arduino.cc/en/Reference/For

I don't see anything wrong with:
int button1 = 4; //button pin, connect to ground to move servo
and
if(press1 == HIGH)

except your diagram shows the button on D2 and not D4.
Usually if one uses the internal pullup, the button would be wired to connect the pin to Gnd when pressed, and a LOW would be tested for.

You should probably change this
for (pos >0; pos >= 0; pos -=1)
to
for (pos =180; pos >= 0; pos -=1)
as most servos only move from 0 to 180 degrees.

5mS may not be enough time to get to 180 initially.
The Uno may also not have enough current available to drive the servo.

Hi,
You have to realise that you have two output states, 0deg and 90deg.
So you need to code both output conditions, look up if ..else statement.
You don't need to use a for loop to move the servo.

myservo.write(0);
myservo.write(90);

Will do, unless you want to slowly move the servo arm.

Tom... :slight_smile: