ShawnHymel / introduction-to-rtos

513 stars 124 forks source link

Question: How code is working without the use of vTaskDelay() in tasks? #7

Closed ramitdour closed 1 year ago

ramitdour commented 1 year ago

In "esp32-freertos-04-solution-heap.ino"

The code is working fine without the use of vTaskDelay() in readSerial or printMessage task.

As both tasks are of the same priority and both have infinite while loop while(1){...} part in the function, how and when does FreeRTOS's scheduler know when to switch between tasks?

mrengineer7777 commented 1 year ago

Both tasks run with priority 1. The FreeRTOS task scheduler likely takes care of time slicing between them. That said, there are several things that would make this code more efficient. At the very least, add delay(1) in the loop, which would put the task to sleep for ~1ms and guarantee other tasks will run. A better approach would be to use a message que, which would allow the receiver to be idle most of the time.

https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/FreeRTOS/Queue/Queue.ino

Also note that on Espressif's version of FreeRTOS in IDF pvPortMalloc maps to malloc.

ShawnHymel commented 1 year ago

Thank you for the insights, @mrengineer7777! That is correct, the scheduler will perform round-robin slicing of equal priority tasks. Using delays or queues is a good way to ensure that the receiver remains idle most of the time. I didn't use queues in this example, as we don't get to them until the next lesson.