26/11/2019 176

Serial Communication with QT-GUI C++

Hello everyone, in this article we are going to talk about how can we communicate with embedded systems via UART Serial Port using QT-GUI C++. Now let's get started. First we have to add below code in .pro file of project to use QSerialPort Class in our project.

QT += serialport

Now we are ready to use QSerialPort Class in QT C++.

We shall add following class in head of header file of our class.

#include <QtSerialPort/QSerialPort> and the below code block in private section:

    QSerialPort *serial;
Now we can use the serial port in our program. Lets write some more codes. Open the .cpp file write below functions.

void MainWindow::fnc_openSerialPort()
    //We will chose the parity bits
    //We will chose the stop bits
    //We will chose the Flow controls
    if (serial->open(QIODevice::ReadWrite)) {

    } else {
        QMessageBox::critical(this, tr("Error"), serial->errorString());

This is the code block to open COM1 serial Port with 9600 BaudRate and the other values.

And below function to close opened serial port.

void MainWindow::fnc_closeSerialPort()
     if (serial->isOpen())

To write data on Serial Port via opened COM port first we need to check the port is opened and avail to write some data. we have to write the data with ASCII values.

void MainWindow::writeData()
            serial->write(ui->txtSerialSendData->text().toLatin1() );
        QMessageBox::critical(this, tr("Write Error"), serial->errorString());

If we want to write data with the writeline we can change the code block like below:

   serial->write(ui->txtSerialSendData->text().toLatin1() + char(13)  );
   serial->write(ui->txtSerialSendData->text().toLatin1() );

And also we need to read datas on Serial Port. We can do it with below code block.

void MainWindow::readData()
    bool _ok;
    //This code is to read all data on serial port
    QByteArray data = serial->readAll();
    if (ui->chkGetHexadecimalValue->isChecked() == true)
        qDebug() << data.toHex();  //Here is the read data as Hex values
        qDebug() << data;  // Here is the code block to read normal latin words.

Now we can use the serial port with our QT GUI C++ program.

That is all for this article.

Have a good communication.

Burak hamdi TUFAN


Share this Post

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment.


    There is no comment. Be the owner of first comment...