Hello! I need help toggling a stepper motor on button press. I used the tutorial for LED toggle and just replaced some of the code with a stepper motor code, but when I press the button a second time to turn it off, it doesn't do anything. Here is the code:
// constants won't change
const int BUTTON_PIN = 7; // Arduino pin connected to button's pin
// variables will change:
int ledState = LOW; // the current state of LED
int lastButtonState; // the previous state of button
int currentButtonState; // the current state of button
#include <Stepper.h>
const float STEPS_PER_REV = 32;
const float GEAR_RED = 64;
const float STEPS_PER_OUT_REV = STEPS_PER_REV * GEAR_RED;
int StepsRequired = 500;
Stepper steppermotor(STEPS_PER_REV, 8, 10, 9, 11);
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
currentButtonState = digitalRead(BUTTON_PIN);
}
void loop() {
lastButtonState = currentButtonState; // save the last state
currentButtonState = digitalRead(BUTTON_PIN); // read new state
if(lastButtonState == LOW & currentButtonState == HIGH) {
Serial.println("The button is pressed");
steppermotor.setSpeed(100);
steppermotor.step(StepsRequired);
}
}
By declaring button pin as INPUT_PULLUP, it will read HIGH when not depressed. You current have it where if the button is pressed, then released it will trigger. Kinda beside your issue, but swapping LOW to current state & HIGH to last state will act upon button press, not release.
If you want it on when it's pressed and currently off, and vise versa, I find it easier to have a run variable and toggle it back and forth, more versatility. Also, may want to look into ISR's(Interrupt Service Routine) which is a better way to do this, so you dont have to constantly check a condition in your code.
Now, id recommend doing it like this:
bool runCondition;
if (lastButtonState == HIGH && currentButtonState == LOW) //If previously the button was not pressed, and is now pressed
{
Serial.println("The button is pressed");
runCondition = !runCondition;
}
if (runCondition == true)
{
//stepper code
}
if (lastButtonState == HIGH && currentButtonState == LOW) //If previously the button was not pressed, and is now pressed
{
Serial.println("The button is pressed");
runCondition = !runCondition;
}
if (runCondition == true)
{
//stepper code
}