|
| 1 | +//! Start and stop a periodic system timer. |
| 2 | +//! |
| 3 | +//! This example should run on all stm32f4xx boards but it was tested with |
| 4 | +//! stm32f4-discovery board (model STM32F407G-DISC1). |
| 5 | +//! |
| 6 | +//! ```bash |
| 7 | +//! cargo run --release --features stm32f407,rt --example timer-syst |
| 8 | +//! ``` |
| 9 | +
|
| 10 | +#![no_std] |
| 11 | +#![no_main] |
| 12 | + |
| 13 | +extern crate panic_halt; |
| 14 | + |
| 15 | +use cortex_m; |
| 16 | +use cortex_m_rt::entry; |
| 17 | +use cortex_m_semihosting::hprintln; |
| 18 | + |
| 19 | +use embedded_hal::timer::Cancel; |
| 20 | +use hal::timer; |
| 21 | +use hal::timer::Timer; |
| 22 | +use nb; |
| 23 | +use stm32f4xx_hal as hal; |
| 24 | + |
| 25 | +use crate::hal::{prelude::*, stm32}; |
| 26 | + |
| 27 | +#[entry] |
| 28 | +fn main() -> ! { |
| 29 | + let dp = stm32::Peripherals::take().unwrap(); |
| 30 | + let cp = cortex_m::peripheral::Peripherals::take().unwrap(); |
| 31 | + let rcc = dp.RCC.constrain(); |
| 32 | + let clocks = rcc.cfgr.sysclk(24.mhz()).freeze(); |
| 33 | + |
| 34 | + // Create a timer based on SysTick |
| 35 | + let mut timer = Timer::syst(cp.SYST, 24.hz(), clocks); |
| 36 | + |
| 37 | + hprintln!("hello!").unwrap(); |
| 38 | + // wait until timer expires |
| 39 | + nb::block!(timer.wait()).unwrap(); |
| 40 | + hprintln!("timer expired 1").unwrap(); |
| 41 | + |
| 42 | + // the function syst() creates a periodic timer, so it is automatically |
| 43 | + // restarted |
| 44 | + nb::block!(timer.wait()).unwrap(); |
| 45 | + hprintln!("timer expired 2").unwrap(); |
| 46 | + |
| 47 | + // cancel current timer |
| 48 | + timer.cancel().unwrap(); |
| 49 | + |
| 50 | + // start it again |
| 51 | + timer.start(24.hz()); |
| 52 | + nb::block!(timer.wait()).unwrap(); |
| 53 | + hprintln!("timer expired 3").unwrap(); |
| 54 | + |
| 55 | + timer.cancel().unwrap(); |
| 56 | + let cancel_outcome = timer.cancel(); |
| 57 | + assert_eq!(cancel_outcome, Err(timer::Error::Disabled)); |
| 58 | + hprintln!("ehy, you cannot cancel a timer two times!").unwrap(); |
| 59 | + // this time the timer was not restarted, therefore this function should |
| 60 | + // wait forever |
| 61 | + nb::block!(timer.wait()).unwrap(); |
| 62 | + // you should never see this print |
| 63 | + hprintln!("if you see this there is something wrong").unwrap(); |
| 64 | + panic!(); |
| 65 | +} |
0 commit comments