aboutsummaryrefslogtreecommitdiff
path: root/embassy-stm32/src/timer/one_pulse.rs
blob: fe8681356ec8f540e09c80ff3a182fb359dacc04 (plain)
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
//! One pulse mode driver.

use core::future::Future;
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use core::pin::Pin;
use core::task::{Context, Poll};

use super::low_level::{
    CountingMode, FilterValue, InputCaptureMode, InputTISelection, SlaveMode, Timer, TriggerSource as Ts,
};
use super::{CaptureCompareInterruptHandler, Channel, ExternalTriggerPin, GeneralInstance4Channel, TimerPin};
pub use super::{Ch1, Ch2};
use crate::Peri;
use crate::gpio::{AfType, AnyPin, Pull};
use crate::interrupt::typelevel::{Binding, Interrupt};
use crate::pac::timer::vals::Etp;
use crate::time::Hertz;
use crate::timer::TimerChannel;

/// External input marker type.
pub enum Ext {}

/// External trigger pin trigger polarity.
#[derive(Clone, Copy)]
pub enum ExternalTriggerPolarity {
    /// Rising edge only.
    Rising,
    /// Falling edge only.
    Falling,
}

impl From<ExternalTriggerPolarity> for Etp {
    fn from(mode: ExternalTriggerPolarity) -> Self {
        match mode {
            ExternalTriggerPolarity::Rising => 0.into(),
            ExternalTriggerPolarity::Falling => 1.into(),
        }
    }
}

/// Trigger pin wrapper.
///
/// This wraps a pin to make it usable as a timer trigger.
pub struct TriggerPin<'d, T, C> {
    #[allow(unused)]
    pin: Peri<'d, AnyPin>,
    phantom: PhantomData<(T, C)>,
}

trait SealedTriggerSource {}

/// Marker trait for a trigger source.
#[expect(private_bounds)]
pub trait TriggerSource: SealedTriggerSource {}

impl TriggerSource for Ch1 {}
impl TriggerSource for Ch2 {}
impl TriggerSource for Ext {}

impl SealedTriggerSource for Ch1 {}
impl SealedTriggerSource for Ch2 {}
impl SealedTriggerSource for Ext {}

impl<'d, T: GeneralInstance4Channel, C: TriggerSource + TimerChannel> TriggerPin<'d, T, C> {
    /// Create a new Channel trigger pin instance.
    pub fn new<#[cfg(afio)] A>(pin: Peri<'d, if_afio!(impl TimerPin<T, C, A>)>, pull: Pull) -> Self {
        set_as_af!(pin, AfType::input(pull));
        TriggerPin {
            pin: pin.into(),
            phantom: PhantomData,
        }
    }
}

impl<'d, T: GeneralInstance4Channel> TriggerPin<'d, T, Ext> {
    /// Create a new external trigger pin instance.
    pub fn new_external<#[cfg(afio)] A>(pin: Peri<'d, if_afio!(impl ExternalTriggerPin<T, A>)>, pull: Pull) -> Self {
        set_as_af!(pin, AfType::input(pull));
        TriggerPin {
            pin: pin.into(),
            phantom: PhantomData,
        }
    }
}

/// One pulse driver.
///
/// Generates a pulse after a trigger and some configurable delay.
pub struct OnePulse<'d, T: GeneralInstance4Channel> {
    inner: Timer<'d, T>,
}

impl<'d, T: GeneralInstance4Channel> OnePulse<'d, T> {
    /// Create a new one pulse driver.
    ///
    /// The pulse is triggered by a channel 1 input pin on both rising and
    /// falling edges. Channel 1 will unusable as an output.
    #[allow(unused)]
    pub fn new_ch1_edge_detect(
        tim: Peri<'d, T>,
        pin: TriggerPin<'d, T, Ch1>,
        _irq: impl Binding<T::CaptureCompareInterrupt, CaptureCompareInterruptHandler<T>> + 'd,
        freq: Hertz,
        pulse_end: u32,
        counting_mode: CountingMode,
    ) -> Self {
        let mut this = Self { inner: Timer::new(tim) };

        this.inner.set_trigger_source(Ts::TI1F_ED);
        this.inner
            .set_input_ti_selection(Channel::Ch1, InputTISelection::Normal);
        this.inner
            .set_input_capture_filter(Channel::Ch1, FilterValue::NO_FILTER);
        this.new_inner(freq, pulse_end, counting_mode);

        this
    }

    /// Create a new one pulse driver.
    ///
    /// The pulse is triggered by a channel 1 input pin. Channel 1 will unusable
    /// as an output.
    pub fn new_ch1(
        tim: Peri<'d, T>,
        _pin: TriggerPin<'d, T, Ch1>,
        _irq: impl Binding<T::CaptureCompareInterrupt, CaptureCompareInterruptHandler<T>> + 'd,
        freq: Hertz,
        pulse_end: u32,
        counting_mode: CountingMode,
        capture_mode: InputCaptureMode,
    ) -> Self {
        let mut this = Self { inner: Timer::new(tim) };

        this.inner.set_trigger_source(Ts::TI1FP1);
        this.inner
            .set_input_ti_selection(Channel::Ch1, InputTISelection::Normal);
        this.inner
            .set_input_capture_filter(Channel::Ch1, FilterValue::NO_FILTER);
        this.inner.set_input_capture_mode(Channel::Ch1, capture_mode);
        this.new_inner(freq, pulse_end, counting_mode);

        this
    }

    /// Create a new one pulse driver.
    ///
    /// The pulse is triggered by a channel 2 input pin. Channel 2 will unusable
    /// as an output.
    pub fn new_ch2(
        tim: Peri<'d, T>,
        _pin: TriggerPin<'d, T, Ch2>,
        _irq: impl Binding<T::CaptureCompareInterrupt, CaptureCompareInterruptHandler<T>> + 'd,
        freq: Hertz,
        pulse_end: u32,
        counting_mode: CountingMode,
        capture_mode: InputCaptureMode,
    ) -> Self {
        let mut this = Self { inner: Timer::new(tim) };

        this.inner.set_trigger_source(Ts::TI2FP2);
        this.inner
            .set_input_ti_selection(Channel::Ch2, InputTISelection::Normal);
        this.inner
            .set_input_capture_filter(Channel::Ch2, FilterValue::NO_FILTER);
        this.inner.set_input_capture_mode(Channel::Ch2, capture_mode);
        this.new_inner(freq, pulse_end, counting_mode);

        this
    }

    /// Create a new one pulse driver.
    ///
    /// The pulse is triggered by a external trigger input pin.
    pub fn new_ext(
        tim: Peri<'d, T>,
        _pin: TriggerPin<'d, T, Ext>,
        _irq: impl Binding<T::CaptureCompareInterrupt, CaptureCompareInterruptHandler<T>> + 'd,
        freq: Hertz,
        pulse_end: u32,
        counting_mode: CountingMode,
        polarity: ExternalTriggerPolarity,
    ) -> Self {
        let mut this = Self { inner: Timer::new(tim) };

        this.inner.regs_gp16().smcr().modify(|r| {
            r.set_etp(polarity.into());
            // No pre-scaling
            r.set_etps(0.into());
            // No filtering
            r.set_etf(FilterValue::NO_FILTER);
        });
        this.inner.set_trigger_source(Ts::ETRF);
        this.new_inner(freq, pulse_end, counting_mode);

        this
    }

    fn new_inner(&mut self, freq: Hertz, pulse_end: u32, counting_mode: CountingMode) {
        self.inner.set_counting_mode(counting_mode);
        self.inner.set_tick_freq(freq);
        self.inner.set_max_compare_value(pulse_end);
        self.inner.regs_core().cr1().modify(|r| r.set_opm(true));
        // Required for advanced timers, see GeneralInstance4Channel for details
        self.inner.enable_outputs();
        self.inner.set_slave_mode(SlaveMode::TRIGGER_MODE);

        T::CaptureCompareInterrupt::unpend();
        unsafe { T::CaptureCompareInterrupt::enable() };
    }

    /// Get the end of the pulse in ticks from the trigger.
    pub fn pulse_end(&self) -> u32 {
        let max = self.inner.get_max_compare_value();
        assert!(max < u32::MAX);
        max + 1
    }

    /// Set the end of the pulse in ticks from the trigger.
    pub fn set_pulse_end(&mut self, ticks: u32) {
        self.inner.set_max_compare_value(ticks)
    }

    /// Reset the timer on each trigger
    #[cfg(not(stm32l0))]
    pub fn set_reset_on_trigger(&mut self, reset: bool) {
        let slave_mode = if reset {
            SlaveMode::COMBINED_RESET_TRIGGER
        } else {
            SlaveMode::TRIGGER_MODE
        };
        self.inner.set_slave_mode(slave_mode);
    }

    /// Get a single channel
    ///
    /// If you need to use multiple channels, use [`Self::split`].
    pub fn channel(&mut self, channel: Channel) -> OnePulseChannel<'_, T> {
        OnePulseChannel {
            inner: unsafe { self.inner.clone_unchecked() },
            channel,
        }
    }

    /// Channel 1
    ///
    /// This is just a convenience wrapper around [`Self::channel`].
    ///
    /// If you need to use multiple channels, use [`Self::split`].
    pub fn ch1(&mut self) -> OnePulseChannel<'_, T> {
        self.channel(Channel::Ch1)
    }

    /// Channel 2
    ///
    /// This is just a convenience wrapper around [`Self::channel`].
    ///
    /// If you need to use multiple channels, use [`Self::split`].
    pub fn ch2(&mut self) -> OnePulseChannel<'_, T> {
        self.channel(Channel::Ch2)
    }

    /// Channel 3
    ///
    /// This is just a convenience wrapper around [`Self::channel`].
    ///
    /// If you need to use multiple channels, use [`Self::split`].
    pub fn ch3(&mut self) -> OnePulseChannel<'_, T> {
        self.channel(Channel::Ch3)
    }

    /// Channel 4
    ///
    /// This is just a convenience wrapper around [`Self::channel`].
    ///
    /// If you need to use multiple channels, use [`Self::split`].
    pub fn ch4(&mut self) -> OnePulseChannel<'_, T> {
        self.channel(Channel::Ch4)
    }

    /// Splits a [`OnePulse`] into four output channels.
    // TODO: I hate the name "split"
    pub fn split(self) -> OnePulseChannels<'static, T>
    where
        // must be static because the timer will never be dropped/disabled
        'd: 'static,
    {
        // without this, the timer would be disabled at the end of this function
        let timer = ManuallyDrop::new(self.inner);

        let ch = |channel| OnePulseChannel {
            inner: unsafe { timer.clone_unchecked() },
            channel,
        };

        OnePulseChannels {
            ch1: ch(Channel::Ch1),
            ch2: ch(Channel::Ch2),
            ch3: ch(Channel::Ch3),
            ch4: ch(Channel::Ch4),
        }
    }
}

/// A group of four [`OnePulseChannel`]s, obtained from [`OnePulse::split`].
pub struct OnePulseChannels<'d, T: GeneralInstance4Channel> {
    /// Channel 1
    pub ch1: OnePulseChannel<'d, T>,
    /// Channel 2
    pub ch2: OnePulseChannel<'d, T>,
    /// Channel 3
    pub ch3: OnePulseChannel<'d, T>,
    /// Channel 4
    pub ch4: OnePulseChannel<'d, T>,
}

/// A single channel of a one pulse-configured timer, obtained from
/// [`OnePulse::split`],[`OnePulse::channel`], [`OnePulse::ch1`], etc.
///
/// It is not possible to change the pulse end tick because the end tick
/// configuration is shared with all four channels.
pub struct OnePulseChannel<'d, T: GeneralInstance4Channel> {
    inner: ManuallyDrop<Timer<'d, T>>,
    channel: Channel,
}

impl<'d, T: GeneralInstance4Channel> OnePulseChannel<'d, T> {
    /// Get the end of the pulse in ticks from the trigger.
    pub fn pulse_end(&self) -> u32 {
        let max = self.inner.get_max_compare_value();
        assert!(max < u32::MAX);
        max + 1
    }

    /// Get the width of the pulse in ticks.
    pub fn pulse_width(&mut self) -> u32 {
        self.pulse_end().saturating_sub(self.pulse_delay())
    }

    /// Get the start of the pulse in ticks from the trigger.
    pub fn pulse_delay(&mut self) -> u32 {
        self.inner.get_compare_value(self.channel)
    }

    /// Set the start of the pulse in ticks from the trigger.
    pub fn set_pulse_delay(&mut self, delay: u32) {
        assert!(delay <= self.pulse_end());
        self.inner.set_compare_value(self.channel, delay);
    }

    /// Set the pulse width in ticks.
    pub fn set_pulse_width(&mut self, width: u32) {
        assert!(width <= self.pulse_end());
        self.set_pulse_delay(self.pulse_end() - width);
    }

    /// Waits until the trigger and following delay has passed.
    pub async fn wait_for_pulse_start(&mut self) {
        self.inner.enable_input_interrupt(self.channel, true);

        OnePulseFuture::<T> {
            channel: self.channel,
            phantom: PhantomData,
        }
        .await
    }
}

#[must_use = "futures do nothing unless you `.await` or poll them"]
struct OnePulseFuture<T: GeneralInstance4Channel> {
    channel: Channel,
    phantom: PhantomData<T>,
}

impl<'d, T: GeneralInstance4Channel> Drop for OnePulseFuture<T> {
    fn drop(&mut self) {
        critical_section::with(|_| {
            let regs = unsafe { crate::pac::timer::TimGp16::from_ptr(T::regs()) };

            // disable interrupt enable
            regs.dier().modify(|w| w.set_ccie(self.channel.index(), false));
        });
    }
}

impl<'d, T: GeneralInstance4Channel> Future for OnePulseFuture<T> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        T::state().cc_waker[self.channel.index()].register(cx.waker());

        let regs = unsafe { crate::pac::timer::TimGp16::from_ptr(T::regs()) };

        let dier = regs.dier().read();
        if !dier.ccie(self.channel.index()) {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    }
}