Skip to main content

ch32_hal/timer/
mod.rs

1//! Timers, PWM.
2//!
3//! Instance type:
4//!
5//! - BasicInstance
6//! - GeneralInstance (16-bit or 32-bit)
7//! - AdvancedInstance
8//!
9//! Different vs embassy-stm32:
10//!
11//! - No too many levels of abstraction
12//! - 2CH GPTM instances are also have helper functions defined
13
14use crate::peripheral::RccPeripheral;
15use crate::interrupt;
16
17pub mod complementary_pwm;
18pub mod low_level;
19pub mod simple_pwm;
20
21/// Timer channel.
22#[derive(Clone, Copy, PartialEq)]
23pub enum Channel {
24    /// Channel 1.
25    Ch1,
26    /// Channel 2.
27    Ch2,
28    /// Channel 3.
29    Ch3,
30    /// Channel 4.
31    Ch4,
32}
33
34impl Channel {
35    /// Get the channel index (0..3)
36    pub fn index(&self) -> usize {
37        match self {
38            Channel::Ch1 => 0,
39            Channel::Ch2 => 1,
40            Channel::Ch3 => 2,
41            Channel::Ch4 => 3,
42        }
43    }
44}
45
46/// Amount of bits of a timer.
47#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48#[cfg_attr(feature = "defmt", derive(defmt::Format))]
49pub enum TimerBits {
50    /// 16 bits.
51    Bits16,
52    /// 32 bits.
53    #[cfg(any(ch32l1, ch32v203, ch32v208, ch32h4))]
54    Bits32,
55}
56
57/// Core timer instance.
58#[allow(private_bounds)]
59pub trait CoreInstance: RccPeripheral + crate::peripheral::RemapBound + embassy_hal_internal::PeripheralType + 'static {
60    /// Update Interrupt for this timer.
61    type UpdateInterrupt: interrupt::typelevel::Interrupt;
62
63    /// Amount of bits this timer has.
64    const BITS: TimerBits;
65
66    /// Registers for this timer.
67    ///
68    /// This is a raw pointer to the register block. The actual register block layout varies depending on the timer type.
69    fn regs() -> *mut ();
70}
71
72/// Basic timer instance, BCTM
73pub trait BasicInstance: CoreInstance {}
74
75trait SealedGeneralInstance: BasicInstance {
76    fn enable_outputs(&self) {}
77
78    fn get_counting_mode(&self) -> low_level::CountingMode {
79        // (vals::Cms::EDGEALIGNED, vals::Dir::UP),
80        low_level::CountingMode::EdgeAlignedUp
81    }
82}
83
84/// General-purpose 16-bit timer with 4 channels instance.
85#[allow(private_bounds)]
86pub trait GeneralInstance16bit: SealedGeneralInstance {
87    /// Capture compare interrupt for this timer.
88    type CaptureCompareInterrupt: interrupt::typelevel::Interrupt;
89
90    /// Trigger event interrupt for this timer.
91    type TriggerInterrupt: interrupt::typelevel::Interrupt;
92}
93
94/// General-purpose 32-bit timer with 4 channels instance.
95pub trait GeneralInstance32bit: GeneralInstance16bit {}
96
97/// Advanced 16-bit timer with 4 channels instance.
98pub trait AdvancedInstance: GeneralInstance16bit {
99    /// Communication interrupt for this timer.
100    type CommunicationInterrupt: interrupt::typelevel::Interrupt;
101    /// Break input interrupt for this timer.
102    type BreakInputInterrupt: interrupt::typelevel::Interrupt;
103}
104
105pin_trait!(Channel1Pin, GeneralInstance16bit);
106pin_trait!(Channel2Pin, GeneralInstance16bit);
107pin_trait!(Channel3Pin, GeneralInstance16bit);
108pin_trait!(Channel4Pin, GeneralInstance16bit);
109pin_trait!(ExternalTriggerPin, GeneralInstance16bit);
110
111pin_trait!(Channel1ComplementaryPin, AdvancedInstance);
112pin_trait!(Channel2ComplementaryPin, AdvancedInstance);
113pin_trait!(Channel3ComplementaryPin, AdvancedInstance);
114// No Channel4ComplementaryPin for ADTM
115// pin_trait!(Channel4ComplementaryPin, AdvancedInstance);
116
117pin_trait!(BreakInputPin, AdvancedInstance);
118
119// Update Event trigger DMA for every timer
120dma_trait!(UpDma, BasicInstance);
121
122dma_trait!(Ch1Dma, GeneralInstance16bit);
123dma_trait!(Ch2Dma, GeneralInstance16bit);
124dma_trait!(Ch3Dma, GeneralInstance16bit);
125dma_trait!(Ch4Dma, GeneralInstance16bit);
126
127// Each macro takes the interrupt-signal *names* (UP / CC / TRG / COM /
128// BRK / GLOBAL / TRG_COM) as extra idents so the same body works for
129// V0/V1/V2/V3/X0 (per-event signals) and H4 (merged GLOBAL or TRG_COM
130// signals). The calling `foreach_interrupt!` arm already knows which
131// signal each TIM provides, so it just forwards the right name.
132
133#[allow(unused)]
134macro_rules! impl_core_timer {
135    ($inst:ident, $bits:expr, $update:ident) => {
136        impl CoreInstance for crate::peripherals::$inst {
137            type UpdateInterrupt = crate::_generated::peripheral_interrupts::$inst::$update;
138
139            const BITS: TimerBits = $bits;
140
141            fn regs() -> *mut () {
142                crate::pac::$inst.as_ptr()
143            }
144        }
145    };
146}
147
148#[allow(unused)]
149macro_rules! impl_general_16bit {
150    ($inst:ident, $cc:ident, $trg:ident) => {
151        impl GeneralInstance16bit for crate::peripherals::$inst {
152            type CaptureCompareInterrupt = crate::_generated::peripheral_interrupts::$inst::$cc;
153            type TriggerInterrupt = crate::_generated::peripheral_interrupts::$inst::$trg;
154        }
155    };
156}
157
158#[allow(unused)]
159macro_rules! impl_advanced {
160    ($inst:ident, $com:ident, $brk:ident) => {
161        impl AdvancedInstance for crate::peripherals::$inst {
162            type CommunicationInterrupt = crate::_generated::peripheral_interrupts::$inst::$com;
163            type BreakInputInterrupt = crate::_generated::peripheral_interrupts::$inst::$brk;
164        }
165    };
166}
167
168// H4 collapses GPTM / GPTM32 / BCTM IRQs into a single `GLOBAL` signal
169// (no separate UP / CC / TRG entries in metadata); earlier families
170// keep them as `UP`. ADTM still uses `UP` on both — it has separate
171// BRK/UP/TRG_COM/CC vectors on H4 too. Below, the BCTM/GPTM/GPTM32
172// arms are duplicated under cfg gates because `foreach_interrupt!`
173// doesn't accept per-arm attributes.
174
175#[cfg(not(timer_h4))]
176foreach_interrupt! {
177    ($inst:ident, timer, BCTM, UP, $irq:ident) => {
178        impl_core_timer!($inst, TimerBits::Bits16, UP);
179        impl BasicInstance for crate::peripherals::$inst {}
180    };
181
182    ($inst:ident, timer, ADTM, UP, $irq:ident) => {
183        impl_core_timer!($inst, TimerBits::Bits16, UP);
184        impl BasicInstance for crate::peripherals::$inst {}
185        impl SealedGeneralInstance for crate::peripherals::$inst {
186            fn enable_outputs(&self) {
187                unsafe { crate::pac::timer::Adtm::from_ptr(Self::regs()) }
188                    .bdtr()
189                    .modify(|w| w.set_moe(true));
190            }
191            fn get_counting_mode(&self) -> low_level::CountingMode {
192                let regs = unsafe { crate::pac::timer::Adtm::from_ptr(Self::regs()) };
193                let cr1 = regs.ctlr1().read();
194                (cr1.cms(), cr1.dir()).into()
195            }
196        }
197        impl_general_16bit!($inst, CC, TRG);
198        impl_advanced!($inst, COM, BRK);
199    };
200}
201
202// On H4, ADTM still has separate BRK/UP/TRG_COM/CC vectors (V3-style).
203#[cfg(timer_h4)]
204foreach_interrupt! {
205    ($inst:ident, timer, BCTM, GLOBAL, $irq:ident) => {
206        impl_core_timer!($inst, TimerBits::Bits16, GLOBAL);
207        impl BasicInstance for crate::peripherals::$inst {}
208    };
209
210    ($inst:ident, timer, ADTM, UP, $irq:ident) => {
211        impl_core_timer!($inst, TimerBits::Bits16, UP);
212        impl BasicInstance for crate::peripherals::$inst {}
213        impl SealedGeneralInstance for crate::peripherals::$inst {
214            fn enable_outputs(&self) {
215                unsafe { crate::pac::timer::Adtm::from_ptr(Self::regs()) }
216                    .bdtr()
217                    .modify(|w| w.set_moe(true));
218            }
219            fn get_counting_mode(&self) -> low_level::CountingMode {
220                let regs = unsafe { crate::pac::timer::Adtm::from_ptr(Self::regs()) };
221                let cr1 = regs.ctlr1().read();
222                (cr1.cms(), cr1.dir()).into()
223            }
224        }
225        // H4 ADTM: CC stays separate, TRG and COM are merged into TRG_COM.
226        impl_general_16bit!($inst, CC, TRG_COM);
227        impl_advanced!($inst, TRG_COM, BRK);
228    };
229}
230
231// GPTM is 2CH, no CTLR1.CMS and CTLR1.DIR
232#[cfg(timer_x0)]
233foreach_interrupt! {
234    ($inst:ident, timer, GPTM, UP, $irq:ident) => {
235        impl_core_timer!($inst, TimerBits::Bits16, UP);
236        impl BasicInstance for crate::peripherals::$inst {}
237        impl SealedGeneralInstance for crate::peripherals::$inst {}
238        impl_general_16bit!($inst, CC, TRG);
239    };
240}
241
242#[cfg(not(any(timer_x0, timer_h4)))]
243foreach_interrupt! {
244    ($inst:ident, timer, GPTM, UP, $irq:ident) => {
245        impl_core_timer!($inst, TimerBits::Bits16, UP);
246        impl BasicInstance for crate::peripherals::$inst {}
247        impl SealedGeneralInstance for crate::peripherals::$inst {
248            fn get_counting_mode(&self) -> low_level::CountingMode {
249                let regs = unsafe { crate::pac::timer::Gptm::from_ptr(Self::regs()) };
250                let cr1 = regs.ctlr1().read();
251                (cr1.cms(), cr1.dir()).into()
252            }
253        }
254        impl_general_16bit!($inst, CC, TRG);
255    };
256
257    ($inst:ident, timer, GPTM32, UP, $irq:ident) => {
258        impl_core_timer!($inst, TimerBits::Bits32, UP);
259        impl BasicInstance for crate::peripherals::$inst {}
260        impl SealedGeneralInstance for crate::peripherals::$inst {
261            fn get_counting_mode(&self) -> low_level::CountingMode {
262                let regs = unsafe { crate::pac::timer::Gptm::from_ptr(Self::regs()) };
263                let cr1 = regs.ctlr1().read();
264                (cr1.cms(), cr1.dir()).into()
265            }
266        }
267        impl_general_16bit!($inst, CC, TRG);
268        impl GeneralInstance32bit for crate::peripherals::$inst {}
269    };
270}
271
272#[cfg(timer_h4)]
273foreach_interrupt! {
274    ($inst:ident, timer, GPTM, GLOBAL, $irq:ident) => {
275        impl_core_timer!($inst, TimerBits::Bits16, GLOBAL);
276        impl BasicInstance for crate::peripherals::$inst {}
277        impl SealedGeneralInstance for crate::peripherals::$inst {
278            fn get_counting_mode(&self) -> low_level::CountingMode {
279                let regs = unsafe { crate::pac::timer::Gptm::from_ptr(Self::regs()) };
280                let cr1 = regs.ctlr1().read();
281                (cr1.cms(), cr1.dir()).into()
282            }
283        }
284        impl_general_16bit!($inst, GLOBAL, GLOBAL);
285    };
286
287    ($inst:ident, timer, GPTM32, GLOBAL, $irq:ident) => {
288        impl_core_timer!($inst, TimerBits::Bits32, GLOBAL);
289        impl BasicInstance for crate::peripherals::$inst {}
290        impl SealedGeneralInstance for crate::peripherals::$inst {
291            fn get_counting_mode(&self) -> low_level::CountingMode {
292                let regs = unsafe { crate::pac::timer::Gptm::from_ptr(Self::regs()) };
293                let cr1 = regs.ctlr1().read();
294                (cr1.cms(), cr1.dir()).into()
295            }
296        }
297        impl_general_16bit!($inst, GLOBAL, GLOBAL);
298        impl GeneralInstance32bit for crate::peripherals::$inst {}
299    };
300}