为什么不能从串口读取数据?

问题描述

我遇到了以下问题:我希望在 linux 上读取进入我的串行端口的数据。数据从具有标准串行设置的外部设备发送。我确信外部设备发送了它们,这已经被检查过了。 但是,在 linux 上我只能读取一个空字节。我设置错了什么?

我的设置如下:

serial = open(_name,O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(serial,F_SETFL,0);
tcgetattr(_serial,&_options);
options.c_ispeed = _baudrate;
options.c_ospeed = _baudrate;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_iflag &= ~(INPCK|PARMRK|ISTRIP); 
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CREAD |CLOCAL ;
tcflush(serial,TCIFLUSH);
tcsetattr(serial,TCSANow,&options);

我的读取函数如下所示:

  char byte = 'a';
  int datasize = 0;
  while (byte != '\n') {
    datasize = read(serial,&byte,sizeof(byte));
    std::cout<< "Read:"<< byte <<".\t";   // this line always prints: "Read: ."
  }

解决方法

我不确定发生了什么,但以下设置终于奏效了。我会与你分享,因为我在 Stackoverflow 上得到了很多帮助:

serial = open(name.c_str(),O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(serial,F_SETFL,0);

tcgetattr(serial,&options);
options.c_ispeed = _baudRate;
options.c_ospeed = _baudRate;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_iflag &= ~(INPCK|PARMRK|ISTRIP); 
options.c_cflag &= ~CSTOPB;

options.c_cflag |= CREAD |CLOCAL ; 
options.c_cc[VMIN]=0;
options.c_cc[VTIME]=10;

options.c_cflag &= ~CRTSCTS; // turn off hardware flow control
options.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off sowftware flow control
options.c_lflag &= ~ICANON;
options.c_lflag &= ~ISIG;
options.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes
options.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
options.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed

tcflush(serial,TCIFLUSH);
tcsetattr(serial,TCSANOW,&options);