Skip to main content

Subsection 2.7.2 Part 2: The State Machine Pattern

Next we’ll put a name to what your code is already doing. Your toggleLED.c implements a finite state machine: the buttonAlreadyPressed variable is the state variable, and the two branches of the if are its two states. The button can be pressed or unpressed, but it is only when we observe a transition that the program needs to do anything: update the state, and toggle the LED on the transition from unpressed to pressed. We’ll write that same logic out twice, once as a formal state diagram and once as C using typedef enum and switch, so that the diagram and the code can be read against each other line by line.
Figure 2.7.1. State diagram for the button-toggle finite state machine (FSM). The two states (Unpressed/Pressed) track whether the button is currently down. The LED toggles exactly once (on the Unpressed→Pressed transition), and the code snippet on each arrow is the C expression that triggers it. The legend (right) maps the color-coded terms to the FSM vocabulary.
#include "ES28.h"            // All the port definitions are here

#define GPIOAEN        (1U<<0)    // Clock access to GPIOA (LED)
#define GPIOBEN        (1U<<1)    // Clock access to GPIOB (button)

#define LED_PIN        (1U<<5)    // LED on PA5     (D13)
#define BUTTON_PIN     (1U<<4)    // Button on PB4 (D5)

typedef enum {UNPRESSED, PRESSED} state_t;

int main(void) {
    state_t state = UNPRESSED;
    unsigned buttonPushed = 0;
    RCC->IOPENR |= (GPIOAEN | GPIOBEN); // Enable clock access

    GPIOA->MODER |= (1U<<10);    // Configure PA5 as output pin
    GPIOA->MODER &= ~(1U<<11);

    GPIOB->MODER &= ~(1U<<8);    // Configure PB4 as input pin
    GPIOB->MODER &= ~(1U<<9);    // (both bits: the reset value is analog, 0b11)

    GPIOB->PUPDR |= (1U<<8);     // enable pull-up for PB4
    GPIOB->PUPDR &= ~(1U<<9);

    while(1) {
        buttonPushed = ((GPIOB->IDR & BUTTON_PIN) == 0);
        switch(state) {
            case UNPRESSED:
                if (buttonPushed) {
                    GPIOA->ODR ^= LED_PIN;
                    state = PRESSED;
                }
                break;
            case PRESSED:
                if (!buttonPushed) {
                    state = UNPRESSED;
                }
                break;
        }
    }
    return 0;                    // never reached
}
Because there is no blocking while loop, this FSM can be embedded in a larger main loop that can blink LEDs, read a UART, or do other work: the state variable preserves context across iterations.