The below receiver code is based on Robin's Serial Input Basics - updated; the changes in his recvWithStartEndMarkers() code are marked with my username.
The loop has an additional functionality simulating a long running process (it should be 2 seconds) during which interrupts are disabled.
// receiver
// slightly modified from https://forum.arduino.cc/t/serial-input-basics-updated/382007
// uses Serial1
// echoes received character
// Example 3 - Receive with start- and end-markers
const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
void setup()
{
Serial.begin(57600);
Serial1.begin(57600);
}
void loop() {
recvWithStartEndMarkers();
showNewData();
// long running animation (2 seconds) with interrupts disabled
cli();
for (uint32_t cnt = 0; cnt < 0x32000000UL; cnt++)
{
__asm__("nop\n\t");
}
sei();
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
// sterretje: use if instead of while
if (Serial1.available() > 0 && newData == false) {
rc = Serial1.read();
// sterretje: echo received character
Serial1.write(rc);
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;
}
}
The below code is for the sender
// sender
char message[32] = "<Hello world>";
void setup()
{
Serial1.begin(57600);
}
void loop()
{
// if a message has been transfered completely
if (sendMessage(message) == true)
{
// delay it a bit before we send the message again
delay(5000);
}
}
/*
Send a message byte by byte waiting for an echo each time
Returns:
false while transfer in progress
true when transfer is complete
*/
bool sendMessage(char *msg)
{
// flag to indicate if we're waiting for an echo
static bool waitEcho = false;
// keep track which character to send
static uint8_t msgIndex;
// if we're not waiting for an echo
if (waitEcho == false)
{
// send one character
Serial1.write(msg[msgIndex]);
waitEcho = true;
}
if (waitEcho == true)
{
if (Serial1.available())
{
char ch = Serial1.read();
waitEcho = false;
msgIndex++;
}
}
if (msgIndex == strlen(message))
{
msgIndex = 0;
return true;
}
return false;
}
Both codes compile but I currently don't have time to test.