- 论坛徽章:
- 0
|
两台linux机器通过串口相连,send端只负责发,recv端只负责收,(每隔两秒传输7个字节),传输过程中偶尔会出现传输的数据不对的情况。
example:
send buf
p[0] = 1
p[1] = 17
p[2] = 88
p[3] = 4
p[4] = 42 //注意这里
p[5] = 5
p[6] = -85
recv buf
p[0] = 1
p[1] = 17
p[2] = 88
p[3] = 4
p[4] = 45 //注意这里
p[5] = 5
p[6] = -85
很是头疼啊,不知道为什么会出现这种现象。
出错的几率随机,有时候传输20-30次才出错一次,有时候传输几次就出错一次。
出错的位置随机,有时候是第4个字节位置错误,有时候是第5个字节位置出错。
但是出错的时候有个共同点就是send端发出来的数据和recv端收到的数据相差3,如:send端p[4]=42,recv端p[4]=45。
现在不知道该如何定位,到底是硬件问题还是程序问题?
附:设置串口函数
- int open_device(int mode)
- {
- int ret;
- int fd = open("/dev/ttyS1", mode | O_NOCTTY | O_NONBLOCK);
- if (-1 == fd)
- {
- perror("open serial port ttyS0 failed");
- return -1;
- }
- struct termios options;
- ret = tcgetattr(fd, &options);
- if (0 != ret)
- {
- perror("tcgetattr failed");
- close(fd);
- return -1;
- }
- #if 1
- cfsetispeed(&options, B115200);
- cfsetospeed(&options, B115200);
- #else
- //与波特率无关,2400一样出错
- cfsetispeed(&options, B2400);
- cfsetospeed(&options, B2400);
- #endif
- options.c_cflag &= ~PARENB;
- options.c_cflag &= ~CSTOPB;
- options.c_cflag &= ~CSIZE;
- options.c_cflag |= CS8;
- options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
- options.c_oflag &= ~OPOST;
- ret = tcsetattr(fd, TCSANOW, &options);
- if (0 != ret)
- {
- perror("tcsetattr failed");
- close(fd);
- return -1;
- }
- tcflush(fd, TCIOFLUSH);
- fcntl(fd, F_SETFL, O_NONBLOCK);
- return fd;
- }
复制代码 |
|