#include <stdlib.h>
#if CONFIG_FREERTOS_UNICORE
static const BaseType_t app_cpu = 0;
#else
static const BaseType_t app_cpu = 1;
#endif
// Settings
static const int led_pin = LED_BUILTIN;
static const uint8_t buf_len = 20;
// Global variables
static int rate = 1000;
// Make the LED blink with given rate.
void toggleLED(void* arg){
while(1) {
digitalWrite(led_pin, HIGH);
vTaskDelay(rate / portTICK_PERIOD_MS);
digitalWrite(led_pin, LOW);
vTaskDelay(rate / portTICK_PERIOD_MS);
}
}
// Read rate from Serial and update the global variable.
void readSerial(void* arg){
// Initialization
char c;
uint8_t index = 0;
char buf[buf_len];
memset(buf, 0, buf_len);
while(1) {
if (Serial.available() > 0){
c = Serial.read();
if (c == '\n'){
// Update the rate.
rate = atoi(buf);
// Print the updated information.
Serial.print("Current LED delay: ");
Serial.println(rate);
// Reset.
index = 0;
memset(buf, 0, buf_len);
}
else{
if (index < buf_len){
buf[index++] = c;
}
}
}
}
}
void setup() {
// put your setup code here, to run once:
// Pin configuration
pinMode(led_pin, OUTPUT);
// Serial configuration
Serial.begin(300);
Serial.println("---Multi-task LED Demo---");
Serial.println("Enter a number in milliseconds to change the LED delay.");
// Task to make the LED blink
xTaskCreatePinnedToCore( // Use xTaskCreate() in vanilla FreeRTOS.
toggleLED, // Function to be called.
"Task 1", // Name of task.
1024, // Stack size (bytes in ESP32, words in FreeRTOS).
NULL, // Parameter to pass to function.
1, // Task priority (o to configMAX_PRIORITIES - 1)
NULL, // Task handle
app_cpu); // Run on one core for demo purposes (ESP32 only)
// Task to read and update rate
xTaskCreatePinnedToCore( // Use xTaskCreate() in vanilla FreeRTOS.
readSerial, // Function to be called.
"Task 2", // Name of task.
1024, // Stack size (bytes in ESP32, words in FreeRTOS).
NULL, // Parameter to pass to function.
1, // Task priority (o to configMAX_PRIORITIES - 1)
NULL, // Task handle
app_cpu); // Run on one core for demo purposes (ESP32 only)
// Delete "setup and loop task"
vTaskDelete(NULL);
}
void loop() {
// put your main code here, to run repeatedly:
}