How to push an item to the start of a queue in ESP32

A queue is an important data structure if you are using FreeRTOS in your ESP32 firmware. While a queue is typically populated from the back, i.e., the latest entry is added at the end of the queue. However, there may be scenarios where the latest entry should be processed first, even if there are other entries in the queue. For dealing with such scenarios, FreeRTOS has an xQueueSendToFront() function. The arguments are similar to xQueueSendToBack() or the xQueueSend() function.

The syntax is as follows:

BaseType_t xQueueSendToFront( QueueHandle_t xQueue,
                               const void * pvItemToQueue,
                               TickType_t xTicksToWait );

As you can see, the function takes in three arguments:

  1. xQueue: The handler of the Queue you are trying to populate
  2. pvItemToQueue: The item you are trying to add to the queue
  3. xTicksToWait: The number of ticks to block waiting for the queue to make space for the new item, if it is already full. Setting it to 0 means that the function will return immediately, and not add the item to the queue.

The implementation of this function in a short example code is given below:

#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"

QueueHandle_t xQueueMyQueue;
uint8_t my_queue_created = 0;

void queueInit(){

    if(my_queue_created == 0){
        xQueueMyQueue = xQueueCreate( 100, sizeof( char * ));
        my_queue_created = 1;
    }

}

void updateMyQueue(char* value){
    ESP_LOGI(TAG, "before sending to queue");
    if( xQueueMyQueue != 0 )
    {
        /* Send a pointer to a MyQueue.  Don't block if the
        queue is already full. */

        xQueueSendToFront( xQueueMyQueue, (void *)value, ( TickType_t ) 0 );

    }
}

void app_main(){
  queueInit();

  //Define tasks
}


//Elsewhere in the program
void myTask(void){
  char *source;

  //Some code that updates source

  updateMyQueue(source);
 
  //Rest of the code
}

That’s it. I hope the above example helped you.


For more tutorials on ESP32, check out https://iotespresso.com/category/esp32/. Also, you may find this course on ESP32 on Udemy to be quite helpful. Do check it out

Leave a comment

Your email address will not be published. Required fields are marked *