Qt串口读取字符串不好

Qt serial port does not read the string well

我在 Ubuntu Gnome 14.04 LTS 上使用 Qt 5.4 从串行端口读取字符串行。一切正常,但当我重新安装 Ubuntu Gnome 14.04 和 Qt 5.4 时,我的串口代码无法正常工作。当 Arduino 发送“0”时,Qt 的代码将其读取为“�”,而通过串行发送的其他数字则 Qt 将其读取为字母和符号。我认为我的 Qt 的 unicode 有问题。我的ubuntu的unicode是en.US.UTF-8,QT的unicode设置为"system"。请帮我 :( 这是我从串口读取数据的代码:

    QByteArray input;    
if (serial->canReadLine())    //chect if data line is ready
     input.clear();
   input = serial->readLine(); //read data line from sreial port
   ui->label->setText(input);
   qDebug ()<<input<<endl;

Arduino 的这段代码与 CuteCom 和 Arduino 串行监视器一起工作正常

    const int analogInPin = A0; 


unsigned int sensorValue = 0;        // value read from the pot


void setup() {

  Serial.begin(19200);
}

void loop() {
  Serial.print("\n");
  Serial.print("#");
  for (int i=0; i < 5; i++) {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);

  Serial.print(sensorValue);
  Serial.print("#");

};
  sensorValue = analogRead(analogInPin);
  Serial.print(sensorValue);
  Serial.print("# \n");  
}

对不起我的英语

如果奇偶校验位或 data/stop 位参数不同,您仍然可以写入和读取,但您会得到 "funny" 类似于您在上面向我们展示的输出,这不是问题unicode 设置(特别是不使用 '0',它是 ASCII 集的一个字符)。

尝试在开始通信之前在两端显式设置相同的端口参数。

有几个问题:

  1. 您没有 post 足够的代码来了解您如何使用它的上下文。我假设您使用附加到 readyRead 信号的方法处理数据。

  2. 您只读了一行,您应该一直读到没有更多可用为止。 readyRead 信号可以用 any 字节数发出,可供读取:这些可能不构成完整的行,或几个完整的行!如果您在没有更多可用数据之前不继续阅读,您将严重落后于传入数据。

  3. 您正在使用隐式 QByteArrayQString 的转换。这些是不好的代码味道。明确说明。

  4. 您的代码相当冗长。在设置其值之前,您不需要清除 QByteArray。您还应该在使用时声明它。更好的是,使用 C++11 带来的类型推断。

因此:

class MyWindow : public QDialog {
  QSerialPort m_port;
  void onData() {
    while (m_port->canReadLine())
      auto input = QString::fromLatin1(m_port->readLine());
      ui->label->setText(input);
      qDebug() << input;
    }
  }
  ...
public:
  MyWindow(QWidget * parent = 0) : QDialog(parent) {
    ...
    connect(&m_port, &QIODevice::readyRead, this, &MyWindow::onData);
  }
};