#include <Arduino.h>
#include <Arduino_FreeRTOS.h>
#include <semphr.h>
#include <queue.h>
const int PIN_SENSOR_MOVIMIENTO = 2;
const int PIN_SENSOR_LUZ = A0;
const int PIN_LUCES = 13;
volatile bool movimientoDetectado = false;
volatile int luzAmbiental = 0;
volatile bool lucesEncendidas = false;
SemaphoreHandle_t xMutex;
QueueHandle_t xQueueLuz;
void TareaMonitorizacion(void *pvParameters);
void TareaLecturaSensores(void *pvParameters);
void TareaControlIluminacion(void *pvParameters);
void setup() {
Serial.begin(9600);
pinMode(PIN_SENSOR_MOVIMIENTO, INPUT);
pinMode(PIN_LUCES, OUTPUT);
xMutex = xSemaphoreCreateMutex();
xQueueLuz = xQueueCreate(10, sizeof(int));
xTaskCreate(TareaMonitorizacion, "Monitorizacion", 96, NULL, 1, NULL);
xTaskCreate(TareaLecturaSensores, "LecturaSensores", 96, NULL, 1, NULL);
xTaskCreate(TareaControlIluminacion, "ControlIluminacion",96, NULL, 1, NULL);
vTaskStartScheduler();
}
void loop() {
}
void TareaMonitorizacion(void *pvParameters) {
while (1) {
xSemaphoreTake(xMutex, portMAX_DELAY);
Serial.print("Movimiento: ");
Serial.print(movimientoDetectado);
Serial.print(" | Luz: ");
Serial.print(luzAmbiental);
Serial.print(" | Luces: ");
Serial.println(lucesEncendidas);
xSemaphoreGive(xMutex);
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void TareaLecturaSensores(void *pvParameters) {
while (1) {
int movimiento = digitalRead(PIN_SENSOR_MOVIMIENTO);
int luz = analogRead(PIN_SENSOR_LUZ);
xSemaphoreTake(xMutex, portMAX_DELAY);
movimientoDetectado = movimiento;
luzAmbiental = luz;
xSemaphoreGive(xMutex);
xQueueSend(xQueueLuz, &luz, portMAX_DELAY);
vTaskDelay(pdMS_TO_TICKS(500));
}
}
void TareaControlIluminacion(void *pvParameters) {
const int UMBRAL_LUZ = 500;
while (1) {
if (xQueueReceive(xQueueLuz, &luzAmbiental, portMAX_DELAY) == pdTRUE) {
xSemaphoreTake(xMutex, portMAX_DELAY);
if (movimientoDetectado && luzAmbiental < UMBRAL_LUZ) {
lucesEncendidas = true;
digitalWrite(PIN_LUCES, HIGH);
} else {
lucesEncendidas = false;
digitalWrite(PIN_LUCES, LOW);
}
xSemaphoreGive(xMutex);
}
}
}