Best approach to execute tasks every 100 ms (or multiples of it) #9287
-
I have an ESP32 running the 2.0.14 arduino-esp32 framework. I want to be able to execute tasks every 100 ms (or multiples of it). Currently, I have tasks that must execute at 100 ms, 2 seconds, 30 seconds and 60 seconds. I am looking for someone to help me understand which is better: to use a timer alarm that runs every 100 ms, and execute all other tasks based on this alarm, or to use the standard Arduino blink without delay example and just check the ellapsed time every loop using My current implementation (which works for my purposes) essentially uses the approach shown in the RepeatTimer example. The configuration in timerSemaphore = xSemaphoreCreateBinary();
timer = timerBegin(0, 80, true);
timerAttachInterrupt(timer, &onTimer, true);
timerAlarmWrite(timer, BASE_TIME * 1000, true);
timerAlarmEnable(timer); My void ARDUINO_ISR_ATTR onTimer(){
portENTER_CRITICAL_ISR(&timerMux);
lastIsrAt = millis(); // this is global
portEXIT_CRITICAL_ISR(&timerMux);
xSemaphoreGiveFromISR(timerSemaphore, NULL);
} Then, I check for this interruption in the main // executes every time the base timer fires
if(xSemaphoreTake(timerSemaphore, 0) == pdTRUE) {
// Read the interrupt time
portENTER_CRITICAL(&timerMux);
isrTime = lastIsrAt;
portEXIT_CRITICAL(&timerMux);
// do something every 100 ms
// check other tasks
// every 2 seconds
if(timer2 == FINISHED && (isrTime - isrTime2) >= TWO_SEC) {
timer2 = START;
isrTime2 = isrTime;
}
// every 30 seconds
if(timer30 == FINISHED && (isrTime - isrTime30) >= THIRTY_SEC) {
timer30 = START;
isrTime30 = isrTime;
}
// every 60 seconds
if(timer60 == FINISHED && (isrTime - isrTime60) >= ONE_MIN) {
timer60 = START;
isrTime60 = isrTime;
}
} Note that For example the task @ 60 s looks like this: if(timer60 == START) {
// do something
// disable timer flag
timer600 = FINISHED;
} Anybody got any ideas whether this is a good approach or just using the BlinkWithoutDelay approach is better??? Or something else? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
it's best to use a FreeRTOS task and delay inside. You can have a few to do the different delays, or do it inside with counting the multiples of 100ms. void myCoolTask(void * arg){
while(1){
// do your thing
delay(100);
}
}
void setup(){
xTaskCreate(myCoolTask, "myCoolTask", 4096, NULL, 2, NULL);
} |
Beta Was this translation helpful? Give feedback.
it's best to use a FreeRTOS task and delay inside. You can have a few to do the different delays, or do it inside with counting the multiples of 100ms.