让RP2040生锈
LI Rui

朋友们,大家下午好。最近被一位大佬种草了微雪电子的RP2040-Zero开发板,看上去非常精致,遂下单购买。

拿到这块板子,上电,按住Boot按钮并按一次Reset后,可以看到被识别为USB存储设备。

我们可以把编译后的程序(UF2格式)拖到挂载的目录中,就可以自动烧录。因为不需要进行调试,所以我们也不需要购买仿真器(其实是没钱了,哭)。看上去官方例程只有C和Python的,这怎么行?下面让我们用Rust来点亮板载的这颗WS2812B小灯。

我们使用的库为rp-hal,这个项目意在为Raspberry Silicon系列微控制器提供Rust支持。同时他们为RP2040提供了项目模板Project template for rp2040-hal,我们可以参考README安装以下依赖:

1
2
3
4
rustup target install thumbv6m-none-eabi
cargo install flip-link
cargo install probe-run
cargo install elf2uf2-rs

Cargo.toml中加入我们需要的依赖:

1
2
3
smart-leds = "0.3.0"
ws2812-pio = { git = "https://github.com/ithinuel/ws2812-pio-rs", rev = "4f0d81e594ea9934f9c4c38ed9824ad0cce4ebb5" }
nb = "1.0.0"

src/main.rs代码如下(参考官方Example,这里我们修改对应的引脚为原理图中的GPIO16):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#![no_std]
#![no_main]

use core::iter::once;
use cortex_m_rt::entry;
use defmt_rtt as _;
use embedded_hal::timer::CountDown;
use embedded_time::duration::Extensions;
use panic_probe as _;
use pico as bsp;
use smart_leds::{brightness, SmartLedsWrite, RGB8};
use ws2812_pio::Ws2812;

use bsp::hal::{
clocks::{init_clocks_and_plls, Clock},
pac,
pio::PIOExt,
sio::Sio,
watchdog::Watchdog,
Timer,
};

#[entry]
fn main() -> ! {
let mut pac = pac::Peripherals::take().unwrap();
let mut watchdog = Watchdog::new(pac.WATCHDOG);
let sio = Sio::new(pac.SIO);

let external_xtal_freq_hz = 12_000_000u32;
let clocks = init_clocks_and_plls(
external_xtal_freq_hz,
pac.XOSC,
pac.CLOCKS,
pac.PLL_SYS,
pac.PLL_USB,
&mut pac.RESETS,
&mut watchdog,
)
.ok()
.unwrap();

let pins = bsp::Pins::new(
pac.IO_BANK0,
pac.PADS_BANK0,
sio.gpio_bank0,
&mut pac.RESETS,
);

let led = pins.gpio16.into_mode();

let timer = Timer::new(pac.TIMER, &mut pac.RESETS);
let mut delay = timer.count_down();

let (mut pio, sm0, _, _, _) = pac.PIO0.split(&mut pac.RESETS);
let mut ws = Ws2812::new(
led,
&mut pio,
sm0,
clocks.peripheral_clock.freq(),
timer.count_down(),
);

let mut n: u8 = 128;
loop {
ws.write(brightness(once(wheel(n)), 32)).unwrap();
n = n.wrapping_add(1);

delay.start(25.milliseconds());
let _ = nb::block!(delay.wait());
}
}

fn wheel(mut wheel_pos: u8) -> RGB8 {
wheel_pos = 255 - wheel_pos;
if wheel_pos < 85 {
// No green in this sector - red and blue only
(255 - (wheel_pos * 3), 0, wheel_pos * 3).into()
} else if wheel_pos < 170 {
// No red in this sector - green and blue only
wheel_pos -= 85;
(0, wheel_pos * 3, 255 - (wheel_pos * 3)).into()
} else {
// No blue in this sector - red and green only
wheel_pos -= 170;
(wheel_pos * 3, 255 - (wheel_pos * 3), 0).into()
}
}

挂载RP2后,cargo run就可以看见彩虹灯啦~

  • 本文标题:让RP2040生锈
  • 本文作者:LI Rui
  • 创建时间:2021-12-17 14:56:55
  • 本文链接:https://www.lirui.tech/post/2021/bc7fc067d039.html
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-SA 许可协议。转载请注明出处!