From 39f01003b4f4b277f34d615734360ac47d9243ff Mon Sep 17 00:00:00 2001
From: Per Lindgren <per.lindgren@ltu.se>
Date: Tue, 13 Feb 2018 10:08:30 +0100
Subject: [PATCH] bare6 v1

---
 examples/bare6.rs | 56 ++++++++++++++++++++++++++++-------------------
 1 file changed, 33 insertions(+), 23 deletions(-)

diff --git a/examples/bare6.rs b/examples/bare6.rs
index 493b814..d855340 100644
--- a/examples/bare6.rs
+++ b/examples/bare6.rs
@@ -5,39 +5,49 @@
 #![feature(use_nested_groups)]
 #![no_std]
 
-extern crate cortex_m;
-extern crate cortex_m_rt;
+extern crate stm32f40x;
 
 #[macro_use]
 extern crate cortex_m_debug;
 
-use cortex_m::{asm::bkpt, peripheral::DWT};
+use stm32f40x::{DWT, GPIOA, RCC};
+
+fn main() {
+    ipln!("init");
+    let dwt = unsafe { &mut *DWT.get() }; // get the reference to DWD in memory
+    let rcc = unsafe { &mut *RCC.get() }; // get the reference to RCC in memory
+    let gpioa = unsafe { &mut *GPIOA.get() }; // get the reference to GPIOA in memory
+
+    dwt.enable_cycle_counter();
+    idle(dwt, rcc, gpioa);
+}
 
 // uses the DWT.CYCNT
 // doc: ARM trm_100166_0001_00_en.pdf, chapter 9.2
 // we use the `cortex-m` abstraction
-fn wait_cycles(nr_cycles: u32) {
-    unsafe {
-        let t = (*DWT.get()).cyccnt.read().wrapping_add(nr_cycles);
-        while ((*DWT.get()).cyccnt.read().wrapping_sub(t) as i32) < 0 {}
-    }
+fn wait_cycles(dwt: &mut DWT, nr_cycles: u32) {
+    let t = dwt.cyccnt.read().wrapping_add(nr_cycles);
+    while (dwt.cyccnt.read().wrapping_sub(t) as i32) < 0 {}
 }
 
-fn main() {
-    unsafe { (*DWT.get()).enable_cycle_counter() };
-    let mut i = 0;
-    loop {
-        ipln!("tick {}", i);
-        wait_cycles(64_000_000);
-        i += 1; // this will eventually cause a panic, when the counter wraps.
-    }
-}
+// user application
+fn idle(dwt: &mut DWT, rcc: &mut RCC, gpioa: &mut GPIOA) {
+    ipln!("idle");
+    // power on GPIOA, RM0368 6.3.11
+    rcc.ahb1enr.modify(|_, w| w.gpioaen().set_bit());
 
-// As we are not using interrupts, we just register a dummy catch all handler
-#[link_section = ".vector_table.interrupts"]
-#[used]
-static INTERRUPTS: [extern "C" fn(); 240] = [default_handler; 240];
+    // configure PA5 as output, RM0368 8.4.1
+    gpioa.moder.modify(|_, w| w.moder5().bits(1));
 
-extern "C" fn default_handler() {
-    cortex_m::asm::bkpt();
+    loop {
+        ipln!("led on");
+        // set PA5 high, RM0368 8.4.7
+        gpioa.bsrr.write(|w| w.bs5().set_bit());
+        wait_cycles(dwt, 10_000);
+
+        ipln!("idle off");
+        // set PA5 low, RM0368 8.4.7
+        gpioa.bsrr.write(|w| w.br5().set_bit());
+        wait_cycles(dwt, 10_000);
+    }
 }
-- 
GitLab