linux – 从串口读取失败
发布时间:2020-12-26 07:18:03 所属栏目:Linux 来源:网络整理
导读:我有以下C程序: #include fcntl.h#include termios.h#include stdio.hint main(){ int fd = open("/dev/ttyS0",O_RDWR | O_NOCTTY | O_NONBLOCK); if(fd 0) { perror("Could not open device"); } printf("Device openedn"); struct termios options; tcge
我有以下C程序: #include <fcntl.h> #include <termios.h> #include <stdio.h> int main() { int fd = open("/dev/ttyS0",O_RDWR | O_NOCTTY | O_NONBLOCK); if(fd < 0) { perror("Could not open device"); } printf("Device openedn"); struct termios options; tcgetattr(fd,&options); cfmakeraw(&options); cfsetispeed(&options,B19200); cfsetospeed(&options,B19200); tcsetattr(fd,TCSANOW,&options); char txpacket[] = {0x23,0x06,0x00,0xdd,0xf9}; ssize_t written = write(fd,txpacket,sizeof(txpacket)); printf("Written %d bytesn",written); printf("Starting to wait for target to respondn"); while(1) { fd_set readset; FD_ZERO(&readset); FD_SET(fd,&readset); int nCount = select(fd + 1,&readset,NULL,NULL); if(nCount > 0) { if(FD_ISSET(fd,&readset)) { int i; char buffer[128]; ssize_t bytesread = read(fd,buffer,sizeof(buffer)); printf("Received %d bytesn",bytesread); for(i = 0; i < bytesread; i++) { printf(" %02x",buffer[i]); } } } } } 该程序打开串行设备/ dev / ttyS0,向其写入一系列数据并开始监听响应.我得到以下输出: Device opened Written 6 bytes Starting to wait for target to respond Received 0 bytes Received 0 bytes Received 0 bytes Received 0 bytes Received 0 bytes Received 0 bytes ... 并且该应用程序消耗100%的CPU.即使目标硬件实际传输它,我也无法接收任何数据. 怎么了? 解决方法read()返回0表示文件结束条件.如果发生这种情况,你应该检查它并突破循环.至于导致什么 – 串口上的文件结尾表明它已检测到挂断,这意味着DCD线路已被丢弃. 如果您的设备没有正确设置它们,您可以在options.c_cflag中设置CLOCAL标志以忽略调制解调器控制线. (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |