我在通过以下方法打开的串行端口读取一些数据时遇到了一些故障。 我多次使用这个代码实例,一切都很正常,但是现在因为一些原因我不知道,所以我不能从串行端口读取任何东西。
我可以在另一端写下所有的内容并正确接收,但没有收到回复(正确发送)。不,电缆也可以; ) )
打开串行端口的代码如下。
FD=open((/dev/TTYUSB0),O_RDWR | O_NONBLOCK | O_NOCTTY );
if (软盘==-1 ) ) ) ) )。
{
视听端口(unabletoopenport );
返回(软盘;
}
else
{
//getthecurrentoptionsfortheport .
Bzero(options,sizeof ) options );/* clearstructfornewportsettings * /
t getattr (软盘,选项);
/---- set baudrate-------------------------- -请参阅
(if (可选,串行总线)总线(=-1 ) ) ) ) ) ) 652
perror(oncfsetispeed: );
(if (可选,串行总线)总线(=-1 ) ) ) ) ) ) 652
perror(oncfsetospeed: );
//enablethereceiverandsetlocalmode .
options.c_cflag|=(clocal|cread;
options.c_cflag=~PARENB;/*禁用parity * /
options.c_cflag=~CSTOPB;
options.c_cflag=~CSIZE;/*掩码the character size bits * /
options.c _ cflag|=serialdatabitsinterp (8;/* cs8-selects 8数据位* /
options.c_cflag=~CRTSCTS;//禁用硬件流程控制
options.c _ iflag=~(ixon ); //disablexonxoff (前端干扰) )。
options.c_cflag |=CRTSCTS;/*启用硬件流程控制* /
options.c_cc[VMIN]=0; //min kwdsw to be read
options.c_cc[VTIME]=0; //timetowaitfordata (tenthsofseconds ) )。
//Set the new options for the port .
tflush(FD,TCIFLUSH );
if (tcsetattr (软盘,TCSANOW,选项)==-1 ) ) )。
{
perror(ontcsetattr: );
}
PortOpen[ComPort]=fd;
}
return PortOpen[ComPort];
初始化端口后,我用简单的写命令给你写了东西…
intNC=write(hcom,txchar,n );
其中hCom是文件描述符(并且没关系),而且,正如我所说的那样,是有效的。但是……我后来读的时候,我从errno那里得到了“暂时不可用资源”的错误。
我测试了选择以确认什么时候读取文件描述符…但是它总是超时!
我读了这样的数据:
ret=read(hcom,rxchar,n );
我总是得到EAGAIN。 我不知道为什么。
更新:
硬件工作正常。 可以看到串行端口上有入站数据。 因为我们制造了一条调试电缆来读取另一个终端上发生的事情。 所以…
我知道无阻塞应该做什么。 我的问题是……为什么什么都不读! 相同的设置在Windows上正常运行,所以所有硬件都正常运行…
这让我发疯了! 我觉得这很简单! 我甚至试图摆脱O_NONBLOCK。 看看我什么时候收到了什么……但是没有……
解决方法:
EAGAIN Non-blocking I/O has been
selectedusingo _ nonblockandnodata
wasimmediatelyavailableforreading。
标签: c-3、linux、串行端口
资料来源: https://codeday.me/bug/2019 1001/1839072.html