QTimers and QThreads
-
Dear all,
I'm writing an application which makes use of QTimers, QThreads and Socket_CAN.
I have a main visualization, I need to send at a certain timing a CANbus message and I want to read the data traffic on the bus at all times. So what I did:
- My main application which runs the visualization.
- CANopen Object.
Please see code below.
#include "canopen.h" CANOpen::CANOpen(QObject *parent) : QObject(parent) { NMT_timer = new QTimer(this); connect(NMT_timer,SIGNAL(timeout()),this,SLOT(NMT_Send())); // initialize CAN socket int com_error; com_error = can_socket->open_port("can0",0); if(com_error<0) { qDebug() << "E301: Internal Error: Unable to open CAN SOCKET. NO Communication possible" + QString::number(com_error); } // Start to send CANbus message at certain timing (800ms) NMT_timer->start(800); iStep = 0; } void CANOpen::canopen_init(QString canbus, int filter) { } void CANOpen::DoSetup(QThread &cThread) { // Setup thread. Function is called when a button is pushed connect(&cThread,SIGNAL(started()),this,SLOT(DoWork())); } void CANOpen::DoWork() { // Read traffic on CANbus qDebug() << "read port"; while(1){ can_socket->read_port(); } } void CANOpen::NMT_Send() { // Send message on CANbus qDebug() << "NMT message"; can_frame NMT_message; NMT_message.can_id = 0x701; NMT_message.can_dlc = 1; NMT_message.data[0] = 0x7F; can_socket->send_port(NMT_message); }
So what is happening now:
The application starts up and start to send messages on the CANbus every 800ms. So so far so good.
Then I push the button, so the DoWork function is called. The thread is started and I can read every message on the CANbus.
The only issue at this moment is that no messages are send on the CANbus anymore. I suppose the Thread block the timer to run. (The main application continues with out any issue)
Is this correct? Ifso, how can I solve this please?Thanks in advance,
Kind regards,
TMJJ -
@TMJJ001 said in QTimers and QThreads:
connect(&cThread,SIGNAL(started()),this,SLOT(DoWork()));
You do NOT execute DoWork() in that thread, you execute it in the GUI thread.
Take a closer look at the example here: https://doc.qt.io/qt-5/qthread.html