Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. problem with writing on serial port
Qt 6.11 is out! See what's new in the release blog

problem with writing on serial port

Scheduled Pinned Locked Moved Unsolved General and Desktop
36 Posts 4 Posters 5.3k Views
  • 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.
  • N nanor

    @jsulm Thank you. You mentioned that if I want to do write my code in a while loop, I have to use thread. I have read about qthread class, but I don't know how to use this class in my project. Could you please give suggestions about the steps I have to take?
    The question is:
    read data continuously and byte by byte from a serial port and if data equals to something special that is defined in code (like"hi"), then write to serial port something.
    I would appreciate if you guide me how to use threads in solving this question

    jsulmJ Offline
    jsulmJ Offline
    jsulm
    Lifetime Qt Champion
    wrote on last edited by
    #13

    @nanor This example does exactly what you need: https://doc.qt.io/qt-5/qtserialport-blockingmaster-example.html
    It uses blocking QSerialPort API in a worker thread.
    Take a look.

    https://forum.qt.io/topic/113070/qt-code-of-conduct

    N 1 Reply Last reply
    2
    • jsulmJ jsulm

      @nanor This example does exactly what you need: https://doc.qt.io/qt-5/qtserialport-blockingmaster-example.html
      It uses blocking QSerialPort API in a worker thread.
      Take a look.

      N Offline
      N Offline
      nanor
      wrote on last edited by
      #14

      @jsulm Thank you so much.
      For the firt step (I want to continuesly read data byte by byte) I have written the following code. But it crashes. Could you please guide me how to fix this?

      mainwindow.h:

      #ifndef MAINWINDOW_H
      #define MAINWINDOW_H
      
      #include <QMainWindow>
      #include <QtSerialPort/QSerialPort>
      #include "mythread.h"
      
      namespace Ui {
      class MainWindow;
      }
      
      class MainWindow : public QMainWindow
      {
          Q_OBJECT
      
      public:
          explicit MainWindow(QWidget *parent = nullptr);
          ~MainWindow();
      
          QSerialPort *serial;
      
          QThread *myThread;
      
      
      private slots:
          void on_pushButton_clicked();
      
      private:
          Ui::MainWindow *ui;
      };
      
      #endif // MAINWINDOW_H
      

      mythread.h:

      #ifndef MYTHREAD_H
      #define MYTHREAD_H
      
      #include <QObject>
      #include <QThread>
      #include <QtSerialPort/QSerialPort>
      #include <QtSerialPort/QSerialPortInfo>
      #include <QDebug>
      
      class MyThread : public QThread
      {
          Q_OBJECT
      public:
          explicit MyThread(QObject *parent = nullptr);
      
          void run();
      
          QSerialPort *serial;
      
      signals:
      
      public slots:
      };
      
      #endif // MYTHREAD_H
      
      

      mainwindow.cpp:

      #include "mainwindow.h"
      #include "ui_mainwindow.h"
      #include <QtSerialPort/QSerialPort>
      #include <QtSerialPort/QSerialPortInfo>
      #include <QDebug>
      
      MainWindow::MainWindow(QWidget *parent) :
          QMainWindow(parent),
          ui(new Ui::MainWindow)
      {
          ui->setupUi(this);
          myThread->start();
      
      }
      
      MainWindow::~MainWindow()
      {
          delete ui;
      }
      
      void MainWindow::on_pushButton_clicked()
      {
          qDebug() << "salam";
      }
      

      mythread.cpp:

      #include "mythread.h"
      
      MyThread::MyThread(QObject *parent) : QThread(parent)
      {
      
      }
      
      void MyThread::run()
      {
          serial = new QSerialPort(this);
          serial->setPortName("COM1");
      
          for(const auto &serialPortInfo : QSerialPortInfo::availablePorts())
          {
             qDebug() << "find serial port: " << serialPortInfo.portName() ;
          }
      
          serial->open(QIODevice::ReadWrite);
      
      
          if(serial->isOpen())
          {
              serial->setBaudRate(QSerialPort::Baud9600);
              serial->setDataBits(QSerialPort::Data8);
              serial->setParity(QSerialPort::NoParity);
              serial->setStopBits(QSerialPort::OneStop);
              serial->setFlowControl(QSerialPort::NoFlowControl);
      
               while(1)
              {
                  serial->read(1);
      
             }
      
          }
      
          else
          {
            qDebug() << "can't open the port";
          }
      
      }
      
      

      the error:

      10:33:50: Starting C:\Users\nanor\OneDrive\Desktop\qt codes\build-serialportreading3-Desktop_Qt_5_12_2_MinGW_32_bit-Debug\debug\serialportreading3.exe...
      ASSERT: "timeout >= 0" in file thread\qmutex.cpp, line 582
      10:33:52: The program has unexpectedly finished.
      10:33:52: The process was ended forcefully.
      10:33:52: C:/Users/nanor/OneDrive/Desktop/qt codes/build-serialportreading3-Desktop_Qt_5_12_2_MinGW_32_bit-Debug/debug/serialportreading3.exe crashed.

      jsulmJ 1 Reply Last reply
      0
      • N nanor

        @jsulm Thank you so much.
        For the firt step (I want to continuesly read data byte by byte) I have written the following code. But it crashes. Could you please guide me how to fix this?

        mainwindow.h:

        #ifndef MAINWINDOW_H
        #define MAINWINDOW_H
        
        #include <QMainWindow>
        #include <QtSerialPort/QSerialPort>
        #include "mythread.h"
        
        namespace Ui {
        class MainWindow;
        }
        
        class MainWindow : public QMainWindow
        {
            Q_OBJECT
        
        public:
            explicit MainWindow(QWidget *parent = nullptr);
            ~MainWindow();
        
            QSerialPort *serial;
        
            QThread *myThread;
        
        
        private slots:
            void on_pushButton_clicked();
        
        private:
            Ui::MainWindow *ui;
        };
        
        #endif // MAINWINDOW_H
        

        mythread.h:

        #ifndef MYTHREAD_H
        #define MYTHREAD_H
        
        #include <QObject>
        #include <QThread>
        #include <QtSerialPort/QSerialPort>
        #include <QtSerialPort/QSerialPortInfo>
        #include <QDebug>
        
        class MyThread : public QThread
        {
            Q_OBJECT
        public:
            explicit MyThread(QObject *parent = nullptr);
        
            void run();
        
            QSerialPort *serial;
        
        signals:
        
        public slots:
        };
        
        #endif // MYTHREAD_H
        
        

        mainwindow.cpp:

        #include "mainwindow.h"
        #include "ui_mainwindow.h"
        #include <QtSerialPort/QSerialPort>
        #include <QtSerialPort/QSerialPortInfo>
        #include <QDebug>
        
        MainWindow::MainWindow(QWidget *parent) :
            QMainWindow(parent),
            ui(new Ui::MainWindow)
        {
            ui->setupUi(this);
            myThread->start();
        
        }
        
        MainWindow::~MainWindow()
        {
            delete ui;
        }
        
        void MainWindow::on_pushButton_clicked()
        {
            qDebug() << "salam";
        }
        

        mythread.cpp:

        #include "mythread.h"
        
        MyThread::MyThread(QObject *parent) : QThread(parent)
        {
        
        }
        
        void MyThread::run()
        {
            serial = new QSerialPort(this);
            serial->setPortName("COM1");
        
            for(const auto &serialPortInfo : QSerialPortInfo::availablePorts())
            {
               qDebug() << "find serial port: " << serialPortInfo.portName() ;
            }
        
            serial->open(QIODevice::ReadWrite);
        
        
            if(serial->isOpen())
            {
                serial->setBaudRate(QSerialPort::Baud9600);
                serial->setDataBits(QSerialPort::Data8);
                serial->setParity(QSerialPort::NoParity);
                serial->setStopBits(QSerialPort::OneStop);
                serial->setFlowControl(QSerialPort::NoFlowControl);
        
                 while(1)
                {
                    serial->read(1);
        
               }
        
            }
        
            else
            {
              qDebug() << "can't open the port";
            }
        
        }
        
        

        the error:

        10:33:50: Starting C:\Users\nanor\OneDrive\Desktop\qt codes\build-serialportreading3-Desktop_Qt_5_12_2_MinGW_32_bit-Debug\debug\serialportreading3.exe...
        ASSERT: "timeout >= 0" in file thread\qmutex.cpp, line 582
        10:33:52: The program has unexpectedly finished.
        10:33:52: The process was ended forcefully.
        10:33:52: C:/Users/nanor/OneDrive/Desktop/qt codes/build-serialportreading3-Desktop_Qt_5_12_2_MinGW_32_bit-Debug/debug/serialportreading3.exe crashed.

        jsulmJ Offline
        jsulmJ Offline
        jsulm
        Lifetime Qt Champion
        wrote on last edited by
        #15

        @nanor said in problem with writing on serial port:

        serial = new QSerialPort(this);

        Remove "this".
        If it is still crashing then please use the debugger to see where exactly and post the stack trace after crash.

        https://forum.qt.io/topic/113070/qt-code-of-conduct

        N 1 Reply Last reply
        0
        • jsulmJ jsulm

          @nanor said in problem with writing on serial port:

          serial = new QSerialPort(this);

          Remove "this".
          If it is still crashing then please use the debugger to see where exactly and post the stack trace after crash.

          N Offline
          N Offline
          nanor
          wrote on last edited by
          #16
          This post is deleted!
          jsulmJ 1 Reply Last reply
          0
          • N nanor

            This post is deleted!

            jsulmJ Offline
            jsulmJ Offline
            jsulm
            Lifetime Qt Champion
            wrote on last edited by
            #17

            @nanor Please build in debug mode before running in debugger!

            https://forum.qt.io/topic/113070/qt-code-of-conduct

            N 1 Reply Last reply
            0
            • jsulmJ jsulm

              @nanor Please build in debug mode before running in debugger!

              N Offline
              N Offline
              nanor
              wrote on last edited by nanor
              #18
              This post is deleted!
              jsulmJ 1 Reply Last reply
              0
              • N nanor

                This post is deleted!

                jsulmJ Offline
                jsulmJ Offline
                jsulm
                Lifetime Qt Champion
                wrote on last edited by
                #19

                @nanor Please post the stack trace (as text). It's in the middle of your screen-shot, in "Debugger" section.

                https://forum.qt.io/topic/113070/qt-code-of-conduct

                N 1 Reply Last reply
                0
                • jsulmJ jsulm

                  @nanor Please post the stack trace (as text). It's in the middle of your screen-shot, in "Debugger" section.

                  N Offline
                  N Offline
                  nanor
                  wrote on last edited by
                  #20
                  This post is deleted!
                  jsulmJ 1 Reply Last reply
                  0
                  • N nanor

                    This post is deleted!

                    jsulmJ Offline
                    jsulmJ Offline
                    jsulm
                    Lifetime Qt Champion
                    wrote on last edited by
                    #21

                    @nanor Please post what is in level 2 and 3, else I'm out of this thread as I do not want to guess what is wrong...
                    It is your job to find out where your app is crashing.

                    https://forum.qt.io/topic/113070/qt-code-of-conduct

                    N 2 Replies Last reply
                    1
                    • jsulmJ jsulm

                      @nanor Please post what is in level 2 and 3, else I'm out of this thread as I do not want to guess what is wrong...
                      It is your job to find out where your app is crashing.

                      N Offline
                      N Offline
                      nanor
                      wrote on last edited by
                      #22

                      @jsulm inside the mainwindow.cpp I didn't initialize the thread (myThread = new QThread();) . I added this and it got fixed.

                      1 Reply Last reply
                      0
                      • jsulmJ jsulm

                        @nanor Please post what is in level 2 and 3, else I'm out of this thread as I do not want to guess what is wrong...
                        It is your job to find out where your app is crashing.

                        N Offline
                        N Offline
                        nanor
                        wrote on last edited by nanor
                        #23

                        @jsulm Sorry again. I have another question. inside the while loop, I have to constantly read data from the port and store them inside an array adn then debug them . I have written the following line. but nothing is printed

                        while(1)
                                {
                                    QByteArray data = serial->read(1);
                                    for(int i=0; i<data.size(); i++)
                                    {
                                        qDebug() << data[i];
                                    }
                        
                        
                                }
                        
                        JonBJ 1 Reply Last reply
                        0
                        • N nanor

                          @jsulm Sorry again. I have another question. inside the while loop, I have to constantly read data from the port and store them inside an array adn then debug them . I have written the following line. but nothing is printed

                          while(1)
                                  {
                                      QByteArray data = serial->read(1);
                                      for(int i=0; i<data.size(); i++)
                                      {
                                          qDebug() << data[i];
                                      }
                          
                          
                                  }
                          
                          JonBJ Offline
                          JonBJ Offline
                          JonB
                          wrote on last edited by JonB
                          #24

                          @nanor
                          Absolutely not! Since it's while(1) how is it ever going to exit the loop?? while (1) is "always" wrong in Qt....

                          You have now changed your code...

                          but nothing is printed

                          So either it never enters the loop, or it never has anything to read.

                          N 1 Reply Last reply
                          1
                          • JonBJ JonB

                            @nanor
                            Absolutely not! Since it's while(1) how is it ever going to exit the loop?? while (1) is "always" wrong in Qt....

                            You have now changed your code...

                            but nothing is printed

                            So either it never enters the loop, or it never has anything to read.

                            N Offline
                            N Offline
                            nanor
                            wrote on last edited by
                            #25

                            @JonB I removed the while loop and mythread.cpp is now:

                            #include "mythread.h"
                            
                            MyThread::MyThread(QObject *parent) : QThread(parent)
                            {
                            
                            }
                            
                            void MyThread::run()
                            {
                                serial = new QSerialPort();
                                serial->setPortName("COM1");
                            
                                for(const auto &serialPortInfo : QSerialPortInfo::availablePorts())
                                {
                                   qDebug() << "find serial port: " << serialPortInfo.portName() ;
                                }
                            
                                serial->open(QIODevice::ReadWrite);
                            
                            
                                if(serial->isOpen())
                                {
                                    serial->setBaudRate(QSerialPort::Baud9600);
                                    serial->setDataBits(QSerialPort::Data8);
                                    serial->setParity(QSerialPort::NoParity);
                                    serial->setStopBits(QSerialPort::OneStop);
                                    serial->setFlowControl(QSerialPort::NoFlowControl);
                            
                            
                            
                                    QByteArray data = serial->read(1);
                                    for(int i=0; i<data.size(); i++)
                                     {
                                            qDebug() << data[i];
                                     }
                            
                            
                            
                            
                                }
                            
                                else
                                {
                                  qDebug() << "can't open the port";
                                }
                            
                            }
                            
                            

                            But still I can't get the messages. I send data from hercules.

                            JonBJ 1 Reply Last reply
                            0
                            • N nanor

                              @JonB I removed the while loop and mythread.cpp is now:

                              #include "mythread.h"
                              
                              MyThread::MyThread(QObject *parent) : QThread(parent)
                              {
                              
                              }
                              
                              void MyThread::run()
                              {
                                  serial = new QSerialPort();
                                  serial->setPortName("COM1");
                              
                                  for(const auto &serialPortInfo : QSerialPortInfo::availablePorts())
                                  {
                                     qDebug() << "find serial port: " << serialPortInfo.portName() ;
                                  }
                              
                                  serial->open(QIODevice::ReadWrite);
                              
                              
                                  if(serial->isOpen())
                                  {
                                      serial->setBaudRate(QSerialPort::Baud9600);
                                      serial->setDataBits(QSerialPort::Data8);
                                      serial->setParity(QSerialPort::NoParity);
                                      serial->setStopBits(QSerialPort::OneStop);
                                      serial->setFlowControl(QSerialPort::NoFlowControl);
                              
                              
                              
                                      QByteArray data = serial->read(1);
                                      for(int i=0; i<data.size(); i++)
                                       {
                                              qDebug() << data[i];
                                       }
                              
                              
                              
                              
                                  }
                              
                                  else
                                  {
                                    qDebug() << "can't open the port";
                                  }
                              
                              }
                              
                              

                              But still I can't get the messages. I send data from hercules.

                              JonBJ Offline
                              JonBJ Offline
                              JonB
                              wrote on last edited by JonB
                              #26

                              @nanor
                              Start by putting in qDebug() statements to see for yourself where you are actually getting to, plus more error checking.

                              I don't know if any serial data is available to read at the instant you open the port. And you only try to read one byte once.

                              N 1 Reply Last reply
                              0
                              • JonBJ JonB

                                @nanor
                                Start by putting in qDebug() statements to see for yourself where you are actually getting to, plus more error checking.

                                I don't know if any serial data is available to read at the instant you open the port. And you only try to read one byte once.

                                N Offline
                                N Offline
                                nanor
                                wrote on last edited by
                                #27

                                @JonB Thank you for mentioning using debug. I added the line qDebug() << "inside the run function"; inside the run function, but after running, this message isn't shown. But I have started the thread inside the mainwindow class. I can't understand why this is happened!

                                JonBJ jsulmJ 2 Replies Last reply
                                0
                                • N nanor

                                  @JonB Thank you for mentioning using debug. I added the line qDebug() << "inside the run function"; inside the run function, but after running, this message isn't shown. But I have started the thread inside the mainwindow class. I can't understand why this is happened!

                                  JonBJ Offline
                                  JonBJ Offline
                                  JonB
                                  wrote on last edited by
                                  #28

                                  @nanor
                                  My own view, often times expressed, is why are you going anywhere near QThread at all? Every time it causes posters problems. Qt framework is asynchronous, so why do you need any threads when you have signals?

                                  jsulmJ 1 Reply Last reply
                                  0
                                  • N nanor

                                    @JonB Thank you for mentioning using debug. I added the line qDebug() << "inside the run function"; inside the run function, but after running, this message isn't shown. But I have started the thread inside the mainwindow class. I can't understand why this is happened!

                                    jsulmJ Offline
                                    jsulmJ Offline
                                    jsulm
                                    Lifetime Qt Champion
                                    wrote on last edited by
                                    #29

                                    @nanor I gave you a link to an example which uses the synchronous API. Apparently you did not really read it carefully, did you? In your loop you should use waitForReadyRead(...) as is done in the example. This makes sure that the event loop can actually do its job.

                                    if (serial.waitForReadyRead(currentWaitTimeout)) {
                                        QByteArray responseData = serial.readAll();
                                    

                                    https://forum.qt.io/topic/113070/qt-code-of-conduct

                                    1 Reply Last reply
                                    2
                                    • JonBJ JonB

                                      @nanor
                                      My own view, often times expressed, is why are you going anywhere near QThread at all? Every time it causes posters problems. Qt framework is asynchronous, so why do you need any threads when you have signals?

                                      jsulmJ Offline
                                      jsulmJ Offline
                                      jsulm
                                      Lifetime Qt Champion
                                      wrote on last edited by
                                      #30

                                      @JonB I asked already why threads. Seems to be an exercise.

                                      https://forum.qt.io/topic/113070/qt-code-of-conduct

                                      J.HilkJ 1 Reply Last reply
                                      1
                                      • jsulmJ jsulm

                                        @JonB I asked already why threads. Seems to be an exercise.

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

                                        @jsulm said in problem with writing on serial port:

                                        I asked already why threads. Seems to be an exercise.

                                        possibly, but the OP only states the while loop as a task. Not threads specifically.

                                        @nanor can you word exactly, what you want to do ?


                                        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.

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

                                          @jsulm said in problem with writing on serial port:

                                          I asked already why threads. Seems to be an exercise.

                                          possibly, but the OP only states the while loop as a task. Not threads specifically.

                                          @nanor can you word exactly, what you want to do ?

                                          N Offline
                                          N Offline
                                          nanor
                                          wrote on last edited by nanor
                                          #32

                                          @J-Hilk Hi
                                          I have a button that when a user pushes it, "salam" is printed. At the same time, I want to constantly read from and write to a port (I want to read byte by byte and print them(debug them)). Now I know that I have to declare a class inheritted from qThread class and inside its run function, read and write. But I don't know if I have to declare while loop inside the run function in order to read constantly or not. In the code I posted, I have:

                                          
                                                  QByteArray data = serial->read(1);
                                                  for(int i=0; i<data.size(); i++)
                                                  {
                                                          qDebug() << data[i];
                                                  }
                                          

                                          Is this part reading the datas byte by byte and store them inside an array and print the datas?

                                          JonBJ J.HilkJ 2 Replies 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