an01264a

22
© 2009 Microchip Technology Inc. DS01264A-page 1 AN1264 INTRODUCTION As customer applications evolve into ever more compli- cated and feature rich designs, there is a requirement to rationalize the development process and streamline the device’s software. Microchip provides a number of middleware stacks and libraries that are designed to aid customers in the creation of these advanced designs. A Real-Time Operating System (RTOS) offers an application developer a number of aids that allow a complex design to be completed in a timely fashion, permit easy integration of existing components and allow for simpler code re-use in the future. With the demand for increased functionality and ever decreasing development times, an RTOS provides a good method of organizing and scheduling the interac- tion of the various libraries now being used in these advanced applications. However, the question that frequently arises is, how best can one’s software be organized to take advantage of the RTOS services. Equally important is what modifications might be required to existing libraries or stacks in order that they will operate in the context of an RTOS along with other libraries. This application note examines the reasons for migrat- ing to a RTOS-based platform. It then discusses the various changes that may be required to one’s software in order to use an RTOS. When discussing this topic, it is easier to do this in the context of a real world appli- cation, such as a home utility metering, as an example. The demonstration shows how a complex application can be built using Commercial Off-The-Shelf (COTS) hardware and software components. By using an RTOS, the workload involved in integrating multiple libraries has been significantly reduced. BACKGROUND Microchip provides several robust and free libraries that include: TCP/IP Ethernet Stack • Zigbee ® Protocol Stack MiWi™ (and MiWi Peer-to-Peer (P2P)) Networking Protocol Stack USB Host and Client Stacks • IrDA ® Stack Microchip Graphics Library Microchip mTouch™ Sensing Solution Library Memory Disk Drive (MDD) Audio Library It can be observed that with such a large variety of libraries, there are innumerable ways in which an application might combine them. Therefore, it is not surprising that a general method for interconnecting them does not exist. Furthermore, since the authors of the various libraries cannot be sure that the libraries will be compiled to execute in a particular run-time environ- ment, they have generally been written to assume that no underlying operating system exists; instead, the libraries will execute in a cooperative multitasking environment. To explain how this architecture is used, consider the basic code loop of the TCP/IP Stack V4.51 found in the file, TCPIP DemoApp/MainDemo.c. Author: Darren Wenn Microchip Technology Inc. Note: Before continuing with this discussion, it is worthwhile to be clear on terminology. While the term, ‘software library’, can apply to any combination of code modules placed together, stack is more generally used in the context of a communications application library. Since not all of the Microchip libraries are stacks, but the integration issues are common to stacks and libraries, we will use the terms interchangeably within this document. Integrating Microchip Libraries with a Real-Time Operating System

Upload: dkscribd

Post on 03-Jan-2016

5 views

Category:

Documents


0 download

DESCRIPTION

App Note 1264

TRANSCRIPT

Page 1: AN01264a

AN1264Integrating Microchip Libraries with a Real-Time Operating System

INTRODUCTIONAs customer applications evolve into ever more compli-cated and feature rich designs, there is a requirementto rationalize the development process and streamlinethe device’s software. Microchip provides a number ofmiddleware stacks and libraries that are designed toaid customers in the creation of these advanceddesigns. A Real-Time Operating System (RTOS) offersan application developer a number of aids that allow acomplex design to be completed in a timely fashion,permit easy integration of existing components andallow for simpler code re-use in the future.

With the demand for increased functionality and everdecreasing development times, an RTOS provides agood method of organizing and scheduling the interac-tion of the various libraries now being used in theseadvanced applications. However, the question thatfrequently arises is, how best can one’s software beorganized to take advantage of the RTOS services.Equally important is what modifications might berequired to existing libraries or stacks in order that theywill operate in the context of an RTOS along with otherlibraries.

This application note examines the reasons for migrat-ing to a RTOS-based platform. It then discusses thevarious changes that may be required to one’s softwarein order to use an RTOS. When discussing this topic, itis easier to do this in the context of a real world appli-cation, such as a home utility metering, as an example.The demonstration shows how a complex applicationcan be built using Commercial Off-The-Shelf (COTS)hardware and software components. By using anRTOS, the workload involved in integrating multiplelibraries has been significantly reduced.

BACKGROUNDMicrochip provides several robust and free librariesthat include:

• TCP/IP Ethernet Stack• Zigbee® Protocol Stack• MiWi™ (and MiWi Peer-to-Peer (P2P))

Networking Protocol Stack• USB Host and Client Stacks• IrDA® Stack• Microchip Graphics Library• Microchip mTouch™ Sensing Solution Library• Memory Disk Drive (MDD)• Audio Library

It can be observed that with such a large variety oflibraries, there are innumerable ways in which anapplication might combine them. Therefore, it is notsurprising that a general method for interconnectingthem does not exist. Furthermore, since the authors ofthe various libraries cannot be sure that the libraries willbe compiled to execute in a particular run-time environ-ment, they have generally been written to assume thatno underlying operating system exists; instead, thelibraries will execute in a cooperative multitaskingenvironment. To explain how this architecture is used,consider the basic code loop of the TCP/IP Stack V4.51found in the file, TCPIP DemoApp/MainDemo.c.

Author: Darren WennMicrochip Technology Inc.

Note: Before continuing with this discussion, it isworthwhile to be clear on terminology.While the term, ‘software library’, canapply to any combination of code modulesplaced together, stack is more generallyused in the context of a communicationsapplication library. Since not all of theMicrochip libraries are stacks, but theintegration issues are common to stacksand libraries, we will use the termsinterchangeably within this document.

© 2009 Microchip Technology Inc. DS01264A-page 1

Page 2: AN01264a

AN1264

EXAMPLE 1: MAIN LOOP FROM TCP/IP

STACK

The sample code in Example 1 shows the ‘C’ function,main, which begins by initializing the hardware on theboard and then continuing to initialize the variouselements of the TCP/IP Stack. Finally, it enters awhile(1) loop, which performs a round-robinsequence of operations. During each pass around themain loop, the StackTask and StackApplicationsfunctions are called to ensure that the TCP/IP Stackkeeps operating and services any network requests,such as a PING or web page GET.

Following the mandatory function calls to the TCP/IPStack, users provide application-specific function calls,such as ProcessIO and ApplicationTask1. Sinceit is necessary to keep the stack working by periodicallycalling the stack functions, any user code must bewritten so as not to block while waiting to complete anyoperation. For existing code, this will often mean that itwill have to be rewritten in a non-blocking fashionperhaps introducing unwanted time dependencies andextra code in the form of switch statements.

Most of the Microchip software libraries are providedwith comprehensive demo applications written specifi-cally to demonstrate a full range of features, and arethus, inherently quite large. For example, in the GraphicsObject Layer Demo application, the MainDemo.c filecontains over 4000 lines of code. This application iscomplete and showcases a full range of the graphicslibrary capabilities, but it may not be readily apparenthow users should integrate their code. Note that whilesimple examples make code transition and integrationeasier, it is inevitable that any TCP/IP or QVGA-basedapplication will always be complex, and hence, theexamples will be lengthy.

When users want to integrate their application with aCOTS component, such as a Microchip library, it maybe possible to redesign their code to work alongsidethe program structure provided by the library. Equally,for relatively simpler libraries, it may be possible tomodify the library itself to fit with either the existing orplanned program architecture. However, the situationbecomes significantly more complicated when theapplication uses more than one COTS component, orthe program architecture does not conveniently fit intothe super-loop programming paradigm.

In these cases, a RTOS can assist with the program-ming effort by allowing a designer to break down theapplication into convenient isolated functional modulesor tasks that perform parts of the application. Later, wewill demonstrate how it is possible to move the softwarelibraries into their own tasks and modify them so thatthey can continue to execute as if they were the onlypiece of software on the microcontroller. The users’new or existing code base can then be placed into itstask, and RTOS services, such as “Semaphores” and“Queues”, can be used to communicate between thevarious tasks.

Embedded RTOSFor applications based upon larger non-embeddedplatforms, it is possible to assume the existence of asuitable run-time environment. For instance, fordevices based upon an embedded PC, it is not uncom-mon for the various software libraries to be writtenassuming that they will have access to a well under-stood kernel, such as Linux or Windows® CE. Such akernel provides a rich set of features that can simplifythe task of integrating multiple libraries.

However, the overhead associated with running suchresource intensive kernels is not always appropriatewhen a cost-effective application is being designed torun on an embedded 16 or 32-bit processor core, suchas the PIC24, dsPIC® DSC or PIC32 families. For themore deeply embedded applications that are com-monly designed to run on Microchip microcontrollers, amore compact RTOS is required.

// Main application entry point.int main(void){

… //Initialize application

//specific hardwareInitializeBoard();

…//Initialize Stack and//application related NV //variables into AppConfig.InitAppConfig();

//Initialize core stack layers StackInit();

//Begin the co-operative//multitasking loop.while(1){…//perform basic stack functionsStackTask();

//perform higher level tasks StackApplications();

//Process application //specific tasks here.ProcessIO();ApplicationTask1();

}}

DS01264A-page 2 © 2009 Microchip Technology Inc.

Page 3: AN01264a

AN1264

There are several good third party products currentlyavailable (see Table 1). For the purpose of this applica-tion note, it was decided to design the demo applicationusing FreeRTOS. This is a popular product with a largeexisting user base readily able to provide support andadvice to any author. Particularly for this application, itcan be used and distributed without any fees or royaltiesassociated with it so long as the standard General PublicLicense (GNU) is complied with. Rather conveniently,this exists in a modified form in this distribution so thatgeneral publication of the product-specific code is notrequired (something that often deters designers fromusing GPL code in their own applications).

Note that while FreeRTOS has been employed, nounique functions have been used; hence, the demoapplication is easy to port to another host operatingsystem.

This application note is not intended to be an authorita-tive article on how an RTOS works and how codeshould best be written to work with it. While the basicconcepts of an RTOS are simple, the details can becomplicated and lengthy.

Refer to the “References” section for more details onhow an RTOS works and the vendor web sites for thespecifics of each RTOS.

TABLE 1: THIRD PARTY PRODUCTS

Note: Users should be familiar with basic RTOSconcepts, such as Tasks, and thedifference between cooperative andpre-emptive multitasking. We haveprovided some additional topics that haverelevance to our application.

Vendor/RTOS Product MPLAB® IDE Plug-in Microchip 16/32 Ports Modules/Support

AVIX AVIX-RT 2.2.1 Yes 16/32 —CMX Systems CMX 5.30 Yes 8/16/32 TCP/IPExpress Logic ThreadX G5.1.5.0 Yes 16/32 —

FreeRTOS FreeRTOS v5.1.1 Yes 16/32 —Micrium μC/OS-II v2.84 Yes 8/16/32 TCP/IPPumpkin Salvo 4 Pro and

Salvo 4 LENo 8/16/32 —

RoweBots DSPNanoUnison No 1632 DSP, TCP/IP, POSIXSegger embOS V3.52 Yes 16/32 GUI, TCP/IP

© 2009 Microchip Technology Inc. DS01264A-page 3

Page 4: AN01264a

AN1264

Blocking FunctionsThe majority of Microchip libraries and stacks are writ-ten to use non-blocking function calls for a TCP/IPStack-based application. For example, assume that theuser application is waiting for an incoming packet ofdata, which may arrive at any time because of thestructure of the Internet. Programmers must allow forrepeated function calls to the lower levels of the TCP/IPStack to process the received packets, so users cannotsimply wait, or block, for the packet to be received.

To simplify the coding problem, the libraries are typicallywritten using state machines that can be called manytimes and only advance the state when the event hasoccurred. Any user application should be written in asimilar manner. Blocking function calls must not be usedas they will prevent program execution from continuinguntil the time elapse or an event occurs.

On the contrary, for an RTOS-based application, block-ing function calls are desirable. Since any RTOS func-tion call may cause a change of task, the code thatneeds to wait for a fixed period can simply use theprovided delay routines and other unrelated tasks willautomatically be scheduled to run. Furthermore, whenthe RTOS is operated in a pre-emptive mode, blockingcode or time-consuming sequences will automatically beinterrupted and the other tasks will be given the opportu-nity to run if they have the required priority. Blockingfunction calls can be viewed as opportunities when othertasks can be allowed to run and their introduction into anapplication is desirable.

Priority Inversion, Mutexes and SemaphoresA problem that often occurs when writing an applicationand breaking it up into appropriate tasks is priorityinversion.

Consider the example of a serial-based output channel.Serial output devices are inherently slow, and sincethey will spend most of the time waiting for the UART tocomplete a transaction, it makes sense to run the serialtask at a low priority. If we were to send something tobe printed via the serial routine from a very high-prioritytask, but the routine was not yet ready, then thehigh-priority task would be made to wait. Depending onour system, we may need to make the low-priorityserial task active in order to complete so that thehigh-priority task can then complete its printing functioncall. In this case, we have made the high-priority taskwait on a low-priority one and the low-priority task hasbeen raised to the same level as the high-priority one.This is the so-called priority inversion problem and it isbest avoided by careful program design. In the demoapplication, a message queue was used to send theprinted strings so that the high-priority task no longerhas to wait for the lower priority one.

Another problem that can occur is when multiple taskswish to access the same or related hardwareperipheral.

Consider several LEDs all connected to the sameperipheral port, for example, PORTA. If we were to startmodifying the bits of PORTA, and in the middle of thesequence, a pre-emption occurs and another task runsthat also switches an LED, then a conflict may occurand PORTA may be incorrectly set; this is thewell-known read-modify-write problem.

The typical method to solve this problem is to create anatomic sequence or critical section. In other words, wesomehow form a sequence of code that cannot beinterrupted, such that only one task can changePORTA at a time.

The common way around the priority inversion and thenon-atomic access is to create some form of mutualexclusion or mutex. An RTOS will provide constructsfor the creation of mutexes so that the code sequenceis protected until it has completed. Depending upon theRTOS, the mutex object may explicitly exist, or it maybe created via the use of a semaphore, and in the caseof FreeRTOS, there is a great deal of similarity betweenthe two. At program start-up, a semaphore or binaryflag is created, and when a task wishes to access theperipheral or function, it must be obtained by the callingtask. Once it has been obtained, the peripheral can bemodified or the slow functions can be called, but anyother task that wants access must wait or block until thesemaphore has been released.

Since the demo application uses FreeRTOS, all of thefunction calls are related to that kernel. Though, as wehave stated, to allow the application to be easily ported,no functions that are unique to that operating systemhave been used. Appendix A: “Function Calls” liststhe functions that have been used along with theirparameters.

Note: To overcome the above mentionedproblem, a serial output task has beenconsidered later in this application note.

DS01264A-page 4 © 2009 Microchip Technology Inc.

Page 5: AN01264a

AN1264

LIBRARY AND APPLICATION MIGRATIONIn the previous sections we have discussed a numberof RTOS features that will aid us when porting thelibraries into our new application. However, these areonly tools and one of the more fundamental questionsis how to modify the software.

There are several possible techniques for performing theintegration; these are broken down into three options:

• First, the entire library can be rewritten to take advantage of the intrinsic multitasking provided by the RTOS. This would entail the identification of all parallel and sequential operations, and the creation of multiple tasks to handle independent sections of the code. A good example would be the TCP/IP Stack, where the main modules could be broken down with separate tasks for TCP/IP, HTTP Server and ICMP. This could also simplify some of the complex state machines present in the code with a separate task being dynamically created for each socket created.

This technique would ultimately allow for the high-est performance but with a number of drawbacks.A deep understanding of the library must beobtained in order to perform the rewrite. This is, inturn, likely to introduce errors and the resultingpackage will need extensive testing and possiblerecertification. In the likely event of new versions ofthe library becoming available, much of the portingwork would have to be performed again.

• Second, time-critical parts of the code can be identified and replaced with calls to the RTOS kernel. This might require the modification of small parts of the code separating short, high-priority code from the majority of the slow blocking code. Time delays can be replaced with API calls performing the same actions, but it may also be possible to remove the delays completely by the introduction of a blocking event, such as a ‘wait for semaphore’ or ‘queue’. Data to be sent in and out of the library can then be sent via queues.

• Third, the unmodified code can be placed inside a task wrapper. This will require the minimum amount of modifications to the library. However, an issue arises with the resulting task and how fre-quently it performs its processing. If the task is given a low priority by the RTOS, then it may never complete its functions or may take too long. Equally, if given a high priority, the library may con-sume all of the processor time, stopping other tasks from executing. To prevent this situation, a blocking call or RTOS delay function must be intro-duced into the task loop so that the lower priority tasks are given the chance to execute. The delay will impair the cycle time of the affected library and so must be kept to a minimum while not degrading the performance of other software modules.

When migrating libraries into a combined application, itis desirable to keep changes in the COTS componentsto a minimum. If we can keep the changes to a minimum,it is then a relatively simple matter to take advantage ofnew library versions when they are released by justcopying them over existing, unmodified versions. Wehave adopted the following technique for structuring theproject and workspace:

• Place the COTS libraries within the main project directory with a path, such as C:\MainProject\Microchip\TCPIP Stack.

• Source files specific to the project are kept within the C:\MainProject\src directory and any files from the libraries that need to be modified are also copied into this directory.

• Include within the MPLAB IDE project, the required files from the original library along with the modified local copies and our program source files.

This handles the project source, but many of the librariesalso have associated header files, which are includedusing relative paths.

To overcome this, the directories that are searched bythe MPLAB IDE, when including a file, have been set upso that the local include path is searched first, followedby the library default paths. This, then, provides the mod-ified local header files, and allows the local source filesto correctly locate and include library-specific headerfiles without any errors.

The reader should examine the project path dialog inthe MPLAB IDE to see the path priority settings.

© 2009 Microchip Technology Inc. DS01264A-page 5

Page 6: AN01264a

AN1264

DEMO APPLICATIONAs mentioned in previous sections, it is difficult todevelop an application that demonstrates certain capa-bilities without it becoming overly complex and large;as in the case of the Graphics Library demonstrationapplication. For the purposes of this demonstration, itwas desirable to target an application that would needthe use of several existing Microchip libraries andwould benefit from the use of an RTOS.

One area of technology that is currently attracting a lotof attention is energy metering. This is being driven byuser demand and also by government legislation that ismandating the introduction of smart energy meters intopeople's homes. It is hoped that with the addition ofmeters that provide accurate and up to date informa-tion, customers will more actively regulate the amountof energy that they use.

The demand for energy meters is being driven byusers’ demand and also by government legislationmandating the introduction of smart energy meters intohome utility sectors. With the introduction of metersthat provide accurate and up-to-date information, theamount of energy used can be actively regulated.

For our example, a smart meter was designed thatdemonstrated some of the capabilities that would befound in one of the new generation of meters. Theactual requirements may vary, but for this design, thefollowing capabilities were chosen:

• Information to be presented on a QVGA display with touch screen.

• Separate itemized accounts for electricity and gas, detailing the number of ‘units’ used along with the total cost.

• Remote connection to the smart meter, via the Internet, allowing current readings to be viewed and permit forced disconnection of the energy supply. This would simulate users disconnecting the gas supply because it had accidentally been left ON in their absence.

• Remote setting of the energy per unit costs, simulating an energy provider charging the rates.

• Actual readings from the electricity and gas meters provided by an RF link from a remote sensor device.

The last requirement is often needed in residentialinstallations where the energy supply enters the build-ing at some remote location and must be measured atthat point. However, for the convenience of the users,the display must be located within the living space ofthe property, for example, the kitchen.

Demonstrator HardwareThe following components are used to develop thisdemonstration application:

• All of the components should be available off-the-shelf.

• Explorer 16 (DM240001) Development Board and PIC24F Plug-in Module (PIM) that is supplied with the board installed in the processor socket.

To demonstrate the capability of easily scaling theapplication, the software was designed to also runon the PIC32 processor using the separatelyavailable PIC32 PIM (MA320001).

• The Graphics PICtail™ Plus Daughter Board (AC164127) to provide the QVGA graphics display.

• The hardware connection to the Internet was made with the Ethernet PICtail™ Plus Daughter Board (AC164123).

• For the wireless connection to the remote board, the MRF24J40MA PICtail Plus 2.4 GHz RF Card (AC164134) provides the radio link.

• The remote end is built using the standard demonstration application on a PICDEM™ Z MRF24J40MA 2.4 GHz Demo Kit (DM163027-5).

The source code for this PIC18F-based device isprovided in the \PIC18 MiWi Meter directory.

For hardware-specific reasons, the MRF24J40 islocated in the upper part of the PICtail Plus slot onthe Explorer 16, and the Ethernet PICtail Plus isplaced into the lower part of the second slot. If thesecond connector is not populated, then it ispossible to separately obtain the connector andsolder it onto the board (part number CON0197).

The baseline project compiles and executes on thePIC24FJ128GA010 supplied with the Explorer 16; con-sequently, some small concessions to the user interfaceare made because of the 128k Flash limit on that part.On the contrary, the PIC32MX360F512L has morememory and increased processor capacity; as a result,the PIC32 project features enhanced QVGA buttonswith bit-mapped images. This kind of trade-off is typicalof the decisions that are made when designing such aproduct. The PIC32 PIM (MA320001) is available sepa-rately and can be simply installed in the Explorer 16. Thefinal hardware configuration can be seen in Figure 1.

The demo application makes extensive use of the Micro-chip Graphics Library for user interaction. In this case,the physical connection between the processor and thedisplay is via the Parallel Master Port (PMP) peripheral.The MPLAB IDE projects and workspace have beenprovided for the PIC24F and PIC32F processors; how-ever, the software could also easily be run on a PIC24Hor dsPIC device with a suitable PMP peripheral.

DS01264A-page 6 © 2009 Microchip Technology Inc.

Page 7: AN01264a

AN1264

FIGURE 1: DEMONSTRATOR HARDWARE

Note that, with a few exceptions, the program sourcefiles are common to all of the projects regardless of theprocessor family, thus making demonstration an easymigration between 16 and 32-bit processors. Becauseof the use of an RTOS, the different software tasks areeffectively isolated. As a result, even if the MRF24J40PICtail Plus is missing, the demonstration can still bebuilt and tested. This is useful if the user wants to testthe application but does not want to purchase all of thehardware.

IMPLEMENTATIONThis section discusses the specific changes made toeach of the stacks and how they have been modified tocreate the demo application. Note that the modifica-tions have been done in such a way that the changescan be readily recreated when new libraries arereleased. It would be possible to use the modified codein another application by taking the individual task filesand libraries that they use. The mechanisms forinter-task communication can then be modified orrecreated to suit the particular target application.Table B-1 lists all of the RTOS related objects used inthe demonstration application.

For each major task in the code, its operation, along withhow any change to the associated COTS componentswere made, is described. For some components, therecould be interactions between the various elements andother unrelated tasks due to their use of common librarycalls or functions within the Microchip stacks. An exam-ple of this is with the TCP/IP and MiWi NetworkingProtocol Stacks, which require a TICK timer routine tomanage the delays associated with sending data andalso to provide time stamps to messages. Thesecommon functions and the changes to those functionsare explained where most appropriate.

One of the primary objectives in this application is tominimize the amount of modifications to the COTScomponents used in the project. To this end, fewchanges have been made to the core functionality ofeach library and only the highest levels have beenmodified to allow their use in a RTOS environment.Because of this, the basic documentation on the oper-ation of each library is still applicable and the reader isdirected to the relevant library application note to obtainan understanding of how they work.

© 2009 Microchip Technology Inc. DS01264A-page 7

Page 8: AN01264a

AN1264

FreeRTOS ModificationsThe original FreeRTOS installation allocates Timer1 asthe default RTOS timer. This is set to periodically inter-rupt the processor and allow the RTOS to perform apre-emptive context switch to another task if required.Timer1 is also used by default by many of the Microchiplibraries and because of this, it is easier to initiallyre-assign the RTOS TICK timer to Timer5. Anotherreason for this change is that the MiWi P2P networkingprotocol makes extensive use of Timer1, and oftenmanipulates the interrupt flag and enable bits directly,so it is simpler to modify the RTOS source.

This section lists the five timers and the way they areused by the various software elements.

• TMR1 – Used exclusively by the MiWi P2P Networking Protocol Stack.

• TMR2 and TMR3 – Form a 32-bit timer used primarily for the TICK functions. TMR2 is also used by the MiWi Networking Protocol Stack to generate packet sequence numbers.

• TMR4 – Used to sequence the ADC sampling by the touch screen routines.

• TMR5 – FreeRTOS periodic TICK timer.

The licensing conditions of the FreeRTOS are that anychanges made to the real-time kernel, along with thekernel source, must be made available to everyone.However, the modified GPL means that any projectcode that merely calls RTOS functions does not needto be released. This is convenient if we want to producea commercial product and do not want to reveal thesource code of our product.

The following components included in the demoapplication are discussed in the following sections.

UARTMany of the Microchip libraries assume that a UART isavailable for the output of diagnostic information or forconfiguration. It is possible to configure the TCP/IPStack parameters using the serial port and a terminalwindow. Equally, when designing any system, it is use-ful to have some form of simple diagnostic output sothat the operation can be confirmed, and this is partic-ularly true for systems that use an RTOS. To supportthis, a simple UART handling task is created, whichcould accept messages for output via a queue, andthen print each character in the output string to theUART peripheral.

The serial output functions can be found in thetaskUART.c file. The UART code performs thefollowing:

1. An initialization function is used, which createsboth the queues and the UART task itself.

2. The task blocks waiting on data to be receivedon the transmit queue.

3. Once a message is received, it is placed onecharacter at a time into the UART peripheraltransmit buffer.

The task has been given a low priority as it isonly outputting diagnostic information to a serialperipheral, which is inherently slow.

4. Incoming data is handled by an Interrupt ServiceRoutine (ISR).

5. Each received character is placed onto a receivequeue and tasks that require the incoming datacan retrieve it.

This mechanism could be improved upon; how-ever, it is sufficient at present as no tasks in thecurrent application use incoming serial data.

6. A generic UARTprint function is provided,which takes a character array as an argument.

7. It then constructs a message of the correct typeand places the data on the transmit queue.

A problem might arise with the UARTprint functionbeing called by multiple tasks simultaneously. Considera sample scenario where several low-priority tasks callthe function and place a number of messages on thetransmit queue. Since the UART, itself, is slow (runningat only 19200 Baud) this may take some time to print astring. If another high-priority task then attempts to printsome data, it may find the transmit queue full. We couldblock until space is available on the queue; however,the result is that a high-priority task (the sender) iswaiting for a low-priority task (the UART) to complete.

This forms a priority inversion, which is undesirable inany application.

In the case of the metering application, only diagnosticinformation is output, so we have adopted the simpler,if less rigorous, technique of allowing a zero wait timewhen attempting to write to the queue. So, if the queueis full when the high-priority task attempts to write data,it will fail and simply not print the message. It is gener-ally not advisable to have high-priority tasks waiting onlower priority ones, and even though RTOS constructs,such as mutexes can help ease the problem, it is still adesign issue. As a result, it is often difficult to outputdiagnostic information from tasks of different prioritieswithin an application. In the case of operating systemslike Linux, specialized routines, such as printk (printfrom kernel), are provided to help log data during kerneloperations. Their use can slow down the system and soshould be minimized.

DS01264A-page 8 © 2009 Microchip Technology Inc.

Page 9: AN01264a

AN1264

MeterA meterTask is written to control the data related tothe main task of metering.

At initialization, the meter readings are zeroed and thestarting values for the unit costs are set up. There aretwo types of event that can affect or access the meterrelated data:

• Updates can be received from the MiWi Networking Protocol Stack that cause the total number of units used to be incremented.

• Changes to the meter billing rates and control actions can be received from both the Graphical User Interface (GUI) and the TCP/IP connection, and these other tasks may also require updating with the changing meter values.

For both types of updates, the meter task defines thatupdate messages are only received via thehMETERQueue. While values may be read from thegMeter object, at any time, the incoming queue is theonly method by which changes to the data areallowed. This allows the task to block waiting forupdates, and hence, consumes no processor cycleswhen nothing is changing.

The second type of update requires that the totals bemodified, taking into account the current unit cost. How-ever, to complicate matters, there are various tasks thataccess this data using different methods. We use theterm, asynchronous tasks, as those tasks that accessthe data from the meter task when they require it.

For example, the HTTP Server, which in response to aweb page update request (HTTP GET), reads thecurrent values from the gMeter global data structure,formats it into hypertext and returns it to the user via aweb browser. These asynchronous tasks require nofurther action to be taken by the meter task since theywill obtain the new values when they are required.Conversely, there are tasks that need to be informedwhen the gMeter data structure has been updated,and these are termed synchronous tasks. In anygeneric application, this style of interaction is desirablebecause it allows tasks that are dependent upon thedata to block until a change occurs, and hence, notconsume any processor cycles directly polling forchanges.

Because of the need for these updates, changes to theenergy values are sent via queues to the synchronoustasks; in our application, this is limited to the QVGAdisplay task.

Since the meter data is stored in a global data structure,called gMeter, which can be accessed from multipletasks, we must also ensure the consistency of data con-tained within it. The access is regulated by a semaphore(called METERSemaphore), and only when a task ownsthe semaphore, should it read or modify the meter data.

An advantage with synchronous events is that sincethe meter task is responsible for sending the updatemessage, it can also propagate the new value alongwith the message, which simplifies some of the mutualexclusion problems inherent when using a semaphore.Note that while the meter task is the only part of the pro-gram that updates the metering data, it also obtains thesemaphore before modifying the values. This is done toensure that any change occurs as a single atomicsequence and the coherency of the data in gMeter isensured.

MiWi P2P Networking ProtocolThe Microchip MiWi P2P Networking Protocol Stack isdesigned for the interconnection of small, embeddeddevices in a simple network structure. This applicationnote uses the first public release, V 0.1, of the stack.Since this is a simple stack, all of the main functions arecontained within one file called, p2p.c. Further examina-tions of this file revealed that there were numerous callsto printf for diagnostic output purposes. Unfortunately,this makes a large amount of the stack incompatible withour multitasking application design.

For ease of development, a local copy of the p2p.cfile is created in the project source tree, which can thenbe modified without affecting the original file.

As previously noted, the console output functionscould cause hardware access issues. It would havebeen possible to redirect this output to the new UARToutput task. However, for simplicity, the existing func-tions are removed. A conventional P2P applicationkeeps the stack operating by periodically calling theP2PTasks function (which is indirectly called by theReceivedPacket function). This returns TRUE if thedata has been received, and also ensures thatpackets are correctly sent and Acknowledgementsprocessed.

© 2009 Microchip Technology Inc. DS01264A-page 9

Page 10: AN01264a

AN1264

To keep the modifications to the MiWi NetworkingProtocol Stack to a minimum, the majority of the codeis left unaltered and blocking functions are directlyintroduced into the stack itself. The MiWi networkingprotocol task, itself, is responsible for initializing thestack, and connecting to the PIC18F transmitting node,after which it enters a while loop, which performs themain processing. The task is given a low-priority level(just above that of the Idle task) but to prevent it fromstarving out other low-priority tasks and the Idle taskitself, it is made to execute only periodically using thevTaskDelay function, which halts its execution for20 ms. This kind of approach is justified in the case ofthis stack, since the data is sent at a very low rate, andso a 16 or 32-bit processor can easily keep up with themessage updates when executed every 20 ms.

The received messages are of two types:

• Electricity Unit Updates• Gas Unit Updates

The start of each message contains either an E or Gcharacter to distinguish the type and the remainingdata contains the ASCII meter reading values. In a realapplication, other data would also be sent, such astemperature, and any practical application wouldprobably use some form of security or encryption. Thereceived data is then passed to the meter task usingthe hMETERQueue.

One area, which can cause conflict between the vari-ous stacks, is in their use of common functions. While,in an ideal situation, there would be no interactionbetween the various modules, programmers often writecode that replicates functions found in other programsbut with slightly different behavior. Structured program-ming techniques and code re-use can mitigate theseoverlaps but they still occur. In the case of the MiWiNetworking Protocol Stack, the SymbolTime.c fileprovides support for obtaining a high-resolution, 24-bittimer value. Within the code, this data is expressedusing the custom TICK data type.

However, this same data type name is used within theTCP/IP Stack and many of the functions for accessingits elements have the same names in the MiWi Net-working Protocol and TCP/IP Stacks. This would notnormally pose a problem; however, in the TCP/IPStack, the TICK data type is 32 bits in length and soposes a conflict. This is overcome by creating aTick.c file that replicates the functionality of theTCP/IP version and provides a MiWi networking proto-col compatible access function to the enlarged timer(MiWiTickGet). Since the functions within the file areidentically named to the TCP/IP ones, no changes arerequired in that stack and only minor changes arerequired to the MiWi P2P Networking Protocol Stack touse the newly provided function, and these alterationsare all isolated within the single P2P.c file.

QVGA and Touch Screen InterfaceThe Microchip Graphical Software Library allowssoftware engineers and designers to rapidly developcustomized user interfaces on small embedded micro-controllers. The library consists of a hierarchicalsoftware structure that allows programmers to pick themost suitable functionality for their design. At the mostbasic level, it provides a driver interface to many com-mercially available LCD controllers, or LCD panels,with integrated controllers (so called intelligent glass).Above this driver layer, a drawing primitives API allowssimple shapes, such as points, lines and circles, to bedrawn, which displays fonts and bitmaps. Finally, abovethis layer comes the Graphics Object Layer (GOL),which contains functions for drawing and managingentities, such as buttons, sliders, text boxes, dials andso on. For user input, the library provides routines anddrivers for handling both keyboards (or buttons) andresistive touch screens.

When a program uses the higher level items, such asbuttons, they are created dynamically using the stan-dard malloc/free calls and adding them to an activedisplay list. The GOL is then responsible for callingdrawing primitives for each of the widgets that are cur-rently in the display list, forcing them to update andreflect their current state. When a button press isreceived, or as in our case, a press of the touch screenoccurs, the graphics library passes the messagearound all of the objects in the active display list, allow-ing each of them to respond if the press occurred intheir screen area. Example 2 provides the GraphicsObject Layer loop.

EXAMPLE 2: GRAPHICS OBJECT LAYER MAIN LOOP

……while(1) {

// Draw GOL objectsIf (GOLDraw())

{ // Get message from touch screen

TouchGetMsg(&msg); // Process message

GOLMsg(&msg);…

}}

DS01264A-page 10 © 2009 Microchip Technology Inc.

Page 11: AN01264a

AN1264

In the demonstration project provided with the GraphicsLibrary (called Graphics Object Layer Demo), theMainDemo.c file contains a while(1) loop; this isdepicted in Figure 1. When GOLDraw is called, thelibrary iterates through all of the objects in the activedisplay list giving them the opportunity to update andredraw themselves if required. The touch screen isthen checked for any activity and this information ispassed on to the message handling functions for theobjects in the display list. It can be seen that there areno delays in this processing algorithm, and the screenredraw, touch screen and message processing func-tions, will be called as rapidly as the processor willallow.

When any form of user interaction is required, it isdesirable to offer fast cycle times so that the userinterface feels responsive. This polling mechanism issuitable for a dedicated demonstration where this is theonly application that is executing. However, for a multi-tasking system, it has the disadvantage of consumingexcessive processor cycles repeatedly drawing andanalyzing the touch screen, when in fact, in mosttypical applications, the display will actually be dormantand no user interaction is required. Generalizing thisfurther, it can be seen that once the screen has beendrawn, it is unlikely that any further updates will berequired unless either the touch screen is pressed or ameter update occurs, hence, mandating a redraw.

For this demo application, the functionality is separatefrom the GOL library and the touch screen. By makingthe touch screen operate in a separate task it can besimplified and made to operate at a high priority, allowingfor good responsiveness. At the same time, the graphicstask can be made lower priority as it only updates thedisplayed items when it has passed a touch screenpress or a data update. This means that updates causethe display to redraw immediately but at all other times,it blocks, hence consuming no processor cycles whichgive the illusion of high speed.

It is worthwhile examining in some detail how our newimproved ‘broken apart’ graphics library now works.The preceding paragraphs have explained the majorchanges to this library, but it is useful to see thesechanges in context with a diagram.

Some of the techniques used are often found inRTOS-based programs and a programmer can usethem in their own applications. Figure 2 provides thepseudocode for the graphics and touch screen tasks. Itcontains two main blocks showing the basic programflow. The related code can be found in the two files:taskTouchScreen.c and taskGraphics.c. Herewe consider the various numbered stages:

1. The Timer4 Interrupt Service Routine (ISR) istriggered every 1 ms. The touch screen requiresthat a bias voltage be applied to the X or Y axiswhile the reading is being taken. To help thissequencing, the ISR implements a state machinethat iterates through the various analog channelsand performs the required readings. Once areading has been taken, it is placed into volatilevariables for access by the taskTouchScreenfunction.

2. At the start of taskTouchScreen, check if thescreen needs calibrating. As the EEPROM on theExplorer 16 board is accessed by the touchscreen during initialization and the TCP/IP Stackwhen displaying web pages, a simple semaphoreis used to control access. The touch screen taskobtains the EEPROMSemaphore and reads thecalibration data. If it detects that calibration isrequired, then it also obtains control of the QVGAdisplay by obtaining QVGASemaphore anddirectly writing to the screen using drawing primi-tives. While the TCP/IP and QVGA tasks alsoaccess the EEPROM and QVGA display,because the taskTouchScreen is higher prior-ity, it will always be able to obtain the semaphoresand carry out its calibration at program start-up.

3. The main touch screen routine operates in awhile(1) loop. At the start of the loop, the taskblocks for a programmable amount of time. Ini-tially, this block time is set to 100 ms. Once theblock time has elapsed, the current value of thetouch screen ADC conversions are compared tothe previous versions. Only when these do notmatch does the task perform any processing.

4. Once a touch is detected, the task switches to afast scanning rate, where the main loop blocktime is reduced to 10 ms. The inputs areanalyzed, and if the screen has been pressed, aMSG_TOUCH_EVENT message will be sent tohQVGAQueue. The type of event depends on thecurrent action and could be either a pressed,released or a move event.

5. All of the data from taskTouchScreen is sent tothe display using hQVGAQueue. This queue isused by other tasks, such as taskMeter, to sendupdated meter readings asynchronously to thedisplay. This mechanism of sending data onqueues, but prefixing the data with a commandtype message (such as MSG_TOUCH_EVENT orMSG_UPDATE_GAS), is a very common mecha-nism within a RTOS application and allowsefficient use of the message passingmechanisms. Depending on the RTOS, it may bepossible to wait for data to be received simultane-ously on multiple queues; however, if this facilitydoes not exist, then the command and datamethod used here works efficiently.

© 2009 Microchip Technology Inc. DS01264A-page 11

Page 12: AN01264a

AN1264

FIGURE 2: RTOS VERSION OF GRAPHICS AND TOUCH SCREEN

6. In the taskGraphics routine, the main draw-ing is again performed in a while(1) loop.Once the drawing is completed, the task blockswaiting for data to arrive on its hQVGAQueue. Asa portMAX_DELAY parameter is used, the taskwill effectively Sleep until new data arrives or thescreen is pressed.

7. After the arrival of the message, the type ischecked and various actions occur based uponthe command. The statement shown next to thelabel is for the arrival of aMSG_UPDATE_ELECTRIC message, which isused to indicate that a new electricity unit readinghas arrived. The control associated withID_ELECTRIC_TOTAL is obtained, and providedit exists (we may not currently be displaying ascreen with this control on it), a new value todisplay is created and the button is marked asneeding an update.

8. Finally, at the end of the main loop, the generaltouch screen handling is performed whenMSG_TOUCH_EVENT arrives. Here, the messageis translated by the standard GOLMsg function,which will call the control handling functions laterin the same file.

The graphics library is used to display a range ofscreens in the home metering application, as depictedin Figure 3. The summary of the functionality is:

• Figure 3 provides a summary of the meter infor-mation along with a dial for room temperature set-point and a real-time temperature display. On the left of the screen is a display of the current electricity cost, and the button will take the user to screen 2. On the right is the gas usage summary and the button will reveal screen 3. Finally, the upper title bar can be pressed to display screen 4.

• The electricity usage screen displays the total num-ber of units consumed along with the total cost based upon the current unit cost. On/Off buttons disable the logging and a graph at the bottom shows a history. A press of the title bar will return to the main screen.

• The gas screen operates in a similar way to the electricity usage screen.

• Finally, the RTOS summary screen displays infor-mation on the main tasks in the application. For each task a bar graph shows the maximum stack size allocated to that task along with the current position of the stack high water mark; a text equiv-alent is also provided. This information could be used to optimize the amount of stack allocated to each task. At the bottom of the screen the current DNS settings for the TCP/IP Stack are shown.

Sequential Scan ofAnalog Inputs

X, Y,

Temperature, Pot

Timer4 ISR (1 ms)

xSempahoreTake(EEPROM, 0);TouchLoadCalibration(();xSemaphoreGive(EEPROM);...while (1) {vTaskDelay(scan_time);

if (touchXY!=oldtouchXY) {// touch press or movescan_time = FAST_RATE;ÀxQueueSend(hQVGAQueue, data);

} else {// Touch releasescan_time -SLOW_RATE;...

}

}

// graphics task main loopwhile (1) {if (GOLDraw()) {// block until we receive // message from queue. if (xQueueReceive(hQVGAQueue,

&msg, portMAX_DELAY) == pdTRUE) {

switch (msg.cmd) {case MSG_UPDATE_DISPLAY:// periodic screen updates...break;

case MSG_UPDATE_TEMPERATURE:// update temperature...break;

case MSG_UPDATE_ELECTRIC:// update electricpObj = GOLFindObject(

ID_ELECTRIC_TOTAL);if (pObj) {sprintf(qvgaBuff1, "%ld",

msg.data.dVal[0]);SetState((BUTTON*) pObj,

DRAW_UPDATE);}break;

case MSG_UPDATE_GAS_TOTAL:// update gas... break;

case MSG_UPDATE_GAS_UNITS:// update gas...break;

case MSG_TOUCH_EVENT:// process touchscreenGOLMsg(&msg.data.golMsg);break;

}}

}} taskTouchScreen

hQVGAQueue

taskMeter Updates

taskGraphics

1

2

3

4

56

7

8

DS01264A-page 12 © 2009 Microchip Technology Inc.

Page 13: AN01264a

AN1264

Figure 3 depicts the Microchip Metering Demo,Electric, Gas and RTOS summary graphics.

FIGURE 3: GRAPHIC SCREENS

TCP/IPThe demon application has been built upon version 4.51of the Microchip TCP/IP Stack. The stack is designed tooffer a range of Internet protocols and services that com-plement the embedded silicon solutions found in theENC28J60 Ethernet transceiver and newer products.The TCP/IP Stack consists of many software modulesthat can be selectively compiled into the end user appli-cation depending upon the program requirements. Theprovided protocols include, ARP, IP, ICMP, UDP, TCP,DHCP, SNMP, SMTP, SNTP, HTTP, FTP, TFTP andapplication support for a web and telnet server. Withsuch a range of supported protocols and applicationlayers, the TCP/IP Stack is naturally quite large andcomplex. Just like the graphics library, modifications tothe stack are involved and it is best if it can be treated asan integral whole.

The standard method for using the stack with one’sown application is to modify the MainDemo.c file, andintegrate a project-specific ProcessIO handler alongwith the appropriate handlers for any web-basedevents. For more information, refer to the library helpfiles and also AN833, “The Microchip TCP/IP Stack”and AN1120, “Ethernet Theory of Operation”. Theseare the demo metering application specifications.

Considering our specification for the metering applica-tion, we needed to implement a simple HTTP servercapable of displaying web pages from either theon-board EEPROM on the Explorer 16 or with webpages stored directly in program memory on the PIC32Starter Kit. To make network operation as simple aspossible, the stack was configured to use DynamicHost Configuration Protocol (DHCP), and it wasassumed that the device would always be used in anetwork with a suitable DHCP server.

Based upon these requirements the following configu-ration options were selected in the TCPIPconfig.hfile:

• STACK_USE_IP_GLEANING – Obtains an IP address by pinging for an unused address.

• STACK_USE_UART – Allows diagnostic printing via the UART.

• STACK_USE_ICMP_SERVER – Responds to ping requests.

• STACK_USE_ICMP_CLIENT – Sends ping requests.

• STACK_USE_HTTP2_SERVER – New web server.• STACK_USE_DHCP_CLIENT – Automatically

configures the IP address.• STACK_USE_DNS – Resolves addresses via the

domain name server.• STACK_USE_NBNS – NetBIOS names server

support.• STACK_USE_MPFS2 – New style file system for

web pages.• STACK_USE_EEPROM – Support for MPFS files in

EEPROM.

© 2009 Microchip Technology Inc. DS01264A-page 13

Page 14: AN01264a

AN1264

To observe the changes to the TCP/IP Stack, the readershould examine the original TCPIP MainDemo.c fileand compare it with the new taskTCPIP.c file shownin Example 3. The use of an RTOS has resulted in amain network processing task (taskTCPIP) that hasequivalent functionality to the original sample withoutrequiring time consuming rewriting for the RTOS-basedsystem. At the start of the task, a semaphore controllingaccess to the EEPROM is obtained. This is not only nec-essary, since the EEPROM is used by the HTTP serverto store web pages and network addresses, but is alsoused by the graphics library to store screen calibrationinformation.

• Once the graphics library has completed initializa-tion, it will release the semaphore and the TCP/IP Stack can then continue.

• The task then performs initialization of the filing system, application configuration structures and the core stack layers.

EXAMPLE 3: taskTCPIP.c MAIN TASK

• Following initialization, the main task loop is entered.

Here, we have decided to implement a simpleblocking scheme by using a vTaskDelay functioncall of 50 ms. In order to enhance throughput, itwould have been more beneficial to separate thefunctionality of the TCP/IP Stack into various sub-tasks for each block pending upon new data arrivingfrom the various TCP/IP modules. However, this isquite a challenging modification to make for thislibrary given its complex nature and the variousinteractions between the protocols.

• It was decided to minimize the changes to the library by implementing the top level task with a simple timed blocking call, and given the nature of the web pages and the network data rates, this provides for adequate data rates in the meter application.

• Following the delay are calls to the StackTask function, which ensures operation of the lower pro-tocol layers and the StackApplications func-tion, which in turn, runs the high-level applications, such as the HTTP Server.

To prevent hardware conflicts, we must ensure that theEEPROM and Ethernet PICtail Plus are not accessedat the same time; otherwise, their serial data out linescould interfere. To prevent this, replacement files,ENC28J60.c and SPIEEPROM.c, are created in thesource (src) directory. These two files replicate thebehavior of the standard files provided with the TCP/IPStack, except that they have been modified to includean additional semaphore (SPI2Semaphore) to controlaccess to SPI Channel 2. With the use of the currentrelease of the TCP/IP Stack in this application, it isunlikely that simultaneous accesses would occur. How-ever, the use of a semaphore provides an additionallevel of security and a degree of future proofing to theprogram. These replacement files further demonstratethe useful technique of keeping the main stack andlibraries intact, and just modifying a few individual files.

The standard TCP/IP demo application comes with aset of web pages that demonstrate various methods ofinteracting with an embedded HTTP server. Thesepages require more application-specific modificationsfor the metering application. Since all of the web pagesmust fit inside the 32k x 8 EEPROM on the Explorer 16board (or inside the program Flash of the PIC32 StarterKit-based version), they must be compact. At the toplevel of the source tree, a Microsoft® Visual Studio®

development system-based project, WebPages.sln,has been provided which contains all of the web relatedmaterial. Either this tool, or a simple text editor, can beused to customize the pages if required.

These pages demonstrate a range of features permittingremote users to view a summary of the application.Real-time updates on the actual energy used are pro-vided using AJAX techniques that asynchronously querythe data from the embedded device. A password pro-tected page allows the unit costs for gas and electricityto be set remotely in a similar manner to a real worldsystem.

Once the pages are created, they must be convertedinto a format suitable for use in the application. This isdone with the MPFS2.exe utility supplied with theTCP/IP Stack. The WebPages directory is selected asa source and is converted into a file suitable for down-load into the EEPROM. When the application is built forthe PIC32 Starter Kit running on the I/O ExpansionBoard (DM320002), no EEPROM is present so thepages must be stored in the internal program Flash.

void taskTCPIP(void* pvParameter){

//obtain the semaphore //to access the SPI EEPROM xSemaphoreTake(EEPROMSemaphore, portMAX_DELAY);

//Initialize the MPFS2 MPFSInit();//initialize the configuration InitAppConfig();//Initialize the stack StackInit();while (1) {vTaskDelay(50 / portTICK_RATE_MS);//perform stack tasks StackTask();

//call the stack //related applications StackApplications();}

}

DS01264A-page 14 © 2009 Microchip Technology Inc.

Page 15: AN01264a

AN1264

As part of the MPFS conversion sequence, severalsupport files are automatically generated. In the eventthat a change of platform results in any of these fileschanging, then the code will need recompilation. Forreference purposes, original copies for the Explorer 16and I/O Expansion Board systems are provided in thesrc\Explorer16 and Starter Kit Web Filesdirectory.

Another interesting feature is a provision of a dynamicmonitoring page, customized for display on ahand-held PDA. This has its screen layout modified inorder to correctly display on a 240 x 320 pixel PDAusing Internet Explorer® Mobile. The page can beaccessed using the \pda.htm URL.

One final area in the TCP/IP Stack that required modifi-cation was its accesses to the ADC. While in normaloperation, it performs no access to the analog data; atinitialization, it takes control of the ADC in order togenerate a pseudo random number used for packetsequencing. Because of the task priorities that wereassigned at design time, this initialization happens afterthe touch screen task has been started and the result isthat proper ADC interrupts are disabled. It would havebeen possible to rectify this with either a different ran-dom number generator or modifications to the algorithm,but for our purposes, a constant value has been used asthe seed.

General Utility Tasks (TickHook)On a typical embedded system, there may be manyoperations that take only a few cycles to execute andwhich have some time dependency associated withthem. For example, the debouncing of a key switch.Here a change in the state of a switch needs to berecorded and checked again, perhaps 20 ms later toensure that any bounce has been removed, and theswitch has actually been pressed. This could also beperformed within the RTOS task that monitors theswitch or a separate task could be created that is solelyresponsible for monitoring key presses. Unfortunately,this consumes significant memory in creating a newtask for a simple operation.

An alternative approach is to add the required code intothe RTOS TickHook routine. This function is normallycalled every time a RTOS pre-emptive TICK occurs (inthe demo application, this is at 200 Hz). InMainDemo.c, a vApplicationTickHook functionhas been added that is executed every 5 ms. Theevents are counted and after 2 seconds have elapsed,a message is sent to the hMETERQueue and also to thehQVGAQueue, allowing the tasks to update thedisplayed temperature, and perform general periodichousekeeping functions.

It should be noted that the TickHook function is calledas part of the pre-emption ISR. Because of this, anyRTOS related calls must be suitable for use within anISR, and therefore, the xQueueSendToBackFromISRfunctions are used.

© 2009 Microchip Technology Inc. DS01264A-page 15

Page 16: AN01264a

AN1264

GUIDELINESThe main part of this application note is focused on themodifications required in order to allow a number ofMicrochip stacks to be used together in a RTOS appli-cation. We have deliberately kept these changes assimple as possible, since this allows for the shortestdevelopment time, and will permit a simple upgrade asnew versions of the libraries are released. It is difficultto arrive at a fixed set of rules for modifying softwarethat will work in all future cases, but here are a numberof items to consider when modifying any library for anew application.

• Consider all low-level hardware resources, I/O pins and peripherals. If they could be accessed by more than one task at the same time, then the resource should be protected by a mutex using a semaphore or critical section. If they are accessed by more than one task, but only sequentially, then task priorities may be sufficient to protect accesses.

• Having advised the use of critical sections, you should, however, minimize their use as they will typically cause interrupts to be disabled for their duration, possibly preventing execution of other tasks.

• Analyze the libraries and your own application code for delay loops or calls to delay functions. These delay functions should be replaced with calls to the RTOS provided delay functions, as this will allow other tasks to execute if required.

• Check for state machines with delay states, where the code stops at a particular stage waiting for an event to occur. If possible, replace potentially long waits with calls that block waiting for a semaphore or queue event. This may require the creation of another task that can signal the event so it could incur a memory or performance penalty.

• Any libraries that are dependent upon slow exter-nal events can potentially have separate tasks created to handle these asynchronous events.

• Application code, and indeed a number of the libraries, will often have common functions. It is fairly obvious that these functions should be replaced with local alternatives that reduce code size. However, when performing these changes, be aware that they may introduce mutual exclusion and atomic access problems if called by multiple tasks.

• Rather than introducing a mutex to prevent multiple tasks from accessing a shared resource, use a ‘gatekeeper’ task to regulate access. Multiple tasks can then send messages to the gatekeeper requesting operations to be per-formed without introducing a mutex. These messages can be sent using queues, rather than global memory blocks, which will simplify future code changes if required.

• Allow COTS components and libraries to be installed in their default locations. However, any modifications that are required should be per-formed upon local copies of the files placed in the project source directory. This ensures the integrity of the original library installation, and if done cor-rectly, the project relative paths will ensure the include files are located easily.

• When upgrading the libraries, they can be installed to their default locations as normal, avoiding overwriting the modified local copies. But it is necessary to ensure that changes to the library files are correctly reflected in the local copies and this can be achieved via a ‘diff’ utility, which will identify the differences.

DS01264A-page 16 © 2009 Microchip Technology Inc.

Page 17: AN01264a

AN1264

CONCLUSIONThis application note describes how to use a Real-TimeOperating System (RTOS) designed for embeddedmicrocontrollers to simplify the task of integratingmultiple software libraries into one application. Thedemo application uses FreeRTOS; any one of thealternatives listed in Table 1 could be used instead.

Microchip provides source code for its applicationlibraries which allows them to be more easily modifiedand integrated into a multi-library RTOS-based applica-tion. This would not be possible if they were provided inbinary form only.

The demo application demonstrates how a feature richproduct can be generated using COTS components. Ifthe code is examined in detail, it can be seen that thenumber of program lines that implement the smartmeter functionality is small compared to the size of thelibrary code. This has resulted in an application thatcould be written in a much shorter amount of time thanif all of the code had to be written from scratch. It alsodemonstrates that complex products can be built withsmall 16 and 32-bit embedded microcontrollers in amore cost-effective manner than with complicatedmicroprocessor-based solutions that require manymegabytes of RAM in order to run systems, such asLinux.

The modifications to the Microchip MiWi networkingprotocol, graphics and TCP/IP libraries could be simplycopied into a new application with minimal changes.Some guidelines have been provided that would allowthe programmer to replicate these modifications in theirown project if required.

REFERENCES• “dsPIC30F/33F Programmer's Reference Manual”

(DS70157)• “16-Bit Language Tools Libraries” (DS51456)• “MPLAB® C32 C Compiler User’s Guide”

(DS51686)• AN833, “The Microchip TCP/IP Stack” (DS00833)• AN1120, “Ethernet Theory of Operation”

(DS01120)• AN1136, “How to Use Widgets in Microchip

Graphics Library” (DS01136)• AN1066, “MiWi™ Wireless Networking Protocol

Stack” (DS01066)• AN1204, “Microchip MiWi™ P2P Wireless

Protocol” (DS01204)• FreeRTOS – http://www.freertos.org

© 2009 Microchip Technology Inc. DS01264A-page 17

Page 18: AN01264a

AN1264

APPENDIX A: FUNCTION CALLS

EXAMPLE A-1: FreeRTOS.org FUNCTIONxTaskCreate(tskFunc, sName, stkSize, param, priority, &handle);

tskFunc - pointer to the task functionsName - task name stringstkSize - size of the stack in wordsparam - a parameter to be passed to the taskpriority - priority of the taskhandle - pointer to the created task handle

xSemaphoreTake(semaphore, timeout);semaphore - handle of a semaphoretimeout - delay timeout (ticks), portMAX_DELAY waits forever

xSemaphoreGive(semaphore);semaphore - handle of a semaphore

xQueueSend(hQueue, &msg, timeout);hQueue - handle to the queuemsg - pointer to data to place on the queue (size varies)timeout - delay timeout (ticks), portMAX_DELAY wait forever

xQueueSendToBackFromISR(hQueue, &msg, &flag);hQueue - handle of the queuemsg - pointer to data to be placed on queueflag - indicates if another task was woken as a result of the send

vTaskDelay(ticks);ticks - delay specified number of ticks

portENTER_CRITICAL();start a critical section, forming an atomic action, disables interrupts

portEXIT_CRITICAL();leave a critical section

DS01264A-page 18 © 2009 Microchip Technology Inc.

Page 19: AN01264a

AN1264

APPENDIX B: RTOS RESOURCESTable B-1 lists the available RTOS resources.

TABLE B-1: DEMONSTRATOR RTOS RESOURCESResource Object Name Inputs Outputs Function

Task taskMeter METERQueue Updates to QVGAQueue Control meter updatesTask taskMiWi Updates Meter via

METERQueueReceive RF updates from PIC18F node

Task taskUART UARTTxQueue Displays diagnostic information via UART

Task taskGraphics QVGAQueue Accesses gMeter Directly

All screen related output and input; direct access to gMeter object

Task taskTouchScreen ADC Readings Touch Events via QVGAQueue

Handle touch screen calibration and processing

Task taskTCPIP Accesses gMeter Directly

Updates Meter via METERQueue

All TCP/IP and Web-related services

Queue METERQueue Meter updates of temperature, units and unit costs

Queue QVGAQueue Meter updates and touch screen actions

Queue UARTTxQueue Data to be transmittedQueue UARTRxQueue Unused

Semaphore QVGASemaphore Regulate access to PMP and screen

Semaphore METERSemaphore Regulate access to global gMeter data structure

Semaphore EEPROMSemaphore Regulate access to EEPROMSemaphore SPI2Semaphore Regulate access to SPI

channel, used by EEPROM functions and TCP/IP functions

Critical Section LEDUtils.c Isolates Modifications to LED Port

Accesses to port on PIC24F are protected by critical section

Critical Section Tick.c Isolates Timer Calculations

Ensures 32-bit timer overflows are atomic actions

© 2009 Microchip Technology Inc. DS01264A-page 19

Page 20: AN01264a

AN1264

B.1 Resource Interdependency

FIGURE B-1: DIAGRAM OF RESOURCE INTERDEPENDENCY

Met

erD

ata

METER

MiWi™ P2P

taskMiWi

TCP/IPtaskTCPIP

UARTtaskUART

MetertaskMeter

GraphicstaskGraphics

Touch ScreentaskTouchScreen

EE

PR

OM

METERQueue

EEPROMQVGA Display

QVGASemaphore

QVGAQueueSPI2

UARTTxQueue

Key

Access Data(Using Semaphore)

Semaphore

Message

Queue

Task

Dat

a O

bjec

tM

iWi P

2P L

ink

NetworkingProtocol

DS01264A-page 20 © 2009 Microchip Technology Inc.

Page 21: AN01264a

Note the following details of the code protection feature on Microchip devices:• Microchip products meet the specification contained in their particular Microchip Data Sheet.

• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions.

• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.

• Microchip is willing to work with the customer who is concerned about the integrity of their code.

• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”

Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.

Information contained in this publication regarding deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS FOR PURPOSE. Microchip disclaims all liabilityarising from this information and its use. Use of Microchipdevices in life support and/or safety applications is entirely atthe buyer’s risk, and the buyer agrees to defend, indemnify andhold harmless Microchip from any and all damages, claims,suits, or expenses resulting from such use. No licenses areconveyed, implicitly or otherwise, under any Microchipintellectual property rights.

© 2009 Microchip Technology Inc.

Trademarks

The Microchip name and logo, the Microchip logo, dsPIC, KEELOQ, KEELOQ logo, MPLAB, PIC, PICmicro, PICSTART, rfPIC and UNI/O are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor, MXDEV, MXLAB, SEEVAL and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A.

Analog-for-the-Digital Age, Application Maestro, CodeGuard, dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, FanSense, HI-TIDE, In-Circuit Serial Programming, ICSP, Mindi, MiWi, MPASM, MPLAB Certified logo, MPLIB, MPLINK, mTouch, Octopus, Omniscient Code Generation, PICC, PICC-18, PICDEM, PICDEM.net, PICkit, PICtail, PIC32 logo, REAL ICE, rfLAB, Select Mode, Total Endurance, TSHARC, UniWinDriver, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.

All other trademarks mentioned herein are property of their respective companies.

© 2009, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.

Printed on recycled paper.

DS01264A-page 21

Microchip received ISO/TS-16949:2002 certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California and India. The Company’s quality system processes and procedures are for its PIC® MCUs and dsPIC® DSCs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.

Page 22: AN01264a

DS01264A-page 22 © 2009 Microchip Technology Inc.

AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support: http://support.microchip.comWeb Address: www.microchip.comAtlantaDuluth, GA Tel: 678-957-9614 Fax: 678-957-1455BostonWestborough, MA Tel: 774-760-0087 Fax: 774-760-0088ChicagoItasca, IL Tel: 630-285-0071 Fax: 630-285-0075ClevelandIndependence, OH Tel: 216-447-0464 Fax: 216-447-0643DallasAddison, TX Tel: 972-818-7423 Fax: 972-818-2924DetroitFarmington Hills, MI Tel: 248-538-2250Fax: 248-538-2260KokomoKokomo, IN Tel: 765-864-8360Fax: 765-864-8387Los AngelesMission Viejo, CA Tel: 949-462-9523 Fax: 949-462-9608Santa ClaraSanta Clara, CA Tel: 408-961-6444Fax: 408-961-6445TorontoMississauga, Ontario, CanadaTel: 905-673-0699 Fax: 905-673-6509

ASIA/PACIFICAsia Pacific OfficeSuites 3707-14, 37th FloorTower 6, The GatewayHarbour City, KowloonHong KongTel: 852-2401-1200Fax: 852-2401-3431Australia - SydneyTel: 61-2-9868-6733Fax: 61-2-9868-6755China - BeijingTel: 86-10-8528-2100 Fax: 86-10-8528-2104China - ChengduTel: 86-28-8665-5511Fax: 86-28-8665-7889China - Hong Kong SARTel: 852-2401-1200 Fax: 852-2401-3431China - NanjingTel: 86-25-8473-2460Fax: 86-25-8473-2470China - QingdaoTel: 86-532-8502-7355Fax: 86-532-8502-7205China - ShanghaiTel: 86-21-5407-5533 Fax: 86-21-5407-5066China - ShenyangTel: 86-24-2334-2829Fax: 86-24-2334-2393China - ShenzhenTel: 86-755-8203-2660 Fax: 86-755-8203-1760China - WuhanTel: 86-27-5980-5300Fax: 86-27-5980-5118China - XiamenTel: 86-592-2388138 Fax: 86-592-2388130China - XianTel: 86-29-8833-7252Fax: 86-29-8833-7256China - ZhuhaiTel: 86-756-3210040 Fax: 86-756-3210049

ASIA/PACIFICIndia - BangaloreTel: 91-80-3090-4444 Fax: 91-80-3090-4080India - New DelhiTel: 91-11-4160-8631Fax: 91-11-4160-8632India - PuneTel: 91-20-2566-1512Fax: 91-20-2566-1513Japan - YokohamaTel: 81-45-471- 6166 Fax: 81-45-471-6122Korea - DaeguTel: 82-53-744-4301Fax: 82-53-744-4302Korea - SeoulTel: 82-2-554-7200Fax: 82-2-558-5932 or 82-2-558-5934Malaysia - Kuala LumpurTel: 60-3-6201-9857Fax: 60-3-6201-9859Malaysia - PenangTel: 60-4-227-8870Fax: 60-4-227-4068Philippines - ManilaTel: 63-2-634-9065Fax: 63-2-634-9069SingaporeTel: 65-6334-8870Fax: 65-6334-8850Taiwan - Hsin ChuTel: 886-3-6578-300Fax: 886-3-6578-370Taiwan - KaohsiungTel: 886-7-536-4818Fax: 886-7-536-4803Taiwan - TaipeiTel: 886-2-2500-6610 Fax: 886-2-2508-0102Thailand - BangkokTel: 66-2-694-1351Fax: 66-2-694-1350

EUROPEAustria - WelsTel: 43-7242-2244-39Fax: 43-7242-2244-393Denmark - CopenhagenTel: 45-4450-2828 Fax: 45-4485-2829France - ParisTel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79Germany - MunichTel: 49-89-627-144-0 Fax: 49-89-627-144-44Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781Netherlands - DrunenTel: 31-416-690399 Fax: 31-416-690340Spain - MadridTel: 34-91-708-08-90Fax: 34-91-708-08-91UK - WokinghamTel: 44-118-921-5869Fax: 44-118-921-5820

WORLDWIDE SALES AND SERVICE

03/26/09