#include <stdlib.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
// Cores
static const BaseType_t app_cpu_0 = 0; //Core 1
static const BaseType_t app_cpu_1 = 1; //Core 2
// Settings
static const uint8_t buf_len = 100;
static int blink_count = 1;
// Pins
static const int led_pin = 4;
/************************************************************/
// Task
// Task: LED Blink Task
void toggleLED(void *parameter)
{
int i;
while(1)
{
if(Serial.available() > 0)
{
vTaskDelay(250 / portTICK_PERIOD_MS);
for(i=0;i<blink_count;i++)
{
digitalWrite(led_pin, HIGH);
vTaskDelay(250 / portTICK_PERIOD_MS);
digitalWrite(led_pin, LOW);
vTaskDelay(250 / portTICK_PERIOD_MS);
}
blink_count = 0;
}
}
}
// Task: Start Serial Read Task
void readSerial(void *parameters)
{
char c;
static char buf[buf_len];
static char inte_buf[buf_len];
uint8_t idx = 0;
uint8_t Ax_buf_idx = 0;
memset(buf, 0, buf_len);
memset(inte_buf, 0, buf_len);
while (1)
{
if (Serial.available() > 0)
{
c = Serial.read();
if (c == '\n')
{
blink_count = atoi(inte_buf);
Serial.print("Updated Blink Count: ");
Serial.println(blink_count);
memset(buf, 0, buf_len);
memset(inte_buf, 0, buf_len);
idx = 0;
Ax_buf_idx = 0;
}
else
{
if (idx < buf_len - 1)
{
buf[idx] = c;
if (c >= '0' && c <= '9' && Ax_buf_idx < buf_len - 1)
{
inte_buf[Ax_buf_idx] = c;
Ax_buf_idx++;
}
idx++;
}
}
}
vTaskDelay(10 / portTICK_PERIOD_MS); // Add delay to prevent task hogging
}
}
/************************************************************/
// Main
void setup()
{
pinMode(led_pin, OUTPUT);
Serial.begin(9600);
vTaskDelay(1000 / portTICK_PERIOD_MS);
Serial.println("\n** Counted LED Blink in Multi-Task **");
Serial.println("Enter the number of time LED will blink(Any Formet):");
//LED Blink Task
xTaskCreatePinnedToCore(
toggleLED,
"Toggle LED",
1024,
NULL,
1, // Task priority(Low)
NULL,
app_cpu_0);
//Start Serial Read Task
xTaskCreatePinnedToCore(
readSerial,
"Read Serial",
1024,
NULL,
2, // Task priority(High)
NULL,
app_cpu_1);
vTaskDelete(NULL); // Delete "setup and loop" task
}
void loop() {
// Nothing
}