Modbus Com in different thread

  • Hi,
    I'm trying to move QModbusRtuSerialMaster in other thread but when try to read something I'm getting this error QObject::startTimer: Timers cannot be started from another thread
    I think this is something inside Qt class and my thought is I can't move this class in separated thread.
    Can someone help me?

  • Moderators

    @guerinoni how is your QModbusRtuSerialMaster instance created ?

    preferably show some code.

    It is possible and is most likely a parenting issue

  • @J-Hilk
    I have this class to handle modbus

    class ModbusCom : public QObject
        explicit ModbusCom(QObject *parent = nullptr);
        [[nodiscard]] bool connectModbus(const SerialPortSettings &settings);
        [[nodiscard]] bool connectModbus(const QString &portName,
                                         QSerialPort::BaudRate baudRate = QSerialPort::Baud9600,
                                         QSerialPort::DataBits dataBits = QSerialPort::Data8,
                                         QSerialPort::Parity parity = QSerialPort::NoParity,
                                         QSerialPort::StopBits stopBits = QSerialPort::OneStop);
        void disconnectModbus();
    public slots:
        virtual void readRegisters(int startingAddress, uint16_t size);
        virtual void writeRegisters(int startingAddress, uint16_t size, std::vector<uint16_t> values);
    private Q_SLOTS:
        void handleReadyRead();
        void modbusConnected();
        void modbusDisconnected();
        void modbusError(const QString &errorString, QModbusDevice::Error error);
        void updateValue(int address, uint16_t value);
        QModbusRtuSerialMaster m_modbusDevice;
        [[nodiscard]] bool open();

    this is ctor

    ModbusCom::ModbusCom(QObject *parent)
        : QObject(parent)
        connect(&m_modbusDevice, &QModbusClient::errorOccurred, this, [this](QModbusDevice::Error error) {
            qCWarning(Serial) << QStringLiteral("Error occurred: %1 (code 0x%2)")
            Q_EMIT modbusError(m_modbusDevice.errorString(), error);
                [this](QModbusDevice::State state) {
                    if (state == QModbusDevice::UnconnectedState) {
                        Q_EMIT modbusDisconnected();

    and from other class when emit read I just connect slot of this class to call a read

    void ModbusCom::readRegisters(int startingAddress, uint16_t size)
        auto dataUnit = QModbusDataUnit(QModbusDataUnit::HoldingRegisters, startingAddress, size);
        if (auto *reply = m_modbusDevice.sendReadRequest(dataUnit, 1)) {
            //        if (!reply->isFinished()) {
            //            connect(reply, &QModbusReply::finished, this, &ModbusCom::handleReadyRead);
            //            connect(reply,
            //                    &QModbusReply::errorOccurred,
            //                    this,
            //                    [this, reply](QModbusDevice::Error error) {
            //                        Q_EMIT modbusError(reply->errorString(), error);
            //                        reply->deleteLater();
            //                    });
            //        } else {
            //            delete reply;
            //        }
        } else {
            qCCritical(Serial) << "Read error:" << m_modbusDevice.errorString();

    when sendReadRequest is called the error i shown

  • Moderators

    @guerinoni ok, m_modbusDevice.setParent(this); should work, even so I'm usually assign the parent in the class initializer list.

    Can you share the section where you create the instance of MosbusCom and where you move it to the thread ?

  • @J-Hilk
    Ok, I can move it in .hpp file like QModbusRtuSerialMaster m_modbusDevice{this};
    All is in a SerialWorker

    class SerialComWorker
        const ModbusCom &modbusCom() const;
        Protocol &protocol();
        OvenPreferencesContainer::OvenTypes m_currentOvenProtocol;
        SerialPortSettings m_serialSettings;
        Protocol m_comProtocol;
        ModbusCom m_modbus;
        QThread m_thread;
        void loadProtocol();

    and the magic in ctor

        : m_currentOvenProtocol{OvenPreferencesContainer::MaxOvenTypes}
        QObject::connect(&m_thread, &QThread::started, &m_modbus, [&]() { loadProtocol(); });

  • Moderators

    ok, heap allocate this one ModbusCom m_modbus; (without with a nullptr as parent), it should be completely detached from your SerialComWorker class otherwise you also run the possible issue of deleting the ModbusCom while m_thread is still active

  • @J-Hilk
    I have same problem

        : m_currentOvenProtocol{OvenPreferencesContainer::MaxOvenTypes}
        m_modbus = new ModbusCom;
        QObject::connect(&m_thread, &QThread::started, m_modbus, [&]() { loadProtocol(); });

    I change only this. I'm on Qt 5.12.7 (embedded but it doesn't matter)

  • Moderators

    actually, looking into the source code of 5.12.7 there seem to be 2 member timers that life in the thread during creation oO

    mmh, what you can do, since you actually listen to the thread started signal,

    You could create a init function, that instantiates the RtuMaster than and after that call loadProtocol()

    would be a workaround!

  • @J-Hilk
    ehehe because of this I posted this question... If I switch on Qt 5.14.x can I resolve this?

  • Moderators

    possibly , the QTimer's are replaced with a custom timer class

    I'm sure that was done for some reason ;)

  • @J-Hilk
    It seems work correctly with 5.14.2 and the workaroud that you suggest :D

  • because m_modbusDevice is created in the constructor of ModbusCom and ModbusCom is instanced in mainthread. So m_modbusDevice is the object belonging the mainthread, and its timeout QTimer can't be worked propertly.

    To fix that, try to create the m_modbusDevice in m_thread, for exaple:

    class ModbusCom
       QModbusRtuSerialMaster*  m_modbusDevice;
       void initModbus()
        m_modbusDevice=new QModbusRtuSerialMaster();//created in m_thread
         //other initialization code...
    connect(SerialComWorker,SIGNAL(startModbus()), m_modbus,SLOT( initModbus()); //then initModbus() function will excute in m_thread and m_modbusDevice will be m_thread's obejct.
    emit startModbus();

Log in to reply