试试用Rust为树莓派RP2040开发程序

发布时间 2023-08-10 15:41:36作者: IotaHydrae

试试用Rust为树莓派RP2040开发程序

实验环境
树莓派Pico开发板
DAPLINK调试器

原工程链接:https://github.com/rp-rs/rp-hal-boards

假设读者已经安装配置好了 cargo 环境

1. 安装配置

获取工具链

rustup self update
rustup update stable
rustup target add thumbv6m-none-eabi

选择性安装下载工具

# Useful to creating UF2 images for the RP2040 USB Bootloader
cargo install elf2uf2-rs --locked
# Useful for flashing over the SWD pins using a supported JTAG probe
cargo install probe-run
  1. 创建工程
cargo new blink

cd blink
cargo add rp-pico
cargo add cortex-m-rt
cargo add panic-halt

.cargo/config

#
# Cargo Configuration for the https://github.com/rp-rs/rp-hal.git repository.
#
# Copyright (c) The RP-RS Developers, 2021
#
# You might want to make a similar file in your own repository if you are
# writing programs for Raspberry Silicon microcontrollers.
#
# This file is MIT or Apache-2.0 as per the repository README.md file
#

[build]
# Set the default target to match the Cortex-M0+ in the RP2040
target = "thumbv6m-none-eabi"

# Target specific options
[target.thumbv6m-none-eabi]
# Pass some extra options to rustc, some of which get passed on to the linker.
#
# * linker argument --nmagic turns off page alignment of sections (which saves
#   flash space)
# * linker argument -Tlink.x tells the linker to use link.x as the linker
#   script. This is usually provided by the cortex-m-rt crate, and by default
#   the version in that crate will include a file called `memory.x` which
#   describes the particular memory layout for your specific chip. 
# * inline-threshold=5 makes the compiler more aggressive and inlining functions
# * no-vectorize-loops turns off the loop vectorizer (seeing as the M0+ doesn't
#   have SIMD)
rustflags = [
    "-C", "link-arg=--nmagic",
    "-C", "link-arg=-Tlink.x",
    "-C", "inline-threshold=5",
    "-C", "no-vectorize-loops",
]

# This runner will make a UF2 file and then copy it to a mounted RP2040 in USB
# Bootloader mode:
runner = "elf2uf2-rs -d"

# This runner will find a supported SWD debug probe and flash your RP2040 over
# SWD:
# runner = "probe-run --chip RP2040"

memory.x

MEMORY {
    BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100
    FLASH : ORIGIN = 0x10000100, LENGTH = 2048K - 0x100
    RAM   : ORIGIN = 0x20000000, LENGTH = 256K
}

EXTERN(BOOT2_FIRMWARE)

SECTIONS {
    /* ### Boot loader */
    .boot2 ORIGIN(BOOT2) :
    {
        KEEP(*(.boot2));
    } > BOOT2
} INSERT BEFORE .text;

src/main.rs

#![no_std]
#![no_main]
use rp_pico::entry;
use panic_halt as _;
#[entry]
fn see_doesnt_have_to_be_called_main() -> ! {
  loop {}
}

编译,烧录测试

$ cargo build -r

输出文件位于 target/thumbv6m-none-eabi/release

uf2 bootloader 烧录

打开工程目录.cargo/config文件,修改runner = "elf2uf2-rs -d"

待添加

daplink烧录

打开工程目录.cargo/config文件,修改runner = "probe-run --chip RP2040"

$ probe-run target/thumbv6m-none-eabi/release/blink --chip rp2040
或者直接执行
$ cargo run