Rocketmagnet
Rocketmagnet

Reputation: 5869

Why is FreeRTOS not preempting tasks?

I'm using FreeRTOS on a Raspberry Pi Pico (R2040). I'm starting with a 'hello world' type program to check that I can run two tasks:

#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "pico/stdlib.h"
#include <stdio.h>

void Task1(void* nothing)
{
    while(1)
    {
        printf("Task1\n");
        sleep_ms(1000);                             // Doesn't allow preemption
        //vTaskDelay(1 * configTICK_RATE_HZ );      // Does allow preemption
    }
}

void Task2(void* nothing)
{
    sleep_ms(500);
    while(1)
    {
        printf("Task2\n");
        sleep_ms(1000);                             // Doesn't allow preemption
        //vTaskDelay(1 * configTICK_RATE_HZ );      // Does allow preemption
    }
}


void main()
{
    stdio_init_all();
    sleep_ms(2000);
    printf("\n\n\n\nHello\n\n");

    TaskHandle_t xTask1Handle = NULL;
    TaskHandle_t xTask2Handle = NULL;

    BaseType_t ret1 = xTaskCreate(Task1, "Task1", 256, 0, 10, &xTask1Handle);
    BaseType_t ret2 = xTaskCreate(Task2, "Task2", 256, 0, 10, &xTask2Handle);

    if (ret1 == pdPASS) printf("Task 1 created OK\n");
    else                printf("Task 1 failed\n");

    if (ret2 == pdPASS) printf("Task 2 created OK\n");
    else                printf("Task 2 failed\n");

    vTaskStartScheduler();

    while(1)
    {
    }
}

The output of the program shows that if I use sleep_ms() then only one task prints its output. But if I use vTaskDelay() then both tasks run. Presumably this means that FreeRTOS is not preempting my tasks?

In my FreeRTOSConfig.h file, I have enabled preemption.

#define configUSE_PREEMPTION                    1
#define configUSE_TIME_SLICING                  1

Is there something else I need to do to enable preemption?

Upvotes: 2

Views: 151

Answers (0)

Related Questions