가장 많이 본 글

이 블로그 검색

2018년 6월 4일 월요일

How to parse incoming command from a serial port.

Parsing serial receive buffer

    When an embedded system needs to receive commands from the host or from other devices, we have to identify what the command has been received and how many its arguments exist. Useful string functions in C can be used to fulfill this job and it is very simple.

With the following declarations, the parser function will work.

/**************************************************************/

#define  maxRxBufLength  200
#define  maxParLength  20
#define  maxParCount   20

char rx_data[maxRxBufLength];
char cmdString[maxParCount][maxParLength];
int  rx_count;

int cmdParser(void) {
    /* Extract each command string from rx_data ---------*/
    /* using string functions,  string to token : strtok() ---*/
    /* and string concatenation ------------------------------*/
    /* Returns argument count */

    char *ptr;
    char delimiters[] = ",:;/ \r\n"; // Specify delimiters here
    int parCount = 0;

    // add null at the end of the rx_data
    rx_data[rx_count] = '\0';

    // extract tokens from rx_data
    ptr = strtok(rx_data, delimiters);
    while(ptr != NULL) {
        cmdString[parCount][0] = '\0'; // Make empty string
        // strncat adds Null termination automatically
        strncat(cmdString[parCount++], ptr, maxParLength - 1);

        ptr = strtok(NULL, delimiters);

        /* check if cmdString overflows */
        if(parCount>= maxParCount) {

            break;
        }
    }

    return parCount;
}
/**************************************************************/

Example >

Before calling cmdParser(), the rx_data and the rx_count should be provided by RX interrupt or other means. 

If we have received data in the rx_data like,

rx_data[] = "SET ADCAVG 300 \r\n"

and then call cmdParser() something like

    rxParCount = cmdParser();

The result will be :

rxParCount = 3, 
cmdString[0] = SET\0,
cmdString[1] = ADCAVG\0,
cmdString[2] = 300\0,

댓글 없음:

댓글 쓰기