Problem running stepper motor using values stored in sd card

Hey Experts,
I'm trying to run my stepper motor using values stored in sd card. The problem is when i try to run this code the stepper motor stutters and takes some steps and slows down. I request you guys to help me!!!

The code is given below:

#include <SD.h>
#include <SPI.h>
#include <AccelStepper.h>

// Pins for the SD card module
const int chipSelect = 10;

// Pins for the stepper motor driver (DRV8825)
const int stepPin = 2;
const int dirPin = 3;
const int enablePin = 4;

// Stepper motor configuration
const int stepsPerRevolution = 200;  // Change this value based on your motor
const float maxSpeed = 1000.0;       // Maximum speed in steps per second
const float acceleration = 1000.0;   // Acceleration in steps per second^2

AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin);

void setup() {
  Serial.begin(9600);
  pinMode(enablePin, OUTPUT);
  
  SD.begin(chipSelect);
  
  stepper.setMaxSpeed(maxSpeed);
  stepper.setAcceleration(acceleration);
}

void loop() {
  if (SD.exists("steps.txt")) {
    File file = SD.open("steps.txt");
    if (file) {
      // Read the integer value from the file
      int targetSteps = file.parseInt();
      file.close();
      
      // Move the stepper motor to the target position
      stepper.moveTo(targetSteps);
      
      // Run the stepper motor until it reaches the target position
      while (stepper.distanceToGo() != 0) {
        stepper.run();
      }
    }
  }
  
  // Wait for a short duration before checking the SD card again
  delay(1000);
}

Use a logic analyzer to see what happens.

Insert Serial.println()´s at points of interrest and analyze the test results.

Have a nice day and enjoy coding in C++.

1 Like

Thanks much @paulpaulson but how would that help?

Give them a try simply.

Why do you re-open the steps file every time through loop ?

Just open it once in setup, and close it if you complete the run cycle.

1 Like

Thanks pal!!
I'll surely try doing that and let you know.
But how do I mention it in the setup to close file once the run cycle is completed??

A bit of restructuring - open in setup(), run your loop until you’ve finished all your data, then close only when complete.

Setup only does the initialisation… no reason to close the file in setup if it’s still being used !

Ok so what you mean is start sd card in setup and close it in loop

Close it when you’re ‘finished’ with reading the data.

1 Like

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