// Una tarea lee retardo por serie y la otra hace parpadear el LED
#include <Arduino.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
// Usamos solo core 1 para la demo (es más sencillo)
#if CONFIG_FREERTOS_UNICORE
static const BaseType_t app_cpu = 0;
#else
static const BaseType_t app_cpu = 1;
#endif
#define LED_PIN 2
static int LED_delay = 100;
#define BUFFER_LENGTH 10
// Tarea parpadeo LED
void toggleLED(void *pvParameters) {
while (true) {
digitalWrite(LED_PIN, HIGH);
vTaskDelay(LED_delay / portTICK_PERIOD_MS);
digitalWrite(LED_PIN, LOW);
vTaskDelay(LED_delay / portTICK_PERIOD_MS);
}
}
// Tarea serial input
void serialInput(void *pvParameters) {
String read_data = "500";
char c;
char buffer[BUFFER_LENGTH];
// borro buffer, si no, se quedar caracteres de antes y no va
memset(buffer, 0, BUFFER_LENGTH);
uint8_t index = 0;
while (true) {
if (Serial.available() > 0) {
c = Serial.read();
if (c == '\n' || c == '\r') {
LED_delay = atoi(buffer);
index = 0;
memset(buffer, 0, BUFFER_LENGTH);
Serial.println("Retardo = " + String(LED_delay));
while (Serial.available()) Serial.read(); // vacía buffer recepción
} else {
if (index < BUFFER_LENGTH - 1) {
buffer[index] = c;
index++;
}
}
// Yo lo había hecho así, pero parece que readStringUntil() bloquea a veces
// read_data = Serial.readStringUntil('\n');
// if (read_data != "") {
// LED_delay = read_data.toInt();
// // if (LED_delay <= 10) // si hay error, retardo mínimo
// // LED_delay = 10;
// Serial.println("Retardo = " + String(LED_delay));
// }
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
}
void setup() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Serial.begin(115200);
xTaskCreatePinnedToCore(toggleLED, "Toggle LED", 1024, NULL, 0, NULL, app_cpu);
xTaskCreatePinnedToCore(serialInput, "Serial input", 1024, NULL, 0, NULL, app_cpu);
// Delete "setup and loop" task
vTaskDelete(NULL);
}
void loop() {
// Aquí no llega, he matado el setup() y el loop()
}