1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use super::{CPin, General, Instance, Timer, WithPwm};
use core::convert::TryFrom;
use core::ops::{Deref, DerefMut};
use fugit::HertzU32 as Hertz;

pub trait Pins<TIM> {}

// implement the `Pins` trait wherever PC1 implements CPin<C1>
impl<TIM, PC1> Pins<TIM> for PC1 where PC1: CPin<TIM, 0> {}

/// Represents a TIMer configured as a PWM input.
/// This peripheral will emit an interrupt on CC2 events, which occurs at two times in this mode:
/// 1. When a new cycle is started: the duty cycle will be `1.00`
/// 2. When the period is captured. the duty cycle will be an observable value.
/// An example interrupt handler is provided:
/// ```
/// use stm32f4xx_hal::pac::TIM8;
/// use stm32f4xx_hal::timer::Timer;
/// use stm32f4xx_hal::pwm_input::PwmInput;
/// use stm32f4xx_hal::gpio::gpioc::PC6;
/// use stm32f4xx_hal::gpio::Alternate;
///
/// type Monitor = PwmInput<TIM8, PC6<Alternate<3>>>;
///
/// fn tim8_cc2(monitor: &Monitor) {
///             let duty_clocks = monitor.get_duty_cycle_clocks();
///             let period_clocks = monitor.get_period_clocks();
///             // check if this interrupt was caused by a capture at the wrong CC2,
///             // peripheral limitation.
///             if !monitor.is_valid_capture(){
///                 return;
///             }
///             let duty = monitor.get_duty_cycle();
/// }
/// ```
pub struct PwmInput<TIM, PINS>
where
    TIM: Instance + WithPwm,
    PINS: Pins<TIM>,
{
    timer: Timer<TIM>,
    _pins: PINS,
}

impl<TIM, PINS> Deref for PwmInput<TIM, PINS>
where
    TIM: Instance + WithPwm,
    PINS: Pins<TIM>,
{
    type Target = Timer<TIM>;
    fn deref(&self) -> &Self::Target {
        &self.timer
    }
}

impl<TIM, PINS> DerefMut for PwmInput<TIM, PINS>
where
    TIM: Instance + WithPwm,
    PINS: Pins<TIM>,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.timer
    }
}

impl<TIM, PINS> PwmInput<TIM, PINS>
where
    TIM: Instance + WithPwm,
    PINS: Pins<TIM>,
{
    pub fn release(mut self) -> Timer<TIM> {
        self.tim.cr1_reset();
        self.timer
    }
}

#[cfg(not(feature = "stm32f410"))]
macro_rules! hal {
    ($($TIM:ident,)+) => {
        $(
        // Drag the associated TIM object into scope.
        // Note: its drawn in via the macro to avoid duplicating the feature gate this macro is
        //       expecting to be guarded by.
        use crate::pac::$TIM;

        impl Timer<$TIM> {
            /// Configures this timer for PWM input. Accepts the `best_guess` frequency of the signal
            /// Note: this should be as close as possible to the frequency of the PWM waveform for best
            /// accuracy.
            ///
            /// This device will emit an interrupt on CC1, which occurs at two times in this mode:
            /// 1. When a new cycle is started: the duty cycle will be `1.00`
            /// 2. When the period is captured. the duty cycle will be an observable value.
            /// See the pwm input example for an suitable interrupt handler.
            #[allow(unused_unsafe)] //for some chips the operations are considered safe.
            pub fn pwm_input<PINS>(mut self, best_guess: Hertz, pins: PINS) -> PwmInput<$TIM, PINS>
            where
                PINS: Pins<$TIM>,
            {
                /*
                Borrowed from PWM implementation.
                Sets the TIMer's prescaler such that the TIMer that it ticks at about the best-guess
                 frequency.
                */
                let ticks = self.clk.raw() / best_guess.raw();
                let psc = u16::try_from((ticks - 1) / (1 << 16)).unwrap();
                self.tim.set_prescaler(psc);

                // Seemingly this needs to be written to
                // self.tim.arr.write(|w| w.arr().bits(u16::MAX));

                /*
                For example, one can measure the period (in TIMx_CCR1 register) and the duty cycle (in
                TIMx_CCR2 register) of the PWM applied on TI1 using the following procedure (depending
                on CK_INT frequency and prescaler value):

                from RM0390 16.3.7
                 */

                // Select the active input for TIMx_CCR1: write the CC1S bits to 01 in the TIMx_CCMR1
                // register (TI1 selected).
                self.tim
                    .ccmr1_input()
                    .modify(|_, w| unsafe { w.cc1s().bits(0b01) });

                // Select the active polarity for TI1FP1 (used both for capture in TIMx_CCR1 and counter
                // clear): write the CC1P and CC1NP bits to ‘0’ (active on rising edge).

                self.tim
                    .ccer
                    .modify(|_, w| w.cc1p().clear_bit().cc2p().clear_bit());

                // disable filters and disable the input capture prescalers.
                self.tim.ccmr1_input().modify(|_, w| unsafe {
                    w.ic1f()
                        .bits(0)
                        .ic2f()
                        .bits(0)
                        .ic1psc()
                        .bits(0)
                        .ic2psc()
                        .bits(0)
                });

                // Select the active input for TIMx_CCR2: write the CC2S bits to 10 in the TIMx_CCMR1
                // register (TI1 selected)
                self.tim
                    .ccmr1_input()
                    .modify(|_, w| unsafe { w.cc2s().bits(0b10) });

                // Select the active polarity for TI1FP2 (used for capture in TIMx_CCR2): write the CC2P
                // and CC2NP bits to ‘1’ (active on falling edge).
                self.tim
                    .ccer
                    .modify(|_, w| w.cc2p().set_bit().cc2np().set_bit());

                // Select the valid trigger input: write the TS bits to 101 in the TIMx_SMCR register
                // (TI1FP1 selected).
                self.tim.smcr.modify(|_, w| unsafe { w.ts().bits(0b101) });

                // Configure the slave mode controller in reset mode: write the SMS bits to 100 in the
                // TIMx_SMCR register.
                self.tim.smcr.modify(|_, w| unsafe { w.sms().bits(0b100) });

                // Enable the captures: write the CC1E and CC2E bits to ‘1’ in the TIMx_CCER register.
                self.tim
                    .ccer
                    .modify(|_, w| w.cc1e().set_bit().cc2e().set_bit());

                // enable interrupts.
                self.tim.dier.modify(|_, w| w.cc2ie().set_bit());
                // enable the counter.
                self.tim.enable_counter();

                PwmInput { timer: self, _pins: pins }
            }
        }

        impl<PINS> PwmInput<$TIM, PINS>
        where
            PINS: Pins<$TIM>,
        {
            /// Period of PWM signal in terms of clock cycles
            pub fn get_period_clocks(&self) -> <$TIM as General>::Width {
                self.tim.ccr1.read().ccr().bits()
            }
            /// Duty cycle in terms of clock cycles
            pub fn get_duty_cycle_clocks(&self) -> <$TIM as General>::Width {
                self.tim.ccr2.read().ccr().bits()
            }
            /// Observed duty cycle as a float in range [0.00, 1.00]
            pub fn get_duty_cycle(&self) -> f32 {
                let period_clocks = self.get_period_clocks();
                if period_clocks == 0 {
                    return 0.0;
                };
                return (self.get_duty_cycle_clocks() as f32 / period_clocks as f32) * 100f32;
            }
            /// Returns whether the timer's duty cycle is a valid observation
            /// (Limitation of how the captures work is extra CC2 interrupts are generated when the
            /// PWM cycle enters a new period).
            pub fn is_valid_capture(&self) -> bool {
                self.get_duty_cycle_clocks() != self.get_period_clocks()
            }
        }
    )+
}}

#[cfg(any(feature = "stm32f411",))]
/* red group */
hal! {
    TIM4,
    TIM3,
    TIM2,
}

/* orange group */
#[cfg(any(
    feature = "stm32f401",
    feature = "stm32f405",
    feature = "stm32f407",
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f415",
    feature = "stm32f417",
    feature = "stm32f423",
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f446",
    feature = "stm32f469",
    feature = "stm32f479",
))]
hal! {
    TIM2,
    TIM3,
    TIM4,
}
/* green group */
#[cfg(any(
    feature = "stm32f405",
    feature = "stm32f407",
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f415",
    feature = "stm32f417",
    feature = "stm32f423",
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f446",
    feature = "stm32f469",
    feature = "stm32f479",
))]
hal! {
    TIM8,
    TIM12,
}

/* every chip across the series have these timers with support for this feature.
.. except for the 410 which, while the timers support this feature, has a different configuration
   than the rest of the series.
*/
/* yellow group */
#[cfg(not(feature = "stm32f410"))]
hal! {
    TIM1,
    TIM5,
    TIM9,
}