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

Interview questions

  1. How does PWM control the speed of a motor?
  2. Why design firmware as a state machine?
  3. 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

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.

Download BoardPilot Try the lessons in your browser