Monday, June 5, 2017

Arduino ESP32 FreeRTOS 1: How to create a task

1. Introduction
- In this tutorial, I will show you how to apply FreeRTOS in Arduino ESP32. As you know, Arduino ESP32 is built over FreeRTOS and actually the main program is put in a loopTask (refer here). But if we only use one task (even using Finite State Machine for pure Arduino application), we will not take full advantage of FreeRTOS like multitasking, good at resources management and maximize system performance.
- In this demo, beside Arduino task (loopTask), we will add one more task to our application. Our application has 2 tasks: Arduino task will print the text "this is Arduino task" and second task will print "this is additional task" on Serial terminal.
2. Hardware
- You do not need any extra hardware.
3. Software
- You should familiar with FreeRTOS API. Here is the FreeRTOS ebook for your reference.
- We will use the xTaskCreate() API Function to create a new task. You can refer this API function at page 48 of FreeRTOS ebook.
- Create an Arduino project with code:
 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
void setup() {

  Serial.begin(112500);
  /* we create a new task here */
  xTaskCreate(
      additionalTask,           /* Task function. */
      "additional Task",        /* name of task. */
      10000,                    /* Stack size of task */
      NULL,                     /* parameter of the task */
      1,                        /* priority of the task */
      NULL);                    /* Task handle to keep track of created task */
}

/* the forever loop() function is invoked by Arduino ESP32 loopTask */
void loop() {
  Serial.println("this is Arduino Task");
  delay(1000);
}
/* this function will be invoked when additionalTask was created */
void additionalTask( void * parameter )
{
  /* loop forever */
  for(;;){
    Serial.println("this is additional Task");
    delay(1000);
  }
  /* delete a task when finish, 
  this will never happen because this is infinity loop */
  vTaskDelete( NULL );
}
4. Result
 Figure: ESP32 FreeRTOS with 2 tasks

1 comments:

Anonymous said...

Great! Solve my problem on getting ESP32 to work on different tasks.
Thanks.