Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

c++ - Why cannot I read data from a serial port?

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 != '
') {
    datasize = read(serial, &byte, sizeof(byte));
    std::cout<< "Read:"<< byte <<".";   // this line always prints: "Read: ."
  }
question from:https://stackoverflow.com/questions/66061664/why-cannot-i-read-data-from-a-serial-port

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...