the ol' servo button move, pause, move back issue

Long, long time lurker and I have learned so much from everyone but I'm a total and abject noob working on his first servo project. I'm trying to get a servo to move to X position when a button is pressed...hold position for 5 seconds and move back to start position. Would someone (or several) like to provide some help in debugging my code and/or pointing me to other threads? Not looking for a handout here.

#include <Servo.h>

const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;

void setup() {
servoOne.attach(9);
servoOne.write(directionState);
pinMode(buttonPin, INPUT);
}

void loop() {
buttonState = digitalRead(buttonPin);
if (directionState == 0) {
if (buttonState == HIGH) {
directionState = 1;
for (pos = 0; pos < 180; pos = pos + 1) {
servoOne.write(pos);
delay(5);
}
}
} else if (directionState == 1) {
delay(5000) {
directionState = 0;
for (pos = 180; pos > 1; pos = pos - 1) {
servoOne.write(pos);
delay(5);
}
}
}
}

What does it do?

As a self proclaimed "long time lurker", you should already be aware of the importance of the use of code tags.

delay(5000) { <---- oops!

  if (directionState == 0) {

if (buttonState == HIGH) {
      //...
  } else if (directionState == 1) {

Of course it's going to be 1 in the else. Why do you even check it the second time?

Read: http://www.thebox.myzen.co.uk/Tutorial/State_Machine.html

Why do you even need 'directionState'?

Isn't your requirement just
if button pressed
move servo one way
wait 5 seconds
move servo other way

back to top of loop to read button again?

When you have a fixed sequence like that you don't need to confuse yourself with states.

Steve

I think you code can be simplified like below by using this library.

#include <ezButton.h>
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
ezButton button(7);  // create Button object that attach to pin 7;

int pos_start = 0;
int pos_end = 180;

void setup() {
  button.setDebounceTime(50); // set debounce time to 50 milliseconds
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  button.loop(); // MUST call the loop() function first

  if(button.isPressed()){
    myservo.write(pos_end);
    delay(5000); // hold position for 5 seconds
    myservo.write(pos_start);
  }
}