esp_hal/timer/systimer.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
//! # System Timer (SYSTIMER)
//!
//! ## Overview
//! The System Timer is a
#![cfg_attr(esp32s2, doc = "64-bit")]
#![cfg_attr(not(esp32s2), doc = "52-bit")]
//! timer which can be used, for example, to generate tick interrupts for an
//! operating system, or simply as a general-purpose timer.
//!
//! ## Configuration
//!
//! The timer consists of two counters, `UNIT0` and `UNIT1`. The counter values
//! can be monitored by 3 comparators, `COMP0`, `COMP1`, and `COMP2`.
//!
//! [Alarm]s can be configured in two modes: [Target] (one-shot) and [Periodic].
//!
//! ## Examples
//!
//! ### Splitting up the System Timer into three alarms
//!
//! Use the [split][SystemTimer::split] method to create three alarms from the
//! System Timer, contained in a [SysTimerAlarms] struct.
//!
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! use esp_hal::timer::systimer::{
//! SystemTimer,
//! Periodic,
//! };
//!
//! let systimer = SystemTimer::new(
//! peripherals.SYSTIMER,
//! ).split::<Periodic>();
//!
//! // Reconfigure a periodic alarm to be a target alarm
//! let target_alarm = systimer.alarm0.into_target();
//! # }
//! ```
//!
//! ### General-purpose Timer
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! use esp_hal::timer::systimer::{
//! Alarm,
//! FrozenUnit,
//! SpecificUnit,
//! SystemTimer,
//! };
//!
//! let mut systimer = SystemTimer::new(peripherals.SYSTIMER);
//!
//! // Get the current tick count:
//! let now = SystemTimer::now();
//!
//! let frozen_unit = FrozenUnit::new(&mut systimer.unit0);
//! let alarm0 = Alarm::new(systimer.comparator0, &frozen_unit);
//!
//! alarm0.set_target(
//! SystemTimer::now() + SystemTimer::ticks_per_second() * 2
//! );
//! alarm0.enable_interrupt(true);
//!
//! while !alarm0.is_interrupt_set() {
//! // Wait for the interrupt to be set
//! }
//!
//! alarm0.clear_interrupt();
//! # }
//! ```
use core::{
fmt::{Debug, Formatter},
marker::PhantomData,
ptr::addr_of_mut,
};
use fugit::{Instant, MicrosDurationU32, MicrosDurationU64};
use super::{Error, Timer as _};
use crate::{
interrupt::{self, InterruptHandler},
peripheral::Peripheral,
peripherals::{Interrupt, SYSTIMER},
sync::{lock, Lock},
system::{Peripheral as PeripheralEnable, PeripheralClockControl},
Async,
Blocking,
Cpu,
InterruptConfigurable,
Mode,
};
/// System Timer driver.
pub struct SystemTimer<'d> {
/// Unit 0
pub unit0: SpecificUnit<'d, 0>,
#[cfg(not(esp32s2))]
/// Unit 1
pub unit1: SpecificUnit<'d, 1>,
/// Comparator 0.
pub comparator0: SpecificComparator<'d, 0>,
/// Comparator 1.
pub comparator1: SpecificComparator<'d, 1>,
/// Comparator 2.
pub comparator2: SpecificComparator<'d, 2>,
}
impl<'d> SystemTimer<'d> {
cfg_if::cfg_if! {
if #[cfg(esp32s2)] {
/// Bitmask to be applied to the raw register value.
pub const BIT_MASK: u64 = u64::MAX;
// Bitmask to be applied to the raw period register value.
const PERIOD_MASK: u64 = 0x1FFF_FFFF;
} else {
/// Bitmask to be applied to the raw register value.
pub const BIT_MASK: u64 = 0xF_FFFF_FFFF_FFFF;
// Bitmask to be applied to the raw period register value.
const PERIOD_MASK: u64 = 0x3FF_FFFF;
}
}
/// Returns the tick frequency of the underlying timer unit.
pub fn ticks_per_second() -> u64 {
cfg_if::cfg_if! {
if #[cfg(esp32s2)] {
const MULTIPLIER: u64 = 2_000_000;
} else if #[cfg(esp32h2)] {
// The counters and comparators are driven using `XTAL_CLK`.
// The average clock frequency is fXTAL_CLK/2, which is 16 MHz.
// The timer counting is incremented by 1/16 μs on each `CNT_CLK` cycle.
const MULTIPLIER: u64 = 10_000_000 / 20;
} else {
// The counters and comparators are driven using `XTAL_CLK`.
// The average clock frequency is fXTAL_CLK/2.5, which is 16 MHz.
// The timer counting is incremented by 1/16 μs on each `CNT_CLK` cycle.
const MULTIPLIER: u64 = 10_000_000 / 25;
}
}
let xtal_freq_mhz = crate::clock::Clocks::xtal_freq().to_MHz();
xtal_freq_mhz as u64 * MULTIPLIER
}
/// Create a new instance.
pub fn new(_systimer: impl Peripheral<P = SYSTIMER> + 'd) -> Self {
// Don't reset Systimer as it will break `time::now`, only enable it
PeripheralClockControl::enable(PeripheralEnable::Systimer);
#[cfg(soc_etm)]
etm::enable_etm();
Self {
unit0: SpecificUnit::new(),
#[cfg(not(esp32s2))]
unit1: SpecificUnit::new(),
comparator0: SpecificComparator::new(),
comparator1: SpecificComparator::new(),
comparator2: SpecificComparator::new(),
}
}
/// Get the current count of Unit 0 in the System Timer.
pub fn now() -> u64 {
// This should be safe to access from multiple contexts
// worst case scenario the second accessor ends up reading
// an older time stamp
let unit = unsafe { SpecificUnit::<'_, 0>::conjure() };
unit.read_count()
}
}
impl SystemTimer<'static> {
/// Split the System Timer into three alarms.
///
/// This is a convenience method to create `'static` alarms of the same
/// type. You are encouraged to use [Alarm::new] over this very specific
/// helper.
pub fn split<MODE>(self) -> SysTimerAlarms<MODE, Blocking> {
static mut UNIT0: Option<AnyUnit<'static>> = None;
let unit0 = unsafe { &mut *addr_of_mut!(UNIT0) };
let unit0 = unit0.insert(self.unit0.into());
let unit = FrozenUnit::new(unit0);
SysTimerAlarms {
alarm0: Alarm::new(self.comparator0.into(), &unit),
alarm1: Alarm::new(self.comparator1.into(), &unit),
alarm2: Alarm::new(self.comparator2.into(), &unit),
#[cfg(not(esp32s2))]
unit1: self.unit1,
}
}
/// Split the System Timer into three alarms.
///
/// This is a convenience method to create `'static` alarms of the same
/// type. You are encouraged to use [Alarm::new_async] over this very
/// specific helper.
pub fn split_async<MODE>(self) -> SysTimerAlarms<MODE, Async> {
static mut UNIT0: Option<AnyUnit<'static>> = None;
let unit0 = unsafe { &mut *addr_of_mut!(UNIT0) };
let unit0 = unit0.insert(self.unit0.into());
let unit = FrozenUnit::new(unit0);
SysTimerAlarms {
alarm0: Alarm::new_async(self.comparator0.into(), &unit),
alarm1: Alarm::new_async(self.comparator1.into(), &unit),
alarm2: Alarm::new_async(self.comparator2.into(), &unit),
#[cfg(not(esp32s2))]
unit1: self.unit1,
}
}
}
/// A
#[cfg_attr(esp32s2, doc = "64-bit")]
#[cfg_attr(not(esp32s2), doc = "52-bit")]
/// counter.
pub trait Unit {
/// Returns the unit number.
fn channel(&self) -> u8;
#[cfg(not(esp32s2))]
/// Configures when this counter can run.
/// It can be configured to stall or continue running when CPU stalls
/// or enters on-chip-debugging mode
fn configure(&self, config: UnitConfig) {
let systimer = unsafe { &*SYSTIMER::ptr() };
let conf = systimer.conf();
lock(&CONF_LOCK, || {
conf.modify(|_, w| match config {
UnitConfig::Disabled => match self.channel() {
0 => w.timer_unit0_work_en().clear_bit(),
1 => w.timer_unit1_work_en().clear_bit(),
_ => unreachable!(),
},
UnitConfig::DisabledIfCpuIsStalled(cpu) => match self.channel() {
0 => {
w.timer_unit0_work_en().set_bit();
w.timer_unit0_core0_stall_en().bit(cpu == Cpu::ProCpu);
w.timer_unit0_core1_stall_en().bit(cpu != Cpu::ProCpu)
}
1 => {
w.timer_unit1_work_en().set_bit();
w.timer_unit1_core0_stall_en().bit(cpu == Cpu::ProCpu);
w.timer_unit1_core1_stall_en().bit(cpu != Cpu::ProCpu)
}
_ => unreachable!(),
},
UnitConfig::Enabled => match self.channel() {
0 => {
w.timer_unit0_work_en().set_bit();
w.timer_unit0_core0_stall_en().clear_bit();
w.timer_unit0_core1_stall_en().clear_bit()
}
1 => {
w.timer_unit1_work_en().set_bit();
w.timer_unit1_core0_stall_en().clear_bit();
w.timer_unit1_core1_stall_en().clear_bit()
}
_ => unreachable!(),
},
});
});
}
/// Set the value of the counter immediately. If the unit is at work,
/// the counter will continue to count up from the new reloaded value.
///
/// This can be used to load back the sleep time recorded by RTC timer
/// via software after Light-sleep
fn set_count(&self, value: u64) {
let systimer = unsafe { &*SYSTIMER::ptr() };
#[cfg(not(esp32s2))]
{
let unitload = systimer.unitload(self.channel() as _);
let unit_load = systimer.unit_load(self.channel() as _);
unitload.hi().write(|w| w.load_hi().set((value << 32) as _));
unitload
.lo()
.write(|w| w.load_lo().set((value & 0xFFFF_FFFF) as _));
unit_load.write(|w| w.load().set_bit());
}
#[cfg(esp32s2)]
{
systimer
.load_hi()
.write(|w| w.load_hi().set((value << 32) as _));
systimer
.load_lo()
.write(|w| w.load_lo().set((value & 0xFFFF_FFFF) as _));
systimer.load().write(|w| w.load().set_bit());
}
}
/// Reads the current counter value.
fn read_count(&self) -> u64 {
// This can be a shared reference as long as this type isn't Sync.
let channel = self.channel() as usize;
let systimer = unsafe { SYSTIMER::steal() };
systimer.unit_op(channel).write(|w| w.update().set_bit());
while !systimer.unit_op(channel).read().value_valid().bit_is_set() {}
// Read LO, HI, then LO again, check that LO returns the same value.
// This accounts for the case when an interrupt may happen between reading
// HI and LO values (or the other core updates the counter mid-read), and this
// function may get called from the ISR. In this case, the repeated read
// will return consistent values.
let unit_value = systimer.unit_value(channel);
let mut lo_prev = unit_value.lo().read().bits();
loop {
let lo = lo_prev;
let hi = unit_value.hi().read().bits();
lo_prev = unit_value.lo().read().bits();
if lo == lo_prev {
return ((hi as u64) << 32) | lo as u64;
}
}
}
}
/// A specific [Unit]. i.e. Either unit 0 or unit 1.
#[derive(Debug)]
pub struct SpecificUnit<'d, const CHANNEL: u8>(PhantomData<&'d ()>);
impl<const CHANNEL: u8> SpecificUnit<'_, CHANNEL> {
fn new() -> Self {
Self(PhantomData)
}
}
impl<const CHANNEL: u8> Unit for SpecificUnit<'_, CHANNEL> {
fn channel(&self) -> u8 {
CHANNEL
}
}
/// Any [Unit]. Could be either unit 0 or unit 1.
#[derive(Debug)]
pub struct AnyUnit<'d>(PhantomData<&'d ()>, u8);
impl Unit for AnyUnit<'_> {
fn channel(&self) -> u8 {
self.1
}
}
impl<'d, const CHANNEL: u8> From<SpecificUnit<'d, CHANNEL>> for AnyUnit<'d> {
fn from(_value: SpecificUnit<'d, CHANNEL>) -> Self {
Self(PhantomData, CHANNEL)
}
}
impl<'d, const CHANNEL: u8> TryFrom<AnyUnit<'d>> for SpecificUnit<'d, CHANNEL> {
type Error = u8;
fn try_from(value: AnyUnit<'d>) -> Result<Self, Self::Error> {
if value.1 == CHANNEL {
Ok(SpecificUnit::new())
} else {
Err(value.1)
}
}
}
/// A comparator that can generate alarms/interrupts based on values of a unit.
pub trait Comparator {
/// Returns the comparators number.
fn channel(&self) -> u8;
/// Enables/disables the comparator. If enabled, this means
/// it will generate interrupt based on its configuration.
fn set_enable(&self, enable: bool) {
let systimer = unsafe { &*SYSTIMER::ptr() };
lock(&CONF_LOCK, || {
#[cfg(not(esp32s2))]
systimer.conf().modify(|_, w| match self.channel() {
0 => w.target0_work_en().bit(enable),
1 => w.target1_work_en().bit(enable),
2 => w.target2_work_en().bit(enable),
_ => unreachable!(),
});
});
// Note: The ESP32-S2 doesn't require a lock because each
// comparator's enable bit in a different register.
#[cfg(esp32s2)]
systimer
.target_conf(self.channel() as usize)
.modify(|_r, w| w.work_en().bit(enable));
}
/// Returns true if the comparator has been enabled. This means
/// it will generate interrupt based on its configuration.
fn is_enabled(&self) -> bool {
#[cfg(not(esp32s2))]
{
let systimer = unsafe { &*SYSTIMER::ptr() };
let conf = systimer.conf().read();
match self.channel() {
0 => conf.target0_work_en().bit(),
1 => conf.target1_work_en().bit(),
2 => conf.target2_work_en().bit(),
_ => unreachable!(),
}
}
#[cfg(esp32s2)]
{
let tconf = unsafe {
let systimer = &*SYSTIMER::ptr();
systimer.target_conf(self.channel() as usize)
};
tconf.read().work_en().bit()
}
}
/// Sets the unit this comparator uses as a reference count.
#[cfg(not(esp32s2))]
fn set_unit(&self, is_unit0: bool) {
let tconf = unsafe {
let systimer = &*SYSTIMER::ptr();
systimer.target_conf(self.channel() as usize)
};
tconf.modify(|_, w| w.timer_unit_sel().bit(is_unit0));
}
/// Set the mode of the comparator to be either target or periodic.
fn set_mode(&self, mode: ComparatorMode) {
let tconf = unsafe {
let systimer = &*SYSTIMER::ptr();
systimer.target_conf(self.channel() as usize)
};
let is_period_mode = match mode {
ComparatorMode::Period => true,
ComparatorMode::Target => false,
};
tconf.modify(|_, w| w.period_mode().bit(is_period_mode));
}
/// Get the current mode of the comparator, which is either target or
/// periodic.
fn mode(&self) -> ComparatorMode {
let tconf = unsafe {
let systimer = &*SYSTIMER::ptr();
systimer.target_conf(self.channel() as usize)
};
if tconf.read().period_mode().bit() {
ComparatorMode::Period
} else {
ComparatorMode::Target
}
}
/// Set how often the comparator should generate an interrupt when in
/// periodic mode.
fn set_period(&self, value: u32) {
unsafe {
let systimer = &*SYSTIMER::ptr();
let tconf = systimer.target_conf(self.channel() as usize);
tconf.modify(|_, w| w.period().bits(value));
#[cfg(not(esp32s2))]
{
let comp_load = systimer.comp_load(self.channel() as usize);
comp_load.write(|w| w.load().set_bit());
}
}
}
/// Set when the comparator should generate an interrupt in target mode.
fn set_target(&self, value: u64) {
let systimer = unsafe { &*SYSTIMER::ptr() };
let target = systimer.trgt(self.channel() as usize);
target.hi().write(|w| w.hi().set((value >> 32) as u32));
target
.lo()
.write(|w| w.lo().set((value & 0xFFFF_FFFF) as u32));
#[cfg(not(esp32s2))]
{
let comp_load = systimer.comp_load(self.channel() as usize);
comp_load.write(|w| w.load().set_bit());
}
}
/// Get the actual target value of the comparator.
fn actual_target(&self) -> u64 {
let target = unsafe {
let systimer = &*SYSTIMER::ptr();
systimer.trgt(self.channel() as usize)
};
let hi = target.hi().read().hi().bits();
let lo = target.lo().read().lo().bits();
((hi as u64) << 32) | (lo as u64)
}
/// Set the interrupt handler for this comparator.
fn set_interrupt_handler(&self, handler: InterruptHandler) {
let interrupt = match self.channel() {
0 => Interrupt::SYSTIMER_TARGET0,
1 => Interrupt::SYSTIMER_TARGET1,
2 => Interrupt::SYSTIMER_TARGET2,
_ => unreachable!(),
};
for core in crate::Cpu::other() {
crate::interrupt::disable(core, interrupt);
}
#[cfg(not(esp32s2))]
unsafe {
interrupt::bind_interrupt(interrupt, handler.handler());
}
#[cfg(esp32s2)]
{
// ESP32-S2 Systimer interrupts are edge triggered. Our interrupt
// handler calls each of the handlers, regardless of which one triggered the
// interrupt. This mess registers an intermediate handler that
// checks if an interrupt is active before calling the associated
// handler functions.
static mut HANDLERS: [Option<extern "C" fn()>; 3] = [None, None, None];
#[crate::prelude::ram]
unsafe extern "C" fn _handle_interrupt<const CH: u8>() {
if unsafe { &*SYSTIMER::PTR }
.int_raw()
.read()
.target(CH)
.bit_is_set()
{
let handler = unsafe { HANDLERS[CH as usize] };
if let Some(handler) = handler {
handler();
}
}
}
unsafe {
HANDLERS[self.channel() as usize] = Some(handler.handler());
let handler = match self.channel() {
0 => _handle_interrupt::<0>,
1 => _handle_interrupt::<1>,
2 => _handle_interrupt::<2>,
_ => unreachable!(),
};
interrupt::bind_interrupt(interrupt, handler);
}
}
unwrap!(interrupt::enable(interrupt, handler.priority()));
}
}
/// A specific [Comparator]. i.e. Either comparator 0, comparator 1, etc.
#[derive(Debug)]
pub struct SpecificComparator<'d, const CHANNEL: u8>(PhantomData<&'d ()>);
impl<const CHANNEL: u8> SpecificComparator<'_, CHANNEL> {
fn new() -> Self {
Self(PhantomData)
}
}
impl<const CHANNEL: u8> Comparator for SpecificComparator<'_, CHANNEL> {
fn channel(&self) -> u8 {
CHANNEL
}
}
/// Any [Comparator]. Could be either comparator 0, comparator 1, etc.
#[derive(Debug)]
pub struct AnyComparator<'d>(PhantomData<&'d ()>, u8);
impl Comparator for AnyComparator<'_> {
fn channel(&self) -> u8 {
self.1
}
}
impl<'d, const CHANNEL: u8> From<SpecificComparator<'d, CHANNEL>> for AnyComparator<'d> {
fn from(_value: SpecificComparator<'d, CHANNEL>) -> Self {
Self(PhantomData, CHANNEL)
}
}
impl<'d, const CHANNEL: u8> TryFrom<AnyComparator<'d>> for SpecificComparator<'d, CHANNEL> {
type Error = u8;
fn try_from(value: AnyComparator<'d>) -> Result<Self, Self::Error> {
if value.1 == CHANNEL {
Ok(SpecificComparator::new())
} else {
Err(value.1)
}
}
}
/// The configuration of a unit.
#[derive(Copy, Clone)]
pub enum UnitConfig {
/// Unit is not counting.
Disabled,
/// Unit is counting unless the Cpu is stalled.
DisabledIfCpuIsStalled(Cpu),
/// Unit is counting.
Enabled,
}
/// The modes of a comparator.
#[derive(Copy, Clone)]
pub enum ComparatorMode {
/// The comparator will generate interrupts periodically.
Period,
/// The comparator will generate an interrupt when the unit reaches the
/// target.
Target,
}
impl SpecificUnit<'static, 0> {
/// Conjure a system timer unit out of thin air.
///
/// # Safety
///
/// Users must take care to ensure that only one reference to the unit is
/// in scope at any given time.
pub const unsafe fn conjure() -> Self {
Self(PhantomData)
}
}
#[cfg(not(esp32s2))]
impl SpecificUnit<'static, 1> {
/// Conjure a system timer unit out of thin air.
///
/// # Safety
///
/// Users must take care to ensure that only one reference to the unit is
/// in scope at any given time.
pub const unsafe fn conjure() -> Self {
Self(PhantomData)
}
}
/// A unit whose value cannot be updated.
pub struct FrozenUnit<'d, U: Unit>(&'d U);
impl<'d, U: Unit> FrozenUnit<'d, U> {
/// Creates a frozen unit. You will no longer be allowed
/// direct access to this unit until all the alarms created
/// from the unit are dropped.
pub fn new(unit: &'d mut U) -> Self {
Self(unit)
}
fn borrow(&self) -> &'d U {
self.0
}
}
/// Alarms created from the System Timer peripheral.
pub struct SysTimerAlarms<MODE, DM: Mode> {
/// Alarm 0
pub alarm0: Alarm<'static, MODE, DM>,
/// Alarm 1
pub alarm1: Alarm<'static, MODE, DM>,
/// Alarm 2
pub alarm2: Alarm<'static, MODE, DM>,
/// Unit 1
///
/// Leftover unit which wasn't used to create the three alarms.
#[cfg(not(esp32s2))]
pub unit1: SpecificUnit<'static, 1>,
}
/// A marker for a [Alarm] in target mode.
#[derive(Debug)]
pub struct Target;
/// A marker for a [Alarm] in periodic mode.
#[derive(Debug)]
pub struct Periodic;
/// A single alarm.
pub struct Alarm<'d, MODE, DM, COMP = AnyComparator<'d>, UNIT = AnyUnit<'d>>
where
DM: Mode,
{
comparator: COMP,
unit: &'d UNIT,
_pd: PhantomData<(MODE, DM)>,
}
impl<T, DM, COMP: Comparator, UNIT: Unit> Debug for Alarm<'_, T, DM, COMP, UNIT>
where
DM: Mode,
{
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Alarm")
.field("comparator", &self.comparator.channel())
.field("unit", &self.unit.channel())
.finish()
}
}
impl<'d, T, COMP: Comparator, UNIT: Unit> Alarm<'d, T, Blocking, COMP, UNIT> {
/// Creates a new alarm from a comparator and unit, in blocking mode.
pub fn new(comparator: COMP, unit: &FrozenUnit<'d, UNIT>) -> Self {
Self {
comparator,
unit: unit.borrow(),
_pd: PhantomData,
}
}
}
impl<'d, T, COMP: Comparator, UNIT: Unit> Alarm<'d, T, Async, COMP, UNIT> {
/// Creates a new alarm from a comparator and unit, in async mode.
pub fn new_async(comparator: COMP, unit: &FrozenUnit<'d, UNIT>) -> Self {
Self {
comparator,
unit: unit.0,
_pd: PhantomData,
}
}
}
impl<T, COMP: Comparator, UNIT: Unit> InterruptConfigurable for Alarm<'_, T, Blocking, COMP, UNIT> {
fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
self.comparator.set_interrupt_handler(handler)
}
}
impl<'d, DM, COMP: Comparator, UNIT: Unit> Alarm<'d, Target, DM, COMP, UNIT>
where
DM: Mode,
{
/// Set the target value of this [Alarm]
pub fn set_target(&self, timestamp: u64) {
#[cfg(esp32s2)]
unsafe {
let systimer = &*SYSTIMER::ptr();
// run at XTAL freq, not 80 * XTAL freq
systimer.step().write(|w| w.xtal_step().bits(0x1));
}
self.comparator.set_mode(ComparatorMode::Target);
self.comparator.set_target(timestamp);
self.comparator.set_enable(true);
}
/// Block waiting until the timer reaches the `timestamp`
pub fn wait_until(&self, timestamp: u64) {
self.clear_interrupt();
self.set_target(timestamp);
let r = unsafe { &*crate::peripherals::SYSTIMER::PTR }.int_raw();
loop {
if r.read().target(self.comparator.channel()).bit_is_set() {
break;
}
}
}
/// Converts this [Alarm] into [Periodic] mode
pub fn into_periodic(self) -> Alarm<'d, Periodic, DM, COMP, UNIT> {
Alarm {
comparator: self.comparator,
unit: self.unit,
_pd: PhantomData,
}
}
}
impl<'d, DM, COMP: Comparator, UNIT: Unit> Alarm<'d, Periodic, DM, COMP, UNIT>
where
DM: Mode,
{
/// Set the period of this [Alarm]
pub fn set_period(&self, period: MicrosDurationU32) {
#[cfg(esp32s2)]
unsafe {
let systimer = &*SYSTIMER::ptr();
// run at XTAL freq, not 80 * XTAL freq
systimer.step().write(|w| w.xtal_step().bits(0x1));
}
let us = period.ticks();
let ticks = us * (SystemTimer::ticks_per_second() / 1_000_000) as u32;
self.comparator.set_mode(ComparatorMode::Period);
self.comparator.set_period(ticks);
self.comparator.set_enable(true);
}
/// Converts this [Alarm] into [Target] mode
pub fn into_target(self) -> Alarm<'d, Target, DM, COMP, UNIT> {
Alarm {
comparator: self.comparator,
unit: self.unit,
_pd: PhantomData,
}
}
}
impl<T, DM, COMP: Comparator, UNIT: Unit> crate::private::Sealed for Alarm<'_, T, DM, COMP, UNIT> where
DM: Mode
{
}
impl<T, DM, COMP: Comparator, UNIT: Unit> super::Timer for Alarm<'_, T, DM, COMP, UNIT>
where
DM: Mode,
{
fn start(&self) {
self.comparator.set_enable(true);
}
fn stop(&self) {
self.comparator.set_enable(false);
}
fn reset(&self) {
let systimer = unsafe { &*SYSTIMER::PTR };
#[cfg(esp32s2)]
// Run at XTAL freq, not 80 * XTAL freq:
systimer
.step()
.modify(|_, w| unsafe { w.xtal_step().bits(0x1) });
#[cfg(not(esp32s2))]
{
systimer
.conf()
.modify(|_, w| w.timer_unit0_core0_stall_en().clear_bit());
}
}
fn is_running(&self) -> bool {
self.comparator.is_enabled()
}
fn now(&self) -> Instant<u64, 1, 1_000_000> {
// This should be safe to access from multiple contexts; worst case
// scenario the second accessor ends up reading an older time stamp.
let ticks = self.unit.read_count();
let us = ticks / (SystemTimer::ticks_per_second() / 1_000_000);
Instant::<u64, 1, 1_000_000>::from_ticks(us)
}
fn load_value(&self, value: MicrosDurationU64) -> Result<(), Error> {
let mode = self.comparator.mode();
let us = value.ticks();
let ticks = us * (SystemTimer::ticks_per_second() / 1_000_000);
if matches!(mode, ComparatorMode::Period) {
// Period mode
// The `SYSTIMER_TARGETx_PERIOD` field is 26-bits wide (or
// 29-bits on the ESP32-S2), so we must ensure that the provided
// value is not too wide:
if (ticks & !SystemTimer::PERIOD_MASK) != 0 {
return Err(Error::InvalidTimeout);
}
self.comparator.set_period(ticks as u32);
// Clear and then set SYSTIMER_TARGETx_PERIOD_MODE to configure COMPx into
// period mode
self.comparator.set_mode(ComparatorMode::Target);
self.comparator.set_mode(ComparatorMode::Period);
} else {
// Target mode
// The counters/comparators are 52-bits wide (except on ESP32-S2,
// which is 64-bits), so we must ensure that the provided value
// is not too wide:
#[cfg(not(esp32s2))]
if (ticks & !SystemTimer::BIT_MASK) != 0 {
return Err(Error::InvalidTimeout);
}
let v = self.unit.read_count();
let t = v + ticks;
self.comparator.set_target(t);
}
Ok(())
}
fn enable_auto_reload(&self, auto_reload: bool) {
// If `auto_reload` is true use Period Mode, otherwise use Target Mode:
let mode = if auto_reload {
ComparatorMode::Period
} else {
ComparatorMode::Target
};
self.comparator.set_mode(mode)
}
fn enable_interrupt(&self, state: bool) {
lock(&INT_ENA_LOCK, || {
unsafe { &*SYSTIMER::PTR }
.int_ena()
.modify(|_, w| w.target(self.comparator.channel()).bit(state));
});
}
fn clear_interrupt(&self) {
unsafe { &*SYSTIMER::PTR }
.int_clr()
.write(|w| w.target(self.comparator.channel()).clear_bit_by_one());
}
fn is_interrupt_set(&self) -> bool {
unsafe { &*SYSTIMER::PTR }
.int_raw()
.read()
.target(self.comparator.channel())
.bit_is_set()
}
fn set_alarm_active(&self, _active: bool) {
// Nothing to do
}
fn set_interrupt_handler(&self, handler: InterruptHandler) {
self.comparator.set_interrupt_handler(handler);
}
}
impl<T, DM, COMP: Comparator, UNIT: Unit> Peripheral for Alarm<'_, T, DM, COMP, UNIT>
where
DM: Mode,
{
type P = Self;
#[inline]
unsafe fn clone_unchecked(&self) -> Self::P {
core::ptr::read(self as *const _)
}
}
static CONF_LOCK: Lock = Lock::new();
static INT_ENA_LOCK: Lock = Lock::new();
// Async functionality of the system timer.
mod asynch {
use core::{
pin::Pin,
task::{Context, Poll},
};
use embassy_sync::waitqueue::AtomicWaker;
use procmacros::handler;
use super::*;
const NUM_ALARMS: usize = 3;
static WAKERS: [AtomicWaker; NUM_ALARMS] = [const { AtomicWaker::new() }; NUM_ALARMS];
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub(crate) struct AlarmFuture<'a, COMP: Comparator, UNIT: Unit> {
alarm: &'a Alarm<'a, Target, crate::Async, COMP, UNIT>,
}
impl<'a, COMP: Comparator, UNIT: Unit> AlarmFuture<'a, COMP, UNIT> {
pub(crate) fn new(alarm: &'a Alarm<'a, Target, crate::Async, COMP, UNIT>) -> Self {
alarm.clear_interrupt();
let (interrupt, handler) = match alarm.comparator.channel() {
0 => (Interrupt::SYSTIMER_TARGET0, target0_handler),
1 => (Interrupt::SYSTIMER_TARGET1, target1_handler),
_ => (Interrupt::SYSTIMER_TARGET2, target2_handler),
};
unsafe {
interrupt::bind_interrupt(interrupt, handler.handler());
interrupt::enable(interrupt, handler.priority()).unwrap();
}
alarm.set_interrupt_handler(handler);
alarm.enable_interrupt(true);
Self { alarm }
}
fn event_bit_is_clear(&self) -> bool {
unsafe { &*crate::peripherals::SYSTIMER::PTR }
.int_ena()
.read()
.target(self.alarm.comparator.channel())
.bit_is_clear()
}
}
impl<COMP: Comparator, UNIT: Unit> core::future::Future for AlarmFuture<'_, COMP, UNIT> {
type Output = ();
fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
WAKERS[self.alarm.comparator.channel() as usize].register(ctx.waker());
if self.event_bit_is_clear() {
Poll::Ready(())
} else {
Poll::Pending
}
}
}
impl<COMP: Comparator, UNIT: Unit> embedded_hal_async::delay::DelayNs
for Alarm<'_, Target, crate::Async, COMP, UNIT>
{
async fn delay_ns(&mut self, nanos: u32) {
self.set_target(
self.unit.read_count()
+ (nanos as u64 * SystemTimer::ticks_per_second()).div_ceil(1_000_000_000),
);
AlarmFuture::new(self).await;
}
async fn delay_ms(&mut self, ms: u32) {
for _ in 0..ms {
self.delay_us(1000).await;
}
}
}
#[handler]
fn target0_handler() {
lock(&INT_ENA_LOCK, || {
unsafe { &*crate::peripherals::SYSTIMER::PTR }
.int_ena()
.modify(|_, w| w.target0().clear_bit());
});
WAKERS[0].wake();
}
#[handler]
fn target1_handler() {
lock(&INT_ENA_LOCK, || {
unsafe { &*crate::peripherals::SYSTIMER::PTR }
.int_ena()
.modify(|_, w| w.target1().clear_bit());
});
WAKERS[1].wake();
}
#[handler]
fn target2_handler() {
lock(&INT_ENA_LOCK, || {
unsafe { &*crate::peripherals::SYSTIMER::PTR }
.int_ena()
.modify(|_, w| w.target2().clear_bit());
});
WAKERS[2].wake();
}
}
#[cfg(soc_etm)]
pub mod etm {
//! # Event Task Matrix Function
//!
//! ## Overview
//!
//! The system timer supports the Event Task Matrix (ETM) function, which
//! allows the system timer’s ETM events to trigger any peripherals’ ETM
//! tasks.
//!
//! The system timer can generate the following ETM events:
//! - SYSTIMER_EVT_CNT_CMPx: Indicates the alarm pulses generated by
//! COMPx
//!
//! ## Example
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! # use esp_hal::timer::systimer::{etm::Event, SystemTimer};
//! # use fugit::ExtU32;
//! let syst = SystemTimer::new(peripherals.SYSTIMER);
//! let syst_alarms = syst.split();
//! let mut alarm0 = syst_alarms.alarm0.into_periodic();
//! alarm0.set_period(1u32.secs());
//!
//! let timer_event = Event::new(&mut alarm0);
//! # }
//! ```
use super::*;
/// An ETM controlled SYSTIMER event
pub struct Event<'a, 'd, M, DM: crate::Mode, COMP, UNIT> {
alarm: &'a mut Alarm<'d, M, DM, COMP, UNIT>,
}
impl<'a, 'd, M, DM: crate::Mode, COMP: Comparator, UNIT: Unit> Event<'a, 'd, M, DM, COMP, UNIT> {
/// Creates an ETM event from the given [Alarm]
pub fn new(alarm: &'a mut Alarm<'d, M, DM, COMP, UNIT>) -> Self {
Self { alarm }
}
/// Execute closure f with mutable access to the wrapped [Alarm].
pub fn with<R>(&self, f: impl FnOnce(&&'a mut Alarm<'d, M, DM, COMP, UNIT>) -> R) -> R {
let alarm = &self.alarm;
f(alarm)
}
}
impl<M, DM: crate::Mode, COMP: Comparator, UNIT: Unit> crate::private::Sealed
for Event<'_, '_, M, DM, COMP, UNIT>
{
}
impl<M, DM: crate::Mode, COMP: Comparator, UNIT: Unit> crate::etm::EtmEvent
for Event<'_, '_, M, DM, COMP, UNIT>
{
fn id(&self) -> u8 {
50 + self.alarm.comparator.channel()
}
}
pub(super) fn enable_etm() {
let syst = unsafe { crate::peripherals::SYSTIMER::steal() };
syst.conf().modify(|_, w| w.etm_en().set_bit());
}
}