1

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);
  myStepper.setMaxSpeed(500);
  Serial.begin(9600);
}

void loop() {
  int speed = analogRead(potPin)/4;
  myStepper.setSpeed(speed);
  digitalWrite(dirPin,LOW);
  buttonState = digitalRead(dirButton);
  
  if(buttonState = 0){
    
  }
  
  Serial.print(buttonState);
  delay(5);
  myStepper.run();
}

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.

thanks

2
  • 1
    direction = ! direction;
    – jsotola
    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
    Jun 30, 2021 at 5:54

0

Your Answer

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

Browse other questions tagged or ask your own question.