Skip to content
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

Multi threading examples (tasks, queues, semaphores, mutexes) #7660

Merged
merged 23 commits into from
Feb 8, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
99 changes: 0 additions & 99 deletions libraries/ESP32/examples/FreeRTOS/FreeRTOS.ino

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Please read file README.md in the folder containing this example.
pedrominatel marked this conversation as resolved.
Show resolved Hide resolved

P-R-O-C-H-Y marked this conversation as resolved.
Show resolved Hide resolved
#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE 0
#else
#define ARDUINO_RUNNING_CORE 1
#endif

#define ANALOG_INPUT_PIN 27

#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 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
, 1024 // 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"
, 1024 // Stack size
, NULL // When no parameter is used, simply pass NULL
, 1 // Priority
, &task_handle // With task handle we will be able to manipulate with this task.
, ARDUINO_RUNNING_CORE // Core on which the task will run
);

// Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop(){
if(task_handle != NULL){ // Make sure that the task actually exists
delay(10000);
vTaskDelete(task_handle); // Delete task
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;

/*
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
}
}
88 changes: 88 additions & 0 deletions libraries/MultiThreading/examples/BasicMultiThreading/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Basic Multi Threading
pedrominatel marked this conversation as resolved.
Show resolved Hide resolved

This example demonstrates basic usage of FreeRTOS Tasks for multi threading.

Please refer to other examples in this folder to better utilize their the full potential and safe-guard potential problems.
It is also advised to read documentation on FreeRTOS web pages:
[https://www.freertos.org/a00106.html](https://www.freertos.org/a00106.html)

This example will blink builtin LED and read analog data.
Additionally this example demonstrates usage of task handle, simply by deleting the analog
read task after 10 seconds from main loop by calling the function `vTaskDelete`.

### Theory:
A task is simply a function which 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 knows when it is useless to keep the processor for itself and gives it away for other tasks to be used.
This can be achieved by many ways, but the simplest is calling `delay(milliseconds)`.
During that delay any other task may run and do it's job.
When the delay runs out the Operating System gives the processor to the task which can continue.
For other ways to yield the CPU in task please see other examples in this folder.
It is also worth mentioning that two or more tasks running the exact same function will run them with separated stack, so if you want to run the same code (could be differentiated by the argument) there is no need to have multiple copies of the same function.

**Task creation has 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 description for your task
- **usStackDepth** is number of words (word = 4B) available to the task. If you see error similar to this "Debug exception reason: Stack canary watchpoint triggered (Task Blink)" you should increase it
- **pvParameters** is a parameter which 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 number from 0 to configMAX_PRIORITIES which determines how the FreeRTOS will allow the tasks to run. 0 is lowest priority.
- **pxCreatedTask** task handle is basically a pointer to the task which allows you to manipulate with the task - delete it, suspend and resume.
If you don't need to do anything special with you 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 built in LED, please connect one to the pin specified by the `LED_BUILTIN` in code (you can also change the number and connect it on pin you desire).

Optionally you can connect analog element to pin ? such as variable resistor, or analog input such as audio signal, or any signal generator. However if the pin is left unconnected it will receive background noise and you will also see change in the signal when the pin is touched by finger.
Please refer to the ESP-IDF ADC documentation for specific SoC for info 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)
P-R-O-C-H-Y marked this conversation as resolved.
Show resolved Hide resolved
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)
91 changes: 91 additions & 0 deletions libraries/MultiThreading/examples/Mutex/Mutex.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// 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
}
Loading