1 | #include<Arduino.h> |
---|
2 | |
---|
3 | SemaphoreHandle_t sem_printer; |
---|
4 | |
---|
5 | void Printer(String value){ |
---|
6 | Serial.println(value); |
---|
7 | } |
---|
8 | |
---|
9 | void print1Task(void *pvParameters){ |
---|
10 | int i; |
---|
11 | while(true){ |
---|
12 | // critical LOCK resource |
---|
13 | if ( xSemaphoreTake(sem_printer, 2000) == pdTRUE ){ |
---|
14 | Printer("Print form print1Task..."); |
---|
15 | xSemaphoreGive(sem_printer); |
---|
16 | // UNLOCK resource |
---|
17 | }else{ |
---|
18 | Serial.println("print1Task failed to get access Printer"); |
---|
19 | } |
---|
20 | vTaskDelay(2000); |
---|
21 | } |
---|
22 | } |
---|
23 | |
---|
24 | void print2Task(void *pvParameters){ |
---|
25 | while(true){ |
---|
26 | // critical LOCK resource |
---|
27 | if ( xSemaphoreTake(sem_printer, 5000) == pdTRUE ){ |
---|
28 | Printer("Print form print2Task..."); |
---|
29 | // 1 experiment to lock mutex and not give will cause print1Task cannot access printer |
---|
30 | //vTaskDelay(5000); |
---|
31 | xSemaphoreGive(sem_printer); |
---|
32 | // UNLOCK resource |
---|
33 | }else{ |
---|
34 | Serial.println("print2Task failed to get access Printer"); |
---|
35 | } |
---|
36 | vTaskDelay(2000); |
---|
37 | |
---|
38 | } |
---|
39 | } |
---|
40 | |
---|
41 | void setup() { |
---|
42 | Serial.begin(115200); |
---|
43 | sem_printer = xSemaphoreCreateMutex(); |
---|
44 | xTaskCreate(print1Task, "print1Task", 1024, NULL, 1, NULL); |
---|
45 | xTaskCreate(print2Task, "print2Task", 1024, NULL, 0, NULL); |
---|
46 | } |
---|
47 | |
---|
48 | void loop() { |
---|
49 | // put your main code here, to run repeatedly: |
---|
50 | } |
---|