串行编程 - Termios。从设备读取0x00字节时卡住

问题描述 投票:0回答:1

我正在使用termios API来读取/写入串行接口中配置的设备。我正在使用的代码如下:

// Open serial interface
const char *device = "/dev/ttyS0";
int fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1)
  printf( "failed to open port\n" );

fcntl(fd, F_SETFL, 0);

// Get current configuration of serial interface
struct termios config;
tcgetattr(fd, &config);

// Set configuration of device
...
...
//

// Apply configuration to descriptor
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &config);

// Send order to device
unsigned char order[2];
int res;
unsigned char m = 0x00;
unsigned char s = 0x00;

order[0] = 0xc1; // Byte 193
order[1] = m;

res = write(fd, &order[0], 2);
if (res != 2)
  return -1;

res = read(fd, &s, 1);
if ((res != 1) || (res == -1))
  return -1;

串行端口打开正确,设备也已正确配置。如果我在gdb中打印配置(config),我会得到以下内容:

{c_iflag = 8240,c_oflag = 0,c_cflag = 3251,c_lflag = 0,c_cc =“\ 003 \ 034 \ 177 \ 025 \ 004 \ 000 \ 000 \ 000 \ 021 \ 023 \ 032 \ 000 \ 000 \ 000 \ 000 \ 026 \ 001 \ 000 \ 000 \ 000 \ 033 [\ 000 \ 000 \ 000 \ 000 \ 000 \ 000DCAB @ P \ 000 \ 000HY \ 000“,保留= {0,0,1552337580},c_ispeed = 9600,c_ospeed = 9600}

然后我可以使用write函数向设备发送命令,但我不能使用read函数。运行行res = read(fd, &s, 1);后代码卡住了,我没有得到任何响应(见下文)。任何提示?

enter image description here

编辑:

// Set configuration of device区块如下:

cfsetispeed(&config, B9600);
cfsetospeed(&config, B9600);

config.c_cflag &= ~CSIZE;
config.c_cflag |= CS8;    

config.c_cflag &= ~CSTOPB;
config.c_cflag |= 0;

config.c_cflag &= ~PARENB;
config.c_cflag &= ~PARODD;
config.c_cflag |= (0 | 0);

config.c_cflag |= (CLOCAL | CREAD);
config.c_iflag |= (INPCK | ISTRIP);

config.c_oflag = 0;
config.c_lflag = 0;

config.c_cc[VMIN]=1;
config.c_cc[VTIME]=0;
c unix serial-port posix termios
1个回答
0
投票

尽管在开放时添加了O_NONBLOCK,但fcntl(fd, F_SETFL, 0)在下面被称为阻塞模式。

fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
fcntl(fd, F_SETFL, 0);   // The O_NONBLOCK flag is overwritten

如果串口上没有数据,则会被阻塞。

© www.soinside.com 2019 - 2024. All rights reserved.