我在读取串口数据时遇到了一些问题。我使用了以下代码实例,之前用过很多次都没有问题,但现在由于某些原因,我完全无法从串口读取任何数据。
我能够写入数据,接收端也正确接收到了数据,但是回复(已经正确发送)却无法接收(不,线缆都没问题;))
我用的代码打开串口如下:
fd = open("/dev/ttyUSB0", O_RDWR | O_NONBLOCK | O_NOCTTY);
if (fd == -1)
{
Aviso("Unable to open port");
return (fd);
}
else
{
//Get the current options for the port...
bzero(&options, sizeof(options)); /* clear struct for new port settings */
tcgetattr(fd, &options);
/*-- Set baud rate -------------------------------------------------------*/
if (cfsetispeed(&options, SerialBaudInterp(BaudRate))==-1)
perror("On cfsetispeed:");
if (cfsetospeed(&options, SerialBaudInterp(BaudRate))==-1)
perror("On cfsetospeed:");
//Enable the receiver and set local mode...
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB; /* Parity disabled */
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE; /* Mask the character size bits */
options.c_cflag |= SerialDataBitsInterp(8); /* CS8 - Selects 8 data bits */
options.c_cflag &= ~CRTSCTS; // disable hardware flow control
options.c_iflag &= ~(IXON | IXOFF | IXANY); // disable XON XOFF (for transmit and receive)
options.c_cflag |= CRTSCTS; /* enable hardware flow control */
options.c_cc[VMIN] = 0; //min carachters to be read
options.c_cc[VTIME] = 0; //Time to wait for data (tenths of seconds)
//Set the new options for the port...
tcflush(fd, TCIFLUSH);
if (tcsetattr(fd, TCSANOW, &options)==-1)
{
perror("On tcsetattr:");
}
PortOpen[ComPort] = fd;
}
return PortOpen[ComPort];
端口初始化后,我通过简单的写入命令向其写入一些内容...
int nc = write(hCom, txchar, n);
在这里,hCom是文件描述符(并且它没问题),这个方法可以正常工作。但是...当我之后进行读取操作时,会从errno返回一个“资源暂时不可用”的错误。
我尝试使用select来检测文件描述符是否有可读内容......但它总是超时!
我按如下方式读取数据:
ret = read(hCom, rxchar, n);
我总是收到 EAGAIN 错误,但不知道为什么。
更新:
硬件没问题!我可以看到串口上有入站数据,因为我做了一个调试电缆来在另一个终端上读取正在发生的事情。所以...
我知道非阻塞应该如何工作。我的问题是... 为什么什么都没有被读取!同样的设置在 Windows 上运行良好,所以所有硬件都正常..。
这让我抓狂!我敢肯定这是极其简单的问题!我甚至尝试去掉 O_NONBLOCK,看看什么时候会收到数据... 但没有任何反应...