Skip to content

Commit b12aecb

Browse files
authored
Add pio pwm example (#365)
* Add pio pwm example This adds a more advance pio example which uses side set and instruction injection
1 parent e5897ca commit b12aecb

File tree

3 files changed

+199
-0
lines changed

3 files changed

+199
-0
lines changed

boards/rp-pico/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ ws2812-pio = "0.3.0"
3434
ssd1306 = "0.7.0"
3535
embedded-graphics = "0.7.1"
3636
hd44780-driver = "0.4.0"
37+
pio = "0.2.0"
38+
pio-proc = "0.2.1"
3739

3840
defmt = "0.2.0"
3941
defmt-rtt = "0.2.0"
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
//! # Pico PIO PWM Blink Example
2+
//!
3+
//! Fades the LED on a Pico board using the PIO peripheral with an pwm program.
4+
//!
5+
//! This will fade in the LED attached to GP25, which is the pin the Pico
6+
//! uses for the on-board LED.
7+
//!
8+
//! This example uses a few advance pio tricks such as side setting pins and instruction injection.
9+
//!
10+
//! See the `Cargo.toml` file for Copyright and license details. Except for the pio program which is subject to a different license.
11+
12+
#![no_std]
13+
#![no_main]
14+
15+
use defmt::info;
16+
use defmt_rtt as _;
17+
// The macro for our start-up function
18+
use rp_pico::entry;
19+
20+
// Time handling traits
21+
use embedded_time::rate::*;
22+
23+
// Ensure we halt the program on panic (if we don't mention this crate it won't
24+
// be linked)
25+
use panic_halt as _;
26+
27+
// Pull in any important traits
28+
use rp_pico::hal::prelude::*;
29+
30+
// A shorter alias for the Peripheral Access Crate, which provides low-level
31+
// register access
32+
use rp_pico::hal::pac;
33+
34+
// A shorter alias for the Hardware Abstraction Layer, which provides
35+
// higher-level drivers.
36+
use rp_pico::hal;
37+
38+
// Import pio crates
39+
use hal::pio::{PIOBuilder, Running, StateMachine, Tx, ValidStateMachine, SM0};
40+
use pio::{InstructionOperands, OutDestination};
41+
use pio_proc::pio_file;
42+
43+
/// Set pio pwm period
44+
///
45+
/// This uses a sneaky trick to set a second value besides the duty cycle.
46+
/// We first write a value to the tx fifo. But instead of the normal instructions we
47+
/// have stopped the state machine and inject our own instructions that move the written value to the ISR.
48+
fn pio_pwm_set_period<T: ValidStateMachine>(
49+
sm: StateMachine<(hal::pac::PIO0, SM0), Running>,
50+
tx: &mut Tx<T>,
51+
period: u32,
52+
) -> StateMachine<(hal::pac::PIO0, SM0), Running> {
53+
// To make sure the inserted instructions actually use our newly written value
54+
// We first busy loop to empty the queue. (Which typically should be the case)
55+
while !tx.is_empty() {}
56+
57+
let mut sm = sm.stop();
58+
tx.write(period);
59+
sm.exec_instruction(
60+
InstructionOperands::PULL {
61+
if_empty: false,
62+
block: false,
63+
}
64+
.encode(),
65+
);
66+
sm.exec_instruction(
67+
InstructionOperands::OUT {
68+
destination: OutDestination::ISR,
69+
bit_count: 32,
70+
}
71+
.encode(),
72+
);
73+
sm.start()
74+
}
75+
76+
/// Set pio pwm duty cycle
77+
///
78+
/// The value written to the TX FIFO is used directly by the normal pio program
79+
fn pio_pwm_set_level<T: ValidStateMachine>(tx: &mut Tx<T>, level: u32) {
80+
// Write duty cycle to TX Fifo
81+
tx.write(level);
82+
}
83+
84+
/// Entry point to our bare-metal application.
85+
///
86+
/// The `#[entry]` macro ensures the Cortex-M start-up code calls this function
87+
/// as soon as all global variables are initialised.
88+
///
89+
/// The function configures the RP2040 peripherals, then fades the LED in an
90+
/// infinite loop.
91+
#[entry]
92+
fn main() -> ! {
93+
// Grab our singleton objects
94+
let mut pac = pac::Peripherals::take().unwrap();
95+
let core = pac::CorePeripherals::take().unwrap();
96+
97+
// Set up the watchdog driver - needed by the clock setup code
98+
let mut watchdog = hal::Watchdog::new(pac.WATCHDOG);
99+
100+
// Configure the clocks
101+
//
102+
// The default is to generate a 125 MHz system clock
103+
let clocks = hal::clocks::init_clocks_and_plls(
104+
rp_pico::XOSC_CRYSTAL_FREQ,
105+
pac.XOSC,
106+
pac.CLOCKS,
107+
pac.PLL_SYS,
108+
pac.PLL_USB,
109+
&mut pac.RESETS,
110+
&mut watchdog,
111+
)
112+
.ok()
113+
.unwrap();
114+
115+
// The single-cycle I/O block controls our GPIO pins
116+
let sio = hal::Sio::new(pac.SIO);
117+
118+
// Set the pins up according to their function on this particular board
119+
let pins = rp_pico::Pins::new(
120+
pac.IO_BANK0,
121+
pac.PADS_BANK0,
122+
sio.gpio_bank0,
123+
&mut pac.RESETS,
124+
);
125+
126+
// The delay object lets us wait for specified amounts of time (in
127+
// milliseconds)
128+
let mut delay = cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().integer());
129+
130+
let (mut pio0, sm0, _, _, _) = pac.PIO0.split(&mut pac.RESETS);
131+
132+
// Create a pio program
133+
let program = pio_file!("./examples/pwm.pio", select_program("pwm"),);
134+
let installed = pio0.install(&program.program).unwrap();
135+
136+
// Set gpio25 to pio
137+
let _led: hal::gpio::Pin<_, hal::gpio::FunctionPio0> = pins.led.into_mode();
138+
let led_pin_id = 25;
139+
140+
// Build the pio program and set pin both for set and side set!
141+
// We are running with the default divider which is 1 (max speed)
142+
let (mut sm, _, mut tx) = PIOBuilder::from_program(installed)
143+
.set_pins(led_pin_id, 1)
144+
.side_set_pin_base(led_pin_id)
145+
.build(sm0);
146+
147+
// Set pio pindir for gpio25
148+
sm.set_pindirs([(led_pin_id, hal::pio::PinDir::Output)]);
149+
150+
// Start state machine
151+
let sm = sm.start();
152+
153+
// Set period
154+
pio_pwm_set_period(sm, &mut tx, u16::MAX as u32 - 1);
155+
156+
// Loop forever and adjust duty cycle to make te led brighter
157+
let mut level = 0;
158+
loop {
159+
info!("Level = {}", level);
160+
pio_pwm_set_level(&mut tx, level * level);
161+
level = (level + 1) % 256;
162+
delay.delay_ms(10);
163+
}
164+
}
165+
166+
// End of file

boards/rp-pico/examples/pwm.pio

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
;
2+
; Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
3+
;
4+
; SPDX-License-Identifier: BSD-3-Clause
5+
;
6+
7+
; Side-set pin 0 is used for PWM output
8+
9+
.program pwm
10+
.side_set 1 opt
11+
12+
pull noblock side 0 ; Pull from FIFO to OSR if available, else copy X to OSR.
13+
mov x, osr ; Copy most-recently-pulled value back to scratch X
14+
mov y, isr ; ISR contains PWM period. Y used as counter.
15+
countloop:
16+
jmp x!=y noset ; Set pin high if X == Y, keep the two paths length matched
17+
jmp skip side 1
18+
noset:
19+
nop ; Single dummy cycle to keep the two paths the same length
20+
skip:
21+
jmp y-- countloop ; Loop until Y hits 0, then pull a fresh PWM value from FIFO
22+
23+
% c-sdk {
24+
static inline void pwm_program_init(PIO pio, uint sm, uint offset, uint pin) {
25+
pio_gpio_init(pio, pin);
26+
pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true);
27+
pio_sm_config c = pwm_program_get_default_config(offset);
28+
sm_config_set_sideset_pins(&c, pin);
29+
pio_sm_init(pio, sm, offset, &c);
30+
}
31+
%}

0 commit comments

Comments
 (0)