赞
踩
我的开发板有两个了 LED 灯,做一个用按键控制两个灯的小测试。电路图如下:
可见 LED 连接在 PF9 和 PF10 引脚,按键连接在 PA0 引脚。
用 Cargo 创建一个 Rust 项目,并在一下文件中添加代码:
./memory.x
:需要自己新建。这是用来配置存储分布的,我的 MCU 是 stm32f407 系列的。
MEMORY
{
/* NOTE 1 K = 1 KiBi = 1024 bytes */
FLASH : ORIGIN = 0x08000000, LENGTH = 512K
RAM : ORIGIN = 0x20000000, LENGTH = 100K
}
./Cargo.toml
:做一些项目配置,加载需要的库。
[package] name = "stm32led" version = "0.1.0" edition = "2021" [profile.release] panic = "abort" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] embedded-hal = "0.2" nb = "1" cortex-m = "0.7" cortex-m-rt = "0.7" # Panic behaviour, see https://crates.io/keywords/panic-impl for alternatives panic-halt = "0.2" [dependencies.stm32f4xx-hal] version = "0.13.1" features = ["stm32f407"]
./src/main.rs
:代码源文件。
#![no_std] #![no_main] use panic_halt as _; use cortex_m_rt::entry; use stm32f4xx_hal as hal; use hal::{prelude::*, pac}; #[entry] fn main() -> ! { if let (Some(dp), Some(cp)) = ( pac::Peripherals::take(), cortex_m::peripheral::Peripherals::take(), ) { let gf = dp.GPIOF.split(); let ga = dp.GPIOA.split(); let mut led0 = gf.pf9.into_push_pull_output(); let mut led1 = gf.pf10.into_push_pull_output(); let key = ga.pa0.into_pull_down_input(); let rcc = dp.RCC.constrain(); let clocks = rcc.cfgr.sysclk(168.MHz()).freeze(); // Create a delay abstraction based on SysTick let mut delay = cp.SYST.delay(&clocks); loop { // On for 1s, off for 1s. if key.is_high() { led1.set_high(); led0.set_low(); } else if key.is_low() { led1.set_low(); led0.set_high(); } delay.delay_ms(50_u32); } } loop {} }
./Makefile
:可选。
stm32led.bin :
cargo rustc --release --target thumbv7em-none-eabihf -- -C link-arg=-Tlink.x
arm-none-eabi-objcopy target/thumbv7em-none-eabihf/release/stm32led -O binary stm32led.bin
load:
sudo stm32flash -w stm32led.bin -v -g 0x00 /dev/ttyUSB0
clean:
rm stm32led.bin
编译下载执行: 成功 load 后你就可以通过按 KEY_UP 键,切换 LED0 和 LED1 的亮灭。
make clean
make
make load
一些注意的点:
rustup target add thumbv7em-none-eabihf
,其他的 MCU 要安装对应的文件。cargo rustc --release --target thumbv7em-none-eabihf -- -C link-arg=-Tlink.x
,注意不是 build 而是 rustc,还有 -C 前的两个横杠不可以省略。yay -S stm32flash
objcopy
去转换为 bin 文件。在 Makefile 中有这一指令,这个指令可由安装 arm-none-eabi-gcc 获得: sudo pacman -S arm-none-eabi-gcc
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。