---
title: Blinking an LED in MicroPython
heading: Pins, sleeps, and keeping time
eyebrow: C12 · Lesson 2 · Blinking an LED in MicroPython
xp: 40
---

::: hook
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.
:::

::: play
- 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 `work` calls 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 = 0` and run again; the gap nearly vanishes, but not quite, because the toggle itself is a call.
:::
:::

```sim board
lang: micropython
attach: led P0 | red
attach: led P1 | green
attach: button P4
scope: P0, P1
run: 3 s
code:
from machine import Pin, Timer
import time

loop_led = Pin(0, Pin.OUT)
grid_led = Pin(1, Pin.OUT)
sensor = Pin(4, Pin.IN, Pin.PULL_UP)
work = 100                     # hardware calls per pass, about 40 µs each

# P1 toggles from a timer: the ideal 250 ms grid.
Timer(period=250, callback=lambda t: grid_led.toggle())

# P0 toggles from a loop: work, then a fixed sleep.
time.sleep_ms(250)
while True:
    loop_led.toggle()
    for i in range(work):
        sensor.value()
    time.sleep_ms(250)
```

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

- [ ] Not at all
- [ ] 2 ms
- [x] About 200 ms
- [ ] About 25 s

::: reveal
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.
:::
:::

::: nameit
## Pins in MicroPython

```python
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 $t_\text{on}$ and off for $t_\text{off}$ blinks with

$$T = t_\text{on} + t_\text{off}, \qquad f = \frac{1}{T}, \qquad D = \frac{t_\text{on}}{T}$$

where D is the **duty cycle**.

## Drift, and the deadline pattern

If each pass of a loop takes the sleep plus some work $t_w$, the period stretches by $t_w$ every pass and the error grows without limit: after N passes the loop is $N t_w$ behind. Sleeping until a deadline fixes it:

```python
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.
:::

::: example
## An LED should blink at 2 Hz with a 20% duty cycle. How long is it on and off?

::: solution
1. **Period.**
   $$\begin{aligned} T &= \frac{1}{2\ \text{Hz}} \\ &= 500\ \text{ms} \end{aligned}$$
2. **On time.**
   $$0.2 \times 500\ \text{ms} = 100\ \text{ms}$$
3. **Off time.** The rest of the period is 400 ms.

**Answer:** on for 100 ms and off for 400 ms.
:::
:::

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

::: solution
1. **Half-period.** Each half-period is the sleep plus the call, 100.04 ms.
2. **Period.**
   $$2 \times 100.04\ \text{ms} = 200.08\ \text{ms}$$
   instead of 200 ms.
3. **Periods in an hour.**
   $$\frac{3600\ \text{s}}{0.20008\ \text{s}} = 17\,993$$
   instead of 18,000.
4. **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.
:::
:::

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

::: solution
1. **One toggle.** Each toggle is one call, 40 µs.
2. **One cycle.** A full cycle of the square wave needs two toggles:
   $$2 \times 40\ \mu\text{s} = 80\ \mu\text{s}$$
3. **Frequency.**
   $$\begin{aligned} f &= \frac{1}{80\ \mu\text{s}} \\ &= 12.5\ \text{kHz} \end{aligned}$$
   at best, with some jitter from the loop itself.
4. **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
given: on = 50 | 100 | 250; off = 150 | 250 | 750
answer: 1000/(on + off)
unit: Hz
tolerance: 0.5%

## An LED is on for {on} ms and off for {off} ms. At what frequency does it blink?

::: right
Right. $1/(t_\text{on} + t_\text{off})$ = {answer} Hz.
:::

::: misses
- [1000/on] The period includes the off time.
- [any] Not yet. $f = 1/T$ with $T = t_\text{on} + t_\text{off}$.
:::
:::

::: check
given: on = 50 | 100 | 250; off = 150 | 250 | 750
answer: 100*on/(on + off)
unit: %
tolerance: 0.5%

## On for {on} ms and off for {off} ms: what's the duty cycle?

::: right
Right. $t_\text{on}/T$ = {answer}%.
:::

::: misses
- [100*on/off] Divide by the whole period, on plus off.
- [any] Not yet. $D = t_\text{on}/T$.
:::
:::

::: check
given: f = 1 | 2 | 5; D = 10 | 25 | 50
answer: 1000*D/100/f
unit: ms
tolerance: 0.5%

## An LED should blink at {f} Hz with a {D}% duty cycle. How long is it on in each period?

::: right
Right. $D/f$ = {answer} ms.
:::

::: misses
- [1000/f] That's the whole period; it's on for {D}% of it.
- [any] Not yet. $t_\text{on} = D \cdot T$.
:::
:::

::: check
given: w = 0.5 | 2 | 8; N = 100 | 1000 | 3600
answer: w*N/1000
unit: s
tolerance: 0.5%

## A fixed-sleep loop also spends {w} ms on work each pass. How far behind is it after {N} passes?

::: right
Right. $N t_w$ = {answer} s.
:::

::: misses
- [w/1000] The error is added on every pass.
- [any] Not yet. The delay accumulates: N times the work.
:::
:::

::: check
given: n = 10 | 50 | 250; s = 5 | 10 | 20
answer: n*0.04 + s
unit: ms
tolerance: 0.5%

## A loop makes {n} hardware calls (40 µs each) and then sleeps {s} ms. How long does one pass take?

::: right
Right. {answer} ms.
:::

::: misses
- [s] The calls take time too: {n} × 40 µs.
- [any] Not yet. Calls plus the sleep.
:::
:::

::: check
kind: choice

## Which loop keeps an LED toggling every 250 ms for a day without drifting?

- [ ] `led.toggle(); time.sleep_ms(250)`
- [ ] `led.toggle(); time.sleep_ms(249)` to make up for the toggle
- [x] Advancing a deadline by 250 ms each time and sleeping until it with `ticks_diff`
- [ ] `time.sleep(0.25)` instead of `sleep_ms`

::: misses
- [1] The toggle's time adds to every pass and accumulates.
- [2] The work's time isn't exactly 1 ms, and it varies; the error still accumulates.
- [4] It's the same fixed sleep in other units.
:::
:::

::: check
kind: micropython
given: on = 100 | 200 | 300; off = 100 | 300
attach: led P0
run: 2
expect: period(P0) = on + off ms ± 1%; duty(P0) = 100*on/(on + off) % ± 2

## Blink the LED on P0: on for {on} ms, off for {off} ms, forever.

```micropython starter
from machine import Pin
import time

led = Pin(0, Pin.OUT)
```

```micropython solution
from machine import Pin
import time

led = Pin(0, Pin.OUT)
while True:
    led.on()
    time.sleep_ms(on)
    led.off()
    time.sleep_ms(off)
```

::: right
Right. The timeline above shows the period and duty cycle you asked for.
:::
:::

::: check
kind: micropython
given: half = 100 | 125 | 200
attach: led P0; button P4
run: 3
expect: period(P0) = 2*half ms ± 0.05%

## Toggle P0 every {half} ms without drifting, even though each pass also reads P4 (a pull-up input) ten times.

```micropython starter
from machine import Pin
import time

led = Pin(0, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)
while True:
    led.toggle()
    for i in range(10):
        button.value()
    time.sleep_ms(half)
```

```micropython solution
from machine import Pin
import time

led = Pin(0, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)
next = time.ticks_ms()
while True:
    led.toggle()
    for i in range(10):
        button.value()
    next = time.ticks_add(next, half)
    time.sleep_ms(time.ticks_diff(next, time.ticks_ms()))
```

::: right
Right. The ten reads still take 0.4 ms each pass, but the deadline absorbs them, so the period stays exact.
:::
:::

::: check
kind: parts
given: f = 0.5 | 2 | 5; D = 10 | 25 | 50

## An LED blinks at {f} Hz with a {D}% duty cycle.

::: part
answer: D/100/f*1000
unit: ms
tolerance: 0.5%

### How long is it on each cycle?

::: misses
- [any] Duty × period.
:::
:::

::: part
answer: (1 - D/100)/f*1000
unit: ms
tolerance: 0.5%

### And off?

::: misses
- [any] The rest of the period.
:::
:::
:::

::: check
kind: parts
given: s = 50 | 100 | 500; c = 1 | 3; h = 1 | 8

## A MicroPython loop makes {c} hardware call(s) of 40 µs, then sleeps {s} ms.

::: part
answer: s + c*0.04
unit: ms
tolerance: 0.5%

### How long is each pass?

::: misses
- [any] Sleep plus 40 µs per call.
:::
:::

::: part
answer: h*3600/((s + c*0.04)/1000)*c*0.04/1000
unit: s
tolerance: 0.5%

### After {h} hours, how far behind is a count of passes against one made with exactly {s} ms passes?

::: misses
- [any] Passes made × the extra time per pass.
:::
:::
:::

::: explain
## Why does sleeping for a fixed time after doing some work make a periodic loop drift, and why does a deadline fix it?

::: model
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

::: check
given: on = 20 | 400; off = 80 | 600
answer: 1000/(on + off)
unit: Hz
tolerance: 0.5%

## Blink frequency for {on} ms on, {off} ms off?

::: misses
- [any] $1/(t_\text{on} + t_\text{off})$.
:::
:::

::: check
given: f = 4 | 10; D = 20 | 75
answer: 1000*D/100/f
unit: ms
tolerance: 0.5%

## On-time for {f} Hz at {D}% duty?

::: misses
- [any] $D/f$.
:::
:::

::: check
given: w = 1 | 4; N = 500 | 2000
answer: w*N/1000
unit: s
tolerance: 0.5%

## Drift after {N} passes with {w} ms of work?

::: misses
- [any] $N t_w$.
:::
:::
:::
