// https://forum.arduino.cc/t/motor-reverse-ideas/1457053/56
const int IN1pin = 8;
const int IN2pin = 7;
const int ENApin = 9;
const int forwardSwPin = 2;
const int reverseSwPin = 3;
int PIN, PWM; // temporary motor PWM and switch pin
bool direction, IN1, IN2; // direction and motor states
void setup() {
pinMode(IN1pin, OUTPUT);
pinMode(IN2pin, OUTPUT);
pinMode(ENApin, OUTPUT);
pinMode(forwardSwPin, INPUT_PULLUP);
pinMode(reverseSwPin, INPUT_PULLUP);
}
void loop() {
if (direction == 0) { // forward direction parameters
IN1 = HIGH;
IN2 = LOW;
PWM = 255;
PIN = forwardSwPin;
} else { // reverse direction parameters
IN1 = LOW;
IN2 = HIGH;
PWM = 191;
PIN = reverseSwPin;
}
move(IN1, IN2, PWM); // move motor
checklimit(PIN); // monitor limit switch
move(LOW, LOW, 0); // STOP motor
delay(3000); // pause
direction = !direction; // change direction
}
void move(bool in1, bool in2, int ena) {
digitalWrite(IN1pin, in1);
digitalWrite(IN2pin, in2);
analogWrite(ENApin, ena);
}
void checklimit(int pin) {
bool pinstate = digitalRead(pin); // read switch state
while (pinstate == HIGH) // while RELEASED...
pinstate = digitalRead(pin); // ... read switch state
}FRONT
SWITCH
REAR
SWITCH
IN1
ENA
IN2