基于STM32的寄存器实现点亮LED--基于RUST实现
main.rs
#![no_std] #![no_main] use core::ptr; use cortex_m_rt::entry; use panic_halt as _; // 当发生 panic 时停止执行 // 定义寄存器地址 const RCC_BASE: u32 = 0x40021000; const GPIOB_BASE: u32 = 0x40010C00; const RCC_APB2ENR_OFFSET: u32 = 0x18; const GPIOB_CRL_OFFSET: u32 = 0x00; const GPIOB_ODR_OFFSET: u32 = 0x0C; #[entry] fn main() -> ! { // 开启 GPIOB 时钟 unsafe { let rcc_apb2enr = (RCC_BASE + RCC_APB2ENR_OFFSET) as *mut u32; ptr::write_volatile(rcc_apb2enr, ptr::read_volatile(rcc_apb2enr) | (1 << 3)); } // 配置 PB5 为推挽输出模式,2MHz unsafe { let gpio_crl = (GPIOB_BASE + GPIOB_CRL_OFFSET) as *mut u32; // 清除 PB5 的模式和配置位 ptr::write_volatile(gpio_crl, ptr::read_volatile(gpio_crl) & !(0b1111 << (4 * 5))); // 设置 PB5 为推挽输出,模式为 2MHz ptr::write_volatile(gpio_crl, ptr::read_volatile(gpio_crl) | (0b0010 << (4 * 5))); } // 设置 PB5 低电平(点亮 LED) unsafe { let gpio_odr = (GPIOB_BASE + GPIOB_ODR_OFFSET) as *mut u32; ptr::write_volatile(gpio_odr, ptr::read_volatile(gpio_odr) & !(1 << 5)); } // 无限循环,防止程序结束 loop {} }
完整的项目源码地址
https://gitee.com/navysummer/stm32-rust-demo/tree/master/reg_led