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 other levels,
167//! the link can fail with `prohibited cross reference from '.rwtext.checked'` and the
168//! name of a helper function. GNU ld, the default linker for the ESP32, ESP32-S2 and ESP32-S3,
169//! finds only some of these calls. The link can then pass, and the chip locks up at run time. The
170//! `Cargo.toml` of the application can set the level for esp-hal only:
171//!
172//! ```toml
173//! [profile.dev.package.esp-hal]
174//! opt-level = 2
175//!
176//! [profile.release.package.esp-hal]
177//! opt-level = 2
178//! ```
179//!
180//! ## Don't use `core::mem::forget`
181//!
182//! You should never use `core::mem::forget` on any type defined in [esp crates].
183//! Many types heavily rely on their `Drop` implementation to not leave the
184//! hardware in undefined state which can cause undefined behavior in your program.
185//!
186//! 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.
187//!
188//! ## Library usage
189//!
190//! If you intend to write a library that uses esp-hal, you should import it as follows:
191//!
192//! ```toml
193//! [dependencies]
194//! esp-hal = { version = "1", default-features = false } }
195//! ```
196//!
197//! This ensures that the `rt` feature is not enabled, nor any chip features. The application that
198//! uses your library will then be able to choose the chip feature it needs and enable `rt` such
199//! that only the final user application calls [`init`].
200//!
201//! If your library depends on `unstable` features, you *must* use the `requires-unstable` feature,
202//! and *not* the unstable feature itself. Doing so, improves the quality of the error messages if a
203//! user hasn't enabled the unstable feature of esp-hal.
204//!
205//! [documentation]: https://docs.espressif.com/projects/rust/esp-hal/latest/
206//! [examples]: https://github.com/esp-rs/esp-hal/tree/main/examples
207//! [embedded-hal]: https://docs.rs/embedded-hal/latest/embedded_hal/
208//! [embedded-hal-async]: https://docs.rs/embedded-hal-async/latest/embedded_hal_async/
209//! [xtask]: https://github.com/matklad/cargo-xtask
210//! [esp-generate]: https://github.com/esp-rs/esp-generate
211//! [book]: https://docs.espressif.com/projects/rust/book/
212//! [training]: https://docs.espressif.com/projects/rust/no_std-training/
213//! [esp crates]: https://docs.espressif.com/projects/rust/book/introduction/ancillary-crates.html#esp-hal-ecosystem
214//!
215//! ## Feature Flags
216#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
217#![doc(html_logo_url = "https://docs.espressif.com/projects/rust/esp-rs-grey-bg.svg")]
218#![allow(asm_sub_register, async_fn_in_trait, stable_features)]
219#![cfg_attr(xtensa, feature(asm_experimental_arch))]
220#![deny(missing_docs, rust_2018_idioms, rustdoc::all)]
221#![allow(rustdoc::private_doc_tests)] // compile tests are done via rustdoc
222#![cfg_attr(docsrs, feature(doc_cfg, custom_inner_attributes, proc_macro_hygiene))]
223// Don't trip up on broken/private links when running semver-checks
224#![cfg_attr(
225    semver_checks,
226    allow(rustdoc::private_intra_doc_links, rustdoc::broken_intra_doc_links)
227)]
228// Do not document `cfg` gates by default.
229#![cfg_attr(docsrs, allow(invalid_doc_attributes))] // doc(auto_cfg = false) requires a new nightly (~2025-10-09+)
230#![cfg_attr(docsrs, doc(auto_cfg = false))]
231#![no_std]
232
233// MUST be the first module
234mod fmt;
235
236#[macro_use]
237extern crate esp_metadata_generated;
238
239// can't use instability on inline module definitions, see https://github.com/rust-lang/rust/issues/54727
240#[doc(hidden)]
241macro_rules! unstable_module {
242    ($(
243        $(#[$meta:meta])*
244        pub mod $module:ident;
245    )*) => {
246        $(
247            $(#[$meta])*
248            #[cfg(feature = "unstable")]
249            #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
250            pub mod $module;
251
252            $(#[$meta])*
253            #[cfg(not(feature = "unstable"))]
254            #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
255            #[allow(unused)]
256            pub(crate) mod $module;
257        )*
258    };
259}
260
261// can't use instability on inline module definitions, see https://github.com/rust-lang/rust/issues/54727
262// we don't want unstable drivers to be compiled even, unless enabled
263#[doc(hidden)]
264macro_rules! unstable_driver {
265    ($(
266        $(#[$meta:meta])*
267        pub mod $module:ident;
268    )*) => {
269        $(
270            $(#[$meta])*
271            #[cfg(feature = "unstable")]
272            #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
273            pub mod $module;
274        )*
275    };
276}
277
278use core::marker::PhantomData;
279
280pub use esp_metadata_generated::chip;
281use esp_rom_sys as _;
282#[allow(unused)]
283pub(crate) use unstable_driver;
284pub(crate) use unstable_module;
285
286metadata!("build_info", CHIP_NAME, chip!());
287metadata!(
288    "build_info",
289    MIN_CHIP_REVISION,
290    esp_config::esp_config_str!("ESP_HAL_CONFIG_MIN_CHIP_REVISION")
291);
292
293#[cfg(feature = "rt")]
294cfg_select! {
295    riscv => {
296        #[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", feature = "rt"))))]
297        #[cfg_attr(not(feature = "unstable"), doc(hidden))]
298        pub use esp_riscv_rt::{self, riscv};
299    }
300    xtensa => {
301        #[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", feature = "rt"))))]
302        #[cfg_attr(not(feature = "unstable"), doc(hidden))]
303        pub use xtensa_lx_rt::{self, xtensa_lx};
304    }
305}
306
307pub(crate) use peripherals::pac;
308pub(crate) mod private;
309
310#[cfg(any(soc_has_dport, soc_has_hp_sys, soc_has_pcr, soc_has_system))]
311pub mod clock;
312#[cfg(gpio_driver_supported)]
313pub mod gpio;
314#[cfg(i2c_master_driver_supported)]
315pub mod i2c;
316// The I2S driver is unstable, but its clock tree nodes are part of every build.
317#[cfg(i2s_driver_supported)]
318#[path = "i2s/clocks/mod.rs"]
319mod i2s_clocks;
320pub mod peripherals;
321#[cfg(all(
322    feature = "unstable",
323    any(
324        hmac_driver_supported,
325        sha_driver_supported,
326        ethernet_driver_supported,
327        mipi_dsi_driver_supported
328    )
329))]
330mod reg_access;
331#[cfg(rng_driver_supported)]
332pub mod rng;
333#[cfg(any(spi_master_driver_supported, spi_slave_driver_supported))]
334pub mod spi;
335pub mod system;
336pub mod time;
337#[cfg(uart_driver_supported)]
338pub mod uart;
339
340mod macros;
341
342#[instability::unstable]
343pub use procmacros::handler;
344#[instability::unstable]
345#[cfg(ulp_riscv_driver_supported)]
346pub use procmacros::load_lp_code;
347#[cfg(feature = "rt")]
348pub use procmacros::main;
349pub use procmacros::ram;
350
351#[instability::unstable]
352#[cfg(ulp_riscv_driver_supported)]
353pub use self::soc::lp_core;
354
355#[cfg(all(feature = "rt", feature = "exception-handler"))]
356mod exception_handler;
357
358pub mod efuse;
359pub mod interrupt;
360
361unstable_module! {
362    pub mod asynch;
363    pub mod debugger;
364    pub mod rom;
365    #[doc(hidden)]
366    pub mod sync;
367    // Drivers needed for initialization or they are tightly coupled to something else.
368    #[cfg(any(adc_driver_supported, dac_driver_supported))]
369    pub mod analog;
370    #[cfg(any(systimer_driver_supported, timergroup_driver_supported))]
371    pub mod timer;
372    #[cfg(temp_sensor_driver_supported)]
373    pub mod tsens;
374    #[cfg(soc_has_lpwr)]
375    pub mod rtc_cntl;
376    #[cfg(dma_driver_supported)]
377    pub mod dma;
378    #[cfg(etm_driver_supported)]
379    pub mod etm;
380    #[cfg(soc_has_psram)] // DMA needs some things from here
381    pub mod psram;
382}
383
384#[cfg(any(
385    sha_driver_supported,
386    rsa_driver_supported,
387    aes_driver_supported,
388    ecc_driver_supported
389))]
390mod work_queue;
391
392unstable_driver! {
393    #[cfg(aes_driver_supported)]
394    pub mod aes;
395    #[cfg(assist_debug_driver_supported)]
396    pub mod assist_debug;
397    #[cfg(canfd_driver_supported)]
398    pub mod canfd;
399    #[cfg(cordic_driver_supported)]
400    pub mod cordic;
401    pub mod delay;
402    #[cfg(ecc_driver_supported)]
403    pub mod ecc;
404    #[cfg(flash_driver_supported)]
405    pub mod flash;
406    #[cfg(hmac_driver_supported)]
407    pub mod hmac;
408    #[cfg(i2s_driver_supported)]
409    pub mod i2s;
410    #[cfg(soc_has_lcd_cam)]
411    pub mod lcd_cam;
412    #[cfg(ledc_driver_supported)]
413    pub mod ledc;
414    #[cfg(mcpwm_driver_supported)]
415    pub mod mcpwm;
416    #[cfg(parl_io_driver_supported)]
417    pub mod parl_io;
418    #[cfg(pcnt_driver_supported)]
419    pub mod pcnt;
420    #[cfg(pixel_accelerator_driver_supported)]
421    pub mod ppa;
422    #[cfg(rmt_driver_supported)]
423    pub mod rmt;
424    #[cfg(rsa_driver_supported)]
425    pub mod rsa;
426    #[cfg(sdmmc_driver_supported)]
427    pub mod sdmmc;
428    #[cfg(sha_driver_supported)]
429    pub mod sha;
430    #[cfg(sdm_driver_supported)]
431    pub mod sdm;
432    #[cfg(touch_driver_supported)]
433    pub mod touch;
434    #[cfg(soc_has_trace0)]
435    pub mod trace;
436    #[cfg(twai_driver_supported)]
437    pub mod twai;
438    #[cfg(any(
439        usb_otg_driver_supported,
440        usb_otg_hs_driver_supported,
441        usb_serial_jtag_driver_supported,
442    ))]
443    pub mod usb;
444    #[cfg(ethernet_driver_supported)]
445    pub mod ethernet;
446    #[cfg(mipi_dsi_driver_supported)]
447    pub mod mipi_dsi;
448}
449
450/// State of the CPU saved when entering exception or interrupt
451#[instability::unstable]
452#[cfg(feature = "rt")]
453#[allow(unused_imports)]
454pub mod trapframe {
455    #[cfg(riscv)]
456    pub use esp_riscv_rt::TrapFrame;
457    #[cfg(xtensa)]
458    pub use xtensa_lx_rt::exception::Context as TrapFrame;
459}
460
461// The `soc` module contains chip-specific implementation details and should not
462// be directly exposed.
463mod soc;
464
465// Some PAC-related utility
466use crate::pac::generic::{Readable, Reg, Resettable, W, Writable};
467
468#[allow(unused)]
469trait RegisterToggle {
470    type Reg: Readable + Resettable + Writable;
471
472    /// Toggles bits in the register, applying the given operation to set and clear them.
473    ///
474    /// More efficient than two modify calls, because it does not read the register
475    /// value twice.
476    fn toggle(&self, op: impl Fn(&mut W<Self::Reg>, bool) -> &mut W<Self::Reg>);
477}
478
479impl<REG> RegisterToggle for Reg<REG>
480where
481    REG: Readable + Resettable + Writable,
482{
483    type Reg = REG;
484
485    fn toggle(&self, op: impl Fn(&mut W<REG>, bool) -> &mut W<REG>) {
486        let bits = self.modify(|_, w| op(w, true));
487
488        self.write(|w| {
489            unsafe { w.bits(bits) };
490            op(w, false)
491        });
492    }
493}
494
495#[cfg(is_debug_build)]
496procmacros::warning! {"
497WARNING: use --release
498  We *strongly* recommend using release profile when building esp-hal.
499  The dev profile can potentially be one or more orders of magnitude
500  slower than release, and may cause issues with timing-sensitive
501  peripherals or devices.
502"}
503
504/// A marker trait for driver modes.
505///
506/// Different driver modes offer different features and different API. Using
507/// this trait as a generic parameter ensures that the driver is initialized in
508/// the correct mode.
509pub trait DriverMode: crate::private::Sealed {}
510
511#[procmacros::doc_replace]
512/// Marker type signaling that a driver is initialized in blocking mode.
513///
514/// Drivers are constructed in blocking mode by default. To learn about the
515/// differences between blocking and async drivers, see the [`Async`] mode
516/// documentation.
517///
518/// [`Async`] drivers can be converted to a [`Blocking`] driver using the
519/// `into_blocking` method, for example:
520#[cfg_attr(
521    // Feature-gated so that this doesn't prevent gradual device bringup. Any
522    // stable driver would serve the purpose here, so this block will be part
523    // of the released documentation.
524    all(uart_driver_supported, gpio_driver_supported),
525    doc = r#"
526```rust, no_run
527# {before_snippet}
528# use esp_hal::uart::{Config, Uart};
529let uart = Uart::new(peripherals.UART0, Config::default())?
530    .with_rx(peripherals.GPIO1)
531    .with_tx(peripherals.GPIO2)
532    .into_async();
533let blocking_uart = uart.into_blocking();
534# {after_snippet}
535```
536"#
537)]
538#[derive(Debug)]
539#[non_exhaustive]
540pub struct Blocking;
541
542#[procmacros::doc_replace]
543/// Marker type signaling that a driver is initialized in async mode.
544///
545/// Drivers are constructed in blocking mode by default. To set up an async
546/// driver, a [`Blocking`] driver must be converted to an `Async` driver using
547/// the `into_async` method, for example:
548#[cfg_attr(
549    // Feature-gated so that this doesn't prevent gradual device bringup. Any
550    // stable driver would serve the purpose here, so this block will be part
551    // of the released documentation.
552    all(uart_driver_supported, gpio_driver_supported),
553    doc = r#"
554```rust, no_run
555# {before_snippet}
556# use esp_hal::uart::{Config, Uart};
557let uart = Uart::new(peripherals.UART0, Config::default())?
558    .with_rx(peripherals.GPIO1)
559    .with_tx(peripherals.GPIO2)
560    .into_async();
561///
562# {after_snippet}
563```
564"#
565)]
566/// Drivers can be converted back to blocking mode using the `into_blocking`
567/// method, see [`Blocking`] documentation for more details.
568///
569/// Async mode drivers offer most of the same features as blocking drivers, but
570/// with the addition of async APIs. Interrupt-related functions are not
571/// available in async mode, as they are handled by the driver's interrupt
572/// handlers.
573///
574/// Async functions usually take up more space than their blocking counterparts,
575/// and they are generally slower. This is because async functions are implemented
576/// using a state machine that is driven by interrupts and is polled by a runtime.
577/// For short operations, the overhead of the state machine can be significant.
578/// Consider using the blocking functions on the async driver for small transfers.
579///
580/// When initializing an async driver, the driver disables user-specified
581/// interrupt handlers, and sets up internal interrupt handlers that drive the
582/// driver's async API. The driver's interrupt handlers run on the same core as
583/// the driver was initialized on. This means that the driver can not be sent
584/// across threads, to prevent incorrect concurrent access to the peripheral.
585///
586/// Switching back to blocking mode will disable the interrupt handlers and
587/// return the driver to a state where it can be sent across threads.
588#[derive(Debug)]
589#[non_exhaustive]
590pub struct Async(PhantomData<*const ()>);
591
592unsafe impl Sync for Async {}
593
594impl crate::DriverMode for Blocking {}
595impl crate::DriverMode for Async {}
596impl crate::private::Sealed for Blocking {}
597impl crate::private::Sealed for Async {}
598
599#[doc(hidden)]
600pub use private::Internal;
601
602/// Marker trait for types that can be safely used in `#[ram(unstable(persistent))]`.
603///
604/// # Safety
605///
606/// - The type must be inhabited
607/// - The type must be valid for any bit pattern of its backing memory in case a reset occurs during
608///   a write or a reset interrupts the zero initialization on first boot.
609/// - Structs must contain only `Persistable` fields and padding
610#[instability::unstable]
611pub unsafe trait Persistable: Sized {}
612
613/// Marker trait for types that can be safely used in `#[ram(reclaimed)]`.
614///
615/// # Safety
616///
617/// - The type must be some form of `MaybeUninit<T>`
618#[doc(hidden)]
619pub unsafe trait Uninit: Sized {}
620
621macro_rules! impl_persistable {
622    ($($t:ty),+) => {$(
623        unsafe impl Persistable for $t {}
624    )+};
625    (atomic $($t:ident),+) => {$(
626        unsafe impl Persistable for portable_atomic::$t {}
627    )+};
628}
629
630impl_persistable!(
631    u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, f32, f64
632);
633impl_persistable!(atomic AtomicU8, AtomicI8, AtomicU16, AtomicI16, AtomicU32, AtomicI32, AtomicUsize, AtomicIsize);
634
635unsafe impl<T: Persistable, const N: usize> Persistable for [T; N] {}
636
637unsafe impl<T> Uninit for core::mem::MaybeUninit<T> {}
638unsafe impl<T, const N: usize> Uninit for [core::mem::MaybeUninit<T>; N] {}
639
640#[doc(hidden)]
641pub mod __macro_implementation {
642    //! Private implementation details of esp-hal-procmacros.
643
644    #[instability::unstable]
645    pub const fn assert_is_zeroable<T: bytemuck::Zeroable>() {}
646
647    #[instability::unstable]
648    pub const fn assert_is_persistable<T: super::Persistable>() {}
649
650    pub const fn assert_is_uninit<T: super::Uninit>() {}
651
652    #[cfg(feature = "rt")]
653    #[cfg(riscv)]
654    pub use esp_riscv_rt::entry as __entry;
655    pub use static_cell;
656    #[cfg(feature = "rt")]
657    #[cfg(xtensa)]
658    pub use xtensa_lx_rt::entry as __entry;
659}
660
661use crate::clock::{ClockConfig, CpuClock};
662#[cfg(feature = "rt")]
663use crate::peripherals::Peripherals;
664
665/// A spinlock for seldom called stuff. Users assume that lock contention is not an issue.
666#[cfg(feature = "rt")]
667pub(crate) static ESP_HAL_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new();
668
669#[procmacros::doc_replace]
670/// System configuration.
671///
672/// This `struct` is marked with `#[non_exhaustive]` and cannot be instantiated
673/// directly. This is done to prevent breaking changes when new fields are added
674/// to the `struct`. Instead, use the [`Config::default()`] method to create a
675/// new instance.
676///
677/// # Examples
678///
679/// ### Default initialization
680///
681/// ```rust, no_run
682/// # {before_snippet}
683/// let peripherals = esp_hal::init(esp_hal::Config::default());
684/// # {after_snippet}
685/// ```
686///
687/// ### Custom initialization
688/// ```rust, no_run
689/// # {before_snippet}
690/// use esp_hal::{clock::CpuClock, time::Duration};
691/// let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
692/// let peripherals = esp_hal::init(config);
693/// # {after_snippet}
694/// ```
695#[non_exhaustive]
696#[derive(Default, Clone, Copy, procmacros::BuilderLite)]
697pub struct Config {
698    /// The CPU clock configuration.
699    #[builder_lite(skip)]
700    cpu_clock: ClockConfig,
701}
702
703impl Config {
704    /// Applies a clock configuration.
705    #[cfg_attr(
706        feature = "unstable",
707        doc = r"
708
709With the `unstable` feature enabled, this function accepts both [`ClockConfig`] and [`CpuClock`].
710"
711    )]
712    #[cfg(feature = "unstable")]
713    pub fn with_cpu_clock(self, cpu_clock: impl Into<ClockConfig>) -> Self {
714        Self {
715            cpu_clock: cpu_clock.into(),
716            ..self
717        }
718    }
719
720    /// Applies a clock configuration.
721    #[cfg(not(feature = "unstable"))]
722    pub fn with_cpu_clock(self, cpu_clock: CpuClock) -> Self {
723        Self {
724            cpu_clock: cpu_clock.into(),
725            ..self
726        }
727    }
728
729    /// The CPU clock configuration preset.
730    ///
731    /// # Panics
732    ///
733    /// Panics if the CPU clock configuration is not **exactly** one of the [`CpuClock`] presets
734    #[cfg_attr(feature = "unstable", deprecated(note = "Use `clock_config` instead."))] // TODO: mention ClockTree APIs once they are exposed to the user.
735    pub fn cpu_clock(&self) -> CpuClock {
736        unwrap!(
737            self.cpu_clock.try_get_preset(),
738            "CPU clock configuration is not a preset"
739        )
740    }
741
742    /// The CPU clock configuration.
743    #[instability::unstable]
744    pub fn clock_config(&self) -> ClockConfig {
745        self.cpu_clock
746    }
747}
748
749#[procmacros::doc_replace]
750/// Initializes the system.
751///
752/// Sets up the CPU clock and watchdog, then returns the peripherals and clocks.
753///
754/// # Examples
755///
756/// ```rust, no_run
757/// # {before_snippet}
758/// use esp_hal::{Config, init};
759/// let peripherals = init(Config::default());
760/// # {after_snippet}
761/// ```
762#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
763#[cfg(feature = "rt")]
764pub fn init(config: Config) -> Peripherals {
765    crate::soc::pre_init();
766
767    let min_rev = esp_config::esp_config_int!(u16, "ESP_HAL_CONFIG_MIN_CHIP_REVISION");
768    assert!(
769        crate::efuse::chip_revision() >= crate::efuse::ChipRevision::from_combined(min_rev),
770        "This chip's hardware revision is older than the minimum required \
771         v{}.{} (ESP_HAL_CONFIG_MIN_CHIP_REVISION).",
772        min_rev / 100,
773        min_rev % 100,
774    );
775
776    #[cfg(soc_cpu_has_branch_predictor)]
777    crate::soc::branch_predictor::enable();
778
779    // Have we already overflown the stack?
780    #[cfg(init_stack_ptr_range_check)]
781    crate::soc::ensure_stack_pointer_in_range();
782
783    #[cfg(stack_guard_monitoring)]
784    crate::soc::enable_main_stack_guard_monitoring();
785
786    #[cfg(all(feature = "rt", enable_pmp, riscv))]
787    crate::soc::enable_pmp();
788
789    system::disable_peripherals();
790
791    let mut peripherals = Peripherals::take();
792
793    crate::clock::init(config.clock_config());
794
795    // RTC domain must be enabled before we try to disable
796    let mut rtc = crate::rtc_cntl::Rtc::new(peripherals.RTC_TIMER.reborrow());
797
798    #[cfg(sleep_driver_supported)]
799    crate::rtc_cntl::sleep::init(&rtc);
800
801    // Disable watchdog timers
802    #[cfg(soc_has_swd_watchdog)]
803    rtc.swd.disable();
804
805    rtc.rwdt.disable();
806
807    #[cfg(timergroup_timg0)]
808    crate::timer::timg::Wdt::<crate::peripherals::TIMG0<'static>>::new().disable();
809
810    #[cfg(timergroup_timg1)]
811    crate::timer::timg::Wdt::<crate::peripherals::TIMG1<'static>>::new().disable();
812
813    crate::time::implem::time_init();
814
815    #[cfg(gpio_driver_supported)]
816    crate::gpio::interrupt::bind_default_interrupt_handler();
817
818    unsafe {
819        esp_rom_sys::init_syscall_table();
820    }
821
822    #[cfg(all(riscv, write_vec_table_monitoring))]
823    crate::soc::setup_trap_section_protection();
824
825    #[cfg(multi_core)]
826    crate::interrupt::ipc::install();
827
828    peripherals
829}