Skip to content

Commit e881d11

Browse files
authored
Multi threading examples (tasks, queues, semaphores, mutexes) (espressif#7660)
* Moved and renamed example ESP32/FreeRTOS to MultiThreading/BasicMultiThreading * Added dummy files * Modified original example * Fixed BasicMultiThreading.ino * Added Example demonstrating use of queues * Extended info in BasicMultiThreading * Renamed Queues to singular Queue * Added Mutex example * Added Semaphore example * Moved info from example to README * Moved doc from Mutex to README * Added Queue README * Removed unecesary text * Fixed grammar * Increased stack size for Sempahore example * Added headers into .ino files * Added word Example at the end of title in README * removed unused line * Added forgotten README * Modified BasicMultiThreading example * Added missing S3 entry in README * moved location
1 parent 5b0a7d0 commit e881d11

File tree

9 files changed

+756
-99
lines changed

9 files changed

+756
-99
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
/* Basic Multi Threading Arduino Example
2+
This example code is in the Public Domain (or CC0 licensed, at your option.)
3+
Unless required by applicable law or agreed to in writing, this
4+
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
5+
CONDITIONS OF ANY KIND, either express or implied.
6+
*/
7+
// Please read file README.md in the folder containing this example.
8+
9+
#if CONFIG_FREERTOS_UNICORE
10+
#define ARDUINO_RUNNING_CORE 0
11+
#else
12+
#define ARDUINO_RUNNING_CORE 1
13+
#endif
14+
15+
#define ANALOG_INPUT_PIN A0
16+
17+
#ifndef LED_BUILTIN
18+
#define LED_BUILTIN 13 // Specify the on which is your LED
19+
#endif
20+
21+
// Define two tasks for Blink & AnalogRead.
22+
void TaskBlink( void *pvParameters );
23+
void TaskAnalogRead( void *pvParameters );
24+
TaskHandle_t analog_read_task_handle; // You can (don't have to) use this to be able to manipulate a task from somewhere else.
25+
26+
// The setup function runs once when you press reset or power on the board.
27+
void setup() {
28+
// Initialize serial communication at 115200 bits per second:
29+
Serial.begin(115200);
30+
// Set up two tasks to run independently.
31+
uint32_t blink_delay = 1000; // Delay between changing state on LED pin
32+
xTaskCreate(
33+
TaskBlink
34+
, "Task Blink" // A name just for humans
35+
, 2048 // The stack size can be checked by calling `uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL);`
36+
, (void*) &blink_delay // Task parameter which can modify the task behavior. This must be passed as pointer to void.
37+
, 2 // Priority
38+
, NULL // Task handle is not used here - simply pass NULL
39+
);
40+
41+
// This variant of task creation can also specify on which core it will be run (only relevant for multi-core ESPs)
42+
xTaskCreatePinnedToCore(
43+
TaskAnalogRead
44+
, "Analog Read"
45+
, 2048 // Stack size
46+
, NULL // When no parameter is used, simply pass NULL
47+
, 1 // Priority
48+
, &analog_read_task_handle // With task handle we will be able to manipulate with this task.
49+
, ARDUINO_RUNNING_CORE // Core on which the task will run
50+
);
51+
52+
Serial.printf("Basic Multi Threading Arduino Example\n");
53+
// Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
54+
}
55+
56+
void loop(){
57+
if(analog_read_task_handle != NULL){ // Make sure that the task actually exists
58+
delay(10000);
59+
vTaskDelete(analog_read_task_handle); // Delete task
60+
analog_read_task_handle = NULL; // prevent calling vTaskDelete on non-existing task
61+
}
62+
}
63+
64+
/*--------------------------------------------------*/
65+
/*---------------------- Tasks ---------------------*/
66+
/*--------------------------------------------------*/
67+
68+
void TaskBlink(void *pvParameters){ // This is a task.
69+
uint32_t blink_delay = *((uint32_t*)pvParameters);
70+
71+
/*
72+
Blink
73+
Turns on an LED on for one second, then off for one second, repeatedly.
74+
75+
If you want to know what pin the on-board LED is connected to on your ESP32 model, check
76+
the Technical Specs of your board.
77+
*/
78+
79+
// initialize digital LED_BUILTIN on pin 13 as an output.
80+
pinMode(LED_BUILTIN, OUTPUT);
81+
82+
for (;;){ // A Task shall never return or exit.
83+
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
84+
// arduino-esp32 has FreeRTOS configured to have a tick-rate of 1000Hz and portTICK_PERIOD_MS
85+
// refers to how many milliseconds the period between each ticks is, ie. 1ms.
86+
delay(blink_delay);
87+
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
88+
delay(blink_delay);
89+
}
90+
}
91+
92+
void TaskAnalogRead(void *pvParameters){ // This is a task.
93+
(void) pvParameters;
94+
// Check if the given analog pin is usable - if not - delete this task
95+
if(!adcAttachPin(ANALOG_INPUT_PIN)){
96+
Serial.printf("TaskAnalogRead cannot work because the given pin %d cannot be used for ADC - the task will delete itself.\n", ANALOG_INPUT_PIN);
97+
analog_read_task_handle = NULL; // Prevent calling vTaskDelete on non-existing task
98+
vTaskDelete(NULL); // Delete this task
99+
}
100+
101+
/*
102+
AnalogReadSerial
103+
Reads an analog input on pin A3, prints the result to the serial monitor.
104+
Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
105+
Attach the center pin of a potentiometer to pin A3, and the outside pins to +5V and ground.
106+
107+
This example code is in the public domain.
108+
*/
109+
110+
for (;;){
111+
// read the input on analog pin:
112+
int sensorValue = analogRead(ANALOG_INPUT_PIN);
113+
// print out the value you read:
114+
Serial.println(sensorValue);
115+
delay(100); // 100ms delay
116+
}
117+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# Basic Multi Threading Example
2+
3+
This example demonstrates the basic usage of FreeRTOS Tasks for multi threading.
4+
5+
Please refer to other examples in this folder to better utilize their full potential and safeguard potential problems.
6+
It is also advised to read the documentation on FreeRTOS web pages:
7+
[https://www.freertos.org/a00106.html](https://www.freertos.org/a00106.html)
8+
9+
This example will blink the built-in LED and read analog data.
10+
Additionally, this example demonstrates the usage of the task handle, simply by deleting the analog
11+
read task after 10 seconds from the main loop by calling the function `vTaskDelete`.
12+
13+
### Theory:
14+
A task is simply a function that runs when the operating system (FreeeRTOS) sees fit.
15+
This task can have an infinite loop inside if you want to do some work periodically for the entirety of the program run.
16+
This, however, can create a problem - no other task will ever run and also the Watch Dog will trigger and your program will restart.
17+
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.
18+
This can be achieved in many ways, but the simplest is called `delay(`milliseconds)`.
19+
During that delay, any other task may run and do its job.
20+
When the delay runs out the Operating System gives the processor the task which can continue.
21+
For other ways to yield the CPU in a task please see other examples in this folder.
22+
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.
23+
24+
**Task creation has a few parameters you should understand:**
25+
```
26+
xTaskCreate(TaskFunction_t pxTaskCode,
27+
const char * const pcName,
28+
const uint16_t usStackDepth,
29+
void * const pvParameters,
30+
UBaseType_t uxPriority,
31+
TaskHandle_t * const pxCreatedTask )
32+
```
33+
- **pxTaskCode** is the name of your function which will run as a task
34+
- **pcName** is a string of human-readable descriptions for your task
35+
- **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
36+
- **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.
37+
- **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.
38+
- **pxCreatedTask** task handle is a pointer to the task which allows you to manipulate the task - delete it, suspend and resume.
39+
If you don't need to do anything special with your task, simply pass NULL for this parameter.
40+
You can read more about task control here: https://www.freertos.org/a00112.html
41+
42+
# Supported Targets
43+
44+
This example supports all SoCs.
45+
46+
### Hardware Connection
47+
48+
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).
49+
50+
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.
51+
Please refer to the ESP-IDF ADC documentation for specific SoC for info on which pins are available:
52+
[ESP32](https://docs.espressif.com/projects/esp-idf/en/v4.4/esp32/api-reference/peripherals/adc.html),
53+
[ESP32-S2](https://docs.espressif.com/projects/esp-idf/en/v4.4/esp32s2/api-reference/peripherals/adc.html),
54+
[ESP32-S3](https://docs.espressif.com/projects/esp-idf/en/v4.4/esp32s3/api-reference/peripherals/adc.html),
55+
[ESP32-C3](https://docs.espressif.com/projects/esp-idf/en/v4.4/esp32c3/api-reference/peripherals/adc.html)
56+
57+
58+
#### Using Arduino IDE
59+
60+
To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).
61+
62+
* Before Compile/Verify, select the correct board: `Tools -> Board`.
63+
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
64+
65+
#### Using Platform IO
66+
67+
* Select the COM port: `Devices` or set the `upload_port` option on the `platformio.ini` file.
68+
69+
## Troubleshooting
70+
71+
***Important: Make sure you are using a good quality USB cable and that you have a reliable power source***
72+
73+
## Contribute
74+
75+
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
76+
77+
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!
78+
79+
Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else.
80+
81+
## Resources
82+
83+
* Official ESP32 Forum: [Link](https://esp32.com)
84+
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
85+
* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf)
86+
* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf)
87+
* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf)
88+
* ESP32-S3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf)
89+
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)

Diff for: libraries/ESP32/examples/FreeRTOS/FreeRTOS.ino

-99
This file was deleted.

0 commit comments

Comments
 (0)