[PROGRAMMING TIPS] - A simple state machine

Software Help

This was originally posted as a reply in a thread, but I thought it might be of more general interest.

Pastebin

Here's a very simple, watered-down explanation of a State Machine. In this example I'm working with the ATMega328 (Arduino UNO, etc.), and you can find its user manual here.

A finite-state machine can only be in one state at any given time. Each state is associated with some action.

Let's take your most simple case: a machine that takes temperature readings from a sensor and calculates an average every 15 minutes. Such a machine would have four states:

  • STARTUP (it has just been switched on)
  • WAITING (it does nothing)
  • MEASURING (it's taking measurements and calculating averages)
  • SHUTDOWN (it is being powered down)

The STARTUP and SHUTDOWN states are optional (the latter more so) and only each run once. These are once-off states. The other two states, SLEEPING and MEASURING is what the machine will be doing while it's running. These are running states.

You can list your states in an enum:

enum States {
    STARTUP,
    WAITING,
    MEASURING,
    SHUTDOWN
};

and keep track of the state with a global variable:

enum States currentState;

in your main() function you will initialise the state by

currentState = STARTUP;

Your loop() function will make use of switch() to determine the behaviour of your machine:

void loop() {
    switch(currentState) {
        case STARTUP:
        init();
        break;

        case WAITING:
        //do nothing
        break;

        case MEASURING:
        measure();
        break;

        case SHUTDOWN:
        shutdown();
        break;

        default:
        currentState = WAITING;
        break;
    }
}

In each of the functions init(), measure() and shutdown() is the code for the actions that should be taken for each one of the states. Since the currentState was set to STARTUP in main(), as soon as theswitch() in the loop() function is entered it will immediately execute the init() function.

In this case, the init() function will be used to set up your Timer0 module to run at 1/1024 of your processor's speed (here assuming ATMega328 @ 16MHz) and to enable the Timer0 interrupt:

void init() {
    TCCR0B |= (1 << CS02) | (1 << CS00);//prescaler set to Fosc/1024 (see page 142)
    TIMSK0 |= (1 << TOV0);//enable Timer0 Overflow Interrupt (see page 143)
    currentState = WAITING;//<--Change the state!
    sei();//enable interrupts
}

For this to work you also need a global variable

unsigned int timerCounter;

and an interrupt service routine

ISR(TIMER0_OVF_vect)
{
    timerCounter++;
    if (timerCounter >= 54931)
    {
        timerCounter = 0;
        currentState = MEASURING;//<--Change the state!
    }
}

Quick explanation of above: The CS clock select bits in the timer control registerTCCR0B is set to run at 1/1024th of the 16MHz clock speed, so it's running at 15.625kHz. The timer0 counter register is automatically incremented once a (timer) clock cycle until it reaches 256 at which point it overflows, raises an interrupt, and resets back to 0. This overflow will happen 15625/256 = 61.035 times a second, so the ISR will be triggered 61.035 times a second, which means timerCounter will increment at the same rate. There are 900 seconds in 15 minutes, therefor the overflow will happen 900*61.035=51931 times in 15 minutes. As seen in the above code, if timerCounterreaches this amount, it is set back to 0 and the currentState is set to MEASURING.

This is called a state transition, as the state was WAITING when the function was entered, and transitioned to MEASURING when it exits.

Back in the loop(), the switch() will respond to the state by branching to the measure() function. As is always the case, make sure to change the state when exiting the function:

void measure()
{
    /* All your measurement and averaging stuff happens here */
    currentState = WAITING;//<--Change the state!
}

...and that's it! There are of course a few optimisations that can be done (like sleeping in stead of waiting (see page Section 14 on page 62)), but this is the gist of an interrupt-based state machine.

Posted May 28, 2019, 6:01 PM UTC · edited

212
kodetroll•

Kudos for a great post explaining a finite state machine. I have two observations, though. I prefer to always express the default case in the switch() statement to handle unexpected issues. If the state variable unexpectedly jumps to non-enumerated value (cause reasons), the state machine would spin forever with no way to recover. The default case could be used to steer the unexpected state value back to a 'safe' state as well as make note of the unexpected state with an error message of some kind.

The other observation I have is that you don't set the next state in the init() function until after enabling interrupts. I prefer to set the next state before enabling interrupts. Murphy says and all that. Probably paranoia on my part.

6
asking_scienceOP•

You're absolutely right about your second observation, I will have edited it by the time you read this. Thanks. Your first one, however, I'm yet (in all my years) to see that happen. Yeah, a stray cosmic ray might just rip through the MCU core and flip a bit, but that's quite rare. That said, the pedant in me got triggered so, ok, I'll add a default.

1