#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 buf_len = 255;
// Global
static char* msg = NULL;
static volatile uint8_t flag = 0;
// Task:
void listen(void* arg) {
// Initialize and reset.
char c;
char buf[buf_len];
memset(buf, 0, buf_len);
int index = 0;
while (1) {
if (Serial.available() > 0) {
c = Serial.read();
if (c == '\n'){
buf[index] = '\0';
// Try to allocate the memory if the buffer is not in use.
// The message will be ignored if the buffer is still in use.
if (flag == 0){
msg = (char*)pvPortMalloc((index + 1) * sizeof(char));
// If malloc return 0 (out of memory), throw an error and reset.
configASSERT(msg);
// Copy message.
memcpy(msg, buf, index + 1);
// Notify other task that message is ready.
flag = 1;
}
// Reset.
index = 0;
memset(buf, 0, buf_len);
}
else{
if (index < buf_len){
buf[index++] = c;
}
}
}
}
}
// Task:
void talk(void* arg) {
while(1) {
if (flag == 1){
Serial.println(msg);
// Give amount of free heap memory.
Serial.print("Free heap (bytes): ");
Serial.println(xPortGetFreeHeapSize());
// Free the memory.
vPortFree(msg);
msg = NULL;
// Reset the flag.
flag = 0;
}
}
}
void setup() {
// put your setup code here, to run once:
// Serial configuration
Serial.begin(115200);
// Wait a moment so that we won't miss outputs.
vTaskDelay(1000 / portTICK_PERIOD_MS);
Serial.println();
Serial.println("---FreeRTOS Heap Demo---");
Serial.println("Please enter a string:");
// Task to run once with higher priority.
xTaskCreatePinnedToCore( // Use xTaskCreate() in vanilla FreeRTOS.
listen, // Function to be called.
"Listen", // 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 run once with higher priority.
xTaskCreatePinnedToCore( // Use xTaskCreate() in vanilla FreeRTOS.
talk, // Function to be called.
"Talk", // 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:
}