I am setting up a two motor stepper control program using an Arduino Mega 2560, and am using USB serial connection from a Raspberry Pi. When I run my code, I would like it so that there are two sequential inputs, to begin with a multiplier for revolution of the stepper motors and then a command to move a specific way. These inputs can then be used multiple times to allow for different revolution multipliers and commands.
I currently have code to take the input for the multiplier with start and end markers, e.g <7.4>, and then the move command, e.g 1. This should then loop once the commands have been executed and take the multiplier and commands again.
An example input would be <7.4> and then 1. This should update y and x to be what you have entered (in x's case without the <>).
float steps;
int x;
const byte numChars = 32;
char recievedChars[numChars];
boolean newData = false;
void setup() {
Serial.begin(9600);
if(Serial.available() > 0){
Serial.read();
}
}
void loop() {
recvWithStartEndMarkers();
if(Serial.available() > 0) {
x = Serial.read() - '0';
Serial.println(x);
float y = atof(recievedChars);
steps = stepsPerRevolution * y;
Serial.println(steps);
// choice(); // This leads to the commands that run the steppers.
}
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
recievedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars -1;
}
}
else {
recievedChars[ndx] = '\0';
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
This is the minimal code for what I am trying to do, and doesn't include actual motor control just serial inputs.
From this, it is expected that I would be able to input a multiplier, and then a command, however when running I cannot input a second multiplier after both the command even when I format it as '<'x'>' (would not let me use the symbols so the ' are not normally there) the program just seems to read x as a the command not a multiplier.
As well as this, occasionally upon running the program will not take any inputs until three or 4 numbers have been entered, or will take the multiplier as the multiplier and the command (so an input of <3.4> would take the three as the multiplier, and 4 as the command).
What can i do to make this serial reading more reliable so that it works every time, and more repeatable so that I can use it more than once per upload to the Mega?
Thanks!