If I want to receive commands via Serial,
I collect all the incoming chars in a buffer,
when the line delimiting CR/LF comes along,
my collecting routine calls the function that processes the received line,
and clears the collection buffer after that function returns.
For this simple example, the processing is just a print, all on Serial.
void setup() {
Serial.begin(115200);
Serial.println(F("Echo lines"));
}
void loop() {
handleSerial();
}
void oneLineReceived(const char * buffer) {
Serial.println(buffer);
}
const byte maxMsgLen = 64;
const byte cbLF = 10;
const byte cbCR = 13;
void handleSerial() {
static uint8_t bIndex;
static uint8_t buffer[maxMsgLen + 1];
bool lineReady = false;
if (Serial.available()) {
uint8_t inChar = Serial.read();
if (inChar != cbLF) {
if (inChar == cbCR) {
lineReady = true;
} else {
buffer[bIndex++] = inChar;
lineReady = (bIndex == maxMsgLen);
}
if (lineReady) {
buffer[bIndex] = 0;
oneLineReceived((const char*)buffer);
bIndex = 0;
}
}
}
}