I want to control the direction of a stepper motor using a push button. I would like it that when I press the push button that the stepper changes direction. The code I have written here makes the stepper complete one rotation then instantly changes direction and completes another rotation when the button is pressed.
I don't understand why it doesn't change direction as soon as I press the button.
You appear to be checking if the button is pressed/unpressed in your first if statement. This will only work for the one loop between you having the button unpushed and then pushed and vice versa. If you want it to reverse direction when you push the button (release having no effect) then you would have it instead be:
#include <Stepper.h>
int stepsPerRevolution = 2048; // number of steps for one rotation
Stepper stepper (stepsPerRevolution, 8, 9, 10, 11); //pin number for stepper
const int directionButtonPin = 6; //button to control direction
int directionButtonState;
int directionLastButtonState;
bool turnRight;
void setup()
{
pinMode(directionButtonPin, INPUT);
stepper.setSpeed(5);
}
void loop() {
directionButtonState = digitalRead(directionButtonPin);
if (directionButtonState == HIGH)
{
if (turnRight == false)
{
turnRight = true;
}else{
turnRight = false;
}
}
if (turnRight == false)
{
stepper.step (stepsPerRevolution);
}else{
stepper.step (-stepsPerRevolution);
}
}
If I remember correctly with Stepper.h, this will complete a full revolution before reversing direction. For an instant change of direction, just have it step a single step each loop (stepsPerRevolution should be changed to 1).
#include <Stepper.h>
int stepsPerRevolution = 2048; // number of steps for one rotation
Stepper stepper (stepsPerRevolution, 8, 9, 10, 11); //pin number for stepper
const int directionButtonPin = 6; //button to control direction
int directionButtonState;
int directionLastButtonState;
void setup() {
pinMode(directionButtonPin, INPUT);
stepper.setSpeed(5);
}
void loop() {
directionButtonState = digitalRead(directionButtonPin);
if (directionButtonState != directionLastButtonState) {
if (directionButtonState == HIGH) {
stepper.step (stepsPerRevolution);
}
if (directionButtonState == LOW) {
stepper.step (-stepsPerRevolution);
}
}
directionLastButtonState = directionButtonState;
}