Add pio pwm example (#365)

* Add pio pwm example

This adds a more advance pio example which uses side set and instruction injection
This commit is contained in:
Hmvp 2022-06-26 14:11:41 +02:00 committed by GitHub
parent e5897ca7a4
commit b12aecb51c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 199 additions and 0 deletions

View file

@ -34,6 +34,8 @@ ws2812-pio = "0.3.0"
ssd1306 = "0.7.0"
embedded-graphics = "0.7.1"
hd44780-driver = "0.4.0"
pio = "0.2.0"
pio-proc = "0.2.1"
defmt = "0.2.0"
defmt-rtt = "0.2.0"

View file

@ -0,0 +1,166 @@
//! # Pico PIO PWM Blink Example
//!
//! Fades the LED on a Pico board using the PIO peripheral with an pwm program.
//!
//! This will fade in the LED attached to GP25, which is the pin the Pico
//! uses for the on-board LED.
//!
//! This example uses a few advance pio tricks such as side setting pins and instruction injection.
//!
//! See the `Cargo.toml` file for Copyright and license details. Except for the pio program which is subject to a different license.
#![no_std]
#![no_main]
use defmt::info;
use defmt_rtt as _;
// The macro for our start-up function
use rp_pico::entry;
// Time handling traits
use embedded_time::rate::*;
// Ensure we halt the program on panic (if we don't mention this crate it won't
// be linked)
use panic_halt as _;
// Pull in any important traits
use rp_pico::hal::prelude::*;
// A shorter alias for the Peripheral Access Crate, which provides low-level
// register access
use rp_pico::hal::pac;
// A shorter alias for the Hardware Abstraction Layer, which provides
// higher-level drivers.
use rp_pico::hal;
// Import pio crates
use hal::pio::{PIOBuilder, Running, StateMachine, Tx, ValidStateMachine, SM0};
use pio::{InstructionOperands, OutDestination};
use pio_proc::pio_file;
/// Set pio pwm period
///
/// This uses a sneaky trick to set a second value besides the duty cycle.
/// We first write a value to the tx fifo. But instead of the normal instructions we
/// have stopped the state machine and inject our own instructions that move the written value to the ISR.
fn pio_pwm_set_period<T: ValidStateMachine>(
sm: StateMachine<(hal::pac::PIO0, SM0), Running>,
tx: &mut Tx<T>,
period: u32,
) -> StateMachine<(hal::pac::PIO0, SM0), Running> {
// To make sure the inserted instructions actually use our newly written value
// We first busy loop to empty the queue. (Which typically should be the case)
while !tx.is_empty() {}
let mut sm = sm.stop();
tx.write(period);
sm.exec_instruction(
InstructionOperands::PULL {
if_empty: false,
block: false,
}
.encode(),
);
sm.exec_instruction(
InstructionOperands::OUT {
destination: OutDestination::ISR,
bit_count: 32,
}
.encode(),
);
sm.start()
}
/// Set pio pwm duty cycle
///
/// The value written to the TX FIFO is used directly by the normal pio program
fn pio_pwm_set_level<T: ValidStateMachine>(tx: &mut Tx<T>, level: u32) {
// Write duty cycle to TX Fifo
tx.write(level);
}
/// Entry point to our bare-metal application.
///
/// The `#[entry]` macro ensures the Cortex-M start-up code calls this function
/// as soon as all global variables are initialised.
///
/// The function configures the RP2040 peripherals, then fades the LED in an
/// infinite loop.
#[entry]
fn main() -> ! {
// Grab our singleton objects
let mut pac = pac::Peripherals::take().unwrap();
let core = pac::CorePeripherals::take().unwrap();
// Set up the watchdog driver - needed by the clock setup code
let mut watchdog = hal::Watchdog::new(pac.WATCHDOG);
// Configure the clocks
//
// The default is to generate a 125 MHz system clock
let clocks = hal::clocks::init_clocks_and_plls(
rp_pico::XOSC_CRYSTAL_FREQ,
pac.XOSC,
pac.CLOCKS,
pac.PLL_SYS,
pac.PLL_USB,
&mut pac.RESETS,
&mut watchdog,
)
.ok()
.unwrap();
// The single-cycle I/O block controls our GPIO pins
let sio = hal::Sio::new(pac.SIO);
// Set the pins up according to their function on this particular board
let pins = rp_pico::Pins::new(
pac.IO_BANK0,
pac.PADS_BANK0,
sio.gpio_bank0,
&mut pac.RESETS,
);
// The delay object lets us wait for specified amounts of time (in
// milliseconds)
let mut delay = cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().integer());
let (mut pio0, sm0, _, _, _) = pac.PIO0.split(&mut pac.RESETS);
// Create a pio program
let program = pio_file!("./examples/pwm.pio", select_program("pwm"),);
let installed = pio0.install(&program.program).unwrap();
// Set gpio25 to pio
let _led: hal::gpio::Pin<_, hal::gpio::FunctionPio0> = pins.led.into_mode();
let led_pin_id = 25;
// Build the pio program and set pin both for set and side set!
// We are running with the default divider which is 1 (max speed)
let (mut sm, _, mut tx) = PIOBuilder::from_program(installed)
.set_pins(led_pin_id, 1)
.side_set_pin_base(led_pin_id)
.build(sm0);
// Set pio pindir for gpio25
sm.set_pindirs([(led_pin_id, hal::pio::PinDir::Output)]);
// Start state machine
let sm = sm.start();
// Set period
pio_pwm_set_period(sm, &mut tx, u16::MAX as u32 - 1);
// Loop forever and adjust duty cycle to make te led brighter
let mut level = 0;
loop {
info!("Level = {}", level);
pio_pwm_set_level(&mut tx, level * level);
level = (level + 1) % 256;
delay.delay_ms(10);
}
}
// End of file

View file

@ -0,0 +1,31 @@
;
; Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
;
; SPDX-License-Identifier: BSD-3-Clause
;
; Side-set pin 0 is used for PWM output
.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) {
pio_gpio_init(pio, pin);
pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true);
pio_sm_config c = pwm_program_get_default_config(offset);
sm_config_set_sideset_pins(&c, pin);
pio_sm_init(pio, sm, offset, &c);
}
%}