0
0
Embedded Cprogramming~30 mins

Simple state machine with switch-case in Embedded C - Mini Project: Build & Apply

Choose your learning style9 modes available
Simple state machine with switch-case
📖 Scenario: You are programming a simple traffic light controller for a small intersection. The traffic light cycles through three states: RED, GREEN, and YELLOW. Each state lasts for a certain number of seconds before switching to the next.
🎯 Goal: Build a simple state machine using switch-case in C to cycle through the traffic light states and print the current state.
📋 What You'll Learn
Create an enum for the traffic light states: RED, GREEN, YELLOW
Create a variable called current_state to hold the current state
Use a switch-case statement to handle state transitions
Print the current state name in each case
💡 Why This Matters
🌍 Real World
Traffic lights and many devices use state machines to control behavior based on current conditions.
💼 Career
Understanding state machines and switch-case logic is essential for embedded systems programming and device control.
Progress0 / 4 steps
1
Define the traffic light states
Create an enum called TrafficLight with the states RED, GREEN, and YELLOW. Then create a variable called current_state of type enum TrafficLight and set it to RED.
Embedded C
Need a hint?

Use enum TrafficLight { RED, GREEN, YELLOW }; to define the states and then enum TrafficLight current_state = RED; to set the initial state.

2
Add a variable for the timer
Create an int variable called timer and set it to 0. This will count seconds in each state.
Embedded C
Need a hint?

Just add int timer = 0; below the current_state variable.

3
Implement the state machine logic with switch-case
Write a switch statement on current_state. For each case (RED, GREEN, YELLOW), print the state name using printf. Then update current_state to the next state in this order: RED -> GREEN -> YELLOW -> RED.
Embedded C
Need a hint?

Use switch (current_state) and inside each case, print the state name and update current_state to the next state.

4
Print the current state
Add a printf statement after the switch-case block to print the text "Current state updated.".
Embedded C
Need a hint?

Use printf("Current state updated.\n"); after the switch-case block.