The following functions receive and send serial data from the RS485 bus network. Packet Data is stored in a global byte array (one for send and another for received) for processing in other parts of the program.
It works as expected but I would like to make it as efficient as possible since it is being called all the time Any suggestions are appreciated
boolean CheckIncData()
{
byte inByte1=0;
byte inByte2=0;
if (Serial1.available()<2) return false;
inByte1 = Serial1.read();
inByte2 = Serial1.read();
if (((inByte1 == 0xAA) and (inByte2 == 0xAA))== false)return false; // First two bytes should be 0xAA
IncPacket[0]=0xAA;
while (IncPacket[0]==0xAA) { // while loop rejects additional AA bytes.
while(Serial1.available()==0) { };
IncPacket[0]= Serial1.read(); // Read Length of incoming packet
}
if (IncPacket[0] > 78) { // IncPacket[0] holds the length (number of bytes to be expected in packet. Next byte is the length and shouldn't be more than 78
IncPacket[0]=0;
return false;}
for (int x=1; x<IncPacket[0]; x++)
{
while(Serial1.available()==0) { };
IncPacket[x]=Serial1.read();
};
// ****** Do Authentication CRC check *******
bool passed=Check_crc(IncPacket, IncPacket[0]-2); // function to check CRC
return passed;
}
And the following is the corresponding function to send a packet :
void SendFeedback() {
if (Serial1.available()>0){ // if someone else is talking postpone transmission
SendPending++;
if (SendPending>10) {SendPending=0;Serial.println (F("Bus Busy. Packet Dropped"));DroppedPackets++;return;} // Try upto 10 times
Serial.print (F("BUS Tx postponed:"));
Serial.println (SendPending);
if (SendPending>7){delay(10);} // Add additional delay for waiting
return;}
digitalWrite (DEpin, HIGH); // Enable rs485 chip
Serial1.write(0xAA); // send two start bytes
Serial1.write(0xAA);
Serial1.write (OutPacket,OutPacket[0]); // Send rest of packet
Serial1.flush();
digitalWrite (DEpin, LOW); // disable chip
if (SendPending) {
Serial.println (F("BUS Tx complete")); // If had to wait for someone to stop talking
SendPending=0; // now reset counter
}
else {TotalSent++;} // This is for statistics on packets sent
}