From 059d747820ddf0b4c689051fc81d30b7ae9c245a Mon Sep 17 00:00:00 2001 From: JP Meijers Date: Thu, 16 Mar 2017 18:03:50 +0100 Subject: [PATCH 1/2] micros() overflow fix The micros() function uses the cycle count register of the CPU. This function divides the cycle count by the number of cycles in a microsecond and returns that value. The problem is when the cycle count overflows at the 32bit maximum value, the microsecond value will also overflow. Many applications expect the microsecond value not to overflow before it reaches 2^32. This function now keeps track of cycle count overflows, and take them into account when calculating the microseconds. --- cores/esp32/esp32-hal-misc.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/cores/esp32/esp32-hal-misc.c b/cores/esp32/esp32-hal-misc.c index bf2ff9b5980..a8f512731bc 100644 --- a/cores/esp32/esp32-hal-misc.c +++ b/cores/esp32/esp32-hal-misc.c @@ -26,9 +26,20 @@ void yield() uint32_t IRAM_ATTR micros() { + static uint32_t ccount_overflows = 0; + static uint32_t previous_ccount = 0; uint32_t ccount; - __asm__ __volatile__ ( "rsr %0, ccount" : "=a" (ccount) ); - return ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ; + ccount = xthal_get_ccount(); + + if(previous_ccount>ccount) + { + previous_ccount = ccount; + ccount_overflows++; + } + + previous_ccount = ccount; + return (4294967296 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)*ccount_overflows + +(ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ); } uint32_t IRAM_ATTR millis() From 9dfd1fc571f0cd25ffa561b815903dd9af3c0595 Mon Sep 17 00:00:00 2001 From: JP Meijers Date: Thu, 16 Mar 2017 18:05:59 +0100 Subject: [PATCH 2/2] Update esp32-hal-misc.c Added a comment to describe the function. --- cores/esp32/esp32-hal-misc.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cores/esp32/esp32-hal-misc.c b/cores/esp32/esp32-hal-misc.c index a8f512731bc..29918e90765 100644 --- a/cores/esp32/esp32-hal-misc.c +++ b/cores/esp32/esp32-hal-misc.c @@ -26,6 +26,8 @@ void yield() uint32_t IRAM_ATTR micros() { + //The ESP32's micro's function overflows too quickly becuase the 32bit + //cycle counter is used. static uint32_t ccount_overflows = 0; static uint32_t previous_ccount = 0; uint32_t ccount;