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
9type InnerRate = fugit::Rate<u32, 1, 1>;
10type InnerInstant = fugit::Instant<u64, 1, 1_000_000, fugit::kind::Monotonic>;
11type InnerDuration = fugit::Duration<u64, 1, 1_000_000>;
12
13/// Represents a rate or frequency of events.
14#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
15pub struct Rate(InnerRate);
16
17impl core::hash::Hash for Rate {
18 #[inline]
19 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
20 self.as_hz().hash(state);
21 }
22}
23
24impl Display for Rate {
25 #[inline]
26 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
27 write!(f, "{} Hz", self.as_hz())
28 }
29}
30
31impl Debug for Rate {
32 #[inline]
33 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
34 write!(f, "Rate({} Hz)", self.as_hz())
35 }
36}
37
38#[cfg(feature = "defmt")]
39impl defmt::Format for Rate {
40 #[inline]
41 fn format(&self, f: defmt::Formatter<'_>) {
42 defmt::write!(f, "{=u32} Hz", self.as_hz())
43 }
44}
45
46impl Rate {
47 #[procmacros::doc_replace]
48 /// Creates a new rate that represents hertz.
49 ///
50 /// # Examples
51 ///
52 /// ```rust, no_run
53 /// # {before_snippet}
54 /// use esp_hal::time::Rate;
55 /// let rate = Rate::from_hz(1000);
56 /// # {after_snippet}
57 /// ```
58 #[inline]
59 pub const fn from_hz(val: u32) -> Self {
60 Self(InnerRate::Hz(val))
61 }
62
63 #[procmacros::doc_replace]
64 /// Creates a new rate that represents kilohertz.
65 ///
66 /// # Examples
67 ///
68 /// ```rust, no_run
69 /// # {before_snippet}
70 /// use esp_hal::time::Rate;
71 /// let rate = Rate::from_khz(1000);
72 /// # {after_snippet}
73 /// ```
74 #[inline]
75 pub const fn from_khz(val: u32) -> Self {
76 Self(InnerRate::kHz(val))
77 }
78
79 #[procmacros::doc_replace]
80 /// Creates a new rate that represents megahertz.
81 ///
82 /// # Examples
83 ///
84 /// ```rust, no_run
85 /// # {before_snippet}
86 /// use esp_hal::time::Rate;
87 /// let rate = Rate::from_mhz(1000);
88 /// # {after_snippet}
89 /// ```
90 #[inline]
91 pub const fn from_mhz(val: u32) -> Self {
92 Self(InnerRate::MHz(val))
93 }
94
95 #[procmacros::doc_replace]
96 /// Converts the `Rate` to an integer number of Hz.
97 ///
98 /// # Examples
99 ///
100 /// ```rust, no_run
101 /// # {before_snippet}
102 /// use esp_hal::time::Rate;
103 /// let rate = Rate::from_hz(1000);
104 /// let hz = rate.as_hz();
105 /// # {after_snippet}
106 /// ```
107 #[inline]
108 pub const fn as_hz(&self) -> u32 {
109 self.0.to_Hz()
110 }
111
112 #[procmacros::doc_replace]
113 /// Converts the `Rate` to an integer number of kHz.
114 ///
115 /// # Examples
116 ///
117 /// ```rust, no_run
118 /// # {before_snippet}
119 /// use esp_hal::time::Rate;
120 /// let rate = Rate::from_khz(1000);
121 /// let khz = rate.as_khz();
122 /// # {after_snippet}
123 /// ```
124 #[inline]
125 pub const fn as_khz(&self) -> u32 {
126 self.0.to_kHz()
127 }
128
129 #[procmacros::doc_replace]
130 /// Converts the `Rate` to an integer number of MHz.
131 ///
132 /// # Examples
133 ///
134 /// ```rust, no_run
135 /// # {before_snippet}
136 /// use esp_hal::time::Rate;
137 /// let rate = Rate::from_mhz(1000);
138 /// let mhz = rate.as_mhz();
139 /// # {after_snippet}
140 /// ```
141 #[inline]
142 pub const fn as_mhz(&self) -> u32 {
143 self.0.to_MHz()
144 }
145
146 #[procmacros::doc_replace]
147 /// Converts the `Rate` to a `Duration`.
148 ///
149 /// # Examples
150 ///
151 /// ```rust, no_run
152 /// # {before_snippet}
153 /// use esp_hal::time::Rate;
154 /// let rate = Rate::from_hz(1000);
155 /// let duration = rate.as_duration();
156 /// # {after_snippet}
157 /// ```
158 #[inline]
159 pub const fn as_duration(&self) -> Duration {
160 Duration::from_micros(1_000_000 / self.as_hz() as u64)
161 }
162}
163
164impl core::ops::Div for Rate {
165 type Output = u32;
166
167 #[inline]
168 fn div(self, rhs: Self) -> Self::Output {
169 self.0 / rhs.0
170 }
171}
172
173impl core::ops::Mul<u32> for Rate {
174 type Output = Rate;
175
176 #[inline]
177 fn mul(self, rhs: u32) -> Self::Output {
178 Rate(self.0 * rhs)
179 }
180}
181
182impl core::ops::Div<u32> for Rate {
183 type Output = Rate;
184
185 #[inline]
186 fn div(self, rhs: u32) -> Self::Output {
187 Rate(self.0 / rhs)
188 }
189}
190
191/// Represents an instant in time.
192#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
193pub struct Instant(InnerInstant);
194
195impl Debug for Instant {
196 #[inline]
197 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
198 write!(
199 f,
200 "Instant({} µs since epoch)",
201 self.duration_since_epoch().as_micros()
202 )
203 }
204}
205
206impl Display for Instant {
207 #[inline]
208 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
209 write!(
210 f,
211 "{} µs since epoch",
212 self.duration_since_epoch().as_micros()
213 )
214 }
215}
216
217#[cfg(feature = "defmt")]
218impl defmt::Format for Instant {
219 #[inline]
220 fn format(&self, f: defmt::Formatter<'_>) {
221 defmt::write!(
222 f,
223 "{=u64} µs since epoch",
224 self.duration_since_epoch().as_micros()
225 )
226 }
227}
228
229impl core::hash::Hash for Instant {
230 #[inline]
231 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
232 self.duration_since_epoch().hash(state);
233 }
234}
235
236impl Instant {
237 /// Represents the moment the system booted.
238 pub const EPOCH: Instant = Instant(InnerInstant::from_ticks(0));
239
240 #[procmacros::doc_replace(
241 "wrap_after" => {
242 cfg(esp32) => "36_558 years",
243 cfg(esp32s2) => "7_311 years",
244 _ => "more than 7 years"
245 }
246 )]
247 /// Returns the current instant.
248 ///
249 /// The counter does not measure time in sleep mode.
250 ///
251 /// The timer has a 1 microsecond resolution and wraps after __wrap_after__.
252 ///
253 /// <section class="warning">
254 /// Returns an unreliable value before <code>esp_hal::init()</code> is called.
255 /// </section>
256 ///
257 /// # Examples
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 /// # Examples
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 /// # Examples
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 #[procmacros::doc_replace]
310 /// Subtracts `other` from this `Instant`, returning [`Duration::ZERO`] if
311 /// `other` is later than this `Instant`.
312 ///
313 /// # Examples
314 ///
315 /// ```rust, no_run
316 /// # {before_snippet}
317 /// use esp_hal::time::{Duration, Instant};
318 /// let deadline = Instant::now() + Duration::from_millis(10);
319 /// let remaining = deadline.saturating_sub(Instant::now());
320 /// # {after_snippet}
321 /// ```
322 #[inline]
323 #[instability::unstable]
324 pub fn saturating_sub(self, other: Instant) -> Duration {
325 if self > other {
326 self - other
327 } else {
328 Duration::ZERO
329 }
330 }
331}
332
333impl core::ops::Add<Duration> for Instant {
334 type Output = Self;
335
336 #[inline]
337 fn add(self, rhs: Duration) -> Self::Output {
338 Instant(self.0 + rhs.0)
339 }
340}
341
342impl core::ops::AddAssign<Duration> for Instant {
343 #[inline]
344 fn add_assign(&mut self, rhs: Duration) {
345 self.0 += rhs.0;
346 }
347}
348
349impl core::ops::Sub for Instant {
350 type Output = Duration;
351
352 #[inline]
353 fn sub(self, rhs: Self) -> Self::Output {
354 Duration(self.0 - rhs.0)
355 }
356}
357
358impl core::ops::Sub<Duration> for Instant {
359 type Output = Self;
360
361 #[inline]
362 fn sub(self, rhs: Duration) -> Self::Output {
363 Instant(self.0 - rhs.0)
364 }
365}
366
367impl core::ops::SubAssign<Duration> for Instant {
368 #[inline]
369 fn sub_assign(&mut self, rhs: Duration) {
370 self.0 -= rhs.0;
371 }
372}
373
374/// Represents a duration of time.
375#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
376pub struct Duration(InnerDuration);
377
378impl Debug for Duration {
379 #[inline]
380 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
381 write!(f, "Duration({} µs)", self.as_micros())
382 }
383}
384
385impl Display for Duration {
386 #[inline]
387 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
388 write!(f, "{} µs", self.as_micros())
389 }
390}
391
392#[cfg(feature = "defmt")]
393impl defmt::Format for Duration {
394 #[inline]
395 fn format(&self, f: defmt::Formatter<'_>) {
396 defmt::write!(f, "{=u64} µs", self.as_micros())
397 }
398}
399
400impl core::hash::Hash for Duration {
401 #[inline]
402 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
403 self.as_micros().hash(state);
404 }
405}
406
407impl Default for Duration {
408 #[inline]
409 fn default() -> Self {
410 Self::ZERO
411 }
412}
413
414impl Duration {
415 /// A duration of zero time.
416 pub const ZERO: Self = Self(InnerDuration::from_ticks(0));
417
418 /// A duration representing the maximum possible time.
419 pub const MAX: Self = Self(InnerDuration::from_ticks(u64::MAX));
420
421 #[procmacros::doc_replace]
422 /// Creates a new duration that represents microseconds.
423 ///
424 /// # Examples
425 ///
426 /// ```rust, no_run
427 /// # {before_snippet}
428 /// use esp_hal::time::Duration;
429 /// let duration = Duration::from_micros(1000);
430 /// # {after_snippet}
431 /// ```
432 #[inline]
433 pub const fn from_micros(val: u64) -> Self {
434 Self(InnerDuration::from_micros(val))
435 }
436
437 #[procmacros::doc_replace]
438 /// Creates a new duration that represents milliseconds.
439 ///
440 /// # Examples
441 ///
442 /// ```rust, no_run
443 /// # {before_snippet}
444 /// use esp_hal::time::Duration;
445 /// let duration = Duration::from_millis(100);
446 /// # {after_snippet}
447 /// ```
448 #[inline]
449 pub const fn from_millis(val: u64) -> Self {
450 Self(InnerDuration::from_millis(val))
451 }
452
453 #[procmacros::doc_replace]
454 /// Creates a new duration that represents seconds.
455 ///
456 /// # Examples
457 ///
458 /// ```rust, no_run
459 /// # {before_snippet}
460 /// use esp_hal::time::Duration;
461 /// let duration = Duration::from_secs(1);
462 /// # {after_snippet}
463 /// ```
464 #[inline]
465 pub const fn from_secs(val: u64) -> Self {
466 Self(InnerDuration::from_secs(val))
467 }
468
469 #[procmacros::doc_replace]
470 /// Creates a new duration that represents minutes.
471 ///
472 /// # Examples
473 ///
474 /// ```rust, no_run
475 /// # {before_snippet}
476 /// use esp_hal::time::Duration;
477 /// let duration = Duration::from_minutes(1);
478 /// # {after_snippet}
479 /// ```
480 #[inline]
481 pub const fn from_minutes(val: u64) -> Self {
482 Self(InnerDuration::from_minutes(val))
483 }
484
485 #[procmacros::doc_replace]
486 /// Creates a new duration that represents hours.
487 ///
488 /// # Examples
489 ///
490 /// ```rust, no_run
491 /// # {before_snippet}
492 /// use esp_hal::time::Duration;
493 /// let duration = Duration::from_hours(1);
494 /// # {after_snippet}
495 /// ```
496 #[inline]
497 pub const fn from_hours(val: u64) -> Self {
498 Self(InnerDuration::from_hours(val))
499 }
500
501 delegate::delegate! {
502 #[inline]
503 to self.0 {
504 #[procmacros::doc_replace]
505 /// Converts the `Duration` to an integer number of microseconds.
506 ///
507 /// # Examples
508 ///
509 /// ```rust, no_run
510 /// # {before_snippet}
511 /// use esp_hal::time::Duration;
512 /// let duration = Duration::from_micros(1000);
513 /// let micros = duration.as_micros();
514 /// # {after_snippet}
515 /// ```
516 pub const fn as_micros(&self) -> u64;
517
518 #[procmacros::doc_replace]
519 /// Converts the `Duration` to an integer number of milliseconds.
520 ///
521 /// # Examples
522 ///
523 /// ```rust, no_run
524 /// # {before_snippet}
525 /// use esp_hal::time::Duration;
526 /// let duration = Duration::from_millis(100);
527 /// let millis = duration.as_millis();
528 /// # {after_snippet}
529 /// ```
530 pub const fn as_millis(&self) -> u64;
531
532 #[procmacros::doc_replace]
533 /// Converts the `Duration` to an integer number of seconds.
534 ///
535 /// # Examples
536 ///
537 /// ```rust, no_run
538 /// # {before_snippet}
539 /// use esp_hal::time::Duration;
540 /// let duration = Duration::from_secs(1);
541 /// let secs = duration.as_secs();
542 /// # {after_snippet}
543 /// ```
544 pub const fn as_secs(&self) -> u64;
545
546 #[procmacros::doc_replace]
547 /// Converts the `Duration` to an integer number of minutes.
548 ///
549 /// # Examples
550 ///
551 /// ```rust, no_run
552 /// # {before_snippet}
553 /// use esp_hal::time::Duration;
554 /// let duration = Duration::from_minutes(1);
555 /// let minutes = duration.as_minutes();
556 /// # {after_snippet}
557 /// ```
558 pub const fn as_minutes(&self) -> u64;
559
560 #[procmacros::doc_replace]
561 /// Converts the `Duration` to an integer number of hours.
562 ///
563 /// # Examples
564 ///
565 /// ```rust, no_run
566 /// # {before_snippet}
567 /// use esp_hal::time::Duration;
568 /// let duration = Duration::from_hours(1);
569 /// let hours = duration.as_hours();
570 /// # {after_snippet}
571 /// ```
572 pub const fn as_hours(&self) -> u64;
573 }
574 }
575
576 #[procmacros::doc_replace]
577 /// Adds two durations while checking for overflow.
578 ///
579 /// # Examples
580 ///
581 /// ```rust, no_run
582 /// # {before_snippet}
583 /// use esp_hal::time::Duration;
584 /// let duration = Duration::from_secs(1);
585 /// let duration2 = Duration::from_secs(2);
586 ///
587 /// if let Some(sum) = duration.checked_add(duration2) {
588 /// println!("Sum: {}", sum);
589 /// } else {
590 /// println!("Overflow occurred");
591 /// }
592 /// # {after_snippet}
593 /// ```
594 #[inline]
595 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
596 if let Some(val) = self.0.checked_add(rhs.0) {
597 Some(Duration(val))
598 } else {
599 None
600 }
601 }
602
603 #[procmacros::doc_replace]
604 /// Subtract two durations while checking for overflow.
605 ///
606 /// # Examples
607 ///
608 /// ```rust, no_run
609 /// # {before_snippet}
610 /// use esp_hal::time::Duration;
611 /// let duration = Duration::from_secs(3);
612 /// let duration2 = Duration::from_secs(1);
613 ///
614 /// if let Some(diff) = duration.checked_sub(duration2) {
615 /// println!("Difference: {}", diff);
616 /// } else {
617 /// println!("Underflow occurred");
618 /// }
619 /// # {after_snippet}
620 /// ```
621 #[inline]
622 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
623 if let Some(val) = self.0.checked_sub(rhs.0) {
624 Some(Duration(val))
625 } else {
626 None
627 }
628 }
629
630 #[procmacros::doc_replace]
631 /// Adds two durations, returning the maximum value if overflow occurred.
632 ///
633 /// # Examples
634 ///
635 /// ```rust, no_run
636 /// # {before_snippet}
637 /// use esp_hal::time::Duration;
638 /// let duration = Duration::from_secs(1);
639 /// let duration2 = Duration::from_secs(2);
640 ///
641 /// let sum = duration.saturating_add(duration2);
642 /// # {after_snippet}
643 /// ```
644 #[inline]
645 pub const fn saturating_add(self, rhs: Self) -> Self {
646 if let Some(val) = self.checked_add(rhs) {
647 val
648 } else {
649 Self::MAX
650 }
651 }
652
653 #[procmacros::doc_replace]
654 /// Subtract two durations, returning the minimum value if the result would
655 /// be negative.
656 ///
657 /// # Examples
658 ///
659 /// ```rust, no_run
660 /// # {before_snippet}
661 /// use esp_hal::time::Duration;
662 /// let duration = Duration::from_secs(3);
663 /// let duration2 = Duration::from_secs(1);
664 ///
665 /// let diff = duration.saturating_sub(duration2);
666 /// # {after_snippet}
667 /// ```
668 #[inline]
669 pub const fn saturating_sub(self, rhs: Self) -> Self {
670 if let Some(val) = self.checked_sub(rhs) {
671 val
672 } else {
673 Self::ZERO
674 }
675 }
676}
677
678impl core::ops::Add for Duration {
679 type Output = Self;
680
681 #[inline]
682 fn add(self, rhs: Self) -> Self::Output {
683 Duration(self.0 + rhs.0)
684 }
685}
686
687impl core::ops::AddAssign for Duration {
688 #[inline]
689 fn add_assign(&mut self, rhs: Self) {
690 self.0 += rhs.0;
691 }
692}
693
694impl core::ops::Sub for Duration {
695 type Output = Self;
696
697 #[inline]
698 fn sub(self, rhs: Self) -> Self::Output {
699 Duration(self.0 - rhs.0)
700 }
701}
702
703impl core::ops::SubAssign for Duration {
704 #[inline]
705 fn sub_assign(&mut self, rhs: Self) {
706 self.0 -= rhs.0;
707 }
708}
709
710impl core::ops::Mul<u32> for Duration {
711 type Output = Self;
712
713 #[inline]
714 fn mul(self, rhs: u32) -> Self::Output {
715 Duration(self.0 * rhs)
716 }
717}
718
719impl core::ops::Div<u32> for Duration {
720 type Output = Self;
721
722 #[inline]
723 fn div(self, rhs: u32) -> Self::Output {
724 Duration(self.0 / rhs)
725 }
726}
727
728impl core::ops::Div<Duration> for Duration {
729 type Output = u64;
730
731 #[inline]
732 fn div(self, rhs: Duration) -> Self::Output {
733 self.0 / rhs.0
734 }
735}
736
737#[inline]
738pub(crate) fn now() -> Instant {
739 let ticks = implem::raw_counter();
740 let micros = implem::ticks_to_us(ticks);
741
742 Instant::from_ticks(micros)
743}
744
745#[cfg(esp32)]
746pub(crate) mod implem {
747 use esp_sync::RawMutex;
748
749 use crate::peripherals::TIMG0;
750
751 #[cfg(feature = "rt")]
752 pub(crate) fn time_init() {
753 // FIXME: does this imply that clock management needs to be "rt", too?
754 let apb = crate::soc::clocks::apb_clk_frequency();
755
756 let tg0 = TIMG0::regs();
757
758 tg0.lactconfig().write(|w| unsafe { w.bits(0) });
759 tg0.lactalarmhi().write(|w| unsafe { w.bits(u32::MAX) });
760 tg0.lactalarmlo().write(|w| unsafe { w.bits(u32::MAX) });
761 tg0.lactload().write(|w| unsafe { w.load().bits(1) });
762
763 // 16 MHz counter
764 tg0.lactconfig().write(|w| {
765 unsafe { w.divider().bits((apb / 16_000_000u32) as u16) };
766 w.increase().bit(true);
767 w.autoreload().bit(true);
768 w.en().bit(true)
769 });
770 }
771
772 #[inline]
773 pub(crate) fn raw_counter() -> u64 {
774 // The latch is shared between cores, so we need additional locking
775 static LACT_LOCK: RawMutex = RawMutex::new();
776
777 // on ESP32 use LACT
778 let tg0 = TIMG0::regs();
779 let (hi, lo) = LACT_LOCK.lock(|| {
780 tg0.lactupdate().write(|w| unsafe { w.update().bits(1) });
781
782 // The peripheral doesn't have a bit to indicate that the update is done, so we
783 // poll the lower 32 bit part of the counter until it changes, or a timeout
784 // expires.
785 let lo_initial = tg0.lactlo().read().bits();
786 let mut div = tg0.lactconfig().read().divider().bits();
787 let lo = loop {
788 let lo = tg0.lactlo().read().bits();
789 if lo != lo_initial || div == 0 {
790 break lo;
791 }
792 div -= 1;
793 };
794 let hi = tg0.lacthi().read().bits();
795
796 (hi, lo)
797 });
798
799 ((hi as u64) << 32u64) | lo as u64
800 }
801
802 #[inline]
803 pub(crate) fn ticks_to_us(ticks: u64) -> u64 {
804 ticks / 16
805 }
806
807 #[inline]
808 #[cfg(all(sleep_light_sleep, feature = "rt"))]
809 pub(crate) fn us_to_ticks(counter: u64) -> u64 {
810 counter * 16
811 }
812
813 /// Callers must ensure this function is not called concurrently.
814 #[inline]
815 #[cfg(all(sleep_light_sleep, feature = "rt"))]
816 pub(crate) unsafe fn update_counter(counter: u64) {
817 // On ESP32 the monotonic counter is the LACT timer of TIMG0. To set its
818 // value we stage the new 64-bit count in the load registers and then
819 // trigger a software reload, which copies the staged value into the
820 // counter immediately.
821 //
822 // A manual `LACTLOAD` while the timer is running (`en = 1`) is silently
823 // dropped when executed from the AppCpu, leaving the monotonic clock stuck
824 // (this is why the post-light-sleep time correction is lost on AppCpu). We
825 // therefore disable the timer around the load (preserving the divider) and
826 // re-enable it afterwards, mirroring `time_init`. Callers run this with
827 // interrupts disabled and the other core parked, so the brief disable is
828 // safe from concurrent reads.
829 let tg0 = TIMG0::regs();
830
831 let divider = tg0.lactconfig().read().divider().bits();
832 tg0.lactconfig().write(|w| unsafe { w.bits(0) });
833
834 tg0.lactloadhi()
835 .write(|w| unsafe { w.load_hi().bits((counter >> 32) as u32) });
836 tg0.lactloadlo()
837 .write(|w| unsafe { w.load_lo().bits(counter as u32) });
838 tg0.lactload().write(|w| unsafe { w.load().bits(1) });
839
840 tg0.lactconfig().write(|w| {
841 unsafe { w.divider().bits(divider) };
842 w.increase().bit(true);
843 w.autoreload().bit(true);
844 w.en().bit(true)
845 });
846 }
847}
848
849#[cfg(systimer_driver_supported)]
850pub(crate) mod implem {
851 use crate::timer::systimer::{SystemTimer, Unit};
852
853 #[cfg(feature = "rt")]
854 pub(crate) fn time_init() {
855 SystemTimer::init_timestamp_scaler();
856 }
857
858 #[inline]
859 pub(crate) fn raw_counter() -> u64 {
860 SystemTimer::unit_value(Unit::Unit0)
861 }
862
863 #[inline]
864 pub(crate) fn ticks_to_us(ticks: u64) -> u64 {
865 SystemTimer::ticks_to_us(ticks)
866 }
867
868 #[inline]
869 #[cfg(all(sleep_light_sleep, feature = "rt"))]
870 pub(crate) fn us_to_ticks(counter: u64) -> u64 {
871 SystemTimer::us_to_ticks(counter)
872 }
873
874 /// Callers must ensure this function is not called concurrently.
875 #[inline]
876 #[cfg(all(sleep_light_sleep, feature = "rt"))]
877 pub(crate) unsafe fn update_counter(counter: u64) {
878 unsafe {
879 SystemTimer::set_unit_value(Unit::Unit0, counter);
880 }
881 }
882}