我有以下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 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。即使目标硬件实际传输了数据,我也无法接收任何数据。
怎么了?
最佳答案
read()
返回0表示文件结束条件。您应该进行检查,并在出现这种情况时跳出循环。
至于造成这种情况的原因-串行端口上的文件结束表明它已检测到挂断,这意味着DCD线路已掉线。
如果设备设置不正确,则可以在CLOCAL
中设置options.c_cflag
标志以忽略调制解调器控制线。
关于linux - 从串行端口读取失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1754621/