Linux串口通信
as1_2 2017-03-02 04:37:46 用Linux编写了一段读写串口数据的程序,用232串口连接电脑USB转232的接口,用通信助手测试的时候,收发数据都没有问题。但是通过232-485转换器连接另外一个需要通信的仪器(该仪器是485的接口),发送数据的时候没有问题,但是接收数据的时候,每次都是只能接收前几个数据,后面的数据接收不了,比如接收的数据是68 36 47 74 00 00 00 68 93 06 69 7A A7 33 33 33 7D 16,但是只接收了68 36 47 或68 36 47 68 00,后面就没有任何其他的数据了。下面是串口部分的主要代码:
int set_Parity(int fd, int databits, int stopbits, int parity,struct termios options) {
//struct termios options;
options.c_cflag |= CLOCAL | CREAD;
options.c_cflag &= ~CSIZE;
switch (databits) /*设置数据位数*/
{
case 7:
options.c_cflag |= CS7;
break;
case 8:
options.c_cflag |= CS8;
break;
default:
// fprintf(stderr, "Unsupported data size\n");
return 0;
}
switch (parity) {
case 'n':
case 'N':
options.c_cflag &= ~PARENB; /* Clear parity enable */
options.c_iflag &= ~INPCK; /* Enable parity checking */
break;
case 'o':
case 'O':
options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/
options.c_iflag |= INPCK; /* Disnable parity checking */
break;
case 'e':
case 'E':
options.c_cflag |= PARENB; /* Enable parity */
options.c_cflag &= ~PARODD; /* 转换为偶效验*/
// options.c_iflag |= INPCK; /* Disnable parity checking */
break;
case 'S':
case 's': /*as no parity*/
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
break;
default:
//fprintf(stderr, "Unsupported parity\n");
return 0;
}
/* 设置停止位*/
switch (stopbits) {
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
//fprintf(stderr, "Unsupported stop bits\n");
return 0;
}
/* Set input parity option */
//if (parity != 'n')
//options.c_iflag |= INPCK;
tcflush(fd, TCIFLUSH);
options.c_cc[VTIME] = 10; /* 设置超时1 seconds*/
options.c_cc[VMIN] = 18; /* Update the options and do it NOW */
if (tcsetattr(fd, TCSANOW, &options) != 0) {
perror("SetupSerial 3");
return 0;
}
return 1;
}