C read()函数经常被阻塞,尤其是在Gpio引脚(tx / rx)上没有任何连接的情况下,但是我只是希望它在没有连接的情况下会自行停止,在有电线的情况下也一样连接,但没有要读取的数据,但是直到我强迫它完成后,它才被阻塞。
打开
fd = open("/dev/serial0", O_RDWR | O_NDELAY | O_NOCTTY | O_NONBLOCK);
阅读
n = read( fd, value, 1 );
if (n < 0) {
printf ( "Error = %s\n", strerror( errno ) );
}
else if (n == 0) {
printf ( "Read Nothing...\n");
}
设置属性
int setAttr(int fd)
{
//Read the configureation of the port
struct termios options;
tcgetattr( fd, &options );
//Set Baud Rate
cfsetispeed( &options, B9600 );
cfsetospeed( &options, B9600 );
//Setting other Port Stuff
options.c_cflag &= ~PARENB; /*Make 8n1 */
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE; /* Mask the character size bits */
options.c_cflag |= CS8; /* Select 8 data bits */
options.c_cflag &= ~CRTSCTS; /* No flow control */
options.c_cc[VMIN] = 0; /*READ doesn't block */
options.c_cc[VTIME] = 1; /* 0.1 seconds read timout */
options.c_cflag |= CREAD | CLOCAL; /* Turn on READ & ignore crtl lines */
//Make raw
cfmakeraw(&options);
//Flush port, then applies attributes
tcflush(fd, TCIOFLUSH);
return tcsetattr( fd, TCSANOW, &options );
}
答案 0 :(得分:1)
对于仅具有tx / rx引脚的UART端口,没有明显的“未连接”状态。为了获得所需的功能,端口将需要DCE / DTR引脚,并且必须从termios设置中删除CLOCAL
标志(忽略调制解调器控制线)。
答案 1 :(得分:0)
我只是在open()之后添加以下代码,当未连接tx / rx引脚时,它不再受阻。可能是open()之后端口被阻塞了。
if (fd == -1)
{
/*
* Could not open the port.
*/
perror("open_port: Unable to open /dev/serial0 - ");
}
else fcntl(fd, F_SETFL, O_NONBLOCK);