Introduction to RTOS Part 2 - Getting Started with FreeRTOS | Digi-Key Electronics

Introduction to RTOS Part 2 - Getting Started with FreeRTOS | Digi-Key Electronics

Introducción a FreeRTOS en ESP32

Conceptos Generales de RTOS

  • En esta serie, se abordarán conceptos generales de RTOS y su implementación usando FreeRTOS en un ESP32, utilizando el Arduino IDE para simplificar el proceso.
  • Se recomienda visitar la documentación de FreeRTOS para entender cómo construir y ejecutar aplicaciones demo que vienen con el código fuente.

Integración de FreeRTOS en Proyectos

  • Incluir FreeRTOS en un proyecto es sencillo; se deben incluir archivos C y encabezados específicos, además de elegir un archivo de gestión de heap.
  • Es importante asignar uno de los temporizadores del microcontrolador como el temporizador tick del RTOS.

Recursos Adicionales para Aprender sobre FreeRTOS

Documentación y Libros Recomendados

  • Se sugiere descargar "Mastering the FreeRTOS Real-Time Kernel" y el manual de referencia para facilitar la navegación por FreeRTOS.
  • La biblioteca FreeRTOS es solo un programador; la biblioteca FreeRTOS Plus incluye controladores adicionales, principalmente para redes como TCP y UDP.

Ejemplos Prácticos

  • Al explorar ejemplos, se debe prestar atención al archivo config que define variables importantes.
  • El ESP32 utiliza una versión modificada de FreeRTOS dentro del marco ESP-IDF, soportando arquitectura SMP (multiprocesamiento simétrico).

Configuraciones Específicas del ESP32

Instalación del Entorno Arduino

  • Para usar el ESP32 con Arduino IDE, se deben agregar URLs específicas en las preferencias del gestor de placas.
  • Los ajustes en un archivo config.h son cruciales; este archivo determina configuraciones como niveles de prioridad y tamaño mínimo del stack.

Definición y Creación de Tareas

  • Al definir tareas, es esencial informar al programador sobre ellas para que pueda priorizarlas adecuadamente. Las funciones deben devolver nada y aceptar un puntero void como parámetro.

Implementación Práctica: Programa Blinky

Creando el Programa Clásico Blinky

  • En este ejemplo clásico, se encenderá un LED durante 500 ms y luego se apagará durante 500 ms.

¿Cómo funcionan los RTOS y la creación de tareas en FreeRTOS?

Introducción a los RTOS y el temporizador de ticks

  • La mayoría de los sistemas operativos en tiempo real (RTOS) utilizan un temporizador de ticks, que es un temporizador de hardware del microcontrolador que interrumpe al procesador a intervalos específicos.
  • El período de interrupción se conoce como "tick", y el planificador tiene la oportunidad de determinar qué tarea debe ejecutarse en cada tick.
  • FreeRTOS establece por defecto el período del tick en un milisegundo, definiendo portTICK_PERIOD_MS como uno.

Creación y configuración de tareas

  • La función vTaskDelay espera el número de ticks para retrasar, no el número de milisegundos; por lo tanto, se debe dividir los milisegundos deseados por el período del tick.
  • Al usar xTaskCreatePinnedToCore, se indica al planificador que la tarea debe ejecutarse solo en uno de los núcleos disponibles. Esta función no está presente en Vanilla FreeRTOS; se utilizaría xTaskCreate en su lugar.

Parámetros importantes para las tareas

  • Se deben especificar varios parámetros: la función a llamar para la tarea, un nombre para la tarea como cadena, y el tamaño del stack en bytes (mínimo 768 bytes).
  • La prioridad de la tarea puede variar entre cero (baja prioridad) y 24 (alta prioridad), siendo 25 el máximo configurado por defecto.

Ejecución y gestión de tareas

  • En Arduino con ESP32, las funciones setup y loop existen dentro de su propia tarea separada del punto principal del programa.
  • Las funciones corren con una prioridad establecida (uno en este caso), lo que puede afectar otras tareas si tienen menor prioridad.

Desafío práctico

Video description

FreeRTOS is a free and open source real-time operating system (RTOS) owned and maintained by Amazon. The solution to the challenge in the video can be found here: https://www.digikey.com/en/maker/projects/introduction-to-rtos-solution-to-part-2-freertos/b3f84c9c9455439ca2dcb8ccfce9dec5 ESP-IDF FreeRTOS SMP Changes: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/freertos-smp.html Add this URL to the "Additional Boards Manager URLs" window in Arduino for ESP32 support: https://dl.espressif.com/dl/package_esp32_index.json In this video, we talk about how a task is created in FreeRTOS using the ESP32 and Arduino. A task in FreeRTOS is similar to a thread in other multi-threaded environments (e.g. POSIX). It is a unit of CPU utilization designed to accomplish some goal. For our purposes, we just want to create a new thread and toggle an LED. The ESP32 that comes with many development boards (including the Adafruit Feather HUZZAH32 shown in the video) runs a modified version of FreeRTOS (if you are using the ESP32 package for Arduino or the Espressif SDK). Most importantly, the ESP32 version (named ESP-IDF) supports the dual-core processor on the ESP32. Tasks created with the regular xTaskCreate() can run on either core as chosen by the scheduler. For demo purposes, we want to run all tasks on a single core. This will allow us to experiment with prioritization and shared resources later in this series. To do this on the ESP32, we use the xTaskCreatePinnedToCore() function instead and specify which core to use. If you are using vanilla FreeRTOS in your own build system, you will want to use xTaskCreate() instead. Product Links: https://www.digikey.com/en/products/detail/adafruit-industries-llc/3405/7244967 Related Videos: Introduction to RTOS Part 1 - What is a Real-Time Operating System (RTOS)? - https://youtu.be/F321087yYy4​ Introduction to RTOS Part 2 - Getting Started with FreeRTOS - https://youtu.be/JIr7Xm_riRs​ Introduction to RTOS Part 3 - Task Scheduling - https://youtu.be/95yUbClyf3E​ Introduction to RTOS Part 4 - Memory Management - https://youtu.be/Qske3yZRW5I​ Introduction to RTOS Part 5 - Queue - https://youtu.be/pHJ3lxOoWeI​ Introduction to RTOS Part 6 - Mutex - https://youtu.be/I55auRpbiTs​ Introduction to RTOS Part 7 - https://youtu.be/5JcMtbA9QEE​ Introduction to RTOS Part 8 - https://youtu.be/b1f1Iex0Tso Introduction to RTOS Part 9 - https://youtu.be/qsflCf6ahXU Introduction to RTOS Part 10 - https://youtu.be/hRsWi4HIENc Introduction to RTOS Part 11 - https://youtu.be/C2xKhxROmhA Introduction to RTOS Part 12 - https://youtu.be/LPSHUcH5aQc Related Project Links: https://www.digikey.com/en/maker/projects/introduction-to-rtos-solution-to-part-2-freertos/b3f84c9c9455439ca2dcb8ccfce9dec5 Related Articles: https://www.digikey.com/en/maker/projects/what-is-an-rtos-real-time-operating-system/28d8087f53844decafa5000d89608016 Learn more: Maker.io - https://www.digikey.com/en/maker Digi-Key’s Blog – TheCircuit https://www.digikey.com/en/blog Connect with Digi-Key on Facebook https://www.facebook.com/digikey.electronics/ And follow us on Twitter https://twitter.com/digikey