繁体   English   中英

串行端口:读取数据问题,未读取完整数据

[英]Serial port : Read data problem, not reading complete data

我有一个应用程序,该应用程序通过PC1(Java App)通过串行端口发送数据,并在PC2(C ++ App)中读取数据。 我面临的问题是我的PC2(C ++ App)无法读取PC1发送的完整数据,即从我的PC1发送190个字节,但是PC2可以读取近140个字节,尽管我尝试读入一个循环。

以下是我的C ++应用程序的代码段

 /**Open the connection to serial port**/



serialfd = open( serialPortName.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);

 if (serialfd == -1)
 {
  /*
   * Could not open the port.
   */
  TRACE << "Unable to open port: " << serialPortName << endl;
 }
 else
 {
  TRACE << "Connected to serial port: " << serialPortName << endl;
  fcntl(serialfd, F_SETFL, 0);
 }



 /**Configure the Serial Port parameters**/

  struct termios options;

  /*
   * Get the current options for the port...
   */
  tcgetattr(serialfd, &options);

  /*
   * Set the baud rates to 9600...
   */
  cfsetispeed(&options, B38400);
  cfsetospeed(&options, B38400);

  /*
   * 8N1
   * Data bits - 8
   * Parity    - None
   * Stop bits - 1
   */
  options.c_cflag &= ~PARENB;
  options.c_cflag &= ~CSTOPB;
  options.c_cflag &= ~CSIZE;
  options.c_cflag |= CS8;

  /*
   * Enable hardware flow control
   */
  options.c_cflag |= CRTSCTS;

  /*
   *  Enable the receiver and set local mode...
   */
  options.c_cflag |= (CLOCAL | CREAD);

  // Flush the earlier data
  tcflush(serialfd, TCIFLUSH);

  /*
   *  Set the new options for the port...
   */
  tcsetattr(serialfd, TCSANOW, &options);


 **Now I am reading data**
  const int MAXDATASIZE = 512;
  std::vector<char> m_vRequestBuf; 
  char buffer[MAXDATASIZE];
  int totalBytes = 0;

  fcntl(serialfd, F_SETFL, FNDELAY);
  while(1) {
          bytesRead = read(serialfd, &buffer, MAXDATASIZE);
  if(bytesRead == -1)
  {
     //Sleep for some time and read again 
                  usleep(900000);
  }
  else
  {
      totalBytes += bytesRead;  
                  //Add data read to vector
                  for(int i =0; i < bytesRead; i++)
      {
   m_vRequestBuf.push_back(buffer[i]);
      }

                  int newBytesRead = 0;

                  //Now keep trying to read more data
      while(newBytesRead != -1)
      {
   //clear contents of buffer
   memset((void*)&buffer, 0, sizeof(char) * MAXDATASIZE); 
   newBytesRead = read(serialfd, &buffer, MAXDATASIZE);
   totalBytes += newBytesRead;

                        for(int j = 0; j < newBytesRead; j++)
   {
       m_vRequestBuf.push_back(buffer[j]);
   }
       }//inner while    
     break;
  } //while

Lateee响应,但是如果您以非规范模式读取,请考虑将VMIN设置为要读取的字节数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM