From 7ce7ff2a6d6bd4e4e374046b554082bbae2a9e5e Mon Sep 17 00:00:00 2001 From: Astro Date: Thu, 14 Mar 2019 18:13:25 +0100 Subject: [PATCH] add timer with systick --- src/main.rs | 28 +++++++++++++++++++--------- src/timer.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 9 deletions(-) create mode 100644 src/timer.rs diff --git a/src/main.rs b/src/main.rs index a705107..d288f26 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,6 +25,9 @@ mod adc_input; mod net; mod server; use server::Server; +mod timer; + +const OUTPUT_INTERVAL: u32 = 1000; #[entry] fn main() -> ! { @@ -37,7 +40,7 @@ fn main() -> ! { let dp = Peripherals::take().unwrap(); stm32_eth::setup(&dp.RCC, &dp.SYSCFG); - let _clocks = dp.RCC.constrain() + let clocks = dp.RCC.constrain() .cfgr .sysclk(84.mhz()) .hclk(84.mhz()) @@ -62,20 +65,27 @@ fn main() -> ! { gpioa.pa1, gpioa.pa2, gpioa.pa7, gpiob.pb13, gpioc.pc1, gpioc.pc4, gpioc.pc5, gpiog.pg11, gpiog.pg13 ); + + writeln!(stdout, "Timer setup").unwrap(); + timer::setup(cp.SYST, clocks); + writeln!(stdout, "Net startup").unwrap(); net::run(&mut cp.NVIC, dp.ETHERNET_MAC, dp.ETHERNET_DMA, |net| { let mut server = Server::new(net); - let mut t = 0; + let mut last_output = 0_u32; loop { - t += 100; - let now = Instant::from_millis(t); - server.poll(now); + let now = timer::now().0; + let instant = Instant::from_millis(now as i64); + server.poll(instant); - let adc_value = adc_input::read(); - adc_value.map(|adc_value| { - writeln!(server, "t={},pa3={}", t, adc_value).unwrap(); - }); + if now - last_output >= OUTPUT_INTERVAL { + let adc_value = adc_input::read(); + adc_value.map(|adc_value| { + write!(server, "t={},pa3={}\r\n", now, adc_value).unwrap(); + }); + last_output = now; + } // Update watchdog wd.feed(); diff --git a/src/timer.rs b/src/timer.rs new file mode 100644 index 0000000..99b76a2 --- /dev/null +++ b/src/timer.rs @@ -0,0 +1,37 @@ +use core::cell::RefCell; +use cortex_m::interrupt::Mutex; +use cortex_m_rt::exception; +use stm32f4xx_hal::{ + rcc::Clocks, + time::{U32Ext, MilliSeconds}, + timer::{Timer, Event as TimerEvent}, + stm32::SYST, +}; + +/// rate in Hz +const TIMER_RATE: u32 = 100; +/// interval duration in milliseconds +const TIMER_DELTA: u32 = 1000 / TIMER_RATE; +/// Elapsed time in milliseconds +static TIMER_MS: Mutex> = Mutex::new(RefCell::new(0)); + +pub fn setup(syst: SYST, clocks: Clocks) { + let mut timer = Timer::syst(syst, TIMER_RATE.hz(), clocks); + timer.listen(TimerEvent::TimeOut); +} + +#[exception] +fn SysTick() { + cortex_m::interrupt::free(|cs| { + *TIMER_MS.borrow(cs) + .borrow_mut() += TIMER_DELTA; + }); +} + +pub fn now() -> MilliSeconds { + let ms = cortex_m::interrupt::free(|cs| { + *TIMER_MS.borrow(cs) + .borrow() + }); + ms.ms() +}