Skip to content

Commit 7864255

Browse files
committed
Track microseconds overflow
Closes: #267
1 parent e81d4d3 commit 7864255

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

Diff for: cores/esp32/esp32-hal-misc.c

+17-4
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,28 @@
1818
#include "freertos/task.h"
1919
#include "esp_attr.h"
2020
#include "nvs_flash.h"
21+
#include <sys/time.h>
2122

2223
void yield()
2324
{
2425
vPortYield();
2526
}
2627

28+
portMUX_TYPE microsMux = portMUX_INITIALIZER_UNLOCKED;
29+
2730
uint32_t IRAM_ATTR micros()
2831
{
32+
static uint32_t lccount = 0;
33+
static uint32_t overflow = 0;
2934
uint32_t ccount;
35+
portENTER_CRITICAL_ISR(&microsMux);
3036
__asm__ __volatile__ ( "rsr %0, ccount" : "=a" (ccount) );
31-
return ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ;
37+
if(ccount < lccount){
38+
overflow += UINT32_MAX / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ;
39+
}
40+
lccount = ccount;
41+
portEXIT_CRITICAL_ISR(&microsMux);
42+
return overflow + (ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ);
3243
}
3344

3445
uint32_t IRAM_ATTR millis()
@@ -45,7 +56,7 @@ void IRAM_ATTR delayMicroseconds(uint32_t us)
4556
{
4657
uint32_t m = micros();
4758
if(us){
48-
uint32_t e = (m + us) % ((0xFFFFFFFF / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ) + 1);
59+
uint32_t e = (m + us);
4960
if(m > e){ //overflow
5061
while(micros() > e){
5162
NOP();
@@ -63,14 +74,16 @@ void initVariant() {}
6374
void init() __attribute__((weak));
6475
void init() {}
6576

66-
void initArduino(){
77+
void initArduino()
78+
{
6779
nvs_flash_init();
6880
init();
6981
initVariant();
7082
}
7183

7284
//used by hal log
73-
const char * IRAM_ATTR pathToFileName(const char * path){
85+
const char * IRAM_ATTR pathToFileName(const char * path)
86+
{
7487
size_t i = 0;
7588
size_t pos = 0;
7689
char * p = (char *)path;

Diff for: cores/esp32/main.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ void loopTask(void *pvParameters)
1414
{
1515
setup();
1616
for(;;) {
17+
micros(); //update overflow
1718
loop();
1819
}
1920
}

0 commit comments

Comments
 (0)