Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt Creator and other tools
  4. Qt serial communication using UART
Forum Updated to NodeBB v4.3 + New Features

Qt serial communication using UART

Scheduled Pinned Locked Moved Solved Qt Creator and other tools
21 Posts 6 Posters 13.6k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S segtteee

    i want to connect qt and device using UART cable (RS232C) in linux. so i writing code and making ui and operating ,but it does not work.

    i want to connecting when i click some button(ui) device turn on and connect. also i want to make a function that if i enter some command device cognize and execute.

    below is my code , someone help me please.

    <mainwindow.cpp>
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QtSerialPort/QSerialPort>
    #include <QMessageBox>
    #include <QObject>
    #include <QIODevice>
    #include <QDebug>
    QSerialPort serial;
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
         QSerialPort*port=new QSerialPort();
        port->setPortName("/dev/ttyUSB0");
        port->setBaudRate(QSerialPort::Baud19200);
        port->setDataBits(QSerialPort::Data8);
        port->setParity(QSerialPort::NoParity);
        port->setStopBits(QSerialPort::OneStop);
        port->setFlowControl(QSerialPort::NoFlowControl);
        port->open(QIODevice::ReadWrite);
        ui->setupUi(this);
    
        serial = new QSerialPort(this);
    
    }
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::on_pushButton_connect_clicked()
    {
        port=new QSerialPort();
    
     QObject::connect(port,SIGNAL(readyRead()),this,
    SLOT(on_pushButton_connect_clicked()));
    
        if(!port->open(QIODevice::ReadWrite)){
            QMessageBox::information(this, tr("connect"), 
               "serialcommunication start");
    
        }
        else
        {
            QMessageBox::critical(this, tr("fail"), serial-
                  >errorString());
    
        }
    }
    
    
    void MainWindow::on_pushButton_disconnect_clicked()
    {
        port->close();
     QMessageBox::information(this, tr("disconnect"), "serial 
      communication end");
             }
    
    
    <mainwindow.h>
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    #include <QMainWindow>
    #include <QtSerialPort/QSerialPort>
    #include <QMessageBox>
    #include <QIODevice>
    #include <QDebug>
    namespace Ui {
    class MainWindow;
     }
    class MainWindow : public QMainWindow
     {
         Q_OBJECT
    public:
        explicit MainWindow(QWidget *parent = 0);
        QSerialPort*serial; //plus
        QSerialPort*port;
        QWidget*main_widget;
        void readData();
        ~MainWindow();
    private slots:
    
        void on_pushButton_connect_clicked();
    
        void on_pushButton_disconnect_clicked();
    
    
    private:
        Ui::MainWindow *ui;
    };
    #endif // MAINWINDOW_H
    
    
    <main.cpp>
    #include "mainwindow.h"
    #include <QApplication>
    #include <QSerialPort>
    #include <QSerialPortInfo>
    #include <QDebug>
    #include <QMessageBox>
    #include <QIODevice>
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        foreach(const QSerialPortInfo 
             &info,QSerialPortInfo::availablePorts()){
    
            QSerialPort serial;
             serial.setPort(info);
             if (serial.open(QIODevice::ReadWrite))
                 serial.close();
        }
    
         MainWindow w;
          w.show();
    
            return a.exec();
         }
    
    
    J.HilkJ Offline
    J.HilkJ Offline
    J.Hilk
    Moderators
    wrote on last edited by
    #3

    @segtteee said in Qt serial communication using UART:

    additionaly to what @sierdzio said,
    change your constructor from

    QSerialPort*port=new QSerialPort();

    to

    port = new QSerialPort();

    otherwise you config a new Variable instead of your member variable.


    Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


    Q: What's that?
    A: It's blue light.
    Q: What does it do?
    A: It turns blue.

    S 1 Reply Last reply
    4
    • J.HilkJ J.Hilk

      @segtteee said in Qt serial communication using UART:

      additionaly to what @sierdzio said,
      change your constructor from

      QSerialPort*port=new QSerialPort();

      to

      port = new QSerialPort();

      otherwise you config a new Variable instead of your member variable.

      S Offline
      S Offline
      segtteee
      wrote on last edited by
      #4

      @J.Hilk

      Thank you for your reply. I delete "port=new QSerialPort();" and fix from "QSerialPort*port=new QSerialPort();" to "port = new QSerialPort();"

      , insert "port->open(QIODevice::ReadWrite);"

      but how can i remote device when i enter the command at line_Edit . ( like echo ____ > /dev/ttyUSB0 in linux terminal )

      i want to remote device using qt ui line Edit and button .

      please let me know TT

      J.HilkJ 1 Reply Last reply
      0
      • sierdzioS Offline
        sierdzioS Offline
        sierdzio
        Moderators
        wrote on last edited by
        #5

        QSerialPort is a QIODevice. You can interact with it the same way you interact with QFile, for example. So:

        QByteArray data = port.read();
        port.write("sth");
        
        // Or using text stream
        QTextStream stream(port);
        stream << "some data";
        

        (Z(:^

        S 1 Reply Last reply
        2
        • S segtteee

          @J.Hilk

          Thank you for your reply. I delete "port=new QSerialPort();" and fix from "QSerialPort*port=new QSerialPort();" to "port = new QSerialPort();"

          , insert "port->open(QIODevice::ReadWrite);"

          but how can i remote device when i enter the command at line_Edit . ( like echo ____ > /dev/ttyUSB0 in linux terminal )

          i want to remote device using qt ui line Edit and button .

          please let me know TT

          J.HilkJ Offline
          J.HilkJ Offline
          J.Hilk
          Moderators
          wrote on last edited by
          #6

          @segtteee I'm not entirely what you want to do, but I'll take quick look at my crystal ball and write something down:

          To send something via your SieralPort you can do something like this:

          void onSendClicked(){
              QString s("String to Send via Serial");
              QByteArray dataToSend; 
              dataToSend.append(s);
          
              if(->isOpen())
                  serialPort->write(dataToSend);
          }
          

          Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


          Q: What's that?
          A: It's blue light.
          Q: What does it do?
          A: It turns blue.

          S 1 Reply Last reply
          0
          • sierdzioS sierdzio

            QSerialPort is a QIODevice. You can interact with it the same way you interact with QFile, for example. So:

            QByteArray data = port.read();
            port.write("sth");
            
            // Or using text stream
            QTextStream stream(port);
            stream << "some data";
            
            S Offline
            S Offline
            segtteee
            wrote on last edited by
            #7

            @sierdzio

            Thank you for your reply. but i can't understand that you say.

            how can i apply "QByteArray data = port.read();" , "port.write("sth");" in my code?

            i think // void MainWindow::lineEdit_command (){ // is that right?
            QByteArray data = port.read();
            port.write("sth");

            sierdzioS 1 Reply Last reply
            0
            • S segtteee

              @sierdzio

              Thank you for your reply. but i can't understand that you say.

              how can i apply "QByteArray data = port.read();" , "port.write("sth");" in my code?

              i think // void MainWindow::lineEdit_command (){ // is that right?
              QByteArray data = port.read();
              port.write("sth");

              sierdzioS Offline
              sierdzioS Offline
              sierdzio
              Moderators
              wrote on last edited by
              #8

              @segtteee said in Qt serial communication using UART:

              Thank you for your reply. but i can't understand that you say.

              Please take a look at some Qt examples to better understand how it works. My code snippets are only an example how to use the QSerialPort, they have little to do with your actual use case.

              So, if I get it right, you want to take the command which is written (by user) into a QLineEdit, and (when user clicks a button) send it via the serial port?

              Then:

              • connect the clicked() signal of the button to a slot you create in your main window class. In your case, that could be void on_pushButton_connect_clicked(); slot, or something else if you want to add another button
              • in the slot, open the port
              • in the slot, write line edit data into your port
              • if needed, add some sanity checking/ validation to the input data. Otherwise users will surely put in some garbage there

              So, in essence, you need something like:

              void MainWindow::on_someButton_clicked() {
                port->open(QSerialPort::ReadWrite);
                port->write(ui->yourLineEditName->text().toLatin1());
              }
              

              (Z(:^

              S 1 Reply Last reply
              1
              • J.HilkJ J.Hilk

                @segtteee I'm not entirely what you want to do, but I'll take quick look at my crystal ball and write something down:

                To send something via your SieralPort you can do something like this:

                void onSendClicked(){
                    QString s("String to Send via Serial");
                    QByteArray dataToSend; 
                    dataToSend.append(s);
                
                    if(->isOpen())
                        serialPort->write(dataToSend);
                }
                
                S Offline
                S Offline
                segtteee
                wrote on last edited by
                #9

                @J.Hilk
                Thank you for your reply.

                you mean if i want use several command , i have to enter code that you tell me one by one?

                otherwise " QString s("String to Send via Serial"); " can understand any commands ? "String to Send via Serial" what mean?

                1 Reply Last reply
                0
                • K Offline
                  K Offline
                  kuzulis
                  Qt Champions 2020
                  wrote on last edited by
                  #10

                  Please read any C++ book at first.

                  1 Reply Last reply
                  2
                  • sierdzioS sierdzio

                    @segtteee said in Qt serial communication using UART:

                    Thank you for your reply. but i can't understand that you say.

                    Please take a look at some Qt examples to better understand how it works. My code snippets are only an example how to use the QSerialPort, they have little to do with your actual use case.

                    So, if I get it right, you want to take the command which is written (by user) into a QLineEdit, and (when user clicks a button) send it via the serial port?

                    Then:

                    • connect the clicked() signal of the button to a slot you create in your main window class. In your case, that could be void on_pushButton_connect_clicked(); slot, or something else if you want to add another button
                    • in the slot, open the port
                    • in the slot, write line edit data into your port
                    • if needed, add some sanity checking/ validation to the input data. Otherwise users will surely put in some garbage there

                    So, in essence, you need something like:

                    void MainWindow::on_someButton_clicked() {
                      port->open(QSerialPort::ReadWrite);
                      port->write(ui->yourLineEditName->text().toLatin1());
                    }
                    
                    S Offline
                    S Offline
                    segtteee
                    wrote on last edited by
                    #11

                    @sierdzio

                    Thaky you for your reply.

                    i add
                    //void MainWindow::on_pushButton_send_clicked()
                    {
                    port->open(QSerialPort::ReadWrite);
                    port->write(ui->lineEdit_command->text().toLatin1());

                    }// in my code and enter the command at lineEdit , but device can't conduct command..

                    Is there something else i have to anything for device's behavior?

                    sierdzioS 1 Reply Last reply
                    0
                    • S segtteee

                      @sierdzio

                      Thaky you for your reply.

                      i add
                      //void MainWindow::on_pushButton_send_clicked()
                      {
                      port->open(QSerialPort::ReadWrite);
                      port->write(ui->lineEdit_command->text().toLatin1());

                      }// in my code and enter the command at lineEdit , but device can't conduct command..

                      Is there something else i have to anything for device's behavior?

                      sierdzioS Offline
                      sierdzioS Offline
                      sierdzio
                      Moderators
                      wrote on last edited by
                      #12

                      @segtteee said in Qt serial communication using UART:

                      in my code and enter the command at lineEdit , but device can't conduct command..

                      Well, I can't guess what error codes are you getting, right? I don't even know if you connected to the device correctly. Did it get the command? Did it reply with anything? Have you connected the readyRead() to some slot, or used waitForReadyRead() to wait for the reply?

                      I don't give you whole solution for your problem, I'm not here to write the code for you. I'm happy to help you overcome problems and learn.

                      (Z(:^

                      S 1 Reply Last reply
                      3
                      • sierdzioS sierdzio

                        @segtteee said in Qt serial communication using UART:

                        in my code and enter the command at lineEdit , but device can't conduct command..

                        Well, I can't guess what error codes are you getting, right? I don't even know if you connected to the device correctly. Did it get the command? Did it reply with anything? Have you connected the readyRead() to some slot, or used waitForReadyRead() to wait for the reply?

                        I don't give you whole solution for your problem, I'm not here to write the code for you. I'm happy to help you overcome problems and learn.

                        S Offline
                        S Offline
                        segtteee
                        wrote on last edited by
                        #13

                        @sierdzio

                        okay thank you for your reply .

                        i have question , how to check connected device with qt ? only i enter the command and device conduct command?

                        when i debuging the code there is no error message and no problem i think . hot to check in qt ?

                        1 Reply Last reply
                        0
                        • aha_1980A Offline
                          aha_1980A Offline
                          aha_1980
                          Lifetime Qt Champion
                          wrote on last edited by aha_1980
                          #14

                          @segtteee: I can only recommend you to have a look at the examples (there are a lot of them):

                          http://doc.qt.io/qt-5/qtserialport-examples.html

                          Take, e.g. the Terminal example http://doc.qt.io/qt-5/qtserialport-terminal-example.html and try to understand how it works. It should be very near to what you want to achive.

                          PS: This example also shows how to check for some errors. Depending on the communication protocol, you may have to add more error checks.

                          Qt has to stay free or it will die.

                          S 1 Reply Last reply
                          0
                          • aha_1980A aha_1980

                            @segtteee: I can only recommend you to have a look at the examples (there are a lot of them):

                            http://doc.qt.io/qt-5/qtserialport-examples.html

                            Take, e.g. the Terminal example http://doc.qt.io/qt-5/qtserialport-terminal-example.html and try to understand how it works. It should be very near to what you want to achive.

                            PS: This example also shows how to check for some errors. Depending on the communication protocol, you may have to add more error checks.

                            S Offline
                            S Offline
                            segtteee
                            wrote on last edited by
                            #15

                            @aha_1980

                            I also saw an example when I wrote this project.

                            But they did not come out in detail and I could not understand.

                            so i search everyday and raise a question here ....

                            1 Reply Last reply
                            0
                            • sierdzioS Offline
                              sierdzioS Offline
                              sierdzio
                              Moderators
                              wrote on last edited by
                              #16

                              @segtteee said in Qt serial communication using UART:

                              i have question , how to check connected device with qt ? only i enter the command and device conduct command?

                              First step is to check if port->open() returned true.
                              When calling port->write() you can check if the amount of bytes written is the same you sent. If not, something went wrong. Then you can check QSerialPort::error and see what was the problem.

                              Another clue might be whether readyRead() is emitted in response to your command. If there is no reply, then again - something might be wrong (or not - that depends on what the command is and which device you connect to).

                              (Z(:^

                              S 1 Reply Last reply
                              0
                              • sierdzioS sierdzio

                                @segtteee said in Qt serial communication using UART:

                                i have question , how to check connected device with qt ? only i enter the command and device conduct command?

                                First step is to check if port->open() returned true.
                                When calling port->write() you can check if the amount of bytes written is the same you sent. If not, something went wrong. Then you can check QSerialPort::error and see what was the problem.

                                Another clue might be whether readyRead() is emitted in response to your command. If there is no reply, then again - something might be wrong (or not - that depends on what the command is and which device you connect to).

                                S Offline
                                S Offline
                                segtteee
                                wrote on last edited by
                                #17

                                @sierdzio

                                Thank you for your answer during long time.

                                i try but i can't solve this situation. but i learn many thing thank to your reply.

                                i'm really thank you .

                                1 Reply Last reply
                                1
                                • mrjjM Offline
                                  mrjjM Offline
                                  mrjj
                                  Lifetime Qt Champion
                                  wrote on last edited by mrjj
                                  #18

                                  Hi
                                  For a pretty good example, please see
                                  http://doc.qt.io/qt-5/qtserialport-terminal-example.html
                                  It has dialog to select comport properties and allows to send text out of the box.
                                  Its also pretty good explained.~

                                  aha_1980A 1 Reply Last reply
                                  0
                                  • mrjjM mrjj

                                    Hi
                                    For a pretty good example, please see
                                    http://doc.qt.io/qt-5/qtserialport-terminal-example.html
                                    It has dialog to select comport properties and allows to send text out of the box.
                                    Its also pretty good explained.~

                                    aha_1980A Offline
                                    aha_1980A Offline
                                    aha_1980
                                    Lifetime Qt Champion
                                    wrote on last edited by
                                    #19

                                    @mrjj Thats what I wrote three days ago...

                                    Qt has to stay free or it will die.

                                    mrjjM 1 Reply Last reply
                                    2
                                    • aha_1980A aha_1980

                                      @mrjj Thats what I wrote three days ago...

                                      mrjjM Offline
                                      mrjjM Offline
                                      mrjj
                                      Lifetime Qt Champion
                                      wrote on last edited by
                                      #20

                                      @aha_1980
                                      Oh yes. sorry. i did miss. Clicked from locked thread. Should have read it all :)

                                      1 Reply Last reply
                                      0
                                      • aha_1980A Offline
                                        aha_1980A Offline
                                        aha_1980
                                        Lifetime Qt Champion
                                        wrote on last edited by
                                        #21

                                        @mrjj said in Qt serial communication using UART:

                                        @aha_1980
                                        Oh yes. sorry. i did miss. Clicked from locked thread. Should have read it all :)

                                        No problem :) (And no need to delete your post)

                                        Qt has to stay free or it will die.

                                        1 Reply Last reply
                                        0

                                        • Login

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • Users
                                        • Groups
                                        • Search
                                        • Get Qt Extensions
                                        • Unsolved