23
Vrije Universiteit Brussel OSSEC mini project Real-Time Operating System on Arduino Author: Nicolas Pantano Professor: Pr. Martin Timmerman Year 2011 - 2012

Nicolas Pantano Report

Embed Size (px)

DESCRIPTION

free-rtos

Citation preview

  • Vrije Universiteit Brussel

    OSSEC mini project

    Real-Time Operating System onArduino

    Author:Nicolas Pantano

    Professor:Pr. Martin Timmerman

    Year 2011 - 2012

  • Contents1 Introduction 2

    2 Real-Time Operating System (RTOS) 22.1 What is a RTOS? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.2 Why do we need a RTOS? . . . . . . . . . . . . . . . . . . . . . . . . . 3

    2.2.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.3 Multitasking and scheduler . . . . . . . . . . . . . . . . . . . . . . . . . 3

    2.3.1 Cooperative multitasking . . . . . . . . . . . . . . . . . . . . . . 42.3.2 Preemptive multitasking . . . . . . . . . . . . . . . . . . . . . . 4

    3 Demonstration application 53.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.2 Arduino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63.3 FreeRTOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

    3.4.1 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83.4.2 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    3.5 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    4 Conclusion 15

    A Source code 18

    1

  • 1 IntroductionMost of control systems use now real-time operating systems (RTOS) to ensure tem-poral constraint and reliability. RTOS are used in most common systems like internalcalculators of vehicles, nuclear power plants, telecommunication systems and so forth,...RTOS are used everywhere. A RTOS is needed when we would that a task is executedwithin a precise time interval, or when you would that your system reacts in the timeconstraint you imposed to an external system.

    This report, will show utility of a real-time OS with a practical application. Thedemonstration application is consists of an Arduino connected to three captors andrelied by USB to a personal computer, which can interact with the Arduino.

    2 Real-Time Operating System (RTOS)In this section we will roughly explain the mechanism of a real-time operating system,why do we need a RTOS and in which case.

    2.1 What is a RTOS?Before seeing what a real-time OS is, lets explain the dierence between a generalpurpose operating system and a real-time operating system. Windows, Mac OS andLinux are general purpose OS, they are designed to run multiple applications and togive the illusion to the user that they are all running simultaneously. They are named asnon-deterministic OS, in other words, the temporal constraint is not the most importantfactor.

    In real-time OS, its a bit dierent. Real-time OS are specially designed to runapplications with very precise timing and a high degree of reliability [1]. Thus, RTOSare used when the temporal constraint in a system is very important.

    There are dierent kinds of RTOS, soft, firm and hard. In order to characterize them,we will introduce the jitter. The Jitter is a measure of how much the execution time ofa task diers over subsequent iterations. Real-time operating systems are optimized tominimize the jitter [1].

    Soft real-time OS are characterized with a high jitter, soft real-time OS are usedwhen the time constraint in which tasks must be executed is less important.Typically used in systems when the risk that a task is not executed in time is notcritical.

    Hard real-time OS have a less jitter than soft real-time OS, in this kind of RTOSthe time constraint is very important and if a task is not executed in time, theresult is no more useful and the system doesnt work anymore. Hard real-timeOS are used, for example, in ABS (anti-lock braking system) or Airbags.

    Firm real-time OS are located between soft and hard real-time OS. The Jitter isless than for soft RTOS and higher than for hard RTOS.

    [1, 2, 3, 4]

    2

  • Figure 1: Illustration of the jitter [1]

    We can see clearly now, the dierence between a real-time OS and a general purposeOS. This dierence is the temporal constraint and reliability.

    2.2 Why do we need a RTOS?When the time constraint and the reliability are important, we use a real-time OS. Forbetter understanding of the need of a RTOS, we will explain it with a concrete example.

    2.2.1 ExampleSuppose that we have an application that executes three tasks: the first one must beexecuted every 5 milliseconds, we assume that this task performs important calculationsfor the smooth of the application. The second task, performs the display o dierentsensors on a screen, this task must be executed every 10 milliseconds to prevent lag-ging on the screen. This task can be assumed as the less important of the three tasks.And the third and last tasks, send a message on a network (CAN for example) everysecond precisely, to inform a central unit that it is still active and to send a lot ofother informations. Imagine that the central unit activates an alarm if it notices that amodule did not send its active message. Thus this third task is the most important one.

    Suppose we do not use a RTOS. To implement such an application, it is clear thatwe will use timers to perform the dierent tasks. Its a good idea, but on small micro-controllers, there is no priority between dierent interruptions, so we can ensure that,for example the third task will be well executed every second precisely. Therefore, itsnecessary to use a real-time OS, which performs these priorities.

    2.3 Multitasking and schedulerThe main feature of an operating system is that it performs multitasking. Time accessto the processor is share between all tasks in order to give the illusion to the user thatall tasks are running simultaneously. There are dierent ways to share time access butin this section, I will only explain the cooperative and the preemptive multitasking.

    3

  • 2.3.1 Cooperative multitaskingCooperative multitasking is the simplest schedulers algorithm. Here, each task give upaccess to the processor, to allow other tasks taking access to the processor. Each taskcooperates with each other to share time access to the processor. And the programmermay not forget the implementation of the giving up of the access to the processor. Thereader will perceive, that if a task with an infinite loop does not give up its access timeto the processor, the system will be blocked.On figure 2, task A has access to the processor, while tasks B and C are waiting untiltask A is finished [5].

    Figure 2: Cooperative multitasking between three tasks [5]

    The advantage of such a system is that no scheduler is requested and therefore theOS is lighter. The disadvantage is the role of the programmers who may not omit theimplementation of the giving up access to the processor and have to reduce the time toaccess the processor as much as possible.

    2.3.2 Preemptive multitaskingIn a preemptive multitasking system, its not anymore the role of each task to give upaccess to the processor. The operating system has a scheduler whose role is to giveaccess the processor for tasks with higher priority. The scheduler is driven by a regularinterrupt named the clock tick [6]. On each clock tick, it checks if there is no task witha higher priority that will access to the processor. If so, it will postponed all othertasks until the high priority task is finished. If there are multiple tasks with the samepriority level, it depends on the schedulers algorithm, but generally, the scheduler willgive access to the processor every tick for a dierent task.

    On figure 3, we will see how the prioritized preemptive scheduler works.

    Task 1, has a priority level 2, is launched every 4 ticks and needs 1 tick to completehis job.

    Task 2 has a priority level 1, is launched every 3 ticks and needs 3 ticks to completehis job.

    The idle task has a priority level 0. The idle task is always present in a real-timeOS, its the task that runs when there no other tasks that is running.

    A short explanation about this timeline:On tick t = 1, the scheduler sees that task 2 must be launched. As task 2 has a higherpriority level than the idle task, the scheduler pauses the idle task and launches task 2.

    4

  • tick clk

    t=0 t=1 t=2 t=3 t=4 t=5 t=6 t=7 t=8 t=9 t=10

    task 1

    task 2

    idle task

    Figure 3: States of dierent tasks in a prioritized preemptive scheduler algorithm (high= task is running, low = task is paused)

    On t = 3, task 2 has not yet finished, but as task 3 has a higher priority level, task 2is paused and task 3 launched. One tick later, task 3 has done its task, the schedulerreactivates task 2.On t = 5, task 2 and 3 do not need access to the processor, the scheduler reactivatesthe idle task.

    Prioritized preemptive multitasking allows a certain level of abstraction in com-parison to cooperative multitasking, The only think the programmer has to do is togiving a correct priority for each task so that the program runs correctly. Preemptivemultitasking is now used in most of operating systems.

    3 Demonstration application3.1 IntroductionIn the demonstration application, we will show the usefulness of a real-time operat-ing system. First we will describe the tools used for our demonstration (Arduino andFreeRTOS). Then, we will explain both; used hardware and software implementation.But first of all, lets introduce our application.

    Our application consists in six tasks. The tasks are described below.

    Task A, performs an analog to digital conversion to read the value of a photo-resistor.

    Task B, performs an analog to digital conversion to read the value of a thermistor. Task C, checks if beams are not interrupted, if yes its sends an error message tothe computer within 10 milliseconds.

    Task D, sends all information through USB to a computer. Task E, checks if a message is received from the computer, if yes it launches acounter within 5 milliseconds.

    5

  • Idle task, where nothing happens.On table 1, you will find the dierent properties (priority and time constraint) for

    the dierent tasks.XXXXXXXXXXXXTask

    Property Priority Time constraintA 2 Every 10msB 2 Every 10msC 3 Every 10msD 1 Every 1sE 4 Every 5ms

    Idle Task 1 -

    Table 1: Priority and time constraint for the dierent tasks

    Task D is the less important task, because it doesnt matter if a delay is introducedin the display, its the less important operation for the proper functioning of the system.We consider that task A and B as more important because, we assume these measuresare used, for example, to control an external system. Task C has a higher priority levelbecause it will represent that something wrong happens with our hypothetical externalsystem. Finally, task E is the most important task because it represents an externalinterruption done by a user or program.

    3.2 ArduinoFor this demonstration I have decided to use an Arduino platform,which disregards to configuration and the mounting of a micro-controller which can be sometimes tedious.I have selected the Arduino platform for its ease of use and thesimplicity of the syntax of its programming language Moreover, theArduino open-source and his community is very active which ensure an ongoing devel-opment.

    The figure 5 displays a screenshot of the development environment (IDE) of Arduinoand the figure 4 retrieves the full description of all pins on the Arduino Nano.

    6

  • Figure 4: Arduino development environment

    Figure 5: Front and back view of an Arduino Nano board (http : //www.arduino.cc)

    3.3 FreeRTOSThe second important part of the demonstration applica-tion is the real-time operating system. This was a hardpart, because it exists plenty of RTOS for embedded sys-tems. There are also several requirements for choosing agood RTOS, they are listed just below.

    Compatible with ATmega328 chipset. Compatible with the Arduino development board. Compatible with the last Arduino IDE (version 1.0). Support of a prioritized preemptive scheduler Light enough to run correctly on an Arduino Nano.

    7

  • A good documentation. Free.

    When all requirements were identified, my choice felt on the FreeRTOS who fulfilledthem all perfectly. I found a good integration for the Arduino IDE on

    http : //code.google.com/p/beta lib/downloads/list

    3.4 ImplementationNow that we found our tools, we can design our demonstration application. In thissection, we will first detail the hardware implementation and finally, describe the usedsource code.

    3.4.1 HardwareAs explain in section 3.1, our system is composed of three sensors.

    1. A photoresistor

    2. A thermistor

    3. An optical switch

    On figure 6, we observe a pull-down resistor of 10k to allow the ADC (analog todigital converter) of the Arduino to detect voltage variations. If the pull-down resistoris not present, the ADC will not detect the voltage drop caused by the sensor.AREF is connected to the 5V output pin to ensure that the reference for the ADCis correct. Note that the connection between the Arduino and the computer is notrepresented on figure 6 and 7.

    Now that the schematic is complete, it only remains to mount the circuit on aprotoboard. Routing and placement of all the component are shown on figure 7.

    8

  • Figure 6: Schematic o the demo application

    Figure 7: Protoboard o the demo application

    3.4.2 SoftwareArduino works with at least two functions, which must be implemented. The setup()and the loop() functions.The setup() function is ran one time directly after a reset. This function serves toinitialize each part we need on the Arduino. In our case, the ADC, the serial commu-nication, the FreeRTOS tasks and the input/output pins.While, the loop() is an infinity loop and is ran after the setup() function . Its in thisfunction that the whole program is running. But in our case this function is empty.

    Working with FreeRTOS on an Arduino platform requires us to adopt another struc-ture for our program. Like all real-time OS, FreeRTOS works with tasks. These tasksmust be defined in a function with a well-defined structure, detailed below.

    9

  • The initialization code (optional) An infinity loop (the task should never return) The task application code

    Listing 1: Task implementation

    1 s t a t i c void vTaskOne ( void pvParameters ) {23 // I n i t i a l i z a t i o n code4 whi le (1 ) {5 //Task app l i c a t i on code6 }7 }When a task is implemented, you should create this task by calling the

    xTaskCreate() function.This function takes five parameters (http://www.freertos.org):

    Pointer to the task entry function. A descriptive name for the task. The size of the task stack. Pointer that will be used as the parameter for the task being created. The priority at which the task should run. A handle by which the created task can be referenced.

    This function should be called in the setup() function. You will find on listing 2, anexample of use of xTaskCreate() for vTaskOne (listing 1).

    Listing 2: Task creation

    1 xTaskCreate (vTaskOne ,2 ( s igned portCHAR ) taskOne ,3 configMINIMAL STACK SIZE + 50 ,4 NULL,5 tskIDLE PRIORITY ,6 NULL) ;Finally to end our description we will introduce a last concept, named mutex. In our

    application multiple tasks have access to global variables. To avoid that a task wantsto change a variables value while another task is reading this one, we use mutexes.A mutex, is a king of token. When a task owns the mutex, it is the only one that canaccess to the variable. Until the task has not given the mutex, other tasks are pausedand are waiting until the mutex is free.

    10

  • Listing 3: Mutex

    12 i n t g l oba lVa r i ab l e = 0 ;3 xSemaphoreHandle xMutex = NULL;45 void vTaskA ( void pvParameters ) {67 whi le (1){8 i f ( xSemaphoreTake ( xMutex , portMAX DELAY == pdTRUE){9 //Reading g l oba lVa r i ab l e10 xSemaphoreGive ( xMutex ) ;11 }12 }13 }1415 void vTaskB ( void pvParameters ) {16 whi le (1){17 i f ( xSemaphoreTake ( xMutex , portMAX DELAY == pdTRUE){18 //Changing g l oba lVa r i ab l e19 xSemaphoreGive ( xMutex ) ;20 }21 }22 }2324 setup ( ) {25 // . . .26 xMutex = xSemaphoreCreateMutex ( ) ;27 / / . . .28 }

    An example of using of a mutex, is shown on listing 3. First of all, the mutex iscreated in the setup() function. Suppose then that vTaskA executes first. Overall itchecks if the mutex is available. If yes, vTaskA executes its code. Otherwise it waits adelay defined by portMAX DELAY before evaluating the condition again. This pieceof code prevents vTaskA and vTaskB accessing globalVariable together.

    We are now ready to explain the whole source code of demo application (refer toappendix for the source code of the application). The aims of this part is not to explainline by line the source code but to explain what the tasks, functions do.

    setup()

    1. Initialization the serial communication (set up the baud rate at 9600 bits/s).

    2. Set up the specified digital pins to behave as an output (used for the logicalanalyzer).

    11

  • 3. Reduce the clock divider of the ADC from 128 to 16 (increase the speed of theconversion).

    4. Define the analog reference on the external pin (AREF).

    5. Create the dierent tasks.

    6. Initialization of the two mutex, used for the temperature and the luminosityvariables.

    Luminosity and temperature measurements

    1. Verify if the mutex is not used.

    2. Perform an analog to digital conversion on the correct pin associated to the correctsensor and assign the value of this conversion the correct global variable.

    3. Release the mutex.

    4. Wait for minimum 10ms, before to run the task again.

    Listing 4 shows the measurement of the luminosity sensor.

    Listing 4: Reading luminosity sensor value

    1 s t a t i c void vLuminosityTask ( void pvParameters )2 {3 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 1 ) ;4 //Create mutex5 whi le (1 )6 {7 i f ( xSemaphoreTake ( xSemaphoreLuminosity , portMAX DELAY == pdTRUE) )8 {9 l uminos i ty = analogRead ( luminos i tySensorPin ) ;10 xSemaphoreGive ( xSemaphoreLuminosity ) ;11 }12 vTaskDelay ( configTICK RATE HZ/100) ; //10ms seconds wai t ing13 }14 }

    Optical switch

    1. Verify the optical switch state

    2. If ON, sending an error message to the computer and assign value true to theglobal variable associated to the optical switch.

    3. If OFF, assign value false to the global variable.

    4. Wait minimum 10ms, before to run the task again.

    In this task, I expressly omit to use a mutex to illustrate a task without it.

    12

  • Listing 5: State checking of the optical switch

    1 s t a t i c void vOpticalSwitchTask ( void pvParameters )2 {3 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 4 ) ;4 whi le (1 )5 {6 i f ( analogRead ( opt i ca lSwi t chSensorP in ) > 50)7 {8 opt i c a lSw i t ch = true ;9 S e r i a l . p r i n t l n ( Error ) ;10 }11 e l s e op t i c a lSw i t ch = f a l s e ;12 vTaskDelay ( configTICK RATE HZ/100) ; //10ms13 }14 }

    Sending informations to the personal computer

    1. Verify if the two mutex for the temperature and the luminosity are available.

    2. If yes, send via serial all the values of the global variables (luminosity, temperature,optical switch)

    3. Wait minimum 1s, before to run the task again.

    Listing 6: Sending information to the computer using serial communication

    1 s t a t i c void vSe r i a l In f oTask ( void pvParameters ) {2 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 3 ) ;3 whi le (1 ) {4 i f ( xSemaphoreTake ( xSemaphoreLuminosity , portMAX DELAY == pdTRUE)5 and xSemaphoreTake ( xSemaphoreTemperature ,portMAX DELAY == pdTRUE))6 {7 S e r i a l . p r i n t ( Luminosity : ) ;8 S e r i a l . p r i n t l n ( luminos i ty ) ;9 S e r i a l . p r i n t ( Temperature : ) ;10 S e r i a l . p r i n t l n ( temperature ) ;11 S e r i a l . p r i n t ( Opt ica l switch : ) ;12 S e r i a l . p r i n t l n ( op t i c a lSw i t ch ) ;13 xSemaphoreGive ( xSemaphoreLuminosity ) ;14 xSemaphoreGive ( xSemaphoreTemperature ) ;15 }16 vTaskDelay ( configTICK RATE HZ ) ;17 }18 }

    13

  • Receiving information from the personal computer

    1. Check if serial communication if available.

    2. Check if the stop message is received (character s).

    3. Freeze the application for 3s.

    4. Wait for 5ms, before to run the task again.

    Listing 7: Reading informations from the serial communication

    1 s t a t i c void vSerialMsgCheck ( void pvParameters )2 {3 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 5 ) ;4 whi le (1 ) {5 i f ( S e r i a l . a v a i l a b l e ( ) > 0)6 {7 i f ( S e r i a l . read ( ) == s )8 {9 delay ( 3000 ) ; //Force wai t ing 1 second10 }11 }12 vTaskDelay ( configTICK RATE HZ/200) ; //5ms13 }14 }

    3.5 ResultsNow that the demonstration application is designed, we have to check if it works as weexpect. To do so we will use a logic analyzer and the trace features from FreeRTOSto collect informations about running tasks (it will set a specified digital pin for eachtask on a logic level 1 when this specific task is running).

    The data given by the logic analyzer are shown on figures 8 and 9. We observe thatthe results are those we expected. Figure 8, task D has the mutex and until the taskgive the mutex back other tasks even with a higher priority are paused. On the otherside, when we do not use mutexs, task D is paused until task C has finished. Thislast eect is shown on time line on figure 9, and visualized on figure 10. Informationsmessages from task D is paused, the error message is send, and then the end of themessage arrives. These priority levels are also observed when the personal computersends to the Arduino the an s. All the system is paused during 3 seconds.

    Fortunately, we see in the results that the system design does what it was expectedfor. Its fits perfectly with the theory of a prioritized preemptive scheduler.

    14

  • clk

    0 1 2 3 4 5 6 7 8 9 101112131415161718192021222324252627282930

    task A

    task B

    task D

    Figure 8: Eect of the use of mutexs

    tick clk

    0 1 2 3 4 5 6 7 8 9 101112131415161718192021222324252627282930

    task C

    task D

    Figure 9: Scheduler pausing lower priority task D to allows task C to run.

    Figure 10: Visualisation of the dierent priority level for dierent tasks.

    4 ConclusionIn this report we have seen on introduction on how works a real-time operating systemsand an overview of FreeRTOS and the Arduino development platform. It allows tobetter understand the usefulness of real-time OS. The aim of this report is not to enterin all details of the scheduler, but well to understand how it works. Especially tounderstand in which case an real-time OS is needed.

    15

  • List of Figures1 Illustration of the jitter [1] . . . . . . . . . . . . . . . . . . . . . . . . . 32 Cooperative multitasking between three tasks [5] . . . . . . . . . . . . . 43 States of dierent tasks in a prioritized preemptive scheduler algorithm

    (high = task is running, low = task is paused) . . . . . . . . . . . . . . 54 Arduino development environment . . . . . . . . . . . . . . . . . . . . 75 Front and back view of an Arduino Nano board (http : //www.arduino.cc) 76 Schematic o the demo application . . . . . . . . . . . . . . . . . . . . 97 Protoboard o the demo application . . . . . . . . . . . . . . . . . . . 98 Eect of the use of mutexs . . . . . . . . . . . . . . . . . . . . . . . . 159 Scheduler pausing lower priority task D to allows task C to run. . . . . 1510 Visualisation of the dierent priority level for dierent tasks. . . . . . . 15

    List of Tables1 Priority and time constraint for the dierent tasks . . . . . . . . . . . . 6

    16

  • References[1] N. Instruments, What is a real-time operating system (rtos).

    http://zone.ni.com/devzone/cda/tut/p/id/3938, January 2010.

    [2] S. Rivoir, Real time operating system. http://www.stanford.edu/ skrufi/r-tospres.ppt, November 2002.

    [3] P. Mathys, ELEC-H410 - Real-time systems. Universite Libre de Bruxelles, 2012.

    [4] Wikipedia, Real time operating system. http://en.wikipedia.org/wiki/rtos, April2012.

    [5] K. Hyder and B. Perrin, Embedded Systems Design Using the Rabbit 3000 Micro-processor: Interfacing, Networking, and Application Design. Embedded TechnologySeries, Newnes, 2004.

    [6] T. Wilmshurst, Designing Embedded Systems With PIC Microcontrollers: Principlesand Applications. Elsevier Science, 2009.

    [7] FreeRTOS, Freertos implementation. http://www.freertos.org/implementation/index.html.

    [8] D. Ibrahim, Advanced PIC Microcontroller Projects in C: From USB to RTOS withthe PIC18F Series. Electronics & Electrical, Newnes/Elsevier, 2008.

    [9] Arduino, Arduino ocial website. http://www.arduino.cc, February 2012.

    17

  • A Source code

    Listing 8: Full source code

    1 #inc lude 23 #de f i n e traceTASK SWITCHED IN( ) vSetDig i ta lOutput ( ( i n t )4 pxCurrentTCB>pxTaskTag )56 i n t luminos i tySensorPin = A0 ;7 i n t temperatureSensorPin = A1 ;8 i n t opt i ca lSwi t chSensorP in = A2 ;910 i n t luminosityTaskON = 12 ;11 i n t temperatureTaskON = 11 ;12 i n t ser ia l InfoTaskON = 10 ;13 i n t opticalSwitchTaskON = 9 ;14 i n t serialMsgTaskON = 8 ;15 i n t idleTaskON = 7 ;1617 unsigned i n t luminos i ty ;18 unsigned i n t temperature ;19 boolean opt i c a lSw i t ch ;2021 xSemaphoreHandle xSemaphoreLuminosity ;22 xSemaphoreHandle xSemaphoreTemperature ;2324 //25 // Reading luminos i ty s enso r value26 s t a t i c void vLuminosityTask ( void pvParameters )27 {28 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 1 ) ;29 //Create mutex30 whi le (1 )31 {32 i f ( xSemaphoreTake ( xSemaphoreLuminosity , portMAX DELAY == pdTRUE))33 {34 l uminos i ty = analogRead ( luminos i tySensorPin ) ;35 xSemaphoreGive ( xSemaphoreLuminosity ) ;36 }37 vTaskDelay ( configTICK RATE HZ/100) ; //10ms seconds wai t ing38 }39 }4041 //42 // Reading luminos i ty s enso r value43 s t a t i c void vTemperatureTask ( void pvParameters )44 {

    18

  • 45 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 2 ) ;46 whi le (1 )47 {48 i f ( xSemaphoreTake ( xSemaphoreTemperature , portMAX DELAY == pdTRUE))49 {50 temperature = analogRead ( temperatureSensorPin ) ;51 xSemaphoreGive ( xSemaphoreTemperature ) ;52 }53 vTaskDelay ( configTICK RATE HZ/100) ; //10ms54 }55 }5657 //58 // Reading optocaptor s enso r value59 s t a t i c void vOpticalSwitchTask ( void pvParameters )60 {61 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 4 ) ;62 unsigned i n t temp ;63 whi le (1 )64 {65 i f ( analogRead ( opt i ca lSwi t chSensorP in ) > 50)66 {67 opt i c a lSw i t ch = true ;68 S e r i a l . p r i n t l n ( Error ) ;69 }70 e l s e op t i c a lSw i t ch = f a l s e ;71 vTaskDelay ( configTICK RATE HZ/100) ; //10ms72 }73 }7475 //76 // Send in fo rmat ions v ia S e r i a l i n t e r f a c e77 s t a t i c void vSe r i a l In f oTask ( void pvParameters ) {78 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 3 ) ;79 whi le (1 ) {80 i f ( xSemaphoreTake ( xSemaphoreLuminosity , portMAX DELAY == pdTRUE) and xSemaphoreTake ( xSemaphoreTemperature , portMAX DELAY == pdTRUE) )81 {82 S e r i a l . p r i n t ( Luminosity : ) ;83 S e r i a l . p r i n t l n ( luminos i ty ) ;84 S e r i a l . p r i n t ( Temperature : ) ;85 S e r i a l . p r i n t l n ( temperature ) ;86 S e r i a l . p r i n t ( Opt ica l switch : ) ;87 S e r i a l . p r i n t l n ( op t i c a lSw i t ch ) ;88 xSemaphoreGive ( xSemaphoreLuminosity ) ;89 xSemaphoreGive ( xSemaphoreTemperature ) ;90 }91 vTaskDelay ( configTICK RATE HZ ) ; //1 secondes wai t ing

    19

  • 92 }93 }9495 //9697 s t a t i c void vSerialMsgCheck ( void pvParameters )98 {99 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 5 ) ;100 whi le (1 ) {101 i f ( S e r i a l . a v a i l a b l e ( ) > 0)102 {103 i n t rece ivedByte = S e r i a l . read ( ) ;104 i f ( r ece ivedByte == s )105 {106 delay ( 3000 ) ; //Force wai t ing 1 second107 }108 }109 vTaskDelay ( configTICK RATE HZ/200) ; //5ms110 }111 }112113 void vIdleTask ( void pvParameters ) {114 vTaskSetApplicationTaskTag (NULL, ( char ( ) ( void ) ) 6 ) ;115 whi le (1 )116 {}117 }118119 //120 void setup ( ) {121 // I n i t i a l i z a t i o n o f the s e r i a l communication with 9600 kb i t s as baud ra t e122 S e r i a l . begin ( 9600 ) ;123124 pinMode ( luminosityTaskON , OUTPUT) ;125 pinMode ( temperatureTaskON , OUTPUT) ;126 pinMode ( ser ia l InfoTaskON , OUTPUT) ;127 pinMode ( opticalSwitchTaskON , OUTPUT) ;128 pinMode ( serialMsgTaskON , OUTPUT) ;129 pinMode ( idleTaskON , OUTPUT) ;130131 // Conf igur ing HIGH SPEED132 b i tC l ea r (ADCSRA, ADPS0) ;133 b i tC l ea r (ADCSRA, ADPS1) ;134 b i tS e t (ADCSRA, ADPS2) ;135 ana logReference (EXTERNAL) ;136137 // c r e a t e luminos i ty measurement task138 xTaskCreate ( vLuminosityTask ,

    20

  • 139 ( s igned portCHAR ) luminos ityTask ,140 configMINIMAL STACK SIZE + 50 ,141 NULL,142 tskIDLE PRIORITY + 2 ,143 NULL) ;144145 // c r e a t e temperature measurement task146 xTaskCreate ( vTemperatureTask ,147 ( s igned portCHAR ) temperatureTask ,148 configMINIMAL STACK SIZE + 50 ,149 NULL,150 tskIDLE PRIORITY + 2 ,151 NULL) ;152153 xTaskCreate ( vOpticalSwitchTask ,154 ( s igned portCHAR ) opt ica lSwitchTask ,155 configMINIMAL STACK SIZE + 50 ,156 NULL,157 tskIDLE PRIORITY + 3 ,158 NULL) ;159160 xTaskCreate ( vSerialMsgCheck ,161 ( s igned portCHAR ) serialMsgCheckTask ,162 configMINIMAL STACK SIZE + 50 ,163 NULL,164 tskIDLE PRIORITY + 4 ,165 NULL) ;166167 xTaskCreate ( vSer ia l In foTask ,168 ( s igned portCHAR ) s e r i a lTa sk ,169 configMINIMAL STACK SIZE + 50 ,170 NULL,171 tskIDLE PRIORITY + 1 ,172 NULL) ;173174 xTaskCreate ( vIdleTask ,175 ( s igned portCHAR ) id l eTask ,176 configMINIMAL STACK SIZE + 50 ,177 NULL,178 tskIDLE PRIORITY ,179 NULL) ;180181 xSemaphoreLuminosity = xSemaphoreCreateMutex ( ) ;182 xSemaphoreTemperature = xSemaphoreCreateMutex ( ) ;183184 // s t a r t FreeRTOS185 vTaskStartScheduler ( ) ;

    21

  • 186187 S e r i a l . p r i n t l n ( Die ) ;188 whi le ( 1 ) ;189 }190191 void vSetDig ita lOutput ( i n t task )192 {193 d i g i t a lWr i t e ( temperatureTaskON , LOW) ;194 d i g i t a lWr i t e ( ser ia lInfoTaskON , LOW) ;195 d i g i t a lWr i t e ( opticalSwitchTaskON , LOW) ;196 d i g i t a lWr i t e ( serialMsgTaskON , LOW) ;197 d i g i t a lWr i t e ( idleTaskON , LOW) ;198 d i g i t a lWr i t e ( temperatureTaskON , LOW) ;199 switch ( task ){200 case 1 :201 d i g i t a lWr i t e ( luminosityTaskON , HIGH) ;202 break ;203 case 2 :204 d i g i t a lWr i t e ( temperatureTaskON , HIGH) ;205 break ;206 case 3 :207 d i g i t a lWr i t e ( ser ia lInfoTaskON , HIGH) ;208 break ;209 case 4 :210 d i g i t a lWr i t e ( opticalSwitchTaskON , HIGH) ;211 break ;212 case 5 :213 d i g i t a lWr i t e ( serialMsgTaskON , HIGH) ;214 break ;215 case 6 :216 d i g i t a lWr i t e ( idleTaskON , HIGH) ;217 break ;218 de f au l t :219 break ;220221 }222 }223224 void loop ( )225 {}

    22

    IntroductionReal-Time Operating System (RTOS)What is a RTOS?Why do we need a RTOS?Example

    Multitasking and schedulerCooperative multitaskingPreemptive multitasking

    Demonstration applicationIntroductionArduinoFreeRTOSImplementationHardwareSoftware

    Results

    ConclusionSource code