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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//! This module allows Timer peripherals to be configured as pwm input.
//! In this mode, the timer sample a squared signal to find it's frequency and duty cycle.

use core::marker::PhantomData;
use core::mem;

use crate::stm32::{DBG, TIM1, TIM2, TIM3, TIM4};

use crate::afio::MAPR;
use crate::gpio::gpioa::{PA0, PA1, PA15, PA6, PA7, PA8, PA9};
use crate::gpio::gpiob::{PB3, PB4, PB5, PB6, PB7};
use crate::gpio::{Alternate, OpenDrain};
use crate::rcc::{Clocks, APB1};
use crate::time::Hertz;
use crate::timer::PclkSrc;

pub trait Pins<TIM> {
    const REMAP: u8;
}

impl Pins<TIM4> for (PB6<Alternate<OpenDrain>>, PB7<Alternate<OpenDrain>>) {
    const REMAP: u8 = 0b0;
}

impl Pins<TIM3> for (PA6<Alternate<OpenDrain>>, PA7<Alternate<OpenDrain>>) {
    const REMAP: u8 = 0b00;
}

impl Pins<TIM3> for (PB4<Alternate<OpenDrain>>, PB5<Alternate<OpenDrain>>) {
    const REMAP: u8 = 0b10;
}

impl Pins<TIM2> for (PA0<Alternate<OpenDrain>>, PA1<Alternate<OpenDrain>>) {
    const REMAP: u8 = 0b00;
}

impl Pins<TIM2> for (PA15<Alternate<OpenDrain>>, PB3<Alternate<OpenDrain>>) {
    const REMAP: u8 = 0b11;
}

impl Pins<TIM1> for (PA8<Alternate<OpenDrain>>, PA9<Alternate<OpenDrain>>) {
    const REMAP: u8 = 0b00;
}

/// PWM Input
pub struct PwmInput<TIM, PINS> {
    _timer: PhantomData<TIM>,
    _pins: PhantomData<PINS>,
}

/// How the data is read from the timer
pub enum ReadMode {
    /// Return the latest captured data
    Instant,
    /// Wait for one period of the signal before computing the frequency and the duty cycle
    /// The microcontroller will be halted for at most two period of the input signal.
    WaitForNextCapture,
}

/// The error returned when reading a frequency from a timer
#[derive(Debug)]
pub enum Error {
    /// The signal frequency is too low to be sampled by the current timer configuration
    FrequencyTooLow,
}

/// Which frequency the timer will try to sample
pub enum Configuration<T>
where
    T: Into<Hertz>,
{
    /// In this mode an algorithm calculates the optimal value for the autoreload register and the
    /// prescaler register in order to be able to sample a wide range of frequency, at the expense
    /// of resolution.
    ///
    /// The minimum frequency that can be sampled is 20% the provided frequency.
    ///
    /// Use this mode if you do not know what to choose.
    Frequency(T),

    /// In this mode an algorithm calculates the optimal value for the autoreload register and the
    /// prescaler register in order to sample the duty cycle with a high resolution.
    /// This will limit the frequency range where the timer can operate.
    ///
    /// The minimum frequency that can be sampled is 90% the provided frequency
    DutyCycle(T),

    /// In this mode an algorithm calculates the optimal value for the autoreload register and the
    /// prescaler register in order to be able to sample signal with a frequency higher than the
    /// provided value : there is no margin for lower frequencies.
    RawFrequency(T),

    /// In this mode, the provided arr and presc are directly programmed in the register.
    RawValues { arr: u16, presc: u16 },
}
pub trait PwmInputExt: Sized {
    fn pwm_input<PINS, T>(
        self,
        pins: PINS,
        apb: &mut APB1,
        mapr: &mut MAPR,
        dbg: &mut DBG,
        clocks: &Clocks,
        mode: Configuration<T>,
    ) -> PwmInput<Self, PINS>
    where
        PINS: Pins<Self>,
        T: Into<Hertz>;
}

impl PwmInputExt for TIM2 {
    fn pwm_input<PINS, T>(
        self,
        pins: PINS,
        apb: &mut APB1,
        mapr: &mut MAPR,
        dbg: &mut DBG,
        clocks: &Clocks,
        mode: Configuration<T>,
    ) -> PwmInput<Self, PINS>
    where
        PINS: Pins<Self>,
        T: Into<Hertz>,
    {
        mapr.mapr()
            .modify(|_, w| unsafe { w.tim2_remap().bits(PINS::REMAP) });
        tim2(self, pins, clocks, apb, mode, dbg)
    }
}

impl PwmInputExt for TIM3 {
    fn pwm_input<PINS, T>(
        self,
        pins: PINS,
        apb: &mut APB1,
        mapr: &mut MAPR,
        dbg: &mut DBG,
        clocks: &Clocks,
        mode: Configuration<T>,
    ) -> PwmInput<Self, PINS>
    where
        PINS: Pins<Self>,
        T: Into<Hertz>,
    {
        mapr.mapr()
            .modify(|_, w| unsafe { w.tim3_remap().bits(PINS::REMAP) });
        tim3(self, pins, clocks, apb, mode, dbg)
    }
}

impl PwmInputExt for TIM4 {
    fn pwm_input<PINS, T>(
        self,
        pins: PINS,
        apb: &mut APB1,
        mapr: &mut MAPR,
        dbg: &mut DBG,
        clocks: &Clocks,
        mode: Configuration<T>,
    ) -> PwmInput<Self, PINS>
    where
        PINS: Pins<Self>,
        T: Into<Hertz>,
    {
        mapr.mapr()
            .modify(|_, w| w.tim4_remap().bit(PINS::REMAP == 1));
        tim4(self, pins, clocks, apb, mode, dbg)
    }
}

/// Courtesy of @TeXitoi (https://github.com/stm32-rs/stm32f1xx-hal/pull/10#discussion_r259535503)
fn compute_arr_presc(freq: u32, clock: u32) -> (u16, u16) {
    if freq == 0 {
        return (core::u16::MAX, core::u16::MAX);
    }
    let presc = clock / freq.saturating_mul(core::u16::MAX as u32 + 1);
    let arr = clock / freq.saturating_mul(presc + 1);
    (core::cmp::max(1, arr as u16), presc as u16)
}
macro_rules! hal {
   ($($TIMX:ident: ($timX:ident, $timXen:ident, $timXrst:ident, $dbg_timX_stop:ident ),)+) => {
      $(
         fn $timX<PINS,T>(
            tim: $TIMX,
            _pins: PINS,
            clocks: &Clocks,
            apb: &mut APB1,
            mode : Configuration<T>,
            dbg : &mut DBG
            ) -> PwmInput<$TIMX,PINS>
         where
         PINS: Pins<$TIMX>,
         T : Into<Hertz>
         {
            use crate::pwm_input::Configuration::*;
            apb.enr().modify(|_, w| w.$timXen().set_bit());
            apb.rstr().modify(|_, w| w.$timXrst().set_bit());
            apb.rstr().modify(|_, w| w.$timXrst().clear_bit());

            // Do not stop the timer in debug mode, because it cause troubles when sampling the
            // signal.
            // Removing this line will break your code if you have breakpoints
            dbg.cr.write(|w| w.$dbg_timX_stop().clear_bit());


            // Disable capture on both channels during setting
            // (for Channel X bit is CCXE)
            tim.ccer.modify(|_,w| w.cc1e().clear_bit().cc2e().clear_bit()
                            .cc1p().clear_bit().cc2p().set_bit());


            // Define the direction of the channel (input/output)
            // and the used input
            // 01: CC1 channel is configured as input, IC1 is mapped on TI1.
            // 10: CC1 channel is configured as input, IC1 is mapped on TI2.
            tim.ccmr1_output.modify( |_,w| unsafe {w.cc1s().bits(0b01)});

            // 01: CC2 channel is configured as input, IC2 is mapped on TI2
            // 10: CC2 channel is configured as input, IC2 is mapped on TI1
            tim.ccmr1_output.modify( |_,w| unsafe {w.cc2s().bits(0b10)});

            tim.dier.write(|w| w.cc1ie().set_bit());

            // Configure slave mode control register
            // Selects the trigger input to be used to synchronize the counter
            // 101: Filtered Timer Input 1 (TI1FP1)
            // ---------------------------------------
            // Slave Mode Selection :
            //  100: Reset Mode - Rising edge of the selected trigger input (TRGI)
            //  reinitializes the counter and generates an update of the registers.
            tim.smcr.modify( |_,w| unsafe {w.ts().bits(0b101).sms().bits(0b100)});

            match mode {
               Frequency(f)  => {
                  let freq = f.into().0;
                  let max_freq = if freq > 5 {freq/5} else {1};
                  let (arr,presc) = compute_arr_presc(max_freq, $TIMX::get_clk(&clocks).0);
                  tim.arr.write(|w| w.arr().bits(arr));
                  tim.psc.write(|w| unsafe {w.psc().bits(presc)});

               },
               DutyCycle(f) => {
                  let freq = f.into().0;
                  let max_freq = if freq > 2 {freq/2 + freq/4 + freq/8} else {1};
                  let (arr,presc) = compute_arr_presc(max_freq, $TIMX::get_clk(&clocks).0);
                  tim.arr.write(|w| w.arr().bits(arr));
                  tim.psc.write(|w| unsafe {w.psc().bits(presc)});
               },
               RawFrequency(f) => {
                  let freq = f.into().0;
                  let (arr,presc) = compute_arr_presc(freq, $TIMX::get_clk(&clocks).0);
                  tim.arr.write(|w| w.arr().bits(arr));
                  tim.psc.write(|w| unsafe {w.psc().bits(presc)});
               }
               RawValues{arr, presc} => {
                  tim.arr.write(|w| w.arr().bits(arr));
                  tim.psc.write(|w| unsafe {w.psc().bits(presc)});

               }
            }

            // Enable Capture on both channels
            tim.ccer.modify(|_,w| w.cc1e().set_bit().cc2e().set_bit());


            tim.cr1.modify(|_,w| w.cen().set_bit());


            unsafe { mem::uninitialized() }
         }

      impl<PINS> PwmInput<$TIMX,PINS> where PINS : Pins<$TIMX> {
         /// Return the frequency sampled by the timer
         pub fn read_frequency(&self, mode : ReadMode, clocks : &Clocks) -> Result<Hertz,Error> {

            match mode {
               ReadMode::WaitForNextCapture => self.wait_for_capture(),
                  _ => (),
            }
            let presc = unsafe { (*$TIMX::ptr()).psc.read().bits() as u16};
            let ccr1 = unsafe { (*$TIMX::ptr()).ccr1.read().bits() as u16};

            // Formulas :
            //
            // F_timer = F_pclk / (PSC+1)*(ARR+1)
            // Frac_arr = (CCR1+1)/(ARR+1)
            // F_signal = F_timer/Frac_arr
            // <=> F_signal = [(F_plck)/((PSC+1)*(ARR+1))] * [(ARR+1)/(CCR1+1)]
            // <=> F_signal = F_pclk / ((PSC+1)*(CCR1+1))
            //
            // Where :
            // * PSC is the prescaler register
            // * ARR is the auto-reload register
            // * F_timer is the number of time per second where the timer overflow under normal
            // condition
            //
            if ccr1 == 0 {
               Err(Error::FrequencyTooLow)
            }
            else {
               let clk : u32 = $TIMX::get_clk(&clocks).0;
               Ok(Hertz(clk/((presc+1) as u32*(ccr1 + 1)as u32)))
            }
         }


         /// Return the duty in the form of a fraction : (duty_cycle/period)
         pub fn read_duty(&self, mode : ReadMode) -> Result<(u16,u16),Error> {

            match mode {
               ReadMode::WaitForNextCapture => self.wait_for_capture(),
               _ => (),
            }

            // Formulas :
            // Duty_cycle = (CCR2+1)/(CCR1+1)
            let ccr1 = unsafe { (*$TIMX::ptr()).ccr1.read().bits() as u16};
            let ccr2 = unsafe { (*$TIMX::ptr()).ccr2.read().bits() as u16};
            if ccr1 == 0 {
               Err(Error::FrequencyTooLow)
            } else {
               Ok((ccr2,ccr1))
            }
         }

         /// Wait until the timer has captured a period
         fn wait_for_capture(&self) {
            unsafe { (*$TIMX::ptr()).sr.write(|w| w.uif().clear_bit().cc1if().clear_bit().cc1of().clear_bit())};
            while unsafe { (*$TIMX::ptr()).sr.read().cc1if().bit_is_clear()} {}
         }
      }

      )+
   }
}

hal! {
   TIM2: (tim2, tim2en, tim2rst, dbg_tim2_stop),
   TIM3: (tim3, tim3en, tim3rst, dbg_tim3_stop),
   TIM4: (tim4, tim4en, tim4rst, dbg_tim4_stop),
}