ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
hal.cpp
Go to the documentation of this file.
1#ifdef USE_ZEPHYR
2
4#include "esphome/core/hal.h"
5
6#include <zephyr/drivers/watchdog.h>
7#include <zephyr/sys/reboot.h>
8
9#include <nrfx.h>
10
11// Empty zephyr namespace block to satisfy ci-custom's lint_namespace check.
12// HAL functions live in namespace esphome (root) — they are not part of the
13// zephyr component's API.
14namespace esphome::zephyr {} // namespace esphome::zephyr
15
16namespace esphome {
17
18#ifdef CONFIG_WATCHDOG
19static int wdt_channel_id = -1; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
20static const device *const WDT = DEVICE_DT_GET(DT_ALIAS(watchdog0));
21#endif
22
23// yield(), delay(), millis(), millis_64(), delayMicroseconds(), micros() except the cycle-counter one
24// inlined in components/zephyr/hal.h.
25
26#if CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC == 1000000 || defined(USE_ZEPHYR_DWT_MICROS)
28 // Nothing else updates SystemCoreClock, so on nRF54L it would keep its 64 MHz default.
29 SystemCoreClockUpdate();
30 return SystemCoreClock;
31}
32#endif
33
34#if CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC == 1000000
35// The DWT cycle counter stays at 0 on nRF54L, so the 1 MHz system timer is scaled to CPU cycles. It wraps at
36// 2^32 like a real cycle counter, so differences stay correct, but it only steps once per microsecond.
37static uint32_t cpu_cycles_per_us; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
38uint32_t arch_get_cpu_cycle_count() { return k_cycle_get_32() * cpu_cycles_per_us; }
39#elif defined(USE_ZEPHYR_DWT_MICROS)
40uint32_t arch_get_cpu_cycle_count() { return DWT->CYCCNT; }
41#else
42// Cortex-M0 cores (nRF51) have no cycle counter, so both use the kernel clock to stay in the same unit.
43uint32_t arch_get_cpu_cycle_count() { return k_cycle_get_32(); }
44uint32_t arch_get_cpu_freq_hz() { return sys_clock_hw_cycles_per_sec(); }
45#endif
46
47#ifdef USE_ZEPHYR_DWT_MICROS
48// The kernel clock counts in ticks of about 30 us, and the CPU cycle counter stops while the CPU sleeps.
49// micros() adds the cycles counted since the last call. While the CPU stays busy the result and the kernel clock
50// each trail the true time by less than a tick, so they differ by less than a tick either way. A sleep shorter
51// than a tick can go unnoticed, so the result may trail the true time by up to two ticks until the next resync.
52// The CPU cannot sleep while interrupts are locked, so a lag there comes from before the lock. It and any drift
53// are left for the next unlocked call, which keeps differences inside an InterruptLock exact; InterruptLock makes that
54// call just before it locks, so timestamps taken under the lock line up with later unlocked ones. A counter that has
55// not moved since the last call is not running, and then the kernel clock is used even under a lock.
56
57// One struct so the code loads a single base address.
58static struct {
60 uint32_t last_cycles; // Moves on by whole microseconds only, so the remainder carries over.
61} micros_state; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
62
63static constexpr uint32_t CYCLES_PER_US = 64; // nRF52 cores always run at 64 MHz.
64// Drift between unlocked calls stays far below this; a larger lead is a lag of over 2^31 us that wrapped. A lag
65// within this of 2^32 us still looks like a lead and holds micros() for at most a second; that is accepted.
66static constexpr int32_t MAX_LEAD_US = 1000000;
67
69 const unsigned int key = irq_lock();
70 const uint32_t cycles = DWT->CYCCNT;
71 const uint32_t elapsed_us = (cycles - micros_state.last_cycles) / CYCLES_PER_US;
72 micros_state.last_cycles += elapsed_us * CYCLES_PER_US;
73 uint32_t value = micros_state.value + elapsed_us;
74
75 const uint32_t kernel_us = k_ticks_to_us_floor32(k_uptime_ticks());
76 // A tick, plus 1 us because kernel_us is rounded down.
77 const int32_t tick_us = k_ticks_to_us_ceil32(1) + 1;
78 const int32_t ahead = static_cast<int32_t>(value - kernel_us);
79 const bool unlocked = arch_irq_unlocked(key);
80 if ((ahead < -tick_us || ahead > MAX_LEAD_US) && (unlocked || elapsed_us == 0)) {
81 // The CPU slept, so the cycle counter fell behind.
82 value = kernel_us;
83 micros_state.last_cycles = cycles;
84 } else if (ahead >= tick_us && ahead <= MAX_LEAD_US && unlocked) {
85 // The CPU clock can run fast against the RTC; cap the drift at one tick, but never below a result already
86 // returned under a lock.
87 const uint32_t cap = kernel_us + tick_us - 1;
88 value = static_cast<int32_t>(cap - micros_state.value) > 0 ? cap : micros_state.value;
89 }
90 micros_state.value = value;
91 irq_unlock(key);
92 return value;
93}
94#endif
95
96void arch_init() {
97 main_loop_thread() = k_current_get();
98#if CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC == 1000000
99 cpu_cycles_per_us = arch_get_cpu_freq_hz() / 1000000;
100#elif defined(USE_ZEPHYR_DWT_MICROS)
101 CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
102 DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
103#endif
104#ifdef CONFIG_WATCHDOG
105 if (device_is_ready(WDT)) {
106 static wdt_timeout_cfg wdt_config{};
107 wdt_config.flags = WDT_FLAG_RESET_SOC;
108#ifndef USE_BOOTLOADER_MCUBOOT
109 // Adafruit bootloader doesn't feed the WDT while
110 // erasing flash during a firmware update, so a shorter timeout can break the update.
111 wdt_config.window.max = 30000;
112#elif defined(USE_ZIGBEE)
113 // zboss thread uses a lot of CPU cycles during startup
114 wdt_config.window.max = 10000;
115#else
116 wdt_config.window.max = 2000;
117#endif
118 wdt_channel_id = wdt_install_timeout(WDT, &wdt_config);
119 if (wdt_channel_id >= 0) {
120 // Paused while a debugger halts the CPU, so flashing over SWD is not cut off by a reset
121 uint8_t options = WDT_OPT_PAUSE_HALTED_BY_DBG;
122#ifdef USE_DEEP_SLEEP
123 options |= WDT_OPT_PAUSE_IN_SLEEP;
124#endif
125 wdt_setup(WDT, options);
126 }
127 }
128#endif
129 // feed watchdog early. Otherwise OTA may rollback.
131}
132
134#ifdef CONFIG_WATCHDOG
135 if (wdt_channel_id >= 0) {
136 wdt_feed(WDT, wdt_channel_id);
137 }
138#endif
139}
140
141void arch_restart() { sys_reboot(SYS_REBOOT_COLD); }
142
143} // namespace esphome
144
145#endif // USE_ZEPHYR
uint8_t options
const char * key
uint32_t arch_get_cpu_cycle_count()
Definition hal.cpp:71
void arch_init()
Definition hal.cpp:44
uint32_t last_cycles
Definition hal.cpp:60
uint32_t value
Definition hal.cpp:59
pthread_t & main_loop_thread()
Definition hal.h:20
uint32_t arch_get_cpu_freq_hz()
Definition hal.cpp:57
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
void arch_feed_wdt()
Definition hal.cpp:133
void arch_restart()
Definition hal.cpp:36
static void uint32_t
uint32_t SystemCoreClock