Hello all, the project I am working on is to press a button, and have a motor spin until it hits a limit switch and stops. Then, when the button is pressed again, the motor spins in the opposite direction until it hits the other limit switch. The code below works for these purposes, but the only issue seems to be that when a limit switch is pressed, I cannot start the motor back up with the button until that limit switch is released. In the real world however, the motor will be resting on the limit switch until activated again.
I am using an Arduino Uno R3 and a L298N motor driver.
I am very new to Arduino, so any help is appreciated. Below is also a wiring diagram for my set up, which could also be a part of the problem. Thank you in advance!
int motorAenablePin = 6; // Motor A, PWM-Pin
int motorAfwdPin = 7; // Motor A, control line 1
int motorArevPin = 2; // Motor A, control line 2
boolean motorRun = false;
char motorDirection = 'F';
int controlButtonPin = 8;
int controlButtonState = 0;
int buttonPushCounter = 0; // counter for the number of button presses
int lastControlButtonState = 0; // previous state of the button
int rightLimitSwitchPin = 9;
int leftLimitSwitchPin = 10;
int rightLimitswitchState = 0;
int leftLimitswitchState = 0;
void setup() {
Serial.begin(9600);
pinMode(motorAenablePin, OUTPUT);
pinMode (motorAfwdPin, OUTPUT);
pinMode (motorArevPin, OUTPUT);
digitalWrite(motorAenablePin, HIGH);
pinMode(controlButtonPin,INPUT);
pinMode(rightLimitSwitchPin,INPUT);
pinMode(leftLimitSwitchPin,INPUT);
}
//=========
void loop() {
readSwitches();
updateMotorControl();
moveMotor();
}
//=========
void readSwitches() {
rightLimitswitchState = digitalRead(rightLimitSwitchPin);
leftLimitswitchState = digitalRead(leftLimitSwitchPin);
controlButtonState = digitalRead(controlButtonPin);
buttonPushCounter = 0;
if (controlButtonState != lastControlButtonState) {
lastControlButtonState = controlButtonState;
if (controlButtonState == 1) {
buttonPushCounter = 1;
Serial.println("on");
}
}
}
//===========
void updateMotorControl() {
if (rightLimitswitchState == HIGH) {
motorRun = false;
motorDirection = 'F';
}
if (leftLimitswitchState == HIGH) {
motorRun = false;
motorDirection = 'R';
}
if (buttonPushCounter == 1) {
motorRun = true;
}
}
//===========
void moveMotor() {
if (motorRun == true) {
if (motorDirection == 'F') {
digitalWrite(motorArevPin, LOW); // write LOW before HIGH
digitalWrite(motorAfwdPin, HIGH);
}
else {
digitalWrite(motorAfwdPin, LOW);
digitalWrite(motorArevPin, HIGH);
}
}
else {
digitalWrite(motorAfwdPin, LOW);
digitalWrite(motorArevPin, LOW);
}
}