ch32_hal/internal/
delay.rs1#[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 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 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}