Fa77:
I know, and that's also the reason why at the beginning I lost many hours trying to understand what was wrong.
Nice!
The code example below might save you a little time. I would have posted it yesterday but needed to hack the snippet out of a larger sketch, which I wrote to de-serialise .conf files.
/* MattS-UK Arduino example code
Extract key value pairs from serial stream
*/
//if you don't want to use the Streaming library
// you need to change the Serial << output statements
// to use .print, .println methods
#include <Streaming.h>
void setup()
{
Serial.begin(9600);
Serial << "Extract key=value pairs from serial stream...\r\n";
}
#define MAX_BUFFER_LENGTH 64
#define MAX_KEY_LENGTH 32
#define MAX_VALUE_LENGTH 32
char messageBuffer[MAX_BUFFER_LENGTH +1] = {0};
char key[MAX_KEY_LENGTH +1] = {0};
char value[MAX_VALUE_LENGTH +1] ={0};
uint16_t bufferHead = 0;
void loop()
{
bool pairAvailable = false;
uint16_t bytesAvailable = Serial.available();
//buffer overrun check
while (bytesAvailable > MAX_BUFFER_LENGTH) {
Serial.read();
}
//sanity check
if (bufferHead > MAX_BUFFER_LENGTH) {
//reset the buffer
messageBuffer[0] = 0;
bufferHead = 0;
return;
}
//read incoming
if(bytesAvailable) {
for(uint8_t i = 0; i < bytesAvailable; i++) {
char inChar = Serial.read();
if (inChar != ':') {
messageBuffer[bufferHead++] = inChar;
}
else {
//end of message.
//Terminate the buffer and extract pair.
messageBuffer[bufferHead] = 0;
if(messageToPair(messageBuffer, key, value)) {
pairAvailable = true;
}
else {
Serial << "malformed message\r\n";
}
//reset the buffer
messageBuffer[0] = 0;
bufferHead = 0;
}
}
}
//process new pair
if(pairAvailable) {
processPair(key, value);
}
}
//extract key = value pair from message buffer
bool messageToPair(char* message, char* key, char* value) {
uint8_t messageLength = strlen(message);
uint8_t valueHead = 0;
bool keyFound = false;
//sanity check
if (!messageLength) {
//failed
key[0] = 0;
value[0] = 0;
return false;
}
//split key = value pair
for (uint8_t i = 0; i < messageLength; i++){
if ((!keyFound) && (i < MAX_KEY_LENGTH)) {
key[i] = message[i];
if(message[i] == '='){
keyFound = true;
key[i] = 0;
}
}
else {
value[valueHead++] = message[i];
}
}
value[valueHead] = 0;
//sanity check
if((!keyFound) || (strlen(value) > MAX_VALUE_LENGTH)) {
//fail
key[0] = 0;
value[0] = 0;
return false;
}
return true;
}
//example pair processing rule
void processPair(char* key, char* value) {
Serial << "Key=" << key << "\tValue=" << value << "\r\n";
if(key[0] = 'L') {
//device is an LED
uint8_t ledID = atoi(&key[1]);
bool ledState = (bool) atoi(value);
Serial << " ledID = " << ledID << "\tstate = " << ledState << "\r\n";
return;
}
}