Queues

Queues are a way for tasks in FreeRTOS to safely pass information between one another. Queues ensures that data passed between tasks is not unexpectedly overwritten, corrupted or lost in the process of running multiple tasks. Additional details can be found in FreeRTOS Queue

Queue Characteristics

  • When a user puts data on a Queue in FreeRTOS, it’s passed by copy, not by reference or location.
  • If a user wants to pass by reference or memory location, they can simply put a pointer on the Queue.
  • Queues can store data of multiple types (even in the same Queue!)

Initializing a Queue

Listing 26. Initialize a FreeRTOS task
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <FreeRTOS.h>
#include <stdarg.h>

QueueHandle_t myQueue = NULL;

volatile uint8_t data_received;
volatile uint8_t my_data;

/* Task function */
void receivedFromQueueTaskFunction(void* a0){
  /* Local variables. Variables here go onto task stack!! */
  uint8_t data_from_queue = 0;

  while (1){ /* Run loop forever (unless terminated) */
    if( myQueue != NULL ){
      /*Give 5 ticks to read the value in the queue.*/
      if( xQueueReceive( myQueue, &( data_from_queue ), ( TickType_t ) 5 ) == pdPASS ){
          /*data_from_queue is ready for processing*/
      }
    }
  }
}

/* Task function */
void addToQueueTaskFunction(void* a0){
  while (1) /* Run loop forever (unless terminated) */
  {
    if(data_received == 1){
      if( myQueue != NULL){
        if( xQueueSend( myQueue, ( void * ) &my_data, ( TickType_t ) 5 ) != pdPASS ){
              /* Unable to post the message after 5 ticks. */
        }
        else{
          /*Successfully posted the message*/
        }
      }
    }
  }
}

int main() {
    /*Create a queue that's 5 bytes long*/
    myQueue = xQueueCreate( 5, sizeof( uint8_t ) );
}

This code uses a queue to pass 8-bit integers from the addToQueueTaskFunction to the receivedFromQueueTaskFunction. Note the error handling ensures that if FreeRTOS isn’t able to add items to the queue in 5 ticks, it times out.