Search code examples
csemaphoreinterruptesp32freertos

ESP32 FreeRTOS non-blocking semaphore in task


I have a task that waits for a semaphore to run. Then it has to go in an infinite loop to control a motor position.

I would like to break this second loop when the stop button is pressed. Is there any way to call xSemaphoreTake() to break from the second loop but not block the while loop of the control?

Let me try to give some code example:

void startTaskFunction(void *params){ //this is the function
    while (true)
    {
        xSemaphoreTake(StartSema,portMAX_DELAY); //which in order to start waits this Semaphore to be Given
        while(true){

            //do some logic to controll a motor and keep it steady

            /////to stop this while on some stop button if i use the next i think it will 
            //stop and waits on the first run of the loop so there is no control
            xSemaphoreTake(StopSema,portMAX_DELAY);
            break;
            // if i wrap it in an if condition i think it is the same isn't it?

        }
    }
}

Solution

  • You can try to take the semaphore without a delay and if successful, break out of the loop:

    void startTaskFunction(void *params)
    {
        while (true) {
            xSemaphoreTake(StartSema, portMAX_DELAY);
            while (true) {
                //do some logic to controll a motor and keep it steady
    
                if (xSemaphoreTake(StopSema, 0) == pdTRUE) {
                    break;
                }
            }
        }
    }