Skip to content

Commit 0c17caa

Browse files
committed
timer: Implement Cancel for Timer
1 parent 31e42e3 commit 0c17caa

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
6060
returned.
6161
- On the bases of these interrupts, the interrupt controller (NVIC) can
6262
be set to mask or unmask these interrupts.
63+
- Implement the `embedded-hal::timer::Cancel` trait for timers. ([#267])
6364

6465
[`enumset`]: https://crates.io/crates/enumset
6566

src/timer.rs

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ use crate::pac::{DCB, DWT};
1313
use enumset::{EnumSet, EnumSetType};
1414
use void::Void;
1515

16-
use crate::hal::timer::{CountDown, Periodic};
17-
use crate::pac::{Interrupt, RCC};
16+
use crate::hal::timer::{Cancel, CountDown, Periodic};
17+
use crate::pac::RCC;
1818
use crate::rcc::{Clocks, APB1, APB2};
1919
use crate::time::{duration, fixed_point::FixedPoint, rate::Hertz};
2020

@@ -275,6 +275,26 @@ where
275275
}
276276
}
277277

278+
/// Error if a [`Cancel`]-ble [`Timer`] was cancled already or never been started.
279+
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
280+
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
281+
pub struct AlreadyCancled;
282+
283+
impl<TIM> Cancel for Timer<TIM>
284+
where
285+
TIM: Instance,
286+
{
287+
type Error = AlreadyCancled;
288+
fn cancel(&mut self) -> Result<(), Self::Error> {
289+
// If timer is already stopped.
290+
if !self.tim.is_cr1_cen_set() {
291+
return Err(AlreadyCancled);
292+
}
293+
self.stop();
294+
Ok(())
295+
}
296+
}
297+
278298
/// Common functionalities of all timer `RegisterBlock` types
279299
/// based on [`crate::pac::tim6::RegisterBlock`].
280300
///
@@ -283,6 +303,8 @@ pub trait CommonRegisterBlock: crate::private::Sealed {
283303
#[doc(hidden)]
284304
fn set_cr1_cen(&mut self, enable: bool);
285305
#[doc(hidden)]
306+
fn is_cr1_cen_set(&mut self) -> bool;
307+
#[doc(hidden)]
286308
fn set_dier_uie(&mut self, enable: bool);
287309
#[doc(hidden)]
288310
fn is_dier_uie_set(&self) -> bool;
@@ -334,6 +356,11 @@ macro_rules! timer {
334356
self.cr1.modify(|_, w| w.cen().bit(enable));
335357
}
336358

359+
#[inline]
360+
fn is_cr1_cen_set(&mut self) -> bool {
361+
self.cr1.read().cen().bit()
362+
}
363+
337364
#[inline]
338365
fn set_dier_uie(&mut self, enable: bool) {
339366
self.dier.modify(|_, w| w.uie().bit(enable));

0 commit comments

Comments
 (0)