Skip to content

Commit e1fe3ab

Browse files
committed
esp32/mphalport: Use esp_timer_get_time instead of gettimeofday.
It's more efficient and improves accuracy.
1 parent c781803 commit e1fe3ab

1 file changed

Lines changed: 10 additions & 16 deletions

File tree

ports/esp32/mphalport.c

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
*/
2828

2929
#include <stdio.h>
30-
#include <sys/time.h>
3130

3231
#include "freertos/FreeRTOS.h"
3332
#include "freertos/task.h"
@@ -86,35 +85,30 @@ void mp_hal_stdout_tx_strn_cooked(const char *str, uint32_t len) {
8685
}
8786

8887
uint32_t mp_hal_ticks_ms(void) {
89-
struct timeval tv;
90-
gettimeofday(&tv, NULL);
91-
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
88+
return esp_timer_get_time() / 1000;
9289
}
9390

9491
uint32_t mp_hal_ticks_us(void) {
95-
struct timeval tv;
96-
gettimeofday(&tv, NULL);
97-
return tv.tv_sec * 1000000 + tv.tv_usec;
92+
return esp_timer_get_time();
9893
}
9994

10095
void mp_hal_delay_ms(uint32_t ms) {
101-
struct timeval tv_start;
102-
struct timeval tv_end;
96+
uint64_t us = ms * 1000;
10397
uint64_t dt;
104-
gettimeofday(&tv_start, NULL);
98+
uint64_t t0 = esp_timer_get_time();
10599
for (;;) {
106-
gettimeofday(&tv_end, NULL);
107-
dt = (tv_end.tv_sec - tv_start.tv_sec) * 1000 + (tv_end.tv_usec - tv_start.tv_usec) / 1000;
108-
if (dt + portTICK_PERIOD_MS >= ms) {
109-
// doing a vTaskDelay would take us beyound requested delay time
100+
uint64_t t1 = esp_timer_get_time();
101+
dt = t1 - t0;
102+
if (dt + portTICK_PERIOD_MS * 1000 >= us) {
103+
// doing a vTaskDelay would take us beyond requested delay time
110104
break;
111105
}
112106
MICROPY_EVENT_POLL_HOOK
113107
vTaskDelay(1);
114108
}
115-
if (dt < ms) {
109+
if (dt < us) {
116110
// do the remaining delay accurately
117-
ets_delay_us((ms - dt) * 1000);
111+
mp_hal_delay_us(us - dt);
118112
}
119113
}
120114

0 commit comments

Comments
 (0)