Search code examples
esp32freertosesp-idf

How to cleanly tell a task to die in FreeRTOS


I'm making a light with an ESP32 and the HomeKit library I chose uses FreeRTOS and esp-idf, which I'm not familiar with.

Currently, I have a function that's called whenever the colour of the light should be changed, which just changes it in a step. I'd like to have it fade between colours instead, which will require a function that runs for a second or two. Having this block the main execution of the program would obviously make it quite unresponsive, so I need to have it run as a task.

The issue I'm facing is that I only want one copy of the fading function to be running at a time, and if it's called a second time before it's finished, the first copy should exit(without waiting for the full fade time) before starting the second copy.

I found vTaskDelete, but if I were to just kill the fade function at an arbitrary point, some variables and the LEDs themselves will be in an unknown state. To get around this, I thought of using a 'kill flag' global variable which the fading function will check on each of its loops.

Here's the pseudocode I'm thinking of:

update_light {
    kill_flag = true
    wait_for_fade_to_die
    xTaskCreate fade
}

fade {
    kill_flag = false
    loop_1000_times {
        (fading code involving local and global variables)
        .
        .
        if kill_flag, vTaskDelete(NULL)
        vTaskDelay(2 / portTICK_RATE_MS)
    }
}

My main questions are:

  • Is this the best way to do this or is there a better option?
  • If this is ok, what is the equivalent of my wait_for_fade_to_die? I haven't been able to find anything from a brief look around, but I'm new to FreeRTOS.

Solution

  • I'm sorry to say that I have the impression that you are pretty much on the wrong track trying to solve your concrete problem. You are writing that you aren't familiar with FreeRTOS and esp-idf, so I would suggest you first familiarize with freeRTOS (or with the idea of RTOS in general or with any other RTOS, transferring that knowledge to freeRTOS, ...).

    In doing so, you will notice that (apart from some specific examples) a task is something completely different than a function which has been written for sequential "batch" processing of a single job.

    Model and Theory

    Usually, the most helpful model to think of when designing a good RTOS task inside an embedded system is that of a state machine that receives events to which it reacts, possibly changing its state and/or executing some actions whose starting points and payload depends on the the event the state machine received as well as the state it was in when the event is detected. While there is no event, the task shall not idle but block at some barrier created by the RTOS function which is supposed to deliver the next relevant event.

    Implementing such a task means programming a task function that consists of a short initialisation block followed by an infinite loop that first calls the RTOS library to get the next logical event (see right below...) and then the code to process that logical event. Now, the logical event doesn't have to be represented by an RTOS event (while this can happen in simple cases), but can also be implemented by an RTOS queue, mailbox or other. In such a design pattern, the tasks of your RTOS-based software exist "forever", waiting for the next job to perform.

    How to apply the theory to your problem

    You have to check how to decompose your programming problem into different tasks.

    Currently, I have a function that's called whenever the colour of the light should be changed, which just changes it in a step. I'd like to have it fade between colours instead, which will require a function that runs for a second or two. Having this block the main execution of the program would obviously make it quite unresponsive, so I need to have it run as a task.

    I hope that I understood the goal of your application correctly: The system is driving multiple light sources of different colours, and some "request source" is selecting the next colour to be displayed. When a different colour is requested, the change shall not be performed instantaneously but there shall be some "fading" over a certain period of time. The system (and its request source) shall remain responsive even while a fade takes place, possibly changing the direction of the fade in the middle.

    I think you didn't say where the colour requests are coming from. Therefore, I am guessing that this request source could be some button(s), a serial interface or a complex algorithm (or random number generator?) running in background. It doesnt really matter now.

    The issue I'm facing is that I only want one copy of the fading function to be running at a time, and if it's called a second time before it's finished, the first copy should exit (without waiting for the full fade time) before starting the second copy.

    What you are essentially looking for is how to change the state (here: the target colour of light fading) at any time so that an old, ongoing fade procedure becomes obsolete but the output (=light) behaviour will not change in an incontinuous way.

    I suggest you set up the following tasks:

    • One (or more) task(s) to generate the colour changing requests from ...whatever you need here.

    • One task to evaluate which colour blend shall be output currently. That task shall be ready to receive

      1. a new-colour request (changing the "target colour" state without changing the current colour blend value)
      2. a periodical tick event (e.g., from a hardware or software timer) that causes the colour blend value to be updated into the direction of the current target colour
    • Zero, one or multiple tasks to implement the colour blend value by driving the output features of the system (e.g., configuring GPIOs or PWMs, or transmitting information through a serial connection...we don't know). If adjusting the output part is just assigning some registers, the "Zero" is the right thing for you here. Otherwise, try "one or multiple".

    What to do now

    I found vTaskDelete, but if I were to just kill the fade function at an arbitrary point, some variables and the LEDs themselves will be in an unknown state. To get around this, I thought of using a 'kill flag' global variable which the fading function will check on each of its loops.

    Just don't do that. Killing a task, even one that didn't prepare for being killed from inside causes a follow-up of requirements to manage and clean-up output stuff by your software that you will end up wondering why you even started using an RTOS.

    I do know that starting to design and program in that way when you never did so is a huge endeavour, starting like a jump into cold water. Please trust me, this way you will learn the basics how to design and implement great embedded systems. Professional education companies offer courses about RTOS integration, responsive programming and state machine design for several thousands of $/€/£, which is a good indicator of this kind of working knowledge.

    Good luck! Along that way, you'll come across a lot of detail questions which you are welcome to post to this board (or find earlier answers on).