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
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#![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>"#)]
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)] #![cfg_attr(docsrs, feature(doc_cfg, custom_inner_attributes, proc_macro_hygiene))]
223#![cfg_attr(
225 semver_checks,
226 allow(rustdoc::private_intra_doc_links, rustdoc::broken_intra_doc_links)
227)]
228#![cfg_attr(docsrs, allow(invalid_doc_attributes))] #![cfg_attr(docsrs, doc(auto_cfg = false))]
231#![no_std]
232
233mod fmt;
235
236#[macro_use]
237extern crate esp_metadata_generated;
238
239#[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#[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#[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 #[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)] 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#[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
461mod soc;
464
465use crate::pac::generic::{Readable, Reg, Resettable, W, Writable};
467
468#[allow(unused)]
469trait RegisterToggle {
470 type Reg: Readable + Resettable + Writable;
471
472 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
504pub trait DriverMode: crate::private::Sealed {}
510
511#[procmacros::doc_replace]
512#[cfg_attr(
521 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#[cfg_attr(
549 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#[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#[instability::unstable]
611pub unsafe trait Persistable: Sized {}
612
613#[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 #[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#[cfg(feature = "rt")]
667pub(crate) static ESP_HAL_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new();
668
669#[procmacros::doc_replace]
670#[non_exhaustive]
696#[derive(Default, Clone, Copy, procmacros::BuilderLite)]
697pub struct Config {
698 #[builder_lite(skip)]
700 cpu_clock: ClockConfig,
701}
702
703impl Config {
704 #[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 #[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 #[cfg_attr(feature = "unstable", deprecated(note = "Use `clock_config` instead."))] 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 #[instability::unstable]
744 pub fn clock_config(&self) -> ClockConfig {
745 self.cpu_clock
746 }
747}
748
749#[procmacros::doc_replace]
750#[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 #[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 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 #[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}