|
| 1 | +/* |
| 2 | + Example of a FreeRTOS mutex |
| 3 | + https://www.freertos.org/Real-time-embedded-RTOS-mutexes.html |
| 4 | +*/ |
| 5 | + |
| 6 | +// Include Arduino FreeRTOS library |
| 7 | +#include <Arduino_FreeRTOS.h> |
| 8 | + |
| 9 | + |
| 10 | +// Include mutex supoport |
| 11 | +#include <semphr.h> |
| 12 | + |
| 13 | +/* |
| 14 | + Declaring a global variable of type SemaphoreHandle_t |
| 15 | +
|
| 16 | +*/ |
| 17 | +SemaphoreHandle_t mutex; |
| 18 | + |
| 19 | +int globalCount = 0; |
| 20 | + |
| 21 | +void setup() { |
| 22 | + |
| 23 | + Serial.begin(9600); |
| 24 | + |
| 25 | + /** |
| 26 | + Create a mutex. |
| 27 | + https://www.freertos.org/CreateMutex.html |
| 28 | + */ |
| 29 | + mutex = xSemaphoreCreateMutex(); |
| 30 | + if (mutex != NULL) { |
| 31 | + Serial.println("Mutex created"); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + Create tasks |
| 36 | + */ |
| 37 | + xTaskCreate(TaskMutex, // Task function |
| 38 | + "Task1", // Task name for humans |
| 39 | + 128, |
| 40 | + 1000, // Task parameter |
| 41 | + 1, // Task priority |
| 42 | + NULL); |
| 43 | + |
| 44 | + xTaskCreate(TaskMutex, "Task2", 128, 1000, 1, NULL); |
| 45 | + |
| 46 | +} |
| 47 | + |
| 48 | +void loop() {} |
| 49 | + |
| 50 | +void TaskMutex(void *pvParameters) |
| 51 | +{ |
| 52 | + int delay = *((int*)pvParameters); // Use task parameters to define delay |
| 53 | + |
| 54 | + for (;;) |
| 55 | + { |
| 56 | + /** |
| 57 | + Take mutex |
| 58 | + https://www.freertos.org/a00122.html |
| 59 | + */ |
| 60 | + if (xSemaphoreTake(mutex, 10) == pdTRUE) |
| 61 | + { |
| 62 | + Serial.print(pcTaskGetName(NULL)); // Get task name |
| 63 | + Serial.print(", Count readed value: "); |
| 64 | + Serial.print(globalCount); |
| 65 | + |
| 66 | + globalCount++; |
| 67 | + |
| 68 | + Serial.print(", Updated value: "); |
| 69 | + Serial.print(globalCount); |
| 70 | + |
| 71 | + Serial.println(); |
| 72 | + /** |
| 73 | + Give mutex |
| 74 | + https://www.freertos.org/a00123.html |
| 75 | + */ |
| 76 | + xSemaphoreGive(mutex); |
| 77 | + } |
| 78 | + |
| 79 | + vTaskDelay(delay / portTICK_PERIOD_MS); |
| 80 | + } |
| 81 | +} |
0 commit comments