Quick Tutorial

1. Include the C/C++ headers

#include <assert.h>

2. Configure optional HFSM2 functionality using #defines (in this case we're using Plans to make transition cycle more straightforward):

#define HFSM2_ENABLE_PLANS

3. Include HFSM2 header:

#include <hfsm2/machine.hpp>

4. Define interface class between the state machine and its host (also ok to use the host object itself):

struct Context {
    bool powerOn;
};

5. (Optional) Define type config:

using Config = hfsm2::Config::ContextT<Context>;

6. (Optional, recommended) Definehfsm2::Machine for convenience:

using M = hfsm2::MachineT<Config>;

7. Declare state machine structure. States need to be forward declared, e.g. with a magic macro:

#define S(s) struct s

using FSM = M::PeerRoot<
                S(Off),                                // initial top-level state
                M::Composite<S(On),                    // sub-machine region with a head state (On) and and 3 sub-states
                    S(Red),                            // initial sub-state of the region
                    S(Yellow),
                    S(Green)
                >,
                S(Done)
            >;

#undef S

8. (Optional) While HFSM2 transitions aren't event-based, events can be used to have FSM react to external stimuli:

9. Define states and override required state methods:

10. Write the client code to use your new state machine:

11. Create context and state machine instances:

12. Call FSM::update() for the FSM to process transitions:

13. (Optional) Event reactions also cause transitions to be processed:

14. Keep updating the FSM for as long as necessary:

See Also

snippets/wiki_tutorial.cpp

Last updated

Was this helpful?