c++qtperipherals

Continuous check in the main loop in Qt 5.5


I have a device that moves on a linear path, basically a linear actuator. When the device reaches the physical ends, it hits a limit contact which sends a signal to my software. I will need to continually check if this signal is online. But I'm having difficulties implementing this logic in Qt5.5.

I've been reading on QtConcurrent and it seems like a viable solution but after implementing it on a test drive I found out that I cannot solve my problem without some sort of a while(true) loop. However implementing a while(true) loop seems to slow down everything else on my code therefore rendering this solution completely useless.

I would post code but given that it uses libraries and nomenclature of devices that are of a very specific niche I will spare you the pain but if anyone can guide me towards reading up on something like this I would be most grateful. I would prefer to steer clear of QtThread and basically manually setting up threads since I do not feel comfortable working with them at this point, and I do have a time limit on this project so it would be best if I don't experiment much.

tldr: I need to put some code somehow within the main loop of the program that checks for a boolean value change. The said change is sent to the program externally by a device which is communicating through Ethernet.


Solution

  • class Checker : public QObject
    {
        Q_OBJECT
    public:
        Checker(void)
        {
            timer.setInterval(100);// give it a interval, like 100ms?
            connect(timer, SIGNAL(timeout()), this, SLOT(checkHW()));
        }
        void start(void)
        {
            timer.start();// although you can start the timer in the constructor 
                          // but I guess you want to start it later, after HW is   
                          // ready.
        }
    private Q_SLOTS:
        void checkHW()
        {
            bool hit = false;
            // check the hardware here
            if(hit){
                emit hitEnd();// tell others about the event
            }
        }
    signals:
        void hitEnd(void);
    private:
        QTimer timer;
    }
    

    If checking the hardware switch doesn't take much time, then you don't really need another thread. However, if checkHW() does takes a lot of time, then it helps if this class is moved out of the main thread.