【问题标题】:Communication issue printing from Arduino to Qt using QSerialPort使用 QSerialPort 从 Arduino 打印到 Qt 的通信问题
【发布时间】:2015-06-08 21:26:39
【问题描述】:

我在通过 QSerialPort 从 arduino 到我的 Qt 应用程序的通信时遇到问题。我有一个监听信号,它告诉我何时准备好从 arduino 读取数据。我期望步进电机在碰到限位开关之前所执行的步数的值,因此只有一个简单的 int,例如“2005”。当数据可供读取时,有时我会得到两个单独的读数,分别为“200”和“5”。显然,当我解析数据时,这会使事情变得混乱,因为它将它记录为两个数字,都比预期的数字小得多。

如果我不设置睡眠或 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;

阿杜诺:

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

【问题讨论】:

  • 你不能在读完所有预期的字符之前阻止吗?

标签: qt arduino microcontroller


【解决方案1】:

您可以添加换行符进行同步。

示例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;

阿杜诺:

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

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

【讨论】:

    【解决方案2】:

    感谢您对 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-05
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      相关资源
      最近更新 更多