time.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. //! Time units
  2. use cortex_m::peripheral::DWT;
  3. use rcc::Clocks;
  4. /// Bits per second
  5. #[derive(Clone, Copy)]
  6. pub struct Bps(pub u32);
  7. /// Hertz
  8. #[derive(Clone, Copy)]
  9. pub struct Hertz(pub u32);
  10. /// KiloHertz
  11. #[derive(Clone, Copy)]
  12. pub struct KiloHertz(pub u32);
  13. /// MegaHertz
  14. #[derive(Clone, Copy)]
  15. pub struct MegaHertz(pub u32);
  16. /// Extension trait that adds convenience methods to the `u32` type
  17. pub trait U32Ext {
  18. /// Wrap in `Bps`
  19. fn bps(self) -> Bps;
  20. /// Wrap in `Hertz`
  21. fn hz(self) -> Hertz;
  22. /// Wrap in `KiloHertz`
  23. fn khz(self) -> KiloHertz;
  24. /// Wrap in `MegaHertz`
  25. fn mhz(self) -> MegaHertz;
  26. }
  27. impl U32Ext for u32 {
  28. fn bps(self) -> Bps {
  29. Bps(self)
  30. }
  31. fn hz(self) -> Hertz {
  32. Hertz(self)
  33. }
  34. fn khz(self) -> KiloHertz {
  35. KiloHertz(self)
  36. }
  37. fn mhz(self) -> MegaHertz {
  38. MegaHertz(self)
  39. }
  40. }
  41. impl Into<Hertz> for KiloHertz {
  42. fn into(self) -> Hertz {
  43. Hertz(self.0 * 1_000)
  44. }
  45. }
  46. impl Into<Hertz> for MegaHertz {
  47. fn into(self) -> Hertz {
  48. Hertz(self.0 * 1_000_000)
  49. }
  50. }
  51. impl Into<KiloHertz> for MegaHertz {
  52. fn into(self) -> KiloHertz {
  53. KiloHertz(self.0 * 1_000)
  54. }
  55. }
  56. /// A monotonic nondecreasing timer
  57. #[derive(Clone, Copy)]
  58. pub struct MonoTimer {
  59. frequency: Hertz,
  60. }
  61. impl MonoTimer {
  62. /// Creates a new `Monotonic` timer
  63. pub fn new(mut dwt: DWT, clocks: Clocks) -> Self {
  64. dwt.enable_cycle_counter();
  65. // now the CYCCNT counter can't be stopped or resetted
  66. drop(dwt);
  67. MonoTimer {
  68. frequency: clocks.sysclk(),
  69. }
  70. }
  71. /// Returns the frequency at which the monotonic timer is operating at
  72. pub fn frequency(&self) -> Hertz {
  73. self.frequency
  74. }
  75. /// Returns an `Instant` corresponding to "now"
  76. pub fn now(&self) -> Instant {
  77. Instant {
  78. now: DWT::get_cycle_count(),
  79. }
  80. }
  81. }
  82. /// A measurement of a monotonically nondecreasing clock
  83. #[derive(Clone, Copy)]
  84. pub struct Instant {
  85. now: u32,
  86. }
  87. impl Instant {
  88. /// Ticks elapsed since the `Instant` was created
  89. pub fn elapsed(&self) -> u32 {
  90. DWT::get_cycle_count().wrapping_sub(self.now)
  91. }
  92. }