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