// FreeRTOS with a queue
//
// It is just a simple queue for integers.
// The ESP32-C3 has 400kbyte of RAM,
// so a few tasks with a stack of 2kbyte should be okay.
const int blueLedPin = 7;
const int greenLedPin = 6;
QueueHandle_t blinkQueue;
void setup()
{
Serial.begin(115200);
pinMode(blueLedPin,OUTPUT);
pinMode(greenLedPin,OUTPUT);
// Create a queue for integers, 10 elements is more than enough.
blinkQueue = xQueueCreate( 10, sizeof(int));
// Create the two new tasks.
xTaskCreate(BlinkTask,"Blink",2000,NULL,1,NULL);
xTaskCreate(ReadSerialTask,"ReadSerial",2000,NULL,1,NULL);
}
void loop()
{
// Do something with the task running the Arduino loop().
digitalWrite(blueLedPin,HIGH);
delay(200);
digitalWrite(blueLedPin,LOW);
delay(350);
}
void BlinkTask(void * pvParameters)
{
int blinkValue = 250;
while(true)
{
int newValue;
// Retrieve a new value.
// Do not wait, to avoid influencing the blinking.
// Check the new value and use it if it is okay.
if( xQueueReceive( blinkQueue, &newValue, 0) == pdPASS)
{
if(newValue > 10 && newValue < 1000)
blinkValue = newValue;
}
digitalWrite(greenLedPin,HIGH);
delay(blinkValue);
digitalWrite(greenLedPin,LOW);
delay(blinkValue);
}
}
void ReadSerialTask(void * pvParameters)
{
// A buffer of 20 characters should be enough.
// The 'index' is the first free index where the
// character can be stored.
char buffer[20];
int index = 0;
Serial.println();
Serial.println("Enter a number (it will be the delay for the green LED).");
while(true)
{
if(Serial.available() > 0)
{
char newChar = (char) Serial.read();
if(newChar == '\n' or newChar == '\r')
{
// The end of the input is found.
// Put a zero terminator at the current location.
// Send the integer.
// The timeout of 1 second for sending it can be seen
// as a safety, if all the tasks gets clogged up.
buffer[index] = '\0';
int number = atoi(buffer);
xQueueSend(blinkQueue,(void *)&number,1000/portTICK_PERIOD_MS);
// Clear the buffer.
index = 0;
}
else
{
// Store the new character and advance the index.
buffer[index] = newChar;
index++;
// An array of 20 elements is [0] up to [19].
// If the buffer is filled up to [19], then
// the character at [19] will be overwritten
// by the zero-terminator.
if(index > 19)
index = 19;
}
}
else
{
// There was nothing available at the Serial input.
// The Arduino function Serial.available() has no timeout
// to work together with FreeRTOS.
// This task does not need to run at 100% checking the
// Serial input. Once every 1...100 ms is fast enoughy.
// Let's use something between 1 and 100: 10 ms
delay(10);
}
}
}
loop()
BlinkTask
Demonstration of a simple queue in FreeRTOS.