Skip to main content

ch32_hal/timer/
low_level.rs

1//! Low-level timer driver.
2
3use super::*;
4use crate::pac::timer::vals;
5use crate::time::Hertz;
6use crate::Peri;
7
8/// Input capture mode.
9#[derive(Clone, Copy)]
10pub enum InputCaptureMode {
11    /// Rising edge only.
12    Rising,
13    /// Falling edge only.
14    Falling,
15    /// Both rising or falling edges.
16    BothEdges,
17}
18
19/// Input TI selection.
20#[derive(Clone, Copy)]
21pub enum InputTISelection {
22    /// Normal
23    Normal,
24    /// Alternate
25    Alternate,
26    /// TRC
27    TRC,
28}
29
30impl From<InputTISelection> for vals::CcmrInputCcs {
31    fn from(tisel: InputTISelection) -> Self {
32        match tisel {
33            InputTISelection::Normal => vals::CcmrInputCcs::TI4,
34            InputTISelection::Alternate => vals::CcmrInputCcs::TI3,
35            InputTISelection::TRC => vals::CcmrInputCcs::TRC,
36        }
37    }
38}
39
40/// Timer counting mode.
41#[repr(u8)]
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub enum CountingMode {
44    #[default]
45    /// The timer counts up to the reload value and then resets back to 0.
46    EdgeAlignedUp,
47    /// The timer counts down to 0 and then resets back to the reload value.
48    EdgeAlignedDown,
49    /// The timer counts up to the reload value and then counts back to 0.
50    ///
51    /// The output compare interrupt flags of channels configured in output are
52    /// set when the counter is counting down.
53    CenterAlignedDownInterrupts,
54    /// The timer counts up to the reload value and then counts back to 0.
55    ///
56    /// The output compare interrupt flags of channels configured in output are
57    /// set when the counter is counting up.
58    CenterAlignedUpInterrupts,
59    /// The timer counts up to the reload value and then counts back to 0.
60    ///
61    /// The output compare interrupt flags of channels configured in output are
62    /// set when the counter is counting both up or down.
63    CenterAlignedBothInterrupts,
64}
65
66impl CountingMode {
67    /// Return whether this mode is edge-aligned (up or down).
68    pub fn is_edge_aligned(&self) -> bool {
69        matches!(self, CountingMode::EdgeAlignedUp | CountingMode::EdgeAlignedDown)
70    }
71
72    /// Return whether this mode is center-aligned.
73    pub fn is_center_aligned(&self) -> bool {
74        matches!(
75            self,
76            CountingMode::CenterAlignedDownInterrupts
77                | CountingMode::CenterAlignedUpInterrupts
78                | CountingMode::CenterAlignedBothInterrupts
79        )
80    }
81}
82
83impl From<CountingMode> for (vals::Cms, vals::Dir) {
84    fn from(value: CountingMode) -> Self {
85        match value {
86            CountingMode::EdgeAlignedUp => (vals::Cms::EDGEALIGNED, vals::Dir::UP),
87            CountingMode::EdgeAlignedDown => (vals::Cms::EDGEALIGNED, vals::Dir::DOWN),
88            CountingMode::CenterAlignedDownInterrupts => (vals::Cms::CENTERALIGNED1, vals::Dir::UP),
89            CountingMode::CenterAlignedUpInterrupts => (vals::Cms::CENTERALIGNED2, vals::Dir::UP),
90            CountingMode::CenterAlignedBothInterrupts => (vals::Cms::CENTERALIGNED3, vals::Dir::UP),
91        }
92    }
93}
94
95impl From<(vals::Cms, vals::Dir)> for CountingMode {
96    fn from(value: (vals::Cms, vals::Dir)) -> Self {
97        match value {
98            (vals::Cms::EDGEALIGNED, vals::Dir::UP) => CountingMode::EdgeAlignedUp,
99            (vals::Cms::EDGEALIGNED, vals::Dir::DOWN) => CountingMode::EdgeAlignedDown,
100            (vals::Cms::CENTERALIGNED1, _) => CountingMode::CenterAlignedDownInterrupts,
101            (vals::Cms::CENTERALIGNED2, _) => CountingMode::CenterAlignedUpInterrupts,
102            (vals::Cms::CENTERALIGNED3, _) => CountingMode::CenterAlignedBothInterrupts,
103        }
104    }
105}
106
107/// Output compare mode.
108#[derive(Clone, Copy)]
109pub enum OutputCompareMode {
110    /// The comparison between the output compare register TIMx_CCRx and
111    /// the counter TIMx_CNT has no effect on the outputs.
112    /// (this mode is used to generate a timing base).
113    Frozen,
114    /// Set channel to active level on match. OCxREF signal is forced high when the
115    /// counter TIMx_CNT matches the capture/compare register x (TIMx_CCRx).
116    ActiveOnMatch,
117    /// Set channel to inactive level on match. OCxREF signal is forced low when the
118    /// counter TIMx_CNT matches the capture/compare register x (TIMx_CCRx).
119    InactiveOnMatch,
120    /// Toggle - OCxREF toggles when TIMx_CNT=TIMx_CCRx.
121    Toggle,
122    /// Force inactive level - OCxREF is forced low.
123    ForceInactive,
124    /// Force active level - OCxREF is forced high.
125    ForceActive,
126    /// PWM mode 1 - In upcounting, channel is active as long as TIMx_CNT<TIMx_CCRx
127    /// else inactive. In downcounting, channel is inactive (OCxREF=0) as long as
128    /// TIMx_CNT>TIMx_CCRx else active (OCxREF=1).
129    PwmMode1,
130    /// PWM mode 2 - In upcounting, channel is inactive as long as
131    /// TIMx_CNT<TIMx_CCRx else active. In downcounting, channel is active as long as
132    /// TIMx_CNT>TIMx_CCRx else inactive.
133    PwmMode2,
134    // TODO: there's more modes here depending on the chip family.
135}
136
137impl From<OutputCompareMode> for vals::Ocm {
138    fn from(mode: OutputCompareMode) -> Self {
139        match mode {
140            OutputCompareMode::Frozen => vals::Ocm::FROZEN,
141            OutputCompareMode::ActiveOnMatch => vals::Ocm::ACTIVEONMATCH,
142            OutputCompareMode::InactiveOnMatch => vals::Ocm::INACTIVEONMATCH,
143            OutputCompareMode::Toggle => vals::Ocm::TOGGLE,
144            OutputCompareMode::ForceInactive => vals::Ocm::FORCEINACTIVE,
145            OutputCompareMode::ForceActive => vals::Ocm::FORCEACTIVE,
146            OutputCompareMode::PwmMode1 => vals::Ocm::PWMMODE1,
147            OutputCompareMode::PwmMode2 => vals::Ocm::PWMMODE2,
148        }
149    }
150}
151
152/// Timer output pin polarity.
153#[derive(Clone, Copy)]
154pub enum OutputPolarity {
155    /// Active high (higher duty value makes the pin spend more time high).
156    ActiveHigh,
157    /// Active low (higher duty value makes the pin spend more time low).
158    ActiveLow,
159}
160
161impl From<OutputPolarity> for bool {
162    fn from(mode: OutputPolarity) -> Self {
163        match mode {
164            OutputPolarity::ActiveHigh => false,
165            OutputPolarity::ActiveLow => true,
166        }
167    }
168}
169
170fn period_registers(clock: u32, frequency: u32, bits: u32, center_aligned: bool, pwm: bool) -> (u16, u32) {
171    assert!(frequency > 0);
172    let ticks = u64::from(clock) / (u64::from(frequency) * if center_aligned { 2 } else { 1 });
173    assert!(ticks > 0);
174    let max_ticks = (1u64 << bits) - u64::from(center_aligned || pwm);
175    let prescaler = (ticks - 1) / max_ticks;
176    let prescaler = u16::try_from(prescaler).unwrap();
177    let period = ticks / (u64::from(prescaler) + 1);
178    let reload = period - u64::from(!center_aligned);
179    (prescaler, u32::try_from(reload).unwrap())
180}
181
182/// Low-level timer driver.
183pub struct Timer<'d, T: CoreInstance> {
184    tim: Peri<'d, T>,
185}
186
187impl<'d, T: CoreInstance> Drop for Timer<'d, T> {
188    fn drop(&mut self) {
189        T::disable()
190    }
191}
192
193impl<'d, T: CoreInstance> Timer<'d, T> {
194    /// Create a new timer driver.
195    pub fn new(tim: Peri<'d, T>) -> Self {
196        T::enable_and_reset();
197
198        Self { tim }
199    }
200
201    #[cfg(any(ch32l1, ch32v203, ch32v208, ch32h4))]
202    fn regs_gp32_unchecked(&self) -> crate::pac::timer::Gptm32 {
203        unsafe { crate::pac::timer::Gptm32::from_ptr(T::regs()) }
204    }
205}
206
207impl<'d, T: BasicInstance> Timer<'d, T> {
208    /// Get access to the Baisc 16bit timer registers.
209    ///
210    /// Note: This works even if the timer is more capable, because registers
211    /// for the less capable timers are a subset. This allows writing a driver
212    /// for a given set of capabilities, and having it transparently work with
213    /// more capable timers.
214    pub fn regs_basic(&self) -> crate::pac::timer::Bctm {
215        unsafe { crate::pac::timer::Bctm::from_ptr(T::regs()) }
216    }
217
218    /// Start the timer.
219    pub fn start(&self) {
220        self.regs_basic().ctlr1().modify(|r| r.set_cen(true));
221    }
222
223    /// Stop the timer.
224    pub fn stop(&self) {
225        self.regs_basic().ctlr1().modify(|r| r.set_cen(false));
226    }
227
228    /// Reset the counter value to 0
229    pub fn reset(&self) {
230        self.regs_basic().cnt().write_value(0);
231    }
232
233    /// Set the frequency of how many times per second the timer counts up to the max value or down to 0.
234    ///
235    /// This means that in the default edge-aligned mode,
236    /// the timer counter will wrap around at the same frequency as is being set.
237    /// In center-aligned mode (which not all timers support), the wrap-around frequency is effectively halved
238    /// because it needs to count up and down.
239    pub fn set_frequency(&self, frequency: Hertz) {
240        self.set_frequency_inner(frequency, false, false);
241    }
242
243    fn set_frequency_inner(&self, frequency: Hertz, center_aligned: bool, pwm: bool) {
244        let bits = match T::BITS {
245            TimerBits::Bits16 => 16,
246            #[cfg(any(ch32l1, ch32v203, ch32v208, ch32h4))]
247            TimerBits::Bits32 => 32,
248        };
249        let (psc, arr) = period_registers(T::frequency().0, frequency.0, bits, center_aligned, pwm);
250
251        match T::BITS {
252            TimerBits::Bits16 => {
253                let regs = self.regs_basic();
254                regs.psc().write_value(psc);
255                regs.atrlr().write_value(arr as u16);
256            }
257            #[cfg(any(ch32l1, ch32v203, ch32v208, ch32h4))]
258            TimerBits::Bits32 => {
259                let regs = self.regs_gp32_unchecked();
260                regs.psc().write_value(psc);
261                regs.atrlr().write_value(arr);
262            }
263        }
264        let regs = self.regs_basic();
265        let previous_urs = regs.ctlr1().read().urs();
266        regs.ctlr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY));
267        regs.swevgr().write(|r| r.set_ug(true));
268        regs.ctlr1().modify(|r| r.set_urs(previous_urs));
269    }
270
271    /// Clear update interrupt.
272    ///
273    /// Returns whether the update interrupt flag was set.
274    pub fn clear_update_interrupt(&self) -> bool {
275        let regs = self.regs_basic();
276        let intfr = regs.intfr().read();
277        if intfr.uif() {
278            regs.intfr().write_value(crate::pac::timer::regs::Intfr(0xfffe));
279            true
280        } else {
281            false
282        }
283    }
284
285    /// Enable/disable the update interrupt.
286    pub fn enable_update_interrupt(&self, enable: bool) {
287        self.regs_basic().dmaintenr().modify(|r| r.set_uie(enable));
288    }
289
290    /// Enable/disable autoreload preload.
291    pub fn set_autoreload_preload(&self, enable: bool) {
292        self.regs_basic().ctlr1().modify(|r| r.set_arpe(enable));
293    }
294
295    /// Get the timer frequency.
296    pub fn get_frequency(&self) -> Hertz {
297        let timer_f = T::frequency();
298
299        match T::BITS {
300            TimerBits::Bits16 => {
301                let regs = self.regs_basic();
302                let arr = u64::from(regs.atrlr().read()) + 1;
303                let psc = u64::from(regs.psc().read()) + 1;
304
305                Hertz((u64::from(timer_f.0) / (arr * psc)) as u32)
306            }
307            #[cfg(any(ch32l1, ch32v203, ch32v208, ch32h4))]
308            TimerBits::Bits32 => {
309                let regs = self.regs_gp32_unchecked();
310                let arr = u64::from(regs.atrlr().read()) + 1;
311                let psc = u64::from(regs.psc().read()) + 1;
312
313                Hertz((u64::from(timer_f.0) / (arr * psc)) as u32)
314            }
315        }
316    }
317
318    /// Enable/disable the update dma.
319    #[cfg(not(timer_x0))] // GPTM_2CH
320    pub fn enable_update_dma(&self, enable: bool) {
321        self.regs_basic().dmaintenr().modify(|r| r.set_ude(enable));
322    }
323
324    /// Get the update dma enable/disable state.
325    #[cfg(not(timer_x0))] // GPTM_2CH
326    pub fn get_update_dma_state(&self) -> bool {
327        self.regs_basic().dmaintenr().read().ude()
328    }
329}
330
331impl<'d, T: GeneralInstance16bit> Timer<'d, T> {
332    pub(crate) fn set_pwm_frequency(&self, frequency: Hertz) {
333        self.set_frequency_inner(frequency, self.get_counting_mode().is_center_aligned(), true);
334    }
335
336    pub(crate) fn get_max_pwm_duty(&self) -> u32 {
337        self.get_max_compare_value() + u32::from(!self.get_counting_mode().is_center_aligned())
338    }
339
340    /// Get access to the general purpose 16bit timer registers.
341    ///
342    /// Note: This works even if the timer is more capable, because registers
343    /// for the less capable timers are a subset. This allows writing a driver
344    /// for a given set of capabilities, and having it transparently work with
345    /// more capable timers.
346    pub fn regs_gp16(&self) -> crate::pac::timer::Gptm {
347        unsafe { crate::pac::timer::Gptm::from_ptr(T::regs()) }
348    }
349
350    /// Set clock divider.
351    pub fn set_clock_division(&self, ckd: vals::Ckd) {
352        self.regs_gp16().ctlr1().modify(|r| r.set_ckd(ckd));
353    }
354
355    /// Get max compare value. This depends on the timer frequency and the clock frequency from RCC.
356    pub fn get_max_compare_value(&self) -> u32 {
357        match T::BITS {
358            TimerBits::Bits16 => self.regs_gp16().atrlr().read() as u32,
359            #[cfg(any(ch32l1, ch32v203, ch32v208, ch32h4))]
360            TimerBits::Bits32 => self.regs_gp32_unchecked().atrlr().read(),
361        }
362    }
363
364    // /// Enable timer outputs.
365    // pub fn enable_outputs(&self) {
366    //    unsafe { crate::pac::timer::Gptm::from_ptr(T::regs()) }
367    //       .bdtr()
368    //      .modify(|w| w.set_moe(true));
369    // }
370
371    /// Set counting mode.
372    #[cfg(not(timer_x0))]
373    pub fn set_counting_mode(&self, mode: CountingMode) {
374        let (cms, dir) = mode.into();
375
376        let timer_enabled = self.regs_basic().ctlr1().read().cen();
377        // Changing from edge aligned to center aligned (and vice versa) is not allowed while the timer is running.
378        // Changing direction is discouraged while the timer is running.
379        assert!(!timer_enabled);
380
381        self.regs_gp16().ctlr1().modify(|r| r.set_dir(dir));
382        self.regs_gp16().ctlr1().modify(|r| r.set_cms(cms))
383    }
384
385    /// Get counting mode.
386    pub fn get_counting_mode(&self) -> CountingMode {
387        self.tim.get_counting_mode()
388    }
389
390    /// Set input capture filter.
391    pub fn set_input_capture_filter(&self, channel: Channel, icf: vals::FilterValue) {
392        let raw_channel = channel.index();
393        self.regs_gp16()
394            .chctlr_input(raw_channel / 2)
395            .modify(|r| r.set_icf(raw_channel % 2, icf));
396    }
397
398    /// Clear input interrupt.
399    pub fn clear_input_interrupt(&self, channel: Channel) {
400        self.regs_gp16()
401            .intfr()
402            .write_value(crate::pac::timer::regs::Intfr(0xffff & !(1 << (channel.index() + 1))));
403    }
404
405    /// Enable input interrupt.
406    pub fn enable_input_interrupt(&self, channel: Channel, enable: bool) {
407        self.regs_gp16()
408            .dmaintenr()
409            .modify(|r| r.set_ccie(channel.index(), enable));
410    }
411
412    /// Set input capture prescaler.
413    pub fn set_input_capture_prescaler(&self, channel: Channel, factor: u8) {
414        let raw_channel = channel.index();
415        self.regs_gp16()
416            .chctlr_input(raw_channel / 2)
417            .modify(|r| r.set_icpsc(raw_channel % 2, factor));
418    }
419
420    /// Set input TI selection.
421    pub fn set_input_ti_selection(&self, channel: Channel, tisel: InputTISelection) {
422        let raw_channel = channel.index();
423        self.regs_gp16()
424            .chctlr_input(raw_channel / 2)
425            .modify(|r| r.set_ccs(raw_channel % 2, tisel.into()));
426    }
427
428    /// Set input capture mode.
429    // CCNP and CCNE is not available in GPTM
430    #[cfg(not(timer_x0))]
431    pub fn set_input_capture_mode(&self, channel: Channel, mode: InputCaptureMode) {
432        self.regs_gp16().ccer().modify(|r| match mode {
433            InputCaptureMode::Rising => {
434                r.set_ccnp(channel.index(), false);
435                r.set_ccp(channel.index(), false);
436            }
437            InputCaptureMode::Falling => {
438                r.set_ccnp(channel.index(), false);
439                r.set_ccp(channel.index(), true);
440            }
441            InputCaptureMode::BothEdges => {
442                r.set_ccnp(channel.index(), true);
443                r.set_ccp(channel.index(), true);
444            }
445        });
446    }
447
448    /// Set output compare mode.
449    pub fn set_output_compare_mode(&self, channel: Channel, mode: OutputCompareMode) {
450        let raw_channel: usize = channel.index();
451        self.regs_gp16()
452            .chctlr_output(raw_channel / 2)
453            .modify(|w| w.set_ocm(raw_channel % 2, mode.into()));
454    }
455
456    /// Set output polarity.
457    pub fn set_output_polarity(&self, channel: Channel, polarity: OutputPolarity) {
458        self.regs_gp16()
459            .ccer()
460            .modify(|w| w.set_ccp(channel.index(), polarity.into()));
461    }
462
463    /// Enable/disable a channel.
464    pub fn enable_channel(&self, channel: Channel, enable: bool) {
465        self.regs_gp16().ccer().modify(|w| w.set_cce(channel.index(), enable));
466    }
467
468    /// Get enable/disable state of a channel
469    pub fn get_channel_enable_state(&self, channel: Channel) -> bool {
470        self.regs_gp16().ccer().read().cce(channel.index())
471    }
472
473    /// Set compare value for a channel.
474    pub fn set_compare_value(&self, channel: Channel, value: u32) {
475        match T::BITS {
476            TimerBits::Bits16 => {
477                let value = (u16::try_from(value)).unwrap();
478                self.regs_gp16().chcvr(channel.index()).write_value(value);
479            }
480            #[cfg(any(ch32l1, ch32v203, ch32v208, ch32h4))]
481            TimerBits::Bits32 => {
482                self.regs_gp32_unchecked().chcvr(channel.index()).write_value(value);
483            }
484        }
485    }
486
487    /// Get compare value for a channel.
488    pub fn get_compare_value(&self, channel: Channel) -> u32 {
489        match T::BITS {
490            TimerBits::Bits16 => self.regs_gp16().chcvr(channel.index()).read() as u32,
491            #[cfg(any(ch32l1, ch32v203, ch32v208, ch32h4))]
492            TimerBits::Bits32 => self.regs_gp32_unchecked().chcvr(channel.index()).read(),
493        }
494    }
495
496    /// Get capture value for a channel.
497    pub fn get_capture_value(&self, channel: Channel) -> u32 {
498        self.get_compare_value(channel)
499    }
500
501    /// Set output compare preload.
502    pub fn set_output_compare_preload(&self, channel: Channel, preload: bool) {
503        let channel_index = channel.index();
504        self.regs_gp16()
505            .chctlr_output(channel_index / 2)
506            .modify(|w| w.set_ocpe(channel_index % 2, preload));
507    }
508
509    /// Enable timer outputs.
510    pub fn enable_outputs(&self) {
511        self.tim.enable_outputs()
512    }
513
514    // The following is not available in GPTM_2CH
515
516    /// Get capture compare DMA selection
517    #[cfg(not(timer_x0))] // no CTLR2
518    pub fn get_cc_dma_selection(&self) -> vals::Ccds {
519        self.regs_gp16().ctlr2().read().ccds()
520    }
521
522    /// Set capture compare DMA selection
523    #[cfg(not(timer_x0))] // no CTLR2
524    pub fn set_cc_dma_selection(&self, ccds: vals::Ccds) {
525        self.regs_gp16().ctlr2().modify(|w| w.set_ccds(ccds))
526    }
527
528    /// Get capture compare DMA enable state
529    #[cfg(not(timer_x0))]
530    pub fn get_cc_dma_enable_state(&self, channel: Channel) -> bool {
531        self.regs_gp16().dmaintenr().read().ccde(channel.index())
532    }
533
534    /// Set capture compare DMA enable state
535    #[cfg(not(timer_x0))]
536    pub fn set_cc_dma_enable_state(&self, channel: Channel, ccde: bool) {
537        self.regs_gp16()
538            .dmaintenr()
539            .modify(|w| w.set_ccde(channel.index(), ccde))
540    }
541}
542
543impl<'d, T: AdvancedInstance> Timer<'d, T> {
544    /// Get access to the advanced timer registers.
545    pub fn regs_advanced(&self) -> crate::pac::timer::Adtm {
546        unsafe { crate::pac::timer::Adtm::from_ptr(T::regs()) }
547    }
548
549    /// Set clock divider for the dead time.
550    pub fn set_dead_time_clock_division(&self, value: vals::Ckd) {
551        self.regs_advanced().ctlr1().modify(|w| w.set_ckd(value));
552    }
553
554    /// Set dead time, as a fraction of the max duty value.
555    pub fn set_dead_time_value(&self, value: u8) {
556        self.regs_advanced().bdtr().modify(|w| w.set_dtg(value));
557    }
558
559    /// Set state of MOE-bit in BDTR register to en-/disable output
560    pub fn set_moe(&self, enable: bool) {
561        self.regs_advanced().bdtr().modify(|w| w.set_moe(enable));
562    }
563
564    /// Set complementary output polarity.
565    pub fn set_complementary_output_polarity(&self, channel: Channel, polarity: OutputPolarity) {
566        self.regs_advanced()
567            .ccer()
568            .modify(|w| w.set_ccnp(channel.index(), polarity.into()));
569    }
570
571    /// Enable/disable a complementary channel.
572    pub fn enable_complementary_channel(&self, channel: Channel, enable: bool) {
573        self.regs_advanced()
574            .ccer()
575            .modify(|w| w.set_ccne(channel.index(), enable));
576    }
577}
578
579// GPTM 2CH does not have these features
580#[cfg(timer_x0)]
581impl<'d, T: AdvancedInstance> Timer<'d, T> {
582    pub fn get_cc_dma_selection(&self) -> vals::Ccds {
583        self.regs_advanced().ctlr2().read().ccds()
584    }
585
586    /// Set capture compare DMA selection
587    pub fn set_cc_dma_selection(&self, ccds: vals::Ccds) {
588        self.regs_advanced().ctlr2().modify(|w| w.set_ccds(ccds))
589    }
590
591    /// Get capture compare DMA enable state
592    pub fn get_cc_dma_enable_state(&self, channel: Channel) -> bool {
593        self.regs_advanced().dmaintenr().read().ccde(channel.index())
594    }
595
596    /// Set capture compare DMA enable state
597    pub fn set_cc_dma_enable_state(&self, channel: Channel, ccde: bool) {
598        self.regs_advanced()
599            .dmaintenr()
600            .modify(|w| w.set_ccde(channel.index(), ccde))
601    }
602
603    pub fn set_input_capture_mode(&self, channel: Channel, mode: InputCaptureMode) {
604        self.regs_advanced().ccer().modify(|r| match mode {
605            InputCaptureMode::Rising => {
606                r.set_ccnp(channel.index(), false);
607                r.set_ccp(channel.index(), false);
608            }
609            InputCaptureMode::Falling => {
610                r.set_ccnp(channel.index(), false);
611                r.set_ccp(channel.index(), true);
612            }
613            InputCaptureMode::BothEdges => {
614                r.set_ccnp(channel.index(), true);
615                r.set_ccp(channel.index(), true);
616            }
617        });
618    }
619
620    pub fn set_counting_mode(&self, mode: CountingMode) {
621        let (cms, dir) = mode.into();
622
623        let timer_enabled = self.regs_basic().ctlr1().read().cen();
624        // Changing from edge aligned to center aligned (and vice versa) is not allowed while the timer is running.
625        // Changing direction is discouraged while the timer is running.
626        assert!(!timer_enabled);
627
628        self.regs_advanced().ctlr1().modify(|r| r.set_dir(dir));
629        self.regs_advanced().ctlr1().modify(|r| r.set_cms(cms))
630    }
631
632    pub fn enable_update_dma(&self, enable: bool) {
633        self.regs_advanced().dmaintenr().modify(|r| r.set_ude(enable));
634    }
635
636    /// Get the update dma enable/disable state.
637    pub fn get_update_dma_state(&self) -> bool {
638        self.regs_advanced().dmaintenr().read().ude()
639    }
640}