Hey guys, I'm working on a project that requires us to control the direction of a stepper motor through the use of two buttons. So far I'm able to make the motor work while either of the buttons are compressed, but I can't figure out how to get the motor to change directions. I've done a good amount of searching around here and using Google and I haven't been able to figure this out yet. Here's my code so far:
Any help you can give is appreciated.
const int button1Pin = 3; // pushbutton 1 pin
const int button2Pin = 2; // pushbutton 2 pin
const int motorPin = 9 ; // motor pin
void setup()
{
// Set up the pushbutton pins to be an input:
pinMode(button1Pin, INPUT);
pinMode(button2Pin, INPUT);
// Set up the LED pin to be an output:
pinMode(motorPin, OUTPUT);
}
void loop()
{
int button1State, button2State; // variables to hold the pushbutton states
if (((button1State == LOW) || (button2State == LOW)) // if we're pushing button 1 OR button 2
&& ! // AND we're NOT
((button1State == LOW) && (button2State == LOW))) // pushing button 1 AND button 2
// then...
{
digitalWrite(motorPin, HIGH); // FIND CODE TO REVERSE MOTOR
}
else
{
digitalWrite(motorPin, LOW); // FIND CODE TO REVERSE MOTOR in 1 of these spots
}
Radagascar:
Hey guys, I'm working on a project that requires us to control the direction of a stepper motor...
emphasis mine...
So...which is it? A DC motor, or a stepper? You might want to figure this out, and either update your title or your post - and then maybe somebody can help you...
The only code that seems to be doing anything relating to motor control is setting a single output HIGH or LOW. There's no sign that you are using any form of motor driver. What sort of motor do you actually have and how are you driving it?
if you press ONLY button1 then
send motor pin HIGH
if you press ONLY button2 then
send motor pin HIGH
if you press BOTH buttons then
send motor pin LOW
if you press NEITHER button then
send motor pin LOW
However, I'm guessing what you actually want is:
if you press ONLY button1 then
send motor pin HIGH
if you press ONLY button2 then
send motor pin LOW
if you press BOTH buttons then
do nothing
if you press NEITHER button then
do nothing
Something like this perhaps:
// if exactly ONE button is pressed then depending on which one, rotate one way or the other.
// If neither or both are pressed then do nothing
if (button1State ^ button2State) // if exactly ONE button is pressed
{
if (button1State == LOW) // if it's button1
{
digitalWrite(motorPin, HIGH);
}
else // it's button2
{
digitalWrite(motorPin, LOW);
}
}
EDIT: Or even simpler... but as the OP seems to have lost interest I'll just add it as an edit rather than resurrect the thread.
if (button1State ^ button2State)
{
digitalWrite(motorPin, button1State);
}