Skip to content
Tactiverge

Textbooks/Electrical and Embedded Systems/Chapter 7Lite (plain text) version

7PWM, state machines and actuators

Version 1 · Technically checked (automated checks only) · 4 source lessons · 8 practice items

Text
All chapters and search
  1. 1. Charge, current and voltage
  2. 2. Ohm's law and real components
  3. 3. Series, parallel and dividers
  4. 4. Power, energy and batteries
  5. 5. Inside a microcontroller
  6. 6. Pins, inputs and sensors
  7. 7. PWM, state machines and actuators
  8. 8. Talking between chips
  9. 9. Registers, interrupts and integration

Introduction

A microcontroller pin can only be fully on or fully off, yet it can dim a light or slow a motor: switch fast enough and the load feels the average. That is pulse-width modulation. Controlling what happens when is the job of a state machine, a short list of states, events and transitions that keeps behaviour predictable. And since pins give milliamps while motors want amps, a driver stage does the heavy lifting.

Average voltage = duty × supply25% → 1.25 V50% → 2.5 V75% → 3.75 V
Figure 7.1. Average voltage = duty × supply. Three PWM waveforms on a 5 V supply with their averages as dashed lines: 25% duty averages 1.25 V, 50% duty averages 2.5 V and 75% duty averages 3.75 V.

Explanation

This chapter is built from 4 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.

7.1 PWM: dimming with an on/off switch

A pin can only be fully on or fully off. So how does it dim an LED to 30% or run a motor at half speed?

Duty cycle

PWM switches an output on and off many times a second. The period is one on-plus-off cycle; the duty cycle is the fraction of the period spent on. 2 ms on in a 10 ms period is 20% duty. 0% is always off; 100% is always on.

Average voltage

Loads that respond slowly (a motor's spinning mass, an LED seen by your eye, a heater's thermal mass) react to the average: V_avg = duty × V_high. On a 5 V pin, 60% duty acts like 3 V. Because the switch is either fully on (tiny voltage across it) or fully off (no current), very little power is wasted as heat.

Fast enough, but not too fast

The PWM frequency must be fast compared with the load. At 50 Hz an LED flickers and a motor can judder. LEDs are typically driven at hundreds of hertz or more; motors at a few kilohertz to about 20 kHz, the upper end being above most people's hearing so the whine disappears. Too fast and the switching itself starts to waste energy in the driver.

Derivation: Average voltage of a PWM wave
  1. In one period T, the output is V_high for the on-time t_on and 0 V for the rest.

  2. Duty cycle D = t_on ÷ T (as a fraction, or × 100 as a percentage).

  3. The average over a period is the area under the wave divided by the period: (V_high × t_on + 0 × (T − t_on)) ÷ T.

  4. So V_avg = D × V_high. 40% of 12 V = 0.40 × 12 = 4.8 V.

  5. The frequency f = 1 ÷ T does not appear: it changes how smooth the effect is, not the average.

Common mix-ups

  • PWM makes the pin output a lower voltage.
    ✓ The pin is always at 0 V or at the supply. Only the average, felt by a slow load, is lower.
  • Higher PWM frequency gives a higher average voltage.
    ✓ Only the duty cycle sets the average. Frequency sets how smooth the effect is.

Open the full lesson: PWM: dimming with an on/off switch →

7.2 States, events and transitions

An automatic door is closing when someone walks up. Should it keep closing? How would a machine even know what it is doing?

Three ingredients

A state is what the machine is doing now (closed, opening, open, closing). An event is something that happens (a person is detected, a limit switch reports 'fully open', a timer ends). A transition is a rule: in state S, on event E, go to state S′. The machine is in exactly one state at a time.

Tables beat tangled ifs

Write every rule as a row: from, event, to. The door needs only five rows. Anything not in the table is ignored: the state stays the same. A table lets you check every state–event pair systematically: four states × four events = 16 pairs to think about.

Complete and safe

A good state machine has no stuck states (every state has a way out) and handles every safety event in every state where it matters. 'Closing + person → opening' is the rule that stops the door shutting on someone. Engineers number states (0, 1, 2, 3) so firmware can store the current state in one variable.

Common mix-ups

  • The machine reacts the same way to an event every time.
    ✓ The reaction depends on the current state. That memory is what makes it a state machine.
  • If a case is not in the table, the program crashes.
    ✓ In a well-designed machine, unlisted events are deliberately ignored, and the designer has checked that ignoring them is safe.

Open the full lesson: States, events and transitions →

7.3 A state machine in twelve lines

Can a whole automatic door fit in one variable and a handful of ifs?

The pattern

CLOSED, OPENING, OPEN, CLOSING = 0, 1, 2, 3
state = CLOSED

def step(state, event):
    if state == CLOSED and event == 'person':
        return OPENING
    elif state == OPENING and event == 'fully_open':
        return OPEN
    elif state == OPEN and event == 'timer':
        return CLOSING
    elif state == CLOSING and event == 'person':
        return OPENING
    elif state == CLOSING and event == 'fully_closed':
        return CLOSED
    return state  # anything else: no change

One line per row of the transition table, plus a default.

Outputs follow the state

In the main loop, after updating the state, set the outputs from it: motor forwards while OPENING, backwards while CLOSING, off otherwise; start the hold-open timer when entering OPEN. Keeping outputs tied to states means you can never forget to switch the motor off.

Test with event lists

Because step is a pure function, you can test it without hardware:

s = CLOSED
for e in ['person', 'fully_open', 'timer', 'person']:
    s = step(s, e)
assert s == OPENING

Write one test for every row, and a few for events that should be ignored.

Common mix-ups

  • State machines need a special library.
    ✓ One variable and some if/elif branches are enough for most small machines.
  • If it works for the normal sequence, it is tested.
    ✓ Test the ignored events and the unusual orders too: that is where the safety bugs live.

Open the full lesson: A state machine in twelve lines →

7.4 Choosing an actuator, and why pins need help

Your microcontroller pin can light an LED. Can it run a 6 W motor on its own?

Power, voltage, current

Electrical power is P = V × I. Rearranged, I = P ÷ V. A 12 V, 18 W pump draws 1.5 A; a 5 V, 1.5 W fan draws 0.3 A. Small motors often draw several times their running current for a moment when starting or stalled, so drivers and supplies need extra headroom.

Pins command, drivers deliver

A pin can safely supply only milliamps. Motors need amps, and they make electrical noise and voltage spikes. So the pin sends a small logic signal to a driver (a transistor or a motor-driver chip), which switches a separate supply through the motor. A diode or the driver's built-in protection catches the spike when the motor is switched off. Servos and stepper drivers follow the same idea.

A fair comparison

List what the task needs (angle or speed? holding force? cost? power?) and score each actuator against it, as in the trade-offs lab. Write down the must-haves first: a vent that must hold 45° in wind rules out a plain DC motor without a sensor, however cheap it is.

Common mix-ups

  • If a motor is small, a pin can power it.
    ✓ Even small motors draw hundreds of milliamps and spike when switched. Always use a driver.
  • The cheapest actuator is the best choice.
    ✓ Must-haves come first. A cheap actuator that cannot hold an angle fails the task.

Open the full lesson: Choosing an actuator, and why pins need help →

Worked examples

PWM: dimming with an on/off switch: example 1

A 1 kHz PWM signal is high for 0.35 ms each period. Duty cycle and average on a 5 V pin?

Solution

T = 1 ÷ 1,000 = 1 ms. D = 0.35 ÷ 1 = 35%. V_avg = 0.35 × 5 = 1.75 V.

States, events and transitions: example 1

Start: closed (0). Events: person, fully open, person, timer ended, person, fully open. Final state?

Solution

0 + person → 1 opening. + fully open → 2 open. + person → stays 2. + timer ended → 3 closing. + person → 1 opening (safety). + fully open → 2 open.

A state machine in twelve lines: example 1

Trace step from CLOSED with events: timer, person, fully_open, person, timer, fully_closed.

Solution

timer: no rule → CLOSED. person → OPENING. fully_open → OPEN. person: no rule for OPEN → OPEN. timer → CLOSING. fully_closed → CLOSED.

Choosing an actuator, and why pins need help: example 1

A 12 V greenhouse fan is rated 3 W. Its current, and how long can it run on a 12 V, 7 Ah battery?

Solution

I = 3 ÷ 12 = 0.25 A. 7 Ah ÷ 0.25 A = 28 hours (ideal; real batteries give less).

Interactive figures

Figure 7.2 from PWM: dimming with an on/off switchWith a 12 V supply, find the duty cycle that gives 6 V average, then 3 V. Watch the motor's model speed. Then drop to 50 Hz and read what happens to an LED and a motor.
Can't use the interactive? Read a description instead

The PWM visualiser draws three periods of a square wave between 0 V and the chosen supply. The wave is high for the duty-cycle fraction of each period; a dashed line marks the average, duty × supply. A simplified motor's speed is proportional to that average (no movement below 0.8 V), and an LED swatch shows brightness rising with duty. At 50 Hz the readout warns of flicker; at 20 kHz it notes the switching is above most people's hearing.

Interactive figure (online). Description: The PWM visualiser draws three periods of a square wave between 0 V and the chosen supply. The wave is high for the duty-cycle fraction of each period; a dashed line marks the average, duty × supply. A simplified motor's speed is proportional to that average (no movement below 0.8 V), and an LED swatch shows brightness rising with duty. At 50 Hz the readout warns of flicker; at 20 kHz it notes the switching is above most people's hearing.

Figure 7.3 from States, events and transitionsChoose the automatic door. Walk it through a whole cycle: person detected, fully open, timer ended, fully closed. Then try to trap someone: while it is closing, fire 'person detected'. Which row of the table lit up?
Can't use the interactive? Read a description instead

The door state machine has states 0 Closed, 1 Opening, 2 Open, 3 Closing and events 0 Person detected, 1 Fully open, 2 Timer ended, 3 Fully closed. Rules: Closed + person → Opening; Opening + fully open → Open; Open + timer ended → Closing; Closing + fully closed → Closed; Closing + person → Opening. Any other event leaves the state unchanged. The runner lists the current state, highlights the rule that matched and keeps a log of transitions.

Interactive figure (online). Description: The door state machine has states 0 Closed, 1 Opening, 2 Open, 3 Closing and events 0 Person detected, 1 Fully open, 2 Timer ended, 3 Fully closed. Rules: Closed + person → Opening; Opening + fully open → Open; Open + timer ended → Closing; Closing + fully closed → Closed; Closing + person → Opening. Any other event leaves the state unchanged. The runner lists the current state, highlights the rule that matched and keeps a log of transitions.

Laboratory

Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.

Guided practice

Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.

Practice 1 · a fresh version every time

A PWM output switches between 0 V and 9 V with a duty cycle of 0%. What is the average voltage, in volts?

V

Practice 2

You want an average of 4.5 V from a 12 V supply. What duty cycle is needed, in percent?

%

Practice 3

An LED driven by PWM at 20 Hz visibly flickers. What is the fix?

Practice 4 · a fresh version every time

An automatic door has states 0 = closed, 1 = opening, 2 = open, 3 = closing. Its events are 0 = person detected, 1 = fully open, 2 = timer ended, 3 = fully closed. Rules: closed + person → opening; opening + fully open → open; open + timer ended → closing; closing + fully closed → closed; closing + person → opening. Any other event leaves the state unchanged. The door is in state 2 and event 0 happens. What state number comes next?

state

Practice 5

A vending machine has states idle, paid, vending, empty. No rule ever leaves 'empty'. What kind of problem is that?

Practice 6

What would happen if you deleted the final `return state` line?

Practice 7

A motor draws 0.6 A. A pin is limited to 0.012 A in this model. How many times the pin's limit is that?

times

Practice 8

A greenhouse vent must hold 0°, 45° or 90°, against gusts, and the budget is tight. Which actuator is the sensible first choice?

  1. A PWM output switches between 0 V and 9 V with a duty cycle of 0%. What is the average voltage, in volts? (V)
  2. You want an average of 4.5 V from a 12 V supply. What duty cycle is needed, in percent? (%)
  3. An LED driven by PWM at 20 Hz visibly flickers. What is the fix?
    • Lower the duty cycle
    • Raise the PWM frequency well above what eyes notice
    • Use a bigger resistor
  4. An automatic door has states 0 = closed, 1 = opening, 2 = open, 3 = closing. Its events are 0 = person detected, 1 = fully open, 2 = timer ended, 3 = fully closed. Rules: closed + person → opening; opening + fully open → open; open + timer ended → closing; closing + fully closed → closed; closing + person → opening. Any other event leaves the state unchanged. The door is in state 2 and event 0 happens. What state number comes next? (state)
  5. A vending machine has states idle, paid, vending, empty. No rule ever leaves 'empty'. What kind of problem is that?
    • A stuck state: once empty it can never recover, even after refilling
    • Nothing: empty machines should stop
    • A noise problem
  6. What would happen if you deleted the final `return state` line?
    • Nothing
    • For unmatched events the function would return None, and the door would lose track of its state
    • The door would open
  7. A motor draws 0.6 A. A pin is limited to 0.012 A in this model. How many times the pin's limit is that? (times)
  8. A greenhouse vent must hold 0°, 45° or 90°, against gusts, and the budget is tight. Which actuator is the sensible first choice?
    • A plain DC motor, no sensor
    • A hobby-sized servo (or a geared servo for a larger vent)
    • A 3D-printer stepper with no homing switch

Engineering applications

  • LED dimming

    Screens and lamps are often dimmed with PWM at hundreds or thousands of hertz. Too slow and people see flicker, especially out of the corner of the eye or on camera.

  • Doors and vending machines

    Automatic doors, vending machines and lifts are state machines. Writing out every state and transition, including what happens on a fault, is how designers make sure the door never closes on someone.

Watch

Optional verified videos. Nothing loads from YouTube until you press play.

A lecture-style explanation of PWM basics, circuits and waveforms, a step more formal than this lesson.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

A programmer builds a traffic-light state machine in code, showing states, transitions and timers as a game developer uses them.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

  • PWM - Pulse Width Modulation (Basics, Circuit, Working, & Waveforms) Explained (Engineering Funda)
  • Finite State Machines -- Game Programming Concepts Series (Gamefromscratch)

Chapter summary

  • PWM switches a pin on and off quickly; the load sees the average: duty × supply.
  • A state machine has states, events and transitions; every state needs a rule for every event.
  • In code, a state machine is a variable and a branch on it inside the loop.
  • Pins cannot drive motors directly; a transistor or driver switches the real current.

Glossary

PWM average voltage
Pulse-width modulation switches a signal fully on and off quickly; the fraction of time it is on, the duty cycle, sets the average voltage delivered.
Hobby servo motor
A hobby servo is a motor, gearbox, position sensor and controller in one case. It moves to an angle set by the width of a pulse repeated about every 20 ms.
Stall torque and no-load speed
For a DC motor, stall torque is the torque at zero speed and no-load speed is the speed with zero torque; between them torque falls roughly linearly as speed rises.
On–off control with hysteresis
On–off control switches the actuator fully on or off; hysteresis uses two thresholds, one to switch on and a different one to switch off, so the output does not chatter around a single value.

Definitions from the Field Guide.

Project: A fan with manners

Design a cooling fan controller with states Off, Low, High and Fault. It reads a temperature, drives the fan with PWM, and enters Fault if the fan stalls. Draw the state diagram, list the transitions, pick duty cycles and choose a driver for a 12 V, 0.5 A fan.

Deliverables

  • A state diagram with every transition
  • Duty cycles and the PWM frequency with reasons
  • The driver choice and its current rating

Keep your work in your Engineering Journal; it stays private unless you choose to share it.

References

  • Edward A. Lee and Sanjit A. Seshia (2017). Introduction to Embedded Systems: A Cyber-Physical Systems Approach, 2nd edition. MIT Press.
  • Paul Scherz and Simon Monk (2016). Practical Electronics for Inventors, 4th edition. McGraw-Hill Education.

Publication record

Version
1
Status
Technically checked (automated checks only)
Technical review
Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
Written by
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
Licence
All rights reserved by the founders unless a licence is approved.
Corrections
None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.