为什么我无法从串口读取数据?

Why cannot I read data from a serial port?

我遇到了以下问题:我希望读取传送到 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: ."
  }

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

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);