Hello, I am looking for help on a project I'm working on. I want to be able to rotate a motor in the clockwise and counterclockwise directions with one AbleNet push button. The idea is that if the button is pressed it moves in the clockwise direction, and if pressed again it moves in the counterclockwise direction. If pressed a third time it again moves in the clockwise direction, and so on. The button is designed to be a momentary switch, so the motor only moves for as long as the button is pressed.
My current approach is to track the motor state as a boolean (either true or false), if it is true it moves clockwise and if false it moves counterclockwise. Then at the end of the code that boolean state is switch (if it was true it is now false).
Full disclosure, I am super new to coding in Arduino, and coding in general, so I do expect my code to be pretty buggy! The circuit has the button connected to the Arduino, which is connected to an H-bridge driver to control the direction of the motor.
Thank you for your help!
const int MotorButton= 8; //Button is connected to pin 8
bool MotorDirection = true; //MotorDirection Starts as true
int MotorPin1= 6; //Driver connected to pin 6
int MotorPin2= 7; //Driver connected to pin 7
void setup(){
Serial.begin(9600);
pinMode(MotorButton, INPUT_PULLUP); //set MotorButton as input
pinMode(MotorPin1, OUTPUT); //set MotorPin1 as output
pinMode(MotorPin2, OUTPUT); //set MotorPin2 as output
}
void loop(){
int ButtonState = digitalRead(MotorButton); //read state of button
bool NewMotorDirection = MotorDirection; //set new direction to old direction
if (ButtonState == LOW){ //if button presed
if (NewMotorDirection == true){ // if New motor direction is true
digitalWrite(MotorPin1, LOW); //set one pin to low
digitalWrite(MotorPin2, HIGH); //set other to high
}
else if (NewMotorDirection == false){ //if New motor direction is false
digitalWrite(MotorPin1, HIGH); //set one pin to hight
digitalWrite(MotorPin2, LOW); //set other to low
}
}
MotorDirection = !NewMotorDirection;//now change old motor direction to opposite of new motor direction
}