qtarduinoqt5qtserialport

How to read serial data from Qt5


I am making a Qt5 an application to read data from the ESP32 microcontroller which I am programming with the Arduino framework using PlatformIO.

The problem I'm having is that I can't get the data to be received in uniform numbers of bytes. Sometimes I receive 1 byte, other times 2 bytes. Is this normal or is there a way to receive a complete buffer every time?

Qt Code:

void Dialog::on_connect_clicked()
{
    if(esp_available){
        esp->setPortName(espPortName);
        esp->open(QSerialPort::ReadWrite);
        esp->setBaudRate(9600);
        esp->setDataBits(QSerialPort::Data8);
        esp->setParity(QSerialPort::NoParity);
        esp->setStopBits(QSerialPort::OneStop);
        esp->setFlowControl(QSerialPort::NoFlowControl);
        connect(esp, SIGNAL(readyRead()), this, SLOT(on_startStream_clicked()));
    }

void Dialog::on_ledOn_clicked()
{
    if(esp->isOpen()){
        esp->write("1");
    }
}

void Dialog::on_startStream_clicked()
{
    QByteArray ba;
    if(esp->isOpen()){
        ba = esp->readAll();
        qDebug() << ba;
    }
}

Arduino Code:

#include <Arduino.h>

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  while (Serial.available() > 0)
  {
    int val = Serial.read() - '0';

    if (val == 1)
    {
      Serial.write("Hello");
    }
  }
  Serial.flush();
}

Clicking the button 3 times sends the following output:

H
e
ll
o
H
e
l
lo
H
e
l
lo

What I would like to see in the output is either the individual characters, or the entire packet/buffer in one line,

Any suggestions?


Solution

  • It is normal to receive bytes of different sizes, in these cases a simple way to find a delimiter is better. For example in your case it is better to use endline ("\n") as delimiter:

    Serial.println("Hello");
    // or
    // Serial.write("Hello\n");
    
    void Dialog::on_startStream_clicked()
    {
        QByteArray ba;
        while(esp->canReadLine()){
            ba = esp->readLine();
            qDebug() << ba;
        }
    }