后来看到一个帖子说串口的读取操作是七层网络模型中的物理层操作,在其之上如果要实现对于帧的完整接收就不仅仅是读取串口数值那么容易。因为串口只是接收数据,不会判断一个完整的帧数据是否到来,而是根据数据传输是否终止。如果数据传输中止,则给系统读的信息,调用read()读取数据。但是完整的帧数据是上层需要的,底层不会处理。这样就需要上层来控制完整帧的接收。
int Read_Com3(unsigned char * Data) { #define TTY_READ_SIZE 8 short int length=0; unsigned char route; unsigned char data[256]; unsigned char *p_data = data; unsigned char start; struct timeval tv = {8, 0}; fd_set serialfd; unsigned int u32Ret = FALSE; unsigned char u8ReadSize; FD_ZERO(&serialfd); FD_SET(fd3,&serialfd); do{ u32Ret = select(fd3 + 1,&serialfd,NULL,NULL,&tv)) if(u32Ret < 1) { break; } u32Ret = FD_ISSET(fd3, &serialfd) ; if(u32Ret < 1) { break; } bzero(data, 256); #if 0 length = read(fd3, data, 256); #else while(1) { u8ReadSize = read(fd3, p_data, TTY_READ_SIZE); if(TTY_READ_SIZE != u8ReadSize) { length += u8ReadSize; break; } p_data += TTY_READ_SIZE; length += TTY_READ_SIZE; } #endif #ifdef DEBUG printf("\n"); printf("recv data downline: "); for(i=0; i<length; i++) printf(" 0x%x ",data[i]); printf("\n"); printf("the length of data: %d\n",length); #endif if(length > 0) { u32Ret = length; } else { u32Ret = FALSE; //error handle } }while(0); tcflush(fd3,TCIOFLUSH); //clear the rest of the data in the fd3 return u32Ret; }
int Read_Com3(unsigned char * Data) { #define READ_DATA_SIZE 256 unsigned char u8CycleTime = 0; short int length=0; unsigned char route; unsigned char data[256]; unsigned char *p_data = data; unsigned char start; unsigned char u8ReadSize; unsigned char u8Ret = FALSE; struct timeval tv = {.tv_sec = 10, .tv_usec = 0}; do{ if(FALSE == is_ready_read(fd3, &tv)) break; bzero(data, 256); while(1) { u8ReadSize = read(fd3, p_data, READ_DATA_SIZE); if(READ_DATA_SIZE != u8ReadSize) { length += u8ReadSize; p_data += u8ReadSize; tcflush(fd3,TCIOFLUSH); //clear the rest of the data in the fd3 if(TRUE == judge(&start, data, length)) { //store the number length = length - start; /*===Copy the data after A===*/ memcpy(Data, &data[start],length); u8Ret = length; break; } u8CycleTime++; if(u8CycleTime & 0x11) { break; } tv.tv_sec = 1; tv.tv_usec = 0; if(FALSE == is_ready_read(fd3, &tv)) { break; } else { printf_str_int("####/***read continue*****/####", TRUE); continue; } } else { p_data += READ_DATA_SIZE; length += READ_DATA_SIZE; } } printf_str_int("judeg_end", NULL); } while(0); //tcflush(fd3,TCIOFLUSH); //clear the rest of the data in the fd3 return u8Ret; }
http://justwinit.cn/post/2856/