Best way to sync events in Qt

I am writing software in Qt / C ++ that communicates via serial port with arduino and other electronic devices.

I need to fire a sequence of events that trigger a different slot with different times:

  • Start engine 1 within 20 seconds
  • After 10 seconds Start engine 2
  • Stop engine 1
  • Change motor 1 speed
  • Start engine 1 within 30 seconds

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

I am currently using a delay function that opposes currentTime do dieTime, but it is difficult to keep track of the time across all devices.

What's the best solution? Suggestions?

+3


source to share


2 answers


You can use the static single shot QTimer function if you use an overloaded method here .

Alternatively, since the question does not contain any code examples, assume that you have already created functions for starting and stopping motors. For a more direct method since C ++ 11, you can 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.

+4


source


Implementing a class for an engine, for example:

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 checking out the QStateMachine Framework. When things get more complicated, you are better off using FSM than spaghetti calls to signal slots.

In my current project, I have built an FSM based on QStateMachine, where the FSM definition is done in DSL (domain specific language).

+3


source







All Articles