Understanding RP2350 PIO Lesson 2

From Stm32World Wiki
Jump to navigation Jump to search

This is lesson 2 of Understanding RP2350 PIO, which has the overview of what PIO is, the instruction set and the tools. Previous: lesson 1, blink an LED without the CPU.


The second example, pio_2_square, turns a state machine into a square wave generator. You give it a frequency, it works out the clock divider, and it prints the divider and the frequency it actually gets, so you can check them on a scope. The output is on GPIO 38, which is PE4 on the Streamline header (position A16), right next to the LED.

Side-set, step by step

Side-set is the one new idea in this lesson, and it is easy to get wrong, so here it is from the ground up.

Understanding RP2350 PIO Side Set Bits.svg

1. Every PIO instruction is one 16-bit word

Every instruction, whatever it does, has the same three parts:

  • 3 bits: which instruction (jmp, wait, in, out, push/pull, mov, irq, set).
  • 8 bits: the details: which register, which value, which condition.
  • 5 spare bits in the middle, which every instruction carries no matter what it is.

The 5 spare bits can be spent on two things:

  • delay: "after doing this, wait N extra cycles". That is the [4] part.
  • side-set: "while you are doing this, also set this pin to 0 or 1". That is the side 1 part.

2. Side-set is "while you're at it"

Think of the instruction as the main job, and side-set as "while you're at it, flip this switch". The pin changes in the same cycle as the instruction, and it costs nothing extra: no extra instruction, no extra cycle.

Compare lesson 1 with lesson 2:

set pins, 1            ; lesson 1: the WHOLE instruction is spent on the pin
nop side 1             ; lesson 2: the instruction does nothing (nop),
                       ;           the pin changes as a free side effect

In square.pio the main job is nop, which does nothing at all, so the side-set is the only useful work. That looks silly, but in a real driver the main job is busy too. The classic example is an SPI clock: out pins, 1 side 0 puts a data bit on one pin and pulls the clock pin low, in the same cycle. That is why drivers like WS2812 and SPI are built around side-set.

3. Why the delay gets shorter

The 5 spare bits are shared, so every bit given to side-set is taken from the delay. .side_set 1 at the top of the program means "use 1 of the 5 bits for one side-set pin":

.side_set The 5 bits Max delay Meaning
(none) d d d d d 31 no side-set
1 s d d d d 15 1 pin
1 opt e s d d d 7 1 pin, and side may be left out
2 s s d d d 7 2 pins
3 s s s d d 3 3 pins
5 s s s s s 0 5 pins, no delay at all

s is a side-set pin value, d a delay bit and e the "this instruction has a side-set" bit that opt needs.

4. square.pio, bit by bit

pioasm turns the two lines of the program into these two words (they are in the generated build/square.pio.h):

nop side 1 [4]  =  0xb442  =  101 1 0100 01000010
nop side 0 [4]  =  0xa442  =  101 0 0100 01000010
                              --- - ---- --------
                               |  |  |       mov y, y  (that is what "nop" really is)
                               |  |  delay = 4
                               |  side-set bit: 1 = pin high, 0 = pin low
                               101 = mov

The two words are identical except for one bit, and that bit is the pin.

5. What happens cycle by cycle

Understanding RP2350 PIO Square Timing.svg

  • The side-set happens at the start of the instruction, in cycle 0.
  • The pin then stays where it was put. It holds its level through the delay, and until another instruction changes it. Side-set doesn't make a short pulse; it sets the pin to a level.
  • So the pin is high for 5 cycles and low for 5 cycles: 10 cycles per period.

6. Which pin does it hit?

The .pio file never says which pin. It only says "side-set uses 1 pin". The C setup picks the actual pin:

sm_config_set_sideset_pins(&c, pin);   // side-set bit 0 -> GPIO 38

So the same program can drive any GPIO the PIO block can reach. This is separate from the set pins mapping used in lesson 1: a state machine has separate pin groups for set, out and side-set, and they can point at different pins (or the same ones).

7. The "must" rule and opt

With plain .side_set 1, every instruction drives the pin, so pioasm makes you write side 0 or side 1 on every line. Leaving it out is an assembler error:

instruction requires 'side' to specify side set value for the instruction
because non optional sideset was specified for the program

If some instructions should leave the pin alone, use .side_set 1 opt. That costs the extra "enable" bit, and the maximum delay drops to 7.

In short

Every PIO instruction has 5 spare bits. Side-set spends some of them to set pins "for free" at the start of that instruction, the pins hold that level until something changes them, and whatever bits are left over are the delay.

The PIO program

.program square
.side_set 1                 ; 1 side-set pin -> delay field is now 4 bits (0..15)

.define DELAY 4
.define public CYCLES_PER_PERIOD (2 * (1 + DELAY))

.wrap_target
    nop side 1 [DELAY]      ; pin high, then wait DELAY more cycles
    nop side 0 [DELAY]      ; pin low, then wait DELAY more cycles
.wrap                       ; jump back to .wrap_target for free (0 cycles)

Two instructions. .define works like a C #define, and can be used for the delay; public exports it to the generated header, here as square_CYCLES_PER_PERIOD. Counting the cycles:

Instruction Cycles Pin
nop side 1 [DELAY] 1 + DELAY high
nop side 0 [DELAY] 1 + DELAY low
.wrap 0
One period 2 × (1 + DELAY)

With DELAY 4 a period is 10 PIO clock cycles, so:

frequency = clk_sys / (clock divider × 10)

At 150 MHz a divider of 1 gives 15 MHz and a divider of 15 gives exactly 1 MHz. DELAY can be anything from 0 to 15; with 0 the period is 2 cycles, 75 MHz at 150 MHz, which is the fastest square wave a state machine can make.

Why .wrap matters

.wrap is what keeps the duty cycle at exactly 50 %. If the program ended with a jmp back to the top instead, the jump would take a cycle of its own, and the low half would be one cycle longer than the high half (6 and 5 cycles instead of 5 and 5). The wrap happens in the same cycle as the last instruction, so it costs nothing. In lesson 1 that didn't matter, but at 15 MHz it would be the difference between 15 MHz at 50 % and 13.6 MHz at 45 %.

Working out the clock divider

The C part of square.pio works out the divider for the requested frequency:

static inline float square_program_init(PIO pio, uint sm, uint offset, uint pin, float freq_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);

    // The default config from pioasm already knows about ".side_set 1" (1 bit, not optional)
    pio_sm_config c = square_program_get_default_config(offset);

    // Side-set drives 1 pin, starting at 'pin'
    sm_config_set_sideset_pins(&c, pin);

    // divider = clk_sys / (freq_hz x CYCLES_PER_PERIOD), in units of 1/256, rounded
    double div = (double)clock_get_hz(clk_sys) / ((double)freq_hz * square_CYCLES_PER_PERIOD);
    uint32_t div_256 = (uint32_t)(div * 256.0 + 0.5);

    // Keep it in range (1 to 65535 + 255/256)
    if (div_256 < 256) div_256 = 256;
    if (div_256 > 0xffffff) div_256 = 0xffffff;

    // Integer part in the top 16 bits, fraction in the bottom 8
    sm_config_set_clkdiv_int_frac8(&c, div_256 >> 8, div_256 & 0xff);

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

    // 24 bits fit exactly in a float, so this is the exact divider the hardware uses
    return (float)div_256 / 256.0f;
}

Compared with lesson 1 there are two differences:

  • sm_config_set_sideset_pins() instead of sm_config_set_set_pins(). The number of side-set bits and whether they are optional is already in the default config that pioasm generates from .side_set 1.
  • The divider is a 16.8 fixed point number: 16 bits of integer and 8 bits of 1/256ths. So the function works it out in 1/256ths, rounds to the nearest one, keeps it in range and hands the two parts to sm_config_set_clkdiv_int_frac8(). It returns the divider the hardware actually uses, not the one that was asked for.

The calculation is done in double on purpose. A float has 24 bits of precision; a divider around 34 000 needs 16 of them for the integer part, leaving exactly 8 for the fraction, so the float division is already rounded to the nearest 1/256 before the code gets to round it. The first version of this example did the calculation in float and split it with the SDK's pio_calculate_clkdiv8_from_float(), and at 440 Hz it came out at 34090 + 234/256, one step off the correct 233/256.

Running it

main() is the same as in lesson 1, apart from the pin and the printouts. GPIO 38 is above 31, so again the SDK has to set the block's GPIO base to 16:

bool ok = pio_claim_free_sm_and_add_program_for_gpio_range(&square_program, &pio, &sm, &offset, SQUARE_PIN, 1, true);
hard_assert(ok);

float div = square_program_init(pio, sm, offset, SQUARE_PIN, SQUARE_HZ);

The output at the default 10 kHz, slow enough for a basic scope:

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 30 (2 instructions)
GPIO base: 16, square wave on GPIO 38
10 PIO cycles per period: 15000000.0 Hz (divider 1) down to 228.9 Hz (divider 65535 + 255/256)
Requested 10000.0 Hz -> clock divider 1500.00000000 (1500 + 0/256)
PIO clock 100000.000 Hz -> square wave 10000.00000 Hz
Core 0 tick 1 (loop = 29842797)
Core 0 tick 2 (loop = 29948201)

The two-instruction program sits at offset 30, the very top of the program memory. 150 MHz / 10 / 10 kHz is exactly 1500, so the divider has no fraction and every period is exactly 15 000 system clocks.

And at 440 Hz (SQUARE_HZ set to 440):

Core 0: Booting...
Running on Arm Cortex-M33 at 150 MHz
PIO2, state machine 0, program at offset 30 (2 instructions)
GPIO base: 16, square wave on GPIO 38
10 PIO cycles per period: 15000000.0 Hz (divider 1) down to 228.9 Hz (divider 65535 + 255/256)
Requested 440.0 Hz -> clock divider 34090.91015625 (34090 + 233/256)
PIO clock 4400.000 Hz -> square wave 439.99999 Hz
Core 0 tick 1 (loop = 29843466)
Core 0 tick 2 (loop = 29948202)

Here the ideal divider is 150 000 000 / 4400 = 34 090.909..., which isn't a whole number of 1/256ths. The nearest one is 34090 + 233/256, which gives 439.99999 Hz. Close enough for an A, but note what a fractional divider does: the state machine runs on 34090 system clocks for some cycles and 34091 for others, so individual periods jitter by one system clock (6.7 ns) while the average is right. At 10 kHz, with a whole-number divider, there is no jitter at all.

Min and max frequency

The clock divider goes from 1 to 65535 + 255/256, so the range of the program is set by the number of cycles per period alone:

max = clk_sys / (1 × CYCLES_PER_PERIOD)
min = clk_sys / ((65535 + 255/256) × CYCLES_PER_PERIOD)

At 150 MHz:

DELAY Cycles per period Max (divider 1) Min (divider 65535 + 255/256)
0 2 75 MHz 1144.41 Hz
4 (this program) 10 15 MHz 228.88 Hz
15 32 4.6875 MHz 71.53 Hz

square_program_init() clamps a request outside the range, so asking this program for 100 Hz gives 228.88 Hz rather than some unrelated frequency, as happened with the blink in lesson 1. Lower frequencies need more cycles per period than the delay field can give, which means a loop, as in lesson 1. The upper end is theory: a GPIO pad, and certainly a cheap scope, gives up long before 75 MHz.