简体   繁体   English

Qt没有从arduino接收串行数据

[英]Qt not receiving serial data from arduino

I am writing a C++ program using Qt that reads data from the serial line. 我正在使用Qt编写一个C ++程序,它从串行线读取数据。 The "producer" of the data is an Arduino UNO board. 数据的“生产者”是Arduino UNO董事会。

The Arduino code is very simple. Arduino代码非常简单。 Currently, it just generates a random number and sends it over the serial line. 目前,它只生成一个随机数并通过串行线发送。 Here is the code: 这是代码:

long randNumber;

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop() {
  randNumber = random(300);
  Serial.write(randNumber);
  delay(10);
}

I have used the Arduino's "serial monitor" to verify that data is coming across the serial line. 我使用Arduino的“串行监视器”来验证数据是否通过串行线传输。

On the Qt side of things, I have a worker thread that is supposed to read the serial data and update a plot on the UI accordingly. 在Qt方面,我有一个工作线程,应该读取串行数据并相应地更新UI上的图。 The worker thread is definitely running, and this code is getting executed (I've checked). 工作线程肯定在运行,并且此代码正在执行(我已经检查过)。 I only have one device in my "port list" that shows up, and it is the Arduino, so currently I connect right to it. 我的“端口列表”中只有一个设备出现,它是Arduino,所以目前我连接到它。 Here is the code: 这是代码:

void doWork ()
{
    QList<QSerialPortInfo> port_list = QSerialPortInfo::availablePorts();
    QSerialPort serialPort;
    serialPort.setPort(port_list[0]);
    serialPort.setBaudRate(QSerialPort::Baud9600);

    if (!serialPort.open(QIODevice::ReadWrite))
    {
        cout << QObject::tr("Failed to open port COM3, error: %1").arg(serialPort.errorString()).toStdString() << endl;
    }

    while(!abort_thread)
    {
        int bytes_available = serialPort.bytesAvailable();
        if (bytes_available >= 4)
        {
            QByteArray byte_array = serialPort.read(4);
            int data = byte_array.toInt();
            emit signalDataReady(data);
        }
    }

    serialPort.close();
}

Unfortunately, there are never any bytes available. 不幸的是,从来没有任何字节可用。 It opens the serial port successfully, but no bytes come through. 它成功打开串口,但没有字节通过。 What am I doing wrong here? 我在这做错了什么? Any ideas? 有任何想法吗? Thanks! 谢谢!

您忘记在bytesAvailable()之前添加waitForReadyRead()。

From https://www.arduino.cc/en/Serial/Write : 来自https://www.arduino.cc/en/Serial/Write

Serial.write(val) Serial.write(VAL)

val: a value to send as a single byte val:要作为单个字节发送的值

If you write a number Arduino only sends one byte, if you want to send a long then you must decompose it as an array and send the array (or get a pointer to the long's address and send each one of the bytes). 如果你写一个数字Arduino只发送一个字节,如果你想发送一个长,那么你必须将它作为一个数组分解并发送数组(或获取指向long的地址并发送每个字节的指针)。

As your Qt code expects to read four bytes the if is never executed. 由于您的Qt代码需要读取四个字节,因此永远不会执行if。

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

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