Hi there!
I'm currently working on a robotics project that requires serial communication to control motor direction and speed. These commands will come one at a time. I have been referencing Serial Input Basics by Robin2, specifically example 5. My modified code (shown below) is supposed to receive the data then print out that same data with labels.
const byte maxInts = 32;
char receivedInformation[maxInts];
char tempInformation[maxInts];
int infoDirection;
int infoPower;
bool newData = false;
void setup() {
Serial.begin(9600);
}
void loop() {
while(newData == false){
receiveInfo();
}
if (newData == true){
strcpy(tempInformation,receivedInformation);
parseData();
showParsedData();
newData = false;
}
}
void receiveInfo(){
static bool receivingInProgress = false;
static byte index = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false){
rc = Serial.read();
//Find Start
if (rc == startMarker){
receivingInProgress = true;
}
//Read Information
else if (rc != endMarker){
receivedInformation[index] = rc;
index++;
if (index >= maxInts){
index = maxInts - 1;
}
}
//Find End
else if (rc == endMarker){
receivedInformation[index] = '\0';
receivingInProgress = false;
index = 0;
newData = true;
}
}
}
void parseData() {
char * strtokIndex;
strtokIndex = strtok(tempInformation,",");
infoDirection = atoi(strtokIndex);
strtokIndex = strtok(NULL,",");
infoPower = atoi(strtokIndex);
}
void showParsedData() {
Serial.print("Direction ");
Serial.println(infoDirection);
Serial.print("Power ");
Serial.println(infoPower);
}
This code receives commands in the format <direction,power>. It works for the first command entered into the terminal, but every other command defaults to <0,0>. I've attached a picture of the output from two inputs.
I think this is possibly happening because the code is not checking for new data as it should or the data is being overridden. Is it possible that this is the case, or is there something else I'm missing?
