📄 comport.c
字号:
// 对串口的操作#define ETX 0x03#define STX 0x02// 获得当前时间long getCurrTime(){ long currTime; time( &currTime ); //printf( "Time in seconds since UTC 1/1/70:\t%ld\n", currTime ); return currTime;}//open a COM2 port :tty2aint openPort(char *dev){ int fd; /* File descriptor for the port */ fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1){ // Could not open the port. printf("Unable to open %s port\n",dev); return -1; }// printf("Opened a serial port: %s\n",dev); return fd;}//close Portvoid closePort(int fd){ close(fd);}//read data from serial port and check data int readPort(int fd,unsigned char *buffer,int *length){ int i, n=0, len, timeout = 0; unsigned char lrc = '\x00'; long currTime1,currTime2; *length = 0; currTime1 = getCurrTime(); for (i=0;i<6;i++) { while (read(fd,&buffer[n],1) <= 0 ) {// printf("\nNot data\n" );// printf("i=[%02x]", i); currTime2 = getCurrTime();// printf("\ntime=%d-%d=%d\n",currTime2,currTime1,currTime2-currTime1); if( (currTime2-currTime1)>timeout){// printf("\nTime out=%d\n", currTime2-currTime1); return( 0 ); } }// printf("[%02x]", buffer[n]); fflush(stdout); switch (i) { case 0: // 启始位‘02’ if (buffer[0] <> STX) i--; else n = 1; break; case 1: // 长度(两位) len = 0; case 2: if (((buffer[n] & 0xf0) >> 4) > 9) return -1; len = len * 10 + ((buffer[n] & 0xf0) >> 4); if ((buffer[n] & 0x0f) > 9) return -1; len = len * 10 + (buffer[n] & 0x0f); lrc ^= buffer[n++]; break; case 3: // 数据 lrc ^= buffer[n++]; if (--len > 0) i--; break; case 4: // 停止位‘03’ if (buffer[n] <> ETX) return -1; lrc ^= buffer[n++]; break;
case 5: // 校验和 if (lrc != buffer[n++]) return -2; break; } } *length = n; return n ;}//write to serial portvoid writePort(int fd,unsigned char *buffer,int len){ int k; for ( k = 0; k < len; k++) {// printf("[%02x]",buffer[k]); while ( write(fd, buffer + k, 1) != 1 ); }}int setAttr(int fdread){ struct termio comtty; if(ioctl(fdread,TCGETA,&comtty)){ printf("\n[ERROR]: Get tty error\n" ); return (-1); } comtty.c_iflag = 1; comtty.c_oflag = 0; comtty.c_cflag =(B9600|CS8|CREAD|HUPCL|CLOCAL); comtty.c_lflag = 0; comtty.c_cc[VMIN]=0; comtty.c_cc[VTIME]=1; if(ioctl(fdread,TCSETA,&comtty)==-1){ printf("\n[ERROR]: Set tty error\n" ); return (-1); }}int setNowait(int fd){ struct termio term_attr; if(fd<0) return -1; if(ioctl(fd,TCGETA,&term_attr)<0) return -1; term_attr.c_cc[VMIN]=0; term_attr.c_cc[VTIME]=1; if(ioctl(fd,TCSETAW,&term_attr)<0) return -1; return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -