Hi all, I'm new to Arduino with no coding experience. I'm slowly working through a few tutorials to learn but I am still in the beginning phases, learning very basic code. I'm using an Arduino Uno board and for the past month, I have been fighting with a piece of code that I found online, that I modified to stop, start and change the direction of a dc motor with a single button. One press should start the motor, the second press should stop the motor. when the button is pressed again, it should start the motor in the opposite direction and another press should stop it again. The code which I will paste below, starts on the first press and stops on the second press as it should, the next press starts it again but sometimes in the opposite direction as it should but sometimes in the same direction as before which tells me that I have some error where it should change direction with every second press. Can you guys have a look at it and tell me where I'm going wrong. I would like to include a schematic but the system does not allow newbies to add attachments.
int IN1pin = 7;
int IN2pin = 8;
int ENApin = 9;
int motorSpeed;
int buttonPin = 3;
int motorState;
int lastButtonState;
int currentButtonState;
void setup() {
// put your setup code here, to run once:
pinMode(IN1pin, OUTPUT);
pinMode(IN2pin, OUTPUT);
pinMode(ENApin, OUTPUT);
pinMode(buttonPin, INPUT);
currentButtonState = digitalRead(buttonPin);
}
void loop() {
// put your main code here, to run repeatedly:
lastButtonState = currentButtonState;
currentButtonState = digitalRead(buttonPin);
if (lastButtonState == HIGH && currentButtonState == LOW) {
//toggle state of motor
if (motorState == LOW) {
motorState = HIGH;
} else {
motorState = LOW;
}
//control motor according to toggled state
digitalWrite(IN1pin, motorState); //turns motor on or off, based on variable
digitalWrite(IN2pin, LOW);
analogWrite(ENApin, 255);
}
lastButtonState = currentButtonState;
currentButtonState = digitalRead(buttonPin);
if (lastButtonState == HIGH && currentButtonState == LOW) {
//toggle state of motor
if (motorState == LOW) {
motorState = HIGH;
} else {
motorState = LOW;
}
//control motor according to toggled state
digitalWrite(IN2pin, motorState); //turns motor on or off, based on variable
digitalWrite(IN1pin, LOW);
analogWrite(ENApin, 255);
}
}