I am trying to find a robust way of sending 2 bytes from one Arduino to another. I have tried sending an array with a start value, the two subject bytes followed by an end byte. (The markers are reserved and will not be sent as data.)
//mega on com6 sender
#include<SoftwareSerial.h>
#define RXPIN 3
#define TXPIN 4
SoftwareSerial SUART(RXPIN,TXPIN);
byte myArr[] = {254,210,1, 255};
void setup()
{
Serial.begin(9600);
SUART.begin(9600);
delay(1000); // tried with and without a delay
SUART.write(myArr,4);
}
void loop()
{
//nano on com7 receiver
#include<SoftwareSerial.h>
#define RXPIN 7
#define TXPIN 8
#define START_BYTE 254
#define END_BYTE 255
byte rcvdArr[4];
const unsigned int MAX_MSG_LENGTH = 4;
SoftwareSerial Suart(RXPIN,TXPIN);
void setup()
{
Serial.begin(9600);
Suart.begin(9600);
delay(1000); // tried with and without this
}
void loop() {
if( Suart.available() != 0) {
int length = Suart.readBytesUntil(END_BYTE, rcvdArr, 4);
Serial.print("length ");
Serial.println(length);
if (length == 4 && rcvdArr[0] == START_BYTE) {// END_BYTE discarded, length var still 4
Serial.println(rcvdArr[1]);
Serial.println(rcvdArr[2]);
} else {
Serial.println("bad packet");
}
}
}
This is the output
length 1
bad packet
length 4
210
1
The sketch sends only one packet by intention but before that comes through there is something else which is rejected (the length 1 return is a 0 for invalid data). I don't know what the invalid data is but it would be disruptive if I drop this into the project sketch I am working on. Before I get into a more elaborate model sketch can anyone tell me what might be causing this? What is the stowaway? Would I avoid it by using Serial.read() in a for loop?