Event-driven architecture helps your program react to things when they happen, like a button press or a sensor alert. It makes your program efficient and easy to manage.
0
0
Event-driven architecture in FreeRTOS
Introduction
When you want your program to respond immediately to user actions like button presses.
When sensors send data at unpredictable times and you need to handle it quickly.
When you want to avoid wasting CPU time by waiting and instead react only when needed.
When managing multiple tasks that depend on different events happening.
When building embedded systems that must be responsive and efficient.
Syntax
FreeRTOS
void vTaskFunction(void *pvParameters) {
for(;;) {
if(xEventGroupWaitBits(xEventGroup, EVENT_BIT, pdTRUE, pdFALSE, portMAX_DELAY) != 0) {
// Handle event here
}
}
}xEventGroupWaitBits waits for specific event bits to be set.
Use pdTRUE to clear bits after handling the event.
Examples
This waits forever until BIT_0 event happens, then clears it.
FreeRTOS
EventGroupHandle_t xEventGroup = xEventGroupCreate(); // In task: if((xEventGroupWaitBits(xEventGroup, BIT_0, pdTRUE, pdFALSE, portMAX_DELAY) & BIT_0) != 0) { // Event BIT_0 occurred }
This sets BIT_0 event from an interrupt safely.
FreeRTOS
// Setting an event bit from an ISR
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xEventGroupSetBitsFromISR(xEventGroup, BIT_0, &xHigherPriorityTaskWoken);Sample Program
This program creates two tasks. One simulates a button press by setting an event bit after 1 second. The other waits for that event and then prints a message when it happens.
FreeRTOS
#include "FreeRTOS.h" #include "task.h" #include "event_groups.h" #include <stdio.h> #define BUTTON_PRESS_BIT (1 << 0) EventGroupHandle_t xEventGroup; void ButtonTask(void *pvParameters) { // Simulate button press after delay vTaskDelay(pdMS_TO_TICKS(1000)); printf("Button pressed! Setting event bit.\n"); xEventGroupSetBits(xEventGroup, BUTTON_PRESS_BIT); vTaskDelete(NULL); } void EventHandlerTask(void *pvParameters) { printf("Waiting for button press event...\n"); xEventGroupWaitBits(xEventGroup, BUTTON_PRESS_BIT, pdTRUE, pdFALSE, portMAX_DELAY); printf("Button event received! Handling event.\n"); vTaskDelete(NULL); } int main(void) { xEventGroup = xEventGroupCreate(); xTaskCreate(ButtonTask, "ButtonTask", 1000, NULL, 1, NULL); xTaskCreate(EventHandlerTask, "EventHandlerTask", 1000, NULL, 1, NULL); vTaskStartScheduler(); for(;;); return 0; }
OutputSuccess
Important Notes
Event bits let tasks communicate without busy waiting.
Always clear event bits after handling to avoid repeated triggers.
Use event groups carefully to avoid race conditions.
Summary
Event-driven architecture lets your program react only when something happens.
FreeRTOS event groups help tasks wait for and signal events efficiently.
This approach saves CPU time and makes your program responsive.