Skip to main content

esp_hal/
lib.rs

1#![cfg_attr(
2    all(docsrs, not(not_really_docsrs)),
3    doc = "<div style='padding:30px;background:#810;color:#fff;text-align:center;'><p>You might want to <a href='https://docs.espressif.com/projects/rust/'>browse the <code>esp-hal</code> documentation on the esp-rs website</a> instead.</p><p>The documentation here on <a href='https://docs.rs'>docs.rs</a> is built for a single chip only (ESP32-C6, in particular), while on the esp-rs website you can select your exact chip from the list of supported devices. Available peripherals and their APIs change depending on the chip.</p></div>\n\n<br/>\n\n"
4)]
5//! # Bare-metal (`no_std`) HAL for all Espressif ESP32 devices.
6//!
7//! This documentation is built for the
8#![doc = concat!("**", chip_pretty!(), "**")]
9//! . Please ensure you are reading the correct [documentation] for your target
10//! device.
11//!
12//! ## Overview
13//!
14//! esp-hal is a Hardware Abstraction Layer (HAL) for Espressif's ESP32 lineup of
15//! microcontrollers offering safe, idiomatic APIs to control hardware peripherals.
16//!
17//! ### Peripheral drivers
18//!
19//! The HAL implements both [`Blocking`] _and_ [`Async`] APIs for all applicable peripherals.
20//! Where applicable, driver implement the [embedded-hal] and
21//! [embedded-hal-async] traits. Drivers that do not currently have a stable API
22//! are marked as `unstable` in the documentation.
23//!
24//! ### Peripheral singletons
25//!
26//! Each peripheral driver needs a peripheral singleton that tells the driver
27//! which hardware block to use. The peripheral singletons are created by the
28//! HAL initialization, and are returned from [`init`] as fields of the
29//! [`Peripherals`] struct.
30//!
31//! These singletons, by default, represent peripherals for the entire lifetime
32//! of the program. To allow for reusing peripherals, the HAL provides a
33//! `reborrow` method on each peripheral singleton. This method creates a new
34//! handle to the peripheral with a shorter lifetime. This lets the handle be
35//! passed to a driver while keeping the original handle alive. Once the driver
36//! is dropped, the peripheral can be reborrowed again.
37#![cfg_attr(
38    // Feature-gated so that this doesn't prevent gradual device bringup. Any
39    // stable driver would serve the purpose here, so this block will be part
40    // of the released documentation.
41    i2c_master_driver_supported,
42    doc = r#"
43For example, if you want to use the [`I2c`](i2c::master::I2c) driver and you
44do not intend to drop the driver, you can pass the peripheral singleton to
45the driver by value:
46
47```rust, ignore
48// Peripheral singletons are returned from the `init` function.
49let peripherals = esp_hal::init(esp_hal::Config::default());
50
51let mut i2c = I2c::new(peripherals.I2C0, /* ... */);
52```
53"#
54)]
55//! If you want to use the peripheral in multiple places (for example, you want
56//! to drop the driver for some period of time to minimize power consumption),
57//! you can reborrow the peripheral singleton and pass it to the driver by
58//! reference:
59//!
60//! ```rust, ignore
61//! // Note that in this case, `peripherals` needs to be mutable.
62//! let mut peripherals = esp_hal::init(esp_hal::Config::default());
63//!
64//! let i2c = I2C::new(peripherals.I2C0.reborrow(), /* ... */);
65//!
66//! // Do something with the I2C driver...
67//!
68//! core::mem::drop(i2c); // Drop the driver to minimize power consumption.
69//!
70//! // Do something else...
71//!
72//! // You can then take or reborrow the peripheral singleton again.
73//! let i2c = I2C::new(peripherals.I2C0.reborrow(), /* ... */);
74//! ```
75//!
76//! ## Examples
77//!
78//! We have a plethora of [examples] in the esp-hal repository. We use
79//! an [xtask] to automate the building, running, and testing of code and
80//! examples within esp-hal.
81//!
82//! Invoke the following command in the root of the esp-hal repository to get
83//! started:
84//!
85//! ```bash
86//! cargo xtask help
87//! ```
88//!
89//! ## Creating a Project
90//!
91//! We have a [book] that explains the full esp-hal ecosystem
92//! and how to get started, it is advisable to give that a read
93//! before proceeding. We also have a [training] that covers some common
94//! scenarios with examples.
95//!
96//! We have developed a project generation tool, [esp-generate], which we
97//! recommend when starting new projects. It can be installed and run, e.g.
98//! for the ESP32-C6, as follows:
99//!
100//! ```bash
101//! cargo install esp-generate
102//! esp-generate --chip=esp32c6 your-project
103//! ```
104#![cfg_attr(
105    // Feature-gated so that this doesn't prevent gradual device bringup. Any
106    // stable driver would serve the purpose here, so this block will be part
107    // of the released documentation.
108    gpio_driver_supported,
109    doc = r#"
110## Blinky
111
112Some minimal code to blink an LED looks like this:
113
114```rust, no_run
115#![no_std]
116#![no_main]
117
118use esp_hal::{
119    clock::CpuClock,
120    gpio::{Io, Level, Output, OutputConfig},
121    main,
122    time::{Duration, Instant},
123};
124
125// You need a panic handler. Usually, you would use esp_backtrace, panic-probe, or
126// something similar, but you can also bring your own like this:
127#[panic_handler]
128fn panic(_: &core::panic::PanicInfo) -> ! {
129    esp_hal::system::software_reset()
130}
131
132#[main]
133fn main() -> ! {
134    let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
135    let peripherals = esp_hal::init(config);
136
137    // Set GPIO0 as an output, and set its state high initially.
138    let mut led = Output::new(peripherals.GPIO0, Level::High, OutputConfig::default());
139
140    loop {
141        led.toggle();
142        // Wait for half a second
143        let delay_start = Instant::now();
144        while delay_start.elapsed() < Duration::from_millis(500) {}
145    }
146}
147```
148"#
149)]
150//! ## Additional configuration
151//!
152//! Some configuration options do not fit into cargo
153//! features. These can be set via environment variables, or via cargo's `[env]`
154//! section inside `.cargo/config.toml`. Unstable options can only be
155//! enabled when the `unstable` feature is enabled for the crate. Below is a
156//! table of tunable parameters for this crate:
157#![doc = ""]
158#![doc = include_str!(concat!(env!("OUT_DIR"), "/esp_hal_config_table.md"))]
159#![doc = ""]
160//! ## Optimization level
161//!
162//! Some operations suspend the caches or change the MSPI clocks. The code that runs in that time
163//! must not call code in flash. The documentation of each operation with this requirement links to
164//! this section.
165//!
166//! To use these operations, build esp-hal at `opt-level` 2 or 3 in each profile. At `opt-level` 0
167//! or 1, each of these operations panics. At `opt-level` `s` or `z`, the link can fail with
168//! `prohibited cross reference from '.rwtext.checked'` and the name of a helper function.
169#![cfg_attr(
170    xtensa,
171    doc = "GNU ld, the default linker for the ESP32, ESP32-S2 and ESP32-S3, finds only some of these",
172    doc = "calls. The link can then pass, and the chip locks up at run time."
173)]
174//! The `Cargo.toml` of the application can set the level for esp-hal only:
175//!
176//! ```toml
177//! [profile.dev.package.esp-hal]
178//! opt-level = 2
179//!
180//! [profile.release.package.esp-hal]
181//! opt-level = 2
182//! ```
183//!
184//! With `-Z stack-protector`, the code of these operations is instrumented too. If it detects
185//! stack corruption while the caches are suspended, the panic handler cannot run, because it lives
186//! in flash, and the chip locks up instead of reporting the corruption.
187#![cfg_attr(
188    psram_supports_code_in_psram,
189    doc = "",
190    doc = "The `code-in-psram` option needs this level in every build, because its start-up runs",
191    doc = "in every firmware. The build stops at `opt-level` 0 or 1."
192)]
193#![doc = ""]
194//! ## Don't use `core::mem::forget`
195//!
196//! You should never use `core::mem::forget` on any type defined in [esp crates].
197//! Many types heavily rely on their `Drop` implementation to not leave the
198//! hardware in undefined state which can cause undefined behavior in your program.
199//!
200//! You might want to consider using [`#[deny(clippy::mem_forget)`](https://rust-lang.github.io/rust-clippy/v0.0.212/index.html#mem_forget) in your project.
201//!
202//! ## Library usage
203//!
204//! If you intend to write a library that uses esp-hal, you should import it as follows:
205//!
206//! ```toml
207//! [dependencies]
208//! esp-hal = { version = "1", default-features = false } }
209//! ```
210//!
211//! This ensures that the `rt` feature is not enabled, nor any chip features. The application that
212//! uses your library will then be able to choose the chip feature it needs and enable `rt` such
213//! that only the final user application calls [`init`].
214//!
215//! If your library depends on `unstable` features, you *must* use the `requires-unstable` feature,
216//! and *not* the unstable feature itself. Doing so, improves the quality of the error messages if a
217//! user hasn't enabled the unstable feature of esp-hal.
218//!
219//! [documentation]: https://docs.espressif.com/projects/rust/esp-hal/latest/
220//! [examples]: https://github.com/esp-rs/esp-hal/tree/main/examples
221//! [embedded-hal]: https://docs.rs/embedded-hal/latest/embedded_hal/
222//! [embedded-hal-async]: https://docs.rs/embedded-hal-async/latest/embedded_hal_async/
223//! [xtask]: https://github.com/matklad/cargo-xtask
224//! [esp-generate]: https://github.com/esp-rs/esp-generate
225//! [book]: https://docs.espressif.com/projects/rust/book/
226//! [training]: https://docs.espressif.com/projects/rust/no_std-training/
227//! [esp crates]: https://docs.espressif.com/projects/rust/book/introduction/ancillary-crates.html#esp-hal-ecosystem
228//!
229//! ## Feature Flags
230#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
231#![doc(html_logo_url = "https://docs.espressif.com/projects/rust/esp-rs-grey-bg.svg")]
232#![allow(asm_sub_register, async_fn_in_trait, stable_features)]
233#![cfg_attr(xtensa, feature(asm_experimental_arch))]
234#![deny(missing_docs, rust_2018_idioms, rustdoc::all)]
235#![allow(rustdoc::private_doc_tests)] // compile tests are done via rustdoc
236#![cfg_attr(docsrs, feature(doc_cfg, custom_inner_attributes, proc_macro_hygiene))]
237// Don't trip up on broken/private links when running semver-checks
238#![cfg_attr(
239    semver_checks,
240    allow(rustdoc::private_intra_doc_links, rustdoc::broken_intra_doc_links)
241)]
242// Do not document `cfg` gates by default.
243#![cfg_attr(docsrs, allow(invalid_doc_attributes))] // doc(auto_cfg = false) requires a new nightly (~2025-10-09+)
244#![cfg_attr(docsrs, doc(auto_cfg = false))]
245#![no_std]
246
247// MUST be the first module
248mod fmt;
249
250#[macro_use]
251extern crate esp_metadata_generated;
252
253// can't use instability on inline module definitions, see https://github.com/rust-lang/rust/issues/54727
254#[doc(hidden)]
255macro_rules! unstable_module {
256    ($(
257        $(#[$meta:meta])*
258        pub mod $module:ident;
259    )*) => {
260        $(
261            $(#[$meta])*
262            #[cfg(feature = "unstable")]
263            #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
264            pub mod $module;
265
266            $(#[$meta])*
267            #[cfg(not(feature = "unstable"))]
268            #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
269            #[allow(unused)]
270            pub(crate) mod $module;
271        )*
272    };
273}
274
275// can't use instability on inline module definitions, see https://github.com/rust-lang/rust/issues/54727
276// we don't want unstable drivers to be compiled even, unless enabled
277#[doc(hidden)]
278macro_rules! unstable_driver {
279    ($(
280        $(#[$meta:meta])*
281        pub mod $module:ident;
282    )*) => {
283        $(
284            $(#[$meta])*
285            #[cfg(feature = "unstable")]
286            #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
287            pub mod $module;
288        )*
289    };
290}
291
292use core::marker::PhantomData;
293
294pub use esp_metadata_generated::chip;
295use esp_rom_sys as _;
296#[allow(unused)]
297pub(crate) use unstable_driver;
298pub(crate) use unstable_module;
299
300metadata!("build_info", CHIP_NAME, chip!());
301metadata!(
302    "build_info",
303    MIN_CHIP_REVISION,
304    esp_config::esp_config_str!("ESP_HAL_CONFIG_MIN_CHIP_REVISION")
305);
306
307#[cfg(feature = "rt")]
308cfg_select! {
309    riscv => {
310        #[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", feature = "rt"))))]
311        #[cfg_attr(not(feature = "unstable"), doc(hidden))]
312        pub use esp_riscv_rt::{self, riscv};
313    }
314    xtensa => {
315        #[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", feature = "rt"))))]
316        #[cfg_attr(not(feature = "unstable"), doc(hidden))]
317        pub use xtensa_lx_rt::{self, xtensa_lx};
318    }
319}
320
321pub(crate) use peripherals::pac;
322pub(crate) mod private;
323
324#[cfg(any(soc_has_dport, soc_has_hp_sys, soc_has_pcr, soc_has_system))]
325pub mod clock;
326#[cfg(gpio_driver_supported)]
327pub mod gpio;
328#[cfg(i2c_master_driver_supported)]
329pub mod i2c;
330// The I2S driver is unstable, but its clock tree nodes are part of every build.
331#[cfg(i2s_driver_supported)]
332#[path = "i2s/clocks/mod.rs"]
333mod i2s_clocks;
334pub mod peripherals;
335#[cfg(all(
336    feature = "unstable",
337    any(
338        hmac_driver_supported,
339        sha_driver_supported,
340        ethernet_driver_supported,
341        mipi_dsi_driver_supported
342    )
343))]
344mod reg_access;
345#[cfg(rng_driver_supported)]
346pub mod rng;
347#[cfg(any(spi_master_driver_supported, spi_slave_driver_supported))]
348pub mod spi;
349pub mod system;
350pub mod time;
351#[cfg(uart_driver_supported)]
352pub mod uart;
353
354mod macros;
355
356#[instability::unstable]
357pub use procmacros::handler;
358#[instability::unstable]
359#[cfg(ulp_riscv_driver_supported)]
360pub use procmacros::load_lp_code;
361#[cfg(feature = "rt")]
362pub use procmacros::main;
363pub use procmacros::ram;
364
365#[instability::unstable]
366#[cfg(ulp_riscv_driver_supported)]
367pub use self::soc::lp_core;
368
369#[cfg(all(feature = "rt", feature = "exception-handler"))]
370mod exception_handler;
371
372pub mod efuse;
373pub mod interrupt;
374
375unstable_module! {
376    pub mod asynch;
377    pub mod debugger;
378    pub mod rom;
379    #[doc(hidden)]
380    pub mod sync;
381    // Drivers needed for initialization or they are tightly coupled to something else.
382    #[cfg(any(adc_driver_supported, dac_driver_supported))]
383    pub mod analog;
384    #[cfg(any(systimer_driver_supported, timergroup_driver_supported))]
385    pub mod timer;
386    #[cfg(temp_sensor_driver_supported)]
387    pub mod tsens;
388    #[cfg(soc_has_lpwr)]
389    pub mod rtc_cntl;
390    #[cfg(dma_driver_supported)]
391    pub mod dma;
392    #[cfg(etm_driver_supported)]
393    pub mod etm;
394    #[cfg(soc_has_psram)] // DMA needs some things from here
395    pub mod psram;
396}
397
398#[cfg(any(
399    sha_driver_supported,
400    rsa_driver_supported,
401    aes_driver_supported,
402    ecc_driver_supported
403))]
404mod work_queue;
405
406unstable_driver! {
407    #[cfg(aes_driver_supported)]
408    pub mod aes;
409    #[cfg(assist_debug_driver_supported)]
410    pub mod assist_debug;
411    #[cfg(canfd_driver_supported)]
412    pub mod canfd;
413    #[cfg(cordic_driver_supported)]
414    pub mod cordic;
415    pub mod delay;
416    #[cfg(dma2d_driver_supported)]
417    pub mod dma2d;
418    #[cfg(ecc_driver_supported)]
419    pub mod ecc;
420    #[cfg(flash_driver_supported)]
421    pub mod flash;
422    #[cfg(hmac_driver_supported)]
423    pub mod hmac;
424    #[cfg(i2s_driver_supported)]
425    pub mod i2s;
426    #[cfg(jpeg_driver_supported)]
427    pub mod jpeg;
428    #[cfg(soc_has_lcd_cam)]
429    pub mod lcd_cam;
430    #[cfg(ledc_driver_supported)]
431    pub mod ledc;
432    #[cfg(mcpwm_driver_supported)]
433    pub mod mcpwm;
434    #[cfg(parl_io_driver_supported)]
435    pub mod parl_io;
436    #[cfg(pcnt_driver_supported)]
437    pub mod pcnt;
438    #[cfg(pixel_accelerator_driver_supported)]
439    pub mod ppa;
440    #[cfg(rmt_driver_supported)]
441    pub mod rmt;
442    #[cfg(rsa_driver_supported)]
443    pub mod rsa;
444    #[cfg(sdmmc_driver_supported)]
445    pub mod sdmmc;
446    #[cfg(sha_driver_supported)]
447    pub mod sha;
448    #[cfg(sdm_driver_supported)]
449    pub mod sdm;
450    #[cfg(touch_driver_supported)]
451    pub mod touch;
452    #[cfg(soc_has_trace0)]
453    pub mod trace;
454    #[cfg(twai_driver_supported)]
455    pub mod twai;
456    #[cfg(any(
457        usb_otg_driver_supported,
458        usb_otg_hs_driver_supported,
459        usb_serial_jtag_driver_supported,
460    ))]
461    pub mod usb;
462    #[cfg(ethernet_driver_supported)]
463    pub mod ethernet;
464    #[cfg(mipi_dsi_driver_supported)]
465    pub mod mipi_dsi;
466}
467
468/// State of the CPU saved when entering exception or interrupt
469#[instability::unstable]
470#[cfg(feature = "rt")]
471#[allow(unused_imports)]
472pub mod trapframe {
473    #[cfg(riscv)]
474    pub use esp_riscv_rt::TrapFrame;
475    #[cfg(xtensa)]
476    pub use xtensa_lx_rt::exception::Context as TrapFrame;
477}
478
479// The `soc` module contains chip-specific implementation details and should not
480// be directly exposed.
481mod soc;
482
483// Some PAC-related utility
484use crate::pac::generic::{Readable, Reg, Resettable, W, Writable};
485
486#[allow(unused)]
487trait RegisterToggle {
488    type Reg: Readable + Resettable + Writable;
489
490    /// Toggles bits in the register, applying the given operation to set and clear them.
491    ///
492    /// More efficient than two modify calls, because it does not read the register
493    /// value twice.
494    fn toggle(&self, op: impl Fn(&mut W<Self::Reg>, bool) -> &mut W<Self::Reg>);
495}
496
497impl<REG> RegisterToggle for Reg<REG>
498where
499    REG: Readable + Resettable + Writable,
500{
501    type Reg = REG;
502
503    fn toggle(&self, op: impl Fn(&mut W<REG>, bool) -> &mut W<REG>) {
504        let bits = self.modify(|_, w| op(w, true));
505
506        self.write(|w| {
507            unsafe { w.bits(bits) };
508            op(w, false)
509        });
510    }
511}
512
513#[cfg(is_debug_build)]
514procmacros::warning! {"
515WARNING: use --release
516  We *strongly* recommend using release profile when building esp-hal.
517  The dev profile can potentially be one or more orders of magnitude
518  slower than release, and may cause issues with timing-sensitive
519  peripherals or devices.
520"}
521
522/// Panics if esp-hal is built at `opt-level` 0 or 1, because `operation` needs `opt-level` 2 or 3.
523#[inline(always)]
524#[track_caller]
525pub(crate) fn needs_optimized_build(operation: &str) {
526    if cfg!(is_debug_build) {
527        panic!(
528            "{} needs esp-hal built at opt-level 2 or 3. See \"Optimization level\" in the esp-hal \
529             documentation.",
530            operation
531        );
532    }
533}
534
535/// A marker trait for driver modes.
536///
537/// Different driver modes offer different features and different API. Using
538/// this trait as a generic parameter ensures that the driver is initialized in
539/// the correct mode.
540pub trait DriverMode: crate::private::Sealed {}
541
542#[procmacros::doc_replace]
543/// Marker type signaling that a driver is initialized in blocking mode.
544///
545/// Drivers are constructed in blocking mode by default. To learn about the
546/// differences between blocking and async drivers, see the [`Async`] mode
547/// documentation.
548///
549/// [`Async`] drivers can be converted to a [`Blocking`] driver using the
550/// `into_blocking` method, for example:
551#[cfg_attr(
552    // Feature-gated so that this doesn't prevent gradual device bringup. Any
553    // stable driver would serve the purpose here, so this block will be part
554    // of the released documentation.
555    all(uart_driver_supported, gpio_driver_supported),
556    doc = r#"
557```rust, no_run
558# {before_snippet}
559# use esp_hal::uart::{Config, Uart};
560let uart = Uart::new(peripherals.UART0, Config::default())?
561    .with_rx(peripherals.GPIO1)
562    .with_tx(peripherals.GPIO2)
563    .into_async();
564let blocking_uart = uart.into_blocking();
565# {after_snippet}
566```
567"#
568)]
569#[derive(Debug)]
570#[non_exhaustive]
571pub struct Blocking;
572
573#[procmacros::doc_replace]
574/// Marker type signaling that a driver is initialized in async mode.
575///
576/// Drivers are constructed in blocking mode by default. To set up an async
577/// driver, a [`Blocking`] driver must be converted to an `Async` driver using
578/// the `into_async` method, for example:
579#[cfg_attr(
580    // Feature-gated so that this doesn't prevent gradual device bringup. Any
581    // stable driver would serve the purpose here, so this block will be part
582    // of the released documentation.
583    all(uart_driver_supported, gpio_driver_supported),
584    doc = r#"
585```rust, no_run
586# {before_snippet}
587# use esp_hal::uart::{Config, Uart};
588let uart = Uart::new(peripherals.UART0, Config::default())?
589    .with_rx(peripherals.GPIO1)
590    .with_tx(peripherals.GPIO2)
591    .into_async();
592///
593# {after_snippet}
594```
595"#
596)]
597/// Drivers can be converted back to blocking mode using the `into_blocking`
598/// method, see [`Blocking`] documentation for more details.
599///
600/// Async mode drivers offer most of the same features as blocking drivers, but
601/// with the addition of async APIs. Interrupt-related functions are not
602/// available in async mode, as they are handled by the driver's interrupt
603/// handlers.
604///
605/// Async functions usually take up more space than their blocking counterparts,
606/// and they are generally slower. This is because async functions are implemented
607/// using a state machine that is driven by interrupts and is polled by a runtime.
608/// For short operations, the overhead of the state machine can be significant.
609/// Consider using the blocking functions on the async driver for small transfers.
610///
611/// When initializing an async driver, the driver disables user-specified
612/// interrupt handlers, and sets up internal interrupt handlers that drive the
613/// driver's async API. The driver's interrupt handlers run on the same core as
614/// the driver was initialized on. This means that the driver can not be sent
615/// across threads, to prevent incorrect concurrent access to the peripheral.
616///
617/// Switching back to blocking mode will disable the interrupt handlers and
618/// return the driver to a state where it can be sent across threads.
619#[derive(Debug)]
620#[non_exhaustive]
621pub struct Async(PhantomData<*const ()>);
622
623unsafe impl Sync for Async {}
624
625impl crate::DriverMode for Blocking {}
626impl crate::DriverMode for Async {}
627impl crate::private::Sealed for Blocking {}
628impl crate::private::Sealed for Async {}
629
630#[doc(hidden)]
631pub use private::Internal;
632
633/// Marker trait for types that can be safely used in `#[ram(unstable(persistent))]`.
634///
635/// # Safety
636///
637/// - The type must be inhabited
638/// - The type must be valid for any bit pattern of its backing memory in case a reset occurs during
639///   a write or a reset interrupts the zero initialization on first boot.
640/// - Structs must contain only `Persistable` fields and padding
641#[instability::unstable]
642pub unsafe trait Persistable: Sized {}
643
644/// Marker trait for types that can be safely used in `#[ram(reclaimed)]`.
645///
646/// # Safety
647///
648/// - The type must be some form of `MaybeUninit<T>`
649#[doc(hidden)]
650pub unsafe trait Uninit: Sized {}
651
652macro_rules! impl_persistable {
653    ($($t:ty),+) => {$(
654        unsafe impl Persistable for $t {}
655    )+};
656    (atomic $($t:ident),+) => {$(
657        unsafe impl Persistable for portable_atomic::$t {}
658    )+};
659}
660
661impl_persistable!(
662    u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, f32, f64
663);
664impl_persistable!(atomic AtomicU8, AtomicI8, AtomicU16, AtomicI16, AtomicU32, AtomicI32, AtomicUsize, AtomicIsize);
665
666unsafe impl<T: Persistable, const N: usize> Persistable for [T; N] {}
667
668unsafe impl<T> Uninit for core::mem::MaybeUninit<T> {}
669unsafe impl<T, const N: usize> Uninit for [core::mem::MaybeUninit<T>; N] {}
670
671#[doc(hidden)]
672pub mod __macro_implementation {
673    //! Private implementation details of esp-hal-procmacros.
674
675    #[instability::unstable]
676    pub const fn assert_is_zeroable<T: bytemuck::Zeroable>() {}
677
678    #[instability::unstable]
679    pub const fn assert_is_persistable<T: super::Persistable>() {}
680
681    pub const fn assert_is_uninit<T: super::Uninit>() {}
682
683    // A PSRAM static needs the code-in-PSRAM start-up, which maps PSRAM before `main`, then copies
684    // or zeroes the static.
685    #[instability::unstable]
686    pub const fn assert_psram_available() {
687        if !cfg!(code_in_psram) {
688            core::panic!("`ram(unstable(psram))` needs the `code-in-psram` option");
689        }
690    }
691
692    #[cfg(feature = "rt")]
693    #[cfg(riscv)]
694    pub use esp_riscv_rt::entry as __entry;
695    pub use static_cell;
696    #[cfg(feature = "rt")]
697    #[cfg(xtensa)]
698    pub use xtensa_lx_rt::entry as __entry;
699}
700
701use crate::clock::{ClockConfig, CpuClock};
702#[cfg(feature = "rt")]
703use crate::peripherals::Peripherals;
704
705/// A spinlock for seldom called stuff. Users assume that lock contention is not an issue.
706#[cfg(feature = "rt")]
707pub(crate) static ESP_HAL_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new();
708
709#[procmacros::doc_replace]
710/// System configuration.
711///
712/// This `struct` is marked with `#[non_exhaustive]` and cannot be instantiated
713/// directly. This is done to prevent breaking changes when new fields are added
714/// to the `struct`. Instead, use the [`Config::default()`] method to create a
715/// new instance.
716///
717/// # Examples
718///
719/// ### Default initialization
720///
721/// ```rust, no_run
722/// # {before_snippet}
723/// let peripherals = esp_hal::init(esp_hal::Config::default());
724/// # {after_snippet}
725/// ```
726///
727/// ### Custom initialization
728/// ```rust, no_run
729/// # {before_snippet}
730/// use esp_hal::{clock::CpuClock, time::Duration};
731/// let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
732/// let peripherals = esp_hal::init(config);
733/// # {after_snippet}
734/// ```
735#[non_exhaustive]
736#[derive(Default, Clone, Copy, procmacros::BuilderLite)]
737pub struct Config {
738    /// The CPU clock configuration.
739    #[builder_lite(skip)]
740    cpu_clock: ClockConfig,
741}
742
743impl Config {
744    /// Applies a clock configuration.
745    #[cfg_attr(
746        feature = "unstable",
747        doc = r"
748
749With the `unstable` feature enabled, this function accepts both [`ClockConfig`] and [`CpuClock`].
750"
751    )]
752    #[cfg(feature = "unstable")]
753    pub fn with_cpu_clock(self, cpu_clock: impl Into<ClockConfig>) -> Self {
754        Self {
755            cpu_clock: cpu_clock.into(),
756            ..self
757        }
758    }
759
760    /// Applies a clock configuration.
761    #[cfg(not(feature = "unstable"))]
762    pub fn with_cpu_clock(self, cpu_clock: CpuClock) -> Self {
763        Self {
764            cpu_clock: cpu_clock.into(),
765            ..self
766        }
767    }
768
769    /// The CPU clock configuration preset.
770    ///
771    /// # Panics
772    ///
773    /// Panics if the CPU clock configuration is not **exactly** one of the [`CpuClock`] presets
774    #[cfg_attr(feature = "unstable", deprecated(note = "Use `clock_config` instead."))] // TODO: mention ClockTree APIs once they are exposed to the user.
775    pub fn cpu_clock(&self) -> CpuClock {
776        unwrap!(
777            self.cpu_clock.try_get_preset(),
778            "CPU clock configuration is not a preset"
779        )
780    }
781
782    /// The CPU clock configuration.
783    #[instability::unstable]
784    pub fn clock_config(&self) -> ClockConfig {
785        self.cpu_clock
786    }
787}
788
789#[procmacros::doc_replace]
790/// Initializes the system.
791///
792/// Sets up the CPU clock and watchdog, then returns the peripherals and clocks.
793///
794/// # Examples
795///
796/// ```rust, no_run
797/// # {before_snippet}
798/// use esp_hal::{Config, init};
799/// let peripherals = init(Config::default());
800/// # {after_snippet}
801/// ```
802#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
803#[cfg(feature = "rt")]
804pub fn init(config: Config) -> Peripherals {
805    crate::soc::pre_init();
806
807    let min_rev = esp_config::esp_config_int!(u16, "ESP_HAL_CONFIG_MIN_CHIP_REVISION");
808    assert!(
809        crate::efuse::chip_revision() >= crate::efuse::ChipRevision::from_combined(min_rev),
810        "This chip's hardware revision is older than the minimum required \
811         v{}.{} (ESP_HAL_CONFIG_MIN_CHIP_REVISION).",
812        min_rev / 100,
813        min_rev % 100,
814    );
815
816    #[cfg(soc_cpu_has_branch_predictor)]
817    crate::soc::branch_predictor::enable();
818
819    // Have we already overflown the stack?
820    #[cfg(init_stack_ptr_range_check)]
821    crate::soc::ensure_stack_pointer_in_range();
822
823    #[cfg(stack_guard_monitoring)]
824    crate::soc::enable_main_stack_guard_monitoring();
825
826    #[cfg(all(feature = "rt", enable_pmp, riscv))]
827    crate::soc::enable_pmp();
828
829    system::disable_peripherals();
830
831    let mut peripherals = Peripherals::take();
832
833    crate::clock::init(config.clock_config());
834
835    #[cfg(code_in_psram)]
836    crate::psram::adopt_started_psram();
837
838    // RTC domain must be enabled before we try to disable
839    let mut rtc = crate::rtc_cntl::Rtc::new(peripherals.RTC_TIMER.reborrow());
840
841    #[cfg(sleep_driver_supported)]
842    crate::rtc_cntl::sleep::init(&rtc);
843
844    // Disable watchdog timers
845    #[cfg(soc_has_swd_watchdog)]
846    rtc.swd.disable();
847
848    rtc.rwdt.disable();
849
850    #[cfg(timergroup_timg0)]
851    crate::timer::timg::Wdt::<crate::peripherals::TIMG0<'static>>::new().disable();
852
853    #[cfg(timergroup_timg1)]
854    crate::timer::timg::Wdt::<crate::peripherals::TIMG1<'static>>::new().disable();
855
856    crate::time::implem::time_init();
857
858    #[cfg(gpio_driver_supported)]
859    crate::gpio::interrupt::bind_default_interrupt_handler();
860
861    unsafe {
862        esp_rom_sys::init_syscall_table();
863    }
864
865    #[cfg(all(riscv, write_vec_table_monitoring))]
866    crate::soc::setup_trap_section_protection();
867
868    #[cfg(multi_core)]
869    crate::interrupt::ipc::install();
870
871    peripherals
872}