Foundations · Lesson 9 of 11 · about 15 min
PWM, state machines and more
Five ideas every firmware engineer uses
PWM: dimming with fast switching
A pin is either fully on or fully off. Switching it very fast, and choosing the share of time it stays on (the duty cycle), makes an LED or a motor feel the average. A timer does the switching, not the CPU.
State machines: how device logic is designed
The device is always in exactly one state, and events move it to another state. Draw the diagram first, then write the code.
typedef enum { IDLE, HEATING, ERROR } State;
switch (state) {
case IDLE: if (temp < target) { heater_on(); state = HEATING; } break;
case HEATING: if (temp >= target) { heater_off(); state = IDLE; } break;
case ERROR: if (button_pressed) { state = IDLE; } break;
}
Try it: in New project, the State machine designer draws your machine, checks it, and writes the C code with a unit test for every transition. The thermostat above is one of its examples.
DMA, watchdog and low power
- DMA moves data (ADC samples, UART bytes, screen pixels) in the background while the CPU does other work, then raises an interrupt when it is done.
- A watchdog is a timer that restarts the chip if the code stops feeding it. A frozen device recovers by itself.
- Low power: the MCU sleeps almost all the time and wakes only on an interrupt. This is how a battery lasts for years.
Interview questions
- How does PWM control the speed of a motor?
- Why design firmware as a state machine?
- How do you feed a watchdog safely when several tasks run?
No answers here on purpose: try answering out loud first. In the BoardPilot app, the interview coach reads your own answer and tells you what was right, what is missing and what a senior interviewer would ask next (it uses the AI provider you choose in the app). Embedded systems interview questions →
Key terms
PWM (pulse-width modulation) Duty cycle DMA (direct memory access) Watchdog Low power and deep sleep State machine
In the app, the lessons come alive
The lessons have interactive demos and hands-on labs checked on your board in the app. These pages are the readable version: the demos are described in words, and the labs need the app.