I wrote a code that controls a stepper motor using the AccelStepper library. When it receives a serial signal from Visual Basic that contains a coordinate value, the Arduino will control the stepper motor by this value. The code works very well but it runs 1 second after receiving the value over the serial port. I want the code to run faster. Here is the code:

#include <AccelStepper.h>
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper(1, 9, 8);

int pos = 0;

void setup()

void loop()
  if (Serial.available()) {
    int steps = Serial.parseInt();

    if (stepper.distanceToGo() == 0) {
  • 4
    Do not use parseInt(): it will wait for one second to make sure there are no digits pending. – Edgar Bonet Nov 4 '16 at 11:13
  • 3
    Or you could try just appending a line terminator when sending the number. – Edgar Bonet Nov 4 '16 at 11:19
  • Unrelated, but why include accelstepper 3x? – Paul Dec 5 '16 at 6:53

As others have said, this issue is created because the parseInt function reads in characters until it receives a non numeric character or until it reaches the timeout value, which is set at 1000 ms (1 second). There are a couple of ways to fix this, order most difficult to least:

  1. Instead of just sending a number, send a number and then a letter at the end. So instead of sending "123", you would send "123x". parseInt() will immediately return when it hits the x. However, you'll still have the x in the stream so you'll need to manually read it and discard it.
  2. Make the value that is sent a set number of digits - say 4 for example. Since you know it will be four digits, use a for loop to read in four characters and build it into a number by multiplying. If you read in digit1, digit2, digit3, digit4 then the number is 1000 * digit1 + 100 * digit2 + 10 * digit3 + digit4.
  3. Make the timeout value for parseInt() smaller. parseInt() inherits from the Stream class so you would use Serial.setTimeout(50) in the setup function to change it to a 50 ms timeout.

Do not use parseInt(): it will wait for one second to make sure there are no digits pending.

-Edgar Bonet

  • can you make line terminator on the code because Iam very new to arduino programing please and what I use if replace the parseInt(): – مهند خليل Nov 4 '16 at 19:25
  • how to terminate the serial – مهند خليل Nov 5 '16 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.