gpt4 book ai didi

清除串口缓冲区

转载 作者:IT王子 更新时间:2023-10-29 00:22:32 28 4
gpt4 key购买 nike

这是我打开串口的函数(使用 Ubuntu 12.04):

int open_port(void)
{
int fd; /* File descriptor for the port */

fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);

if (fd == -1)
{
// Could not open the port.
perror("open_port: Unable to open /dev/ttyUSB0 - ");
}
else
fcntl(fd, F_SETFL, 0);

struct termios options;

tcgetattr(fd, &options);
//setting baud rates and stuff
cfsetispeed(&options, B19200);
cfsetospeed(&options, B19200);
options.c_cflag |= (CLOCAL | CREAD);
tcsetattr(fd, TCSANOW, &options);

tcsetattr(fd, TCSAFLUSH, &options);

options.c_cflag &= ~PARENB;//next 4 lines setting 8N1
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;

//options.c_cflag &= ~CNEW_RTSCTS;

options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //raw input

options.c_iflag &= ~(IXON | IXOFF | IXANY); //disable software flow control

return (fd);
}

问题是,当我运行这个程序时,如果我的串行设备已经插入,缓冲区中就有内容。在开始读取缓冲区之前,我需要一种清除缓冲区的方法。我认为使用 tcsetattr(fd, TCSAFLUSH, &options); 可以解决这个问题,方法是在初始化端口之前刷新 IO 缓冲区,但没有这样的运气。有什么见解吗?

最佳答案

我想我明白了。出于某种原因,我需要在冲洗前添加延迟。在返回 fd 之前添加的这两行 似乎 已经完成了这个技巧:

  sleep(2); //required to make flush work, for some reason
tcflush(fd,TCIOFLUSH);

关于清除串口缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013387/

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