#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#define NUM_SENSORS 5
uint16_t sharedDataBuffer[NUM_SENSORS] = {0};
SemaphoreHandle_t bufferMutex;
uint16_t readSensor(int sensorId) {
return rand() % 100; // Generate random data for sensor
}
void sensorTask(void *param) {
while (1) {
if (xSemaphoreTake(bufferMutex, portMAX_DELAY)) { //get mutex
printf("Sensor Task: Updating buffer...\n");
for (int i = 0; i < NUM_SENSORS; i++) {
sharedDataBuffer[i] = readSensor(i);
}
xSemaphoreGive(bufferMutex); // Release mutex
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void communicationTask(void *param) {
while (1) {
if (xSemaphoreTake(bufferMutex, portMAX_DELAY)) {
printf("Communication Task: Sending data [");
for (int i = 0; i < NUM_SENSORS; i++) {
printf("%d", sharedDataBuffer[i]);
if (i < NUM_SENSORS - 1) printf(", ");
}
printf("]\n");
xSemaphoreGive(bufferMutex);
}
vTaskDelay(pdMS_TO_TICKS(2000));
}
}
void app_main(void)
{
bufferMutex = xSemaphoreCreateMutex(); //mutex create
if (bufferMutex == NULL) {
printf("Failed to create mutex!\n");
return;
}
xTaskCreate(sensorTask, "Sensor Task", 2048, NULL, 2, NULL);
xTaskCreate(communicationTask, "Communication Task", 2048, NULL, 1, NULL);
}