|
| 1 | +/* |
| 2 | + * Example to demonstrate thread definition, semaphores, and thread sleep. |
| 3 | + */ |
| 4 | +#include <STM32FreeRTOS.h> |
| 5 | + |
| 6 | +// Define the LED pin is attached |
| 7 | +const uint8_t LED_PIN = LED_BUILTIN; |
| 8 | + |
| 9 | +// Declare a semaphore handle. |
| 10 | +SemaphoreHandle_t sem; |
| 11 | +//------------------------------------------------------------------------------ |
| 12 | +/* |
| 13 | + * Thread 1, turn the LED off when signalled by thread 2. |
| 14 | + */ |
| 15 | +// Declare the thread function for thread 1. |
| 16 | +static void Thread1(void* arg) { |
| 17 | + UNUSED(arg); |
| 18 | + while (1) { |
| 19 | + |
| 20 | + // Wait for signal from thread 2. |
| 21 | + xSemaphoreTake(sem, portMAX_DELAY); |
| 22 | + |
| 23 | + // Turn LED off. |
| 24 | + digitalWrite(LED_PIN, LOW); |
| 25 | + } |
| 26 | +} |
| 27 | +//------------------------------------------------------------------------------ |
| 28 | +/* |
| 29 | + * Thread 2, turn the LED on and signal thread 1 to turn the LED off. |
| 30 | + */ |
| 31 | +// Declare the thread function for thread 2. |
| 32 | +static void Thread2(void* arg) { |
| 33 | + UNUSED(arg); |
| 34 | + pinMode(LED_PIN, OUTPUT); |
| 35 | + |
| 36 | + while (1) { |
| 37 | + // Turn LED on. |
| 38 | + digitalWrite(LED_PIN, HIGH); |
| 39 | + |
| 40 | + // Sleep for 200 milliseconds. |
| 41 | + vTaskDelay((200L * configTICK_RATE_HZ) / 1000L); |
| 42 | + |
| 43 | + // Signal thread 1 to turn LED off. |
| 44 | + xSemaphoreGive(sem); |
| 45 | + |
| 46 | + // Sleep for 200 milliseconds. |
| 47 | + vTaskDelay((200L * configTICK_RATE_HZ) / 1000L); |
| 48 | + } |
| 49 | +} |
| 50 | +//------------------------------------------------------------------------------ |
| 51 | +void setup() { |
| 52 | + portBASE_TYPE s1, s2; |
| 53 | + |
| 54 | + Serial.begin(9600); |
| 55 | + |
| 56 | + // initialize semaphore |
| 57 | + sem = xSemaphoreCreateCounting(1, 0); |
| 58 | + |
| 59 | + // create task at priority two |
| 60 | + s1 = xTaskCreate(Thread1, NULL, configMINIMAL_STACK_SIZE, NULL, 2, NULL); |
| 61 | + |
| 62 | + // create task at priority one |
| 63 | + s2 = xTaskCreate(Thread2, NULL, configMINIMAL_STACK_SIZE, NULL, 1, NULL); |
| 64 | + |
| 65 | + // check for creation errors |
| 66 | + if (sem== NULL || s1 != pdPASS || s2 != pdPASS ) { |
| 67 | + Serial.println(F("Creation problem")); |
| 68 | + while(1); |
| 69 | + } |
| 70 | + |
| 71 | + // start scheduler |
| 72 | + vTaskStartScheduler(); |
| 73 | + Serial.println("Insufficient RAM"); |
| 74 | + while(1); |
| 75 | +} |
| 76 | + |
| 77 | +//------------------------------------------------------------------------------ |
| 78 | +// WARNING idle loop has a very small stack (configMINIMAL_STACK_SIZE) |
| 79 | +// loop must never block |
| 80 | +void loop() { |
| 81 | + // Not used. |
| 82 | +} |
0 commit comments