我正在使用termios用于读取/写入串行接口(interface)中配置的设备的 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", reserved = {0, 0, 1552337580}, c_ispeed = 9600, c_ospeed = 9600}
然后我可以使用写入功能向设备发送命令,但无法使用读取功能。运行 res = read(fd, &s, 1);
行后,代码卡住了,我没有得到任何响应(见下文)。有什么提示吗?
编辑:
//设置设备配置
block 如下:
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;
最佳答案
虽然在open的时候添加了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
如果串口没有数据,则会被阻塞。
关于c - 串行编程 - Termios。从设备读取 0x00 字节时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55122274/