Understanding RP2350 PIO Lesson 1

From Stm32World Wiki
Jump to navigation Jump to search

This is lesson 1 of Understanding RP2350 PIO, which has the overview of what PIO is, the instruction set and the tools. Next: lesson 2, square waves with side-set.


The video for this lesson (PIO #1):


The first example, pio_1_blink, does the same as the very first blink example, but with a state machine toggling the LED instead of the CPU.

The PIO program

.program blink

.define public CYCLES_PER_BLINK 2052

.wrap_target
    set pins, 1         ; LED on
    set x, 31           ; loop counter: 31, 30, ... 0 = 32 rounds
on_delay:
    jmp x-- on_delay [31]

    set pins, 0         ; LED off
    set x, 31
off_delay:
    jmp x-- off_delay [31]
.wrap                   ; jump back to .wrap_target for free (0 cycles)

Six instructions. The only new ideas are:

  • set pins, 1 drives the pin(s) configured as "set pins" high.
  • jmp x-- label jumps if X is not zero, and decrements X either way. Starting from 31, it loops 32 times.
  • [31] adds 31 idle cycles, so each round of the loop takes 32 cycles.
  • .wrap_target / .wrap make the program loop forever without spending a cycle on a jump.

Counting the cycles for one half of the blink:

Instruction Cycles
set pins 1
set x, 31 1
jmp x-- [31], 32 rounds 32 × 32 = 1024
Total 1026

A full blink (on and off) is 2052 PIO clock cycles, exported to C as blink_CYCLES_PER_BLINK.

Understanding RP2350 PIO Blink Timing.svg

Setting up the state machine

The C part of blink.pio hands the pin to PIO, configures it, and calculates the clock divider for the requested blink rate. It returns the blink rate it actually got, worked back from the divider as the hardware stored it, so a divider that didn't fit shows up as a wrong rate instead of going unnoticed:

static inline float blink_program_init(PIO pio, uint sm, uint offset, uint pin, float blink_hz) {
    // Hand the pin over to this PIO block and make it an output
    pio_gpio_init(pio, pin);
    pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true);

    pio_sm_config c = blink_program_get_default_config(offset);

    // 'set pins' drives 1 pin, starting at 'pin'
    sm_config_set_set_pins(&c, pin, 1);

    // PIO clock = system clock / divider. Max divider is 65535 + 255/256.
    float div = (float)clock_get_hz(clk_sys) / (blink_hz * blink_CYCLES_PER_BLINK);
    sm_config_set_clkdiv(&c, div);

    pio_sm_init(pio, sm, offset, &c);
    pio_sm_set_enabled(pio, sm, true);

    // Work back from the divider the hardware really got: the fraction is only 8 bits, and if
    // 'div' was too big the integer part was silently cut down to 16 bits (0 means 65536)
    uint32_t div_int = (c.clkdiv & PIO_SM0_CLKDIV_INT_BITS) >> PIO_SM0_CLKDIV_INT_LSB;
    uint32_t div_frac = (c.clkdiv & PIO_SM0_CLKDIV_FRAC_BITS) >> PIO_SM0_CLKDIV_FRAC_LSB;
    if (div_int == 0) {
        div_int = 65536;
    }
    float real_div = (float)div_int + (float)div_frac / 256.0f;

    return (float)clock_get_hz(clk_sys) / (real_div * blink_CYCLES_PER_BLINK);
}

main() is the usual setup from the other examples: UART at 921600 baud and a 1 ms systick from a repeating timer (only core 0 is used). It lets the SDK find a PIO block and state machine and starts the program, and then the CPU is free. The main loop never touches the LED; it just counts how many times it gets round between ticks, to show that the CPU is busy with something else:

PIO pio;
uint sm;
uint offset;

bool ok = pio_claim_free_sm_and_add_program_for_gpio_range(&blink_program, &pio, &sm, &offset, PICO_DEFAULT_LED_PIN, 1, true);
hard_assert(ok);

float blink_hz = blink_program_init(pio, sm, offset, PICO_DEFAULT_LED_PIN, BLINK_HZ);

uint32_t now, loop_cnt = 0, next_tick = TICK_DELAY;

// Main loop for Core 0: the LED is not touched here, PIO does all the blinking
while (true) {

    now = systick;

    if (now >= next_tick) {
        printf("Core 0 tick %lu (loop = %lu)\n", now / 1000, loop_cnt);
        loop_cnt = 0;
        next_tick = now + TICK_DELAY;
    }

    ++loop_cnt;

    tight_loop_contents();
}

The output on the Streamline MCU RP2354 (921600 baud), running blink.pio at 2 Hz. The loop count shows the CPU going round its loop about 30 million times a second while the LED blinks:

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 26 (6 instructions)
GPIO base: 16, LED on GPIO 37
Blink rate: asked for 2.0000 Hz, got 2.0000 Hz
Core 0 tick 1 (loop = 29899344)
Core 0 tick 2 (loop = 29947417)
Core 0 tick 3 (loop = 29947835)

Two things are worth noticing:

  • The SDK picked PIO2, not PIO0, and loaded the program at offset 26, at the top of the program memory. pio_claim_free_sm_and_add_program_for_gpio_range() looks for any block with room for the program and a free state machine; don't assume it will be PIO0, state machine 0.
  • The slowest this program can blink is set by the clock divider: at 150 MHz it is about 1.1 Hz, so asking it for 1 Hz doesn't work. See below.

Why it can't blink at 1 Hz

The blink rate is set by the clock divider alone:

blink rate = clk_sys / (clock divider × 2052)

To blink slower, the divider has to be bigger. Its integer part is only 16 bits, so it tops out at 65535 + 255/256 (just under 65536). At the stock 150 MHz the slowest this program can blink is:

150 000 000 / (65536 × 2052) ≈ 1.115 Hz

1 Hz would need a divider of 150 000 000 / 2052 ≈ 73 099, which doesn't fit in 16 bits. The SDK doesn't catch this: sm_config_set_clkdiv() simply cuts the integer part down to 16 bits (its parameter checks are off by default), so instead of 1 Hz the LED blinks at some unrelated, faster rate. A faster system clock makes it worse, not better: at 300 MHz the floor is about 2.2 Hz.

The fix is to burn more cycles per blink rather than divide the clock more. A single instruction can't be delayed by more than 31 cycles (the delay field is 5 bits), and set can only load 0-31 into X, so the next step is a loop inside a loop.

blink2.pio: a loop inside a loop

blink2.pio uses Y as an outer counter around the X loop from blink.pio:

.program blink

.define public CYCLES_PER_BLINK 65668

.wrap_target
    set pins, 1             ; LED on
    set y, 31               ; outer loop counter: 31..0 = 32 rounds
on_outer:
    set x, 31               ; inner loop counter: 31..0 = 32 rounds
on_inner:
    jmp x-- on_inner [31]
    jmp y-- on_outer

    set pins, 0             ; LED off
    set y, 31
off_outer:
    set x, 31
off_inner:
    jmp x-- off_inner [31]
    jmp y-- off_outer
.wrap                       ; jump back to .wrap_target for free (0 cycles)

Counting the cycles for one half of the blink:

Instruction Cycles
set pins 1
set y, 31 1
32 outer rounds of set x, 31 (1) + jmp x-- [31] (32 × 32 = 1024) + jmp y-- (1) 32 × 1026 = 32 832
Total 32 834

A full blink is 65 668 cycles, about 32 times as many as blink.pio. The program is 10 instructions instead of 6, and the C setup function is the same, so switching is just a matter of generating the header from blink2.pio in CMakeLists.txt and including blink2.pio.h in main.c, which is how the example in the repository is set up. At 1 Hz the clock divider is 150 000 000 / 65 668 ≈ 2284, comfortably in range, and the slowest possible blink is now about 0.035 Hz (one blink every 28.7 seconds).

The output with blink2.pio at 1 Hz:

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 22 (10 instructions)
GPIO base: 16, LED on GPIO 37
Blink rate: asked for 1.0000 Hz, got 1.0000 Hz
Core 0 tick 1 (loop = 29898185)
Core 0 tick 2 (loop = 29947916)
Core 0 tick 3 (loop = 29948342)
Core 0 tick 4 (loop = 29948342)

The 10-instruction program now starts at offset 22 instead of 26, still at the top of the program memory, and the CPU loop count is the same as before: the slower blink costs the CPU nothing.

The GPIO base

Understanding RP2350 PIO GPIO Base.svg

On the Streamline MCU RP2354 the LED is on GPIO 37. A PIO block can only reach 32 GPIOs at a time, so to drive GPIO 37 the block's GPIO base has to be 16 (GPIO 16-47) instead of the default 0 (GPIO 0-31). The last argument of pio_claim_free_sm_and_add_program_for_gpio_range() (true) lets the SDK set that up. Done by hand, it is:

pio_set_gpio_base(pio, 16); // This block now sees GPIO 16-47

The GPIO base belongs to the whole block, so all 4 state machines in it share the same window. A program that needs both GPIO 5 and GPIO 40 can't run in one state machine; it has to be split across blocks with different bases. On the RP2350A (and the RP2040), with only 30 GPIOs, this never comes up.

Lesson 1b: 32-bit delays, no divider

Lesson 1 ended with a loop inside a loop to get below 1 Hz. This follow-up looks at what blink.pio really does when it is asked for 1 Hz, and then at two more programs, blink3.pio and blink4.pio, that leave the clock divider at exactly 1 and count system clocks with a 32-bit value from the CPU instead.

What has changed in the code

Since the lesson 1 video, all four blink programs in pio_1_blink have the same blink_program_init(), so switching between them is just a matter of changing one line in main.c:

// Pick one: blink.pio.h, blink2.pio.h, blink3.pio.h or blink4.pio.h (generated by pioasm).
// All four have the same blink_program_init(), so nothing else needs to change.
#include "blink4.pio.h"

CMakeLists.txt generates all four headers. blink_program_init() no longer returns the divider it asked for, but the blink rate the state machine actually gets, and main() prints it:

float blink_hz = blink_program_init(pio, sm, offset, PICO_DEFAULT_LED_PIN, BLINK_HZ);

printf("PIO%u, state machine %u, program at offset %u (%u instructions)\n", PIO_NUM(pio), sm, offset, blink_program.length);
printf("GPIO base: %u, LED on GPIO %u\n", pio_get_gpio_base(pio), PICO_DEFAULT_LED_PIN);
printf("Blink rate: asked for %.4f Hz, got %.4f Hz\n", BLINK_HZ, blink_hz);

What blink.pio really does at 1 Hz

For blink.pio and blink2.pio, the rate is worked back from the divider the hardware really stored, read out of the configuration after sm_config_set_clkdiv():

    // Work back from the divider the hardware really got: the fraction is only 8 bits, and if
    // 'div' was too big the integer part was silently cut down to 16 bits (0 means 65536)
    uint32_t div_int = (c.clkdiv & PIO_SM0_CLKDIV_INT_BITS) >> PIO_SM0_CLKDIV_INT_LSB;
    uint32_t div_frac = (c.clkdiv & PIO_SM0_CLKDIV_FRAC_BITS) >> PIO_SM0_CLKDIV_FRAC_LSB;
    if (div_int == 0) {
        div_int = 65536;
    }
    float real_div = (float)div_int + (float)div_frac / 256.0f;

    return (float)clock_get_hz(clk_sys) / (real_div * blink_CYCLES_PER_BLINK);

At 2 Hz the divider fits, and the program gets what it asks for:

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 26 (6 instructions)
GPIO base: 16, LED on GPIO 37
Blink rate: asked for 2.0000 Hz, got 2.0000 Hz
Core 0 tick 1 (loop = 29904249)
Core 0 tick 2 (loop = 29947942)
Core 0 tick 3 (loop = 29948349)

At 1 Hz it doesn't:

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 26 (6 instructions)
GPIO base: 16, LED on GPIO 37
Blink rate: asked for 1.0000 Hz, got 9.6649 Hz
Core 0 tick 1 (loop = 29904242)
Core 0 tick 2 (loop = 29947916)
Core 0 tick 3 (loop = 29948342)

The divider should be 150 000 000 / 2052 ≈ 73 099.4. The SDK cuts the integer part to 16 bits: 73 099 − 65 536 = 7563, so the state machine runs with a divider of about 7563.4 and the LED blinks almost ten times a second instead of once. That is the "unrelated, faster rate" from lesson 1, and it is real: sampling the LED pin over SWD for a few seconds measured 9.665 Hz.

blink2.pio at 1 Hz prints Blink rate: asked for 1.0000 Hz, got 1.0000 Hz, and the LED measures 1.0000 Hz.

blink3.pio: a 32-bit count from the CPU

The nested loop in blink2.pio still relies on the clock divider to set the rate, and both X and Y can only be loaded with 0-31 by set. But X and Y are 32-bit registers. If the CPU sends the count once, through the TX FIFO, the state machine can run at the full system clock (divider exactly 1.0) and burn a 32-bit number of cycles per half period:

.program blink

.define public OVERHEAD_CYCLES_PER_HALF 3

    pull block          ; Pull 32-bit delay count from TX FIFO into OSR (once)
    out y, 32           ; Save it permanently in scratch register Y (once)

.wrap_target
    set pins, 1         ; LED on (1 cycle)
    mov x, y            ; Reload loop counter X from Y (1 cycle)
on_delay:
    jmp x-- on_delay    ; Decrement X until 0 (Y + 1 cycles)

    set pins, 0         ; LED off (1 cycle)
    mov x, y            ; Reload loop counter X from Y (1 cycle)
off_delay:
    jmp x-- off_delay   ; Decrement X until 0 (Y + 1 cycles)
.wrap                   ; Jump back to .wrap_target for free (0 cycles)

The new instructions:

  • pull block waits until there is a word in the TX FIFO and moves it into the OSR.
  • out y, 32 shifts all 32 bits of the OSR into Y.
  • mov x, y copies Y into X. Y keeps the count for good, and X is the one that gets counted down.

The first two instructions are before .wrap_target, so they only run once. After that the program loops between .wrap_target and .wrap forever, and Y never changes. Counting the cycles for one half of the blink:

Instruction Cycles
set pins 1
mov x, y 1
jmp x--, Y + 1 rounds Y + 1
Total Y + 3

A full blink is 2 × (Y + 3) system clocks. The C side sets the divider to 1, works out Y from the requested rate, starts the state machine and then pushes Y into the TX FIFO, where the waiting pull block picks it up:

    // Run at full clk_sys speed (divider = 1.0) so we never hit the 16-bit limit
    sm_config_set_clkdiv(&c, 1.0f);

    uint32_t sys_hz = clock_get_hz(clk_sys);
    double half_cycles = (double)sys_hz / (2.0 * (double)blink_hz);

    // Clamp to valid 32-bit unsigned range [0, UINT32_MAX]
    uint32_t delay_cycles;
    if (half_cycles <= (double)blink_OVERHEAD_CYCLES_PER_HALF) {
        delay_cycles = 0;
    } else if (half_cycles - (double)blink_OVERHEAD_CYCLES_PER_HALF >= (double)UINT32_MAX) {
        delay_cycles = UINT32_MAX;
    } else {
        delay_cycles = (uint32_t)(half_cycles - (double)blink_OVERHEAD_CYCLES_PER_HALF + 0.5);
    }

    pio_sm_init(pio, sm, offset, &c);
    pio_sm_set_enabled(pio, sm, true);

    // The state machine is stalled on 'pull block' and takes the count straight away
    pio_sm_put_blocking(pio, sm, delay_cycles);

    // Return the exact achieved frequency
    return (float)((double)sys_hz / (2.0 * ((double)delay_cycles + blink_OVERHEAD_CYCLES_PER_HALF)));

At 0.5 Hz, Y is 150 000 000 − 3 = 149 999 997:

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 24 (8 instructions)
GPIO base: 16, LED on GPIO 37
Blink rate: asked for 0.5000 Hz, got 0.5000 Hz
Core 0 tick 1 (loop = 29904058)
Core 0 tick 2 (loop = 29947910)
Core 0 tick 3 (loop = 29948342)

At 0.02 Hz (one blink every 50 seconds), Y is 3 749 999 997, well beyond anything the divider could do. Sampled over SWD, the LED stays off for 25.000 s:

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 24 (8 instructions)
GPIO base: 16, LED on GPIO 37
Blink rate: asked for 0.0200 Hz, got 0.0200 Hz
Core 0 tick 1 (loop = 29903647)
Core 0 tick 2 (loop = 29947976)
Core 0 tick 3 (loop = 29948342)

The largest Y is 4 294 967 295 (232 − 1), so at 150 MHz the slowest blink is:

150 000 000 / (2 × (4 294 967 295 + 3)) ≈ 0.0175 Hz (about 57 seconds per blink)

Ask for less and blink_program_init() clamps Y and says so, rather than blinking at some unrelated rate:

Blink rate: asked for 0.0100 Hz, got 0.0175 Hz

At the other end, Y = 0 gives 6 cycles per blink: 25 MHz at 150 MHz.

No jitter

There is a second, less obvious gain. In blink.pio at 2 Hz the divider is 150 000 000 / (2 × 2052) ≈ 36 549.7, which isn't a whole number. A fractional divider makes the state machine run on 36 549 system clocks for some of its cycles and 36 550 for others, so the average rate is right but individual blinks jitter by one system clock (6.7 ns at 150 MHz). The same thing happens with the 440 Hz square wave in lesson 2.

blink3.pio runs with a divider of exactly 1.0, so every half period is exactly Y + 3 system clocks, every time. The rate can only be set in steps of one system clock per half period, but at slow rates those steps are tiny: at 0.5 Hz, one step changes the rate by about 3 parts per billion.

blink4.pio: side-set saves two instructions

blink4.pio does the same with side-set (see Side-set, step by step in lesson 2). The LED is switched by mov x, y itself, in the same cycle as X is reloaded, so the two set pins instructions go:

.program blink
.side_set 1 opt

.define public OVERHEAD_CYCLES_PER_HALF 2

    pull block              ; Pull 32-bit delay count from TX FIFO into OSR (once)
    out y, 32               ; Save it permanently in scratch register Y (once)

.wrap_target
    mov x, y        side 1  ; LED on AND reload loop counter X from Y (1 cycle)
on_delay:
    jmp x-- on_delay        ; Decrement X until 0; pin stays high (Y + 1 cycles)

    mov x, y        side 0  ; LED off AND reload loop counter X from Y (1 cycle)
off_delay:
    jmp x-- off_delay       ; Decrement X until 0; pin stays low (Y + 1 cycles)
.wrap                       ; Jump back to .wrap_target for free (0 cycles)

opt is needed because pull, out and the two jmp instructions must leave the LED alone. Side-set with opt takes 2 of the 5 delay/side-set bits (one for the pin, one to say whether the instruction side-sets at all), leaving 3 bits, a maximum delay of 7. This program doesn't use any delays, so that costs nothing here. In C, sm_config_set_set_pins() becomes sm_config_set_sideset_pins(&c, pin); everything else is the same as in blink3.pio, with an overhead of 2 cycles instead of 3.

Instruction Cycles
mov x, y side 1/0 1
jmp x--, Y + 1 rounds Y + 1
Total Y + 2

The program is 6 instructions, 4 of them in the loop, so it sits at offset 26 instead of 24:

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 26 (6 instructions)
GPIO base: 16, LED on GPIO 37
Blink rate: asked for 0.5000 Hz, got 0.5000 Hz
Core 0 tick 1 (loop = 29904161)
Core 0 tick 2 (loop = 29947945)
Core 0 tick 3 (loop = 29948342)

At 0.02 Hz it also prints got 0.0200 Hz, and the LED stays off for 25.000 s. The slowest blink is the same 0.0175 Hz; the fastest, with Y = 0, is 4 cycles per blink, 37.5 MHz at 150 MHz (in theory; the GPIO pad and the LED give up long before that).

The four programs side by side

At 150 MHz:

Program Instructions Cycles per blink Clock divider Fastest Slowest
blink.pio 6 2052 1 to 65535 + 255/256 73.1 kHz 1.115 Hz
blink2.pio 10 65 668 1 to 65535 + 255/256 2284 Hz 0.0349 Hz
blink3.pio 8 2 × (Y + 3) exactly 1 25 MHz 0.0175 Hz
blink4.pio 6 2 × (Y + 2) exactly 1 37.5 MHz 0.0175 Hz

In every case the CPU loop count stays at about 29.9 million per second: however the LED is blinked, the CPU isn't involved.