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,
가장 많이 본 글
-
PIC microprocessor에 대한 경험을 알려 드리고 선택에 도움이 되었으면 합니다. 저는 PIC을 접한지 꽤 되었는데 아직도 완벽 하다고는 생각지 않습니다. 너무나 종류도 많고 memory크기, interface도 다양해서 어떤...
-
PIC Peripheral Pin Select(PPS: 주변장치 Pin선택기능) PIC24 또는 32 Series 중에는 주변장치 pin을 program에서 select 할 수 있는 기능이 있는 chip들이 있습니다. HW design시 rou...
-
Development environment is more important than others. This is the stepping stone for success. 개발환경 구축이 무엇보다 중요 합니다. 첫단추를 잘 끼워야 하니까요. 개발...
댓글 없음:
댓글 쓰기