FreeRTOS Simple Tasks

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

Code Link: Tutorial Source Code Github – Keil

In this tutorial we will demonstrate how to create a FreeRTOS Task. Tasks are main building blocks of any Application that wants to use a real-time OS. A task is a piece of code that can be scheduled by OS scheduler and dedicated for specific functionality. In FreeRTOS tasks are the key component of OS Kernel that requires the following prerequisites to meet before a task is recognized by FreeRTOS Kernel and put forward to scheduler.

1. Task Function: Task function define what task is all about i.e implementation of Task functionality e.g. blinking LED, reading sensors data etc. The function implementation must follow void functionName (void *); function declaration and must never return. functionName can be any valid C-function name. Following is a sample Task function code definition.

/*
  Sample Task funciton
*/
void myTaskFtn (void * pvParam) {
	
    for (;;) {
		
        /* Task implementation */
        ...
    }
}

2. Task Name: Any Valid ACSII string of maximum length configMAX_TASK_NAME_LEN (including the NULL terminator) or simply NULL. configMAX_TASK_NAME_LEN is defined in FreeRTOSConfig.h header file. This is a descriptive name for the task. This is not used by FreeRTOS in any way. It is included purely as a debugging aid.

3. Stack Size: In freeRTOS, every task has its own stack that stores TCB (Task Control Block) and other stack related operations while the task is being executed. It also stores processor context before a context switch (switching to other task). Stack size must be sufficient to accommodate all local variables + processor context (registers etc.).

4. Task Priority: Tasks in freeRTOS are executed based on Priority. Task Priority can be any number between 0 and configMAX_PRIORITIES – 1. Higher the priority number, higher will be the task priority. Scheduler always choose highest priority task available in ready state. Once higher priority tasks let go of processor then other tasks are given chance to execute.

5. Task Handler: A task handler is a pointer of type xTaskHandle and is used to refer to Task outside Task Function. This handle is used to perform various operations on tasks like Task deletionChanging Priority etc. from outside the Task Function body. If your application doesn’t refer to a task from outside Task Function body, then the Task Handler can be set to NULL.

FreeRTOS Tasks API:

The following API is used to create a FreeRTOS Task.

portBASE_TYPE xTaskCreate(
                           pdTASK_CODE pvTaskCode,
                           const portCHAR * const pcName,
                           unsigned portSHORT usStackDepth,
                           void *pvParameters,
                           unsigned portBASE_TYPE uxPriority,
                           xTaskHandle *pvCreatedTask
                           );

Table-1 summarizes xTaskCreate(...) function parameters and return value.

Table-1: xTaskCreate() Parameters/Return Value

Don’t worry if you haven’t pick anything from the above table. We will explain it here via simple Task Example.

Tutorial Scenario:

In this tutorial we will create two FreeRTOS Tasks i.e. T1 and T2. Both tasks will be given equal priorities i.e. 1. Upon execution, each task prints its own execution message.
T1 Prints: Task-1 Running.
T2 Prints: Task-2 Running.

Note: As both Tasks are of equal priorities; so both will be given equal execution time as shown in Figure-1.

Figure-1: Task switching between Task-1 and Task-2

Note: Apart from above tasks an IDLE task is created in the background for various duties like Garbage collection i.e. reclaiming memory of deleted tasks etc. This task is crated by freeRTOS Kernel with fixed priority of 0 and runs only when there is no other task running.

Let’s get back to programming. Following are the steps.

Steps:

1. The first step is to create task functions – See Table-1. Task function must never return and must follow void functionName (void *) function declaration In our case, task function just prints its execution message forever after some dummy delay.

/*
    Task Function for Task-1
*/
void vTask1(void * pvParams) {

  volatile unsigned int i = 0;

  for (;;) {
    printf("Task-1 Running.\n");
    
    /*Dummy Delay - Lazy work */
    for (i =0; i < 50000; ++i);
  }
}


/*
    Task Function for Task-2
*/
void vTask2(void * pvParams) {

  volatile unsigned int i = 0;
 
  for (;;) {
    printf("Task-2 Running.\n");  

    /*Dummy Delay - Lazy work */
    for (i =0; i < 50000; ++i);
  }
}

2. Next Step is to create two Tasks via xTaskCreate() APIs. We are not passing any parameters to task function neither we need any task handler so both are kept NULL – Refer to Table-2.

  xTaskCreate (vTask1, "T1", 150, NULL, 1, NULL);

  xTaskCreate (vTask2, "T2", 150, NULL, 1, NULL);
Table-2: Params description of Simple Task

3. The next step is to start FreeRTOS Scheduler so that the tasks we created be executed.

/*
    Start the Scheduler
*/
vTaskStartScheduler();

4. Finally Compile source code (github link given at the start of the tutorial), connect STM32F4-Discovery board to PC and enter debug mode. Open printf serial window via View -> Serial Windows -> Debug (printf) Viewer. Run the Program, You will see Task execution 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



66 thoughts on “FreeRTOS Simple Tasks”

  • Someone essentially help to make seriously articles I’d state.

    That is the first time I frequented your web
    page and to this point? I surprised with the analysis you
    made to create this actual post amazing. Fantastic
    job! 0mniartist asmr

  • I was curious if you ever considered changing
    the structure of your website? Its very well written;
    I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it
    better. Youve got an awful lot of text for only having 1 or two
    pictures. Maybe you could space it out better? asmr 0mniartist

  • Thanks a bunch for sharing this with all folks you really recognize what
    you are speaking approximately! Bookmarked. Kindly additionally
    discuss with my website =). We will have a hyperlink change arrangement between us
    asmr 0mniartist

  • I simply could not go away your website before suggesting that I actually loved the standard information a
    person provide for your visitors? Is going to be back steadily to check up
    on new posts asmr 0mniartist

  • I think that everything said made a ton of
    sense. But, what about this? what if you composed a catchier title?

    I am not saying your information isn’t good, however suppose you added a title that
    grabbed a person’s attention? I mean FreeRTOS Simple
    Tasks – EcoderLenz is a little vanilla. You might look at Yahoo’s front page and note
    how they create news titles to get viewers interested.
    You might try adding a video or a pic or two to grab
    people interested about what you’ve written. In my
    opinion, it could make your posts a little livelier.
    0mniartist asmr

  • After checking out a few of the blog posts on your blog, I really
    like your technique of blogging. I book marked it to my bookmark site list and
    will be checking back soon. Please visit my website too and tell me
    how you feel.

  • After exploring a number of the articles on your web site,
    I seriously appreciate your way of blogging. I saved
    it to my bookmark site list and will be checking back
    soon. Take a look at my website too and let me know your opinion.

  • Awesome blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple tweeks would really make my blog shine.
    Please let me know where you got your theme. Many thanks

  • excellent submit, very informative. I’m wondering why
    the opposite specialists of this sector do not realize this.

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

  • We are a bunch of volunteers and opening a new scheme in our community.
    Your site offered us with helpful information to work on. You have done a formidable process and our
    entire group can be thankful to you.

  • Good day! I could have sworn I’ve been to this blog before but after
    looking at some of the posts I realized it’s new to me.

    Regardless, I’m definitely pleased I stumbled upon it and I’ll be book-marking it and checking back often!

  • Hello would you mind letting me know which web host you’re using?
    I’ve loaded your blog in 3 completely different browsers and I must say this
    blog loads a lot quicker then most. Can you recommend
    a good web hosting provider at a fair price? Cheers, I appreciate it!

  • scoliosis
    Today, I went to the beach with my children. I
    found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear
    and screamed. There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is totally off topic but I had to tell someone!
    scoliosis

  • scoliosis
    Nice blog here! Also your site loads up very fast!
    What web host are you using? Can I get your affiliate link to your
    host? I wish my site loaded up as quickly as yours lol scoliosis

  • free dating sites
    I was curious if you ever thought of changing the structure of your website?
    Its very well written; I love what youve got to say.

    But maybe you could a little more in the way of content so people could
    connect with it better. Youve got an awful lot of text for only having one or two
    images. Maybe you could space it out better? https://785days.tumblr.com/ dating sites

  • dating sites
    Just wish to say your article is as amazing. The clarity in your post is just great
    and i could assume you are an expert on this subject.
    Fine with your permission allow me to grab your feed to
    keep up to date with forthcoming post. Thanks a million and please continue the enjoyable work.
    free dating sites

  • Hello there! This post couldn’t be written any better!
    Looking at this post reminds me of my previous roommate!
    He constantly kept talking about this. I am going to forward this article to him.
    Pretty sure he’s going to have a great read. Thanks for sharing!

  • Hey there, I think your site might be having browser compatibility
    issues. When I look at your website in Safari, 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,
    fantastic blog!

  • Hmm it seems like your website ate my first comment (it was super long)
    so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog.

    I too am an aspiring blog blogger but I’m still new to the whole
    thing. Do you have any helpful hints for newbie blog writers?

    I’d genuinely appreciate it.

  • Nice blog here! Also your website loads up fast! What host are you using?
    Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  • I am no longer positive where you are getting your info, but
    great topic. I needs to spend some time studying more or understanding more.
    Thank you for wonderful info I was on the lookout for this info for my mission.

  • Excellent beat ! I would like to apprentice at the same
    time as you amend your website, how could i subscribe
    for a blog website? The account helped me a
    acceptable deal. I had been tiny bit familiar of this your broadcast offered
    vivid clear concept

  • Hello, i think that i noticed you visited my blog thus i came to go back the desire?.I’m attempting to find things to improve my site!I assume its ok to
    use some of your ideas!!

  • I was wondering if you ever thought of changing the
    structure of your blog? Its very well written; I
    love what youve got to say. But maybe you could a little
    more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having one or two pictures.
    Maybe you could space it out better?

  • Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something.
    I think that you could do with some pics to drive the message home a little bit, but other than that, this is wonderful blog.

    An excellent read. I will certainly be back.

  • Hey there! This is my first visit to your blog!
    We are a group of volunteers and starting a new project in a community
    in the same niche. Your blog provided us useful information to work on. You have
    done a marvellous job!

  • 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 three e-mails with
    the same comment. Is there any way you can remove people from that service?
    Thanks!

  • I do not know whether it’s just me or if everybody else experiencing
    issues with your site. It looks like some of the text in your posts are running off
    the screen. Can somebody else please provide feedback and let me
    know if this is happening to them too? This might be a problem with my browser because I’ve had
    this happen previously. Kudos

  • I’m not sure where you’re getting your info, but good topic.

    I needs to spend some time learning much more
    or understanding more. Thanks for wonderful information I was looking for this info for my mission.

  • Attractive section of content. I just stumbled upon your blog and in accession capital
    to assert that I get actually enjoyed account your blog posts.
    Any way I will be subscribing to your feeds and even I achievement
    you access consistently quickly.

  • Howdy! This blog post could not be written much better!
    Going through this article reminds me of my previous roommate!
    He always kept talking about this. I’ll forward this post to him.
    Pretty sure he’s going to have a very good read. Many thanks for sharing!

  • Nice post. I used to be checking continuously this blog and I’m impressed!
    Very useful info specifically the last phase 🙂 I take care of such information a lot.
    I used to be seeking this particular information for a long time.
    Thanks and good luck.

  • Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is fundamental and all.
    But think about if you added some great photos or video clips to give your posts more, “pop”!
    Your content is excellent but with pics and video clips,
    this website could definitely be one of the best in its field.
    Wonderful blog! scoliosis surgery https://0401mm.tumblr.com/ scoliosis surgery

  • Simply want to say your article is as astounding. The clearness in your submit is
    simply nice and that i can think you’re a professional on this subject.
    Fine with your permission allow me to seize your RSS feed to stay updated with impending post.

    Thanks 1,000,000 and please continue the rewarding work.
    quest bars http://bit.ly/3C2tkMR quest bars

  • Hi would you mind sharing which blog platform you’re using?
    I’m going to start my own blog in the near future but I’m having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most blogs and I’m looking for something unique.
    P.S Sorry for being off-topic but I had to ask!

    quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

  • Hello, i think that i saw you visited my website thus i came to “return the favor”.I’m attempting
    to find things to enhance my website!I suppose its ok to use some of your
    ideas!!

Leave a Reply

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