esp-hal 1.2.0

Bare-metal HAL for Espressif devices
Documentation
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
#![cfg_attr(docsrs, procmacros::doc_replace)]
//! # General-purpose Timers
//!
//! ## Overview
//! The [OneShotTimer] and [PeriodicTimer] types can be backed by any hardware
//! peripheral which implements the [Timer] trait. This means that the same API
//! can be used to interact with different hardware timers, like the `TIMG` and
//! SYSTIMER.
#![cfg_attr(
    systimer_driver_supported,
    doc = "See the [timg] and [systimer] modules for more information."
)]
#![cfg_attr(
    not(systimer_driver_supported),
    doc = "See the [timg] module for more information."
)]
//! ## Examples
//!
//! ### One-shot Timer
//!
//! ```rust, no_run
//! # {before_snippet}
//! # use esp_hal::timer::{OneShotTimer, PeriodicTimer, timg::TimerGroup};
//! #
//! let timg0 = TimerGroup::new(peripherals.TIMG0);
//! let mut one_shot = OneShotTimer::new(timg0.timer0);
//!
//! one_shot.delay_millis(500);
//! # {after_snippet}
//! ```
//!
//! ### Periodic Timer
//! ```rust, no_run
//! # {before_snippet}
//! # use esp_hal::timer::{PeriodicTimer, timg::TimerGroup};
//! #
//! let timg0 = TimerGroup::new(peripherals.TIMG0);
//! let mut periodic = PeriodicTimer::new(timg0.timer0);
//!
//! periodic.start(Duration::from_secs(1));
//! loop {
//!     periodic.wait();
//! }
//! # }
//! ```

use core::{
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};

use crate::{
    Async,
    Blocking,
    DriverMode,
    asynch::AtomicWaker,
    interrupt::{InterruptConfigurable, InterruptHandler},
    peripherals::Interrupt,
    system::Cpu,
    time::{Duration, Instant},
};

#[cfg(systimer_driver_supported)]
pub mod systimer;
#[cfg(timergroup_driver_supported)]
pub mod timg;

/// Timer errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// The timer is already active.
    TimerActive,
    /// The timer is not currently active.
    TimerInactive,
    /// The alarm is not currently active.
    AlarmInactive,
    /// The provided timeout is too large.
    InvalidTimeout,
}

/// Functionality provided by any timer peripheral.
pub trait Timer: crate::private::Sealed {
    /// Starts the timer.
    #[doc(hidden)]
    fn start(&self);

    /// Stops the timer.
    #[doc(hidden)]
    fn stop(&self);

    /// Resets the timer value to 0.
    #[doc(hidden)]
    fn reset(&self);

    /// Is the timer running?
    #[doc(hidden)]
    fn is_running(&self) -> bool;

    /// The current timer value.
    #[doc(hidden)]
    fn now(&self) -> Instant;

    /// Loads a target value into the timer.
    #[doc(hidden)]
    fn load_value(&self, value: Duration) -> Result<(), Error>;

    /// Enables auto reload of the loaded value.
    #[doc(hidden)]
    fn enable_auto_reload(&self, auto_reload: bool);

    /// Enables or disables the timer's interrupt.
    #[doc(hidden)]
    fn enable_interrupt(&self, state: bool);

    /// Clears the timer's interrupt.
    fn clear_interrupt(&self);

    /// Returns whether the timer has triggered.
    fn is_interrupt_set(&self) -> bool;

    /// Returns the HAL provided async interrupt handler.
    #[doc(hidden)]
    fn async_interrupt_handler(&self) -> InterruptHandler;

    /// Returns the interrupt source for the underlying timer.
    fn peripheral_interrupt(&self) -> Interrupt;

    /// Configures the interrupt handler.
    #[doc(hidden)]
    fn set_interrupt_handler(&self, handler: InterruptHandler);

    #[doc(hidden)]
    fn waker(&self) -> &AtomicWaker;
}

/// A one-shot timer.
pub struct OneShotTimer<'d, Dm: DriverMode> {
    inner: AnyTimer<'d>,
    _ph: PhantomData<Dm>,
}

impl<'d> OneShotTimer<'d, Blocking> {
    /// Creates a new [`OneShotTimer`].
    pub fn new(inner: impl Timer + Into<AnyTimer<'d>>) -> OneShotTimer<'d, Blocking> {
        Self {
            inner: inner.into(),
            _ph: PhantomData,
        }
    }
}

impl<'d> OneShotTimer<'d, Blocking> {
    /// Converts the driver to [`Async`] mode.
    pub fn into_async(self) -> OneShotTimer<'d, Async> {
        let handler = self.inner.async_interrupt_handler();
        self.inner.set_interrupt_handler(handler);
        OneShotTimer {
            inner: self.inner,
            _ph: PhantomData,
        }
    }
}

impl<'d> OneShotTimer<'d, Async> {
    /// Converts the driver to [`Blocking`] mode.
    pub fn into_blocking(self) -> OneShotTimer<'d, Blocking> {
        crate::interrupt::disable(Cpu::current(), self.inner.peripheral_interrupt());
        OneShotTimer {
            inner: self.inner,
            _ph: PhantomData,
        }
    }

    /// Delays for *at least* `ns` nanoseconds.
    pub async fn delay_nanos_async(&mut self, ns: u32) {
        self.delay_async(Duration::from_micros(ns.div_ceil(1000) as u64))
            .await
    }

    /// Delays for *at least* `ms` milliseconds.
    pub async fn delay_millis_async(&mut self, ms: u32) {
        self.delay_async(Duration::from_millis(ms as u64)).await;
    }

    /// Delays for *at least* `us` microseconds.
    pub async fn delay_micros_async(&mut self, us: u32) {
        self.delay_async(Duration::from_micros(us as u64)).await;
    }

    /// Waits for *at least* the time interval `timeout`.
    ///
    /// Once the time period elapses, the underlying timer hardware does not automatically schedule
    /// the next timeout. The next timeout is scheduled only when `delay_async` is called again.
    async fn delay_async(&mut self, timeout: Duration) {
        unwrap!(self.schedule(timeout));

        WaitFuture::new(self.inner.reborrow()).await;

        self.stop();
        self.clear_interrupt();
    }
}

#[must_use = "futures do nothing unless you `.await` or poll them"]
struct WaitFuture<'d> {
    timer: AnyTimer<'d>,
}

impl<'d> WaitFuture<'d> {
    fn new(timer: AnyTimer<'d>) -> Self {
        // For some reason, on the S2 we need to enable the interrupt before we
        // read its status. Doing so in the other order causes the interrupt
        // request to never be fired.
        timer.enable_interrupt(true);
        Self { timer }
    }

    fn is_done(&self) -> bool {
        self.timer.is_interrupt_set()
    }
}

impl core::future::Future for WaitFuture<'_> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
        // Interrupts are enabled, so we need to register the waker before we check for
        // done. Otherwise we might miss the interrupt that would wake us.
        self.timer.waker().register(ctx.waker());

        if self.is_done() {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    }
}

impl Drop for WaitFuture<'_> {
    fn drop(&mut self) {
        self.timer.enable_interrupt(false);
    }
}

impl<Dm> OneShotTimer<'_, Dm>
where
    Dm: DriverMode,
{
    /// Delays for *at least* `ms` milliseconds.
    pub fn delay_millis(&mut self, ms: u32) {
        self.delay(Duration::from_millis(ms as u64));
    }

    /// Delays for *at least* `us` microseconds.
    pub fn delay_micros(&mut self, us: u32) {
        self.delay(Duration::from_micros(us as u64));
    }

    /// Delays for *at least* `ns` nanoseconds.
    pub fn delay_nanos(&mut self, ns: u32) {
        self.delay(Duration::from_micros(ns.div_ceil(1000) as u64))
    }

    fn delay(&mut self, us: Duration) {
        self.schedule(us).unwrap();

        while !self.inner.is_interrupt_set() {
            // Wait
        }

        self.stop();
        self.clear_interrupt();
    }

    /// Starts counting until the given timeout and raise an interrupt.
    pub fn schedule(&mut self, timeout: Duration) -> Result<(), Error> {
        if self.inner.is_running() {
            self.inner.stop();
        }

        self.inner.clear_interrupt();
        self.inner.reset();

        self.inner.enable_auto_reload(false);
        self.inner.load_value(timeout)?;
        self.inner.start();

        Ok(())
    }

    /// Stops the timer.
    pub fn stop(&mut self) {
        self.inner.stop();
    }

    /// Sets the interrupt handler.
    ///
    /// Replaces any previously set interrupt handler.
    #[instability::unstable]
    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
        self.inner.set_interrupt_handler(handler);
    }

    /// Listens for interrupt.
    pub fn listen(&mut self) {
        self.inner.enable_interrupt(true);
    }

    /// Unlistens for interrupt.
    pub fn unlisten(&mut self) {
        self.inner.enable_interrupt(false);
    }

    /// Clears the interrupt flag.
    pub fn clear_interrupt(&mut self) {
        self.inner.clear_interrupt();
    }
}

impl<Dm> crate::private::Sealed for OneShotTimer<'_, Dm> where Dm: DriverMode {}

impl<Dm> InterruptConfigurable for OneShotTimer<'_, Dm>
where
    Dm: DriverMode,
{
    fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) {
        OneShotTimer::set_interrupt_handler(self, handler);
    }
}

impl embedded_hal::delay::DelayNs for OneShotTimer<'_, Blocking> {
    fn delay_ns(&mut self, ns: u32) {
        self.delay_nanos(ns);
    }
}

impl embedded_hal_async::delay::DelayNs for OneShotTimer<'_, Async> {
    async fn delay_ns(&mut self, ns: u32) {
        self.delay_nanos_async(ns).await
    }
}

/// A periodic timer.
pub struct PeriodicTimer<'d, Dm: DriverMode> {
    inner: AnyTimer<'d>,
    _ph: PhantomData<Dm>,
}

impl<'d> PeriodicTimer<'d, Blocking> {
    /// Creates a new instance of [`PeriodicTimer`].
    pub fn new(inner: impl Timer + Into<AnyTimer<'d>>) -> PeriodicTimer<'d, Blocking> {
        Self {
            inner: inner.into(),
            _ph: PhantomData,
        }
    }

    /// Converts the driver to [`Async`] mode.
    pub fn into_async(self) -> PeriodicTimer<'d, Async> {
        let handler = self.inner.async_interrupt_handler();
        self.inner.set_interrupt_handler(handler);
        PeriodicTimer {
            inner: self.inner,
            _ph: PhantomData,
        }
    }
}

impl<'d> PeriodicTimer<'d, Async> {
    /// Converts the driver to [`Blocking`] mode.
    pub fn into_blocking(self) -> PeriodicTimer<'d, Blocking> {
        crate::interrupt::disable(Cpu::current(), self.inner.peripheral_interrupt());
        PeriodicTimer {
            inner: self.inner,
            _ph: PhantomData,
        }
    }

    /// Waits for *at least* the time interval loaded by [`PeriodicTimer::start`].
    ///
    /// Once the time period elapses, the underlying timer hardware automatically schedules the
    /// next timeout.
    pub async fn wait_async(&mut self) {
        WaitFuture::new(self.inner.reborrow()).await;
        self.clear_interrupt();
    }
}

impl<Dm> PeriodicTimer<'_, Dm>
where
    Dm: DriverMode,
{
    /// Starts a new count down.
    pub fn start(&mut self, period: Duration) -> Result<(), Error> {
        if self.inner.is_running() {
            self.inner.stop();
        }

        self.inner.clear_interrupt();
        self.inner.reset();

        self.inner.enable_auto_reload(true);
        self.inner.load_value(period)?;
        self.inner.start();

        Ok(())
    }

    /// "Wait", by blocking, until the count down finishes.
    pub fn wait(&mut self) {
        while !self.inner.is_interrupt_set() {}
        self.inner.clear_interrupt();
    }

    /// Tries to cancel the active count down.
    pub fn cancel(&mut self) -> Result<(), Error> {
        if !self.inner.is_running() {
            return Err(Error::TimerInactive);
        }

        self.inner.stop();

        Ok(())
    }

    /// Sets the interrupt handler.
    ///
    /// Replaces any previously set interrupt handler.
    #[instability::unstable]
    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
        self.inner.set_interrupt_handler(handler);
    }

    /// Listens for interrupt.
    pub fn listen(&mut self) {
        self.inner.enable_interrupt(true);
    }

    /// Unlistens for interrupt.
    pub fn unlisten(&mut self) {
        self.inner.enable_interrupt(false);
    }

    /// Clears the interrupt flag.
    pub fn clear_interrupt(&mut self) {
        self.inner.clear_interrupt();
    }
}

impl<Dm> crate::private::Sealed for PeriodicTimer<'_, Dm> where Dm: DriverMode {}

impl<Dm> InterruptConfigurable for PeriodicTimer<'_, Dm>
where
    Dm: DriverMode,
{
    fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) {
        PeriodicTimer::set_interrupt_handler(self, handler);
    }
}

crate::any_peripheral! {
    /// Any Timer peripheral.
    pub peripheral AnyTimer<'d> {
        #[cfg(timergroup_driver_supported)]
        TimgTimer(timg::Timer<'d>),
        #[cfg(systimer_driver_supported)]
        SystimerAlarm(systimer::Alarm<'d>),
    }
}

impl Timer for AnyTimer<'_> {
    delegate::delegate! {
        to match &self.0 {
            #[cfg(timergroup_driver_supported)]
            any::Inner::TimgTimer(inner) => inner,
            #[cfg(systimer_driver_supported)]
            any::Inner::SystimerAlarm(inner) => inner,
        } {
            fn start(&self);
            fn stop(&self);
            fn reset(&self);
            fn is_running(&self) -> bool;
            fn now(&self) -> Instant;
            fn load_value(&self, value: Duration) -> Result<(), Error>;
            fn enable_auto_reload(&self, auto_reload: bool);
            fn enable_interrupt(&self, state: bool);
            fn clear_interrupt(&self);
            fn is_interrupt_set(&self) -> bool;
            fn async_interrupt_handler(&self) -> InterruptHandler;
            fn peripheral_interrupt(&self) -> Interrupt;
            fn set_interrupt_handler(&self, handler: InterruptHandler);
            fn waker(&self) -> &AtomicWaker;
        }
    }
}