0

我遇到了以下问题:我希望在 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: ."
  }
4

1 回答 1

0

我不确定发生了什么,但以下设置终于奏效了。我将与您分享它,因为我在 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);
于 2021-02-05T10:51:38.497 回答