YOCTO平台下RS232 read()返回0问题求助
问题:RS232通信接收端
read()提前返回0 我在两块不同板卡上分别部署发送端和接收端程序,通过RS232链路通信。两端RS232端口配置完全一致,发送端每2秒发送一次递增的计数器数值。出现的异常是:接收端收到少量数据包后,read()返回0且errno为"Success",发送端全程无报错。调整发送延迟后,问题出现的时机有变化:延迟设为1秒时,9-10次消息后触发;设为2秒时,4-5次后触发。
以下是串口配置代码:
int Set_RS232_Params(int fd, speed_t speed) { int error = 0; int v_ret = -1; struct termios attribs; /*get attributes */ v_ret = tcgetattr(fd, &attribs); if (v_ret != 0) { error = 1; printf("ERROR\n"); } else { error = 0; } /*set output baudrate */ if (error == 0) { v_ret = -1; v_ret = cfsetospeed(&attribs, speed); if (v_ret != 0) { error = 1; printf("ERROR\n"); } } /*set input baudrate */ if (error == 0) { v_ret = -1; v_ret = cfsetispeed(&attribs, speed); if (v_ret != 0) { error = 1; printf("ERROR\n"); } } /*modify and save attributes */ if (error == 0) { /*CFLAG */ attribs.c_cflag &= ~PARENB; attribs.c_cflag &= ~CSTOPB; attribs.c_cflag &= ~CSIZE; attribs.c_cflag |= CS8; attribs.c_cflag &= ~CRTSCTS; attribs.c_cflag |= CREAD; attribs.c_cflag |= CLOCAL; /*LFLAG */ attribs.c_lflag &= ~ECHO; attribs.c_lflag &= ~ECHOE; attribs.c_lflag &= ~ECHONL; attribs.c_lflag &= ~ICANON; attribs.c_lflag &= ~ISIG; /*IFLAG */ attribs.c_iflag &= ~(IXON | IXOFF | IXANY); attribs.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL); /*OFLAG */ attribs.c_oflag &= ~OPOST; attribs.c_oflag &= ~ONLCR; /*VMIN and VTIME */ attribs.c_cc[VMIN] = 0; attribs.c_cc[VTIME] = 0; /*save attributes */ v_ret = -1; v_ret = tcsetattr(fd, TCSANOW, &attribs); if (v_ret != 0) { error = 1; printf("ERROR\n"); } } return error; }
排查建议
- 调整VMIN/VTIME参数:当前配置
VMIN=0且VTIME=0属于非阻塞模式,read()会立即返回,无数据时直接返回0。如果业务需要等待数据,建议修改为VMIN=1(至少读取1字节)、VTIME=10(超时1秒),让read()等待数据或超时后再返回。 - 排查硬件链路问题:检查RS232线缆的TX/RX/GND引脚是否正确对接,线缆是否存在破损、干扰;可以用串口助手替换一端程序,验证链路本身的稳定性。
- 添加发送端数据flush操作:发送数据后调用
tcdrain(fd),等待发送缓冲区数据全部发送完成,避免数据滞留在发送端导致接收端无数据可读。 - 检查接收端read逻辑:在
read()返回0时,调用ioctl(fd, FIONREAD, &bytes_available)查询串口缓冲区中未读取的字节数,确认是否真的无数据到达。 - 验证配置是否生效:调用
tcsetattr后,重新调用tcgetattr读取端口属性,确认所有配置项都被正确应用,避免部分板卡驱动存在配置不生效的问题。
内容的提问来源于stack exchange,提问作者H2O
相关产品推荐
相关产品推荐

