-
Notifications
You must be signed in to change notification settings - Fork 7.6k
Multi threading examples (tasks, queues, semaphores, mutexes) #7660
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
Merged
Merged
Changes from 21 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
335e56f
Moved and renamed example ESP32/FreeRTOS to MultiThreading/BasicMulti…
PilnyTomas dd2e474
Added dummy files
PilnyTomas f189822
Modified original example
PilnyTomas ad2968c
Fixed BasicMultiThreading.ino
PilnyTomas c18d355
Added Example demonstrating use of queues
PilnyTomas 84725b3
Extended info in BasicMultiThreading
PilnyTomas e321229
Renamed Queues to singular Queue
PilnyTomas 3a9fa4e
Added Mutex example
PilnyTomas 1a20317
Added Semaphore example
PilnyTomas 1c6a435
Moved info from example to README
PilnyTomas 87be4ab
Moved doc from Mutex to README
PilnyTomas ae79f67
Added Queue README
PilnyTomas ece1b40
Merge branch 'master' into MultiThreading
PilnyTomas 5af4f89
Removed unecesary text
PilnyTomas f3b840f
Fixed grammar
PilnyTomas a1dcca8
Increased stack size for Sempahore example
PilnyTomas 3f2b231
Added headers into .ino files
PilnyTomas 289452c
Added word Example at the end of title in README
PilnyTomas 81660e6
removed unused line
PilnyTomas f4dbaf2
Added forgotten README
PilnyTomas 0bec759
Modified BasicMultiThreading example
PilnyTomas 7c68f7e
Added missing S3 entry in README
PilnyTomas 7200582
moved location
PilnyTomas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
117 changes: 117 additions & 0 deletions
117
libraries/MultiThreading/examples/BasicMultiThreading/BasicMultiThreading.ino
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
|
||
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
88
libraries/MultiThreading/examples/BasicMultiThreading/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.