Skip to content

Instantly share code, notes, and snippets.

@circuit4u-medium
Last active October 11, 2021 23:45
Show Gist options
  • Save circuit4u-medium/a5048cae351c7827f90e47cf32a3b4bb to your computer and use it in GitHub Desktop.
Save circuit4u-medium/a5048cae351c7827f90e47cf32a3b4bb to your computer and use it in GitHub Desktop.
bare metal rust code for STM32F103
#![no_std]
#![no_main]
use panic_rtt_target as _;
use cortex_m_rt::entry;
use core::ptr;
#[entry]
fn main() -> ! {
// Set up named variables for the register addresses we'll use. These are defined in the STM32's
// reference manual (RM): rm0008. You can find base addresses under the Memory and bus architecture chapter, and the offsets (Things we | the base addresses with), under the RCC and GPIO chapters, registers sections.
let RCC_AHB2ENR = 0x4002_1000 | 0x18;
let GPIOC_BASE = 0x4001_1000;
// You can find these offsets under each RM register table: `Address Offset`
let GPIOC_CRH = GPIOC_BASE | 0x04;
let GPIOC_BSRR = GPIOC_BASE | 0x10;
let gpiocen_field = 4;
let output_pin_num = 13; // A variable to indicate with GPIO pin number we're using. Ie PC13
unsafe {
// Set the GPIOCEN field of the RCC register block, AHB2_ENR register. This enables the peripheral clock
// to all pins on the GPIOC port.
ptr::write_volatile(RCC_AHB2ENR as *mut u32, 1 << gpiocen_field);
// Set the mode of PC13 to Output, The hex values 0b01 is defined in the GPIO registers section of the RM
// We Multiply the pin numbers by 4, since each field of this register is 4 bits wide. Also note that we perform a register read, as not to override previous settings.
let mut existing_val = ptr::read_volatile(GPIOC_CRH as *const u32);
// We use binary arithmetic here to 0 out the fields we’ll write to. Modifying single-bit fields is simpler.
existing_val = existing_val & !(0b1111 << ((output_pin_num -8) * 4) ); //-8 being the offset for CRH register
ptr::write_volatile(
GPIOC_CRH as *mut u32,
existing_val | (0b0001 << ((output_pin_num -8) * 4) ) // output mode @ 10MHz max speed; general purpose push-pull
);
// check schematic for this bit inverse
// light up LED; RESET PC13 (0V)
ptr::write_volatile(GPIOC_BSRR as *mut u32, 1 << (output_pin_num + 16));
// turn off LED; SET PC13 (3.3V)
//ptr::write_volatile(GPIOC_BSRR as *mut u32, 1 << (output_pin_num));
}
loop {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment