#include <stdio.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_timer.h"
#define NUM_SENSORS 5
typedef struct {
float values[NUM_SENSORS];
int64_t update_timestamp; // Waktu saat data diupdate (ms)
bool data_new;
} shared_buffer_t;
shared_buffer_t sharedDataBuffer;
SemaphoreHandle_t xMutex;
// Task Sensor (Producer)
void sensor_task(void *pvParameters) {
while (1) {
if (xSemaphoreTake(xMutex, portMAX_DELAY)) {
int64_t now = esp_timer_get_time() / 1000;
printf("\n[Sensor Task] Updating buffer at %lld ms\n", now);
for (int i = 0; i < NUM_SENSORS; i++) {
sharedDataBuffer.values[i] = (float)(25 + (rand() % 10));
}
sharedDataBuffer.update_timestamp = now; // Catat waktu update
sharedDataBuffer.data_new = true;
xSemaphoreGive(xMutex);
}
// Sensor update setiap 700ms
vTaskDelay(pdMS_TO_TICKS(700));
}
}
// Task Communication (Consumer)
void communication_task(void *pvParameters) {
while (1) {
if (xSemaphoreTake(xMutex, portMAX_DELAY)) {
if (sharedDataBuffer.data_new) {
int64_t send_time = esp_timer_get_time() / 1000;
// Hitung selisih waktu (Latency)
int64_t latency = send_time - sharedDataBuffer.update_timestamp;
printf("[Comm Task] Sending data... (Time: %lld ms)\n", send_time);
printf(" >> Data Latency (Selisih): %lld ms\n", latency);
sharedDataBuffer.data_new = false;
} else {
printf("[Comm Task] No new data in buffer.\n");
}
xSemaphoreGive(xMutex);
}
// Cek pengiriman setiap 1000ms
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void app_main(void) {
printf("=== SISTEM TASK SYNCHRONIZATION WITH LATENCY LOG ===\n");
xMutex = xSemaphoreCreateMutex();
sharedDataBuffer.data_new = false;
xTaskCreate(sensor_task, "SensorTask", 2048, NULL, 5, NULL);
xTaskCreate(communication_task, "CommTask", 2048, NULL, 5, NULL);
}