Skip to main content
2 of 2
Add state machine explanation in code
Thomas Weller
  • 1.1k
  • 1
  • 9
  • 24

What you likely need is a state machine. The behavior of the actions depends on the state the program is currently in.

In your case, the state machine might look like this:

State machine

What does it mean?

  • black circle: this is where the system powers on
  • rectangle: a state
  • arrow: a transition from one state to another
  • green text: action

For the problematic double click action, you can see:

  • it changes the state from "set size" to "speed"
  • in all other cases, it does not change the state (actually it changes the state to the same state)

I always recommend drawing the state machine before implementing it. It makes mistakes much more obvious.

There are several ways to implement it. The easiest one being a switch/case. More advanced implementations may use object orientation. When using switch/case, I prefer to have one method per state, like so:

void loop()
{
    switch(state):
        case setsize:
             setsize();
             break;
        case speed:
             speed();
             break;
        ...
}

If you know about function pointers, it gets even easier:

enum State {
  setsize = 0,
  speed,
  clock,
  temperature
};

State state;

void setup() {
  state = State::setsize;
}


typedef void (* functionPointer) ();
functionPointer process[] = {do_setsize, do_speed, do_clock, do_temperature};
void loop() {
  process[state]();
}

void do_setsize()
{
  state = State::speed;
}
void do_speed()
{
  state = State::clock;
}
void do_temperature()
{
  state = State::speed;
}
void do_clock()
{
  state = State::temperature;
}
Thomas Weller
  • 1.1k
  • 1
  • 9
  • 24