#include <stdlib.h>
// Use only core 1 for demo purposes
#if CONFIG_FREERTOS_UNICORE
static const BaseType_t app_cpu = 0;
#else
static const BaseType_t app_cpu = 1;
#endif
// Settings
static const uint8_t buf_len = 20;
// Pins
static const int led_pin = 2;
// Globals
static int led_delay = 500; // ms
// Task handles
TaskHandle_t SerialTaskHandle = NULL;
TaskHandle_t BlinkTaskHandle = NULL;
//*****************************************************************************
// Tasks
// Task: Blink LED at rate set by global variable
void toggleLED(void *parameter) {
pinMode(led_pin, OUTPUT);
while (1) {
digitalWrite(led_pin, HIGH);
vTaskDelay(pdMS_TO_TICKS(led_delay));
digitalWrite(led_pin, LOW);
vTaskDelay(pdMS_TO_TICKS(led_delay));
}
}
// Task: Read from serial terminal
void readSerial(void *parameters) {
char c;
char buf[buf_len];
uint8_t idx = 0;
Serial.println("Enter a number in milliseconds to change the LED delay.");
// Loop forever
while (1) {
if (Serial.available() > 0) {
c = Serial.read();
// Update delay variable and reset buffer if we get a newline character
if (c == '\n') {
buf[idx] = '\0'; // Null-terminate the string
led_delay = atoi(buf);
Serial.print("Updated LED delay to: ");
Serial.println(led_delay);
idx = 0;
} else {
// Only append if index is not over message limit
if (idx < buf_len - 1) {
buf[idx] = c;
idx++;
}
}
}
vTaskDelay(pdMS_TO_TICKS(100)); // Delay to avoid busy-waiting
}
}
//*****************************************************************************
// Main
void setup() {
Serial.begin(115200);
// Create tasks
xTaskCreate(readSerial, "SerialTask", 2048, NULL, 1, &SerialTaskHandle);
xTaskCreate(toggleLED, "BlinkTask", 2048, NULL, 2, &BlinkTaskHandle);
}
void loop() {
// Empty because everything is handled by FreeRTOS tasks
}