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¶
1#include <FreeRTOS.h>
2#include <stdarg.h>
3
4QueueHandle_t myQueue = NULL;
5
6volatile uint8_t data_received;
7volatile uint8_t my_data;
8
9/* Task function */
10void receivedFromQueueTaskFunction(void* a0){
11 /* Local variables. Variables here go onto task stack!! */
12 uint8_t data_from_queue = 0;
13
14 while (1){ /* Run loop forever (unless terminated) */
15 if( myQueue != NULL ){
16 /*Give 5 ticks to read the value in the queue.*/
17 if( xQueueReceive( myQueue, &( data_from_queue ), ( TickType_t ) 5 ) == pdPASS ){
18 /*data_from_queue is ready for processing*/
19 }
20 }
21 }
22}
23
24/* Task function */
25void addToQueueTaskFunction(void* a0){
26 while (1) /* Run loop forever (unless terminated) */
27 {
28 if(data_received == 1){
29 if( myQueue != NULL){
30 if( xQueueSend( myQueue, ( void * ) &my_data, ( TickType_t ) 5 ) != pdPASS ){
31 /* Unable to post the message after 5 ticks. */
32 }
33 else{
34 /*Successfully posted the message*/
35 }
36 }
37 }
38 }
39}
40
41int main() {
42 /*Create a queue that's 5 bytes long*/
43 myQueue = xQueueCreate( 5, sizeof( uint8_t ) );
44}
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.