Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add asm::delay_cycles #127

Merged
merged 1 commit into from
May 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,47 @@ pub fn wdr() {
}
}
}

/// Blocks the program for at least `cycles` CPU cycles.
///
/// This is intended for very simple delays in low-level drivers, but it
/// has some caveats:
///
/// - The delay may be significantly longer if an interrupt is serviced at the
/// same time, since the delay loop will not be executing during the interrupt.
/// If you need precise timing, use a hardware timer peripheral instead.
///
/// - The real-time delay depends on the CPU clock frequency. If you want to
/// conveniently specify a delay value in real-time units like microseconds,
/// then use the `delay` module in the HAL crate for your platform.
#[inline(always)]
pub fn delay_cycles(cycles: u32) {
cfg_if::cfg_if! {
if #[cfg(target_arch = "avr")] {
let mut cycles_bytes = cycles.to_le_bytes();
// Each loop iteration takes 6 cycles when the branch is taken,
// and 5 cycles when the branch is not taken.
// So, this loop is guaranteed to run for at least `cycles - 1`
// cycles, and there will be approximately 4 cycles before the
// loop to initialize the counting registers.
unsafe {
asm!(
"1:",
"subi {r0}, 6",
"sbci {r1}, 0",
"sbci {r2}, 0",
"sbci {r3}, 0",
"brcc 1b",

r0 = inout(reg_upper) cycles_bytes[0],
r1 = inout(reg_upper) cycles_bytes[1],
r2 = inout(reg_upper) cycles_bytes[2],
r3 = inout(reg_upper) cycles_bytes[3],
)
}
} else {
let _ = cycles;
unimplemented!()
}
}
}