// https://wokwi.com/projects/409959282965946369
// Code from https://forum.arduino.cc/t/serial-input-basics-updated/382007/2#example-3-a-more-complete-system-1
// Other simulations https://forum.arduino.cc/t/wokwi-simulations-for-arduino-built-in-examples/1304754
/*
Example 2 - Receive with start- and end-markers
The simple system in Example 2 will work well with a
sympathetic human who does not try to mess it up. But
if the computer or person sending the data cannot know
when the Arduino is ready to receive there is a real risk
that the Arduino will not know where the data starts.
The answer to this problem is to include a start-marker
as well as an end-marker.
*/
// Example 3 - Receive with start- and end-markers
const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
void setup() {
Serial.begin(9600);
Serial.println("<Arduino is ready>");
}
void loop() {
recvWithStartEndMarkers();
showNewData();
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.println(receivedChars);
newData = false;
}
}