esp_hal/time.rs
1//! # Timekeeping
2//!
3//! This module provides types for representing frequency and duration, as well
4//! as an instant in time. Time is measured since boot, and can be accessed
5//! by the [`Instant::now`] function.
6
7use core::fmt::{Debug, Display, Formatter, Result as FmtResult};
8
9#[cfg(esp32)]
10use crate::peripherals::TIMG0;
11
12type InnerRate = fugit::Rate<u32, 1, 1>;
13type InnerInstant = fugit::Instant<u64, 1, 1_000_000>;
14type InnerDuration = fugit::Duration<u64, 1, 1_000_000>;
15
16/// Represents a rate or frequency of events.
17#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18pub struct Rate(InnerRate);
19
20impl core::hash::Hash for Rate {
21 #[inline]
22 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
23 self.as_hz().hash(state);
24 }
25}
26
27impl Display for Rate {
28 #[inline]
29 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
30 write!(f, "{} Hz", self.as_hz())
31 }
32}
33
34impl Debug for Rate {
35 #[inline]
36 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
37 write!(f, "Rate({} Hz)", self.as_hz())
38 }
39}
40
41#[cfg(feature = "defmt")]
42impl defmt::Format for Rate {
43 #[inline]
44 fn format(&self, f: defmt::Formatter<'_>) {
45 defmt::write!(f, "{=u32} Hz", self.as_hz())
46 }
47}
48
49impl Rate {
50 #[procmacros::doc_replace]
51 /// Shorthand for creating a rate which represents hertz.
52 ///
53 /// ## Example
54 ///
55 /// ```rust, no_run
56 /// # {before_snippet}
57 /// use esp_hal::time::Rate;
58 /// let rate = Rate::from_hz(1000);
59 /// # {after_snippet}
60 /// ```
61 #[inline]
62 pub const fn from_hz(val: u32) -> Self {
63 Self(InnerRate::Hz(val))
64 }
65
66 #[procmacros::doc_replace]
67 /// Shorthand for creating a rate which represents kilohertz.
68 ///
69 /// ## Example
70 ///
71 /// ```rust, no_run
72 /// # {before_snippet}
73 /// use esp_hal::time::Rate;
74 /// let rate = Rate::from_khz(1000);
75 /// # {after_snippet}
76 /// ```
77 #[inline]
78 pub const fn from_khz(val: u32) -> Self {
79 Self(InnerRate::kHz(val))
80 }
81
82 #[procmacros::doc_replace]
83 /// Shorthand for creating a rate which represents megahertz.
84 ///
85 /// ## Example
86 ///
87 /// ```rust, no_run
88 /// # {before_snippet}
89 /// use esp_hal::time::Rate;
90 /// let rate = Rate::from_mhz(1000);
91 /// # {after_snippet}
92 /// ```
93 #[inline]
94 pub const fn from_mhz(val: u32) -> Self {
95 Self(InnerRate::MHz(val))
96 }
97
98 #[procmacros::doc_replace]
99 /// Convert the `Rate` to an interger number of Hz.
100 ///
101 /// ## Example
102 ///
103 /// ```rust, no_run
104 /// # {before_snippet}
105 /// use esp_hal::time::Rate;
106 /// let rate = Rate::from_hz(1000);
107 /// let hz = rate.as_hz();
108 /// # {after_snippet}
109 /// ```
110 #[inline]
111 pub const fn as_hz(&self) -> u32 {
112 self.0.to_Hz()
113 }
114
115 #[procmacros::doc_replace]
116 /// Convert the `Rate` to an interger number of kHz.
117 ///
118 /// ## Example
119 ///
120 /// ```rust, no_run
121 /// # {before_snippet}
122 /// use esp_hal::time::Rate;
123 /// let rate = Rate::from_khz(1000);
124 /// let khz = rate.as_khz();
125 /// # {after_snippet}
126 /// ```
127 #[inline]
128 pub const fn as_khz(&self) -> u32 {
129 self.0.to_kHz()
130 }
131
132 #[procmacros::doc_replace]
133 /// Convert the `Rate` to an interger number of MHz.
134 ///
135 /// ## Example
136 ///
137 /// ```rust, no_run
138 /// # {before_snippet}
139 /// use esp_hal::time::Rate;
140 /// let rate = Rate::from_mhz(1000);
141 /// let mhz = rate.as_mhz();
142 /// # {after_snippet}
143 /// ```
144 #[inline]
145 pub const fn as_mhz(&self) -> u32 {
146 self.0.to_MHz()
147 }
148
149 #[procmacros::doc_replace]
150 /// Convert the `Rate` to a `Duration`.
151 ///
152 /// ## Example
153 ///
154 /// ```rust, no_run
155 /// # {before_snippet}
156 /// use esp_hal::time::Rate;
157 /// let rate = Rate::from_hz(1000);
158 /// let duration = rate.as_duration();
159 /// # {after_snippet}
160 /// ```
161 #[inline]
162 pub const fn as_duration(&self) -> Duration {
163 Duration::from_micros(1_000_000 / self.as_hz() as u64)
164 }
165}
166
167impl core::ops::Div for Rate {
168 type Output = u32;
169
170 #[inline]
171 fn div(self, rhs: Self) -> Self::Output {
172 self.0 / rhs.0
173 }
174}
175
176impl core::ops::Mul<u32> for Rate {
177 type Output = Rate;
178
179 #[inline]
180 fn mul(self, rhs: u32) -> Self::Output {
181 Rate(self.0 * rhs)
182 }
183}
184
185impl core::ops::Div<u32> for Rate {
186 type Output = Rate;
187
188 #[inline]
189 fn div(self, rhs: u32) -> Self::Output {
190 Rate(self.0 / rhs)
191 }
192}
193
194/// Represents an instant in time.
195#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
196pub struct Instant(InnerInstant);
197
198impl Debug for Instant {
199 #[inline]
200 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
201 write!(
202 f,
203 "Instant({} µs since epoch)",
204 self.duration_since_epoch().as_micros()
205 )
206 }
207}
208
209impl Display for Instant {
210 #[inline]
211 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
212 write!(
213 f,
214 "{} µs since epoch",
215 self.duration_since_epoch().as_micros()
216 )
217 }
218}
219
220#[cfg(feature = "defmt")]
221impl defmt::Format for Instant {
222 #[inline]
223 fn format(&self, f: defmt::Formatter<'_>) {
224 defmt::write!(
225 f,
226 "{=u64} µs since epoch",
227 self.duration_since_epoch().as_micros()
228 )
229 }
230}
231
232impl core::hash::Hash for Instant {
233 #[inline]
234 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
235 self.duration_since_epoch().hash(state);
236 }
237}
238
239impl Instant {
240 /// Represents the moment the system booted.
241 pub const EPOCH: Instant = Instant(InnerInstant::from_ticks(0));
242
243 #[procmacros::doc_replace(
244 "wrap_after" => {
245 cfg(esp32) => "36_558 years",
246 cfg(esp32s2) => "7_311 years",
247 _ => "more than 7 years"
248 }
249 )]
250 /// Returns the current instant.
251 ///
252 /// The counter won’t measure time in sleep-mode.
253 ///
254 /// The timer has a 1 microsecond resolution and will wrap after
255 /// # {wrap_after}
256 ///
257 /// ## Example
258 ///
259 /// ```rust, no_run
260 /// # {before_snippet}
261 /// use esp_hal::time::Instant;
262 /// let now = Instant::now();
263 /// # {after_snippet}
264 /// ```
265 #[inline]
266 pub fn now() -> Self {
267 now()
268 }
269
270 #[inline]
271 pub(crate) fn from_ticks(ticks: u64) -> Self {
272 Instant(InnerInstant::from_ticks(ticks))
273 }
274
275 #[procmacros::doc_replace]
276 /// Returns the elapsed `Duration` since boot.
277 ///
278 /// ## Example
279 ///
280 /// ```rust, no_run
281 /// # {before_snippet}
282 /// use esp_hal::time::Instant;
283 /// let now = Instant::now();
284 /// let duration = now.duration_since_epoch();
285 /// # {after_snippet}
286 /// ```
287 #[inline]
288 pub fn duration_since_epoch(&self) -> Duration {
289 *self - Self::EPOCH
290 }
291
292 #[procmacros::doc_replace]
293 /// Returns the elapsed `Duration` since this `Instant` was created.
294 ///
295 /// ## Example
296 ///
297 /// ```rust, no_run
298 /// # {before_snippet}
299 /// use esp_hal::time::Instant;
300 /// let now = Instant::now();
301 /// let duration = now.elapsed();
302 /// # {after_snippet}
303 /// ```
304 #[inline]
305 pub fn elapsed(&self) -> Duration {
306 Self::now() - *self
307 }
308}
309
310impl core::ops::Add<Duration> for Instant {
311 type Output = Self;
312
313 #[inline]
314 fn add(self, rhs: Duration) -> Self::Output {
315 Instant(self.0 + rhs.0)
316 }
317}
318
319impl core::ops::AddAssign<Duration> for Instant {
320 #[inline]
321 fn add_assign(&mut self, rhs: Duration) {
322 self.0 += rhs.0;
323 }
324}
325
326impl core::ops::Sub for Instant {
327 type Output = Duration;
328
329 #[inline]
330 fn sub(self, rhs: Self) -> Self::Output {
331 // Avoid "Sub failed! Other > self" panics
332 Duration::from_micros(self.0.ticks().wrapping_sub(rhs.0.ticks()))
333 }
334}
335
336impl core::ops::Sub<Duration> for Instant {
337 type Output = Self;
338
339 #[inline]
340 fn sub(self, rhs: Duration) -> Self::Output {
341 Instant(self.0 - rhs.0)
342 }
343}
344
345impl core::ops::SubAssign<Duration> for Instant {
346 #[inline]
347 fn sub_assign(&mut self, rhs: Duration) {
348 self.0 -= rhs.0;
349 }
350}
351
352/// Represents a duration of time.
353#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
354pub struct Duration(InnerDuration);
355
356impl Debug for Duration {
357 #[inline]
358 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
359 write!(f, "Duration({} µs)", self.as_micros())
360 }
361}
362
363impl Display for Duration {
364 #[inline]
365 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
366 write!(f, "{} µs", self.as_micros())
367 }
368}
369
370#[cfg(feature = "defmt")]
371impl defmt::Format for Duration {
372 #[inline]
373 fn format(&self, f: defmt::Formatter<'_>) {
374 defmt::write!(f, "{=u64} µs", self.as_micros())
375 }
376}
377
378impl core::hash::Hash for Duration {
379 #[inline]
380 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
381 self.as_micros().hash(state);
382 }
383}
384
385impl Duration {
386 /// A duration of zero time.
387 pub const ZERO: Self = Self(InnerDuration::from_ticks(0));
388
389 /// A duration representing the maximum possible time.
390 pub const MAX: Self = Self(InnerDuration::from_ticks(u64::MAX));
391
392 #[procmacros::doc_replace]
393 /// Creates a duration which represents microseconds.
394 ///
395 /// ## Example
396 ///
397 /// ```rust, no_run
398 /// # {before_snippet}
399 /// use esp_hal::time::Duration;
400 /// let duration = Duration::from_micros(1000);
401 /// # {after_snippet}
402 /// ```
403 #[inline]
404 pub const fn from_micros(val: u64) -> Self {
405 Self(InnerDuration::micros(val))
406 }
407
408 #[procmacros::doc_replace]
409 /// Creates a duration which represents milliseconds.
410 ///
411 /// ## Example
412 ///
413 /// ```rust, no_run
414 /// # {before_snippet}
415 /// use esp_hal::time::Duration;
416 /// let duration = Duration::from_millis(100);
417 /// # {after_snippet}
418 /// ```
419 #[inline]
420 pub const fn from_millis(val: u64) -> Self {
421 Self(InnerDuration::millis(val))
422 }
423
424 #[procmacros::doc_replace]
425 /// Creates a duration which represents seconds.
426 ///
427 /// ## Example
428 ///
429 /// ```rust, no_run
430 /// # {before_snippet}
431 /// use esp_hal::time::Duration;
432 /// let duration = Duration::from_secs(1);
433 /// # {after_snippet}
434 /// ```
435 #[inline]
436 pub const fn from_secs(val: u64) -> Self {
437 Self(InnerDuration::secs(val))
438 }
439
440 #[procmacros::doc_replace]
441 /// Creates a duration which represents minutes.
442 ///
443 /// ## Example
444 ///
445 /// ```rust, no_run
446 /// # {before_snippet}
447 /// use esp_hal::time::Duration;
448 /// let duration = Duration::from_minutes(1);
449 /// # {after_snippet}
450 /// ```
451 #[inline]
452 pub const fn from_minutes(val: u64) -> Self {
453 Self(InnerDuration::minutes(val))
454 }
455
456 #[procmacros::doc_replace]
457 /// Creates a duration which represents hours.
458 ///
459 /// ## Example
460 ///
461 /// ```rust, no_run
462 /// # {before_snippet}
463 /// use esp_hal::time::Duration;
464 /// let duration = Duration::from_hours(1);
465 /// # {after_snippet}
466 /// ```
467 #[inline]
468 pub const fn from_hours(val: u64) -> Self {
469 Self(InnerDuration::hours(val))
470 }
471
472 delegate::delegate! {
473 #[inline]
474 to self.0 {
475 #[procmacros::doc_replace]
476 /// Convert the `Duration` to an interger number of microseconds.
477 ///
478 /// ## Example
479 ///
480 /// ```rust, no_run
481 /// # {before_snippet}
482 /// use esp_hal::time::Duration;
483 /// let duration = Duration::from_micros(1000);
484 /// let micros = duration.as_micros();
485 /// # {after_snippet}
486 /// ```
487 #[call(to_micros)]
488 pub const fn as_micros(&self) -> u64;
489
490 #[procmacros::doc_replace]
491 /// Convert the `Duration` to an interger number of milliseconds.
492 ///
493 /// ## Example
494 ///
495 /// ```rust, no_run
496 /// # {before_snippet}
497 /// use esp_hal::time::Duration;
498 /// let duration = Duration::from_millis(100);
499 /// let millis = duration.as_millis();
500 /// # {after_snippet}
501 /// ```
502 #[call(to_millis)]
503 pub const fn as_millis(&self) -> u64;
504
505 #[procmacros::doc_replace]
506 /// Convert the `Duration` to an interger number of seconds.
507 ///
508 /// ## Example
509 ///
510 /// ```rust, no_run
511 /// # {before_snippet}
512 /// use esp_hal::time::Duration;
513 /// let duration = Duration::from_secs(1);
514 /// let secs = duration.as_secs();
515 /// # {after_snippet}
516 /// ```
517 #[call(to_secs)]
518 pub const fn as_secs(&self) -> u64;
519
520 #[procmacros::doc_replace]
521 /// Convert the `Duration` to an interger number of minutes.
522 ///
523 /// ## Example
524 ///
525 /// ```rust, no_run
526 /// # {before_snippet}
527 /// use esp_hal::time::Duration;
528 /// let duration = Duration::from_minutes(1);
529 /// let minutes = duration.as_minutes();
530 /// # {after_snippet}
531 /// ```
532 #[call(to_minutes)]
533 pub const fn as_minutes(&self) -> u64;
534
535 #[procmacros::doc_replace]
536 /// Convert the `Duration` to an interger number of hours.
537 ///
538 /// ## Example
539 ///
540 /// ```rust, no_run
541 /// # {before_snippet}
542 /// use esp_hal::time::Duration;
543 /// let duration = Duration::from_hours(1);
544 /// let hours = duration.as_hours();
545 /// # {after_snippet}
546 /// ```
547 #[call(to_hours)]
548 pub const fn as_hours(&self) -> u64;
549 }
550 }
551
552 #[procmacros::doc_replace]
553 /// Add two durations while checking for overflow.
554 ///
555 /// ## Example
556 ///
557 /// ```rust, no_run
558 /// # {before_snippet}
559 /// use esp_hal::time::Duration;
560 /// let duration = Duration::from_secs(1);
561 /// let duration2 = Duration::from_secs(2);
562 ///
563 /// if let Some(sum) = duration.checked_add(duration2) {
564 /// println!("Sum: {}", sum);
565 /// } else {
566 /// println!("Overflow occurred");
567 /// }
568 /// # {after_snippet}
569 /// ```
570 #[inline]
571 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
572 if let Some(val) = self.0.checked_add(rhs.0) {
573 Some(Duration(val))
574 } else {
575 None
576 }
577 }
578
579 #[procmacros::doc_replace]
580 /// Subtract two durations while checking for overflow.
581 ///
582 /// ## Example
583 ///
584 /// ```rust, no_run
585 /// # {before_snippet}
586 /// use esp_hal::time::Duration;
587 /// let duration = Duration::from_secs(3);
588 /// let duration2 = Duration::from_secs(1);
589 ///
590 /// if let Some(diff) = duration.checked_sub(duration2) {
591 /// println!("Difference: {}", diff);
592 /// } else {
593 /// println!("Underflow occurred");
594 /// }
595 /// # {after_snippet}
596 /// ```
597 #[inline]
598 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
599 if let Some(val) = self.0.checked_sub(rhs.0) {
600 Some(Duration(val))
601 } else {
602 None
603 }
604 }
605
606 #[procmacros::doc_replace]
607 /// Add two durations, returning the maximum value if overflow occurred.
608 ///
609 /// ## Example
610 ///
611 /// ```rust, no_run
612 /// # {before_snippet}
613 /// use esp_hal::time::Duration;
614 /// let duration = Duration::from_secs(1);
615 /// let duration2 = Duration::from_secs(2);
616 ///
617 /// let sum = duration.saturating_add(duration2);
618 /// # {after_snippet}
619 /// ```
620 #[inline]
621 pub const fn saturating_add(self, rhs: Self) -> Self {
622 if let Some(val) = self.checked_add(rhs) {
623 val
624 } else {
625 Self::MAX
626 }
627 }
628
629 #[procmacros::doc_replace]
630 /// Subtract two durations, returning the minimum value if the result would
631 /// be negative.
632 ///
633 /// ## Example
634 ///
635 /// ```rust, no_run
636 /// # {before_snippet}
637 /// use esp_hal::time::Duration;
638 /// let duration = Duration::from_secs(3);
639 /// let duration2 = Duration::from_secs(1);
640 ///
641 /// let diff = duration.saturating_sub(duration2);
642 /// # {after_snippet}
643 /// ```
644 #[inline]
645 pub const fn saturating_sub(self, rhs: Self) -> Self {
646 if let Some(val) = self.checked_sub(rhs) {
647 val
648 } else {
649 Self::ZERO
650 }
651 }
652}
653
654impl core::ops::Add for Duration {
655 type Output = Self;
656
657 #[inline]
658 fn add(self, rhs: Self) -> Self::Output {
659 Duration(self.0 + rhs.0)
660 }
661}
662
663impl core::ops::AddAssign for Duration {
664 #[inline]
665 fn add_assign(&mut self, rhs: Self) {
666 self.0 += rhs.0;
667 }
668}
669
670impl core::ops::Sub for Duration {
671 type Output = Self;
672
673 #[inline]
674 fn sub(self, rhs: Self) -> Self::Output {
675 Duration(self.0 - rhs.0)
676 }
677}
678
679impl core::ops::SubAssign for Duration {
680 #[inline]
681 fn sub_assign(&mut self, rhs: Self) {
682 self.0 -= rhs.0;
683 }
684}
685
686impl core::ops::Mul<u32> for Duration {
687 type Output = Self;
688
689 #[inline]
690 fn mul(self, rhs: u32) -> Self::Output {
691 Duration(self.0 * rhs)
692 }
693}
694
695impl core::ops::Div<u32> for Duration {
696 type Output = Self;
697
698 #[inline]
699 fn div(self, rhs: u32) -> Self::Output {
700 Duration(self.0 / rhs)
701 }
702}
703
704impl core::ops::Div<Duration> for Duration {
705 type Output = u64;
706
707 #[inline]
708 fn div(self, rhs: Duration) -> Self::Output {
709 self.0 / rhs.0
710 }
711}
712
713#[inline]
714fn now() -> Instant {
715 #[cfg(esp32)]
716 let (ticks, div) = {
717 // on ESP32 use LACT
718 let tg0 = TIMG0::regs();
719 tg0.lactupdate().write(|w| unsafe { w.update().bits(1) });
720
721 // The peripheral doesn't have a bit to indicate that the update is done, so we
722 // poll the lower 32 bit part of the counter until it changes, or a timeout
723 // expires.
724 let lo_initial = tg0.lactlo().read().bits();
725 let mut div = tg0.lactconfig().read().divider().bits();
726 let lo = loop {
727 let lo = tg0.lactlo().read().bits();
728 if lo != lo_initial || div == 0 {
729 break lo;
730 }
731 div -= 1;
732 };
733 let hi = tg0.lacthi().read().bits();
734
735 let ticks = ((hi as u64) << 32u64) | lo as u64;
736 (ticks, 16)
737 };
738
739 #[cfg(not(esp32))]
740 let (ticks, div) = {
741 use crate::timer::systimer::{SystemTimer, Unit};
742 // otherwise use SYSTIMER
743 let ticks = SystemTimer::unit_value(Unit::Unit0);
744 (ticks, (SystemTimer::ticks_per_second() / 1_000_000))
745 };
746
747 Instant::from_ticks(ticks / div)
748}
749
750#[cfg(all(esp32, feature = "rt"))]
751pub(crate) fn time_init() {
752 let apb = crate::Clocks::get().apb_clock.as_hz();
753 // we assume 80MHz APB clock source - there is no way to configure it in a
754 // different way currently
755 assert_eq!(apb, 80_000_000u32);
756
757 let tg0 = TIMG0::regs();
758
759 tg0.lactconfig().write(|w| unsafe { w.bits(0) });
760 tg0.lactalarmhi().write(|w| unsafe { w.bits(u32::MAX) });
761 tg0.lactalarmlo().write(|w| unsafe { w.bits(u32::MAX) });
762 tg0.lactload().write(|w| unsafe { w.load().bits(1) });
763
764 // 16 MHz counter
765 tg0.lactconfig()
766 .modify(|_, w| unsafe { w.divider().bits((apb / 16_000_000u32) as u16) });
767 tg0.lactconfig().modify(|_, w| {
768 w.increase().bit(true);
769 w.autoreload().bit(true);
770 w.en().bit(true)
771 });
772}