0
0
FreeRTOSprogramming~5 mins

xTaskNotify() with value in FreeRTOS

Choose your learning style9 modes available
Introduction

xTaskNotify() lets one task send a simple number or signal to another task. This helps tasks talk to each other without complex tools.

When you want to tell a task to start or stop doing something.
When you want to send a small number or code to another task quickly.
When you want to signal a task that an event happened.
When you want to update a task with a new value without using queues.
When you want simple task-to-task communication with low overhead.
Syntax
FreeRTOS
BaseType_t xTaskNotify(
    TaskHandle_t xTaskToNotify,
    uint32_t ulValue,
    eNotifyAction eAction
);

xTaskToNotify is the task that will receive the notification.

ulValue is the number you want to send.

eAction decides how the value is sent (set, increment, bitwise OR, etc.).

Examples
This sends the value 10 to the task, replacing any old value.
FreeRTOS
xTaskNotify(taskHandle, 10, eSetValueWithOverwrite);
This adds 1 to the current notification value of the task.
FreeRTOS
xTaskNotify(taskHandle, 1, eIncrement);
This sets bit 0 of the task's notification value.
FreeRTOS
xTaskNotify(taskHandle, 0x01, eSetBits);
Sample Program

This program creates two tasks. The SenderTask waits 1 second, then sends the number 42 to ReceiverTask using xTaskNotify(). ReceiverTask waits for the notification and prints the received value.

FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>

TaskHandle_t taskHandle;

void ReceiverTask(void *params) {
    uint32_t notifiedValue = 0;
    while (1) {
        // Wait for notification and get the value
        xTaskNotifyWait(0x00, 0xFFFFFFFF, &notifiedValue, portMAX_DELAY);
        printf("Received notification with value: %lu\n", notifiedValue);
    }
}

void SenderTask(void *params) {
    vTaskDelay(pdMS_TO_TICKS(1000)); // Wait 1 second
    xTaskNotify(taskHandle, 42, eSetValueWithOverwrite);
    vTaskDelete(NULL);
}

int main(void) {
    xTaskCreate(ReceiverTask, "Receiver", 1000, NULL, 1, &taskHandle);
    xTaskCreate(SenderTask, "Sender", 1000, NULL, 1, NULL);
    vTaskStartScheduler();
    return 0;
}
OutputSuccess
Important Notes

Use eSetValueWithOverwrite to replace the old value, or eIncrement to add to it.

Notifications are faster and use less memory than queues for simple signals.

Always check the return value of xTaskNotify() to ensure the notification was sent.

Summary

xTaskNotify() sends a number or signal from one task to another.

You choose how the number is sent using eNotifyAction.

This is a simple and fast way for tasks to communicate small data.