我在从以下方式打开的串口读取一些数据时遇到了一些麻烦.我已经多次使用这个代码实例并且一切正常,但现在,由于某些原因我无法弄清楚,我完全无法从串口读取任何内容.
我能够在另一端写入并正确接收所有内容,但是从未收到回复(正确发送)(不,电缆都可以;))
我用来打开串口的代码如下:
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得到一个“暂时不可用的资源”错误.
我测试了选择以查看文件描述符何时读取…但它总是超时!
我读了这样的数据:
ret = read(hCom, rxchar, n);
我总是得到一个EAGAIN,我不知道为什么.
更新:
硬件工作正常!我可以看到串口上有入站数据,因为我已经制作了一条调试电缆来读取在另一个终端上发生的事情.所以…
我知道非阻塞应该做什么.我的问题是……为什么不读任何东西!相同的设置在Windows上工作正常,所以所有硬件都工作正常…
这让我疯了!我确定这很简单!我甚至试图摆脱O_NONBLOCK,看看我什么时候收到东西……但没有……
解决方法:
EAGAIN Non-blocking I/O has been
selected using O_NONBLOCK and no data
was immediately available for reading.
标签:c-3,linux,serial-port
来源: https://codeday.me/bug/20191001/1839072.html