Skip to content

micros() returning inconsistent values when call from different tasks #1165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 32 additions & 7 deletions cores/esp32/esp32-hal-misc.c
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,45 @@ void yield()
}

portMUX_TYPE microsMux = portMUX_INITIALIZER_UNLOCKED;
static pthread_key_t microsStore=NULL; // Thread Local Storage Handle

void* microsStoreDelete(void * storage) { // release thread local data when task is delete.
if(storage) free(storage);
}

unsigned long IRAM_ATTR micros()
{
static unsigned long lccount = 0;
static unsigned long overflow = 0;
if (!microsStore) { // first Time Ever thread local not init'd
portENTER_CRITICAL_ISR(&microsMux);
pthread_key_create(&microsStore,microsStoreDelete); // create initial holder
portEXIT_CRITICAL_ISR(&microsMux);
}

uint32_t *ptr;// [0] is lastCount, [1] is overFlow

ptr = pthread_getspecific(microsStore); // get address of storage

if(ptr == NULL) { // first time in this thread, allocate mem, init it.
portENTER_CRITICAL_ISR(&microsMux);
ptr = (uint32_t*)malloc(sizeof(uint32_t)*2);
pthread_setspecific(microsStore,ptr); // store the pointer to this thread's values
ptr[0] = 0; // lastCount value
ptr[1] = 0; // overFlow
portEXIT_CRITICAL_ISR(&microsMux);
}

unsigned long ccount;

portENTER_CRITICAL_ISR(&microsMux);
__asm__ __volatile__ ( "rsr %0, ccount" : "=a" (ccount) );
if(ccount < lccount){
overflow += UINT32_MAX / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ;
__asm__ __volatile__ ( "rsr %0, ccount" : "=a" (ccount) ); //get cycle count
if(ccount < ptr[0]) { // overflow occurred
ptr[1] += UINT32_MAX / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ;
}
lccount = ccount;

ptr[0] = ccount;
portEXIT_CRITICAL_ISR(&microsMux);
return overflow + (ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ);

return ptr[1] + (ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ);
}

unsigned long IRAM_ATTR millis()
Expand Down