#include <SoftwareSerial.h>
SoftwareSerial mySerial(D2, D3); // RX, TX
const byte numBytes = 6;
byte receivedBytes[numBytes];
byte numReceived = 0;
boolean newData = false;
void setup()
{
Serial.begin(115200);
mySerial.begin(9600);
pinMode(D8,OUTPUT);
digitalWrite(D8,LOW);
}
void loop() {
recvBytesWithStartEndMarkers();
showNewData();
}
void recvBytesWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
byte startMarker = 0x7B;
byte endMarker = 0xFE;
byte rb;
while (mySerial.available() > 0 && newData == false) {
rb = mySerial.read();
if (recvInProgress == true) {
if (rb != endMarker&&ndx<=6) {
receivedBytes[ndx] = rb;
ndx++;
if (ndx ==6 ) {//ndx>=numBytes
//ndx = numBytes-1 ;
receivedBytes[ndx] = rb;
recvInProgress = false;
numReceived = ndx;
newData = true;
receivedBytes[ndx] = '\0';
ndx=0;
}
/* else if (ndx == numBytes)
{
receivedBytes[ndx] = rb;
numReceived = ndx ;
newData = true;
}*/
}
else {
receivedBytes[ndx] = '\0'; // terminate the string
recvInProgress = false;
numReceived = ndx; // save the number for use when printing
ndx = 0;
newData = true;
}
}
else if (rb == startMarker) {
recvInProgress = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in (HEX values)... ");
Serial.print("no receiver ");
Serial.print(numReceived);
Serial.print("...");
for (byte n = 0; n < numReceived; n++)
{
Serial.print(receivedBytes[n]);
Serial.print(' ');
}
//for (byte n = 0; n < numReceived; n++)
if(receivedBytes[4]==0x00&& receivedBytes[3]==0x01)
{
Serial.println("HIGH");
digitalWrite(D8,HIGH);
}
if(receivedBytes[4]==0xFF&& receivedBytes[3]==0x01)
{
Serial.println("LOW");
digitalWrite(D8,LOW);
}
if(receivedBytes[4]==0xFF&& receivedBytes[3]==0x05)
{
Serial.println("LOW");
digitalWrite(D8,LOW);
}
if(receivedBytes[4]==0xFF&& receivedBytes[3]==0x05)
{
Serial.println("LOW");
digitalWrite(D8,LOW);
}
Serial.println();
newData = false;
}
}