The method outlined by Majenko is the general way of dealing with this
kind of requirement, and also probably the “cleanest” way. If, however,
you are confident that the incoming data always follows the pattern you
are showing, then you can “cheat” and cut some corners.
Consider this: in the sample you show, the character 'A' only ever
appears as the second character in a line, and always as part of the
sequence "#A-R=". If you are confident that this is always the case,
then you can apply the following algorithm:
- the program processes one input character at a time, and decides
whether to print it to its output or not
- it has two possible states: either it is printing every character it
reads (because it believes the character belongs to a “#A-R” line), or
it is not
- if it is printing and it reads an end of line, it prints that end of
line, and then stops printing
- if it is not printing and it reads an
'A', it outputs "#A", then
starts printing all its input.
In code:
void loop() {
static bool printing = false; // are we printing what we read?
if (Serial2.available()) {
char c = Serial2.read();
if (printing) {
Serial.write(c);
if (c == '\n') // on end of line, stop printing
printing = false;
} else if (c == 'A') { // on 'A', start printing
Serial.print("#A");
printing = true;
}
}
}
This code assumes your device uses ASCII LF ('\n') as end-of-line
indicator. You will have to replace '\n' by '\r' if it uses ASCII CR
instead.
grep '#A-R=' /dev/ttyACM0