Implementing FreeRTOS sensor tasks with task notifications and I2C gatekeeper
Here's a concise C example showing multiple sensor tasks using direct-to-task notifications to trigger measurements and wait for I2C completion, while a high-priority I2C gatekeeper task processes requests from a queue and notifies sensor tasks when done. Tasks run at different priorities; the gatekeeper handles exclusive I2C access, enabling efficient synchronization without binary semaphores.
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include <stdint.h>
#include <stdio.h>
/* Define the I2C request structure */
typedef struct {
uint8_t sensorAddress;
uint8_t registerAddress;
uint8_t *pData;
uint8_t dataLength;
TaskHandle_t requestingTask; // Used for notification
} I2C_Request_t;
/* Queue handle for I2C requests */
static QueueHandle_t xI2CQueue;
/* Stub I2C transfer function; replace with actual hardware code */
static BaseType_t I2C_Transfer(uint8_t addr, uint8_t reg, uint8_t *data, uint8_t len) {
// Simulate hardware access delay
vTaskDelay(pdMS_TO_TICKS(10));
// For demonstration, just print
printf("I2C Transfer Addr:0x%02X Reg:0x%02X Len:%u\n", addr, reg, len);
return pdPASS;
}
/* High-priority gatekeeper task: processes I2C requests */
static void I2CGatekeeperTask(void *pvParameters) {
I2C_Request_t request;
for (;;) {
if (xQueueReceive(xI2CQueue, &request, portMAX_DELAY) == pdPASS) {
// Exclusive I2C access here
BaseType_t res = I2C_Transfer(
request.sensorAddress,
request.registerAddress,
request.pData,
request.dataLength
);
// Notify the requesting task that I2C transaction is done
if (res == pdPASS) {
xTaskNotifyGive(request.requestingTask);
} else {
// Optionally notify on error differently or handle error
xTaskNotifyGive(request.requestingTask);
}
}
}
}
/* Sensor task example */
static void SensorTask(void *pvParameters) {
/* Cast parameter as sensor ID for demonstration */
uint8_t sensorId = (uint8_t)(uintptr_t)pvParameters;
uint8_t dataBuffer[10] = {0};
for (;;) {
// Wait for notification to start measurement
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
// Prepare I2C request
I2C_Request_t request = {
.sensorAddress = 0x50 + sensorId, // example address
.registerAddress = 0x01,
.pData = dataBuffer,
.dataLength = sizeof(dataBuffer),
.requestingTask = xTaskGetCurrentTaskHandle()
};
// Send request to I2C gatekeeper
xQueueSend(xI2CQueue, &request, portMAX_DELAY);
// Wait for I2C transaction completion notification
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
// Process data (dummy)
printf("Sensor %u processed data\n", sensorId);
}
}
/* Timer or interrupt could call this to trigger sensor tasks */
static void TriggerSensorTask(TaskHandle_t sensorTaskHandle) {
xTaskNotifyGive(sensorTaskHandle);
}
int main(void) {
xI2CQueue = xQueueCreate(5, sizeof(I2C_Request_t));
// Create high priority gatekeeper task
xTaskCreate(
I2CGatekeeperTask,
"I2CGatekeeper",
configMINIMAL_STACK_SIZE,
NULL,
tskIDLE_PRIORITY + 3,
NULL
);
// Create sensor tasks with lower priority
for (uint8_t i = 1; i <= 2; i++) {
char name[12];
snprintf(name, sizeof(name), "SensorTask%u", i);
xTaskCreate(
SensorTask,
name,
configMINIMAL_STACK_SIZE,
(void *)(uintptr_t)i,
tskIDLE_PRIORITY + 1,
NULL
);
}
vTaskStartScheduler();
// Scheduler should never return
for (;;) {}
}
This pattern uses direct-to-task notifications (ulTaskNotifyTake / xTaskNotifyGive) for low-overhead blocking and signaling between the high-priority gatekeeper and sensor tasks, plus a queue to serialize access to the shared I2C bus. The code is minimal yet demonstrates the recommended synchronization for better performance than binary semaphores.
Below is an example showing how to manage multiple sensors with FreeRTOS using task notifications instead of binary semaphores, and a high-priority I2C gatekeeper task that processes requests from lower-priority sensor tasks via a queue. The gatekeeper performs the bus transactions and notifies the requesting task when the operation completes.
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
// Example: an I2C request structure
typedef enum {
I2C_READ,
I2C_WRITE
} I2C_Operation;
typedef struct {
I2C_Operation op;
uint8_t deviceAddr;
uint8_t regAddr;
uint8_t *pData; // pointer to data buffer
size_t length; // data length for read/write
TaskHandle_t requesterTask; // task to notify when done
} I2C_Request;
// Queue for I2C requests
static QueueHandle_t xI2CQueue;
// Handles for tasks (optional; you can also get them dynamically)
static TaskHandle_t xI2CGatekeeperHandle = NULL;
static TaskHandle_t xSensorTask1Handle = NULL;
static TaskHandle_t xSensorTask2Handle = NULL;
// Stub functions for I2C operations (replace with real driver code)
static BaseType_t I2C_Write(uint8_t devAddr, uint8_t regAddr, uint8_t *data, size_t len) {
// Perform actual I2C write
return pdPASS;
}
static BaseType_t I2C_Read(uint8_t devAddr, uint8_t regAddr, uint8_t *data, size_t len) {
// Perform actual I2C read
return pdPASS;
}
// High-priority gatekeeper task: owns the I2C bus
static void vI2CGatekeeperTask(void *pvParameters) {
I2C_Request req;
for (;;) {
// Block until a request arrives
if (xQueueReceive(xI2CQueue, &req, portMAX_DELAY) == pdTRUE) {
BaseType_t status = pdFAIL;
// Perform the requested I2C operation
if (req.op == I2C_WRITE) {
status = I2C_Write(req.deviceAddr, req.regAddr, req.pData, req.length);
} else {
status = I2C_Read(req.deviceAddr, req.regAddr, req.pData, req.length);
}
// Notify the requesting task that the operation is done
// Use a direct-to-task notification
if (req.requesterTask != NULL) {
// Optionally pass status as notification value
xTaskNotify(req.requesterTask, (status == pdPASS), eSetValueWithOverwrite);
}
}
}
}
// Sensor task example: requests periodic I2C reads
static void vSensorTask1(void *pvParameters) {
// Buffer for the sensor data
static uint8_t sensorData[4];
for (;;) {
// Wait for an external event (timer, interrupt, or simply delay)
vTaskDelay(pdMS_TO_TICKS(100));
// Prepare an I2C read request
I2C_Request req = {
.op = I2C_READ,
.deviceAddr = 0x40, // example device address
.regAddr = 0x10, // example register
.pData = sensorData,
.length = sizeof(sensorData),
.requesterTask = xSensorTask1Handle
};
// Send request to the gatekeeper
xQueueSend(xI2CQueue, &req, portMAX_DELAY);
// Wait for notification that the transaction is complete
uint32_t notifyValue = 0;
xTaskNotifyWait(0, 0, ¬ifyValue, portMAX_DELAY);
// notifyValue could carry success/failure info
if (notifyValue == 1) {
// Data in sensorData is now valid
// Process it...
}
}
}
// Another sensor task example: might write configuration or read a different register
static void vSensorTask2(void *pvParameters) {
static uint8_t cfgData[2] = {0xAA, 0x55};
for (;;) {
vTaskDelay(pdMS_TO_TICKS(200));
I2C_Request req = {
.op = I2C_WRITE,
.deviceAddr = 0x42, // example device address
.regAddr = 0x20, // example register
.pData = cfgData,
.length = sizeof(cfgData),
.requesterTask = xSensorTask2Handle
};
xQueueSend(xI2CQueue, &req, portMAX_DELAY);
// Wait for completion notification
uint32_t notifyValue = 0;
xTaskNotifyWait(0, 0, ¬ifyValue, portMAX_DELAY);
// notifyValue==1 if write succeeded
if (notifyValue == 1) {
// Config write successful
}
}
}
int main(void) {
// Create the queue for I2C requests
xI2CQueue = xQueueCreate(5, sizeof(I2C_Request));
// Create the gatekeeper task at high priority
xTaskCreate(vI2CGatekeeperTask, "I2C_Gatekeeper", configMINIMAL_STACK_SIZE + 200,
NULL, configMAX_PRIORITIES - 1, &xI2CGatekeeperHandle);
// Create sensor tasks at lower priority
xTaskCreate(vSensorTask1, "Sensor1", configMINIMAL_STACK_SIZE + 200,
NULL, tskIDLE_PRIORITY + 1, &xSensorTask1Handle);
xTaskCreate(vSensorTask2, "Sensor2", configMINIMAL_STACK_SIZE + 200,
NULL, tskIDLE_PRIORITY + 1, &xSensorTask2Handle);
// Start the scheduler
vTaskStartScheduler();
// Should never reach here
for (;;);
return 0;
}
Key points:
- Each sensor task sends an
I2C_Request to the gatekeeper via xQueueSend().
- The gatekeeper exclusively owns and accesses the I2C bus, ensuring no contention.
- Once the gatekeeper finishes the I2C transaction, it uses
xTaskNotify() to signal completion to the requesting task.
- This approach replaces binary semaphores with direct-to-task notifications, reducing overhead and improving performance.