My code works but wont step the stepper

Hello, Below is a code that I have written. The code displays correctly on the LCD and responds correctly to the encoder but for some reason the stepper will not more in the homing function or in the loop function after selecting the speed. Can anyone spot why that would be? and i have uploaded a basic code and the stepper corresponds correctly.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <AccelStepper.h>
#include <Adafruit_seesaw.h>

#define SS_SWITCH        24
#define SS_NEOPIX        6
#define SEESAW_ADDR      0x36

// LCD setup
LiquidCrystal_I2C lcd(0x27, 16, 2);

// Adafruit Rotary encoder setup
Adafruit_seesaw ss;

const int dirPin = 8;      // Direction pin
const int stepPin = 9;     // Step pin
const int enablePin = 10;  // Enable pin (if your driver supports it)


const int moveUpSwitchPin = 5;            // Switch input to move stepper up
const int emergencyStopSwitchPin = 6;     // Emergency stop button pin with pull-up
const int homeSwitchPin = 7;              // Switch input for homing pull-up
int32_t encoder_position;

int minSpeed = 500;
int maxSpeed = 5000;

int minAcceleration = 500;
int maxAcceleration = 5000;

AccelStepper stepper(1, 9, 8);

int totalCases = 0;

void displaySpeedAndAccel(int speed, int acceleration) {
  lcd.clear();
  lcd.print("Speed: ");
  lcd.print(speed);
  lcd.setCursor(0, 1);
  lcd.print("Accel: ");
  lcd.print(acceleration);
  delay(1000);
}

void lcdSetup() {
  lcd.init();
  lcd.backlight();
}

void setup() {
   lcdSetup();  // Initialize LCD only once in the setup
  if (!ss.begin(SEESAW_ADDR)) {
    while (1);
  }

  Serial.begin(9600);
  pinMode(dirPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  //if (enablePin != -1) pinMode(enablePin, OUTPUT);

  //if (enablePin != -1) digitalWrite(enablePin, HIGH);

  stepper.setMaxSpeed(1500);
  stepper.setAcceleration(1500);
  pinMode(emergencyStopSwitchPin, INPUT_PULLUP); // Set up the emergency stop switch as pull-up
}


bool encoderTurnedUp = false;

void waitForSelectionButtonPress() {
  while (ss.digitalRead(SS_SWITCH) == HIGH) {
    // Wait for the selection button to be pressed
  }
  delay(100); // Debounce
}

bool speedSelectionCompleted = false; // Global variable to track if speed selection is completed

void selectSpeed() {
  // Check if speed selection has already been completed
  if (speedSelectionCompleted) {
    return;
  }

  const int maxSpeed = 5000;
  const int minSpeed = 500;
  
  lcd.clear();
  lcd.print("Select speed");
  delay(2000);

encoder_position = ss.getEncoderPosition();
int buttonState = HIGH; // Assuming the button is not pressed initially
int lastButtonState = buttonState;
bool speedSelected = false;

  while (!speedSelected) {
    buttonState = ss.digitalRead(SS_SWITCH);

    // Check if the encoder is turned
    int32_t new_position = ss.getEncoderPosition();
    int32_t positionChange = new_position - encoder_position;

    int newSpeed = stepper.maxSpeed() - (positionChange * 250);
    int newAccel = stepper.acceleration() - (positionChange * 250);

    // Ensure the speed stays within the range
    stepper.setMaxSpeed(constrain(newSpeed, minSpeed, maxSpeed));

    // Ensure the acceleration stays within the range
    stepper.setAcceleration(constrain(newAccel, minSpeed, maxSpeed));

    encoder_position = new_position;

    displaySpeedAndAccel(stepper.maxSpeed(), stepper.acceleration());
    delay(10); // Adjust this delay if needed

    if (buttonState == HIGH && lastButtonState == LOW) {
      // Button was released
      speedSelected = true;
    }

    lastButtonState = buttonState;

    // Check if the emergency stop switch is pressed
    if (digitalRead(emergencyStopSwitchPin) == LOW) {
      emergencyStop();
    }
  }

  // Display "Speed selected" message
  lcd.clear();
  lcd.print("Speed selected");
  delay(1000); // Display the message for 1 second
  lcd.clear();
  

  // Set the global variable to indicate that speed selection is completed
  speedSelectionCompleted = true;

  // Return to exit the function
  return;
}

void displayHomingInstructions() {
  lcd.clear();
  lcd.print("Press SELECT");
  lcd.setCursor(0, 1);
  lcd.print("to start homing");
}

//bool homingDone = false;

void initiateHomingSequence() {
  displayHomingInstructions();
  
  // Wait for the user to press the SELECT button to start homing
  waitForSelectionButtonPress();
  
  // Display "Homing..." message
  lcd.clear();
  lcd.print("Homing...");

  // Set stepper speed and acceleration to lower values during homing
  stepper.setMaxSpeed(1000);  // Adjust as needed
  stepper.setAcceleration(500);  // Adjust as needed

  // Set the direction for homing
  digitalWrite(dirPin, LOW);  // Adjust the direction as needed

  // Move the stepper motor until the home switch is triggered or a timeout occurs
  unsigned long startTime = millis();
  while (!digitalRead(homeSwitchPin) && (millis() - startTime < 5000)) {
    stepper.runSpeed();  // Run at a constant speed during homing
    delay(10);
  }

  // Stop the motor
  stepper.stop();

  // Reset position to zero
  stepper.setCurrentPosition(0);

  // Reset speed and acceleration to desired values for normal operation
  stepper.setMaxSpeed(maxSpeed);
  stepper.setAcceleration(maxAcceleration);

  // Display "Homing Done" message
  lcd.clear();
  lcd.print("Homing Done");
  delay(1000);

  // Clear the LCD
  lcd.clear();
}


void updateTotalCases() {
  lcd.setCursor(0, 0);
  lcd.print("Total Cases: ");
  lcd.setCursor(0, 1);
  lcd.print(totalCases);
}

bool emergencyStopTriggered = false;

void emergencyStop() {
  lcd.clear();
  lcd.print("E-STOP");
  lcd.setCursor(0, 1);
  lcd.print("Press ENCODER to restart");

  while (ss.digitalRead(SS_SWITCH) == HIGH) {
    // Wait for the encoder button to be pressed
    delay(10);
  }
  // Reset the emergency stop flag
  emergencyStopTriggered = false;

  // Clear the LCD after restarting
  lcd.clear();
  lcd.print("Restarting...");
  delay(1000); // Display "Restarting..." for 1 second
  loop();

}

void loop() {
  // Check if the emergency stop button is pressed at any time
  if (ss.digitalRead(SS_SWITCH) == LOW && !emergencyStopTriggered) {
    emergencyStopTriggered = true;
    emergencyStop();
  }

  lcd.clear();
  lcd.print("Press SELECT");
  lcd.setCursor(0, 1);
  lcd.print("to start homing");

  // Wait for the user to release the select button to avoid accidental double-click
  while (ss.digitalRead(SS_SWITCH) == LOW) {
    delay(5);
  }

  // Wait for the user to press the select button to start homing
  waitForSelectionButtonPress();
  initiateHomingSequence();
  

  // Display "Homing Done" for 1 second
  lcd.clear();
  lcd.print("Homing Done");
  delay(1000);
  lcd.clear();

  while (true) {
    // Check if the emergency stop or soft stop button is pressed at any time
    if (ss.digitalRead(SS_SWITCH) == LOW && !emergencyStopTriggered) {
      emergencyStopTriggered = true;
      emergencyStop();
    }

    // Allow the user to select the speed using the button
    selectSpeed();
    updateTotalCases();
    delay(10);  // Add a small delay for stability

    if (digitalRead(emergencyStopSwitchPin) == LOW) {
      emergencyStop();
      // Emergency stop
      //stepper.stop();
      //lcd.clear();
      //lcd.print("Emergency Stop");
      while (true) {}  // Halt further execution
    }

    // Check if the move-up switch is closed
    if (!digitalRead(moveUpSwitchPin)) {
   // If move-up switch is not pressed, move to position 1500 and then back to 0
   stepper.moveTo(1500);
   stepper.runToPosition();

   // Increment totalCases after reaching the target position
   totalCases++;  // Increment total cases
   updateTotalCases();

   stepper.moveTo(0);
   stepper.runToPosition();

   // Increment totalCases after reaching the target position
   totalCases++;  // Increment total cases
   updateTotalCases();
    }
  }
}

Since your code works Post an annotated schematic showing exactly how you have wired it. Show all connections, power, ground, power sources and note any leads over 10"/25cm.

And describe what your code should do.
Which board are you using?

The code is very confusing. Usually homing is done in setup(), and loop() should do what its name assumes: loop forever. But you created your own endless while(true); ( There are even boards that crash if you do so .. ).

And there are some points that let me assume you don't really understand how AccelStepper works.

        stepper.runSpeed();  // Run at a constant speed during homing

runSpeed() needs setting the speed before with setSpeed(). But there is not any call to setSpeed() in your sketch. And the direction of movement is defined by the sign of the speed set with setSpeed(). Never set the dirPin by yourself - AccelStepper will set it as needed.

    // Stop the motor
    stepper.stop();

The stop() function is only useful together with run(). It will not really stop the stepper, but set a new target as close to the current position, that it can be reached with the current deceleration. If you stop creating steps ( e.g. by not calling runSpeed() or run() ) the stepper will stop anyway.

My intention is to use either a uno or nano. As for the runSpeed I was under the assumption that the set speed function would set the determined speed. As for what I want the machine to do is basically, home the machine. Have the user set the desired speed then run back and forth at 1500 steps until the e-stop is pressed. When the stop is pressed I want the homing function to restart then have the machine continue the loop cycle. My problem is that I cannot get any stepper movement out of this current code. Basic code works just fine. Home switch works correctly with this code as well.

Also I have tried stepper.run and stepper.runSpeed with still no movement. I have tried a bunch of debugging code and in the monitor it dose go through that section just fine.

But you never did set the speed, so it is 0 by default. That means no movement with runSpeed() -> never trigger the home switch -> block forever.

I tried to add stepper.run and stepper.set speed and still no movement.

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