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(all(dac, not(ch32h4)))]
116pub mod dac;
117// H4's DAC uses per-channel registers (`R12BDHR1`, `EN1`, ...) instead of the
118// V3 arrays, so it needs its own module.
119#[cfg(dac_h4)]
120#[path = "dac/h4.rs"]
121pub mod dac;
122#[cfg(awu)]
123pub mod awu;
124#[cfg(crc)]
125pub mod crc;
126pub mod exti;
127pub mod gpio;
128// H4 flags I2C as `version: v3`, so the existing V3 driver applies directly.
129#[cfg(i2c)]
130pub mod i2c;
131#[cfg(i3c_v4x7)]
132pub mod i3c;
133#[cfg(rng)]
134pub mod rng;
135// `pioc` is a manual opt-in: the driver is useless without a firmware image,
136// so it is not part of any chip feature.
137#[cfg(all(peri_pioc, feature = "pioc"))]
138pub mod pioc;
139// Independent of `cfg(i2c)`: soft I2C exists precisely for chips or pins
140// without an I2C peripheral.
141#[cfg(feature = "soft-i2c")]
142pub mod soft_i2c;
143// The RTC block is the shared F1-style layout, but only CH32H4 currently has
144// a PWR peripheral in the PAC for the `DBP` backup-domain write enable. V4x7
145// has `PWR.CTLR.DBP` too, but a raw `RTCSEL` byte instead of the `Rtcsel`
146// enum, so it needs its own branch before this gate can widen.
147#[cfg(all(rtc, rcc_h4))]
148pub mod rtc;
149#[cfg(sdio_v3)]
150pub mod sdio;
151#[cfg(sdio_v4x7)]
152#[path = "sdio/v4x7.rs"]
153pub mod sdio;
154pub mod signature;
155#[cfg(spi)]
156pub mod spi;
157#[cfg(any(timer_x0, timer_v3, timer_h4, timer_v4x7))]
158pub mod timer;
159pub mod usart;
160#[cfg(any(iwdg, wwdg))]
161pub mod wdg;
162
163/// Shared USB endpoint-buffer helpers (not a controller driver).
164///
165/// FS/HS controller drivers live in the modules below. Taxonomy (USBD vs
166/// WCH-USBFS layouts vs USBHS) is documented in `ch32-data` `docs/usb_ip.md`.
167pub mod usb;
168
169/// WCH USBFS + OTG (`kind: otg` / `otg_v2`) โ v2fs device layout + OTG regs.
170#[cfg(otg)]
171pub mod otg_fs;
172
173/// H4's FS controller (`kind: usbfs` / `usbfs_h4`) and X035's `x0fs` block
174/// (`kind: usb` / `x0fs`) are the same device core as `crate::otg_fs`, so
175/// they reuse that driver. X035's register block is array-grouped; the
176/// differences live in the `otg_fs::regs` adapter.
177#[cfg(any(usbfs_h4, usb_x0fs))]
178#[path = "otg_fs/mod.rs"]
179pub mod usbfs;
180
181/// WCH USBFS `l1fs` layout only (`kind: usb`, CH32L103). Sibling layouts
182/// (`v1fs`/`v2fs`/`x0fs`) are not this module; see `ch32-data` `docs/usb_ip.md`.
183/// H4's `kind: usbfs` and X035's `x0fs` use the OTG-v2 backend above, never
184/// both at once.
185#[cfg(usb_l1fs)]
186pub mod usbfs;
187
188/// Classic USB device-only (`kind: usbd` / EPR+BTABLE). Manual name: USBD.
189#[cfg(usbd)]
190pub mod usbd;
191
192/// USB high-speed (`kind: usbhs`). H4 shares the `v4x7` register map; `v3`
193/// is its own layout.
194#[cfg(usbhs_v3)]
195pub mod usbhs;
196// H4's USBHS keeps the V4x7 device-block layout (same offsets, fieldsets and
197// endpoint arrays), so the V4x7 driver serves both.
198#[cfg(any(usbhs_v4x7, usbhs_h4))]
199#[path = "usbhs/v4x7/mod.rs"]
200pub mod usbhs;
201
202/// USB 3.0 SuperSpeed device (`kind: usbss`, CH32H417) โ RM ยง27.
203#[cfg(usbss_h4)]
204pub mod usbss;
205
206// H4's USBPD register layout differs from V3 โ gate out for now.
207#[cfg(all(usbpd, not(ch32h4)))]
208pub mod usbpd;
209
210#[cfg(all(can, not(any(ch32h4, ch32v4))))]
211pub mod can;
212// H4's CAN block is the same bxCAN layout as V4x7 plus the shared 42-bank
213// filter table, so the V4x7 driver covers both (see `can/v4x7.rs`).
214#[cfg(any(can_v4x7, can_h4))]
215#[path = "can/v4x7.rs"]
216pub mod can;
217// The V4x7 driver targets its own 10/100 `emac` register set; H4 has a
218// separate gigabit block (`emac_h4`) with `PHY_CFGR` and RGMII. The V208 10M
219// driver (`eth_10m`) needs `embassy-time` for TX completion and link polling,
220// so it only exists with the `embassy` feature.
221#[cfg(all(
222 any(eth, emac),
223 not(any(ch32v4, emac_h4)),
224 any(not(eth_10m), feature = "embassy")
225))]
226pub mod eth;
227#[cfg(emac_v4x7)]
228#[path = "eth/v4x7.rs"]
229pub mod eth;
230#[cfg(emac_h4)]
231#[path = "eth/h4.rs"]
232pub mod eth;
233
234#[cfg(flash)]
235pub mod flash;
236
237mod patches;
238
239#[cfg(feature = "embassy")]
240pub mod embassy;
241
242// This must go last, so that it sees all the impl_foo! macros defined earlier.
243pub(crate) mod _generated {
244 #![allow(dead_code)]
245 #![allow(unused_imports)]
246 #![allow(non_snake_case)]
247 #![allow(missing_docs)]
248
249 include!(concat!(env!("OUT_DIR"), "/_generated.rs"));
250}
251
252pub use crate::_generated::interrupt;
253
254pub struct Config {
255 pub rcc: rcc::Config,
256 pub dma_interrupt_priority: interrupt::Priority,
257 /// Release the debug-interface pins for GPIO. Defaults to `false`.
258 ///
259 /// The debugger can only reattach after resetting into the system bootloader.
260 #[cfg(afio)]
261 pub release_swd_pins: bool,
262}
263
264impl Default for Config {
265 fn default() -> Self {
266 Self {
267 rcc: Default::default(),
268 dma_interrupt_priority: interrupt::Priority::P0,
269 #[cfg(afio)]
270 release_swd_pins: false,
271 }
272 }
273}
274
275/// Initialize the HAL with the provided configuration.
276///
277/// This returns the peripheral singletons that can be used for creating drivers.
278///
279/// This should only be called once at startup, otherwise it panics.
280pub fn init(config: Config) -> Peripherals {
281 // Do this first, so that it panics if user is calling `init` a second time
282 // before doing anything important.
283 let p = Peripherals::take();
284
285 unsafe {
286 rcc::init(config.rcc);
287 delay::init();
288
289 #[cfg(feature = "embassy")]
290 embassy::init();
291 }
292
293 ::critical_section::with(|cs| unsafe {
294 gpio::init(cs, true);
295 // After `gpio::init`, because its AFIO reset pulse clears `SW_CFG`.
296 #[cfg(afio)]
297 if config.release_swd_pins {
298 debug::release_swd_pins();
299 }
300 dma::init(cs, config.dma_interrupt_priority, true);
301 #[cfg(feature = "exti")]
302 exti::init(cs);
303 });
304
305 p
306}
307
308/// What [`init_secondary`] may touch on a core that does not own the chip.
309///
310/// The defaults only do what is safe while the boot core is running: read the
311/// clock tree back, and turn on the GPIO port and DMA clocks (both are
312/// write-1-to-enable bits the boot core already set). The AFIO reset and the
313/// DMA interrupt enables are off because each changes state the boot core
314/// relies on.
315#[cfg(rcc_h4)]
316pub struct SecondaryConfig {
317 /// Crystal frequency, needed only when the boot core switched SYSCLK to
318 /// HSE or to a PLL driven by it. `None` for HSI.
319 pub hse: Option<time::Hertz>,
320 /// Pulse the AFIO reset. That clears `GPIO_AFR` back to AF0, dropping
321 /// every alternate function the boot core configured, so leave it off
322 /// unless this core owns the whole pin mux.
323 pub reset_afio: bool,
324 /// Enable every DMA channel interrupt. On CH32H4 an interrupt above 31 is
325 /// delivered to exactly one core, and enabling it assigns it to the core
326 /// that did the enable, so this takes the DMA interrupts away from the
327 /// boot core. Leave it off and let each transfer enable its own channel.
328 pub enable_dma_irqs: bool,
329 /// Priority stored for the DMA interrupts. Only matters for the channels
330 /// this core actually enables.
331 pub dma_interrupt_priority: interrupt::Priority,
332}
333
334#[cfg(rcc_h4)]
335impl Default for SecondaryConfig {
336 fn default() -> Self {
337 Self {
338 hse: None,
339 reset_afio: false,
340 enable_dma_irqs: false,
341 dma_interrupt_priority: interrupt::Priority::P0,
342 }
343 }
344}
345
346/// Initialize the HAL on a core that does not own the clock tree.
347///
348/// For the second core of a dual-core chip: the boot core has already run
349/// [`init`] and programmed the PLL, and doing that again here would switch
350/// SYSCLK out from under it. This reads the RCC registers back into [`rcc::clocks`]
351/// instead of writing them.
352///
353/// # Safety
354///
355/// The boot core must have finished [`init`] before this runs. The two cores
356/// must not both use one peripheral. Each image is linked on its own, so each
357/// has its own `Peripherals` singleton and this cannot tell that the other
358/// core already took one.
359#[cfg(rcc_h4)]
360pub unsafe fn init_secondary(config: SecondaryConfig) -> Peripherals {
361 let p = Peripherals::take();
362
363 unsafe {
364 rcc::refresh(config.hse);
365 delay::init();
366
367 #[cfg(feature = "embassy")]
368 embassy::init();
369 }
370
371 ::critical_section::with(|cs| unsafe {
372 gpio::init(cs, config.reset_afio);
373 dma::init(cs, config.dma_interrupt_priority, config.enable_dma_irqs);
374 #[cfg(feature = "exti")]
375 exti::init(cs);
376 });
377
378 p
379}
380
381#[macro_export]
382macro_rules! bind_interrupts {
383 ($vis:vis struct $name:ident { $($irq:ident => $($handler:ty),*;)* }) => {
384 #[derive(Copy, Clone)]
385 $vis struct $name;
386
387 $(
388 #[allow(non_snake_case)]
389 #[$crate::interrupt]
390 unsafe fn $irq() {
391 $(
392 <$handler as $crate::interrupt::typelevel::Handler<$crate::interrupt::typelevel::$irq>>::on_interrupt();
393 )*
394 }
395
396 $(
397 unsafe impl $crate::interrupt::typelevel::Binding<$crate::interrupt::typelevel::$irq, $handler> for $name {}
398 )*
399 )*
400 };
401}