I have been working on this for a few days and have been unable to figure out what is wrong. I need to be able to send commands larger than 1 character and have attempted using a 2d char array and a string array as in the code posted below.
When I run the code with the outer for loop in the gatherData() function set to i < 1, it will run 19 times returning clean data but if I set i < 2, it will run the first command 19 times and the second command 1 time, with random garbage in the returned data.
I have modified the code slightly (changed the actual commands).
Does anyone have any advice or see what I am doing wrong here? Thank you for your assistance.
#include <SoftwareSerial.h>
SoftwareSerial rs232(10, 11);
int rcvCount = 0;
const byte numChars = 64;
char endStr[numChars];
char receivedChars[numChars];
String cmds[3] = {"1234", "5678"};
bool RTS = true;
bool newData = false;
bool executed = false;
void setup() {
Serial.begin(9600);
rs232.begin(9600);
}
void loop() {
recvWithEndMarker();
showNewData();
if(executed == false){
gatherData();
}
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\r';
char rc, t;
while (Serial.available() > 0) {
t = Serial.read();
if (t == 'A') {
Serial.println("Caught A");
executed = false;
RTS = true;
rcvCount = 0;
}
else {
}
}
while (rs232.available() > 0 && newData == false) {
rc = rs232.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
rcvCount++;
RTS = true;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.println(receivedChars);
newData = false;
receivedChars[0] = (char)0; //clear the char array
}
}
void gatherData(){
if(RTS == true){
int i;
int j;
for(i = 0; i < 1; i++){
char charBuf[cmds[i].length()];
cmds[i].toCharArray(charBuf, cmds[i].length() + 1);
for(j = 0; j < cmds[i].length(); j++){
//Serial.print(charBuf[j]);
rs232.write(charBuf[j]);
}
rs232.write('\r');
}
RTS = false;
}
if(sizeof(cmds) == rcvCount){
executed = true;
}
}