/*
Example of a FreeRTOS mutex
https://www.freertos.org/Real-time-embedded-RTOS-mutexes.html
*/
// Include Arduino FreeRTOS library
#include <Arduino_FreeRTOS.h>
// Include mutex support
#include <semphr.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address of the LCD
struct SensorData {
int ldr1;
int ldr2;
};
SemaphoreHandle_t mutex; // Declare the mutex globally
SensorData sensorValues;
/*
Declaring a global variable of type SemaphoreHandle_t
*/
int globalCount = 0;
void setup() {
Serial.begin(9600);
Wire.begin();
lcd.init();
lcd.backlight();
/**
Create a mutex.
https://www.freertos.org/CreateMutex.html
*/
mutex = xSemaphoreCreateMutex();
if (mutex != NULL) {
Serial.println("Mutex created");
}
/**
Create tasks
*/
xTaskCreate(TaskLDR, "LDR_Task", 128, NULL, 1, NULL);
xTaskCreate(TaskLCD, "LCD_Task", 128, NULL, 1, NULL);
}
void loop() {}
void TaskLDR(void *pvParameters) {
for (;;) {
// Simulate reading LDR values (replace with actual readings)
int ldr1Value = analogRead(A0);
int ldr2Value = analogRead(A1);
if (xSemaphoreTake(mutex, 10) == pdTRUE) {
sensorValues.ldr1 = ldr1Value;
sensorValues.ldr2 = ldr2Value;
xSemaphoreGive(mutex);
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void TaskLCD(void *pvParameters) {
for (;;) {
if (xSemaphoreTake(mutex, 10) == pdTRUE) {
lcd.setCursor(0, 0);
lcd.print("LDR1: ");
lcd.print(sensorValues.ldr1);
lcd.setCursor(0, 1);
lcd.print("LDR2: ");
lcd.print(sensorValues.ldr2);
xSemaphoreGive(mutex);
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}