Home / Learn Chip Programming / RP2040 PIO: Write Your Own Hardware Protocol

RP2040 PIO: Write Your Own Hardware Protocol

Programmable I/O state machines let you implement WS2812, I2S, UART or a VGA signal without bit-banging.

In shortProgrammable I/O state machines let you implement WS2812, I2S, UART or a VGA signal without bit-banging.

Theory in plain words

PIO programC writes to TX FIFOPIO: pullout pins / side-setdelay [n] cyclesrepeat
PIO program

What it is

PIO has small state machines with a 32 instruction program, FIFOs, shift registers and precise cycle timing. Each instruction takes exactly one cycle, optionally with side-set pins.

Why we use it

You can add a UART, an extra SPI or a custom protocol in hardware, at full speed, without CPU load.

How it works

Write PIO assembly (.pio), the assembler produces a C header, load it into a state machine, push data to the TX FIFO from C or DMA.

Where it is used

  • WS2812 LED strips
  • DPI/VGA video, I2S audio
  • Unusual sensors with strict timing

WS2812 timing generator

Bit timing from a PIO programTry it Yourself

The timing is exact because PIO is hardware, not software. A tweak of the clock divider shifts every edge.

WS2812 PIO program
.program ws2812
.side_set 1
.wrap_target
bitloop:
    out x, 1       side 0 [2]     ; shift 1 bit, line low for T3 cycles
    jmp !x do_zero side 1 [1]     ; high for T1; if bit is 0 go to do_zero
do_one:
    jmp bitloop    side 1 [4]     ; stay high longer for a 1
do_zero:
    nop            side 0 [4]     ; go low early for a 0
.wrap
PIO instructionWhat it does
in / outshift bits between pins/registers and the shift registers
push / pullmove data between shift register and FIFO
movcopy between x, y, pins, status
jmpconditional jump (x==0, pin, !osre)
waitstall until a pin or IRQ matches
setset pins or x/y immediate
irqsignal the CPU or other state machines

Quick quiz

1. How many cycles does each PIO instruction take?

2. Why use PIO for WS2812?

Common questions

How many cycles does each PIO instruction take?

1 (plus optional delay). Deterministic timing.

Why use PIO for WS2812?

Exact nanosecond timing without CPU time. The CPU only fills the FIFO.