0
0
Embedded Cprogramming~5 mins

Simple state machine with switch-case in Embedded C

Choose your learning style9 modes available
Introduction

A state machine helps a program remember what it is doing and decide what to do next. Using switch-case makes it easy to check the current state and act accordingly.

Controlling a traffic light that changes colors in order.
Managing a simple game where the player moves between menus and playing states.
Handling a device that turns on, waits, and then turns off automatically.
Reading buttons where each press changes the mode of operation.
Syntax
Embedded C
switch (state) {
    case STATE1:
        // actions for STATE1
        break;
    case STATE2:
        // actions for STATE2
        break;
    // add more states as needed
    default:
        // default action
        break;
}

Each case matches a state value.

Use break; to stop checking other cases after one matches.

Examples
Simple two-state machine: IDLE and RUNNING.
Embedded C
switch (state) {
    case IDLE:
        // wait for event
        break;
    case RUNNING:
        // perform task
        break;
}
Traffic light cycle switching states inside each case.
Embedded C
switch (state) {
    case RED:
        // turn on red light
        state = GREEN;
        break;
    case GREEN:
        // turn on green light
        state = YELLOW;
        break;
    case YELLOW:
        // turn on yellow light
        state = RED;
        break;
}
Sample Program

This program cycles through three states: OFF, ON, and BLINK. It prints the current state and then moves to the next one. It repeats this 5 times.

Embedded C
#include <stdio.h>

// Define states
#define STATE_OFF 0
#define STATE_ON 1
#define STATE_BLINK 2

int main() {
    int state = STATE_OFF;
    int count = 0;

    while (count < 5) {
        switch (state) {
            case STATE_OFF:
                printf("State: OFF\n");
                state = STATE_ON;
                break;
            case STATE_ON:
                printf("State: ON\n");
                state = STATE_BLINK;
                break;
            case STATE_BLINK:
                printf("State: BLINK\n");
                state = STATE_OFF;
                break;
            default:
                printf("Unknown state\n");
                state = STATE_OFF;
                break;
        }
        count++;
    }
    return 0;
}
OutputSuccess
Important Notes

Always include a default case to catch unexpected states.

Remember to update the state inside each case to move the machine forward.

Summary

A state machine keeps track of what the program is doing.

Use switch-case to handle different states clearly.

Change the state inside cases to move between states.