This is a comprehensive request to implement FreeRTOS tasks for managing multiple sensors using advanced features like task notifications and a queue-based I2C bus gatekeeper pattern. Let me create a complete, production-ready implementation.
Key requirements:
- Multiple sensor management tasks
- Use task notifications instead of binary semaphores
- High-priority gatekeeper task for I2C bus
- Request queue for coordination
- Better performance through notifications
I'll create:
- Sensor structure definitions
- I2C gatekeeper task
- Multiple sensor reader tasks
- A simple I2C driver abstraction
- Task notification handling
- Queue message structures
- Example usage and configuration
Let me structure this properly with good practices:
- Error handling
- Proper task priorities
- Queue management
- Notification patterns
- Resource sharing patterns
FreeRTOS Multi-Sensor Management with Task Notifications and I2C Gatekeeper
Here's a comprehensive implementation with multiple sensors managed through task notifications:
1. Header Files and Structures
// sensor_manager.h
#ifndef SENSOR_MANAGER_H
#define SENSOR_MANAGER_H
#include <stdint.h>
#include <stdbool.h>
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
/* ============== Sensor Configuration ============== */
#define NUM_SENSORS 4
#define I2C_REQUEST_QUEUE_SIZE 16
#define SENSOR_STACK_SIZE 512
#define GATEKEEPER_STACK_SIZE 1024
#define MAX_I2C_RETRIES 3
#define I2C_TIMEOUT_MS 100
/* Task Priorities */
#define GATEKEEPER_PRIORITY (configMAX_PRIORITIES - 1) // Highest
#define SENSOR_TASK_PRIORITY (configMAX_PRIORITIES - 2)
/* I2C Bus Arbitration Timeout */
#define I2C_BUS_TIMEOUT pdMS_TO_TICKS(50)
/* ============== Data Structures ============== */
typedef enum {
SENSOR_TYPE_TEMPERATURE,
SENSOR_TYPE_HUMIDITY,
SENSOR_TYPE_PRESSURE,
SENSOR_TYPE_MOTION
} sensor_type_t;
typedef struct {
uint8_t i2c_address;
sensor_type_t type;
uint16_t polling_period_ms;
uint8_t sensor_id;
TaskHandle_t task_handle;
TaskHandle_t requesting_task;
} sensor_config_t;
/* I2C Request Structure */
typedef enum {
I2C_OP_READ,
I2C_OP_WRITE,
I2C_OP_READ_WRITE
} i2c_operation_t;
typedef struct {
i2c_operation_t operation;
uint8_t i2c_address;
uint8_t *tx_buffer;
uint8_t tx_length;
uint8_t *rx_buffer;
uint8_t rx_length;
TaskHandle_t requester_task;
BaseType_t notification_value;
TickType_t timeout;
} i2c_request_t;
/* Sensor Reading Structure */
typedef struct {
uint8_t sensor_id;
sensor_type_t type;
uint32_t timestamp;
int32_t raw_value;
float processed_value;
BaseType_t status;
} sensor_reading_t;
/* ============== Function Declarations ============== */
// Initialization
BaseType_t sensor_manager_init(void);
// Sensor management
BaseType_t sensor_create_task(uint8_t sensor_id, const sensor_config_t *config);
BaseType_t sensor_read_async(uint8_t sensor_id);
// I2C bus operations
BaseType_t i2c_request(i2c_request_t *request);
// Callback for results
typedef void (*sensor_callback_t)(const sensor_reading_t *reading);
void sensor_set_callback(uint8_t sensor_id, sensor_callback_t callback);
// Utility
void sensor_manager_print_stats(void);
#endif // SENSOR_MANAGER_H
2. I2C Gatekeeper Task
// i2c_gatekeeper.c
#include "sensor_manager.h"
#include "i2c_driver.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include <string.h>
/* ============== Static Variables ============== */
static QueueHandle_t i2c_request_queue = NULL;
static TaskHandle_t gatekeeper_task_handle = NULL;
typedef struct {
uint32_t total_requests;
uint32_t successful_ops;
uint32_t failed_ops;
uint32_t queue_overflow;
uint32_t max_queue_depth;
} gatekeeper_stats_t;
static gatekeeper_stats_t gatekeeper_stats = {0};
/* ============== I2C Bus Driver Abstraction ============== */
typedef struct {
bool is_initialized;
uint32_t error_count;
uint32_t last_error;
} i2c_bus_state_t;
static i2c_bus_state_t i2c_state = {false, 0, 0};
// Mock I2C driver - replace with actual hardware driver
static BaseType_t i2c_master_transmit(uint8_t addr, uint8_t *data, uint16_t len,
TickType_t timeout) {
if (!i2c_state.is_initialized) {
return pdFALSE;
}
// Actual implementation would use hardware I2C
vTaskDelay(pdMS_TO_TICKS(1)); // Simulate I2C operation
return pdTRUE;
}
static BaseType_t i2c_master_receive(uint8_t addr, uint8_t *data, uint16_t len,
TickType_t timeout) {
if (!i2c_state.is_initialized) {
return pdFALSE;
}
vTaskDelay(pdMS_TO_TICKS(1));
return pdTRUE;
}
static BaseType_t i2c_master_transmit_receive(uint8_t addr,
uint8_t *tx_data, uint16_t tx_len,
uint8_t *rx_data, uint16_t rx_len,
TickType_t timeout) {
if (!i2c_state.is_initialized) {
return pdFALSE;
}
vTaskDelay(pdMS_TO_TICKS(1));
return pdTRUE;
}
/* ============== I2C Request Processing ============== */
static BaseType_t process_i2c_request(i2c_request_t *request) {
BaseType_t result = pdFALSE;
uint32_t retries = 0;
if (request == NULL || request->requester_task == NULL) {
return pdFALSE;
}
do {
switch (request->operation) {
case I2C_OP_WRITE:
result = i2c_master_transmit(
request->i2c_address,
request->tx_buffer,
request->tx_length,
request->timeout
);
break;
case I2C_OP_READ:
result = i2c_master_receive(
request->i2c_address,
request->rx_buffer,
request->rx_length,
request->timeout
);
break;
case I2C_OP_READ_WRITE:
result = i2c_master_transmit_receive(
request->i2c_address,
request->tx_buffer,
request->tx_length,
request->rx_buffer,
request->rx_length,
request->timeout
);
break;
default:
result = pdFALSE;
break;
}
if (result != pdTRUE && retries < MAX_I2C_RETRIES) {
retries++;
vTaskDelay(pdMS_TO_TICKS(2)); // Brief delay before retry
} else {
break;
}
} while (retries < MAX_I2C_RETRIES);
if (!result) {
i2c_state.error_count++;
i2c_state.last_error = xTaskGetTickCount();
gatekeeper_stats.failed_ops++;
} else {
gatekeeper_stats.successful_ops++;
}
return result;
}
/* ============== Gatekeeper Task ============== */
static void vGatekeeperTask(void *pvParameters) {
i2c_request_t request;
UBaseType_t queue_depth;
BaseType_t i2c_result;
configASSERT(i2c_request_queue != NULL);
// Initialize I2C bus
i2c_state.is_initialized = true;
while (1) {
// Wait for I2C requests (indefinite wait)
if (xQueueReceive(i2c_request_queue, &request, portMAX_DELAY) == pdTRUE) {
gatekeeper_stats.total_requests++;
// Check queue depth
queue_depth = uxQueueMessagesWaiting(i2c_request_queue);
if (queue_depth > gatekeeper_stats.max_queue_depth) {
gatekeeper_stats.max_queue_depth = queue_depth;
}
// Process I2C operation
i2c_result = process_i2c_request(&request);
// Notify the requesting task using task notification
// Notification value indicates success/failure
xTaskNotify(request.requester_task,
(i2c_result << request.notification_value),
eSetBits);
}
}
}
/* ============== Public API ============== */
QueueHandle_t i2c_gatekeeper_init(void) {
// Create I2C request queue
i2c_request_queue = xQueueCreate(I2C_REQUEST_QUEUE_SIZE, sizeof(i2c_request_t));
if (i2c_request_queue == NULL) {
return NULL;
}
// Create gatekeeper task
BaseType_t task_created = xTaskCreate(
vGatekeeperTask,
"GateKeeper",
GATEKEEPER_STACK_SIZE,
NULL,
GATEKEEPER_PRIORITY,
&gatekeeper_task_handle
);
if (task_created != pdPASS) {
vQueueDelete(i2c_request_queue);
return NULL;
}
return i2c_request_queue;
}
BaseType_t i2c_gatekeeper_request(i2c_request_t *request) {
if (i2c_request_queue == NULL) {
return pdFALSE;
}
// Set requester task if not set
if (request->requester_task == NULL) {
request->requester_task = xTaskGetCurrentTaskHandle();
}
// Send request to gatekeeper
BaseType_t result = xQueueSend(i2c_request_queue, request, pdMS_TO_TICKS(10));
if (result != pdTRUE) {
gatekeeper_stats.queue_overflow++;
}
return result;
}
gatekeeper_stats_t i2c_gatekeeper_get_stats(void) {
return gatekeeper_stats;
}
3. Sensor Reader Tasks
// sensor_tasks.c
#include "sensor_manager.h"
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>
#include <string.h>
/* ============== Sensor Callbacks ============== */
typedef struct {
uint8_t sensor_id;
sensor_callback_t callback;
sensor_reading_t last_reading;
uint32_t read_count;
uint32_t error_count;
} sensor_context_t;
static sensor_context_t sensor_contexts[NUM_SENSORS];
/* ============== Temperature Sensor Task (BME280) ============== */
// Temperature sensor register definitions
#define BME280_ADDR 0x77
#define BME280_CTRL_MEAS 0xF4
#define BME280_DATA_START 0xF7
static BaseType_t read_bme280_temperature(sensor_context_t *ctx,
sensor_reading_t *reading) {
uint8_t tx_buffer[1] = {BME280_DATA_START};
uint8_t rx_buffer[3] = {0};
i2c_request_t request = {
.operation = I2C_OP_READ_WRITE,
.i2c_address = BME280_ADDR,
.tx_buffer = tx_buffer,
.tx_length = 1,
.rx_buffer = rx_buffer,
.rx_length = 3,
.requester_task = xTaskGetCurrentTaskHandle(),
.notification_value = 0, // Bit position for notification
.timeout = I2C_BUS_TIMEOUT
};
BaseType_t result = i2c_gatekeeper_request(&request);
if (result != pdTRUE) {
return pdFALSE;
}
// Wait for notification - task will pause here
uint32_t notification_value = 0;
BaseType_t notify_result = xTaskNotifyWait(
pdTRUE, // Clear all bits on exit
0,
¬ification_value,
pdMS_TO_TICKS(200) // Timeout if I2C takes too long
);
if (notify_result != pdTRUE) {
ctx->error_count++;
return pdFALSE;
}
if (notification_value & (1 << 0)) {
// Process raw data
int32_t adc_temp = (rx_buffer[0] << 12) | (rx_buffer[1] << 4) |
(rx_buffer[2] >> 4);
// Simplified conversion (actual BME280 requires calibration data)
reading->raw_value = adc_temp;
reading->processed_value = (adc_temp / 5120.0f) - 40.5f;
return pdTRUE;
}
ctx->error_count++;
return pdFALSE;
}
static void vTemperatureSensorTask(void *pvParameters) {
sensor_config_t *config = (sensor_config_t *)pvParameters;
sensor_context_t *ctx = &sensor_contexts[config->sensor_id];
sensor_reading_t reading;
ctx->sensor_id = config->sensor_id;
ctx->read_count = 0;
ctx->error_count = 0;
while (1) {
memset(&reading, 0, sizeof(sensor_reading_t));
reading.sensor_id = config->sensor_id;
reading.type = config->type;
reading.timestamp = xTaskGetTickCount();
// Read sensor
reading.status = read_bme280_temperature(ctx, &reading);
ctx->read_count++;
// Store reading
ctx->last_reading = reading;
// Call callback if registered
if (ctx->callback != NULL) {
ctx->callback(&reading);
}
// Sleep until next polling period
vTaskDelay(pdMS_TO_TICKS(config->polling_period_ms));
}
}
/* ============== Humidity Sensor Task (DHT22) ============== */
#define DHT22_ADDR 0x38
#define DHT22_CMD_READ 0xAC
static BaseType_t read_dht22_humidity(sensor_context_t *ctx,
sensor_reading_t *reading) {
uint8_t tx_buffer[3] = {DHT22_CMD_READ, 0x00, 0x00};
uint8_t rx_buffer[6] = {0};
i2c_request_t request = {
.operation = I2C_OP_READ_WRITE,
.i2c_address = DHT22_ADDR,
.tx_buffer = tx_buffer,
.tx_length = 3,
.rx_buffer = rx_buffer,
.rx_length = 6,
.requester_task = xTaskGetCurrentTaskHandle(),
.notification_value = 1,
.timeout = I2C_BUS_TIMEOUT
};
BaseType_t result = i2c_gatekeeper_request(&request);
if (result != pdTRUE) {
return pdFALSE;
}
uint32_t notification_value = 0;
BaseType_t notify_result = xTaskNotifyWait(
pdTRUE,
0,
¬ification_value,
pdMS_TO_TICKS(200)
);
if (notify_result != pdTRUE) {
ctx->error_count++;
return pdFALSE;
}
if (notification_value & (1 << 1)) {
// Process humidity data (simplified)
int32_t humidity_raw = (rx_buffer[1] << 8) | rx_buffer[2];
reading->raw_value = humidity_raw;
reading->processed_value = (humidity_raw / 655.36f); // 0-100%
return pdTRUE;
}
ctx->error_count++;
return pdFALSE;
}
static void vHumiditySensorTask(void *pvParameters) {
sensor_config_t *config = (sensor_config_t *)pvParameters;
sensor_context_t *ctx = &sensor_contexts[config->sensor_id];
sensor_reading_t reading;
ctx->sensor_id = config->sensor_id;
while (1) {
memset(&reading, 0, sizeof(sensor_reading_t));
reading.sensor_id = config->sensor_id;
reading.type = config->type;
reading.timestamp = xTaskGetTickCount();
reading.status = read_dht22_humidity(ctx, &reading);
ctx->read_count++;
ctx->last_reading = reading;
if (ctx->callback != NULL) {
ctx->callback(&reading);
}
vTaskDelay(pdMS_TO_TICKS(config->polling_period_ms));
}
}
/* ============== Pressure Sensor Task (BMP390) ============== */
#define BMP390_ADDR 0x77
#define BMP390_DATA_REG 0x04
static BaseType_t read_bmp390_pressure(sensor_context_t *ctx,
sensor_reading_t *reading) {
uint8_t tx_buffer[1] = {BMP390_DATA_REG};
uint8_t rx_buffer[3] = {0};
i2c_request_t request = {
.operation = I2C_OP_READ_WRITE,
.i2c_address = BMP390_ADDR,
.tx_buffer = tx_buffer,
.tx_length = 1,
.rx_buffer = rx_buffer,
.rx_length = 3,
.requester_task = xTaskGetCurrentTaskHandle(),
.notification_value = 2,
.timeout = I2C_BUS_TIMEOUT
};
BaseType_t result = i2c_gatekeeper_request(&request);
if (result != pdTRUE) {
return pdFALSE;
}
uint32_t notification_value = 0;
BaseType_t notify_result = xTaskNotifyWait(
pdTRUE,
0,
¬ification_value,
pdMS_TO_TICKS(200)
);
if (notify_result != pdTRUE) {
ctx->error_count++;
return pdFALSE;
}
if (notification_value & (1 << 2)) {
int32_t pressure_raw = (rx_buffer[0] << 16) | (rx_buffer[1] << 8) |
rx_buffer[2];
reading->raw_value = pressure_raw;
reading->processed_value = (pressure_raw / 256.0f) / 100.0f; // Convert to hPa
return pdTRUE;
}
ctx->error_count++;
return pdFALSE;
}
static void vPressureSensorTask(void *pvParameters) {
sensor_config_t *config = (sensor_config_t *)pvParameters;
sensor_context_t *ctx = &sensor_contexts[config->sensor_id];
sensor_reading_t reading;
ctx->sensor_id = config->sensor_id;
while (1) {
memset(&reading, 0, sizeof(sensor_reading_t));
reading.sensor_id = config->sensor_id;
reading.type = config->type;
reading.timestamp = xTaskGetTickCount();
reading.status = read_bmp390_pressure(ctx, &reading);
ctx->read_count++;
ctx->last_reading = reading;
if (ctx->callback != NULL) {
ctx->callback(&reading);
}
vTaskDelay(pdMS_TO_TICKS(config->polling_period_ms));
}
}
/* ============== Motion Sensor Task (PIR) ============== */
static BaseType_t read_pir_motion(sensor_context_t *ctx,
sensor_reading_t *reading) {
// PIR sensor typically uses GPIO, but can be handled via I2C expander
uint8_t tx_buffer[1] = {0x00}; // Read GPIO register
uint8_t rx_buffer[1] = {0};
i2c_request_t request = {
.operation = I2C_OP_READ,
.i2c_address = 0x20, // I2C GPIO expander
.tx_buffer = tx_buffer,
.tx_length = 1,
.rx_buffer = rx_buffer,
.rx_length = 1,
.requester_task = xTaskGetCurrentTaskHandle(),
.notification_value = 3,
.timeout = I2C_BUS_TIMEOUT
};
BaseType_t result = i2c_gatekeeper_request(&request);
if (result != pdTRUE) {
return pdFALSE;
}
uint32_t notification_value = 0;
BaseType_t notify_result = xTaskNotifyWait(
pdTRUE,
0,
¬ification_value,
pdMS_TO_TICKS(100)
);
if (notify_result != pdTRUE) {
ctx->error_count++;
return pdFALSE;
}
if (notification_value & (1 << 3)) {
reading->raw_value = rx_buffer[0] & 0x01;
reading->processed_value = (float)reading->raw_value;
return pdTRUE;
}
ctx->error_count++;
return pdFALSE;
}
static void vMotionSensorTask(void *pvParameters) {
sensor_config_t *config = (sensor_config_t *)pvParameters;
sensor_context_t *ctx = &sensor_contexts[config->sensor_id];
sensor_reading_t reading;
ctx->sensor_id = config->sensor_id;
while (1) {
memset(&reading, 0, sizeof(sensor_reading_t));
reading.sensor_id = config->sensor_id;
reading.type = config->type;
reading.timestamp = xTickCount();
reading.status = read_pir_motion(ctx, &reading);
ctx->read_count++;
ctx->last_reading = reading;
if (ctx->callback != NULL) {
ctx->callback(&reading);
}
vTaskDelay(pdMS_TO_TICKS(config->polling_period_ms));
}
}
/* ============== Sensor Task Factory ============== */
BaseType_t sensor_create_task(uint8_t sensor_id, const sensor_config_t *config) {
if (sensor_id >= NUM_SENSORS || config == NULL) {
return pdFALSE;
}
TaskFunction_t task_function;
switch (config->type) {
case SENSOR_TYPE_TEMPERATURE:
task_function = vTemperatureSensorTask;
break;
case SENSOR_TYPE_HUMIDITY:
task_function = vHumiditySensorTask;
break;
case SENSOR_TYPE_PRESSURE:
task_function = vPressureSensorTask;
break;
case SENSOR_TYPE_MOTION:
task_function = vMotionSensorTask;
break;
default:
return pdFALSE;
}
// Create config copy for task
sensor_config_t *task_config = pvPortMalloc(sizeof(sensor_config_t));
if (task_config == NULL) {
return pdFALSE;
}
*task_config = *config;
task_config->sensor_id = sensor_id;
BaseType_t result = xTaskCreate(
task_function,
"SensorTask",
SENSOR_STACK_SIZE,
task_config,
SENSOR_TASK_PRIORITY,
&sensor_contexts[sensor_id].last_reading.sensor_id // Store task handle
);
return result;
}
void sensor_set_callback(uint8_t sensor_id, sensor_callback_t callback) {
if (sensor_id < NUM_SENSORS) {
sensor_contexts[sensor_id].callback = callback;
}
}
sensor_reading_t sensor_get_last_reading(uint8_t sensor_id) {
if (sensor_id < NUM_SENSORS) {
return sensor_contexts[sensor_id].last_reading;
}
sensor_reading_t empty = {0};
return empty;
}
void sensor_print_stats(uint8_t sensor_id) {
if (sensor_id < NUM_SENSORS) {
sensor_context_t *ctx = &sensor_contexts[sensor_id];
printf("Sensor %u Stats: Reads=%lu, Errors=%lu, Success Rate=%.1f%%\n",
sensor_id,
ctx->read_count,
ctx->error_count,
(ctx->read_count > 0) ?
(100.0f * (ctx->read_count - ctx->error_count) / ctx->read_count) : 0.0f);
}
}
4. Sensor Manager Main Module
// sensor_manager.c
#include "sensor_manager.h"
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>
#include <string.h>
extern QueueHandle_t i2c_gatekeeper_init(void);
extern BaseType_t i2c_gatekeeper_request(i2c_request_t *request);
extern gatekeeper_stats_t i2c_gatekeeper_get_stats(void);
extern void sensor_create_task(uint8_t sensor_id, const sensor_config_t *config);
extern void sensor_set_callback(uint8_t sensor_id, sensor_callback_t callback);
extern sensor_reading_t sensor_get_last_reading(uint8_t sensor_id);
extern void sensor_print_stats(uint8_t sensor_id);
static QueueHandle_t i2c_queue = NULL;
static bool manager_initialized = false;
/* ============== Sensor Callbacks ============== */
static void temperature_callback(const sensor_reading_t *reading) {
if (reading->status == pdTRUE) {
printf("[TEMP] Sensor %u: %.2f°C (Raw: %ld)\n",
reading->sensor_id,
reading->processed_value,
reading->raw_value);
}
}
static void humidity_callback(const sensor_reading_t *reading) {
if (reading->status == pdTRUE) {
printf("[HUMID] Sensor %u: %.1f%% (Raw: %ld)\n",
reading->sensor_id,
reading->processed_value,
reading->raw_value);
}
}
static void pressure_callback(const sensor_reading_t *reading) {
if (reading->status == pdTRUE) {
printf("[PRESS] Sensor %u: %.1f hPa (Raw: %ld)\n",
reading->sensor_id,
reading->processed_value,
reading->raw_value);
}
}
static void motion_callback(const sensor_reading_t *reading) {
if (reading->status == pdTRUE) {
printf("[MOTION] Sensor %u: %s\n",
reading->sensor_id,
reading->raw_value ? "Detected" : "Clear");
}
}
/* ============== Initialization ============== */
BaseType_t sensor_manager_init(void) {
if (manager_initialized) {
return pdTRUE;
}
// Initialize I2C gatekeeper
i2c_queue = i2c_gatekeeper_init();
if (i2c_queue == NULL) {
printf("ERROR: Failed to initialize I2C gatekeeper\n");
return pdFALSE;
}
manager_initialized = true;
printf("Sensor Manager initialized successfully\n");
return pdTRUE;
}
/* ============== Sensor Creation and Management ============== */
BaseType_t sensor_create_and_register(uint8_t sensor_id,
const sensor_config_t *config,
sensor_callback_t callback) {
if (!manager_initialized || sensor_id >= NUM_SENSORS) {
return pdFALSE;
}
// Create sensor task
BaseType_t result = sensor_create_task(sensor_id, config);
if (result != pdPASS) {
printf("ERROR: Failed to create sensor task %u\n", sensor_id);
return pdFALSE;
}
// Register callback
if (callback != NULL) {
sensor_set_callback(sensor_id, callback);
}
printf("Sensor %u registered (Type: %u, Addr: 0x%02X, Period: %u ms)\n",
sensor_id, config->type, config->i2c_address,
config->polling_period_ms);
return pdTRUE;
}
/* ============== Statistics and Monitoring ============== */
void sensor_manager_print_stats(void) {
printf("\n========== Sensor Manager Statistics ==========\n");
// Print I2C gatekeeper stats
gatekeeper_stats_t stats = i2c_gatekeeper_get_stats();
printf("\nI2C Gatekeeper Stats:\n");
printf(" Total Requests: %lu\n", stats.total_requests);
printf(" Successful Ops: %lu\n", stats.successful_ops);
printf(" Failed Ops: %lu\n", stats.failed_ops);
printf(" Queue Overflow Events: %lu\n", stats.queue_overflow);
printf(" Max Queue Depth: %lu/%u\n", stats.max_queue_depth,
I2C_REQUEST_QUEUE_SIZE);
if (stats.total_requests > 0) {
float success_rate = (100.0f * stats.successful_ops) / stats.total_requests;
printf(" Success Rate: %.1f%%\n", success_rate);
}
// Print individual sensor stats
printf("\nIndividual Sensor Stats:\n");
for (uint8_t i = 0; i < NUM_SENSORS; i++) {
sensor_print_stats(i);
}
// Print task information
printf("\nTask Information:\n");
TaskStatus_t *task_status_array;
UBaseType_t num_tasks = uxTaskGetNumberOfTasks();
task_status_array = pvPortMalloc(num_tasks * sizeof(TaskStatus_t));
if (task_status_array != NULL) {
num_tasks = uxTaskGetSystemState(task_status_array, num_tasks, NULL);
for (UBaseType_t i = 0; i < num_tasks; i++) {
printf(" Task: %-20s Priority: %lu State: %u\n",
task_status_array[i].pcTaskName,
task_status_array[i].uxCurrentPriority,
task_status_array[i].eCurrentState);
}
vPortFree(task_status_array);
}
printf("==============================================\n\n");
}
/* ============== I2C Request Wrapper ============== */
BaseType_t i2c_request(i2c_request_t *request) {
if (!manager_initialized || request == NULL) {
return pdFALSE;
}
return i2c_gatekeeper_request(request);
}
/* ============== Async Read Function ============== */
BaseType_t sensor_read_async(uint8_t sensor_id) {
// This function can be called to trigger immediate read if needed
if (sensor_id >= NUM_SENSORS) {
return pdFALSE;
}
return pdTRUE; // Sensors read continuously in their tasks
}
5. Example Usage
// main.c
#include "sensor_manager.h"
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>
/* ============== Monitoring Task ============== */
static void vMonitoringTask(void *pvParameters) {
while (1) {
vTaskDelay(pdMS_TO_TICKS(10000)); // Print stats every 10 seconds
sensor_manager_print_stats();
// Get and print latest readings
printf("\nLatest Sensor Readings:\n");
for (uint8_t i = 0; i < NUM_SENSORS; i++) {
sensor_reading_t reading = sensor_get_last_reading(i);
if (reading.timestamp > 0) {
printf(" Sensor %u: Value=%.2f, Status=%ld\n",
reading.sensor_id,
reading.processed_value,
reading.status);
}
}
}
}
/* ============== Application Entry Point ============== */
int main(void) {
printf("Initializing FreeRTOS Sensor Manager\n");
// Initialize sensor manager (creates gatekeeper task)
if (sensor_manager_init() != pdTRUE) {
printf("FATAL: Sensor manager initialization failed\n");
return 1;
}
// Configure sensors
sensor_config_t sensor_configs[NUM_SENSORS] = {
{
.i2c_address = 0x77,
.type = SENSOR_TYPE_TEMPERATURE,
.polling_period_ms = 1000,
.sensor_id = 0
},
{
.i2c_address = 0x38,
.type = SENSOR_TYPE_HUMIDITY,
.polling_period_ms = 1000,
.sensor_id = 1
},
{
.i2c_address = 0x77,
.type = SENSOR_TYPE_PRESSURE,
.polling_period_ms = 2000,
.sensor_id = 2
},
{
.i2c_address = 0x20,
.type = SENSOR_TYPE_MOTION,
.polling_period_ms = 500,
.sensor_id = 3
}
};
// Create sensor tasks
sensor_create_and_register(0, &sensor_configs[0], temperature_callback);
sensor_create_and_register(1, &sensor_configs[1], humidity_callback);
sensor_create_and_register(2, &sensor_configs[2], pressure_callback);
sensor_create_and_register(3, &sensor_configs[3], motion_callback);
// Create monitoring task
xTaskCreate(vMonitoringTask, "Monitor", 512, NULL,
configMAX_PRIORITIES - 3, NULL);
// Start scheduler
vTaskStartScheduler();
// Should not reach here
return 0;
}
Key Features and Performance Benefits:
1. Task Notifications vs Semaphores
- ✅ Faster (no queue lookup)
- ✅ Uses notification bits for multiple sensors
- ✅ Reduced memory overhead
- ✅ Lower latency for sensor response
2. I2C Gatekeeper Pattern
- ✅ Single point of I2C bus access
- ✅ Prevents bus contention
- ✅ Queue-based request handling
- ✅ Automatic retry mechanism
3. Performance Optimizations
- ✅ Efficient notification-based synchronization
- ✅ Per-sensor precision polling periods
- ✅ Minimal context switching
- ✅ Built-in statistics and monitoring
4. Error Handling
- ✅ Automatic I2C retry logic
- ✅ Timeout protection
- ✅ Error tracking per sensor
- ✅ Queue overflow detection
This implementation provides a robust, scalable solution for managing multiple I2C sensors in resource-constrained embedded systems!