Introduction to FreeRTOS Queues

Keywords: Embedded systems, ARM, FreeRTOS, STM32F4, Tasks, Queues

“A Queue is a Data Structure that holds a finite number of fixed-size data items and follows FIFO (First in First Out) access mechanism”.

Most of the low power low end embedded systems follows legacy hardware architecture of shared memory where any part of volatile memory can be read/modified/written by any part of embedded software running on the hardware. This is not a big issue until the software gets complex and runs multiple units of independent software tasks accessing shared memory simultaneously e.g. System is performing multi-tasking under an RTOS.

In such systems one of the major problem is memory protection and inter-tasks communication. Though some part of shared memory can be reserved (via some global variables/arrays) that can be written by one task and read by another task when required; The problem in such systems arises when it comes the memory operation Atomicity.

It is quite probable that one task is in the process of writing data to the shared memory and has partially completed the write operation (like writing to a large array) when a context switch occures and another task reads it assuming its the correct data. A more worse situation occurs when multiple tasks are trying to write data to the same shared memory simultaneously.

As an example, the following video shows two freeRTOS tasks trying to write string to same serial Port. As can be seen while the one task has not yet finished writing to serial port, the context switch preempt the first task and runs the second task resulting into mixing of two strings. The exact same things may happen in case of shared memory.

* Task1 Prints: “Message From Task-1: FreeRTOS Task-1 Running...
* Task2 Prints: “Message From Task-2: FreeRTOS Task-2 Running...

In order to tackle such problem, queues are used that ensures the data can’t be written to queue if its full (prevent replacing data) and can’t be read if its empty (prevents reading garbage values).

Queues are used to provide communication channels between various independent pieces of code like task-to-task, task-to-ISR and ISRs-to-task communication.

Generally in Queue, data is written to the back; called tail of the queue and removed from the front; called head of the queue – Figure-1 [1].

Figure-1: FreeRTOS Queue

1. FreeRTOS Queues:

FreeRTOS implements an enhanced version of generic Queue (FIFO). A queue can only be written to back (tail) and be read in revered order (from front to tail) i.e. FIFO (First in First out). This means if a message is written last, it will be read last as well. Thus Queue messaging mechanism has no message priority associated with them. FreeRTOS provides a partially way around it by providing APIs that can write both to the front and back of Queue. Thus the message written to the front will be read first (sort of high priority). This makes freeRTOS Queues follow both FIFO and LIFO mechanism. In this way FreeRTOS queues get somehow closer to POSIX messaging mechanism. More details are covered in the APIs discussion.

2. FreeRTOS Queues APIs:

This following APIs are used for freeRTOS Queue main Operations.

2.1 xQueueCreate():

Before a queue can be used, it must be created explicitly with predefined length and item size it will hold. Queues are referenced by handles, which are variables of type QueueHandle_t. The xQueueCreate() API function creates a queue and returns a QueueHandle_t as a references to the queue just created.

Parameter NameDescription
uxQueueLengthThe maximum number of items that the queue being created can hold at any one time.
uxItemSizeThe size, in bytes, of each data item that can be stored in the queue.
Return ValueIf NULL is returned, then the queue cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the queue data structures and storage area.

If a non-NULL value is returned, the queue has been created successfully. The returned value should be stored as the handle to the created queue.

2.2 xQueueSendToBack() and xQueueSendToFront():

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

xQueueSendToBack() is used to send data to the back (tail) of a queue. xQueueSendToFront() is used to send data to the front (head) of a queue.

Parameter NameDescription
xQueueThe handle of the queue to which the data is being sent (written). The queue handle will have been returned from the call to xQueueCreate() used to create the queue.
pvItemToQueueA pointer to the data to be copied into the queue.

The size of each item that the queue can hold is set when the queue is created, so this many bytes will be copied from pvItemToQueue into the queue storage area.
xTicksToWaitThe maximum amount of time the task should remain in the Blocked state to wait for space to become available on the queue, should the queue already be full.

Both xQueueSendToFront() and xQueueSendToBack() will return immediately if xTicksToWait is zero and the queue is already full.

The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks.

Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h.
Return ValueThere are two possible return values:

1. pdPASS

Returned only if data was successfully sent to the queue.

If a block time was specified (xTicksToWait was not zero), then it is possible the calling task was placed into the Blocked state, to wait for space to become available in the queue, before the function returned, but data was successfully written to the queue before the block time expired.

2. errQUEUE_FULL

Returned if data could not be written to the queue because the queue was already full.

If a block time was specified (xTicksToWait was not zero) then the calling task will have been placed into the Blocked state to wait for another task or interrupt to make space in the queue, but the specified block time expired before that happened.

Note: Do not call xQueueSendToFront() or xQueueSendToBack() from an interrupt service routine. Use the interrupt-safe versions, xQueueSendToFrontFromISR() and xQueueSendToBackFromISR(), instead.

2.3 xQueueReceive():

BaseType_t xQueueReceive( QueueHandle_t xQueue,
void * const pvBuffer,
TickType_t xTicksToWait );

xQueueReceive() is used to receive (read) a message from a queue. The message that is received is removed from the queue.

Parameter Name/ Returned valueDescription
xQueueThe handle of the queue to which the data is being sent (written). The queue handle will have been returned from the call to xQueueCreate() used to create the queue.
pvBufferA pointer to the memory into which the received data will be copied.

The size of each data item that the queue holds is set when the queue is created. The memory pointed to by pvBuffer must be at least large enough to hold that many bytes.
xTicksToWaitThe maximum amount of time the task should remain in the Blocked state to wait for data to become available on the queue, should the queue already be empty.

If xTicksToWait is zero, then xQueueReceive() will return immediately if the queue is already empty.

The block time is specified in tick periods, so the absolute time it represents depends on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into ticks.

Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h.
Return ValueThere are two possible return values:

1. pdPASS

Returned only if data was successfully read from the queue.

If a block time was specified (xTicksToWait was not zero), then it is possible the calling task was placed into the Blocked state, to wait for data to become available on the queue, but data was successfully read from the queue before the block time expired.

2. errQUEUE_EMPTY

Returned if data cannot be read from the queue because the queue is already empty. If a block time was specified (xTicksToWait was not zero,) then the calling task will have been placed into the Blocked state to wait for another task or interrupt to send data to the queue, but the block time expired before that happened.

Note: Do not call xQueueReceive() from an interrupt service routine. Use the interrupt-safe xQueueReceiveFromISR() API function instead.

2.4 uxQueueMessagesWaiting():

UBaseType_t uxQueueMessagesWaiting( QueueHandle_t xQueue );

uxQueueMessagesWaiting() is used to query the number of items that are currently in a queue.

Parameter NameDescription
xQueueThe handle of the queue being queried. The queue handle will have been returned from the call to xQueueCreate() used to create the queue.
Return ValueThe number of items that the queue being queried is currently holding. If zero is returned, then the queue is empty.

Note: Do not call uxQueueMessagesWaiting() from an interrupt service routine. Use the interrupt-safe uxQueueMessagesWaitingFromISR() instead.

References:

[1] – FreeRTOS Official Website



64 thoughts on “Introduction to FreeRTOS Queues”

  • Undeniably imagine that that you said. Your favourite reason seemed to be
    on the web the simplest factor to take into account of.
    I say to you, I definitely get annoyed even as folks think about issues that they plainly don’t recognize about.
    You controlled to hit the nail upon the top as neatly as outlined out the whole thing without having side effect , other people can take a signal.
    Will likely be back to get more. Thank you asmr
    0mniartist

  • Hi there I am so thrilled I found your weblog, I really found
    you by mistake, while I was browsing on Aol for something else, Nonetheless
    I am here now and would just like to say many thanks for a fantastic post and a all round entertaining blog (I also
    love the theme/design), I don’t have time to go through
    it all at the moment but I have saved it and also included your RSS feeds, so when I have time I will be
    back to read more, Please do keep up the superb work. 0mniartist asmr

  • I’m really loving the theme/design of your weblog. Do you
    ever run into any web browser compatibility issues? A small number
    of my blog visitors have complained about my blog not working
    correctly in Explorer but looks great in Safari. Do you
    have any advice to help fix this problem? asmr 0mniartist

  • Link exchange is nothing else except it is simply
    placing the other person’s web site link on your page
    at suitable place and other person will also do same in favor of you.
    0mniartist asmr

  • Hey There. I discovered your blog using msn. This is an extremely smartly written article.
    I’ll make sure to bookmark it and come back to learn more
    of your useful information. Thank you for the post.
    I will definitely comeback.

  • An outstanding share! I’ve just forwarded this onto
    a coworker who has been conducting a little
    research on this. And he actually ordered me lunch
    simply because I found it for him… lol. So allow me to reword this….
    Thank YOU for the meal!! But yeah, thanks for spending time to discuss this subject here on your web site.

  • What’s up i am kavin, its my first occasion to commenting anyplace, when i read
    this post i thought i could also make comment due to this sensible paragraph.

  • Hi there superb blog! Does running a blog similar to this take a massive amount work?
    I’ve virtually no expertise in coding but I was hoping to start
    my own blog in the near future. Anyway, if you have any ideas or tips for new blog owners please share.
    I know this is off topic however I simply needed
    to ask. Many thanks!

  • Do you have a spam problem on this website; I also am a blogger, and I was curious about your situation; we have created some nice procedures and
    we are looking to swap strategies with others, be sure
    to shoot me an e-mail if interested.

  • Have you ever thought about including a little bit more than just your articles?
    I mean, what you say is valuable and all. But think about if you added some great visuals or video
    clips to give your posts more, “pop”! Your content is
    excellent but with pics and video clips, this site could certainly
    be one of the greatest in its niche. Very good blog!

  • scoliosis
    Heya superb blog! Does running a blog like this require a great deal
    of work? I’ve absolutely no understanding of computer programming but I
    was hoping to start my own blog soon. Anyway, should you have any ideas or tips for new blog owners please share.
    I know this is off subject nevertheless I simply needed to ask.

    Cheers! scoliosis

  • scoliosis
    If some one desires to be updated with most up-to-date technologies then he must be go
    to see this site and be up to date every day. scoliosis

  • dating sites
    My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs. But he’s tryiong
    none the less. I’ve been using Movable-type on several websites for
    about a year and am anxious about switching to another platform.
    I have heard great things about blogengine.net. Is there a way I can import all my wordpress posts into it?
    Any kind of help would be greatly appreciated! free dating
    sites

  • I’ll right away snatch your rss feed as I can’t in finding your e-mail subscription link or newsletter service.
    Do you’ve any? Kindly allow me know in order that I may subscribe.
    Thanks.

  • Hey! This is my 1st comment here so I just wanted to give a quick shout out and tell you I really enjoy reading
    your posts. Can you suggest any other blogs/websites/forums that deal with the same
    topics? Thanks a lot!

  • It is the best time to make some plans for the long run and it’s time to be happy.
    I have read this post and if I could I want to counsel
    you few interesting things or suggestions. Maybe you can write subsequent articles referring to this
    article. I wish to read even more issues approximately it!

  • Howdy, i read your blog from time to time and i own a similar one and i was
    just wondering if you get a lot of spam responses? If so how do you reduce it, any plugin or anything you can advise?
    I get so much lately it’s driving me mad so any help is very
    much appreciated.

  • I have to thank you for the efforts you’ve put in penning this site.
    I am hoping to check out the same high-grade blog posts from you in the future as
    well. In truth, your creative writing abilities has encouraged me to get my
    very own website now 😉

  • This is the right blog for anyone who wishes to find out about this
    topic. You know so much its almost tough to argue with you (not that I personally will need to…HaHa).
    You certainly put a brand new spin on a topic that’s been discussed for a
    long time. Great stuff, just wonderful!

  • This is the perfect blog for anybody who really wants to find out about this topic.
    You realize so much its almost tough to argue with you
    (not that I actually will need to…HaHa). You definitely put a
    fresh spin on a subject which has been written about for years.
    Great stuff, just great!

  • Heya! I just wanted to ask if you ever have any issues with hackers?

    My last blog (wordpress) was hacked and I ended up losing several weeks of hard work
    due to no backup. Do you have any methods to stop hackers?

  • Hello there, I discovered your website by way of Google even as searching for a similar
    matter, your web site got here up, it appears good. I have bookmarked it in my google bookmarks.

    Hi there, just was alert to your blog thru Google, and
    found that it’s really informative. I’m going to watch out for brussels.

    I’ll be grateful in case you proceed this in future.
    Many folks will be benefited out of your writing. Cheers!

  • Good day I am so thrilled I found your webpage, I really found you by mistake, while I was looking on Digg for something
    else, Regardless I am here now and would just like to say many thanks for a
    incredible post and a all round interesting blog (I also love
    the theme/design), I don’t have time to browse it
    all at the minute but I have bookmarked it and also added in your
    RSS feeds, so when I have time I will be back to
    read more, Please do keep up the excellent jo.

  • Right here is the perfect website for anyone who wants to find out about this topic.
    You know so much its almost hard to argue with you (not that I really will
    need to…HaHa). You definitely put a new spin on a topic that’s been written about for many years.
    Great stuff, just excellent!

  • Hello there! I know this is kinda off topic nevertheless I’d figured I’d
    ask. Would you be interested in exchanging links or maybe guest authoring a blog post or
    vice-versa? My blog addresses a lot of the same topics
    as yours and I feel we could greatly benefit from each other.
    If you might be interested feel free to send me an email.
    I look forward to hearing from you! Wonderful blog by the way!

  • Somebody essentially help to make significantly articles I might state.

    This is the first time I frequented your website page and thus far?
    I amazed with the research you made to make this particular post incredible.
    Fantastic job!

  • I’ll right away seize your rss feed as I can not to find your email subscription hyperlink or e-newsletter service.

    Do you’ve any? Please permit me recognise so that
    I could subscribe. Thanks.

  • I’ve been exploring for a bit for any high-quality articles
    or weblog posts in this sort of space . Exploring in Yahoo I finally stumbled upon this
    site. Reading this information So i’m glad to show that I have an incredibly just right uncanny feeling I
    discovered just what I needed. I such a lot surely will make sure to do not disregard this site and provides it a glance on a
    continuing basis.

  • Awesome blog you have here but I was curious if you knew
    of any forums that cover the same topics discussed here?

    I’d really like to be a part of online community where I can get suggestions from other knowledgeable individuals that share the same
    interest. If you have any recommendations, please let me know.
    Appreciate it!

  • I believe what you said made a bunch of sense.
    However, think on this, suppose you added a little content?
    I am not saying your content isn’t good., but suppose you added something that makes people
    desire more? I mean Introduction to FreeRTOS Queues –
    EcoderLenz is a little vanilla. You could glance at Yahoo’s home page and note how they
    create news headlines to grab people to click.
    You might add a video or a related pic or two to grab people excited about
    what you’ve got to say. In my opinion, it would bring your website a little livelier.
    cheap flights http://1704milesapart.tumblr.com/ cheap flights

Leave a Reply

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