I have a program that will read from 2 different serial ports. The receive() function is almost identical for both of them, the only difference is really the serial port to read from and to check. Is there a way to make this serial port a variable so I don't have to duplicate code? Using define and macros maybe? This is my code:
bool Data::receive(){
static byte const syncByte = 204; // actual value of sync byte
static byte msgLen; // length of message
static byte cmdByte; // command byte
static byte recvdSyncByte = 0; // first byte read from fuze setter
static bool receivedString = false; // check received full string
static bool recvMsgLen = false; // check received message length
// if the at least 3 bytes are available in the serial buffer
if (teensy.available() >= 3 && !recvMsgLen) {
recvdSyncByte = teensy.read(); // read possible sync byte
if (recvdSyncByte == syncByte) { // does recvdSyncByte equal 0xCC?
teensyBuffer[0] = recvdSyncByte; // save sync byte to buffer
for (int i = 1; i < 3; i++) // save command and msglen bytes to buffer
teensyBuffer[i] = teensy.read();
cmdByte = teensyBuffer[1]; // save command byte
msgLen = teensyBuffer[2]; // save length of message
recvMsgLen = true; // set received to true so this code only executes once
}
}
// read rest of hexstring if there was a message
if (recvMsgLen && msgLen > 0 && !receivedString && (teensy.available() >= msgLen + 1)) {
for (int i = 1; i <= msgLen + 2; i++) // save the message and CRC bytes to buffer
teensyBuffer[i + 2] = teensy.read(); // read until last CRC bit, calculated from msgLen -byte
teensyBufferSize = msgLen + 4; // saves the length of the message
receivedString = true; // received message
}
/*
// timeout if no message received
if ( recvMsgLen && !receivedString && timeoutTimer.current() >= timeoutTimer.period() )
emptyBuffer();
*/
if(receivedString) // return true if data has been received
{
receivedString = false;
recvMsgLen = false;
return true;
}
else
return false;
}
So if you look at the "if(teensy.available() >= 3 && !recvMsgLen)" statement, you will see that the only thing I need to do is make "teensy" be a variable so that I could make it equal something else. I know this doesn't work, but is there any thing I can do in a good way here so I don't duplicate code?
thanks.