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