▶ Ver video ⌥ Código en GitHub

¿Qué es FreeRTOS?

Un RTOS (Real-Time Operating System) permite ejecutar múltiples tareas “en paralelo” en un microcontrolador de un solo núcleo mediante time-slicing. FreeRTOS es el más usado en sistemas embebidos.

Conceptos clave

  • Task: función que corre indefinidamente (loop infinito)
  • Semáforo binario: mecanismo de señalización entre tareas (dado/tomado)
  • Scheduler: decide qué tarea corre en cada tick del sistema

Crear dos tareas

#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"

SemaphoreHandle_t xSem;

void vTaskLED(void *pvParameters) {
    for (;;) {
        /* Esperar señal del pulsador */
        if (xSemaphoreTake(xSem, portMAX_DELAY) == pdTRUE) {
            HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
        }
    }
}

void vTaskButton(void *pvParameters) {
    for (;;) {
        if (HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13) == GPIO_PIN_RESET) {
            xSemaphoreGiveFromISR(xSem, NULL);
            vTaskDelay(pdMS_TO_TICKS(200)); /* debounce */
        }
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}

Inicializar y lanzar el scheduler

int main(void) {
    HAL_Init();
    SystemClock_Config();
    MX_GPIO_Init();

    xSem = xSemaphoreCreateBinary();

    xTaskCreate(vTaskLED,    "LED",    128, NULL, 1, NULL);
    xTaskCreate(vTaskButton, "Button", 128, NULL, 2, NULL);

    vTaskStartScheduler(); /* nunca retorna */
    for (;;);
}

Puntos importantes

  • vTaskDelay libera la CPU durante la espera (no es un busy-wait)
  • portMAX_DELAY en el semáforo bloquea indefinidamente hasta recibir la señal
  • El stack de cada tarea se configura en palabras (128 = 512 bytes en ARM)
← Volver a proyectos