实时操作系统FreeRTOS学习笔记

FreeRTOS官方API手册

创建任务

#include <stdio.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
static const char* TAG = "main.c";

void task1(void *pt)
{
    while (1)
    {
        ESP_LOGI(TAG, "1");
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

void task2(void *pt)
{
    while (1)
    {
        ESP_LOGI(TAG, "2");
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

void app_main(void)
{
    xTaskCreate(task1, "task1", 2048, NULL, 1, NULL);
    xTaskCreate(task2, "task2", 2048, NULL, 1, NULL);
}

任务状态

image

队列

#include <stdio.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
static const char* TAG = "main.c";
static QueueHandle_t xQueueHandle;

void task1(void *pt)
{
    int a = 0;
    while (1)
    {
        // 往队列里面放数据,若队列已满,阻塞在这里
        xQueueSend(xQueueHandle, &a, portMAX_DELAY);
        a++;
        vTaskDelay(2000 / portTICK_PERIOD_MS);
    }
}

void task2(void *pt)
{
    int val;
    while (1)
    {
        // 从队列里面取数据,若队列里没有数据,阻塞在这里
        xQueueReceive(xQueueHandle, &val, portMAX_DELAY);
        ESP_LOGI(TAG, "%d",val);
        vTaskDelay(500 / portTICK_PERIOD_MS);
    }
}

void app_main(void)
{
    xQueueHandle = xQueueCreate(10, sizeof(int));
    xTaskCreate(task1, "task1", 2048, NULL, 1, NULL);
    xTaskCreate(task2, "task2", 2048, NULL, 1, NULL);
}

信号量

#include <stdio.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
static const char *TAG = "main.c";
static SemaphoreHandle_t xSemCalc;

void task1(void *pt)
{
    while (1)
    {
        // 将信号量+1
        xSemaphoreGive(xSemCalc);
        ESP_LOGI(TAG, "生产");
        vTaskDelay(2000 / portTICK_PERIOD_MS);
    }
}

void task2(void *pt)
{
    while (1)
    {
        // 若信号量为0,永远阻塞在这里
        // 若信号量不为0,将信号量-1,然后执行下面的内容
        xSemaphoreTake(xSemCalc, portMAX_DELAY);
        ESP_LOGI(TAG, "消费");
        vTaskDelay(500 / portTICK_PERIOD_MS);
    }
}

void app_main(void)
{
    xSemCalc = xSemaphoreCreateCounting(10, 0);
    xTaskCreate(task1, "task1", 2048, NULL, 1, NULL);
    xTaskCreate(task2, "task2", 2048, NULL, 1, NULL);
}

定时器

image

#include <stdio.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
static const char *TAG = "main.c";
static TimerHandle_t xTimerHandle;

void MyTimerCallbackFunction(TimerHandle_t xTimer)
{
    static int cnt = 0;
    ESP_LOGI(TAG, "%d", cnt++);
}

void app_main(void)
{
    xTimerHandle = xTimerCreate("mytimer", 100, pdTRUE, NULL, MyTimerCallbackFunction);
    xTimerStart(xTimerHandle, 0);
}

注意:在定时器中断中使用ESP_LOGI或其它打印函数,需要在menuconfig中修改configTIMER_TASK_STACK_DEPTH,默认值不足以支撑打印函数。

posted @ 2024-07-29 21:21:47
评论加载中...
发表评论