So to start off I apologize for being a newb at this. I've tried to work through this on my own and search out other answers but I'm not even really sure what exactly to search for. I found this to be a helpful answer but just hoping for some more clarification.
I'm working with a couple dev boards for work trying to get them to talk to each other. The one board I need to talk to gave some sample code I've been trying to work with. The TX function works fine, I'm just not familiar enough with C to understand fully what I'm doing.
The RX function they provide is:
int recv_packet(char *p, int len){
char c;
int received = 0;
/* sit in a loop reading bytes until we put together
* a whole packet.
* Make sure not to copy them into the packet if we
* run out of room.
*/
while(1) {
/* get a character to process
*/
c = UART_GetChar();
/* handle bytestuffing if necessary
*/
switch(c) {
/* if it's an END character then we're done with
* the packet
*/
case END:
/* a minor optimization: if there is no
* data in the packet, ignore it. This is
* meant to avoid bothering IP with all
* the empty packets generated by the
* duplicate END characters which are in
* turn sent to try to detect line noise.
*/
if(received)
return received;
else
break;
/* if it's the same code as an ESC character, wait
* and get another character and then figure out
* what to store in the packet based on that.
*/
case ESC:
c = UART_GetChar();
/* if "c" is not one of these two, then we
* have a protocol violation. The best bet
* seems to be to leave the byte alone and
* just stuff it into the packet
*/
switch(c) {
case ESC_END:
c = END;
break;
case ESC_ESC:
c = ESC;
break;
}
/* here we fall into the default handler and let
* it store the character for us
*/
default:
if(received < len)
p[received++] = c;
}
}
}
then based on the answer I found I'm able to call it with a function like
int main() {
char arr[10] = {0};
recv_packet(arr, 10);
/*then parse it somehow--
* I'll figure this out on my own,
* but for now I just want to read it all
* into an array.
*/
parse_function(arr);
}
So if you made it through all that.... my big question is how do I prevent my array from filling up if I make the length smaller than the message I need to receive? the device I'm using C to talk to will send back a series of hex characters starting and ending with 0xC0 (otherwise defined in other code as 'END') but the middle is a whole mess of hex that is a response back from the device depending on what I send in send_packet. I guess I could make arr
very large just in case but I want to know what proper coding would dictate in this scenario.