Skip to content

Commit 4ed5865

Browse files
committed
esp32/mphalport: Improve mp_hal_delay_us so it handles pending events.
Thanks to @BBoSer for the initial idea and implementation.
1 parent e1fe3ab commit 4ed5865

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

ports/esp32/mphalport.c

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,28 @@ void mp_hal_delay_ms(uint32_t ms) {
113113
}
114114

115115
void mp_hal_delay_us(uint32_t us) {
116-
ets_delay_us(us);
116+
// these constants are tested for a 240MHz clock
117+
const uint32_t this_overhead = 5;
118+
const uint32_t pend_overhead = 150;
119+
120+
// return if requested delay is less than calling overhead
121+
if (us < this_overhead) {
122+
return;
123+
}
124+
us -= this_overhead;
125+
126+
uint64_t t0 = esp_timer_get_time();
127+
for (;;) {
128+
uint64_t dt = esp_timer_get_time() - t0;
129+
if (dt >= us) {
130+
return;
131+
}
132+
if (dt + pend_overhead < us) {
133+
// we have enough time to service pending events
134+
// (don't use MICROPY_EVENT_POLL_HOOK because it also yields)
135+
mp_handle_pending();
136+
}
137+
}
117138
}
118139

119140
// this function could do with improvements (eg use ets_delay_us)

0 commit comments

Comments
 (0)