2015-04-03 23 views
0

通过QSerialPort将arduino和我的Qt应用程序进行通信时出现问题。我有一个监听信号告诉我什么时候有数据可以从Arduino中读取。我希望步进电机在碰到限位开关之前已经执行的步数值,因此只有一个简单的整数,例如“2005”。当数据可供阅读时,有时候我会用“200”和“5”得到两个单独的读数。很明显,当我解析数据时,这会让我感到困惑,因为它会将它记录为两个数字,这两个数字都比预期的数字小得多。使用QSerialPort从Arduino打印到Qt的通信问题

我该如何解决这个问题,而不需要在睡眠或QTimer中允许多一点时间让数据从arduino进入?注意:我的程序不是多线程的。

例Qt代码:

//Get the data from serial, and let MainWindow know it's ready to be collected. 
    QByteArray direct = arduino->readAll(); 
    data = QString(direct); 
    emit dataReady(); 

    return 0; 

的Arduino:

int count = 2005; 
    Serial.print(count); 
+0

难道你不能阻止,直到你阅读所有预期的字符? – 2015-04-03 19:04:51

回答

0

您可以添加换行符同步。

例Qt代码:

//Get the data from serial, and let MainWindow know it's ready to be collected. 
    QByteArray direct = arduino->readLine(); 
    data = QString(direct); 
    emit dataReady(); 

    return 0; 

的Arduino:

int count = 2005; 
    Serial.print(count); 
    Serial.println(); 

如果你要使用QSerialPort::readyRead信号,你还需要使用QSerialPort::canReadLine功能,见this

0

谢谢你的帮助Arpegius。 println()函数绝对是用于换行符分隔符的不错选择。在这个链接之后,我能够获得一个监听函数,它将arduino作为单独的字符串发送。循环中额外的if语句处理传入字符串不包含换行符的任何情况(我是偏执狂:D)

我的代码适用于任何未来有同样问题的人。

int control::read() 
{ 
    QString characters; 
    //Get the data from serial, and let MainWindow know it's ready to be collected. 
    while(arduino->canReadLine()) 
    { 
     //String for data to go. 
     bool parsedCorrectly = 0; 
     //characters = ""; 

     //Loop until we find the newline delimiter. 
     do 
     { 
      //Get the line. 
      QByteArray direct = arduino->readLine();//Line(); 

      //If we have found a new line character in any line, complete the parse. 
      if(QString(direct).contains('\n')) 
      { 
       if(QString(direct) != "\n") 
       { 
        characters += QString(direct); 
        characters.remove(QRegExp("[\\n\\t\\r]")); 
        parsedCorrectly = 1; 
       } 
      } 
      //If we don't find the newline straight away, add the string we got to the characters QString and keep going. 
      else 
       characters += QString(direct); 
     }while(!parsedCorrectly); 

     //Save characters to data and emit signal to collect it. 
     data = characters; 

     emit dataReady(); 

     //Reset characters! 
     characters = ""; 
    } 

    return 0; 
}