delay.rs 826 B

123456789101112131415161718192021222324252627282930
  1. //! Delay devices and providers
  2. use crate::register::mcycle;
  3. use embedded_hal::delay::DelayUs;
  4. /// Machine mode cycle counter (`mcycle`) as a delay provider
  5. #[derive(Copy, Clone)]
  6. #[repr(transparent)]
  7. pub struct McycleDelay {
  8. /// The clock speed of the core, in Hertz
  9. ticks_second: u32,
  10. }
  11. impl McycleDelay {
  12. /// Constructs the delay provider.
  13. /// `ticks_second` should be the clock speed of the core, in Hertz
  14. #[inline]
  15. pub const fn new(ticks_second: u32) -> Self {
  16. Self { ticks_second }
  17. }
  18. }
  19. impl DelayUs for McycleDelay {
  20. #[inline]
  21. fn delay_us(&mut self, us: u32) {
  22. let t0 = mcycle::read64();
  23. let us_64: u64 = us.into();
  24. let clock = (us_64 * (self.ticks_second as u64)) / 1_000_000u64;
  25. while mcycle::read64().wrapping_sub(t0) <= clock {}
  26. }
  27. }