I’m working on a QT QML and embedded STM32 project where an oven is being controlled by a PC via serial communications. Everything was going great until I tried to add a timed heartbeat signal to let both sides know that the other was still there and talking. The idea was to use a QTimer on the PC side to send a heartbeat packet if the PC had not received any oven data for more than a couple of seconds. The oven would then acknowledge the heartbeat and both sides would know that the other was still connected and running.
My problem has been with getting the QTimer to work without it being created in the main.c file. I have been working on this for several days trying any suggested solution I can find. NO Joy! I have gotten many different error messages. Like:
QObject::startTimer: Timers can only be used with threads started with QThread
QEventLoop: Cannot be used without QApplication
I’m still pretty new using QT and I have both search the internet and purchased and watched several Udemy tutorials trying to learn more. I have not found a working example or a good explanation of how this works and/or how it should be done.
The attached code is what I currently have. Please feel free to comment on any part of it.
The goal is to have the HeartBeatTimer class use a QTimer () that is reset by the SerialCom class every time data is received from the oven. If received data stops, a heartbeat will be sent to verify the connection, not heartbeat response the ALARM!!
Any assistance would be greatly appreciated (possibly a working example).
Thanks Jim
#define HEARTBEATTIMER_H
#include <QObject>
#include <QDebug>
#include <QTimer>
#include <QThread>
class HeartBeatTimer : public QObject
{
Q_OBJECT
public:
explicit HeartBeatTimer(QObject *parent = nullptr);
void Reset();
private:
QThread m_workerThread;
QTimer m_heartBeat;
signals:
public slots:
void ThreadStarted();
void TimedOut();
};
#endif // HEARTBEATTIMER_H
// The heart Beat timer is reset whenever the PC receives any serial
// communication from the Oven.
#include "heartBeatTimer.h"
#define HbTimeOut 2000
HeartBeatTimer::HeartBeatTimer(QObject *parent)
: QObject{parent}
{
this->moveToThread(&m_workerThread);
connect(&m_workerThread, SIGNAL(started()), this, SLOT(ThreadStarted()));
connect(&m_heartBeat, SIGNAL(timeout()), this, SLOT(TimedOut()));
m_workerThread.start();
}
void HeartBeatTimer::TimedOut()
{
qDebug() << "Timer...";
}
// Starts or restarts the timer.
void HeartBeatTimer::Reset()
{
m_heartBeat.start(HbTimeOut);
qDebug() << "Reset...";
}
void HeartBeatTimer::ThreadStarted()
{
m_heartBeat.start(HbTimeOut);
}
I create qtimer object in
HeartBeatTimer::ThreadStartedusenewoperator.Should be no error messages.