AccelStepper and motor control

Hi!
I would like to program this type of task:

  1. read serial
  2. if char is for ex. ‘a’ call function step(numberOfSteps)
    3. function should move stepper for exact number of steps, with constant speed, steps are given in function argument - it’s very important for me
  3. motor should stop after movement
  4. program waits for another input from serial port

I’m using A4988 stepper driver.
I’ve made a program, but I doesn’t work. After calling function step(numberOfSteps) motor moves only one step.
Any comments and suggestions are welcomed.

#include <AccelStepper.h>

// Define a stepper and the pins it will use
#define STEP_PIN        9
#define DIR_PIN         8
#define ENABLE_PIN      7
#define MS1_PIN         3
#define MS2_PIN         4
#define MS3_PIN         5 
AccelStepper stepper(1, STEP_PIN, DIR_PIN);

char inChar; // command from user

void setup()
{  
  Serial.begin(9600);
  pinMode(DIR_PIN,  OUTPUT);
  pinMode(STEP_PIN, OUTPUT);
  pinMode(ENABLE_PIN,1);
  pinMode(MS1_PIN,OUTPUT);
  pinMode(MS2_PIN,OUTPUT);
  pinMode(MS3_PIN,OUTPUT);
  digitalWrite(MS1_PIN,1);  // microstepping on
  digitalWrite(MS2_PIN,1);
  digitalWrite(MS3_PIN,1);
  digitalWrite(ENABLE_PIN,1);
  
  stepper.setMaxSpeed(200);
  stepper.setSpeed(200);
  
  Serial.println("Device ready");
}

void loop()
{ 
  digitalWrite(ENABLE_PIN,0); // Enable on A4988 chip
  
  if(Serial.available() > 0){
  inChar = Serial.read();  //read command
  Serial.println(inChar);
  switch (inChar){
  case 'a':  // if 'a' do for ex. 10 steps and stop -> call function step(10)
   // What should I type here?
  step(10);
  break;
  }
  }
}

void step(int numberOfSteps){
  
  if (stepper.distanceToGo() == 0)
  {
   stepper.move(numberOfSteps);
   stepper.setSpeed(100);
  }
   stepper.runSpeed();
}

Is it allowed to call setSpeed directly after move ? Perhaps you could create a new sketch without library and set the direction and toggle the step pin a number of times. Only to see if the hardware is working.

Please use HIGH and LOW with digitalWrite.

The runSpeed should be at the end of loop(), you have it inside the step() function which is only called when you type 'a'.

If you have a Pololu A4988 driver and you do not need acceleration then it is probably easier NOT to use the AccelStepper library. Look at the simple code in this demo.

You should look at the Arduino code in this demo for a reliable way to receive data.

If the data is being sent to your Arduino by a program on your PC it would probably be wise for the Arduino to tell the PC it is ready after the movement is complete - so the PC won't send data prematurely. Another option is to request new data before the movement starts but only check if it has arrived when the movement is complete - but that is different from the above demo program.

...R