C12 · Lesson 2 · Blinking an LED in MicroPython
Pins, sleeps, and keeping time
Blinking an LED is the first program on any new board, because it proves the toolchain, the pin and the timing all work. In MicroPython it takes five lines. But even five lines hide a timing question: a loop that toggles a pin and then sleeps for 250 ms runs a little slower than 250 ms per step, because the toggle itself takes time. Over a minute the error adds up, and a clock or a data logger built that way drifts. The fix is to sleep until a deadline instead of for a fixed time, and it's the first of many places where embedded code has to think about where time goes.
- Two LEDs share the same intended half-period, 250 ms. P1 toggles from a timer: the ideal grid. P0 toggles from a loop that does some work, then sleeps a fixed 250 ms.
- The work is
workcalls into the hardware (reading a pin), about 40 µs each. With 100 calls, every pass of the loop is 4 ms longer than it should be. - Run it and compare the last edges: P0 has fallen behind P1, and the gap grows every pass. Set
work = 0and run again; the gap nearly vanishes, but not quite, because the toggle itself is a call.
Predict
A loop toggles an LED, does 2 ms of other work, and sleeps 250 ms. After 100 toggles, how far behind the ideal 250 ms grid is it?
About 200 ms: each pass takes 252 ms instead of 250, and the extra 2 ms is never taken back, so it accumulates, 100 × 2 ms. Sleeping until a deadline that advances by exactly 250 ms each time keeps every toggle on the grid; only the work's own jitter remains.
Name it
Pins in MicroPython
from machine import Pin
led = Pin(0, Pin.OUT) # direction: output
led.on(); led.off() # level high or low
led.value(1); led.value() # write, or read back
led.toggle() # flip it
Each call becomes a read or write of the GPIO registers from lesson 1. On this board each call into the hardware costs about 40 µs, MicroPython's overhead at 10 MHz.
Blink timing
An LED on for and off for blinks with
where D is the duty cycle.
Drift, and the deadline pattern
If each pass of a loop takes the sleep plus some work , the period stretches by every pass and the error grows without limit: after N passes the loop is behind. Sleeping until a deadline fixes it:
next = time.ticks_ms()
while True:
led.toggle()
next = time.ticks_add(next, 250)
time.sleep_ms(time.ticks_diff(next, time.ticks_ms()))
ticks_ms() counts milliseconds and wraps around; ticks_add and ticks_diff do the arithmetic correctly across the wrap.
Worked example
An LED should blink at 2 Hz with a 20% duty cycle. How long is it on and off?
Show the solution
- Period.
- On time.
- Off time. The rest of the period is 400 ms.
Answer on for 100 ms and off for 400 ms.
Worked example
A loop toggles a pin (one 40 µs call) and sleeps 100 ms. How long is the blink period, and how far off is it after an hour?
Show the solution
- Half-period. Each half-period is the sleep plus the call, 100.04 ms.
- Period. instead of 200 ms.
- Periods in an hour. instead of 18,000.
- How far behind. That's 7 periods short, about 1.4 s behind.
Answer the period is 200.08 ms, and after an hour the blink is about 1.4 s behind.
Worked example
Each MicroPython hardware call takes about 40 µs on this board. How fast can a loop that only toggles a pin make a square wave?
Show the solution
- One toggle. Each toggle is one call, 40 µs.
- One cycle. A full cycle of the square wave needs two toggles:
- Frequency. at best, with some jitter from the loop itself.
- What it's good for. That's plenty for blinking and slow signals, and nowhere near enough for generating audio or reading fast pulses, which need timers or C.
Answer about 12.5 kHz at best.
Check
An LED is on for 100 ms and off for 150 ms. At what frequency does it blink?
Write units the way you normally would: 1.5 Hz, 1500 mHz and 0.0015 kHz are the same answer.
Check
On for 100 ms and off for 150 ms: what's the duty cycle?
Check
An LED should blink at 2 Hz with a 10% duty cycle. How long is it on in each period?
Write units the way you normally would: 1.5 ms, 1500 µs and 0.0015 s are the same answer.
Check
A fixed-sleep loop also spends 2 ms on work each pass. How far behind is it after 100 passes?
Write units the way you normally would: 1.5 s and 1500 ms are the same answer.
Check
A loop makes 50 hardware calls (40 µs each) and then sleeps 5 ms. How long does one pass take?
Write units the way you normally would: 1.5 ms, 1500 µs and 0.0015 s are the same answer.
Check
Which loop keeps an LED toggling every 250 ms for a day without drifting?
Check
Blink the LED on P0: on for 200 ms, off for 100 ms, forever.
MicroPython on the course's board: machine (Pin, PWM, ADC, DAC, UART, I2C, SPI, Timer, WDT) and time. Each call into the hardware takes about 40 µs. Tab indents; press Esc and then Tab to move on.
Check
Toggle P0 every 125 ms without drifting, even though each pass also reads P4 (a pull-up input) ten times.
MicroPython on the course's board: machine (Pin, PWM, ADC, DAC, UART, I2C, SPI, Timer, WDT) and time. Each call into the hardware takes about 40 µs. Tab indents; press Esc and then Tab to move on.
Check
An LED blinks at 2 Hz with a 10% duty cycle.
(a)
How long is it on each cycle?
Write units the way you normally would: 1.5 ms, 1500 µs and 0.0015 s are the same answer.
(b)
And off?
Check
A MicroPython loop makes 1 hardware call(s) of 40 µs, then sleeps 100 ms.
(a)
How long is each pass?
Write units the way you normally would: 1.5 ms, 1500 µs and 0.0015 s are the same answer.
(b)
After 8 hours, how far behind is a count of passes against one made with exactly 100 ms passes?
Explain why
Why does sleeping for a fixed time after doing some work make a periodic loop drift, and why does a deadline fix it?
With a fixed sleep, each pass lasts the sleep plus however long the work took, so every period is longer than intended by the work's duration, and nothing ever corrects it: the errors add up pass after pass. A deadline is a target time that advances by exactly one period each pass, independent of how long the work took; the loop sleeps only for whatever time remains until it. If the work takes longer one pass, the sleep is shorter, so the timing error never exceeds one pass's variation and never accumulates.
Practice
Keep practicing
12 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.