#include <Arduino.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/semphr.h>
// Deklarasi handle semaphore
SemaphoreHandle_t xSemaphore;
// Deklarasi resource bersama
int sharedCounter = 0;
// Task function prototypes
void Task1(void *pvParameters);
void Task2(void *pvParameters);
void Task3(void *pvParameters);
void setup() {
// Initialize serial communication
Serial.begin(115200);
delay(1000); // Give time for serial monitor to initialize
// Membuat binary semaphore
xSemaphore = xSemaphoreCreateBinary(); // Create a binary semaphore
// Pastikan semaphore berhasil dibuat
if (xSemaphore != NULL) {
// Berikan semaphore pertama kali
xSemaphoreGive(xSemaphore);
// Membuat 3 tasks
xTaskCreate(Task1, "Task 1", 1000, NULL, 1, NULL);
xTaskCreate(Task2, "Task 2", 1000, NULL, 1, NULL);
xTaskCreate(Task3, "Task 3", 1000, NULL, 1, NULL);
}
}
void loop() {
// Tidak ada yang perlu dilakukan dalam loop()
delay(10);
}
// Task 1
void Task1(void *pvParameters) {
while (1) {
// Coba ambil semaphore
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
// Akses resource bersama
Serial.print("Task 1: Mengakses dan mengubah sharedCounter. Sebelumnya: ");
Serial.println(sharedCounter);
sharedCounter++;
Serial.print("Task 1: Setelah diubah: ");
Serial.println(sharedCounter);
// Lepaskan semaphore
xSemaphoreGive(xSemaphore);
}
vTaskDelay(1000 / portTICK_PERIOD_MS); // Delay task 1 detik
}
}
// Task 2
void Task2(void *pvParameters) {
while (1) {
// Coba ambil semaphore
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
// Akses resource bersama
Serial.print("Task 2: Mengakses dan mengubah sharedCounter. Sebelumnya: ");
Serial.println(sharedCounter);
sharedCounter += 2;
Serial.print("Task 2: Setelah diubah: ");
Serial.println(sharedCounter);
// Lepaskan semaphore
xSemaphoreGive(xSemaphore);
}
vTaskDelay(2000 / portTICK_PERIOD_MS); // Delay task 2 detik
}
}
// Task 3
void Task3(void *pvParameters) {
while (1) {
// Coba ambil semaphore
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) {
// Akses resource bersama
Serial.print("Task 3: Mengakses dan mengubah sharedCounter. Sebelumnya: ");
Serial.println(sharedCounter);
sharedCounter += 3;
Serial.print("Task 3: Setelah diubah: ");
Serial.println(sharedCounter);
// Lepaskan semaphore
xSemaphoreGive(xSemaphore);
}
vTaskDelay(3000 / portTICK_PERIOD_MS); // Delay task 3 detik
}
}