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()
{
Serial.begin(115200);
stepper.setMaxSpeed(90);
stepper.setAcceleration(90);
}
void loop()
{
if (Serial.available()) {
int steps = Serial.parseInt();
stepper.moveTo(steps);
if (stepper.distanceToGo() == 0) {
stepper.moveTo(stepper.currentPosition());
stepper.setSpeed(100);
}
}
stepper.run();
}
2 Answers 2
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:
- 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. - 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
. - Make the timeout value for
parseInt()
smaller.parseInt()
inherits from the Stream class so you would useSerial.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():مهند خليل– مهند خليل2016年11月04日 19:25:43 +00:00Commented Nov 4, 2016 at 19:25
-
how to terminate the serialمهند خليل– مهند خليل2016年11月05日 14:39:53 +00:00Commented Nov 5, 2016 at 14:39
parseInt()
: it will wait for one second to make sure there are no digits pending.