I am using Uno and the A4988 driver with nema17 motor and finally the Accelstepper, I want to make the motor run endlessly in a direction, but when I press a button I want it to stop and run in the other direction also endlessly until I push the button again, here is my code:

// Include the AccelStepper Library
#include <AccelStepper.h>

// Define pin connections
const int dirPin = 2;
const int stepPin = 3;
const int dirButton = 8;
int potPin = 0;

int buttonState = 0;

// Define motor interface type
#define motorInterfaceType 1

// Creates an instance
AccelStepper myStepper(motorInterfaceType, stepPin, dirPin);

void setup() {
  pinMode(dirPin, OUTPUT);
  pinMode(dirButton, INPUT_PULLUP);

void loop() {
  int speed = analogRead(potPin)/4;
  buttonState = digitalRead(dirButton);
  if(buttonState = 0){

so the question is what should i put inside the :

if(buttonState = 0){

to make it switch direction?

I tried countless examples from the internet but the motor never changes direction.


  • 1
    direction = ! direction;
    – jsotola
    Commented Jun 30, 2021 at 1:18
  • 1
    buttonState = 0 is an assignments, sets button state to zero and the expression itself evaluates to zero. So your if condition is always false. Use == for comparison.
    – Mat
    Commented Jun 30, 2021 at 5:54


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.