#include <Arduino.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

// Task function to demonstrate heap usage
void vTaskFunction(void *pvParameters)
{
    // Infinite loop for task
    for (;;)
    {
        // Get the free heap size
        size_t xFreeHeapSize = xPortGetFreeHeapSize();
        size_t xMinimumEverFreeHeapSize = xPortGetMinimumEverFreeHeapSize();

        // Print the heap size to the Serial Monitor
        Serial.print("Free Heap Size: ");
        Serial.print(xFreeHeapSize);
        Serial.println(" bytes");

        Serial.print("Minimum Ever Free Heap Size: ");
        Serial.print(xMinimumEverFreeHeapSize);
        Serial.println(" bytes");

        // Use pvPortMalloc() to allocate memory
        size_t allocSize = 100;
        void* pvMemory = pvPortMalloc(allocSize * sizeof(char));
        if (pvMemory != NULL)
        {
            // Initialize allocated memory to zero
            memset(pvMemory, 0, allocSize * sizeof(char));
            
            Serial.print("Allocated ");
            Serial.print(allocSize);
            Serial.println(" bytes using pvPortMalloc()");
            
            // Free the allocated memory
            vPortFree(pvMemory);
        }

        // Delay for a while
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void setup()
{
    // Initialize Serial Monitor
    Serial.begin(115200);

    // Create task
    xTaskCreate(vTaskFunction, "Task 1", 2048, NULL, 1, NULL);
}

void loop()
{
    // Do nothing in loop
}