文档介绍:串口通信协议实现 2 串口通信协议实现 如果青春的时光在闲散中度过, 那么回忆岁月将是一场凄凉的悲剧。杂草多的地方庄稼少, 空话多的地方智慧少。即使路上没有花朵, 我仍可以欣赏荒芜。这几天, 由于长春门检系统项目的需要, 涉及到了读卡器信息的串口读取, 所以在 Linux 下串口信息的读取有了一点心得体会。 1. 打开串口与其他的关于设备编程的方法一样,在 Linux 下,操作、控制串口也是通过操作起设备文件进行的。在 Linux 下, 串口的设备文件是/dev/ttyS0 或/dev/ttyS1 等。因此要读写串口,我们首先要打开串口: char *dev = "/dev/ttyS0"; // 串口 1 int fd= open( dev, O_RDWR ); //| O_NOCTTY | O_NDELAY if (-1 == fd) { perror("Can't Open Serial Port"); return -1; } else return fd; 2. 设置串口速度打开串口成功后,我们就可以对其进行读写了。首先要设置串口的波特率: int speed_arr[] ={ B38400, B19200, B9600, B4800, B2400, B1200, B300, B38400, B19200, B9600, B4800, B2400, B1200, B300, }; int name_arr[] = {38400, 19200, 9600, 4800, 2400, 1200, 300, 38400, 19200, 9600, 4800, 2400, 1200, 300, }; void set_speed(int fd, int speed){ int i; int status; struct termios Opt; tcgetattr(fd, &Opt); for ( i= 0;i< sizeof(speed_arr) / sizeof(int); i++) { if (speed == name_arr[i]) { tcflush(fd, TCIOFLUSH); cfsetispeed(&Opt, speed_arr[i]); cfsetospeed(&Opt, speed_arr[i]); status = tcsetattr(fd, TCSANOW, &Opt); if (status != 0){ perror("tcsetattr fd"); return; } tcflush(fd,TCIOFLUSH); }}} 3. 设置串口信息这主要包括:数据位、停止位、奇偶校验位这些主要的信息。/** ****@brief 设置串口数据位,停止位和效验位****@param fd 类型 int 打开的串口文件句柄****@param databits 类型 int 数据位取值为7 或者 8 ****@param stopbits 类型 int 停止位取值为 1 或者 2 ****@param parity 类型 int 效验类型取值为 N,E,O,,S */ int set_Parity(int fd,int databits,int stopbits,int parity) { struct termios options; if( tcgetattr( fd,&options) != 0){ perror("SetupSerial 1"); return(FALSE); } &= ~CSIZE; &= ~(ICANON | ECHO | ECHOE | ISIG); /*Input*/ &= ~OPOST; /*Output*/ switch (databits) /* 设置数据位数*/ { case 7: |= CS7; break; case 8: |= CS8; break; default: fprintf(stderr,"Unsupported data size\n"); return (FALSE); } switch (parity) { case 'n': case 'N': &= ~PARENB; /* Clear parity enable */ &= ~INPCK; /* Enable parity checking */ break; case 'o': case 'O': |= (PARODD | PARENB); /* 设置为奇效