PIO on the Raspberry Pi Pico
Every time I’ve started to approach the use of the programmable IO (PIO) subsystem on the RP2040 or RP2350 (as used on the Raspberry Pi Pico), I’ve found myself essentially starting from scratch again and the examples quite opaque to me.
So this time as I’ve worked through it yet again, I’ve decided to write it all down 🙂
Here are some existing tutorials and projects that talk about getting going with the PIO:
- RP2350 Datasheet – “Chapter 11: PIO”
- Raspberry Pi Pico-series C/C++ SDK – “Chapter 3: Using Programmable I/O (PIO)”.
- Hackspace Magazine Issue 39 – Raspberry Pi Pico Programmable I/O (page 40).
- Stephen Smith’s “I/O Co-processing on the Raspberry Pi Pico”
- PIO Examples: https://github.com/raspberrypi/pico-examples?tab=readme-ov-file#pio
Assembling PIO Code
The PIO has its own bespoke micro-instruction set that is very similar to many types of assembly language and it requires its own pio assembler to process it. The basic sequence is as follows:
- PIO -> pioasm -> C header file -> include in C/C++ project and build
There are options for writing PIO in both Micropython and Circuitpython, which I have done in the past, but I’m sticking with the C route here. This requires the pioasm to take PIO code and produce a C header file that can then be included in a C project.
To use the RP2040/2350 Arduino environment, it is necessary to process PIO independently and then add the C file to the Arduino project. The Raspberry Pi C/C++ SDK can process PIO files directly as part of the main build.
There is also an option to use hardware SDK functions for dynamic creation of PIO code at runtime. The functions are a series of pio_encode_XX() functions representing the different PIO instructions as listed here: https://www.raspberrypi.com/documentation/pico-sdk/hardware.html#group_pio_instructions
There are two other novel approaches I found so far too:
- Wokwi online PIO assembler: https://wokwi.com/tools/pioasm
- Piersrocks’ runtime PIO assembler: https://github.com/piersfinlayson/apio
The first is an online editing environment that creates the required processed PIO related code for the C/C++ SDK or Python which can then be included in your build environment as required.
The second is an alternative run-time approach that uses a range of C macros to allow the “assembling” of PIO code as part of the run-time execution. It does this by directly creating the HEX equivalents of PIO instructions, thereby effectively assembling in the fly. This means that the PIO code can be customised to the specific run-time situation.
At this stage I’m not sure what it gives over using the pio_encode_ SDK functions directly. I do note however there is an equivalent PIO emulator which means this approach will run equally well on real hardware or in emulation. I’ve bookmarked this to come back to at some point.
Running PIO Code
Regardless of how the PIO instructions become code, to use them requires setting up and configuring the PIO state machines at run time as part of a project. A common approach is to include an initialisation function within the PIO code itself that is destined for passing straight through to the C/C++ SDK. This will have access to all definitions used within the PIO code and also allows the appropriate configuration information to remain encapsulated with the code.
But I have to admit I find there is an awful lot of assumed “magic” going on when configuring and getting running PIO programs and state machines. And whilst there are plenty of examples to study, I don’t find that they are written so as to teach. Consequently, I’ve noted the following as “reminders to self” on how to read some of the examples. It doesn’t help that the SDK function list is very long and there are several ways to achieve the same things.
Taking the PIO PWM code from the pico_examples as a starting point (https://github.com/raspberrypi/pico-examples/tree/master/pio/pwm), I’ve added in some comments containing the full function prototypes for some of the calls to make them a bit easier to walk through.
pwm.pio:
;; Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
;
; SPDX-License-Identifier: BSD-3-Clause
;
; Side-set pin 0 is used for PWM output
.pio_version 0 // only requires PIO version 0
.program pwm
.side_set 1 opt
pull noblock side 0 ; Pull from FIFO to OSR if available, else copy X to OSR.
mov x, osr ; Copy most-recently-pulled value back to scratch X
mov y, isr ; ISR contains PWM period. Y used as counter.
countloop:
jmp x!=y noset ; Set pin high if X == Y, keep the two paths length matched
jmp skip side 1
noset:
nop ; Single dummy cycle to keep the two paths the same length
skip:
jmp y-- countloop ; Loop until Y hits 0, then pull a fresh PWM value from FIFO
% c-sdk {
static inline void pwm_program_init(PIO pio, uint sm, uint offset, uint pin) {
// static void pio_gpio_init (PIO pio, uint pin)
pio_gpio_init(pio, pin);
// int pio_sm_set_consecutive_pindirs (PIO pio, uint sm, uint pins_base, uint pin_count, bool is_out)
pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true);
// A piece of pioasm "magic" based on .program pwm (see following notes)
pio_sm_config c = pwm_program_get_default_config(offset);
// static void sm_config_set_sideset_pins (pio_sm_config *c, uint sideset_base)
sm_config_set_sideset_pins(&c, pin);
// int pio_sm_init (PIO pio, uint sm, uint initial_pc, const pio_sm_config *config)
pio_sm_init(pio, sm, offset, &c);
}
%}
And its associated C code pwm.c:
/*** Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pio.h"
#include "pwm.pio.h"
// Write `period` to the input shift register
void pio_pwm_set_period(PIO pio, uint sm, uint32_t period) {
pio_sm_set_enabled(pio, sm, false);
pio_sm_put_blocking(pio, sm, period);
pio_sm_exec(pio, sm, pio_encode_pull(false, false));
pio_sm_exec(pio, sm, pio_encode_out(pio_isr, 32));
pio_sm_set_enabled(pio, sm, true);
}
// Write `level` to TX FIFO. State machine will copy this into X.
void pio_pwm_set_level(PIO pio, uint sm, uint32_t level) {
pio_sm_put_blocking(pio, sm, level);
}
int main() {
stdio_init_all();
#ifndef PICO_DEFAULT_LED_PIN
#warning pio/pwm example requires a board with a regular LED
puts("Default LED pin was not defined");
#else
// todo get free sm
PIO pio = pio0;
int sm = 0;
uint offset = pio_add_program(pio, &pwm_program);
printf("Loaded program at %d\n", offset);
pwm_program_init(pio, sm, offset, PICO_DEFAULT_LED_PIN);
pio_pwm_set_period(pio, sm, (1u << 16) - 1);
int level = 0;
while (true) {
printf("Level = %d\n", level);
pio_pwm_set_level(pio, sm, level * level);
level = (level + 1) % 256;
sleep_ms(10);
}
#endif
}
There are a few key things to remember to make sense of these examples:
- The offset that is talked about is (I believe) the location within the shared 32 instruction program area and is used to refer back to the installed PIO program. It is returned from pio_add_program().
- A PIO .program directive becomes a default C like directive on processing by pioasm. This results in two obscure bits of “magic” coding going on meaning in this case that “.program pwm” in the PIO file becomes “pwm_program” in C/C++:
- pio_program_t pwm_program is a C structure which can then be referenced from the C code as shown in the line pio_add_program(pio, &pwm_program).
- static inline pio_sm_config pwm_program_get_default_config(uint offset) is a C function based on pio_get_default_sm_config() that returns the PIO configuration for the specific PIO program in question – in this case of course the pwm program.
- The use of .side_step opt means that not every PIO instruction has to have a side step instruction too.
- The PIO refers to an abstract group of pins, but it is the configuration which is part of the C/C++ SDK that determines which pins are used.
- The %c-sdk { … %} pairing signifies that this part of the PIO code will be passed straight onto the C/C++ SDK.
- There are multiple ways of initialising GPIO pins and directions. In this example it doesn’t use pindirs in the PIO code but uses pio_sm_set_consecutive_pindirs() in the C code.
- This example uses hardcoded references to PIO 0 and SM 0, but in many cases the PIO and SM would be chosen dynamically using API calls such as the following:
- pio_claim_free_sm_and_add_program ()
- pio_claim_free_sm_and_add_program_for_gpio_range()
- pio_claim_unused_sm()
- Each PIO program has a default configuration associated with it which can be updated. A typical pattern is shown here where the default configuration is grabbed using (in this case) pwm_program_get_default_config() and then updated by passing into following SDK calls.
- The state machine is finally set running using pio_sm_init();
There is one additional mix of techniques that is worth pulling out here. In the C code the function pio_pwm_set_period() is used to update the PWM period which it has to do by passing it into the SM via the FIFO. It is using some SM manipulation routines and then some inline, run-time PIO code, to achieve this.
void pio_pwm_set_period(PIO pio, uint sm, uint32_t period) {pio_sm_set_enabled(pio, sm, false);
pio_sm_put_blocking(pio, sm, period);
pio_sm_exec(pio, sm, pio_encode_pull(false, false));
pio_sm_exec(pio, sm, pio_encode_out(pio_isr, 32));
pio_sm_set_enabled(pio, sm, true);
}
Again some pretty confusing API calls, especially giving this is meant to be an example, but essentially what is going on (I think) is:
Disable the statemachine by using pio_sm_set_enabled(... false).Push the period value into the TX FIFO, blocking if full to wait for it to be empty.
Execute two direct PIO instructions using pio_sm_exec():
This uses pio_encode_pull and pio_encode_out to run the following PIO code:
pull noblock ; non-blocking pull
out isr, 32 ; out 32 bits to the interrupt shift register
Re-enable he state machine using pio_sm_set_enabled(... true).
By default anything sent to the FIFO is written to the X register and used to set the duty cycle of the PWM. But this code creates some temporary PIO code to receive the contents of the FIFO and put it into ISR instead. Of course it has to temporarily suspend the execution of the stored PIO code in order to do this.
I really dislike the nomenclature of “set enabled (false)” as an API approach. I’d much prefer to see something like pio_sm_enable() and pio_sm_disable() myself. I suppose they haven’t done this due to the large increase in API functions it creates.
I guess this is personal preference, but I do find that it adds to the opaqueness of much of the example code when it doesn’t read naturally.
So To Recap…
Writing PIO code can be done at build time (from Python or C/C++ using pioasm or an online assembler) or run time (using pio_encode_ functions or maybe APIO).
pioasm bridges the gap between PIO code and C/C++ including creating two magic C/C++ constructs: pwm_program for the code and pwm_program_get_default_config() to return the created PIO configuration.
PIO and SMs can be allocated by the system using a range of “claim” functions. There are 2 PIOs on the RP2040 and 3 on the RP2350, each with its own 32 instruction program memory and each with four state machines.
It can be useful to include an initialisation routine, that configures and starts the PIO program, within the PIO code for use from the C/C++ code using % c-sdk { … %}.
The PIO program is added into the system and given an offset in instruction memory using pio_add_program.
PIO code is very dense and often the functionality cannot be seen from the PIO code itself as it is defined by the PIO configuration – e.g. pins to use, frequency of execution, direction of shifts and so on.
I’ve not touched on it here, but the use of PIO and DMA (direct memory access) often go hand in hand to create completely CPU-free means of getting data in and out of a RP2040/RP2350 system. A really good example of this is Piers Rocks’ OneROM (see this video for a brilliant summary of how this works: https://www.youtube.com/watch?v=Y8RODQZM2HY).
Finally I need to remember that ISR stands for Input Shift Register and not Interrupt Service Routine…
Kevin
#pio #raspberryPiPico #rp2040 #rp2350