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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! Macros used by the HAL.
//!
//! Most of the macros in this module are hidden and intended for internal use
//! only. For the list of public macros, see the [procmacros](https://docs.rs/esp-hal-procmacros/latest/esp_hal_procmacros/)
//! documentation.

#[doc(hidden)]
/// Helper macro for checking doctest code snippets
#[macro_export]
macro_rules! before_snippet {
    () => {
        r#"
# #![no_std]
# use esp_hal::{interrupt::{self, InterruptConfigurable}, time::{Duration, Instant, Rate}};
# macro_rules! println {
#     ($($tt:tt)*) => { };
# }
# macro_rules! print {
#     ($($tt:tt)*) => { };
# }
# #[panic_handler]
# fn panic(_ : &core::panic::PanicInfo) -> ! {
#     loop {}
# }
# fn main() {
#   let _ = example();
# }
# struct ExampleError {}
# impl <T> From<T> for ExampleError where T: core::fmt::Debug {
#   fn from(_value: T) -> Self {
#       Self{}
#   }
# }
# async fn example() -> Result<(), ExampleError> {
#   let mut peripherals = esp_hal::init(esp_hal::Config::default());
"#
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! after_snippet {
    () => {
        r#"
# Ok(())
# }
"#
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! trm_markdown_link {
    () => {
        concat!("[Technical Reference Manual](", property!("trm"), ")")
    };
    ($anchor:literal) => {
        concat!(
            "[Technical Reference Manual](",
            property!("trm"),
            "#",
            $anchor,
            ")"
        )
    };
}

#[doc(hidden)]
/// Shorthand to define AnyPeripheral instances.
///
/// This macro generates the following:
///
/// - An `AnyPeripheral` struct, name provided by the macro call.
/// - An `any::Degrade` trait which is supposed to be used as a supertrait of a relevant Instance.
/// - An `any::Inner` enum, with the same variants as the original peripheral.
/// - A `From` implementation for each peripheral variant.
/// - A `degrade` method for each peripheral variant using the `any::Degrade` trait.
#[macro_export]
macro_rules! any_peripheral {
    ($(#[$meta:meta])* $vis:vis peripheral $name:ident<'d> {
        $(
            $(#[cfg($variant_meta:meta)])*
            $variant:ident($inner:ty)
        ),* $(,)?
    }) => {
        #[doc = concat!("Utilities related to [`", stringify!($name), "`]")]
        #[doc(hidden)]
        #[instability::unstable]
        pub mod any {
            #[allow(unused_imports)]
            use super::*;

            macro_rules! delegate {
                ($any:ident, $inner_ident:ident => $code:tt) => {
                    match &$any.0 {
                        $(
                            $(#[cfg($variant_meta)])*
                            any::Inner::$variant($inner_ident) => $code,
                        )*
                    }
                }
            }

            pub(crate) use delegate;

            $(#[$meta])*
            #[derive(Debug)]
            pub(crate) enum Inner<'d> {
                $(
                    $(#[cfg($variant_meta)])*
                    $variant($inner),
                )*
            }

            #[cfg(feature = "defmt")]
            impl defmt::Format for Inner<'_> {
                fn format(&self, fmt: defmt::Formatter<'_>) {
                    match self {
                        $(
                            $(#[cfg($variant_meta)])*
                            Self::$variant(inner) => inner.format(fmt),
                        )*
                    }
                }
            }

            // Trick to make peripherals implement something Into-like, without
            // requiring Instance traits to have lifetimes. Rustdoc will list
            // this trait as a supertrait, but will not give its definition.
            // Users are encouraged to use From to convert a singleton into its
            // relevant AnyPeripheral counterpart.
            #[allow(unused)]
            pub trait Degrade: Sized + $crate::private::Sealed {
                fn degrade<'a>(self) -> super::$name<'a>
                where
                    Self: 'a;
            }
        }

        $(#[$meta])*
        ///
        /// A type-erased version of a peripheral singleton. Useful
        /// for creating arrays of peripherals, or avoiding generics. Peripheral singletons
        /// can be type erased by using their `From` implementation.
        ///
        /// ```rust,ignore
        #[doc = concat!("let any_peripheral = ", stringify!($name), "::from(peripheral);")]
        /// ```
        #[derive(Debug)]
        #[cfg_attr(feature = "defmt", derive(defmt::Format))]
        $vis struct $name<'d>(any::Inner<'d>);

        impl $name<'_> {
            /// Unsafely clone this peripheral reference.
            ///
            /// # Safety
            ///
            /// The caller must ensure that only one instance of this type is used at a time.
            #[inline]
            #[allow(unused)]
            pub unsafe fn clone_unchecked(&self) -> Self { unsafe {
                any::delegate!(self, inner => { Self::from(inner.clone_unchecked()) })
            }}

            /// Creates a new peripheral reference with a shorter lifetime.
            ///
            /// Use this method to keep working with the peripheral after
            /// dropping the driver that consumes this.
            ///
            /// See [Peripheral singleton] section for more information.
            ///
            /// [Peripheral singleton]: crate#peripheral-singletons
            #[inline]
            #[allow(unused)]
            pub fn reborrow(&mut self) -> $name<'_> {
                unsafe { self.clone_unchecked() }
            }

            #[procmacros::doc_replace]
            /// Attempts to downcast the pin into the underlying peripheral instance.
            #[cfg_attr(
                // Feature-gated so that this doesn't prevent gradual device bringup. Any
                // stable driver would serve the purpose here, so this block will be part
                // of the released documentation.
                uart_driver_supported,
                doc = r#"
## Example

```rust,no_run
# {before_snippet}
#
# use esp_hal::{
#     uart::AnyUart as AnyPeripheral,
#     peripherals::{UART0 as PERI0, UART1 as PERI1},
# };
#
# let peri0 = peripherals.UART0;
# let peri1 = peripherals.UART1;
// let peri0 = peripherals.PERI0;
// let peri1 = peripherals.PERI1;
let any_peri0 = AnyPeripheral::from(peri0);
let any_peri1 = AnyPeripheral::from(peri1);

let uart0 = any_peri0
    .downcast::<PERI0>()
    .expect("This downcast succeeds because AnyPeripheral was created from Peri0");
let uart0 = any_peri1
    .downcast::<PERI0>()
    .expect_err("This AnyPeripheral was created from Peri1, it cannot be downcast to Peri0");
#
# {after_snippet}
```
"#
            )]
            #[inline]
            #[allow(unused)]
            pub fn downcast<P>(self) -> Result<P, Self>
            where
                Self: TryInto<P, Error = Self>
            {
                self.try_into()
            }
        }

        impl $crate::private::Sealed for $name<'_> {}

        // AnyPeripheral converts into itself
        impl<'d> any::Degrade for $name<'d> {
            #[inline]
            fn degrade<'a>(self) -> $name<'a>
            where
                Self: 'a,
            {
                self
            }
        }

        $(
            // Variants convert into AnyPeripheral
            $(#[cfg($variant_meta)])*
            impl<'d> any::Degrade for $inner {
                #[inline]
                fn degrade<'a>(self) -> $name<'a>
                where
                    Self: 'a,
                {
                    $name::from(self)
                }
            }

            $(#[cfg($variant_meta)])*
            impl<'d> From<$inner> for $name<'d> {
                #[inline]
                fn from(inner: $inner) -> Self {
                    Self(any::Inner::$variant(inner))
                }
            }

            $(#[cfg($variant_meta)])*
            impl<'d> TryFrom<$name<'d>> for $inner {
                type Error = $name<'d>;

                #[inline]
                fn try_from(any: $name<'d>) -> Result<Self, $name<'d>> {
                    #[allow(irrefutable_let_patterns)]
                    if let $name(any::Inner::$variant(inner)) = any {
                        Ok(inner)
                    } else {
                        Err(any)
                    }
                }
            }
        )*
    };
}

/// Macro to choose between two expressions. Useful for implementing "else" for
/// `$()?` macro syntax.
#[macro_export]
#[doc(hidden)]
macro_rules! if_set {
    (, $not_set:expr) => {
        $not_set
    };
    ($set:expr, $not_set:expr) => {
        $set
    };
}

#[cfg(feature = "unstable")]
include!(concat!(env!("OUT_DIR"), "/version_macro.rs"));

#[doc_replace]
/// Selects code based on the `esp-hal` version.
///
/// Branches are considered from top to bottom. The first branch whose version
/// is less than or equal to the current `esp-hal` version is
/// expanded. The fallback branch is expanded if no version branch matches.
///
/// Version branches should be listed in descending order.
///
/// # Examples
///
/// ```rust,no_run
/// # {before_snippet}
/// use esp_hal::at_least_version;
///
/// let description = at_least_version! {
///     (2, 0, 0) => { "esp-hal 2.0.0 or newer" }
///     (1, 1, 0) => { "esp-hal 1.1.0 or newer" }
///     _ => { "an older esp-hal version" }
/// };
/// # {after_snippet}
/// ```
#[macro_export]
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
macro_rules! at_least_version {
    ($($branch:tt)*) => {
        $crate::__esp_hal_at_least_version! { $($branch)* }
    };
}

/// Macro to ignore tokens.
///
/// This is useful when a metavariable must exist (to expand a
/// repetition), but need not be used.
#[macro_export]
#[doc(hidden)]
macro_rules! ignore {
    ($($item:tt)*) => {};
}

/// Defines a piece of (Espressif-specific) metadata that external tools may
/// parse.
///
/// The symbol name be formatted as `_ESP_METADATA_<category>_<name>`.
///
/// This metadata is zero cost, i.e. the value will not be flashed to the
/// device.
#[macro_export]
#[doc(hidden)]
macro_rules! metadata {
    ($category:literal, $key:ident, $value:expr) => {
        #[cfg(feature = "rt")]
        #[unsafe(link_section = concat!(".espressif.metadata"))]
        #[used]
        #[unsafe(export_name = concat!($category, ".", stringify!($key)))]
        static $key: [u8; $value.len()] = const {
            let val_bytes = $value.as_bytes();
            let mut val_bytes_array = [0; $value.len()];
            let mut i = 0;
            while i < val_bytes.len() {
                val_bytes_array[i] = val_bytes[i];
                i += 1;
            }
            val_bytes_array
        };
    };
}

#[procmacros::doc_replace]
/// Extract fields from [`Peripherals`][crate::peripherals::Peripherals] into named groups.
#[cfg_attr(
    // Feature-gated so that this doesn't prevent gradual device bringup. Any
    // stable driver would serve the purpose here, so this block will be part
    // of the released documentation.
    all(soc_has_spi2, soc_has_i2c0, gpio_driver_supported),
    doc = r#"
## Example

```rust,no_run
# {before_snippet}
#
use esp_hal::assign_resources;

assign_resources! {
    Resources<'d> {
        display: DisplayResources<'d> {
            spi:  SPI2,
            sda:  GPIO5,
            sclk: GPIO4,
            cs:   GPIO3,
            dc:   GPIO2,
        },
        axl: AccelerometerResources<'d> {
            i2c: I2C0,
            sda: GPIO0,
            scl: GPIO1,
        },
    }
}

# struct Display<'d>(core::marker::PhantomData<&'d ()>);
fn init_display<'d>(r: DisplayResources<'d>) -> Display<'d> {
    // use `r.spi`, `r.sda`, `r.sclk`, `r.cs`, `r.dc`
    todo!()
}

# struct Accelerometer<'d>(core::marker::PhantomData<&'d ()>);
fn init_accelerometer<'d>(r: AccelerometerResources<'d>) -> Accelerometer<'d> {
    // use `r.i2c`, `r.sda`, `r.scl`
    todo!()
}

// let peripherals = esp_hal::init(...);
let resources = split_resources!(peripherals);

let display = init_display(resources.display);
let axl = init_accelerometer(resources.axl);

// Other fields (`peripherals.UART0`, ...) of the `peripherals` struct can still be accessed.
# {after_snippet}
```
"#
)]
// Based on https://crates.io/crates/assign-resources
#[macro_export]
#[cfg(feature = "unstable")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
macro_rules! assign_resources {
    {
        $(#[$struct_meta:meta])*
        $vis:vis $struct_name:ident<$struct_lt:lifetime> {
            $(
                $(#[$group_meta:meta])*
                $group_name:ident : $group_struct:ident<$group_lt:lifetime> {
                    $(
                        $(#[$resource_meta:meta])*
                        $resource_name:ident : $resource_field:ident
                    ),*
                    $(,)?
                }
            ),+
            $(,)?
        }
    } => {
        // Group structs
        $(
            $(#[$group_meta])*
            #[allow(missing_docs)]
            $vis struct $group_struct<$group_lt> {
                $(
                    $(#[$resource_meta])*
                    pub $resource_name: $crate::peripherals::$resource_field<$group_lt>,
                )+
            }

            impl<$group_lt> $group_struct<$group_lt> {
                /// Unsafely creates an instance of the assigned peripherals out of thin air.
                ///
                /// # Safety
                ///
                /// The caller must ensure that only one instance of the contained peripherals is used at a time.
                pub unsafe fn steal() -> Self {
                    unsafe {
                        Self {
                            $($resource_name: $crate::peripherals::$resource_field::steal()),*
                        }
                    }
                }

                /// Creates a new reference to the peripheral group with a shorter lifetime.
                ///
                /// Use this method to keep working with the peripherals after
                /// dropping the drivers that consume this.
                pub fn reborrow(&mut self) -> $group_struct<'_> {
                    $group_struct {
                        $($resource_name: self.$resource_name.reborrow()),*
                    }
                }
            }
        )+

        // Outer struct
        $(#[$struct_meta])*
        /// Assigned resources.
        $vis struct $struct_name<$struct_lt> {
            $( pub $group_name: $group_struct<$struct_lt>, )+
        }

        impl<$struct_lt> $struct_name<$struct_lt> {
            /// Unsafely creates an instance of the assigned peripherals out of thin air.
            ///
            /// # Safety
            ///
            /// The caller must ensure that only one instance of the contained peripherals is used at a time.
            pub unsafe fn steal() -> Self {
                unsafe {
                    Self {
                        $($group_name: $group_struct::steal()),*
                    }
                }
            }

            /// Creates a new reference to the assigned peripherals with a shorter lifetime.
            ///
            /// Use this method to keep working with the peripherals after
            /// dropping the drivers that consume this.
            pub fn reborrow(&mut self) -> $struct_name<'_> {
                $struct_name {
                    $($group_name: self.$group_name.reborrow()),*
                }
            }
        }

        /// Extracts resources from the `Peripherals` struct.
        #[macro_export]
        macro_rules! split_resources {
            ($peris:ident) => {
                $struct_name {
                    $($group_name: $group_struct {
                        $($resource_name: $peris.$resource_field),*
                    }),*
                }
            }
        }
    };
}

/// Helper macro to implement the relevant DMA channel compatibility trait for peripheral
/// instances and DMA channel types.
///
/// Expected uses:
///
/// Drivers that define an AnyPeripheral type:
///
/// ```rust, ignore
/// with_spi_dma_engine! {
///     ($engine:tt, $any_peri:ident) => {
///         crate::impl_dma_channel_trait! {
///             $engine,
///             any_peri = AnySpi,
///             peris = for_each_spi_master,
///             ($peri:path, $ch:path) => {
///                 impl<'d> SpiMasterDmaChannel<'d, $peri<'d>> for $ch<'d> {}
///             }
///         }
///     }
/// }
/// ```
///
/// Drivers that do not:
///
/// ```rust, ignore
/// with_aes_dma_engine! {
///     ($engine:tt, $any_peri:ident) => {
///         crate::impl_dma_channel_trait! {
///             $engine,
///             peri = AES, // no lifetime!
///             ($peri:path, $ch:path) => {
///                 impl<'d> AesDmaChannel<'d> for $ch<'d> {}
///             }
///         }
///     }
/// }
/// ```
#[doc(hidden)]
#[rustfmt::skip]
#[cfg(dma_driver_supported)]
macro_rules! impl_dma_channel_trait {
    // Single peripheral instance case
    (
        $dma_engine:tt,
        peri = $peri:tt,
        $pattern:tt => $body:tt
    ) => {
        macro_rules! impl_dma_channel_trait_inner {
            ($pattern) => $body;
        }

        for_each_dma_channel_peri_pair! {
            ($dma_engine, any_channel = $any_ch:ident, $peri) => {
                impl_dma_channel_trait_inner! { ( $peri <'d>, $crate::dma::$any_ch<'d>) }
            };
            ($dma_engine, $ch:ident, $peri) => {
                impl_dma_channel_trait_inner! { ( $peri <'d>, $crate::peripherals::$ch<'d>) }
            };
        }
    };

    // Multiple peripheral instances case - implies AnyPeripheral
    (
        $dma_engine:tt,
        any_peri = $any_peri:ty,
        peris = $for_each_peri_macro:ident,
        $pattern:tt => $body:tt
    ) => {
        macro_rules! impl_dma_channel_trait_inner {
            ($pattern) => $body;
        }

        for_each_dma_channel! {
            ($dma_engine, any_channel = $any_ch:ident) => {
                impl_dma_channel_trait_inner! { ($any_peri, $crate::dma::$any_ch<'d>) }
            };
            ($dma_engine, $ch:ident) => {
                impl_dma_channel_trait_inner! { ($any_peri, $crate::peripherals::$ch<'d>) }
            };
        }

        $for_each_peri_macro! {
            ($peri:ident) => {
                for_each_dma_channel_peri_pair! {
                    ($dma_engine, any_channel = $any_ch:ident, $peri) => {
                        impl_dma_channel_trait_inner! { ($crate::peripherals::$peri<'d>, $crate::dma::$any_ch<'d>) }
                    };
                    ($dma_engine, $ch:ident, $peri) => {
                        impl_dma_channel_trait_inner! { ($crate::peripherals::$peri<'d>, $crate::peripherals::$ch<'d>) }
                    };
                }
            };
        }
    };
}
#[cfg(dma_driver_supported)]
pub(crate) use impl_dma_channel_trait;
#[cfg(feature = "unstable")]
use procmacros::doc_replace;

/// Macro to allow using unstable HAL features conditionally. Other crates can
/// use this to "detect" the esp-hal/unstable feature.
#[macro_export]
#[doc(hidden)]
#[cfg(feature = "unstable")]
macro_rules! if_unstable_hal {
    ($($tt:tt)*) => {
        $($tt)*
    };
}

/// Macro to allow using unstable HAL features conditionally. Other crates can
/// use this to "detect" the esp-hal/unstable feature.
#[macro_export]
#[doc(hidden)]
#[cfg(not(feature = "unstable"))]
macro_rules! if_unstable_hal {
    ($($tt:tt)*) => {};
}