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#![doc = concat!("**", chip_pretty!(), "**")]
9# driver and you
44don't 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#![cfg_attr(
105 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#![doc = ""]
158#![doc = include_str!(concat!(env!("OUT_DIR"), "/esp_hal_config_table.md"))]
159#![doc = ""]
160#![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)] #![cfg_attr(docsrs, feature(doc_cfg, custom_inner_attributes, proc_macro_hygiene))]
203#![cfg_attr(
205 semver_checks,
206 allow(rustdoc::private_intra_doc_links, rustdoc::broken_intra_doc_links)
207)]
208#![cfg_attr(docsrs, allow(invalid_doc_attributes))] #![cfg_attr(docsrs, doc(auto_cfg = false))]
211#![no_std]
212
213mod fmt;
215
216#[macro_use]
217extern crate esp_metadata_generated;
218
219#[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#[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 #[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)] 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#[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
429mod soc;
432
433use crate::pac::generic::{Readable, Reg, Resettable, W, Writable};
435
436#[allow(unused)]
437trait RegisterToggle {
438 type Reg: Readable + Resettable + Writable;
439
440 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 and/or devices.
470"}
471
472pub trait DriverMode: crate::private::Sealed {}
478
479#[procmacros::doc_replace]
480#[cfg_attr(
489 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#[cfg_attr(
517 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#[derive(Debug)]
558#[non_exhaustive]
559pub struct Async(PhantomData<*const ()>);
560
561unsafe impl Sync for Async {}
562
563impl crate::DriverMode for Blocking {}
564impl crate::DriverMode for Async {}
565impl crate::private::Sealed for Blocking {}
566impl crate::private::Sealed for Async {}
567
568#[doc(hidden)]
569pub use private::Internal;
570
571#[instability::unstable]
580pub unsafe trait Persistable: Sized {}
581
582#[doc(hidden)]
588pub unsafe trait Uninit: Sized {}
589
590macro_rules! impl_persistable {
591 ($($t:ty),+) => {$(
592 unsafe impl Persistable for $t {}
593 )+};
594 (atomic $($t:ident),+) => {$(
595 unsafe impl Persistable for portable_atomic::$t {}
596 )+};
597}
598
599impl_persistable!(
600 u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, f32, f64
601);
602impl_persistable!(atomic AtomicU8, AtomicI8, AtomicU16, AtomicI16, AtomicU32, AtomicI32, AtomicUsize, AtomicIsize);
603
604unsafe impl<T: Persistable, const N: usize> Persistable for [T; N] {}
605
606unsafe impl<T> Uninit for core::mem::MaybeUninit<T> {}
607unsafe impl<T, const N: usize> Uninit for [core::mem::MaybeUninit<T>; N] {}
608
609#[doc(hidden)]
610pub mod __macro_implementation {
611 #[instability::unstable]
614 pub const fn assert_is_zeroable<T: bytemuck::Zeroable>() {}
615
616 #[instability::unstable]
617 pub const fn assert_is_persistable<T: super::Persistable>() {}
618
619 pub const fn assert_is_uninit<T: super::Uninit>() {}
620
621 #[cfg(feature = "rt")]
622 #[cfg(riscv)]
623 pub use esp_riscv_rt::entry as __entry;
624 pub use static_cell;
625 #[cfg(feature = "rt")]
626 #[cfg(xtensa)]
627 pub use xtensa_lx_rt::entry as __entry;
628}
629
630use crate::clock::{ClockConfig, CpuClock};
631#[cfg(feature = "rt")]
632use crate::peripherals::Peripherals;
633
634#[cfg(feature = "rt")]
636pub(crate) static ESP_HAL_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new();
637
638#[procmacros::doc_replace]
639#[non_exhaustive]
665#[derive(Default, Clone, Copy, procmacros::BuilderLite)]
666pub struct Config {
667 #[builder_lite(skip)]
669 cpu_clock: ClockConfig,
670}
671
672impl Config {
673 #[cfg_attr(
675 feature = "unstable",
676 doc = r"
677
678With the `unstable` feature enabled, this function accepts both [`ClockConfig`] and [`CpuClock`].
679"
680 )]
681 #[cfg(feature = "unstable")]
682 pub fn with_cpu_clock(self, cpu_clock: impl Into<ClockConfig>) -> Self {
683 Self {
684 cpu_clock: cpu_clock.into(),
685 ..self
686 }
687 }
688
689 #[cfg(not(feature = "unstable"))]
691 pub fn with_cpu_clock(self, cpu_clock: CpuClock) -> Self {
692 Self {
693 cpu_clock: cpu_clock.into(),
694 ..self
695 }
696 }
697
698 #[cfg_attr(feature = "unstable", deprecated(note = "Use `clock_config` instead."))] pub fn cpu_clock(&self) -> CpuClock {
706 unwrap!(
707 self.cpu_clock.try_get_preset(),
708 "CPU clock configuration is not a preset"
709 )
710 }
711
712 #[instability::unstable]
714 pub fn clock_config(&self) -> ClockConfig {
715 self.cpu_clock
716 }
717}
718
719#[procmacros::doc_replace]
720#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
734#[cfg(feature = "rt")]
735pub fn init(config: Config) -> Peripherals {
736 crate::soc::pre_init();
737
738 let min_rev = esp_config::esp_config_int!(u16, "ESP_HAL_CONFIG_MIN_CHIP_REVISION");
739 assert!(
740 crate::efuse::chip_revision() >= crate::efuse::ChipRevision::from_combined(min_rev),
741 "This chip's hardware revision is older than the minimum required \
742 v{}.{} (ESP_HAL_CONFIG_MIN_CHIP_REVISION).",
743 min_rev / 100,
744 min_rev % 100,
745 );
746
747 #[cfg(soc_cpu_has_branch_predictor)]
748 crate::soc::enable_branch_predictor();
749
750 #[cfg(init_stack_ptr_range_check)]
752 crate::soc::ensure_stack_pointer_in_range();
753
754 #[cfg(stack_guard_monitoring)]
755 crate::soc::enable_main_stack_guard_monitoring();
756
757 #[cfg(all(feature = "rt", enable_pmp, riscv))]
758 crate::soc::enable_pmp();
759
760 system::disable_peripherals();
761
762 let mut peripherals = Peripherals::take();
763
764 crate::clock::init(config.clock_config());
765
766 let mut rtc = crate::rtc_cntl::Rtc::new(peripherals.RTC_TIMER.reborrow());
768
769 #[cfg(sleep_driver_supported)]
770 crate::rtc_cntl::sleep::init(&rtc);
771
772 #[cfg(soc_has_swd_watchdog)]
774 rtc.swd.disable();
775
776 rtc.rwdt.disable();
777
778 #[cfg(timergroup_timg0)]
779 crate::timer::timg::Wdt::<crate::peripherals::TIMG0<'static>>::new().disable();
780
781 #[cfg(timergroup_timg1)]
782 crate::timer::timg::Wdt::<crate::peripherals::TIMG1<'static>>::new().disable();
783
784 crate::time::implem::time_init();
785
786 #[cfg(gpio_driver_supported)]
787 crate::gpio::interrupt::bind_default_interrupt_handler();
788
789 unsafe {
790 esp_rom_sys::init_syscall_table();
791 }
792
793 #[cfg(all(riscv, write_vec_table_monitoring))]
794 crate::soc::setup_trap_section_protection();
795
796 peripherals
797}