Skip to main content

ch32_hal/internal/
delay.rs

1//! Peripheral settling delays without borrowing SysTick or another hardware timer.
2
3/// Busy-wait for peripheral initialization, not for precise signal timing.
4///
5/// The clock cache must match the running core and the clock must not increase
6/// during the wait. Without Embassy, count one dependent decrement per requested
7/// core cycle: unlike a calibrated loop, this does not assume a fixed branch cost.
8/// Flash wait states, fetch stalls, RAM execution and interrupts only change the
9/// upper bound: each decrement depends on the previous one, so it cannot execute
10/// more than once per core cycle.
11#[allow(dead_code)]
12pub(crate) fn block_for_us(micros: u32) {
13    if micros == 0 {
14        return;
15    }
16
17    #[cfg(feature = "embassy")]
18    embassy_time::block_for(embassy_time::Duration::from_micros(micros as u64));
19
20    #[cfg(not(feature = "embassy"))]
21    {
22        let clocks = crate::rcc::clocks();
23        #[cfg(rcc_h4)]
24        let hz = match qingke::pfic::HartId::current() {
25            qingke::pfic::HartId::C0 => clocks.v3f.0,
26            qingke::pfic::HartId::C1 => clocks.v5f.0,
27        };
28        #[cfg(not(rcc_h4))]
29        let hz = clocks.hclk.0;
30        assert!(hz != 0);
31
32        let mut cycles = cycles_for_us(hz, micros);
33        while cycles != 0 {
34            let chunk = cycles.min(u32::MAX as u64) as u32;
35            unsafe {
36                core::arch::asm!(
37                    "2:",
38                    "addi {counter}, {counter}, -1",
39                    "bnez {counter}, 2b",
40                    counter = inout(reg) chunk => _,
41                    // Keep peripheral accesses ordered around the settling delay.
42                    options(nostack),
43                );
44            }
45            cycles -= chunk as u64;
46        }
47    }
48}
49
50#[cfg(not(feature = "embassy"))]
51fn cycles_for_us(hz: u32, micros: u32) -> u64 {
52    // Avoid a 64-bit division when the core runs at a whole number of MHz.
53    let mut cycles = micros as u64 * (hz / 1_000_000) as u64;
54    let rem = hz % 1_000_000;
55    if rem != 0 {
56        cycles += (micros as u64 * rem as u64).div_ceil(1_000_000);
57    }
58    cycles
59}