feilipu / Arduino_FreeRTOS_Library

A FreeRTOS Library for all Arduino ATmega Devices (Uno R3, Leonardo, Mega, etc).
MIT License
852 stars 204 forks source link

vTaskDelay not functioning as expected in setup #107

Closed s1913388 closed 3 years ago

s1913388 commented 3 years ago

Code:

#include <Arduino.h>
#include <Arduino_FreeRTOS.h>

void setup()
{
    Serial.begin(9600);
    while (!Serial)
    {
        ;
    }
    Serial.print("Setup and loop task running with priority ");
    Serial.println(uxTaskPriorityGet(NULL));
    vTaskDelay(1000 / portTICK_PERIOD_MS);
    Serial.println("OK");
}

void loop() {}

Expected (if comment out the vTaskDelay line):

Setup and loop task running with priority 32
OK

Actual output: Weird output.

Using Arduino Mega 2560

feilipu commented 3 years ago

The scheduler is not running until after the end of the setup() function. Therefore calling for a task delay via vTaskDelay is meaningless.

Also no tasks have been created, so except for the idle task running the contents of loop() function, your code has no tasks running with any priority.

Suggestion, read the documentation. Follow the examples provided, and you will find it will be easier.

s1913388 commented 3 years ago

However it runs perfectly with ESP32 in Arduino IDE,

#include <Arduino.h>

void setup()
{
    Serial.begin(9600);
    while (!Serial)
    {
        ;
    }
    Serial.print("Setup and loop task running with priority ");
    Serial.println(uxTaskPriorityGet(NULL));
    vTaskDelay(1000 / portTICK_PERIOD_MS);
    Serial.println("OK");
}

void loop() {}

It gives expected output (with delay of 1000ms):

Setup and loop task running with priority 1
OK

Actually the code is shamelessly copied from the guide Digi-Key

@feilipu I am wondering why "OK" is not printed for the Arduino Mega 2560?

feilipu commented 3 years ago

The ESP32 is a totally different 240MHz / dual core 32-bit thing. Their IDF uses FreeRTOS to schedule WiFI / Bluetooth activities under the cover.

The "OK" is not printed because the vTaskDelay() function is waiting for an increment that never happens (because the scheduler is not running). Your results will be completely random at that point.

Actually the code is shamelessly copied from the guide Digi-Key.

I suggest to use the examples installed with this library, and available here.