Skip to main content

ch32_hal/
lib.rs

1#![no_std]
2#![allow(static_mut_refs, unexpected_cfgs)]
3
4use core::future::Future;
5
6pub use ch32_metapac as pac;
7pub(crate) use embassy_hal_internal::{impl_peripheral, peripherals_definition, peripherals_struct};
8pub use embassy_hal_internal::{Peri, PeripheralType};
9#[cfg(feature = "rt")]
10pub use qingke_rt::{entry, interrupt};
11
12// This must go FIRST so that all the other modules see its macros.
13include!(concat!(env!("OUT_DIR"), "/_macros.rs"));
14
15pub(crate) mod internal;
16
17mod macros;
18
19pub mod time;
20/// Operating modes for peripherals.
21pub mod mode {
22    trait SealedMode {}
23
24    /// Operating mode for a peripheral.
25    #[allow(private_bounds)]
26    pub trait Mode: SealedMode {}
27
28    macro_rules! impl_mode {
29        ($name:ident) => {
30            impl SealedMode for $name {}
31            impl Mode for $name {}
32        };
33    }
34
35    /// Blocking mode.
36    pub struct Blocking;
37    /// Async mode.
38    pub struct Async;
39    /// NB mode.
40    pub struct NonBlocking;
41
42    impl_mode!(Blocking);
43    impl_mode!(Async);
44    impl_mode!(NonBlocking);
45}
46
47// Without an Embassy time driver, hardware waits have no deadline and may
48// block indefinitely if the peripheral or bus does not make progress.
49#[derive(Copy, Clone)]
50struct Timeout {
51    #[cfg(feature = "embassy")]
52    deadline: embassy_time::Instant,
53}
54
55#[allow(dead_code)]
56impl Timeout {
57    #[inline]
58    fn check(self) -> Option<()> {
59        #[cfg(feature = "embassy")]
60        if embassy_time::Instant::now() > self.deadline {
61            return None;
62        }
63
64        Some(())
65    }
66
67    #[inline]
68    fn with<R>(self, fut: impl Future<Output = Option<R>>) -> impl Future<Output = Option<R>> {
69        #[cfg(feature = "embassy")]
70        {
71            use futures::FutureExt;
72
73            embassy_futures::select::select(embassy_time::Timer::at(self.deadline), fut).map(|r| match r {
74                embassy_futures::select::Either::First(_) => None,
75                embassy_futures::select::Either::Second(r) => r,
76            })
77        }
78
79        #[cfg(not(feature = "embassy"))]
80        fut
81    }
82}
83
84pub mod rcc;
85
86pub mod debug;
87pub mod prelude;
88
89mod peripheral;
90pub use peripheral::{RccPeripheral, RemapPeripheral};
91
92// #[cfg(not(ch32v0))]
93mod interrupt_ext;
94
95pub use crate::_generated::{peripherals, Peripherals};
96
97#[cfg(not(time_driver_systick))]
98pub mod delay;
99pub mod dma;
100
101// ADC / DAC drivers are written against the V3-family register layout
102// (`pac::adc::vals::SampleTime`, `pac::dac::vals::TrigSel`, ...). On H4 and
103// V4x7 these `vals` submodules don't exist because chiptool only emits them
104// for fields that carry enum types, so those families use the V4x7 driver,
105// which defines its own sample-time enum. H4's block keeps the V4x7 layout
106// apart from the regular-data split; the driver covers both.
107#[cfg(all(adc, not(any(ch32h4, ch32v4))))]
108pub mod adc;
109#[cfg(adc_v4x7)]
110#[path = "adc/v4x7.rs"]
111pub mod adc;
112#[cfg(adc_h4)]
113#[path = "adc/v4x7.rs"]
114pub mod adc;
115#[cfg(adc_x0)]
116pub mod tkey;
117#[cfg(all(dac, not(ch32h4)))]
118pub mod dac;
119// H4's DAC uses per-channel registers (`R12BDHR1`, `EN1`, ...) instead of the
120// V3 arrays, so it needs its own module.
121#[cfg(dac_h4)]
122#[path = "dac/h4.rs"]
123pub mod dac;
124#[cfg(awu)]
125pub mod awu;
126#[cfg(crc)]
127pub mod crc;
128pub mod exti;
129pub mod gpio;
130// H4 flags I2C as `version: v3`, so the existing V3 driver applies directly.
131#[cfg(i2c)]
132pub mod i2c;
133#[cfg(i3c_v4x7)]
134pub mod i3c;
135#[cfg(rng)]
136pub mod rng;
137// `pioc` is a manual opt-in: the driver is useless without a firmware image,
138// so it is not part of any chip feature.
139#[cfg(all(peri_pioc, feature = "pioc"))]
140pub mod pioc;
141// Independent of `cfg(i2c)`: soft I2C exists precisely for chips or pins
142// without an I2C peripheral.
143#[cfg(feature = "soft-i2c")]
144pub mod soft_i2c;
145// The RTC block is the shared F1-style layout; it needs the PAC's PWR for the
146// `DBP` backup-domain write enable. V4x7 has `PWR.CTLR.DBP` too, but a raw
147// `RTCSEL` byte instead of the `Rtcsel` enum, so it needs its own branch
148// before this gate can widen.
149#[cfg(all(rtc, any(rcc_h4, pwr_v3)))]
150pub mod rtc;
151#[cfg(sdio_v3)]
152pub mod sdio;
153#[cfg(sdio_v4x7)]
154#[path = "sdio/v4x7.rs"]
155pub mod sdio;
156pub mod signature;
157#[cfg(spi)]
158pub mod spi;
159#[cfg(any(timer_x0, timer_v3, timer_h4, timer_v4x7))]
160pub mod timer;
161pub mod usart;
162#[cfg(any(iwdg, wwdg))]
163pub mod wdg;
164
165/// Shared USB endpoint-buffer helpers (not a controller driver).
166///
167/// FS/HS controller drivers live in the modules below. Taxonomy (USBD vs
168/// WCH-USBFS layouts vs USBHS) is documented in `ch32-data` `docs/usb_ip.md`.
169pub mod usb;
170
171/// WCH USBFS + OTG (`kind: otg` / `otg_v2`) โ€” v2fs device layout + OTG regs.
172#[cfg(otg)]
173pub mod otg_fs;
174
175/// H4's FS controller (`kind: usbfs` / `usbfs_h4`), X035's `x0fs` block and the
176/// CH32V20x/V303 `v2fs` block (`kind: usb`) are the same device core as
177/// `crate::otg_fs`, so they reuse that driver. X035's register block is
178/// array-grouped; the differences live in the `otg_fs::regs` adapter.
179#[cfg(any(usbfs_h4, usb_x0fs, usb_v2fs))]
180#[path = "otg_fs/mod.rs"]
181pub mod usbfs;
182
183/// WCH USBFS `l1fs` layout only (`kind: usb`, CH32L103). Sibling layouts
184/// (`v1fs`/`v2fs`/`x0fs`) are not this module; see `ch32-data` `docs/usb_ip.md`.
185/// H4's `kind: usbfs` and the `x0fs`/`v2fs` layouts use the OTG-v2 backend
186/// above, never both at once.
187#[cfg(usb_l1fs)]
188pub mod usbfs;
189
190/// Classic USB device-only (`kind: usbd` / EPR+BTABLE). Manual name: USBD.
191#[cfg(usbd)]
192pub mod usbd;
193
194/// USB high-speed (`kind: usbhs`). H4 shares the `v4x7` register map; `v3`
195/// is its own layout.
196#[cfg(usbhs_v3)]
197pub mod usbhs;
198// H4's USBHS keeps the V4x7 device-block layout (same offsets, fieldsets and
199// endpoint arrays), so the V4x7 driver serves both.
200#[cfg(any(usbhs_v4x7, usbhs_h4))]
201#[path = "usbhs/v4x7/mod.rs"]
202pub mod usbhs;
203
204/// USB 3.0 SuperSpeed device (`kind: usbss`, CH32H417) โ€” RM ยง27.
205#[cfg(usbss_h4)]
206pub mod usbss;
207
208// H4's USBPD register layout differs from V3 โ€” gate out for now.
209#[cfg(all(usbpd, not(ch32h4)))]
210pub mod usbpd;
211
212#[cfg(all(can, not(any(ch32h4, ch32v4))))]
213pub mod can;
214// H4's CAN block is the same bxCAN layout as V4x7 plus the shared 42-bank
215// filter table, so the V4x7 driver covers both (see `can/v4x7.rs`).
216#[cfg(any(can_v4x7, can_h4))]
217#[path = "can/v4x7.rs"]
218pub mod can;
219// The V4x7 driver targets its own 10/100 `emac` register set; H4 has a
220// separate gigabit block (`emac_h4`) with `PHY_CFGR` and RGMII. The V208 10M
221// driver (`eth_10m`) needs `embassy-time` for TX completion and link polling,
222// so it only exists with the `embassy` feature.
223#[cfg(all(
224    any(eth, emac),
225    not(any(ch32v4, emac_h4)),
226    any(not(eth_10m), feature = "embassy")
227))]
228pub mod eth;
229#[cfg(emac_v4x7)]
230#[path = "eth/v4x7.rs"]
231pub mod eth;
232#[cfg(emac_h4)]
233#[path = "eth/h4.rs"]
234pub mod eth;
235
236#[cfg(flash)]
237pub mod flash;
238
239mod patches;
240
241#[cfg(feature = "embassy")]
242pub mod embassy;
243
244// This must go last, so that it sees all the impl_foo! macros defined earlier.
245pub(crate) mod _generated {
246    #![allow(dead_code)]
247    #![allow(unused_imports)]
248    #![allow(non_snake_case)]
249    #![allow(missing_docs)]
250
251    include!(concat!(env!("OUT_DIR"), "/_generated.rs"));
252}
253
254pub use crate::_generated::interrupt;
255
256pub struct Config {
257    pub rcc: rcc::Config,
258    pub dma_interrupt_priority: interrupt::Priority,
259    /// Release the debug-interface pins for GPIO. Defaults to `false`.
260    ///
261    /// The debugger can only reattach after resetting into the system bootloader.
262    #[cfg(afio)]
263    pub release_swd_pins: bool,
264}
265
266impl Default for Config {
267    fn default() -> Self {
268        Self {
269            rcc: Default::default(),
270            dma_interrupt_priority: interrupt::Priority::P0,
271            #[cfg(afio)]
272            release_swd_pins: false,
273        }
274    }
275}
276
277/// Initialize the HAL with the provided configuration.
278///
279/// This returns the peripheral singletons that can be used for creating drivers.
280///
281/// This should only be called once at startup, otherwise it panics.
282pub fn init(config: Config) -> Peripherals {
283    // Do this first, so that it panics if user is calling `init` a second time
284    // before doing anything important.
285    let p = Peripherals::take();
286
287    unsafe {
288        rcc::init(config.rcc);
289        delay::init();
290
291        #[cfg(feature = "embassy")]
292        embassy::init();
293    }
294
295    ::critical_section::with(|cs| unsafe {
296        gpio::init(cs, true);
297        // After `gpio::init`, because its AFIO reset pulse clears `SW_CFG`.
298        #[cfg(afio)]
299        if config.release_swd_pins {
300            debug::release_swd_pins();
301        }
302        dma::init(cs, config.dma_interrupt_priority, true);
303        #[cfg(feature = "exti")]
304        exti::init(cs);
305    });
306
307    p
308}
309
310/// What [`init_secondary`] may touch on a core that does not own the chip.
311///
312/// The defaults only do what is safe while the boot core is running: read the
313/// clock tree back, and turn on the GPIO port and DMA clocks (both are
314/// write-1-to-enable bits the boot core already set). The AFIO reset and the
315/// DMA interrupt enables are off because each changes state the boot core
316/// relies on.
317#[cfg(rcc_h4)]
318pub struct SecondaryConfig {
319    /// Crystal frequency, needed only when the boot core switched SYSCLK to
320    /// HSE or to a PLL driven by it. `None` for HSI.
321    pub hse: Option<time::Hertz>,
322    /// Pulse the AFIO reset. That clears `GPIO_AFR` back to AF0, dropping
323    /// every alternate function the boot core configured, so leave it off
324    /// unless this core owns the whole pin mux.
325    pub reset_afio: bool,
326    /// Enable every DMA channel interrupt. On CH32H4 an interrupt above 31 is
327    /// delivered to exactly one core, and enabling it assigns it to the core
328    /// that did the enable, so this takes the DMA interrupts away from the
329    /// boot core. Leave it off and let each transfer enable its own channel.
330    pub enable_dma_irqs: bool,
331    /// Priority stored for the DMA interrupts. Only matters for the channels
332    /// this core actually enables.
333    pub dma_interrupt_priority: interrupt::Priority,
334}
335
336#[cfg(rcc_h4)]
337impl Default for SecondaryConfig {
338    fn default() -> Self {
339        Self {
340            hse: None,
341            reset_afio: false,
342            enable_dma_irqs: false,
343            dma_interrupt_priority: interrupt::Priority::P0,
344        }
345    }
346}
347
348/// Initialize the HAL on a core that does not own the clock tree.
349///
350/// For the second core of a dual-core chip: the boot core has already run
351/// [`init`] and programmed the PLL, and doing that again here would switch
352/// SYSCLK out from under it. This reads the RCC registers back into [`rcc::clocks`]
353/// instead of writing them.
354///
355/// # Safety
356///
357/// The boot core must have finished [`init`] before this runs. The two cores
358/// must not both use one peripheral. Each image is linked on its own, so each
359/// has its own `Peripherals` singleton and this cannot tell that the other
360/// core already took one.
361#[cfg(rcc_h4)]
362pub unsafe fn init_secondary(config: SecondaryConfig) -> Peripherals {
363    let p = Peripherals::take();
364
365    unsafe {
366        rcc::refresh(config.hse);
367        delay::init();
368
369        #[cfg(feature = "embassy")]
370        embassy::init();
371    }
372
373    ::critical_section::with(|cs| unsafe {
374        gpio::init(cs, config.reset_afio);
375        dma::init(cs, config.dma_interrupt_priority, config.enable_dma_irqs);
376        #[cfg(feature = "exti")]
377        exti::init(cs);
378    });
379
380    p
381}
382
383#[macro_export]
384macro_rules! bind_interrupts {
385    ($vis:vis struct $name:ident { $($irq:ident => $($handler:ty),*;)* }) => {
386        #[derive(Copy, Clone)]
387        $vis struct $name;
388
389        $(
390            #[allow(non_snake_case)]
391            #[$crate::interrupt]
392            unsafe fn $irq() {
393                $(
394                    <$handler as $crate::interrupt::typelevel::Handler<$crate::interrupt::typelevel::$irq>>::on_interrupt();
395                )*
396            }
397
398            $(
399                unsafe impl $crate::interrupt::typelevel::Binding<$crate::interrupt::typelevel::$irq, $handler> for $name {}
400            )*
401        )*
402    };
403}