gin66 / FastAccelStepper

A high speed stepper library for Atmega 168/328p (nano), Atmega32u4, Atmega 2560, ESP32, ESP32S2, ESP32S3, ESP32C3 and Atmel SAM Due
MIT License
282 stars 67 forks source link

Issue with stepper direction when using serial #233

Closed maarufvazifdar closed 4 months ago

maarufvazifdar commented 4 months ago

Hey, I'm trying to control a stepper over USB serial commands, and the rotation direction is not changing. Here's my code:

#include <Arduino.h>
#include "FastAccelStepper.h"

#define led_pin 2

// top_stepper
#define enablePin0 23
#define stepPin0 22
#define dirPin0 1

FastAccelStepperEngine engine = FastAccelStepperEngine();
FastAccelStepper *top_stepper = NULL;

void setup() {
  engine.init();
  top_stepper = engine.stepperConnectToPin(stepPin0);

  if (top_stepper) {
    top_stepper->setDirectionPin(dirPin0);
    top_stepper->setEnablePin(enablePin0);
    top_stepper->setAutoEnable(true);
    top_stepper->setDelayToDisable(2000);  // Disable motor after 2 sec delay

    top_stepper->setSpeedInHz(500);
    top_stepper->setAcceleration(1000);
  }

  Serial.begin(9600);
  pinMode(led_pin, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    String command = Serial.readStringUntil('\n');
    if (command == "1") {
      digitalWrite(led_pin, HIGH);
      Serial.println("Rotate Clockwise");
      top_stepper->move(200);
      delay(1000);
    } else if (command == "0") {
      digitalWrite(led_pin, LOW);
      Serial.println("Rotate Counter-clockwise");
      top_stepper->move(-200);
      delay(1000);
    } 
  }
}

I tried simply moving the motor back and forth with

void loop() {
  top_stepper->move(200);
  delay(1000);
  top_stepper->move(-200);
  delay(1000);
}

and this works, and the motor spins 1 rotation in both directions, but whenever I add Serial.begin(9600); to the setup() it doesn't turn in backward direction.

Any ideas and suggestions to solve this issue are greatly appreciated.

gin66 commented 4 months ago

Pin 0 and 1 are normally used for Serial. So change the direction pin to another one.

maarufvazifdar commented 4 months ago

@gin66 Thanks for the quick reply. This was the issue; I was using GPIO 1/3 (TX0 and RX0) that are used for the UART-USB bridge.