假设字符串作为行发送(末尾有一个换行符\n)。
typedef struct {
int A = 0;
int B = 0;
int C = 0;
int D = 0;
int E = 0;
int F = 0;
char G = 0;
int H = 0;
} Line;
typedef void (*LineHandler)(Line data);
bool line_parser(char c, LineHandler line_handler) {
static Line data;
static int value = 0;
static byte state = 0;
bool complete = false;
// ignore the carriage return character
if (c == '\r') return complete;
if (state < 8) {
if (isdigit(c)) {
value = value*10 + c-'0'; // add the digit
}
else if (c == ',' || c == '\n') {
// if a comma or end of line is found, save the value
switch (state) {
case 0: data.A = value; break;
case 1: data.B = value; break;
case 2: data.C = value; break;
case 3: data.D = value; break;
case 4: data.E = value; break;
// the F and G are set when the letter is found
case 7: data.H = value; break;
}
// advance the parsing state and reset the value
state++;
value = 0;
}
else if (state == 5 && isalpha(c)) { // if parsing the 6th number and a letter is found
data.F = value; // save the 6th number
data.G = c; // save the letter
state += 2; // advance to parsing the 8th value
value = 0; // reset the value
}
else
state = 10; // unexpected character; stop the parser
}
if (c == '\n') {
if (state == 8) {
//got complete line
line_handler(data);
complete = true;
}
else {
// parsing failed
}
// reset the parser
value = 0;
state = 0;
}
return complete;
}
void handle_line(Line data) {
// just print out the data
Serial.println("Line:");
Serial.print("A = ");
Serial.println(data.A);
Serial.print("B = ");
Serial.println(data.B);
Serial.print("C = ");
Serial.println(data.C);
Serial.print("D = ");
Serial.println(data.D);
Serial.print("E = ");
Serial.println(data.E);
Serial.print("F = ");
Serial.println(data.F);
Serial.print("G = ");
Serial.println(data.G);
Serial.print("H = ");
Serial.println(data.H);
Serial.println();
}
void setup() {
Serial.begin(115200);
}
void loop() {
if (Serial.available()) {
line_parser(Serial.read(), handle_line);
}
}
这个解析器是非阻塞的,是一个字符一个字符的输入,在接收到整行之后,它会调用一个函数来处理解析后的数据。
发送:
54,125,11045,11,78,4H45
invalid line
11,22,33,44,55,66K88
30,30,20,10,50,50M20
应该发回:
Line:
A = 54
B = 125
C = 11045
D = 11
E = 78
F = 4
G = H
H = 45
Line:
A = 11
B = 22
C = 33
D = 44
E = 55
F = 66
G = K
H = 88
Line:
A = 30
B = 30
C = 20
D = 10
E = 50
F = 50
G = M
H = 20