How do I create a state machine for my purpose?

I am new to arduino.
I have a motor which drives a sliding door back and forth. The motor is connected to an H bridge which has two control pins (direction, speed). I have a switch which is intended to activate the motor for a set amount of seconds to open it when it is switched on. When the switch is deactivated, the motor reverses for the same duration as opening.

I have written some basic code using the 'if' argument, but my issue is that the code under the 'if' argument loops infinitely. Looking online I saw that a state machine may be my solution, but my lack of expertise with coding means I cannot create a state machine. This is my code:

const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

pinMode(hbridge1, OUTPUT);
pinMode(hbridge2, OUTPUT);
pinMode(Switch, INPUT_PULLUP);

Serial.begin(9600);
}

void loop() {
int buttonState = digitalRead(Switch);
Serial.println(buttonState);

if (buttonState == HIGH) {
digitalWrite(hbridge1, HIGH);
digitalWrite(hbridge2, LOW);
delay(4000);
digitalWrite(hbridge1, LOW);
digitalWrite(hbridge2, LOW); //I only need the motor to activate for four seconds, but 'if' loops it infinitely
} else {
digitalWrite(hbridge1, LOW);
digitalWrite(hbridge2, HIGH);
delay(4000);
digitalWrite(hbridge1, LOW);
digitalWrite(hbridge2, LOW); //Same issue here
}

;
delay(1);
}

Your if statement is invoked repeatedly because the loop function is called repeatedly - by design. A state machine could help, but is not necessary for this fairly simple case.

Your problem is that you are checking whether button state is high or low. You need to check whether it has just become high or low. Look at the StateChangeDetection example that comes with the IDE.

wildbill:
Your if statement is invoked repeatedly because the loop function is called repeatedly - by design. A state machine could help, but is not necessary for this fairly simple case.

Your problem is that you are checking whether button state is high or low. You need to check whether it has just become high or low. Look at the StateChangeDetection example that comes with the IDE.

Absolutely.

Also check out Blink Without Delay.
As your program is written right now, you won't be able to stop your door, or reverse it, until your delay is finished.

Start creating the state machine by listing the states that the system can be in

Perhaps

DOOR_CLOSED
DOOR_OPENING
DOOR_OPEN
DOOR CLOSING

Add a description of what causes each state to change and what the next state will be

DOOR_CLOSED until button becomes pressed then move to DOOR_OPENING
etc

Complete that list and come back for more advice