Skip to content

Commit 4e80157

Browse files
authored
Merge pull request #71 from hectorespert/mutex
Add Mutex example
2 parents 6e4d50b + ab0466f commit 4e80157

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Ignore .development file, https://arduino.github.io/arduino-cli/library-specification/#development-flag-file
2+
.development

examples/Mutex/Mutex.ino

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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 support
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

Comments
 (0)