delay.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //! Delays
  2. use cast::u32;
  3. use cortex_m::peripheral::syst::SystClkSource;
  4. use cortex_m::peripheral::SYST;
  5. use hal::blocking::delay::{DelayMs, DelayUs};
  6. use rcc::Clocks;
  7. /// System timer (SysTick) as a delay provider
  8. pub struct Delay {
  9. clocks: Clocks,
  10. syst: SYST,
  11. }
  12. impl Delay {
  13. /// Configures the system timer (SysTick) as a delay provider
  14. pub fn new(mut syst: SYST, clocks: Clocks) -> Self {
  15. syst.set_clock_source(SystClkSource::Core);
  16. Delay { syst, clocks }
  17. }
  18. /// Releases the system timer (SysTick) resource
  19. pub fn free(self) -> SYST {
  20. self.syst
  21. }
  22. }
  23. impl DelayMs<u32> for Delay {
  24. fn delay_ms(&mut self, ms: u32) {
  25. self.delay_us(ms * 1_000);
  26. }
  27. }
  28. impl DelayMs<u16> for Delay {
  29. fn delay_ms(&mut self, ms: u16) {
  30. self.delay_ms(u32(ms));
  31. }
  32. }
  33. impl DelayMs<u8> for Delay {
  34. fn delay_ms(&mut self, ms: u8) {
  35. self.delay_ms(u32(ms));
  36. }
  37. }
  38. impl DelayUs<u32> for Delay {
  39. fn delay_us(&mut self, us: u32) {
  40. // The SysTick Reload Value register supports values between 1 and 0x00FFFFFF.
  41. const MAX_RVR: u32 = 0x00FF_FFFF;
  42. let mut total_rvr = us * (self.clocks.sysclk().0 / 1_000_000);
  43. while total_rvr != 0 {
  44. let current_rvr = if total_rvr <= MAX_RVR {
  45. total_rvr
  46. } else {
  47. MAX_RVR
  48. };
  49. self.syst.set_reload(current_rvr);
  50. self.syst.clear_current();
  51. self.syst.enable_counter();
  52. // Update the tracking variable while we are waiting...
  53. total_rvr -= current_rvr;
  54. while !self.syst.has_wrapped() {}
  55. self.syst.disable_counter();
  56. }
  57. }
  58. }
  59. impl DelayUs<u16> for Delay {
  60. fn delay_us(&mut self, us: u16) {
  61. self.delay_us(u32(us))
  62. }
  63. }
  64. impl DelayUs<u8> for Delay {
  65. fn delay_us(&mut self, us: u8) {
  66. self.delay_us(u32(us))
  67. }
  68. }