linux串口文件打不开,linux – 从串口读取失败

本文介绍了一个C程序,用于通过串口与外部设备通信。程序能够成功打开串口并向其发送数据,但在等待接收响应时出现问题,导致应用程序占用过高CPU且无法接收到任何数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我有以下C程序:

#include

#include

#include

int main()

{

int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);

if(fd < 0)

{

perror("Could not open device");

}

printf("Device opened\n");

struct termios options;

tcgetattr(fd, &options);

cfmakeraw(&options);

cfsetispeed(&options, B19200);

cfsetospeed(&options, B19200);

tcsetattr(fd, TCSANOW, &options);

char txpacket[] = {0x23, 0x06, 0x00, 0x00, 0xdd, 0xf9};

ssize_t written = write(fd, txpacket, sizeof(txpacket));

printf("Written %d bytes\n", written);

printf("Starting to wait for target to respond\n");

while(1)

{

fd_set readset;

FD_ZERO(&readset);

FD_SET(fd, &readset);

int nCount = select(fd + 1, &readset, NULL, 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 bytes\n", 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.即使目标硬件实际传输它,我也无法接收任何数据.

怎么了?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值