gpt4 book ai didi

使用 termios.h 配置阻止 Linux 串行端口

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:59 27 4
gpt4 key购买 nike

我正在编写一个嵌入式 Linux 应用程序,它 (1) 打开与另一台设备的串行连接,(2) 发送已知命令,(3) 检查端口中的传入字符(响应),直到检测到预期的响应短语或字符, (4) 重复步骤 2 和 3,直到发送一系列命令并收到响应, (5) 然后关闭端口。

我的应用程序会经历上述序列的一些循环,时不时地等待响应(读取)时突然通信停止并且我的软件由于我的内置超时逻辑而出现故障.

我的端口配置中是否有任何内容会导致端口因发送特定字节而被阻塞(可能是由于电噪声)?

这是我打开端口的方式(通过 termios.h 显示配置):

struct termios options;

fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) {
debug() << "Port open failed!"
return FAIL;
}
debug() << "Port Opened Successful"
fcntl(fd, F_SETFL, 0); // This setting interacts with VMIN and VTIME below

// Get options
tcgetattr(fd, &options);

// Adjust Com port options

options.c_cflag |= (CLOCAL | CREAD); // Program will not "own" port, enable reading on port
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Sets RAW input mode (does not treat input as a line of text with CR/LF ending)
options.c_oflag &= ~ OPOST; // Sets RAW ouput mode (avoids newline mapping to CR+LF characters)
options.c_iflag &= ~(IXON | IXOFF | IXANY); // Turns off SW flow c

options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;

// Set options
tcsetattr(fd, TCSANOW, &options);

//return fd;
return SUCCEED;

我不明白为什么通信会突然停止,然后在我为我的设备循环供电时消失。谢谢大家!

更多信息 - 这是我的读写函数:

int Comm::Receive(unsigned char* rBuf)
{
int bytes;
ioctl(fd, FIONREAD, &bytes);
if (bytes >= 1)
{
bytes = read(fd, rBuf, 1);
if (bytes < 0)
return READ_ERR;
return SUCCEED;
}
else
return NO_DATA_AVAILABLE;
}


int Comm::Send(int xCt, unsigned char* xBuf)
{
int bytes;
if (fd == -1)
return FAIL;
bytes = write(fd, xBuf, xCt);
if (bytes != xCt)
return FAIL;
else
return SUCCEED;
}

最佳答案

欢迎来到串行端口的乐趣...

想法 1:用 select () 包裹你的 read 调用

想法 2:取消设置 tcsetattr 中的 ICANON 标志,并设置一个 VTIME 属性用于故意超时(然后,很明显,处理它)

想法 3:关于串行通信,没有什么是完美的。

关于使用 termios.h 配置阻止 Linux 串行端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20437476/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com