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#![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#![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#![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)] #![cfg_attr(docsrs, feature(doc_cfg, custom_inner_attributes, proc_macro_hygiene))]
237#![cfg_attr(
239 semver_checks,
240 allow(rustdoc::private_intra_doc_links, rustdoc::broken_intra_doc_links)
241)]
242#![cfg_attr(docsrs, allow(invalid_doc_attributes))] #![cfg_attr(docsrs, doc(auto_cfg = false))]
245#![no_std]
246
247mod fmt;
249
250#[macro_use]
251extern crate esp_metadata_generated;
252
253#[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#[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#[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 #[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)] 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#[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
479mod soc;
482
483use crate::pac::generic::{Readable, Reg, Resettable, W, Writable};
485
486#[allow(unused)]
487trait RegisterToggle {
488 type Reg: Readable + Resettable + Writable;
489
490 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#[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
535pub trait DriverMode: crate::private::Sealed {}
541
542#[procmacros::doc_replace]
543#[cfg_attr(
552 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#[cfg_attr(
580 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#[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#[instability::unstable]
642pub unsafe trait Persistable: Sized {}
643
644#[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 #[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 #[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#[cfg(feature = "rt")]
707pub(crate) static ESP_HAL_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new();
708
709#[procmacros::doc_replace]
710#[non_exhaustive]
736#[derive(Default, Clone, Copy, procmacros::BuilderLite)]
737pub struct Config {
738 #[builder_lite(skip)]
740 cpu_clock: ClockConfig,
741}
742
743impl Config {
744 #[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 #[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 #[cfg_attr(feature = "unstable", deprecated(note = "Use `clock_config` instead."))] 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 #[instability::unstable]
784 pub fn clock_config(&self) -> ClockConfig {
785 self.cpu_clock
786 }
787}
788
789#[procmacros::doc_replace]
790#[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 #[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 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 #[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}