TactivergeLite

Lite / Textbooks / Electrical and Embedded Systems / Chapter 7

7. PWM, state machines and actuators

Version 1 · Technically checked (automated checks only) · 4 source lessons · Full interactive version

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.

Figure 7.1. Average voltage = duty × supply (described in words)

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

Built from 4 School lessons. Each part is the lesson's own explanation.

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

Open the Lite 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

Open the Lite 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

Open the Lite 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

Open the Lite 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, in words

Figure 7.2 from PWM: dimming with an on/off switch

With 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.

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 transitions

Choose 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?

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.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. A PWM output switches between 0 V and 9 V with a duty cycle of 0%. What is the average voltage, in volts?
    Answer it in “PWM: dimming with an on/off switch”
  2. You want an average of 4.5 V from a 12 V supply. What duty cycle is needed, in percent?
    Answer it in “PWM: dimming with an on/off switch”
  3. An LED driven by PWM at 20 Hz visibly flickers. What is the fix?
    Answer it in “PWM: dimming with an on/off switch”
  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?
    Answer it in “States, events and transitions”
  5. A vending machine has states idle, paid, vending, empty. No rule ever leaves 'empty'. What kind of problem is that?
    Answer it in “States, events and transitions”
  6. What would happen if you deleted the final `return state` line?
    Answer it in “A state machine in twelve lines”
  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?
    Answer it in “Choosing an actuator, and why pins need help”
  8. A greenhouse vent must hold 0°, 45° or 90°, against gusts, and the budget is tight. Which actuator is the sensible first choice?
    Answer it in “Choosing an actuator, and why pins need help”

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)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

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. Field Guide
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. Field Guide
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. Field Guide
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. 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

Write it up on paper or in your own notes. Lite never stores what you write.

References

← 6. Pins, inputs and sensors8. Talking between chips →