Parcourir la source

Implement timer::Cancel trait for CountDownTimer (#261)

Marius Knaust il y a 3 ans
Parent
commit
1d9ec16dc4
2 fichiers modifiés avec 37 ajouts et 1 suppressions
  1. 1 0
      CHANGELOG.md
  2. 36 1
      src/timer.rs

+ 1 - 0
CHANGELOG.md

@@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
 ### Added
 
 - Add 16 bit dataframe size for `SPI`
+- Implement `timer::Cancel` trait for `CountDownTimer`
 
 ### Added
 

+ 36 - 1
src/timer.rs

@@ -47,7 +47,7 @@
   | CH4 |     PB9     |    PD15   |
 */
 
-use crate::hal::timer::{CountDown, Periodic};
+use crate::hal::timer::{Cancel, CountDown, Periodic};
 #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
 use crate::pac::TIM1;
 #[cfg(feature = "medium")]
@@ -83,6 +83,12 @@ pub enum Event {
     Update,
 }
 
+#[derive(Debug, PartialEq)]
+pub enum Error {
+    /// Timer is canceled
+    Canceled,
+}
+
 pub struct Timer<TIM> {
     pub(crate) tim: TIM,
     pub(crate) clk: Hertz,
@@ -255,6 +261,19 @@ impl CountDown for CountDownTimer<SYST> {
     }
 }
 
+impl Cancel for CountDownTimer<SYST> {
+    type Error = Error;
+
+    fn cancel(&mut self) -> Result<(), Self::Error> {
+        if !self.tim.is_counter_enabled() {
+            return Err(Self::Error::Canceled);
+        }
+
+        self.tim.disable_counter();
+        Ok(())
+    }
+}
+
 impl Periodic for CountDownTimer<SYST> {}
 
 macro_rules! hal {
@@ -407,6 +426,22 @@ macro_rules! hal {
                 }
             }
 
+            impl Cancel for CountDownTimer<$TIMX>
+            {
+                type Error = Error;
+
+                fn cancel(&mut self) -> Result<(), Self::Error> {
+                    let is_counter_enabled = self.tim.cr1.read().cen().is_enabled();
+                    if !is_counter_enabled {
+                        return Err(Self::Error::Canceled);
+                    }
+
+                    // disable counter
+                    self.tim.cr1.modify(|_, w| w.cen().clear_bit());
+                    Ok(())
+                }
+            }
+
             impl Periodic for CountDownTimer<$TIMX> {}
         )+
     }