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 21 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,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.
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 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
}
}
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 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)
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)
Loading