nicodio
nicodio

Reputation: 55

Best way to timing events in Qt

I'm writing a software in Qt/c++ that communicate through serial with arduino and other electronic devices.

I need to start a sequence of events that call different slot with different timing like this:

I've tried with QTimer::singleShot but it works only with slot with no parameters and I need to set parameters like motor speed different from time to time.

Right now I'm using a delay function that confront currentTime do dieTime but it is complicated to keep track of timing to all the devices.

What is the best solution in doing this? Suggestions?

Upvotes: 3

Views: 1081

Answers (2)

TheDarkKnight
TheDarkKnight

Reputation: 27611

You can use the static QTimer single shot function if you use the overloaded method, which takes a Functor (function object). This would allow you to capture the variables required; which motor, speed, action etc. If you're not familiar with Functors, you can read about them here.

Alternatively, since the question provides no code examples, let's assume you've already written functions for starting and stopping motors. For a more direct method, with C++11, you could do something like this:

StartMotor(1);

// Stop in 20 seconds
QTimer* p1 = new QTimer;
connect(p1, &QTimer::timeout, [=]{
    StopMotor(1);
    p1->deleteLater(); // clean up
});
p1->start(1000 * 20); // trigger in 20 seconds

// After 10 seconds, start motor 2

QTimer* p2 = new QTimer;
connect(p2, &QTimer::timeout, [=]{
    StartMotor(2);

    // And Stop Motor 1
    StopMotor(1);

    p2->deleteLater(); // clean up
});
p2->start(1000 * 10); // trigger in 10 seconds

...And so on for each timed action.

Upvotes: 4

Valentin H
Valentin H

Reputation: 7448

Implement a class for a motor e.g.:

class Motor:public QObject
{
  Q_OBJECT
  public slots:
    void start();
    void start(int ms); //this one starts QTimer::singleShot and calls stop
    void stop();
};

I would recommend to check QStateMachine Framework. When tasks will get more complicated, you'd be better off using FSM than spaghetti of signal-slot calls.

In my current project I've built a FSM based on QStateMachine where the definition of FSMs is done in a DSL (domain specific language).

Upvotes: 3

Related Questions