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. QSerialPort outside main function not working
Forum Updated to NodeBB v4.3 + New Features

QSerialPort outside main function not working

Scheduled Pinned Locked Moved Unsolved General and Desktop
11 Posts 3 Posters 706 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.
  • J Offline
    J Offline
    julienchz
    wrote on last edited by julienchz
    #1

    Hello, I'm trying to get data from an USB connection with QSerialPort. When I am running the following code from the main function, everything works properly. However, when I try to run this code somewhere else, I manage to open the connection but I can't read any data. What could be the reason of this beahvior ?

        QList<QSerialPortInfo> serialPortInfoList = QSerialPortInfo::availablePorts();
        QSerialPortInfo currentPortInfo;;
        for (QSerialPortInfo& portInfo: serialPortInfoList)
        {
            if (portInfo.description() == "USB-SERIAL CH340")
            {
                qDebug() << "Valid port found";
                currentPortInfo = portInfo;
            }
        }
        
        QSerialPort serialPort(currentPortInfo);
        serialPort.setBaudRate(57600);
        
        if (!serialPort.setDataBits(QSerialPort::Data8))
            qDebug() << "Data bits not set";
        if (!serialPort.setFlowControl(QSerialPort::HardwareControl))
            qDebug() << "Flow control not set";
        if (!serialPort.setParity(QSerialPort::NoParity))
            qDebug() << "Parity not set";
        if (!serialPort.setStopBits(QSerialPort::OneStop))
            qDebug() << "Stop bits not set";
        if (!serialPort.open(QIODevice::ReadOnly))
        {
            qDebug() << "Failed to open port";
        }
        
        QObject::connect(&serialPort, &QSerialPort::readyRead, [&]
        {
            //this is called when readyRead() is emitted
            qDebug() << "New data available: " << serialPort.bytesAvailable();
            QByteArray datas = serialPort.readAll();
            qDebug() << datas;
        });
    

    Thank you for your help

    JonBJ 1 Reply Last reply
    0
    • J julienchz

      Hello, I'm trying to get data from an USB connection with QSerialPort. When I am running the following code from the main function, everything works properly. However, when I try to run this code somewhere else, I manage to open the connection but I can't read any data. What could be the reason of this beahvior ?

          QList<QSerialPortInfo> serialPortInfoList = QSerialPortInfo::availablePorts();
          QSerialPortInfo currentPortInfo;;
          for (QSerialPortInfo& portInfo: serialPortInfoList)
          {
              if (portInfo.description() == "USB-SERIAL CH340")
              {
                  qDebug() << "Valid port found";
                  currentPortInfo = portInfo;
              }
          }
          
          QSerialPort serialPort(currentPortInfo);
          serialPort.setBaudRate(57600);
          
          if (!serialPort.setDataBits(QSerialPort::Data8))
              qDebug() << "Data bits not set";
          if (!serialPort.setFlowControl(QSerialPort::HardwareControl))
              qDebug() << "Flow control not set";
          if (!serialPort.setParity(QSerialPort::NoParity))
              qDebug() << "Parity not set";
          if (!serialPort.setStopBits(QSerialPort::OneStop))
              qDebug() << "Stop bits not set";
          if (!serialPort.open(QIODevice::ReadOnly))
          {
              qDebug() << "Failed to open port";
          }
          
          QObject::connect(&serialPort, &QSerialPort::readyRead, [&]
          {
              //this is called when readyRead() is emitted
              qDebug() << "New data available: " << serialPort.bytesAvailable();
              QByteArray datas = serialPort.readAll();
              qDebug() << datas;
          });
      

      Thank you for your help

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

      @julienchz

      QSerialPort serialPort(currentPortInfo);
      QObject::connect(&serialPort, &QSerialPort::readyRead, [&] { ... }
      

      serialPort is local variable. If in main() its lifetime is as long as your program. If you put this elsewhere think about its scope/lifetime.

      J 1 Reply Last reply
      2
      • JonBJ JonB

        @julienchz

        QSerialPort serialPort(currentPortInfo);
        QObject::connect(&serialPort, &QSerialPort::readyRead, [&] { ... }
        

        serialPort is local variable. If in main() its lifetime is as long as your program. If you put this elsewhere think about its scope/lifetime.

        J Offline
        J Offline
        julienchz
        wrote on last edited by
        #3

        @JonB I tried to use it as an attribute of a class inheriting QObject, but without success

        Christian EhrlicherC JonBJ 2 Replies Last reply
        0
        • J julienchz

          @JonB I tried to use it as an attribute of a class inheriting QObject, but without success

          Christian EhrlicherC Online
          Christian EhrlicherC Online
          Christian Ehrlicher
          Lifetime Qt Champion
          wrote on last edited by
          #4

          @julienchz said in QSerialPort outside main function not working:

          I tried to use it as an attribute of a class inheriting QObject, but without success

          please show the code

          Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
          Visit the Qt Academy at https://academy.qt.io/catalog

          J 1 Reply Last reply
          0
          • J julienchz

            @JonB I tried to use it as an attribute of a class inheriting QObject, but without success

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

            @julienchz That in itself says nothing about the instance's lifetime.

            1 Reply Last reply
            0
            • Christian EhrlicherC Christian Ehrlicher

              @julienchz said in QSerialPort outside main function not working:

              I tried to use it as an attribute of a class inheriting QObject, but without success

              please show the code

              J Offline
              J Offline
              julienchz
              wrote on last edited by
              #6

              @Christian-Ehrlicher @JonB Here is my class

              class SerialPortReader : public QObject
              {
                  Q_OBJECT
              public:
                  explicit SerialPortReader(QObject *parent = nullptr);
              
              protected:
                  QSerialPortInfo FindSerialPortInfo();
              
              private slots:
                  void HandleReadyRead();
                  void HandleTimeout();
                  void HandleError(QSerialPort::SerialPortError error);
              
              private:
                  const QString PORT_DESCRIPTION = "USB-SERIAL CH340";
                  const qint32 BAUD_RATE = QSerialPort::Baud57600;
              
                  QSerialPort *m_serialPort;
                  QByteArray m_readData;
                  QTextStream m_standardOutput;
                  QTimer m_timer;
              };
              
              SerialPortReader::SerialPortReader(QObject *parent) :
                  QObject(parent),
                  m_serialPort(new QSerialPort(this))
              {
                  QSerialPortInfo portInfo = FindSerialPortInfo();
                  if (portInfo.isNull())
                      return;
              
              
                  m_serialPort->setPort(portInfo);
                  // m_serialPort = new QSerialPort(portInfo, this);
                  if (!m_serialPort->setBaudRate(BAUD_RATE))
                      qDebug() << "Baud rate not set";
                  if (!m_serialPort->setDataBits(QSerialPort::Data8))
                      qDebug() << "Data bits not set";
                  if (!m_serialPort->setFlowControl(QSerialPort::HardwareControl))
                      qDebug() << "Flow control not set";
                  if (!m_serialPort->setParity(QSerialPort::NoParity))
                      qDebug() << "Parity not set";
                  if (!m_serialPort->setStopBits(QSerialPort::OneStop))
                      qDebug() << "Stop bits not set";
              
                  if (!m_serialPort->open(QIODevice::ReadOnly))
                  {
                      qDebug() << "Failed to open port";
                      return;
                  }
              
                  qDebug() << "Port correctly opened";
              
                  connect(m_serialPort, &QSerialPort::readyRead, this, &SerialPortReader::HandleReadyRead);
                  connect(m_serialPort, &QSerialPort::errorOccurred, this, &SerialPortReader::HandleError);
                  connect(&m_timer, &QTimer::timeout, this, &SerialPortReader::HandleTimeout);
              
                  m_timer.start(5000);
              }
              
              QSerialPortInfo SerialPortReader::FindSerialPortInfo()
              {
                  QList<QSerialPortInfo> serialPortInfoList = QSerialPortInfo::availablePorts();
                  for (QSerialPortInfo& portInfo: serialPortInfoList)
                  {
                      if (portInfo.description() == PORT_DESCRIPTION)
                      {
                          qDebug() << "Valid port found";
                          return portInfo;
                      }
                  }
              
                  qDebug() << "No valid port found";
                  return QSerialPortInfo();
              }
              
              
              void SerialPortReader::HandleReadyRead()
              {
                  m_readData.append(m_serialPort->readAll());
              
                  if (!m_timer.isActive())
                      m_timer.start(5000);
              }
              
              void SerialPortReader::HandleTimeout()
              {
                  if (m_readData.isEmpty()) {
                      qDebug() << QObject::tr("No data was currently available "
                                                      "for reading from port");
                  } else {
                      qDebug() << QObject::tr("Data successfully received from port");
                      qDebug() << m_readData;
                  }
              }
              
              void SerialPortReader::HandleError(QSerialPort::SerialPortError serialPortError)
              {
                  if (serialPortError == QSerialPort::ReadError) {
                      qDebug() << QObject::tr("An I/O error occurred while reading "
                                                      "the data from port, error:");
                  }
              }
              
              Christian EhrlicherC JonBJ 2 Replies Last reply
              0
              • J julienchz

                @Christian-Ehrlicher @JonB Here is my class

                class SerialPortReader : public QObject
                {
                    Q_OBJECT
                public:
                    explicit SerialPortReader(QObject *parent = nullptr);
                
                protected:
                    QSerialPortInfo FindSerialPortInfo();
                
                private slots:
                    void HandleReadyRead();
                    void HandleTimeout();
                    void HandleError(QSerialPort::SerialPortError error);
                
                private:
                    const QString PORT_DESCRIPTION = "USB-SERIAL CH340";
                    const qint32 BAUD_RATE = QSerialPort::Baud57600;
                
                    QSerialPort *m_serialPort;
                    QByteArray m_readData;
                    QTextStream m_standardOutput;
                    QTimer m_timer;
                };
                
                SerialPortReader::SerialPortReader(QObject *parent) :
                    QObject(parent),
                    m_serialPort(new QSerialPort(this))
                {
                    QSerialPortInfo portInfo = FindSerialPortInfo();
                    if (portInfo.isNull())
                        return;
                
                
                    m_serialPort->setPort(portInfo);
                    // m_serialPort = new QSerialPort(portInfo, this);
                    if (!m_serialPort->setBaudRate(BAUD_RATE))
                        qDebug() << "Baud rate not set";
                    if (!m_serialPort->setDataBits(QSerialPort::Data8))
                        qDebug() << "Data bits not set";
                    if (!m_serialPort->setFlowControl(QSerialPort::HardwareControl))
                        qDebug() << "Flow control not set";
                    if (!m_serialPort->setParity(QSerialPort::NoParity))
                        qDebug() << "Parity not set";
                    if (!m_serialPort->setStopBits(QSerialPort::OneStop))
                        qDebug() << "Stop bits not set";
                
                    if (!m_serialPort->open(QIODevice::ReadOnly))
                    {
                        qDebug() << "Failed to open port";
                        return;
                    }
                
                    qDebug() << "Port correctly opened";
                
                    connect(m_serialPort, &QSerialPort::readyRead, this, &SerialPortReader::HandleReadyRead);
                    connect(m_serialPort, &QSerialPort::errorOccurred, this, &SerialPortReader::HandleError);
                    connect(&m_timer, &QTimer::timeout, this, &SerialPortReader::HandleTimeout);
                
                    m_timer.start(5000);
                }
                
                QSerialPortInfo SerialPortReader::FindSerialPortInfo()
                {
                    QList<QSerialPortInfo> serialPortInfoList = QSerialPortInfo::availablePorts();
                    for (QSerialPortInfo& portInfo: serialPortInfoList)
                    {
                        if (portInfo.description() == PORT_DESCRIPTION)
                        {
                            qDebug() << "Valid port found";
                            return portInfo;
                        }
                    }
                
                    qDebug() << "No valid port found";
                    return QSerialPortInfo();
                }
                
                
                void SerialPortReader::HandleReadyRead()
                {
                    m_readData.append(m_serialPort->readAll());
                
                    if (!m_timer.isActive())
                        m_timer.start(5000);
                }
                
                void SerialPortReader::HandleTimeout()
                {
                    if (m_readData.isEmpty()) {
                        qDebug() << QObject::tr("No data was currently available "
                                                        "for reading from port");
                    } else {
                        qDebug() << QObject::tr("Data successfully received from port");
                        qDebug() << m_readData;
                    }
                }
                
                void SerialPortReader::HandleError(QSerialPort::SerialPortError serialPortError)
                {
                    if (serialPortError == QSerialPort::ReadError) {
                        qDebug() << QObject::tr("An I/O error occurred while reading "
                                                        "the data from port, error:");
                    }
                }
                
                Christian EhrlicherC Online
                Christian EhrlicherC Online
                Christian Ehrlicher
                Lifetime Qt Champion
                wrote on last edited by Christian Ehrlicher
                #7

                And what 'does not work' with this code?
                The timeout handling looks strange... why wait 5000ms before doing something with the received data?

                Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                Visit the Qt Academy at https://academy.qt.io/catalog

                J 1 Reply Last reply
                0
                • Christian EhrlicherC Christian Ehrlicher

                  And what 'does not work' with this code?
                  The timeout handling looks strange... why wait 5000ms before doing something with the received data?

                  J Offline
                  J Offline
                  julienchz
                  wrote on last edited by
                  #8

                  @Christian-Ehrlicher It was from an example I commented it to try. The opening of the port is successful but the signal readyRead is never triggered

                  Christian EhrlicherC 1 Reply Last reply
                  0
                  • J julienchz

                    @Christian-Ehrlicher It was from an example I commented it to try. The opening of the port is successful but the signal readyRead is never triggered

                    Christian EhrlicherC Online
                    Christian EhrlicherC Online
                    Christian Ehrlicher
                    Lifetime Qt Champion
                    wrote on last edited by
                    #9

                    @julienchz Are you sure that there is data coming in? And do you have a running eventloop (QCoreApplication::exec() in your main.cpp?)

                    Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                    Visit the Qt Academy at https://academy.qt.io/catalog

                    1 Reply Last reply
                    0
                    • J julienchz

                      @Christian-Ehrlicher @JonB Here is my class

                      class SerialPortReader : public QObject
                      {
                          Q_OBJECT
                      public:
                          explicit SerialPortReader(QObject *parent = nullptr);
                      
                      protected:
                          QSerialPortInfo FindSerialPortInfo();
                      
                      private slots:
                          void HandleReadyRead();
                          void HandleTimeout();
                          void HandleError(QSerialPort::SerialPortError error);
                      
                      private:
                          const QString PORT_DESCRIPTION = "USB-SERIAL CH340";
                          const qint32 BAUD_RATE = QSerialPort::Baud57600;
                      
                          QSerialPort *m_serialPort;
                          QByteArray m_readData;
                          QTextStream m_standardOutput;
                          QTimer m_timer;
                      };
                      
                      SerialPortReader::SerialPortReader(QObject *parent) :
                          QObject(parent),
                          m_serialPort(new QSerialPort(this))
                      {
                          QSerialPortInfo portInfo = FindSerialPortInfo();
                          if (portInfo.isNull())
                              return;
                      
                      
                          m_serialPort->setPort(portInfo);
                          // m_serialPort = new QSerialPort(portInfo, this);
                          if (!m_serialPort->setBaudRate(BAUD_RATE))
                              qDebug() << "Baud rate not set";
                          if (!m_serialPort->setDataBits(QSerialPort::Data8))
                              qDebug() << "Data bits not set";
                          if (!m_serialPort->setFlowControl(QSerialPort::HardwareControl))
                              qDebug() << "Flow control not set";
                          if (!m_serialPort->setParity(QSerialPort::NoParity))
                              qDebug() << "Parity not set";
                          if (!m_serialPort->setStopBits(QSerialPort::OneStop))
                              qDebug() << "Stop bits not set";
                      
                          if (!m_serialPort->open(QIODevice::ReadOnly))
                          {
                              qDebug() << "Failed to open port";
                              return;
                          }
                      
                          qDebug() << "Port correctly opened";
                      
                          connect(m_serialPort, &QSerialPort::readyRead, this, &SerialPortReader::HandleReadyRead);
                          connect(m_serialPort, &QSerialPort::errorOccurred, this, &SerialPortReader::HandleError);
                          connect(&m_timer, &QTimer::timeout, this, &SerialPortReader::HandleTimeout);
                      
                          m_timer.start(5000);
                      }
                      
                      QSerialPortInfo SerialPortReader::FindSerialPortInfo()
                      {
                          QList<QSerialPortInfo> serialPortInfoList = QSerialPortInfo::availablePorts();
                          for (QSerialPortInfo& portInfo: serialPortInfoList)
                          {
                              if (portInfo.description() == PORT_DESCRIPTION)
                              {
                                  qDebug() << "Valid port found";
                                  return portInfo;
                              }
                          }
                      
                          qDebug() << "No valid port found";
                          return QSerialPortInfo();
                      }
                      
                      
                      void SerialPortReader::HandleReadyRead()
                      {
                          m_readData.append(m_serialPort->readAll());
                      
                          if (!m_timer.isActive())
                              m_timer.start(5000);
                      }
                      
                      void SerialPortReader::HandleTimeout()
                      {
                          if (m_readData.isEmpty()) {
                              qDebug() << QObject::tr("No data was currently available "
                                                              "for reading from port");
                          } else {
                              qDebug() << QObject::tr("Data successfully received from port");
                              qDebug() << m_readData;
                          }
                      }
                      
                      void SerialPortReader::HandleError(QSerialPort::SerialPortError serialPortError)
                      {
                          if (serialPortError == QSerialPort::ReadError) {
                              qDebug() << QObject::tr("An I/O error occurred while reading "
                                                              "the data from port, error:");
                          }
                      }
                      
                      JonBJ Offline
                      JonBJ Offline
                      JonB
                      wrote on last edited by JonB
                      #10

                      @julienchz
                      Does your SerialPortReader instance (wherever you create it) live as long as the readyRead()s you are expecting.

                      When I am running the following code from the main function, everything works properly. However, when I try to run this code somewhere else, I manage to open the connection but I can't read any data

                      If that is the case lifetime seems the obvious candidate.

                      1 Reply Last reply
                      0
                      • J Offline
                        J Offline
                        julienchz
                        wrote on last edited by
                        #11

                        @Christian-Ehrlicher Yes i'am sure there is data coming

                        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