0

I have faced the following problem: I wish to read data comming to my serial port on linux. Data are send from an external device with standard serial settings. I'm sure that the external device sends them, that has been already checked. However, on linux all i can read is an empty byte. What am I setting wrong?

My settings looks like that:

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

my read function looks like that:

  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: ."
  }
user
  • 95
  • 1
  • 9
  • 1
    Could you try adding `<< std::flush` at the end of your `std::cout` call? (Probably not the issue if you say it prints "Read: ." though...) – m88 Feb 05 '21 at 10:40
  • I added std::flush and got the data. But at the same time I modifed the settings as well.. It's hard to say what really happened. thank you :) – user Feb 05 '21 at 10:53
  • 1
    If you want to read a line terminated by '\n', then you could let the OS do the work for you (more efficiently) by using canonical mode. See https://stackoverflow.com/questions/57152937/canonical-mode-linux-serial-port/57155531#57155531 BTW your method of setting the baudrates is not portable; instead use cfsetospeed() and cfsetispeed(). – sawdust Feb 05 '21 at 20:05

1 Answers1

1

I'm not sure what has happened but the following settings finally worked. I will share it with you as I got a lot of help here on 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);
user
  • 95
  • 1
  • 9