0
0
Embedded Cprogramming~30 mins

Event-driven state machine in Embedded C - Mini Project: Build & Apply

Choose your learning style9 modes available
Event-driven state machine
📖 Scenario: You are programming a simple device that changes its behavior based on events like button presses. This device has three states: OFF, ON, and BLINKING. It starts in the OFF state.
🎯 Goal: Build a small event-driven state machine in C that changes the device state when events occur. You will create the states, define events, write the logic to handle events and update the state, and finally print the current state.
📋 What You'll Learn
Define an enum called State with values OFF, ON, and BLINKING
Define an enum called Event with values BUTTON_PRESS and TIMER_EXPIRE
Create a variable current_state of type State initialized to OFF
Write a function handle_event that takes an Event and updates current_state based on the rules:
OFF + BUTTON_PRESS -> ON
ON + BUTTON_PRESS -> BLINKING
BLINKING + BUTTON_PRESS -> OFF
BLINKING + TIMER_EXPIRE -> ON
Print the current state as a string after handling an event
💡 Why This Matters
🌍 Real World
Event-driven state machines are used in embedded devices like remote controls, appliances, and IoT gadgets to manage behavior based on user input or timers.
💼 Career
Understanding event-driven state machines is essential for embedded software engineers working on firmware for hardware devices.
Progress0 / 4 steps
1
Define states and initial state
Define an enum called State with values OFF, ON, and BLINKING. Then create a variable called current_state of type State and set it to OFF.
Embedded C
Need a hint?

Use typedef enum { OFF, ON, BLINKING } State; and then State current_state = OFF;.

2
Define events
Define an enum called Event with values BUTTON_PRESS and TIMER_EXPIRE.
Embedded C
Need a hint?

Use typedef enum { BUTTON_PRESS, TIMER_EXPIRE } Event;.

3
Write event handler function
Write a function called handle_event that takes an Event parameter named event. Inside, use switch on current_state and nested switch on event to update current_state following these rules: OFF + BUTTON_PRESS -> ON, ON + BUTTON_PRESS -> BLINKING, BLINKING + BUTTON_PRESS -> OFF, BLINKING + TIMER_EXPIRE -> ON. Do nothing for other cases.
Embedded C
Need a hint?

Use nested switch statements to check current_state and event, then update current_state accordingly.

4
Print current state after event
Write a main function that calls handle_event with BUTTON_PRESS, then prints the current state as a string. Then call handle_event with BUTTON_PRESS again and print the state. Finally, call handle_event with TIMER_EXPIRE and print the state. Use printf and a switch on current_state to print "OFF", "ON", or "BLINKING".
Embedded C
Need a hint?

Call handle_event with the events in order, then print the state after each call using a switch and printf.