清除串行端口的缓冲区 [英] Clearing the serial port's buffer

查看:290
本文介绍了清除串行端口的缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的功能看起来像打开串口(使用Ubuntu 12.04):

This is what my function looks like to open the serial port (using 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,&安培;期权); 将解决这个问题,通过冲洗初始化端口之前的IO缓冲区,但没有这样的运气。任何见解?

What the problem is, is that when I run this program and if my serial device was already plugged in, the buffer has content in it. I need a way to clear the buffer before I start reading from it. I thought using tcsetattr(fd, TCSAFLUSH, &options); would fix this problem, by flushing the IO buffers before initializing the port, but no such luck. Any insight?

推荐答案

我想我想通了。出于某种原因,我需要冲洗前添加延迟。返回前将这两行 FD 显得的已经做的伎俩:

I think I figured it out. For some reason, I need to add a delay before flushing. These two lines added before returning fd seem to have done the trick:

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

这篇关于清除串行端口的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆