Stepper motor only rotates in one direction

Hello, I need help as my stepper motor would not change directions and rotate the other way. I am trying to connect it to a microswitch and have it home itself but it is not getting the microswitch reading and it is also only rotating in one direction, I have tried various more simplified codes just to get it to rotate the opposite direction but noting is working.
I am using stepper NEMA 23,stepper driver DM542T, and Arduino Uno, and accelstep library.

I will attach my code and wiring diagram, please help.

#include <AccelStepper.h>
#include <math.h>
#define DirectionPin 9
#define PulsePin 8
#define switchPIN 10

AccelStepper stepper1(1, PulsePin, DirectionPin);

int maxSp = 1000; // Maximum speed in steps per second
int accelSt = 500; // Acceleration in steps per second per second
long stepsPerRev = 200; // Steps per revolution of your stepper motor
float stepsPerCM = stepsPerRev / (2 * 3.14159 * 2); // Steps per cm (assuming a 2 cm diameter pulley)

bool switchValue = false;
bool isHomed = false;

void setup() {
  pinMode(DirectionPin, OUTPUT);
  pinMode(PulsePin, OUTPUT);
  pinMode(switchValue, INPUT_PULLUP);

  stepper1.setMaxSpeed(maxSp);
  stepper1.setAcceleration(accelSt);

  // Move to home position (position 0)
  stepper1.moveTo(0);
  stepper1.runToPosition();
  isHomed = true;
}

void loop() {
  digitalRead(switchPIN);
  // If not homed, move 10 cm and set homed flag
  if (switchPIN == false) {
    isHomed = false;
    digitalWrite(DirectionPin, HIGH);
    digitalWrite(PulsePin, LOW);
    stepper1.moveTo(10 * stepsPerCM);
    stepper1.runToPosition();

  
  }

  // Check if the microswitch is triggered
  else {
    digitalWrite(DirectionPin, LOW);
    digitalWrite(PulsePin, HIGH);
    stepper1.moveTo(-10 * stepsPerCM);
    stepper1.moveTo(0);
    stepper1.runToPosition();
    isHomed = true;
  }
}

That's completely useless. The position of the stepper when starting the sketch is assumed as position 0. So you are moving to the actual position -> nothing happens.

You don't save the state of the switchPIN. digitalRead returns the state, but you don't use that.

This will never be true. You defined switchPin as 10. false is a equivalent to 0.
You must not compare the switchPIN number but the result you got from the digitalRead(switchPIN).

Change this:

void loop() {
digitalRead(switchPIN);
// If not homed, move 10 cm and set homed flag
if (switchPIN == false) {

to this:

void loop() {
int swpin = digitalRead(switchPIN);
// If not homed, move 10 cm and set homed flag
if (swpin == LOW) {

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.