diff --git a/libraries/ESP32/examples/FreeRTOS/BasicMultiThreading/BasicMultiThreading.ino b/libraries/ESP32/examples/FreeRTOS/BasicMultiThreading/BasicMultiThreading.ino new file mode 100644 index 00000000000..745d5b6a46c --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/BasicMultiThreading/BasicMultiThreading.ino @@ -0,0 +1,117 @@ +/* Basic Multi Threading Arduino Example + This example code is in the Public Domain (or CC0 licensed, at your option.) + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +// Please read file README.md in the folder containing this example. + +#if CONFIG_FREERTOS_UNICORE +#define ARDUINO_RUNNING_CORE 0 +#else +#define ARDUINO_RUNNING_CORE 1 +#endif + +#define ANALOG_INPUT_PIN A0 + +#ifndef LED_BUILTIN + #define LED_BUILTIN 13 // Specify the on which is your LED +#endif + +// Define two tasks for Blink & AnalogRead. +void TaskBlink( void *pvParameters ); +void TaskAnalogRead( void *pvParameters ); +TaskHandle_t analog_read_task_handle; // You can (don't have to) use this to be able to manipulate a task from somewhere else. + +// The setup function runs once when you press reset or power on the board. +void setup() { + // Initialize serial communication at 115200 bits per second: + Serial.begin(115200); + // Set up two tasks to run independently. + uint32_t blink_delay = 1000; // Delay between changing state on LED pin + xTaskCreate( + TaskBlink + , "Task Blink" // A name just for humans + , 2048 // The stack size can be checked by calling `uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL);` + , (void*) &blink_delay // Task parameter which can modify the task behavior. This must be passed as pointer to void. + , 2 // Priority + , NULL // Task handle is not used here - simply pass NULL + ); + + // This variant of task creation can also specify on which core it will be run (only relevant for multi-core ESPs) + xTaskCreatePinnedToCore( + TaskAnalogRead + , "Analog Read" + , 2048 // Stack size + , NULL // When no parameter is used, simply pass NULL + , 1 // Priority + , &analog_read_task_handle // With task handle we will be able to manipulate with this task. + , ARDUINO_RUNNING_CORE // Core on which the task will run + ); + + Serial.printf("Basic Multi Threading Arduino Example\n"); + // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started. +} + +void loop(){ + if(analog_read_task_handle != NULL){ // Make sure that the task actually exists + delay(10000); + vTaskDelete(analog_read_task_handle); // Delete task + analog_read_task_handle = NULL; // prevent calling vTaskDelete on non-existing task + } +} + +/*--------------------------------------------------*/ +/*---------------------- Tasks ---------------------*/ +/*--------------------------------------------------*/ + +void TaskBlink(void *pvParameters){ // This is a task. + uint32_t blink_delay = *((uint32_t*)pvParameters); + +/* + Blink + Turns on an LED on for one second, then off for one second, repeatedly. + + If you want to know what pin the on-board LED is connected to on your ESP32 model, check + the Technical Specs of your board. +*/ + + // initialize digital LED_BUILTIN on pin 13 as an output. + pinMode(LED_BUILTIN, OUTPUT); + + for (;;){ // A Task shall never return or exit. + digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) + // arduino-esp32 has FreeRTOS configured to have a tick-rate of 1000Hz and portTICK_PERIOD_MS + // refers to how many milliseconds the period between each ticks is, ie. 1ms. + delay(blink_delay); + digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW + delay(blink_delay); + } +} + +void TaskAnalogRead(void *pvParameters){ // This is a task. + (void) pvParameters; + // Check if the given analog pin is usable - if not - delete this task + if(!adcAttachPin(ANALOG_INPUT_PIN)){ + Serial.printf("TaskAnalogRead cannot work because the given pin %d cannot be used for ADC - the task will delete itself.\n", ANALOG_INPUT_PIN); + analog_read_task_handle = NULL; // Prevent calling vTaskDelete on non-existing task + vTaskDelete(NULL); // Delete this task + } + +/* + AnalogReadSerial + Reads an analog input on pin A3, prints the result to the serial monitor. + Graphical representation is available using serial plotter (Tools > Serial Plotter menu) + Attach the center pin of a potentiometer to pin A3, and the outside pins to +5V and ground. + + This example code is in the public domain. +*/ + + for (;;){ + // read the input on analog pin: + int sensorValue = analogRead(ANALOG_INPUT_PIN); + // print out the value you read: + Serial.println(sensorValue); + delay(100); // 100ms delay + } +} diff --git a/libraries/ESP32/examples/FreeRTOS/BasicMultiThreading/README.md b/libraries/ESP32/examples/FreeRTOS/BasicMultiThreading/README.md new file mode 100644 index 00000000000..c7112e8b4f9 --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/BasicMultiThreading/README.md @@ -0,0 +1,89 @@ +# Basic Multi Threading Example + +This example demonstrates the basic usage of FreeRTOS Tasks for multi threading. + +Please refer to other examples in this folder to better utilize their full potential and safeguard potential problems. +It is also advised to read the documentation on FreeRTOS web pages: +[https://www.freertos.org/a00106.html](https://www.freertos.org/a00106.html) + +This example will blink the built-in LED and read analog data. +Additionally, this example demonstrates the usage of the task handle, simply by deleting the analog +read task after 10 seconds from the main loop by calling the function `vTaskDelete`. + +### Theory: +A task is simply a function that runs when the operating system (FreeeRTOS) sees fit. +This task can have an infinite loop inside if you want to do some work periodically for the entirety of the program run. +This, however, can create a problem - no other task will ever run and also the Watch Dog will trigger and your program will restart. +A nice behaving tasks know when it is useless to keep the processor for itself and give it away for other tasks to be used. +This can be achieved in many ways, but the simplest is called `delay(`milliseconds)`. +During that delay, any other task may run and do its job. +When the delay runs out the Operating System gives the processor the task which can continue. +For other ways to yield the CPU in a task please see other examples in this folder. +It is also worth mentioning that two or more tasks running the same function will run them with separate stacks, so if you want to run the same code (which could be differentiated by the argument) there is no need to have multiple copies of the same function. + +**Task creation has a few parameters you should understand:** +``` + xTaskCreate(TaskFunction_t pxTaskCode, + const char * const pcName, + const uint16_t usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) +``` + - **pxTaskCode** is the name of your function which will run as a task + - **pcName** is a string of human-readable descriptions for your task + - **usStackDepth** is the number of words (word = 4B) available to the task. If you see an error similar to this "Debug exception reason: Stack canary watchpoint triggered (Task Blink)" you should increase it + - **pvParameters** is a parameter that will be passed to the task function - it must be explicitly converted to (void*) and in your function explicitly converted back to the intended data type. + - **uxPriority** is a number from 0 to configMAX_PRIORITIES which determines how the FreeRTOS will allow the tasks to run. 0 is the lowest priority. + - **pxCreatedTask** task handle is a pointer to the task which allows you to manipulate the task - delete it, suspend and resume. + If you don't need to do anything special with your task, simply pass NULL for this parameter. + You can read more about task control here: https://www.freertos.org/a00112.html + +# Supported Targets + +This example supports all SoCs. + +### Hardware Connection + +If your board does not have a built-in LED, please connect one to the pin specified by the `LED_BUILTIN` in the code (you can also change the number and connect it to the pin you desire). + +Optionally you can connect the analog element to the pin. such as a variable resistor, analog input such as an audio signal, or any signal generator. However, if the pin is left unconnected it will receive background noise and you will also see a change in the signal when the pin is touched by a finger. +Please refer to the ESP-IDF ADC documentation for specific SoC for info on which pins are available: +[ESP32](https://docs.espressif.com/projects/esp-idf/en/v4.4/esp32/api-reference/peripherals/adc.html), + [ESP32-S2](https://docs.espressif.com/projects/esp-idf/en/v4.4/esp32s2/api-reference/peripherals/adc.html), + [ESP32-S3](https://docs.espressif.com/projects/esp-idf/en/v4.4/esp32s3/api-reference/peripherals/adc.html), + [ESP32-C3](https://docs.espressif.com/projects/esp-idf/en/v4.4/esp32c3/api-reference/peripherals/adc.html) + + +#### Using Arduino IDE + +To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits). + +* Before Compile/Verify, select the correct board: `Tools -> Board`. +* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port. + +#### Using Platform IO + +* Select the COM port: `Devices` or set the `upload_port` option on the `platformio.ini` file. + +## Troubleshooting + +***Important: Make sure you are using a good quality USB cable and that you have a reliable power source*** + +## Contribute + +To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst) + +If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome! + +Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else. + +## Resources + +* Official ESP32 Forum: [Link](https://esp32.com) +* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) +* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf) +* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf) +* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf) +* ESP32-S3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf) +* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com) diff --git a/libraries/ESP32/examples/FreeRTOS/FreeRTOS.ino b/libraries/ESP32/examples/FreeRTOS/FreeRTOS.ino deleted file mode 100644 index c9ba0eca6aa..00000000000 --- a/libraries/ESP32/examples/FreeRTOS/FreeRTOS.ino +++ /dev/null @@ -1,99 +0,0 @@ -#if CONFIG_FREERTOS_UNICORE -#define ARDUINO_RUNNING_CORE 0 -#else -#define ARDUINO_RUNNING_CORE 1 -#endif - -#ifndef LED_BUILTIN -#define LED_BUILTIN 13 -#endif - -// define two tasks for Blink & AnalogRead -void TaskBlink( void *pvParameters ); -void TaskAnalogReadA3( void *pvParameters ); - -// the setup function runs once when you press reset or power the board -void setup() { - - // initialize serial communication at 115200 bits per second: - Serial.begin(115200); - - // Now set up two tasks to run independently. - xTaskCreatePinnedToCore( - TaskBlink - , "TaskBlink" // A name just for humans - , 1024 // This stack size can be checked & adjusted by reading the Stack Highwater - , NULL - , 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest. - , NULL - , ARDUINO_RUNNING_CORE); - - xTaskCreatePinnedToCore( - TaskAnalogReadA3 - , "AnalogReadA3" - , 1024 // Stack size - , NULL - , 1 // Priority - , NULL - , ARDUINO_RUNNING_CORE); - - // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started. -} - -void loop() -{ - // Empty. Things are done in Tasks. -} - -/*--------------------------------------------------*/ -/*---------------------- Tasks ---------------------*/ -/*--------------------------------------------------*/ - -void TaskBlink(void *pvParameters) // This is a task. -{ - (void) pvParameters; - -/* - Blink - Turns on an LED on for one second, then off for one second, repeatedly. - - If you want to know what pin the on-board LED is connected to on your ESP32 model, check - the Technical Specs of your board. -*/ - - // initialize digital LED_BUILTIN on pin 13 as an output. - pinMode(LED_BUILTIN, OUTPUT); - - for (;;) // A Task shall never return or exit. - { - digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) - // arduino-esp32 has FreeRTOS configured to have a tick-rate of 1000Hz and portTICK_PERIOD_MS - // refers to how many milliseconds the period between each ticks is, ie. 1ms. - vTaskDelay(1000 / portTICK_PERIOD_MS ); // vTaskDelay wants ticks, not milliseconds - digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW - vTaskDelay(1000 / portTICK_PERIOD_MS); // 1 second delay - } -} - -void TaskAnalogReadA3(void *pvParameters) // This is a task. -{ - (void) pvParameters; - -/* - AnalogReadSerial - Reads an analog input on pin A3, prints the result to the serial monitor. - Graphical representation is available using serial plotter (Tools > Serial Plotter menu) - Attach the center pin of a potentiometer to pin A3, and the outside pins to +5V and ground. - - This example code is in the public domain. -*/ - - for (;;) - { - // read the input on analog pin A3: - int sensorValueA3 = analogRead(A3); - // print out the value you read: - Serial.println(sensorValueA3); - vTaskDelay(100 / portTICK_PERIOD_MS); // 100ms delay - } -} diff --git a/libraries/ESP32/examples/FreeRTOS/Mutex/Mutex.ino b/libraries/ESP32/examples/FreeRTOS/Mutex/Mutex.ino new file mode 100644 index 00000000000..157c5742e69 --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/Mutex/Mutex.ino @@ -0,0 +1,97 @@ +/* Basic Multi Threading Arduino Example + This example code is in the Public Domain (or CC0 licensed, at your option.) + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +// Please read file README.md in the folder containing this example. + +#define USE_MUTEX +int shared_variable = 0; +SemaphoreHandle_t shared_var_mutex = NULL; + +// Define a task function +void Task( void *pvParameters ); + +// The setup function runs once when you press reset or power on the board. +void setup() { + // Initialize serial communication at 115200 bits per second: + Serial.begin(115200); + while(!Serial) delay(100); + Serial.printf(" Task 0 | Task 1\n"); + +#ifdef USE_MUTEX + shared_var_mutex = xSemaphoreCreateMutex(); // Create the mutex +#endif + + // Set up two tasks to run the same function independently. + static int task_number0 = 0; + xTaskCreate( + Task + , "Task 0" // A name just for humans + , 2048 // The stack size + , (void*)&task_number0 // Pass reference to a variable describing the task number + //, 5 // High priority + , 1 // priority + , NULL // Task handle is not used here - simply pass NULL + ); + + static int task_number1 = 1; + xTaskCreate( + Task + , "Task 1" + , 2048 // Stack size + , (void*)&task_number1 // Pass reference to a variable describing the task number + , 1 // Low priority + , NULL // Task handle is not used here - simply pass NULL + ); + + // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started. +} + +void loop(){ +} + +/*--------------------------------------------------*/ +/*---------------------- Tasks ---------------------*/ +/*--------------------------------------------------*/ + +void Task(void *pvParameters){ // This is a task. + int task_num = *((int*)pvParameters); + Serial.printf("%s\n", task_num ? " Starting |" : " | Starting"); + for (;;){ // A Task shall never return or exit. +#ifdef USE_MUTEX + if(shared_var_mutex != NULL){ // Sanity check if the mutex exists + // Try to take the mutex and wait indefintly if needed + if(xSemaphoreTake(shared_var_mutex, portMAX_DELAY) == pdTRUE){ + // Mutex successfully taken +#endif + int new_value = random(1000); + + char str0[32]; sprintf(str0, " %d <- %d |", shared_variable, new_value); + char str1[32]; sprintf(str1, " | %d <- %d", shared_variable, new_value); + Serial.printf("%s\n", task_num ? str0 : str1); + + shared_variable = new_value; + delay(random(100)); // wait random time of max 100 ms - simulating some computation + + sprintf(str0, " R: %d |", shared_variable); + sprintf(str1, " | R: %d", shared_variable); + Serial.printf("%s\n", task_num ? str0 : str1); + //Serial.printf("Task %d after write: reading %d\n", task_num, shared_variable); + + if(shared_variable != new_value){ + Serial.printf("%s\n", task_num ? " Mismatch! |" : " | Mismatch!"); + //Serial.printf("Task %d: detected race condition - the value changed!\n", task_num); + } + +#ifdef USE_MUTEX + xSemaphoreGive(shared_var_mutex); // After accessing the shared resource give the mutex and allow other processes to access it + }else{ + // We could not obtain the semaphore and can therefore not access the shared resource safely. + } // mutex take + } // sanity check +#endif + delay(10); // Allow other task to be scheduled + } // Infinite loop +} \ No newline at end of file diff --git a/libraries/ESP32/examples/FreeRTOS/Mutex/README.md b/libraries/ESP32/examples/FreeRTOS/Mutex/README.md new file mode 100644 index 00000000000..d1c8c19e3be --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/Mutex/README.md @@ -0,0 +1,121 @@ +# Mutex Example + +This example demonstrates the basic usage of FreeRTOS Mutually Exclusive Locks (Mutex) for securing access to shared resources in multi-threading. +Please refer to other examples in this folder to better understand the usage of tasks. +It is also advised to read the documentation on FreeRTOS web pages: +https://www.freertos.org/a00106.html + +This example creates 2 tasks with the same implementation - they write into a shared variable and then read it and check if it is the same as what they have written. +In single-thread programming like on Arduino this is of no concern and will be always ok, however when multi-threading is used the execution of the task is switched by the FreeRTOS and the value can be rewritten from another task before reading again. +The tasks print write and read operation - each in their column for better reading. Task 0 is on the left and Task 1 is on the right. +Watch the writes and read in secure mode when using the mutex (default) as the results are as you would expect them. +Then try to comment the USE_MUTEX and watch again - there will be a lot of mismatches! + +### Theory: +Mutex is a specialized version of Semaphore (please see the Semaphore example for more info). +In essence, the mutex is a variable whose value determines if the mute is taken (locked) or given (unlocked). +When two or more processes access the same resource (variable, peripheral, etc) it might happen, for example, that when one task starts to read a variable and the operating system (FreeRTOS) will schedule the execution of another task +which will write to this variable and when the previous task runs again it will read something different. + +Mutexes and binary semaphores are very similar but have some subtle differences: +Mutexes include a priority inheritance mechanism, whereas binary semaphores do not. +This makes binary semaphores the better choice for implementing synchronization (between tasks or between tasks and an interrupt), and mutexes the better +choice for implementing simple mutual exclusion. +What is priority inheritance? +If a low-priority task holds the Mutex but gets interrupted by a Higher priority task, which +then tries to take the Mutex, the low-priority task will temporarily ‘inherit’ the high priority so a middle-priority task can't block the low-priority task, and thus also block the high priority task. +Semaphores don't have the logic to handle this, in part because Semaphores aren't 'owned' by the task that takes them. + +A mutex can also be recursive - if a task that holds the mutex takes it again, it will succeed, and the mutex will be released +for other tasks only when it is given the same number of times that it was taken. + +You can check the danger by commenting on the definition of USE_MUTEX which will disable the mutex and present the danger of concurrent access. + + +# Supported Targets + +This example supports all ESP32 SoCs. + +## How to Use Example + +Flash and observe the serial output. + +Comment the `USE_MUTEX` definition, save and flash again and observe the behavior of unprotected access to the shared variable. + +* How to install the Arduino IDE: [Install Arduino IDE](https://github.com/espressif/arduino-esp32/tree/master/docs/arduino-ide). + +#### Using Arduino IDE + +To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits). + +* Before Compile/Verify, select the correct board: `Tools -> Board`. +* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port. + +#### Using Platform IO + +* Select the COM port: `Devices` or set the `upload_port` option on the `platformio.ini` file. + +## Example Log Output + +The expected output of shared variables protected by mutex demonstrates mutually exclusive access from tasks - they do not interrupt each other and do not rewrite the value before the other task has read it back. + +``` + Task 0 | Task 1 + | Starting + | 0 <- 227 + Starting | + | R: 227 + 227 <- 737 | + R: 737 | + | 737 <- 282 + | R: 282 + 282 <- 267 | +``` + +The output of unprotected access to shared variable - it happens often that a task is interrupted after writing and before reading the other task write a different value - a corruption occurred! + +``` + Task 0 | Task 1 + | Starting + | 0 <- 333 + Starting | + 333 <- 620 | + R: 620 | + 620 <- 244 | + | R: 244 + | Mismatch! + | 244 <- 131 + R: 131 | + Mismatch! | + 131 <- 584 | + | R: 584 + | Mismatch! + | 584 <- 134 + | R: 134 + | 134 <- 554 + R: 554 | + Mismatch! | + 554 <- 313 | +``` + +## Troubleshooting + +***Important: Make sure you are using a good quality USB cable and that you have a reliable power source*** + +## Contribute + +To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst) + +If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome! + +Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else. + +## Resources + +* Official ESP32 Forum: [Link](https://esp32.com) +* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) +* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf) +* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf) +* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf) +* ESP32-S3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf) +* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com) diff --git a/libraries/ESP32/examples/FreeRTOS/Queue/Queue.ino b/libraries/ESP32/examples/FreeRTOS/Queue/Queue.ino new file mode 100644 index 00000000000..a26ee3310d6 --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/Queue/Queue.ino @@ -0,0 +1,120 @@ +/* Basic Multi Threading Arduino Example + This example code is in the Public Domain (or CC0 licensed, at your option.) + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +// Please read file README.md in the folder containing this example./* + +#define MAX_LINE_LENGTH (64) + +// Define two tasks for reading and writing from and to the serial port. +void TaskWriteToSerial(void *pvParameters); +void TaskReadFromSerial(void *pvParameters); + +// Define Queue handle +QueueHandle_t QueueHandle; +const int QueueElementSize = 10; +typedef struct{ + char line[MAX_LINE_LENGTH]; + uint8_t line_length; +} message_t; + +// The setup function runs once when you press reset or power on the board. +void setup() { + // Initialize serial communication at 115200 bits per second: + Serial.begin(115200); + while(!Serial){delay(10);} + + // Create the queue which will have number of elements, each of size `message_t` and pass the address to . + QueueHandle = xQueueCreate(QueueElementSize, sizeof(message_t)); + + // Check if the queue was successfully created + if(QueueHandle == NULL){ + Serial.println("Queue could not be created. Halt."); + while(1) delay(1000); // Halt at this point as is not possible to continue + } + + // Set up two tasks to run independently. + xTaskCreate( + TaskWriteToSerial + , "Task Write To Serial" // A name just for humans + , 2048 // The stack size can be checked by calling `uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL);` + , NULL // No parameter is used + , 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest. + , NULL // Task handle is not used here + ); + + xTaskCreate( + TaskReadFromSerial + , "Task Read From Serial" + , 2048 // Stack size + , NULL // No parameter is used + , 1 // Priority + , NULL // Task handle is not used here + ); + + // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started. + Serial.printf("\nAnything you write will return as echo.\nMaximum line length is %d characters (+ terminating '0').\nAnything longer will be sent as a separate line.\n\n", MAX_LINE_LENGTH-1); +} + +void loop(){ + // Loop is free to do any other work + + delay(1000); // While not being used yield the CPU to other tasks +} + +/*--------------------------------------------------*/ +/*---------------------- Tasks ---------------------*/ +/*--------------------------------------------------*/ + +void TaskWriteToSerial(void *pvParameters){ // This is a task. + message_t message; + for (;;){ // A Task shall never return or exit. + // One approach would be to poll the function (uxQueueMessagesWaiting(QueueHandle) and call delay if nothing is waiting. + // The other approach is to use infinite time to wait defined by constant `portMAX_DELAY`: + if(QueueHandle != NULL){ // Sanity check just to make sure the queue actually exists + int ret = xQueueReceive(QueueHandle, &message, portMAX_DELAY); + if(ret == pdPASS){ + // The message was successfully received - send it back to Serial port and "Echo: " + Serial.printf("Echo line of size %d: \"%s\"\n", message.line_length, message.line); + // The item is queued by copy, not by reference, so lets free the buffer after use. + }else if(ret == pdFALSE){ + Serial.println("The `TaskWriteToSerial` was unable to receive data from the Queue"); + } + } // Sanity check + } // Infinite loop +} + +void TaskReadFromSerial(void *pvParameters){ // This is a task. + message_t message; + for (;;){ + // Check if any data are waiting in the Serial buffer + message.line_length = Serial.available(); + if(message.line_length > 0){ + // Check if the queue exists AND if there is any free space in the queue + if(QueueHandle != NULL && uxQueueSpacesAvailable(QueueHandle) > 0){ + int max_length = message.line_length < MAX_LINE_LENGTH ? message.line_length : MAX_LINE_LENGTH-1; + for(int i = 0; i < max_length; ++i){ + message.line[i] = Serial.read(); + } + message.line_length = max_length; + message.line[message.line_length] = 0; // Add the terminating nul char + + // The line needs to be passed as pointer to void. + // The last parameter states how many milliseconds should wait (keep trying to send) if is not possible to send right away. + // When the wait parameter is 0 it will not wait and if the send is not possible the function will return errQUEUE_FULL + int ret = xQueueSend(QueueHandle, (void*) &message, 0); + if(ret == pdTRUE){ + // The message was successfully sent. + }else if(ret == errQUEUE_FULL){ + // Since we are checking uxQueueSpacesAvailable this should not occur, however if more than one task should + // write into the same queue it can fill-up between the test and actual send attempt + Serial.println("The `TaskReadFromSerial` was unable to send data into the Queue"); + } // Queue send check + } // Queue sanity check + }else{ + delay(100); // Allow other tasks to run when there is nothing to read + } // Serial buffer check + } // Infinite loop +} diff --git a/libraries/ESP32/examples/FreeRTOS/Queue/README.md b/libraries/ESP32/examples/FreeRTOS/Queue/README.md new file mode 100644 index 00000000000..745ce9e8db6 --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/Queue/README.md @@ -0,0 +1,75 @@ +# Queue Example + +This example demonstrates the basic usage of FreeRTOS Queues which enables tasks to pass data between each other in a secure asynchronous way. +Please refer to other examples in this folder to better understand the usage of tasks. +It is also advised to read the documentation on FreeRTOS web pages: +[https://www.freertos.org/a00106.html](https://www.freertos.org/a00106.html) + +This example reads data received on the serial port (sent by the user) pass it via queue to another task which will send it back on Serial Output. + +### Theory: +A queue is a simple-to-use data structure (in the most basic way) controlled by `xQueueSend` and `xQueueReceive` functions. +Usually, one task writes into the queue and the other task reads from it. +Usage of queues enables the reading task to yield the CPU until there are data in the queue and therefore not waste precious computation time. + +# Supported Targets + +This example supports all ESP32 SoCs. + +## How to Use Example + +Flash and write anything to serial input. + +* How to install the Arduino IDE: [Install Arduino IDE](https://github.com/espressif/arduino-esp32/tree/master/docs/arduino-ide). + +#### Using Arduino IDE + +To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits). + +* Before Compile/Verify, select the correct board: `Tools -> Board`. +* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port. + +#### Using Platform IO + +* Select the COM port: `Devices` or set the `upload_port` option on the `platformio.ini` file. + +## Example Log Output + +``` +Anything you write will return as echo. +Maximum line length is 63 characters (+ terminating '0'). +Anything longer will be sent as a separate line. + +``` +< Input text "Short input" + +``Echo line of size 11: "Short input"`` + +< Input text "An example of very long input which is longer than default 63 characters will be split." + +``` +Echo line of size 63: "An example of very long input which is longer than default 63 c" +Echo line of size 24: "haracters will be split." +``` + +## Troubleshooting + +***Important: Make sure you are using a good quality USB cable and that you have a reliable power source*** + +## Contribute + +To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst) + +If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome! + +Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else. + +## Resources + +* Official ESP32 Forum: [Link](https://esp32.com) +* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) +* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf) +* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf) +* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf) +* ESP32-S3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf) +* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com) diff --git a/libraries/ESP32/examples/FreeRTOS/Semaphore/README.md b/libraries/ESP32/examples/FreeRTOS/Semaphore/README.md new file mode 100644 index 00000000000..8f860a52db5 --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/Semaphore/README.md @@ -0,0 +1,81 @@ +# Semaphore Example + +This example demonstrates the basic usage of FreeRTOS Semaphores and queue sets for coordination between tasks for multi-threading. +Please refer to other examples in this folder to better understand the usage of tasks. +It is also advised to read the documentation on FreeRTOS web pages: +[https://www.freertos.org/a00106.html](https://www.freertos.org/a00106.html) + +### Theory: +Semaphore is in essence a variable. Tasks can set the value, wait until one or more +semaphores are set and thus communicate between each other their state. +A binary semaphore is a semaphore that has a maximum count of 1, hence the 'binary' name. +A task can only 'take' the semaphore if it is available, and the semaphore is only available if its count is 1. + +Semaphores can be controlled by any number of tasks. If you use semaphore as a one-way +signalization with only one task giving and only one task taking there is a much faster option +called Task Notifications - please see FreeRTOS documentation and read more about them: [https://www.freertos.org/RTOS-task-notifications.html](https://www.freertos.org/RTOS-task-notifications.html) + +This example uses a semaphore to signal when a package is delivered to a warehouse by multiple +delivery trucks, and multiple workers are waiting to receive the package. + +# Supported Targets + +This example supports all ESP32 SoCs. + +## How to Use Example + +Read the code and try to understand it, then flash and observe the Serial output. + +* How to install the Arduino IDE: [Install Arduino IDE](https://github.com/espressif/arduino-esp32/tree/master/docs/arduino-ide). + +#### Using Arduino IDE + +To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits). + +* Before Compile/Verify, select the correct board: `Tools -> Board`. +* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port. + +#### Using Platform IO + +* Select the COM port: `Devices` or set the `upload_port` option on the `platformio.ini` file. + +## Example Log Output + +``` +Anything you write will return as echo. +Maximum line length is 63 characters (+ terminating '0'). +Anything longer will be sent as a separate line. + +``` +< Input text "Short input" + +``Echo line of size 11: "Short input"`` + +< Input text "An example of very long input which is longer than default 63 characters will be split." + +``` +Echo line of size 63: "An example of very long input which is longer than default 63 c" +Echo line of size 24: "haracters will be split." +``` + +## Troubleshooting + +***Important: Make sure you are using a good quality USB cable and that you have a reliable power source*** + +## Contribute + +To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst) + +If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome! + +Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else. + +## Resources + +* Official ESP32 Forum: [Link](https://esp32.com) +* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) +* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf) +* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf) +* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf) +* ESP32-S3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf) +* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com) diff --git a/libraries/ESP32/examples/FreeRTOS/Semaphore/Semaphore.ino b/libraries/ESP32/examples/FreeRTOS/Semaphore/Semaphore.ino new file mode 100644 index 00000000000..ae3b3fd1bf7 --- /dev/null +++ b/libraries/ESP32/examples/FreeRTOS/Semaphore/Semaphore.ino @@ -0,0 +1,56 @@ +/* Basic Multi Threading Arduino Example + This example code is in the Public Domain (or CC0 licensed, at your option.) + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +// Please read file README.md in the folder containing this example. + +#include + +SemaphoreHandle_t package_delivered_semaphore; + +void delivery_truck_task(void *pvParameters) { + int truck_number = (int) pvParameters; + while(1) { + // Wait for a package to be delivered + // ... + // Notify the warehouse that a package has been delivered + xSemaphoreGive(package_delivered_semaphore); + Serial.printf("Package delivered by truck: %d\n", truck_number); + //wait for some time + vTaskDelay(1000 / portTICK_PERIOD_MS); + } +} + +void warehouse_worker_task(void *pvParameters) { + int worker_number = (int) pvParameters; + while(1) { + // Wait for a package to be delivered + xSemaphoreTake(package_delivered_semaphore, portMAX_DELAY); + Serial.printf("Package received by worker: %d\n", worker_number); + // Receive the package + // ... + } +} + +void setup() { + Serial.begin(115200); + while(!Serial){ delay(100); } + // Create the semaphore + package_delivered_semaphore = xSemaphoreCreateCounting(10, 0); + + // Create multiple delivery truck tasks + for (int i = 0; i < 5; i++) { + xTaskCreate(delivery_truck_task, "Delivery Truck", 2048, (void *)i, tskIDLE_PRIORITY, NULL); + } + + // Create multiple warehouse worker tasks + for (int i = 0; i < 3; i++) { + xTaskCreate(warehouse_worker_task, "Warehouse Worker", 2048, (void *)i, tskIDLE_PRIORITY, NULL); + } +} + +void loop() { + // Empty loop +} \ No newline at end of file