Exchange data between a Task and an ISR via Queue

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

Code Link: Tutorial Source Code Github – Keil

In the previous tutorial we demonstrated how to establish inter-task communication via queue. The link to the tutorial is given bellow.

This tutorial is not much different from the previous one except in this tutorial we will demostrate how to create link between a Hardware interrupt ISR and a freeRTOS Task.

When inter Task-ISR comm is needed:

Most of the embedded systems uses interrupts to handle various on chip and off-chip events. As an example, interrupt generated by a serial buffer indicating data is ready to be received and processed. The data processing may be time consuming and if done inside ISR, it MAY starve normal application flow.

In embedded systems it is highly recommended to keep the ISR as short as possible to avoid blocking/starving of normal application flow especially in time critical systems. The problem becomes more sever if interrupts are arriving at high rate like in case of Serial communication at 115200kbps. The case bacomes even more severe if Interrupt Nesting and Interrupt Re-entrant are allowed.

In order to tackle this problem, queues and binary semaphores (discussed in separate tutorial) best fit. A Task/process responsible for data processing is sent to block state via an empty queue and when interrupt occurs, the Task is unblocked by simply sending a signal via queue and exiting ISR immediately. This achieve two thing, i.e. the ISR remains short and extensive processing is done outside ISR.

Tutorial Scenario:

In this tutorial a freeRTOS task is created that waits for the data to be available on queue. The task remains in block state until an external event (button press in this case) fills the queue. Once the ISR places data on queue, the task is automatically unblocked by freeRTOS kernel. The Task runs and print a message to the debugger serial console.

Button-Press –> ISR –> Queue –> Task

–> Inter Task-Interrupt Communication

Following are the tutorial steps.

Steps:

1. First of all let’s define what messages will be passed to queue. For the purpose of simplicity we will define a global string literal.

/*
  string literals
*/
const char *t1_Msg = "Message received From Button ISR...";

2. Next we will create freeRTOS Queue of length `2` and accepting item size of Pointer to char (char *).

/*
     freeRTOS Queue
*/
qHandle = xQueueCreate(2, sizeof(char *));

qHandle is globally defined variable of type QueueHandle_t.

/*
	freeRTOS Queue Handler
*/
QueueHandle_t qHandle;

3. If queue is created successfully (memory is allocated), a freeRTOS Tasks i.e. “RxTask” is created and Scheduler is started. Otherwise a failed message is sent to serial window and processor is trapped via while(1).

Note: If you don’t know how to create freeRTOS Tasks, refer to the following Tutorial.

if (qHandle != NULL) {
    
  xTaskCreate (vRxTask, "RxTask", 200, NULL, 2, NULL);    
  vTaskStartScheduler();
    
}else {
    
  printf ("Failed to create Queue! :-(\n");
  while (1);
    
}

4. “Inside “RxTask” Task Function”: The following is the definition of “RxTask” Task Function.

void vRxTask(void * pvParams) {

  volatile unsigned int i = 0;
  char * msgPtr;
  
  int rxStatus = 0;
  
  for (;;) {
    
    rxStatus = xQueueReceive(qHandle, &msgPtr, 500);

    if (0 == rxStatus) {
      printf ("Awaiting Message...\n");
    }else {
      printf ("Rx Msg: %s\n", msgPtr);    
    }
  }
}

What happens is:

rxStatus = xQueueReceive(qHandle, &msgPtr, 500); /* 500 is enough to compensate dummy delay in transmitter tasks.*/

xQueueReceive is called to check if data in qHandle Queue is available. If data is available (pointer to string in this case), the data (pointer) is copied into msgPtr pointer variable otherwise the Receiver Task “vRxTask” is sent to Block State waiting for the data to be available in next 500 Ticks. If data is not sent to queue within next 500 Ticks, the message “Awaiting Message…” is displayed and the Receiver Task (vRxTask) goes back to Block State. As soon as the data (pointer to string) becomes available on qHandle Queue, the Receiver task (Rx1) receives the pointer and displays string pointed by the received pointer and wait for the next message (pointer) reception.

5. The next step is to configure User button GPIO on STM32F4-Discovery as input and its interrupt configuration on button press. We already have a dedicated tutorial for STM32F4 interrupts and demo tutorial. Therefor the code will not be repeated here. The link to the tutorial is given bellow. Kindly go through the link bellow and relate it to the source code link given at the start of this tutorial.

6. The next step is to define an ISR for button interrupt. On STM32F4-Discovery User button is connected to PA.0 which produces interrupt on EXTI0 and subsequently calls ISR defined by void EXTI0_IRQHandler (void) functions definition.

Note: See the STM32F4 Interrupt tutorial for more detail. Link given above.

void EXTI0_IRQHandler (void) {

    int txStatus = 0;
    BaseType_t xHigherPriorityTaskWoken;
    /*
        Clear the pending interrupt
    */
    __setbit (EXTI->PR, 0);

      printf("Button Pressed, Sending message to Queue!\n");
  
    txStatus = xQueueSendToBackFromISR(qHandle, &t1_Msg, &xHigherPriorityTaskWoken);

    if (0 == txStatus) {
      
      printf("Sending failed Task-1!\n");
    
    } else {

      portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
	  
    }
}

What happens is:

The __setbit (EXTI->PR, 0); clears the interrupt so that next interrupt/button press can be detected.

printf("Button Pressed, Sending message to Queue!\n"); prints to the user that the button interrupt received and now ISR is about to write to Queue.

txStatus = xQueueSendToBackFromISR(qHandle, &t1_Msg, &xHigherPriorityTaskWoken); statement (API explained in the introductory tutorial) fills the queue with the pointer of string created in step-1 and send it. If queue operation is successful and it caused a higher priority Task to unblock i.e. A low priority Task was running and a Task with higher priority was waiting (blocked) for the qHandle data to be available and mean while the interrupt occurs than the xHigherPriorityTaskWoken flag will be set to indicate to the user to Yield from ISR immediately.

If queue operation is successful, an immediate return from ISR is required DIRECTLY to the high priority Task being unblocked by queue. In freeRTOS in order to switch directly to the that higher priority task being unblocked, portEND_SWITCHING_ISR and portYIELD_FROM_ISR are used and depends upon the freeRTOS Port used. In case of STM32F4 (ARM Cortex-M) the first one is used. portEND_SWITCHING_ISR will cause the kernel to directly jump to the high priority task instead of returning from ISR to the low priority task and then waiting for the context switch upon which the high priority will be selected. This minimize the delay between unblocking a Task from an ISR and subsequently achieving perfect synchronization.

Now as soon as the button is pressed, EXTI0_IRQHandler will be called. The EXTI0_IRQHandler will fill the queue with string pointer and return immediately. Once the data is available in queue, the “vRxTask” will be unblocked to receive the string pointer from queue and print the string pointer by the sent pointer thus achieving inter Task-ISR Communication.

7. Finally Compile source code, connect STM32F4-Discovery board to PC and enter debug mode. Open printf serial window via View -> Serial Windows -> Debug (printf) Viewer. Run the Program, Press the Blue User button, You will see printf messages as shown in bellow Video.

Note: We have routed printf messages to ST-Link debugger via ARM-ITM. There is a dedicated tutorial on how to redirect printf messages to debugger. Link to the tutorial is given bellow.

For complete source code refer to Github link given at the start of this tutorial.

Click the full screen button for more clear view.

References:

[1] – FreeRTOS Official Website



107 thoughts on “Exchange data between a Task and an ISR via Queue”

  • Hey There. I found your weblog the use of msn. That is an extremely well written article.
    I will be sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I’ll definitely return. 0mniartist asmr

  • Heya i’m for the first time here. I came across
    this board and I find It really useful & it helped me out much.
    I hope to give something back and help others like you helped me.
    0mniartist asmr

  • I really like what you guys are usually up too. This kind of clever
    work and coverage! Keep up the excellent works guys I’ve added you guys to my own blogroll.

  • With havin so much content and articles do you
    ever run into any problems of plagorism or copyright infringement?
    My website has a lot of completely unique content I’ve either written myself or outsourced but
    it looks like a lot of it is popping it up all over the internet without my
    authorization. Do you know any methods to help protect against content from being ripped off?
    I’d certainly appreciate it.

  • I enjoy what you guys are usually up too. This type of clever work and exposure!
    Keep up the excellent works guys I’ve added you guys to my blogroll.

  • Hola! I’ve been following your blog for a while now and finally
    got the courage to go ahead and give you a shout out from Atascocita Texas!

    Just wanted to tell you keep up the excellent job!

  • Wonderful beat ! I wish to apprentice while you amend your
    website, how could i subscribe for a blog website? The account aided me a
    acceptable deal. I had been a little bit acquainted of this your
    broadcast offered bright clear concept

  • Wonderful beat ! I wish to apprentice while you amend your site,
    how can i subscribe for a weblog website? The account
    helped me a appropriate deal. I have been a little bit acquainted of this your broadcast provided shiny transparent idea

  • I think everything published made a bunch of sense.
    However, what about this? what if you were to write a killer post
    title? I ain’t saying your information isn’t good, but what if you added a post
    title to maybe grab a person’s attention? I mean Exchange
    data between a Task and an ISR via Queue – EcoderLenz is kinda boring.
    You should look at Yahoo’s front page and watch how they write
    article titles to grab people to open the links.
    You might add a related video or a related pic or two to get people excited about everything’ve written. Just my opinion, it could bring your posts a little
    livelier.

  • scoliosis
    Great article! This is the type of info that are meant to be shared across the
    internet. Disgrace on Google for not positioning this put up upper!

    Come on over and discuss with my web site .
    Thanks =) scoliosis

  • The other day, while I was at work, my sister stole my
    iPad and tested to see if it can survive a
    thirty foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has
    83 views. I know this is entirely off topic but I had to share it with someone!

  • Heya are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and set up my
    own. Do you need any html coding expertise to make your own blog?
    Any help would be really appreciated!

  • After exploring a handful of the blog posts on your blog, I honestly like your technique of writing a blog.
    I added it to my bookmark website list and will be checking back soon. Please check out my web site too and let me know
    your opinion.

  • Hey there I am so thrilled I found your webpage, I really
    found you by error, while I was browsing on Yahoo for something else, Regardless I am here
    now and would just like to say many thanks for a marvelous post and a all round entertaining blog (I also love the theme/design), I don’t have time to look over it all at
    the minute but I have book-marked it and also added in your RSS feeds, so when I have
    time I will be back to read a great deal more, Please do keep
    up the superb job.

  • Good day I am so thrilled I found your webpage, I really
    found you by error, while I was browsing on Yahoo for something else, Nonetheless I am here now and would just like to say thanks for
    a tremendous post and a all round entertaining blog (I also love
    the theme/design), I don’t have time to read through it all at the moment but I have bookmarked it and also added your RSS feeds, so when I have time I
    will be back to read much more, Please do keep up the great work.

  • Hey there would you mind letting me know which
    web host you’re utilizing? I’ve loaded your blog in 3 different web browsers and I
    must say this blog loads a lot faster then most.
    Can you recommend a good hosting provider at a fair price?

    Thanks, I appreciate it!

  • What’s up everyone, it’s my first pay a quick visit at this website, and post is really fruitful in favor of
    me, keep up posting these types of articles or reviews.

  • Hey There. I found your blog using msn. This
    is a very well written article. I will be sure to bookmark it and come back to read
    more of your useful information. Thanks for the post.
    I will certainly return.

  • Hello there! I know this is somewhat off topic but I was
    wondering if you knew where I could find a captcha plugin for my comment form?

    I’m using the same blog platform as yours and I’m having difficulty finding one?
    Thanks a lot!

  • I don’t even know how I finished up here, however I
    thought this post was good. I don’t realize who
    you might be however definitely you’re going to a well-known blogger in case you are not already.

    Cheers!

  • excellent put up, very informative. I wonder why the other experts of this sector don’t understand this.

    You must proceed your writing. I’m confident, you’ve a huge readers’ base already!

  • I think everything published made a ton of sense. However,
    what about this? what if you added a little information?
    I am not suggesting your content isn’t good., however
    what if you added something that grabbed people’s attention?
    I mean Exchange data between a Task and an ISR
    via Queue – EcoderLenz is a little boring. You should glance at Yahoo’s front page and note how they create article titles
    to get viewers interested. You might add a related video or a related pic or two
    to grab readers interested about what you’ve got to say.
    In my opinion, it might bring your posts a little
    livelier.

  • I do believe all the concepts you have presented on your post.
    They are really convincing and can certainly work. Still, the posts are very short for starters.
    May you please lengthen them a bit from next time? Thanks for
    the post.

  • Have you ever considered publishing an ebook or guest authoring on other blogs?
    I have a blog based on the same information you discuss and would
    really like to have you share some stories/information. I know my visitors would enjoy your work.

    If you are even remotely interested, feel free to send
    me an email.

  • I simply wanted to thank you a lot more for that amazing web site you have built here. It really is full of ideas for those who are genuinely interested in this specific subject, particularly this very post. You’re really all so sweet along with thoughtful of others as well as reading your website posts is a great delight in my opinion. And exactly what a generous present! Mary and I will have fun making use of your suggestions in what we must do next week. Our record is a kilometer long and simply put tips will definitely be put to very good use. firmonet

  • I’ve been exploring for a little for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this site. Reading this info So i’m happy to convey that I have a very good uncanny feeling I discovered exactly what I needed. I most certainly will make certain to don’t forget this web site and give it a look on a constant basis.

  • Howdy! I understand this is somewhat off-topic but I had to
    ask. Does operating a well-established website such as yours require a
    lot of work? I am completely new to running a blog
    but I do write in my journal daily. I’d like to start a blog so I can easily share my own experience
    and thoughts online. Please let me know if you have any kind of suggestions or tips for new aspiring bloggers.
    Appreciate it! asmr https://app.gumroad.com/asmr2021/p/best-asmr-online asmr

  • I am really impressed with your writing talents as well as with the layout to your weblog. Is this a paid subject matter or did you customize it yourself? Either way keep up the nice high quality writing, it is rare to look a great weblog like this one these days..

  • I’ve been browsing online more than 3 hours today, yet I never found
    any interesting article like yours. It’s pretty worth enough for me.
    In my view, if all website owners and bloggers made good content as you did, the web
    will be much more useful than ever before. cheap flights
    http://1704milesapart.tumblr.com/ cheap flights

  • Hey! I know this is kinda off topic but I’d figured I’d ask. Would you be interested in trading links or maybe guest writing a blog post or vice-versa? My blog addresses a lot of the same subjects as yours and I believe we could greatly benefit from each other. If you happen to be interested feel free to shoot me an e-mail. I look forward to hearing from you! Terrific blog by the way!

  • An impressive share! I have just forwarded this onto a colleague
    who has been conducting a little homework on this.
    And he actually bought me dinner because I discovered it for him…

    lol. So allow me to reword this…. Thank YOU for
    the meal!! But yeah, thanx for spending the time to discuss this
    subject here on your website. scoliosis surgery https://coub.com/stories/962966-scoliosis-surgery scoliosis surgery

  • Thanks for the sensible critique. Me and my neighbor were just preparing to do a little research on this. We got a grab a book from our local library but I think I learned more from this post. I’m very glad to see such fantastic information being shared freely out there.

  • I would like to voice my appreciation for your generosity in support of folks that really need help with this situation. Your special commitment to getting the message up and down ended up being rather invaluable and have frequently helped some individuals like me to arrive at their ambitions. Your helpful tutorial means so much a person like me and further more to my mates. Thank you; from each one of us.

  • When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

  • Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I?d prefer to use some with the content on my blog whether you don?t mind. Natually I?ll give you a link on your web blog. Thanks for sharing.

  • Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

  • Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I?d prefer to use some with the content on my blog whether you don?t mind. Natually I?ll give you a link on your web blog. Thanks for sharing.

  • Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

  • I’m really impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you modify it yourself? Either way keep up the excellent quality writing, its rare to see a great blog like this one today..

  • Thanks , I’ve recently been searching for information approximately this topic for a while and yours is the greatest I’ve found out so far. However, what in regards to the bottom line? Are you certain about the source?

  • Hey there! I’m at work surfing around your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the fantastic work!

  • I write often and I seriously value your web content. This outstanding write-up has absolutely actually peaked my curiosity. I am going to book mark your internet site and keep checking for brand-new data regarding as soon as a week. I opted in for your RSS feed as well.

  • Hello, I think your blog might be having browser compatibility issues. When I look at your blog in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, amazing blog!

  • I think this is among the most significant info for me. And i’m glad reading your article. But want to remark on few general things, The site style is great, the articles is really excellent : D. Good job, cheers

  • Hi! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My weblog looks weird when browsing from my iphone 4. I’m trying to find a theme or plugin that might be able to fix this problem. If you have any suggestions, please share. Appreciate it!

  • Hi there this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!

  • Have you ever considered publishing an e-book or guest authoring on other sites? I have a blog based on the same subjects you discuss and would really like to have you share some stories/information. I know my subscribers would enjoy your work. If you’re even remotely interested, feel free to shoot me an e mail.

Leave a Reply

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