Home

SE350 Project Manual - Electrical and Computer Engineering

image

Contents

1. o o 36 ii td be 64 So aa Ee dead 37 bok SoM oe e Ee eA ed owed we aed 37 7 4 Keil IDE A default new project a 38 aee o A a 38 oe oe ge A a e 38 A Se HRS Kd ee sD 39 7 8 Keil IDE Add Source File to Source Group 39 Oh Ae as Re DR A 40 110 Keil IDE Create New File 2 25 ee ewe dee eee RR ewe eee 40 7 11 Keil IDE Final Project Setting o 40 7 12 Keil IDE Build Target 2446462480244 tadas ira dead 41 7 13 Keil IDE Build Target area a a e A 41 7 14 Keil IDE Download Target to Flash a 41 7 15 Keil IDE Debugging ance eo Bers E Ma Sw AAA 43 vil 7 16 startup LPC17xx s excerpt o ooo o 43 7 17 Keil IDE Using Simulator for Debugging o 43 7 18 Keil IDE Using Simulator for Debugging 44 Aca de e dc a 44 o 45 8 1 Role o OVMISIA 5 e iuris ered ee Soe we Bee we a Re bi g 49 eh awe ea ee ee TEE 50 a Geode Bh Wi eek Oe a a ee ae 51 8 4 CMSIS NVIC Functions secos ee eee BEd Beek wes 51 TOTOY 65 A 2 MDK ARM Installation Steps Finish 0 66 e 66 viii Preface The University of Waterloo Software Engineering SE SE350 course laboratory project is to design a small real time executive RTX and implement it on a Keil MCB1700 board populated with an NXP LPC1768 microcontroller The main purpose of this document is a quick reference guide of the r
2. Notes e Process C has a local message queue distinct from the incoming message queue maintained by the RTX onto which it enqueues in FIFO order messages which arrive while it hibernates It processes these mes sages later 14 e For your own testing set the priority levels for processes A B and C to values which are most likely to cause memory block depletion in the RTX During project demo you may be asked to re initialize your RTX with TA instructor specified priorities for A B and C and vary the total number of message enve lopes available 3 4 Process ID Assignment To facilitate the project evaluation we enforce the process ID assignment rule listed in Table process ID Process Process ID Process 0 Null 8 B 1 Test 1 9 C 2 Test 2 10 Set process priority process 3 Test 3 11 Wall clock display 4 Test 4 12 KCD 5 Test 5 13 CRT 6 Test 6 14 Timer i process T A 15 UART i process Table 3 1 Required RTX Processes 15 Chapter 4 RTX Initialization To make the RTX more generally applicable the RTX will be configured at initialization as specified in the RTX Configuration Table This table has three sections 1 Memory configuration section memory block size number of memory blocks created 2 System process section 3 Application process section Chapter 8 Required Processes lists the processes to be created Each entry contains the following d
3. e The WS hh mm ss command sets the current wall clock time to hh mm ss starts the clock running and causes display of the current wall clock time on the console CRT The display will be updated every sec ond e The WT command will cause the wall clock display to be terminated 3 3 3 Set Priority Command Process This process registers itself with the Keyboard Command Decoder process as the handler for the ZC command The C command has two parameters C process_id new_priority where process_id and new_priority are integers This command changes the priority of the specified process process_id to new_priority The change in priority level is immediate It could also affect the target processs position on a ready queue or a blocked resource queue The parameters must be verified to ensure a valid process_id and priority level is given A C command with illegal parameters will be ignored with an error message printed on the console 12 3 3 4 Stress Test Processes An important category of software tests are the stress tests These tests seek to verify the behaviour of the system under heavy stress scenarios One such scenario is depletion or near depletion of system resources For the demonstration of this project you will implement three processes whose behaviour is described below The stress scenario being tested is depletion of memory blocks Process A p lt request_memory_block register with Command Decoder as handler of Z
4. 8 3 3 System Exceptions ccoo 445445 b4 544 dre 8 3 4 Intrinsic Functions 8 3 5 Vendor Peripherals 40 a lt 4 lt ose a lt Glew kh ee se eR 8 4 Accessing C Symbols from Assembly 008004 8 5 UART Programming isso Bk ea Oa ea SSS EG SES 8 6 Timer Programming si oe hak A eR A lv A MDK ARM Installation References 65 67 69 List of Tables 1 Project Deliverable Weight and Deadlines Replace the id in Gid with the two digit group ID 22228 ee ee eee ee we ee we 3 2 Bi weekly Office Hour Schedule ooa aaa o 4 3 1 Required RIX Processes o0 aa 0 o as 15 6 1 Summary of processor mode execution privilege level and stack use options 29 6 2 LPC1768 Memory Map 2a op a a we e GE Eo 30 6 3 LPC1768 Exception and Interrupt Table 31 6 4 EXC RETURN bit fields 2444 2044544 248440484 a 33 6 5 EXC RETURN Values on Cortex M3 aaa aaa RE a Es 33 8 1 Assembler instruction examples o 47 8 2 Core Registers and AAPCS Usage oo oaa 48 8 3 CMSIS intrinsic functions eo oa a da as 53 vi List of Figures hee en eee hk ee he eo a 24 Ci Ek tk Sh Ok Fe awe be ee 24 sath hoot is e QQ we Glee te Soe a ee OD 25 a ee A A ANA ee 26 RAN ee MO ee A ee aR 27 6 6 Cortex M3 Operating Mode and Privilege Level 2 28 phe a a Eb a aa 32 7 1 Keil IDE Create a New Project
5. The Cortex Microcontroller Software Interface Standard CMSIS was developed by ARM It provides a standardized access interface for embedded software products see Figure 8 1 This improves software portability and re usability It enables software solution suppliers to develop products that can work seamlessly with device libraries from various silicon vendors 2 Microcontroller Software Device driver library hardware Application software Cortex M3 Cortex MO Cortex M1 Embedded os Middleware Figure 8 1 Role of CMSIS 5 The CMSIS uses standardized methods to organize header files that makes it easy to learn new Cortex M microcontroller products and improve software portability With the lt device gt h e g LPC17xx h and system startup code files e g startup_LPC17xx s your program has a common way to access e Cortex M processor core registers with standardized definitions for NVIC Sy sTick MPU registers System Control Block registers and their core access functions see core_cm x ch files e system exceptions with standardized exception number and handler names to allow RTOS and middleware components to utilize system exceptions without having compatibility issues e intrinsic functions with standardized name to produce instructions that cannot be generated by IEC ISO C e system initialization by common methods for each MCU Fore
6. 0 MSP is used When bit 1 of the CONTROL register is 1 PSP is used e R14 LR is the link register The return address of a subroutine is stored in the link register when the subroutine is called e R15 PC is the program counter It can be written to control the program flow e Special Registers are as follows Program Status registers PSRs Interrupt Mask registers PRIMASK FAULTMASK and BASEPRI Control register CONTROL When at privilege level all the registers are accessible When at unprivileged user level access to these registers are limited 27 6 2 2 Processor mode and privilege levels The Cortex M3 processor supports two modes of operation Thread mode and Handler mode e Thread mode is entered upon Reset and is used to execute application software e Handler mode is used to handle exceptions The processor returns to Thread mode when it has finished exception handling Software execution has two access levels Privileged level and Unprivileged User level e Privileged The software can use all instructions and has access to all resources Your RTOS kernel functions are running in this mode e Unprivileged User The software has limited access to MSR and MRS instructions and cannot use the CPS instruction There is no access to the system timer NVIC or system control block The software might also have restricted access to memory or peripherals User processes such as the wall clock proce
7. 2 Demonstration The first three deliverables of the project is evaluated by demonstration in the SE350 RTX Lab room 5 2 1 Demo Reservation and Cancellation e Use the Course Book System to reserve a time slot for a demo e You may cancel a demo reservation 48 hours before the reserved deo time slot starts by using the course book system 5 2 2 The Demo Policy e During the demo of your project your original submitted RTX implementation archive file will be retrieved and the demo will use those files in the archive No substitutions are allowed e The demo is not some dry run to do additional debugging under live conditions If minor bugs are discovered during the demo depending on the complexity you might be allowed to fix the bug recompile and download and continue the demo Under no circumstances will file replacements be allowed during the demo fixes are basically limited to minor manual editing of a source file Each demo for P1 and P2 is scheduled for a 30 minute slot maximum The P3 demo slot is 50 minutes maximum e You are only allowed to demo once e ALL project group members are required to be presented during the demonstrations 19 5 2 3 The Demo Procedure P1 Demo Procedure e Basic Functionality Demo You will need to demonstrate you have successfully completed the required APIs by using your own six test processes e Source Code Spot Check An evaluator will ask each group member implementation
8. 20 Store word in R1 to memory address SP 20 MRS Rd spec_reg Move from special register to general register MRS RO MSP Read MSP into RO MRS RO PSP Read PSP into RO MSR spec_reg Rm Move from general register to special register MSR MSP RO Write RO to MSP MSR PSP RO Write RO to PSP PUSH reglist Push registers onto stack PUSH R4 R11 LR push in order of decreasing the register numbers POP reglist Pop registers from stack POP R4 R11 PC pop in order of increasing the register numbers BL label Branch with Link BL func Branch to address labeled by funC return address stored in LR BLX Rm Branch indirect with link BLX R12 Branch with link and exchange Call to an address stored in R12 BX Rm Branch indirect BX LR Branch to address in LR normally for function call return Table 8 1 Assembler instruction examples 47 C compiler follows the AAPCS to generate the assembly code Table lists registers used by the AAPCS Register Synonym Special Role in the procedure call standard r15 PC The Program Counter r14 LR The Link Register r13 SP The Stack Pointer full descending stack r12 IP The Intra Procedure call scratch register rll v8 Variable register 8 r10 v7 Variable register 7 r9 v6 Platform register SB The meaning of this register is defined by platform standard TR r8 vo Variable register 5 r7 v4 Variable register 4 r6 v3 Variable register 3 r5 v2 Variable register 2 r4
9. 4 LPC17xx User Manual Rev2 0 2010 J Yiu The Definitive Guide to the ARM Cortex M3 Newnes 2009 89 w al 69
10. 6 oe a oS ER 5 2 1 Demo Reservation and Cancellation 5 2 2 The Demo Policy A II Keil MCB1700 Quick Reference Guide 6 Keil MCB1700 Hardware Environment 6 1 MCB1700 Board Overview 6 2 Cortex M3 Processor 6 2 Registers oa ei SOR 6 2 2 Processor mode and privilege levels 111 10 10 11 11 12 12 13 15 16 17 17 17 17 18 18 19 19 19 20 22 PA 2 sos IIED 6 3 Memory WIAD osu Ao Soe oe ee eee A ee bas a enya Me a Be ge ee gs ee 6 4 1 Vector Tablel so s sac ek be a ERE RGR A A EHR OS 6 4 2 Exception Entry eze bis asa eR She Mie da HE ce aa ee oot ee ee ee ee ere Bee eee ee nasa oe ee Se bey Oo 6 a A Bene E 7 Keil Software Development Tools 8 7 1 Creating an Application in yVision4 IDE 7 1 1 Create a New Project 24 lt 4 4 22444 2444 a 46 52 7 1 2 Managing Project Components 2 265414 a 464 bea es 7 1 3 Build and Download 126 464 ae b enw ebay e eR eae e EO E Se eee Le Che ee ee ee ee aR ee DE we ASS REN AAA 7 2 3 Configure In Memory Execution Using ULINK Cortex Debugger Programming MCB1700 8 1 The Thumb 2 Instruction Set Architecturel 8 2 ARM Architecture Procedure Call Standard AAPCS 8 3 Cortex Microcontroller Software Interface Standard CMSIS amp 31 OMSTS fles lt o Pte ane e OG ee ee a ee eee ee G 8 3 2 Cortex M Core Peripherals o
11. IR BIT 0 ack interrupt see section 21 6 1 on pg 493 of LPC17XX_UM g_timer_countt Listing 8 6 Timer0 IRQ Sample Code timer c 64 Appendix A MDK ARM Installation There is only a windows port for the Keil MDK ARM for now The MDK ARM V4 60 0 0 direct download link is inside the Learn http learn uwaterloo ca During the process of the installation of the MDK ARM you will be asked to add example code Choose Keil NXP MCB1xxx Boards example projects see Figure A 1 x TM File installation completed gt KE i L Tools by ARM Wision Setup has installed all files successfully IV Add example projects to the recently used project list Preselect Example Projects for Keil NXP MCB1xxx Boards Keil Nuvoton Board Keil NP MEB1 xxx Boards Keil NP MCB2xxx Boards Keil STM MCBST 3xxx Boards Keil STM MCBST xxx Sxx Boards Keil Luminary MCBLM3S Board Keil TI MCBTMS570 Board Keil Tashihal MCR TMPM yey Rnarde Kelly Cancel Figure A 1 MDK ARM Installation Steps Choose Example Projects The latest version of MDK ARM is at Keil website http www keil com download product How ever the lab manual is written for V4 60 0 0 We haven t tested the latest version 65 TT x Keil pVision4 Setup completed gt KE i L MDK ARM 4 20 Tools by ARM Wision Setup has performed all requested operations successfully Y Launch Driver I
12. Target Output Listing User C C Asm Linker Debug Utiities Conditional Assembly Control Symbols Define NO_CRF Undefine Figure 7 17 Keil IDE Using Simulator for Debugging 43 7 2 2 Simulation Most of the development normally is done under the simulation mode The default setting of the project uses the simulator to debug as shown in the target option see Figure Instead of load the program to the board for execution you can run the code using the Es 3 Options for Target HelloWorld SIM Device Target Output Listing User C C Asm Linker Debug Utities Settings Use JULINK Cortex Debugger _x Settings Limit Speed to Real Time IV Load Application at Startup V Run to main IV Load Application at Startup I Run to main Initialization File Initialization File A le Figure 7 18 Keil IDE Using Simulator for Debugging debugger under simulation mode 7 2 3 Configure In Memory Execution Using ULINK Cortex De bugger When you debug hardware related problems you most likely will find the ULINK Cortex Debugger is helpful You need to configure the debugger as shown in Figure e Use ULINK Cortex Debugger y Settings Use Simulator Settings Limit Speed to Real Time IV Load Application at Startup Y Runto main IV Load Application at Startup Run to main Initialization File itialization File AE E a es Figure 7 19
13. This primitive delivers to the destination process identified by process_id a message carried in a message envelope The message_envelope argument is a pointer to caller defined structure of the following general form struct msgbuf 4 int mtype user defined message type char mtext 1 body of the message y The mtype field takes a user defined message type And the following macro defines the value of this field DEFAULT A general purpose message KCD_REG A message to register a command with the Keyboard Command Decoder Process see Sectoin 3 1 2 These macros are defined in rtx h file as follows define DEFAULT 0 define KCD_REG 1 You are free to add more user defined message type macros The mtext field is an array or other structure whose size is limited to the size of one memory block less size of type field in the msgbuf structure The primitive changes the state of destination process to ready to execute if appropriate The sending process is preempted if the receiving process was blocked waiting for a message and has higher priority otherwise the sender continues executing void receive_message int sender_id This is a blocking receive If there is a message waiting a pointer to the message envelope containing it will be returned to the caller If there is no such message the calling process blocks and another process is selected for execution The sender of the message is identified through se
14. as a C subroutine When the exception return instruction is executed the following exception return se quences happen e Unstacking The registers i e exception stack frame pushed to the stack will be restored The order of the POP will be the same as in stacking The SP will also be changed back e NVIC register update The active bit of the exception will be cleared The pending bit will be set again if the external interrupt is still asserted causing the processor to reenter the interrupt handler 6 5 Data Types The processor supports 32 bit words 16 bit halfwords and 8 bit bytes It supports 64 bit data transfer instructions All data memory accesses are managed as little endian 34 Chapter 7 Keil Software Development Tools The Keil MDK ARM development tools are used for MCB1700 boards in our lab The tools include e Vision4 IDE which combines the project manager source code editor and program debugger into one environment e ARM compiler assembler linker and utilities e ULINK USB JTAG Adapter which allows you to debug the embedded programs running on the board The MDK Lite is the evaluation version and does not require a license However it has a code size limit of 32KB which is adequate for your course projects The MDK Lite version 4 60 0 0 t is installed on all lab computers If you want to install the software on your own computer Appendix A gives detailed instruction 7 1 Creating an Applic
15. bus interfaces hence they can be carried out at the same time e Register Updates After the stacking and vector fetch are completed the exception vector will start to execute On entry of the exception handler the following registers will be updated as follows SP The SP MSP or PSP will be updated to the new location during stacking Stacking from the privileged unprivileged thread to the first level of the ex ception handler uses the MSP PSP During the execution of exception handler routine the MSP will be used when stack is accessed PSR The IPSR will be updated to the new exception number 32 PC The PC will change to the vector handler when the vector fetch completes and starts fetching instructions from the exception vector LR The LR will be updated to a special value called EXC_RETURN This indicates which stack pointer corresponds to the stack frame and what operation mode the processor was in before the exception entry occurred Other NVIC registers a number of other NVIC registers will be updated For example the pending status of exception will be cleared and the active bit of the exception will be set 6 4 3 EXC RETURN Value EXC_RETURN is the value loaded into the LR on exception entry The exception mechanism relies on this value to detect when the processor has completed an exception handler The EXC_RETURN bits 31 4 is always set to OxFFFFFFF by the processor When this value is loade
16. well you are free to implement other hot keys to help in debugging For example a hot key which lists the processes their priorities their states or another which prints out the number of memory blocks available Like all other debug prints the hot key implementation should be wrapped in ifdef _DEBUG_HOTKEYS endif preprocessor statements and should be turned off during automated testing If the auto mated test processes fail you may be asked to turn the hot keys on again in determining why the test processes are failing Another hot key debug printout may be used to display recent interprocess message passing A circular log buffer keeps track of the 10 most 10 recent send_message and receive_message invocations made by the processes upon re ceiving a specific hot key these most recent 10 sent and 10 received messages are printed to the debug con sole The number 10 is used only as an example The information printed could contain information such as e Sender process id Destination process id Message type First 16 bytes of the message text The time stamp of the transaction using the RTX clock 3 3 User Processes These processes operate at unprivileged level and will be used to demonstrate the operation of your system 3 3 1 User Level Test Process Write up to six user level test processes to test your own OS These test processes should run at unprivileged level and do not assume any kernel level data stru
17. 5 20139 15PM C Figure 7 8 Keil IDE Add Source File to Source Group int main SystemInit uart0_init uart0_put_string Hello World n r return 0 Then add main c to the Source Code group Your final project would look like the screen shot in Figure 39 Project a El 0 43 HelloWorld SIM 6 3 Startup Code A startup_LPC1 72 as System Code af system_LPC17r0x Bs Source Code 2 uart_polling c Figure 7 9 Keil IDE Updated Project Profile Fil Edit View Project Flash Figure 7 10 Keil IDE Create New File Project a 1 43 HelloWorld SIM 1 include lt LPC17xx h gt 4 3 Startup Code 2 include uart polling h ow E startup_LPC1 Dos 3 int main 3 3 System Code 4 SystemInit i 5 uartO init system_LPC17xx c i ft 6 uartO put string Hello World n r 8 3 Source Code 7 i return 0 uart_polling c 2 i E main c a Figure 7 11 Keil IDE Final Project Setting 7 1 3 Build and Download To build the target click the Build button see Figure 7 12 If nothing is wrong the build output window at the bottom of the IDE will show a log similar like the one shown in Figure To download the code to the board click the Load button see Figure 7 14 The download is through the Ulink Me You will need a terminal emulator such as PuTTY that talks directly to COM ports in 40 File Edit View Project Flash OS s ma
18. FFF 8 KB Boot ROM 0x2000 0000 to On chip SRAM 0x2007 C000 0x2007 FFFF AHB SRAM bank0 16 KB Ox3FFF FFFF typically used for 0x2008 0000 0x2008 3FFF AHB SRAM bank1 16 KB peripheral data GPIO 0x2009 C000 0x2009 FFFF GPIO 0x4000 0000 to APB Peripherals 0x4000 0000 0x4007 FFFF APBO Peripherals Ox5FFF FFFF 0x4008 0000 0x400F FFFF APB1 Peripherals AHB peripherals 0x5000 0000 0x501F FFFF DMA Controller Ethernet interface and USB interface OxE000 0000 to Cortex M3 Private 0xE000 0000 OxEOOF FFFF Cortex M3 private registers NVIC OxEOOF FFFF Peripheral Bus PPB MPU and SysTick Timer et al Table 6 2 LPC1768 Memory Map 6 4 Exceptions and Interrupts The Cortex M3 processor supports system exceptions and interrupts The processor and the Nested Vectored Interrupt Controller NVIC prioritize and handle all exceptions The processor uses Handler mode to handle all exceptions except for reset 6 4 1 Vector Table Exceptions are numbered 1 15 for system exceptions and 16 and above for external interrupt inputs LPC1768 NVIC supports 35 vectored interrupts Table 6 3 shows system exceptions and some frequently used interrupt sources See Table 50 and Table 639 in 4 for the complete exceptions and interrupts sources On system reset the vector table is fixed at address 0x00000000 Privileged software can write to the VTOR within the System Control Block to relocate the vector table start address to a different me
19. IC can be accessed by using CMSIS functions see Figure 8 4 As an 50 Core Peripheral Access Layer core_cm3 h Core intrinsic functions Interrupt number and peripheral registers definitions lt device gt h system_ lt device gt h other header files Figure 8 3 CMSIS Organization 2 System functions including initialization Startup code files lj Device Peripheral Access Layer and additional access functions Function definition Description void NVIC_SystemReset void Resets the whole system including peripherals void NVIC_SetPriorityGrouping uint32_t priority_grouping Sets the priority grouping uint32_t NVIC_GetPriorityGrouping void Returns the value of the current priority grouping void NVIC_EnableIRQ IROn_Type IRQn Enables the interrupt IRQn void NVIC_DisableIRQ IROn_Type IRQn Disables the interrupt IRQn void NVIC_SetPriority IRQn_Type IROn int32_t priority Sets the priority for the interrupt IRQn uint32_t NVIC_GetPriority IRQn_Type IRQn Returns the priority for the specified interrupt void NVIC_SetPendingIRQ IRQn_Type IRQn Sets the interrupt IRQn pending IRQn_Type NVIC_GetPendingIRQ IRQn_Type IRQn Returns the pending status of the interrupt IRQn void NVIC_ClearPendingIRQ IRQn_Type IRQn Clears the pending status of the interrupt IRQn if it is not already running or active IRQn_Type NVIC_GetActive IRQn_Type IRQn Returns the active status for the
20. Keil IDE Using ULINK Cortex Debugger The default image memory map setting is that the code is executed from the ROM see Figurd7 20 a Since the ROM portion of the code needs to be flashed in order to be executed on the board this incurs wear and tear on the on chip flash of the LPC1768 Since most attempts to write a functioning RTX will eventually require some more or less elaborate debugging the flash memory might wear out quickly Unlike the flash memory stick file systems where the wear is aimed to be uniformly distributed across the memory portion this flash memory will get used over and over again in the same portion The ARM compiler can be configured to have a different starting address We can create a RAM target where the code starting address is in RAM see Figure 7 20 b An 44 initialization file RAM ini see Listing 7 1pis needed to do the proper setting of SP PC and vector table offset register Device Target Output Listing User C C Asm Linker Debug Utities Device Target Output Listing User C C Asm Linker Debug Utities NXP founded by Philips LPC1768 ae NXP founded by Philips LPC1768 Generation z Code Generation Xal MHz 112 0 Xtal MHz Nor I Use Cross Module Optimization ee Operating system None Operating system None I Use Cross Module Optimization TT Use MicroLIB r T Use MicroLIB FT Big Enc IT Use Link
21. Software Engineering 350 Laboratory Project Manual A Real time Executive for Keil MCB1700 by Yiqing Huang Thomas Reidemeister Electrical and Computer Engineering Department University of Waterloo Waterloo Ontario Canada January 5 2014 Y Huang and T Reidemeister 2014 Contents List of Tables vi List of Figures viii RTX Project Description 1 H a Di Y o O Introduction 2 A A 2 1 2 Summary of RIX Requirements o 0004 N 2 Description of RTX Primitives and Services 2 1 Memory Management aoao aa a a 2 2 Processor Management a 2 3 Interprocess Communication e ee eee 24 liming Services s s oaa ye wh AE a SA SO EO 2 5 Process Priority ddr e NI Dow amp A w Required Processes 3 1 System Processes aS wehbe Se hee eee ee eee do bee a 3 1 1 The Null Process scores ee RD ORE eR OE HS 3 1 2 System Console I O Processes o 00002 eee o o o 00 ii 3 2 Interrupt Processes I Processes 3 2 1 The Timer Processl 3 2 2 The UART I Process 3 3 User Processesl 3 3 1 User Level Test Process 3 3 4 stress Test Processes 3 4 Process ID Assignment 4 RIX Initialization 5 Deliverables and Demonstration LOC He oe He ee amp BA REAP at hy oe oe a oS AA RIX P2 erer gisar i ne Gilg RTX B3 4 oe es a ee S 514 RTX P4 2 64 de
22. Time Code Generation TT Use Link Time Code Generation Read Only Memory Areas Read Write Memory Areas Read Only Memory Areas Read Write Memory Areas default off chip Start Size Startup default off chip Start Size Nolnit default off chi Stat Si St defaut off chi Stat Si Nolnit Fee E ge E x a r rom c r Ram r c Doo m Eii x T rom c M RAMZ D m ROMZ c RAM2 x I ROM3 c I ROM3 c a anehip 5 irom 010000000 04000 a YZ IROM1 00 080000 e Prom C C IROMZ c a Default Memory Setting b In Memory Execution Setting Figure 7 20 Keil IDE Configure for In Memory Execution FUNC void Setup void Stack Pointer SP _RDWORD 0x10000000 PC _RDWORD 0x10000004 _WDWORD OxEOOOEDO8 0x10000000 Setup Setup Setup Program Counter Vector Table Offset Register J You need to provide the path of the axf file here LOAD build RAM HelloWorld axf INCREMENTAL Download Setup Setup for Running g main Listing 7 1 The RAM ini file To download the code to the board one should not use the download button Instead the debug button is used to initiate a debug session and the RAM ini file will load the code to the board 45 Chapter 8 Programming MCB1700 8 1 The Thumb 2 Instruction Set Architecture The Cortex M3 supports only the Thumb 2 and traditional Thumb instruction set With support for both 16 bit and 32 bit instructions in the Thumb 2 instructio
23. _UARTO_TX_empty 1 volatile uint8_t g_UARTO_buffer BUFSIZE volatile uint32_t g_UARTO_count 0 brief initialize the n_uart NOTES only fully supports uartO so far but can be easily extended to other uarts The step number in the comments matches the item number in Section 14 1 on pg 298 of LPC17xx_UM e 56 int uart_init int n_uart LPC_UART_TypeDef pUart if n_uart 0 Steps 1 amp 2 system control configuration Under CMSIS system_LPC17xx c does these two steps Step 1 Power control configuration table 46 pg63 in LPC17xx_UM enable UARTO power this is the default setting done in system_LPC17xx c under CMSIS enclose the code for your refrence LPC_SC gt PCONP BIT 3 Step2 select the clock source default PCLK CCLK 4 where CCLK 100MHZ tables 40 and 42 on pg56 and pg57 in LPC17xx_UM Check the PLLO configuration to see how XTAL 12 0MHZ gets to CCLK 100MHZ in system_LPC17xx c file enclose the code for your reference LPC_SC gt PCLKSELO amp BIT 7 BIT 6 Step 5 Pin Ctrl Block configuration for TXD and RXD See Table 79 on pg108 in LPC17xx_UM for pin settings Done before Steps3 4 for better coding purpose LPC_PINCON gt PINSELO 1 lt lt 4 Pin P0 2 used as TXDO Com0 LPC_PINCON gt PINSELO 1 lt lt 6 Pin P0 3 used as RXDO Com0 pUart LPC_UART_TypeDef LPC_UARTO else if n_uart 1 see Tab
24. ased Sores Translation Selection BYE CSEsSOes Selection Stop bits Colours UARTO Colours P 3 Connection Default Settings E Connection aey Load ArT esteen Data Flow contol ecelinux roxy Telnet Save Telnet Rlogin PARRA Rlogin H SSH t Delete s H SSH Close window on exit Always Never Only on clean exit About Help Open Cancel About l Help Cancel a PuTTY Session for Serial Port Communication b PuTTY Serial Port Configuration 7 2 Debugging You can use either the simulator within the IDE or the ULINK Cortex Debugger to debug your program To start a debug session click Debug Start Stop Debug Session from the IDE menu bar or press Ctrl F5 Figure shows the a typical debug session interface As any other GUI debugger the IDE allows you to set up break points and step through your source code It also shows the registers which is very helpful for debugging low level code Click View Debug and Peripherals from the IDE menu bar and explore the functionality of the debugger 7 2 1 Disabling CRP In order to avoid stealing firmware the LPC1768 provides Code Read Protection CRP that allows fine grain control about which areas of the memory can be read A detailed description is found in Section 32 6 of 4 In essence if the Assembler Directive NO CRP is not present the hardware is initialized to only make the firmware read only see Figure 7 16 Since it is advisable to change values on the fly when deb
25. ata e process id e priority e stack size e start address and e for system processes whether the process is an i process All initializations must take place after the RTX execution starts 16 Chapter 5 Deliverables and Demonstration 5 1 Deliverable The project has four deliverables where the first three deliverables are evaluated by in lab demonstrations The deliverables are as follows 5 1 1 RTX Pl This is the source code and documentation of a tiny kernel which provides memory man agement processor management and process priority services You need to implement e APIs listed in Sections and e processes in Sections and and e the corresponding part in Chapter 4 5 1 2 RTX P2 This is the source code and documentation of a simplified version of the final RTX On top of P1 you will e add APIs listed in Sections 2 3 and Note you need to write the six user testing processes to demonstrate that your implementation meets the requirements 17 e finish implementing all processes as described in Sections 3 1 and 3 3 2 e enhance user test processes in Section so that they test this version of the kernel and e implement the corresponding part in Chapter 4 5 1 3 RTX P3 This is the final RTX source code to implement the specifications in Chapters and based on the P1 and P2 implementations done previously To be more specific you will e finish implementing processes as described in Se
26. ation in pVision4 IDE To get started with the Keil IDE the MDK ARM Primer http www keil com support man docs gsac is a good place to start We will walk you through the IDE by developing a simple HelloWorld application which displays Hello World through the UARTO that is connected to the lab PC Note the HelloWorld example uses polling rather than interrupt The latest version is 5 1 0 0 We have not fully tested the supplied sample code with this version This manual is based on version 4 60 0 0 35 7 1 1 Create a New Project 1 Create a folder named HelloWorld on your computer 2 Copy the following files to HelloWorld folder e manual_code UART_polling src uart_polling h e manual_code UART_polling src uart_polling c e manual_code Startup system_LPC17xx c 3 Create a new pVision project by click e Project New pVision Project See Figure 7 1 Project Flash Debug Peripherals Tools SVCS Window Help LR New pVision Project e New Multi Project Workspace Open Project Close Project Space Export b Figure 7 1 Keil IDE Create a New Project e Choose NXP Founded by Philips LPC1768 See Figure 7 2 a and Figure 7 2 b e Answer Yes to copy the startup code See Figure 7 3 7 1 2 Managing Project Components You just finished creating a new project One the left side of the IDE is the Project window and expand all objects you will see the default proje
27. ations of processes A B and C priorities e Contribution Check Each group member will be asked what he she has contributed to the RTX i e Pl P2 and P3 implementation 21 Part II Keil MCB1700 Quick Reference Guide Chapter 6 Keil MCB1700 Hardware Environment 6 1 MCB1700 Board Overview The Keil MCB1700 board is populated with NXP LPC1768 Microcontroller Figure shows the important interface and hardware components of the MCB1700 board Figure is the hardware block diagram that helps you to understand the MCB1700 board components Note that our lab will only use a small subset of the components which include the LPC1768 CPU COM and Dual RS232 The LPC1768 is a 32 bit ARM Cortex M3 microcontroller for embedded applications requiring a high level of integration and low power dissipation The LPC1768 operates at up to an 100 MHz CPU frequency The peripheral complement of LPC1768 includes 512KB of on chip flash memory 64KB of on chip SRAM and a variety of other on chip peripherals Among the on chip peripherals there are system control block pin connect block 4 UARTs and 4 general purpose timers some of which will be used in your RTX course project Figure 6 3 is the simplified LPC1768 block diagram 4 where the components to be used in your RTX project are circled with red Note that this manual will only discuss the components that are relevant to the RTX course project The LPC17xx User Manual is the complete reference
28. bug Peripherals Tools SVCS TELE wel 9 o E RAR 3 iS Es PE targets CEIM AS ea Target 1 5 3 Source Group 1 Figure 7 4 Keil IDE A default new project New Vision Project New Multi Project Workspace Open Project Close Project Figure 7 5 Keil IDE Manage Project Components Components Environment Project Components Folders Extensions Books Click here to add a new target Click here to add a new group Project Targets Gx 4 Groups KIA Fies Ki t Figure 7 6 Keil IDE Manage Components Window the file to the source group Or you can select the file and click the Add button at the lower right corner of the window See Figure 7 8 Similarly add uart_polling c to Source Code group Your project will now look like Figure Create a new source file The project does not have a main function yet We now create a new file by clicking the New button See Figure 7 10 Before typing anything to the file save the file and name it main c Put the following code to the main c file include lt LPC17xx h gt include uart_polling h 38 Ded sosale cleo s ee o 8B SA B Heiowora sim aX 0 3 HelloWorld SIM E E3 Startup Code E startup_LPC17xx s KA Add Files to Group System od l Lookin Jj sre Je E e Edy Name gt Date modified Ty LPC17x c 1 5 20139 14PM__ C uart_polling c 1
29. commands loop forever p lt receive a message if the message p contains the Z command then release_memory_block p exit the loop else release_memory_block p endif endloop num 0 loop forever p lt request memory block to be used as a message envelope set message_type field of p to count_report set msg_data 0 field of p to num send the message p to process B num num 1 release_processor endloop note that Process A does not de allocate any received envelopes in the second loop Process B loop forever receive a message send the message to process C endloop 13 Process C perform any needed initialization and create a local message queue loop forever if local message queue is empty then p lt receive a message else p lt dequeue the first message from the local message queue endif if msg_type of p count_report then if msg_data 0 of p is evenly divisible by 20 then send Process C to CRT display using msg envelope p hibernate for 10 sec endif endif deallocate message envelope p release_processor endloop The line hibernate for 10 sec is further expanded as q lt request_memory_block request a delayed_send for 10 sec delay with msg_type wakeup10 using q loop forever p lt receive a message block and let other processes execute if message_type of p wakeup10 then exit this loop else put message p on the local message queue for later processing endif endloop
30. ct setup as shown in Figure 1 Rename the Target The Target 1 is the default name of the project build target and you can rename it by clicking the target name to highlight it and then click the highlighted name to input a new target name say HelloWorld SIM 2 Rename the Source Group The IDE allows you to group source files to different groups to better manage the source code By default Source Group 1 is created and the startup code 36 Vendor NXP founded by Philips Device LPC1768 Toolset ARM a Choose NXP b Choose LPC1768 Figure 7 2 Keil IDE Choose MCU OS Figure 7 3 Keil IDE Copy Startup Code startup LPC17xx s is put under this source group You can rename the source group by clicking the source group name to highlight it and then click again to input a new name say Startup Code Add a New Source Group You can add new source groups to your project Click Project Manage gt Components Environment Books See Figure 7 5 You can now add new source groups to the project Let s add System Code and Source Code source groups to the project See Figure Your project will now look like Figure Add Source Code to a Source Group Now add system_LPC17xx c to System Code group by double clicking the source group and choose the file from the file window Double clicking the file name will add 37 File Edit View Project Flash De
31. ctions and 3 3 4 e enhance user test processes in Section so that they test the final version of the kernel and e implement the corresponding part in Chapter 4 5 1 4 RTX P4 Program a second timer on the MCB1700 board to measure the speed of primitives Write a final project report which include the following e RTX Project Software Design Description This document describes the RTX design It should include a structural description of the design procedures and their interconnect data structures processes a functional description of all procedures pseudo code show all input output parameters and globals implementation testing and measurement plan include responsibilities of indi vidual team members This part document should be kept reasonably small no more than thirty pages not including appendices A design description should be shorter than the actual implementation e The measured times for the following primitives send_message 18 receive_message and request_memory_block and a check of the reasonableness of the values measured e A lessons learned summary what you did do well both technically and organiza tionally and what you would do differently if you were to do it again This summary should be brief one to two pages The deliverable contains both the source code of the project with the timing code added in and the final report in pdf format 5
32. ctures These test processes only call the RTX APIs The test processes should provide at least two and at most six test cases and finish testing within three minutes The process id 1 2 3 4 5 and 6 are reserved for these processes Since the test processes have no knowledge of your detailed internal design they only invoke the functions specified by the RTX API The test processes can use the timer that is not used by the RTX for timing testing We require the testing results to follow the following format and you output the results to the HyperTerminal i e UARTO Gid_test START Gid_test test n OK Gid_test test m FAIL Gid_test x N tests OK Gid_test y N tests FAIL Gid_test END 11 For example if you are group G099 and you have 3 testing cases in total Two of the testing cases pass and one of the testing cases does not pass The final testing results should be output to putty terminal as follows GO99_test START GO99_test total 3 tests GO99_test test 1 OK GO99_test test 2 OK GO99_test test 3 FAIL GO99_test 2 3 tests OK GOo99_test 1 3 tests FAIL GO99_test END 3 3 2 24 Hour Wall Clock Display Process This process registers itself with the Keyboard Command Decoder process as the handler for the W command e The WR command will reset the current wall clock time to 00 00 00 starts the clock running and causes display of the current wall clock time on the console CRT The display will be updated every second
33. d This preemption may affect the currently executing process int get_process_priority int process_id This primitive returns the priority of the process specified by the process_id parameter For an invalid process_id the primitive returns 1 Chapter 3 Required Processes This chapter describes the processes which you must implement for the project 3 1 System Processes System processes are those processes needed by the system to perform basic services scheduling and I O You will need to make your design choice to determine which system processes require privileged level and which system processes may operate at unprivileged level 3 1 1 The Null Process This process runs as the lowest priority process level 4 in the RTX The Null process is the only process assigned to level 4 Level 4 is basically a hidden priority level reserved for the Null process This preserves the four levels of user priorities levels 0 1 2 and 3 Process id 0 is reserved for the null process Initially the following pseudo code can be used to design your null process loop forever release the processor end loop Once you have preemption working then the release the processor line could be removed from the infinite loop 3 1 2 System Console I O Processes The system console is used for communication with the RTX and application processes It consists of two devices keyboard and CRT display These two devices communicate se
34. d into the PC it indicates to the processor that the exception is complete and the processor initiates the exception return sequence Table describes the EXC_RETURN bit fields Table 6 5 lists Cortex M3 allowed EXC_RETURN values Bits 31 4 3 2 1 0 Description OxFFFFFFF Return mode Return stack Reserved Process state Thread Handler must be 0 Thumb ARM Table 6 4 EXC_RETURN bit fields Value Description Return Exception return SP after return Mode gets state from OxFFFFFFF1 Handler MSP MSP OxFFFFFFF9 Thread MSP MSP OxFFFFFFFD Thread PSP PSP Table 6 5 EXC_RETURN Values on Cortex M3 6 4 4 Exception Return Exception return occurs when the processor is in Handler mode and executes one of the following instructions to load the EXC RETURN value into the PC 33 e a POP instruction that includes the PC This is normally used when the EXC_RETURN in LR upon entering the exception is pushed onto the stack e a BX instruction with any register This is normally used when LR contains the proper EXC_RETURN value before the exception return then BX LR instruction will cause an exception return e a LDR or LDM instruction with the PC as the destination This is another way to load PC with the EXC_RETURN value Note unlike the ColdFire processor which has the RTE as the special instruction for exception return in Cortex M3 a normal return instruction is used so that the whole interrupt handler can be implemented
35. e implementation of programming TIMERO interrupts The timer interrupt fires every one millisecond x file timer h ef ifndef _TIMER_H_ define _TIMER_H_ extern uint32_t timer_init uint8_t n_timer initialize timer n_timer endif _TIMER_H_ Listing 8 5 Timer0 IRQ Sample Code timer h file timer c brief Timer irq setup and handling routine ll 61 include lt LPC17xx h gt include timer h define BIT X 1 lt lt X volatile uint32_t g_timer_count 0 increment every 1 ms brief initialize timer Only timer 0 is supported uint32_t timer_init uint8_t n_timer LPC_TIM_TypeDef pTimer if n_timer 0 Steps 1 amp 2 system control configuration Under CMSIS system_LPC17xx c does these two steps Step 1 Power control configuration table 46 pg63 in LPC17xx_UM enable TIMERO power this is the default setting done in system_LPC17xx c under CMSIS enclose the code for your refrence LPC_SC gt PCONP BIT 1 Step2 select the clock source default PCLK CCLK 4 where CCLK 100MHZ tables 40 and 42 on pg56 and pg57 in LPC17xx_UM Check the PLLO configuration to see how XTAL 12 0MHZ gets to CCLK 100MHZ in system_LPC17xx c file enclose the code for your reference 77 PC2SC gt PCLKGELO amp BIT BIT 2 Step 3 Pin Ctrl Block configuration Optional not used in this example See Table 82 on pg110 in LPC17
36. elevant hardware environment and software development tools of the Keil MCB1700 board for completing the laboratory project To make the manual self contained we also include the project description E to further guide students There are two parts of the document e Part I RTX Project Description e Part III Keil MCB1700 Reference Guide Acknowledgments We would like to sincerely thank Professor Paul Dasiewicz who originally designed the RTX course project and provided us with detailed notes and sample code We also own many thanks to our students who did this course project in the past ten years and provided constructive feedback Professor Sebastian Fischmeister made the Keil Boards and MDK ARM donations possible Professor Jim Barby provided timely departmental resource towards the development of the course project without which this project will not be possible in winter 2012 Roger Sanderson oversees the ECE lab and provides us with all necessary experiment tools and resources which we are grateful We appreciate that Bernie Roehl has shared his valuable Keil board experiences with us Our gratitude also goes out to Eric Praetzel who sets up the RTOS lab and also maintains the Keil software on Nexus machines Laura Winger who managed to customize the boards so that we have the neat The original project description was written by Professor Paul Dasiewicz The project description included in this manual is a modified version of the o
37. enable the UART interrupt from the system level Use CMSIS call 58 NVIC_EnableIRQ UARTO_IRQn return 0 Es brief use CMSIS ISR for UARTO IRQ Handler NOTE This example shows how to save restore all registers rather than just those backed up by the exception stack frame We add extra push and pop instructions in the assembly routine ws The actual c_UARTO_IRQHandler does the rest of irq handling __asm void UARTO_IRQHandler void i PRESERVES IMPORT c_UARTO_IRQHandler PUSH r4 r11 lr BL c_UARTO_IRQHandler POP r4 r11 pc b brief c UARTO IRQ Handler void c_UARTO_IRQHandler void uint8_t IIR_IntId Interrupt ID from IIR uint8_t LSR_Val 1SR Value uint8_t dummy dummy dummy variable to clear interrupt upon LSR error LPC_UART_TypeDef pUart LPC_UART_TypeDef LPC_UARTO Reading IIR automatically acknowledges the interrupt IIR_IntId pUart gt IIR gt gt 1 skip pending bit in IIR if IIR_IntId IIR_RDA Receive Data Avaialbe Note read RBR will clear the interrupt g_UARTO_buffer g_UARTO_count pUart gt RBR read from the uart if g_UARTO_count BUFSIZE g_UARTO_count 0 buffer overflow 59 else if IIR_IntId amp IIR_THRE THRE Interrupt transmit holding register empty LSR_Val pUart gt LSR if LSR_Val E LSR THRE g_UARTO_TX_empty 1 UART is ready to transmit else g_UARTO_TX_empty 0 UART is
38. example the stan dardized SystemInit function to configure clock e system clock frequency with standardized variable named as SystemFrequency defined in the device driver 49 e vendor peripherals with standardized C structure User Application Code E Core Peripheral Functions Device Peripheral Functions RTOS CMSIS E Peripheral Registers and Interrupt Exception Vector Definitions SysTick NVIC mcu Core estar oe ea acco Timer Interrupt Controller Peripherals Cortex M Processor Figure 8 2 CMSIS Organization 2 8 3 1 CMSIS files The CMSIS is divided into multiple layers See Figure 8 2 For each device the MCU vendor provides a device header file lt device gt h e g LPC17xx h which pulls in additional header files required by the device driver library and the Core Peripheral Access Layer see Figure 8 3 By including the lt device gt h e g LPC17xx h file into your code file The first step to initialize the system can be done by calling the CMSIS function as shown in Listing 8 1 SystemInit Initialize the MCU clock Listing 8 1 CMSIS SystemInit The CMSIS compliant device drivers also contain a startup code e g startup_LPC17xx s which include the vector table with standardized exception handler names See Section 8 3 3 8 3 2 Cortex M Core Peripherals We only introduce the NVIC programming in this section The Nested Vectored Interrupt Controller NV
39. f intrinsic functions 8 3 5 Vendor Peripherals All vendor peripherals are organized as C structure in the lt device gt h file e g LPC17xx h For example to read a character received in the RBR of UARTO we can use the following code unsigned char ch ch LPC_UARTO gt RBR read UARTO RBR and save it in ch 52 Instruction CMSIS Intrinsic Function CPSIE I void _enable_irq void CPSID I void _disable_irq void Special Register Access CMSIS Function CONTROL Read uinit32t _get_CONTROL void Write void _ set_CONTROL uint32_t value MSP Read uinit32t _ get MSP void Write void set_MSP uint32_t value PSP Read uinit32t _get_PSP void Write void _set_PSP uint32_t value Table 8 3 CMSIS intrinsic functions defined in core_cmFunc h 8 4 Accessing C Symbols from Assembly Only embedded assembly is support in Cortex M3 i e inline assembly is not supported To write an embedded assembly function you need to use the _ asm keyword For exam ple the the function embedded_asm function in Listing is an embedded assembly function You can only put assembly instructions inside this function Note that inline assembly is not supported in Cortex M3 The _cpp keyword allows one to access C compile time constant expressions including the addresses of data or functions with external linkage from the assembly code The expression inside the __cpp can be one of the followings e A global variable def
40. for LPC1768 MCU 6 2 Cortex M3 Processor The Cortex M3 processor is the central processing unit CPU of the LPC1768 chip The processor is a 32 bit microprocessor with a 32 bit data path a 32 bit register bank and 23 USB USB Device USB Cortex Ethemet Host Power OTG Debug JTAG Ceoeeseeseoesee Secoeeeeesereces CAN ait oh a e a E Potentiometer LPC1768 Port Cortex INTO amp Joystick LEDs Debug Reset ETM Buttons Figure 6 1 MCB1700 Board Components User I O LCD Display Dual RS232 Configuration CPU Dual CAN Jumpers LPC17xx Reset amp Interrupt Or variant Buttons USB SD Card Power amp COM Ethernet Figure 6 2 MCB1700 Board Block Diagram I 24 ween wwe cme cnn mmm woe woe oe dd Figure 6 3 LPC1768 Block Diagram 25 Cortex M3 Processor core system Register bank Memory interface interrupts Instruction fetch unit Decoder Interrupt controller NVIC Memory Instruction bus protection Data bus i unit H Bus interconnect Debug interface pS _ Y E 1 Code Memory system Private Optional memory and peripherals peripherals Figure 6 4 Simplified Cortex M3 Block Diagram 5 32 bit memory interfaces Figure is the simplified block diagram of the Cortex M3 processor 5 The processor has private peripherals which are system control block system timer NVIC Nested Vectored Interrupt Controlle
41. ined in C typedef struct pcb struct mp_next uint32_t m_sp pcb_t pcb_t g_pcb uint32_t g_var __asm embedded_asm_function void LDR R3 __cpp amp g_pcb load R3 with the address of g_pcb LDM R3 R1 R2 load R1 with g_pcb mp_next load R2 with g_pcb m_sp LDR R4 __cpp g_var load R4 with the value of g_var 53 Listing 8 2 Example of accessing global variable from assembly e A C function extern void a_c_function void __asm embedded_asm_function void e A constant expression in the range of 0 255 defined in C uint8_t const g_flag __asm embedded_asm_function void Note the MOV instruction only applies to immediate constant value in the range of 0 255 You can also use the IMPORT directive to import a C symbol in the embedded assembly function and then start to use the imported symbol just as a regular assembly symbol For example void a_c_function void do something E __asm embedded_asm_add void 4 IMPORT a_c_function a_c_function is a regular C function BL a_c_function branch with link to a_c_function E 54 Names in the __cpp expression are looked up in the C context of the __asm function Any names in the result of the __cpp expression are mangled as required and automatically have IMPORT statements generated from them 8 5 UART Programming To program a UART on MCB1700 board one first needs to configure the UART by following the steps listed in Sectio
42. interrupt IRQn Figure 8 4 CMSIS NVIC Functions 2 example the following code enables the UARTO and TIMERO interrupt NVIC_EnableIRQ UARTO_IRQn UARTO_IRQn is defined in LPC17xx h NVIC_EnableIRQ TIMERO_IRQn TIMERO_IRQn is defined in LPC17xx h 51 8 3 3 System Exceptions Writing an exception handler becomes very easy One just defines a function that takes no input parameter and returns void The function takes the name of the standardized exception handler name as defined in the startup code e g startup_LPC17xx s The following listing shows an example to write the UARTO interrupt handler entirely in C void UARTO_Handler void write your IRQ here Another way is to use the embedded assembly code __asm void UARTO_Handler void do some asm instructions here BL __cpp a_c_function a_c_function is a regular C function do some asm instructions here 8 3 4 Intrinsic Functions ANSI cannot directly access some Cortex M3 instructions The CMSIS provides intrinsic functions that can generate these instructions The CMSIS also provides a number of functions for accessing the special registers using MRS and MSR instructions The intrinsic functions are provided by the RealView Compiler Table 8 3 lists some intrinsic functions that your RTOS project most likely will need to use We refer the reader to Tables 613 and 614 one page 650 in Section 34 2 2 of 4 for the complete list o
43. ironment with five priority levels preemption simple memory management message based inter process communication a basic timing service system console I O and debugging support Such an RTX is suitable for embedded computers which operate in real time A co operative non malicious software environment is assumed The design of the RTX should allow its placement in ROM Applications and non kernel RTX processes must execute in the unprivileged level of LPC1768 The RTX kernel will execute in the privileged level It has 32K of RAM for use by the RTX and application processes It contains four timers four UARTs and several other peripheral interface devices The board has two RS 232 interfaces from which UARTO is used for your RTX system console 1 2 Summary of RTX Requirements The summary of the RTX requirements are listed as follows 1 Scheduling Strategy Four user priority levels plus an additional hidden priority level for the Null process We do not require application processes to use Process Stack Pointer PSP You may use the Main Stack Pointer MSP both for your kernel and non kernel code However non trivial implementations that are not required such as using PSP for user processes and using memory protection unit to safe guard kernel sensitive data will be rewarded with bonus marks preemption no time slicing FIFO First In First Out discipline at each priority level RTX Primitives and Services Refer t
44. k The primitive returns a pointer to a memory block to the calling process If no memory block is available the calling process is blocked until a memory block becomes available If several processes are waiting for a memory block and a block becomes available the highest priority waiting process will get it lFor example you may define a macro as the number of memory blocks and change the macro value at compile time int release_memory_block void memory_block This primitive returns the memory block to the RTX If there are processes waiting for a block the block is given to the highest priority process which is then unblocked The caller of this primitive never blocks but could be preempted Thus it may affect the currently executing process 2 2 Processor Management One primitive is to be provided int release_processor This primitive transfers the control to the RTX the calling process voluntarily releases the processor The invoking process remains ready to execute and is put at the end of the ready queue of the same priority Another process may possibly be selected for execution 2 3 Interprocess Communication The RTX will support a message based Interprocess Communication IPC discussed in lectures Messages are carried in envelopes memory blocks see below with a header which is less than 64 bytes Two IPC primitives will be implemented int send_message int process_id void message_envelope
45. l Sil FB Heno E Build F7 Build target files Figure 7 12 Keil IDE Build Target E Project Books Functi Op Tempi m Build Output Build target HelloWorld SIM assembling startup LPC17xx s compiling main c compiling system LPC17xx cCc compiling uart polling c linking Program Size Code 1216 RO data 236 RW data 4 ZI data 612 HelloWorld axf 0 Error s O Warning s Figure 7 13 Keil IDE Build Target File Edit View Project Flash Debug Peripherals Tools Figure 7 14 Keil IDE Download Target to Flash order to see output of the serial port Open up the PuTTY on your PC and choose COM1 An example PuTTY Serial configuration is shown in Figures 7 15 a and 7 15 b Press the Reset button on the board and you should see Hello World displayed on PuTTY 41 BR PuTTY Configuration 2 183 ER PuTTY Configuration Category i Category Session Basic options for your PuTTY session E Session Options controlling local serial lines Bea Speci the destination you wantto connectto EN cae Selecta serial line Keyboard Serial line Speed Keyboard Serial line to connectto COMI Bell COMI 115200 Bell Paras Connection type de da Configure the serial line E A Beg Window Appearance Ree Jena Rogn SSH Appearance Speed baud 115200 Behaviour Load save or delete a stored session Behaviour Data bits Translation B
46. le 79 on pg108 in LPC17xx_UM for pin settings LPC_PINCON gt PINSELO 2 lt lt 0 Pin P2 0 used as TXD1 Comi LPC_PINCON gt PINSELO 2 lt lt 2 Pin P2 1 used as RXD1 Comi pUart LPC_UART_TypeDef LPC_UART1 57 else return 1 not supported yet Step 3 Transmission Configuration Step 3a DLAB 1 8N1 pUart gt LCR UART_8N1 see uart h file Step 3b 115200 baud rate 25 0 MHZ PCLK seep section 14 4 12 1 pg313 315 in LPC17xx_UM for baud rate calculation pUart gt DLM 0 see table 274 pg302 in LPC17xx_UM pUart gt DLL 9 see table 273 pg302 in LPC17xx_UM pUart gt FDR 0x21 FR 1 507 1 2 DivAddVal 1 MulVal 2 FR 1 507 25MHZ 16 9 115200 see table 285 on pg312 in LPC_17xxUM Step 4 FIFO setup pUart gt FCR 0x07 enable Rx and Tx FIFOs clear Rx and Tx FIFOs Trigger level 0 1 char per interrupt see table 278 on pg305 in LPC17xx_UM Step 5 was done between step 2 and step 4 a few lines above Step 6 Interrupt setting Step 6a enable interrupt bits wihtin the specific peripheral register Interrupt Sources Setting RBR THRE or RX Line Stats See Table 50 on pg73 in LPC17xx_UM for all possible UARTO interrupt sources See Table 275 on pg 302 in LPC17xx_UM for IER setting pUart gt LCR amp BIT 7 disable the Divisior Latch Access Bit DLAB 0 pUart gt IER IER RBR IER_THRE LER RLS Step 6b
47. may contain control characters e g newline The process causes the string to be output to the console CRT In printing to the console display the process must use the UART i process Any message received is freed using the release_memory_block primitive 3 2 Interrupt Processes I Processes Two interrupt handling processes are required 3 2 1 The Timer I Process The timer i process is executed each time a hardware timer interrupt occurs The timer i process should handle the delivery of delayed send messages after the required time has expired 3 2 2 The UART I Process The UART i process uses interrupts for both the transmission and receiving of characters from the serial port No polling or busy waiting strategies may be implemented The UART i process forwards characters or commands received to the KCD and also responds to messages received from the CRT display process to transmit characters to the serial port Three Hot Keys As well the UART i process is used to provide debugging services which will be used during the demonstration Upon receiving a specific character a hot key your choice e g as input the UART i process will print one of the following to the RTX system console e The processes currently on the ready queue s and their priority e The processes currently on the blocked on memory queue s and their priorities e The processes currently on the blocked on receive queue s and their priorities As
48. mory location in the range 0x00000080 to 0x3FFFFF80 6 4 2 Exception Entry Exception entry occurs when there is a pending exception with sufficient priority and either e the processor is in Thread mode 30 Exception IRQ Vector address Exception Priority C PreFix number number or offset type 1 0x00000004 Reset 3 the highest 2 14 0x00000008 NMI 2 NML 3 13 0x0000000C Hard fault 1 HardFault_ 4 12 0x00000010 Memory Configurable MemManage _ management fault 11 5 0x0000002C SVCall Configurable SVC_ 14 2 0x00000038 PendSV Configurable PendSVC_ 15 1 0x0000003C SysTick Configurable SysTick_ 16 0 0x00000040 WDT Configurable WDT_IRQ 17 1 0x00000044 Timer0 Configurable TIMERO IRQ 18 2 0x00000048 Timerl Configurable TIMER1_IRQ 19 3 0x0000004C Timer2 Configurable TIMER2_ IRQ 20 4 0x00000050 Timer3 Configurable TIMER3_ IRQ 21 5 0x00000054 UARTO Configurable UARTO_IRQ 22 6 0x00000058 UARTI Configurable UART1 IRQ 23 7 0x0000005C UART2 Configurable UART2 IRQ 24 8 0x00000060 UART3 Configurable UART3_IRQ Table 6 3 LPC1768 Exception and Interrupt Table e the processor is in Handler mode and the new exception is of higher priority than the exception being handled in which case the new exception preempts the original exception This is the nested exception case which is not required in our RTOS lab When an exception takes place the following happens e Stacking When the processor invokes an exception excep
49. n 15 1 in 4 referred as LPC17xx_UM in the sample code comments Listings and give one sample implementation of programming UARTO interrupts file uart h ifndef _UART_H_ define _UART_H_ include lt stdint h gt typedefs The following macros are from NXP uart h define IER_RBR 0x01 define IER_THRE 0x02 define IER_RLS 0x04 define IIR_PEND 0x01 define IIR_RLS 0x03 define IIR_RDA 0x02 define IIR_CTI 0x06 define IIR_THRE 0x01 define LSR_RDR 0x01 define LSR_OE 0x02 define LSR_PE 0x04 define LSR_FE 0x08 define LSR_BI 0x10 define LSR_THRE 0x20 define LSR_TEMT 0x40 define LSR_RXFE 0x80 59 define BUFSIZE 0x40 end of NXP uart h file reference define BIT X 1 lt lt X define UART_8N1 0x83 8 bits no Parity 1 Stop bit BOS SEL OOOO ORADOR O LCR 7 1 enable Divisor Latch Access Bit DLAB LCR 6 0 disable break transmission LCR 5 4 00 odd parity LCR 3 0 no parity 7f TCRISI 0 1 stop bat LCRI1 0 11 8 bit char len See table 279 pg306 LPC17xx_UM define uart0_init uart_init 0 int uart_init int n_uart initialize the n_uart void uart_send_string uint32_t n_uart uint8_t p_buffer uint32_t len write a string to the n_uart Hendif _UART_H_ Listing 8 3 UARTO IRQ Sample Code uart h file uart_irq c brief uart interrupt setup and handling functions include lt LPC17xx h gt include uart h volatile uint8_t g
50. n set there is no need to switch the processor between Thumb state 16 bit instructions and ARM state 32 bit instructions In the RTOS lab you will need to program a little bit in the assembler language We introduce a few assembly instructions that you most likely need to use in your project in this section The general formatting of the assembler code is as follows label opcode operandi operand2 Comments The label is optional Normally the first operand is the destination of the operation note STR is one exception Table 8 1 lists some assembly instructions that the RTX project may use For complete instruction set reference we refer the reader to Section 34 2 ARM Cortex M3 User Guide Instruction Set in 4 8 2 ARM Architecture Procedure Call Standard AAPCS The AAPCS ARM Architecture Procedure Call Standard defines how subroutines can be separately written separately compiled and separately assembled to work together The 46 Mnemonic Operands Examples Description LDR Rt Rn offset Load Register with word LDR R1 RO 24 Load word value from an memory address RO 24 into R1 LDM Rn reglist Load Multiple registers LDM R4 RO R1 Load word value from memory address R4 to RO increment the address load the value from the updated address to R1 STR Rt Rn offset Store Register word STR R3 R2 R6 Store word in R3 to memory address R2 R6 STR R1 SP
51. nder_id unless it is NULL Note the sender_id is an output parameter and is not meant to filter which message to receive 2 4 Timing Services Unprivileged level processes obtain the timing service from RTX by the following primitive 2Unprivileged processes should not read kernel timer data directly You are free to add a primitive to return the kernel clock ticks to unprivileged processes should you find the delayed_send primitive is not sufficient to provide the timing service you need int delayed_send int process_id void message_envelope int delay The invoking process does not block The message in the memory block pointed to by the second parameter will be sent to the destination process process_id after the expiration of the delay timeout given in millisecond units 2 5 Process Priority Process priorities have an integer priority value 0 1 2 3 4 where 0 is the highest priority level Two primitives are to be provided to set and get the process priority int set_process_priority int process_id int priority This primitive sets the priority of the process with process_id to the value given in priority A process may change priority of any process including itself except for i processes see Section 3 2 The priority of the null process may not be changed from level 4 and it is the only process that can be assigned to level 4 see Section 3 1 1 The caller of this primitive never blocks but could be preempte
52. not ready to transmit yet else if IIR_IntId amp IIR_RLS LSR_Val pUart gt LSR if LSR_Val amp LSR_OE LSR_PE LSR_FE LSR_RXFE LSR_BI 4 There are errors or break interrupt Read LSR will clear the interrupt dummy pUart gt RBR Dummy read on RX to clear interrupt then bail out return error occurs return If no error on RLS normal ready save into the data buffer Note read RBR will clear the interrupt if LSR_Val amp LSR_RDR Receive Data Ready g_UARTO_buffer g_UARTO_count pUart gt RBR read from the uart if g_UARTO_count BUFSIZE g_UARTO_count 0 buffer overflow else IIR_CTI and reserved combination are not implemented yet return H i void uart_send_string uint32_t n_uart uint8_t p_buffer uint32_t len LPC_UART_TypeDef pUart if n_uart 0 UARTO is implemented pUart LPC_UART_TypeDef LPC_UARTO else other UARTs are not implemented return 60 while len 0 THRE status contain valid data while g_UARTO_TX_empty amp 0x01 pUart gt THR p_buffer g_UARTO_TX_empty 0 not empty in the THR until it shifts out p_buffer len return Listing 8 4 UARTO IRQ Sample Code uart irq c 8 6 Timer Programming To program a TIMER on MCB1700 board one first needs to configure the TIMER by following the steps listed in Section 21 1 in KM Listings and give one sampl
53. nstallation ULINK Pro Driver 1 0 JV Show Release Notes KellpWisiond Setup lt lt Back Cancel Figure A 2 MDK ARM Installation Steps Finish At the last step of MDK ARM installation be sure that the launch the ULINK Pro Driver ES Windows Security x Would you like to install this device software Name KEIL Tools By ARM Universal Serial Bus TIT Publisher ARM Ltd Click Install V Always trust software from ARM Ltd P You should only install driver software from publishers you trust How can I decide which device software is safe to install Figure A 3 MDK ARM Installation Steps ULINK Pro Driver V1 0 driver installation check box is checked see Figure Once you click Finish button the ULINK Pro Driver installation starts Click Install button to install the driver see Figure A 3 66 Appendix B Forms Lab administration related forms are given in this appendix 67 SE350 Request to Leave a Project Group Form Name Quest ID Student ID Lab Assignment ID Group ID Names of Other Group Members Provide the reason for leaving the project group here Signature Date 68 Bibliography KH MCB1700 User s Guide http www keil com support man docs mcb1700 2 MDK Primer http www keil com support man docs gsac Realview compilation tools version 4 0 Compiler reference guide 2007 2010
54. o the Chapter 2 Description of RTX Primitives and Services RTX Footprint and Processor Loading A reasonably Jean implementation is expected No standard C library function call is allowed in the kernel code Error Detection and Recovery At minimum the RTX kernel must detect one type of error an attempt to send_message to or set_process_priority of a non existent process ID The primitive will return an error code a non zero integer value No error recovery is required It may be assumed that the application processes can deal with this situation Chapter 2 Description of RTX Primitives and Services This chapter lists the RTX primitive and services You must implement theses as described and may not modify the prototypes in any way The primitives listed below will always return a value either a pointer or an int return code In the latter case the return code value of 0 indicates a success non zero value indicates a failure where applicable 2 1 Memory Management The RTX supports a simple memory management scheme The memory is divided into blocks of fixed size 128 bytes minimum The size and the number of these blocks is a con figuration parameter at compile timef The blocks can be used by the requesting processes for storing local variables or as envelopes for messages sent to other processes A block which is no longer needed must be returned to the RTX Two primitives are to be provided void request_memory_bloc
55. questions e Contribution Check Each group member will be asked what he she has contributed to P1 implementation P2 Demo Procedure e Basic Functionality Demo You will need to demonstrate you have successfully completed the required APIs by displaying the wall clock display process using various 4W commands and showing the output of the three hot keys Note you are responsible to program the six user test processes so that one process is blocked on memory and one process is blocked on receive to demonstrate the full functionality of the all the hot keys e Source Code Spot Check An evaluator will ask each group member implementation questions P3 Demo Procedure e Basic Functionality Demo You will demonstrate the basic functionality of the RTX through commands line input The evaluator will start observe and stop wall clock display by using various ZW commands check the hot keys output and set priority of processes by using C commands test of wall clock display 20 e Stress Test Your RTX will be go through a stress testing demo by using processes A B and C The evaluator will reinitialize RTX with N N 30 envelopes one combination of processes A B and C priorities start test process activity by 4Z command observe system operation wall clock display as indicator may also display trace buffer is your have it implemented The above will be repeated with two other combin
56. r and MPU Memory Protection Unit The MPU programming is not required in the course project The processor includes a number of internal debugging components which provides debugging features such as breakpoints and watchpoints 6 2 1 Registers The processor core registers are shown in Figure For detailed description of each register Chapter 34 in 4 is the complete reference e RO R12 are 32 bit general purpose registers for data operations Some 16 bit Thumb instructions can only access the low registers RO R7 e R13 SP is the stack pointer alias for two banked registers shown as follows Main Stack Pointer MSP This is the default stack pointer and also reset value It is used by the OS kernel and exception handlers Process Stack Pointer PSP This is used by user application code 26 RO R1 R3 R4 R5 R6 R7 R8 R9 High registers lt R10 R11 L R12 Stack Pointer Link Register LR R14 Program Counter PC R15 Low registers lt General purpose registers PSP MSP Banked version of SP PSR PRIMASK FAULTMASK BASEPRI CONTROL Program status register Exception mask registers Special registers CONTROL register Figure 6 5 Cortex M3 Registers 4 On reset the processor loads the MSP with the value from address 0x00000000 The lowest 2 bits of the stack pointers are always 0 which means they are always word aligned In Thread mode when bit 1 of the CONTROL register is
57. rially with the microcomputer using the receive and transmit lines of one of the two RS 232 ports The RTX will include two system processes the Keyboard Command Decoder KCD process and the CRT Display process These processes work in cooperation with the UART interrupt handler i process The Keyboard Command Decoder KCD Process A keyboard command starts with the prompt character followed by a single or mul tiple letter command identifier and possibly additional command data For example AWS 12 45 00 could be a command to the wall clock process telling it to start the wall clock display and setttig the current time to 12 45 00 where the command format is WS hh mm ss The command decoder process responds to two types of messages console keyboard input and command registra tion The latter contains the command identifier and the process id of the process to which such commands are to be delivered when entered on the console keyboard The processing of messages received depends on their type e Command Registration The command identifier is associated with the process id of the registrant e Keyboard Input The string input is sent to CRT display for output If the string begins with a registered command identifier it is also sent to the registered requester The CRT Display Process This process responds to only one message type a CRT display request The message body contains the character string to be displayed The string
58. riginal one plastic cover to protect our hardware Bob Boy from ARM always answers our questions in a detailed and timely manner Thank everyone who has helped Lab Project Administration Policy Project Group Policy e Group Size The project is done in groups of four A group of less than four members is not recommended There is no reduction in project deliverables regardless the size of the project group Everyone in the group normally gets the same mark The Course Book System at URL https ecewo32 uwaterloo ca cgi bin Web0bjects CourseBook is used to signup for groups and reserve project demo times The project group signup is due by 4 30pm on the second Friday of the academic term Late group sign up incurs a 5 per day final lab mark deduction e Group Split up If you notice workload imbalance try to solve it as soon as possible within your group or split up the group as the last resort Group split up is only allowed once There is one grace day deduction penalty to be applied to each member in the old group We highly recommend everyone to stay with your group members as much as possible for the ability to do team work will be an important skill in your future career Please choose your lab partners carefully A copy of the code and documentation completed before the group split up will be given to each individual in the group e Group Split up Deadline To split from your group for a particular project de liverable you need
59. s only one stack is visible at a time as R13 In Handler mode the main stack is always used The bit 1 in CONTROL register reads as zero and ignores writes in Handler mode In Thread mode the bit 1 setting in CONTROL register determines whether the main stack or the process stack is currently used Table 6 1 summarizes the processor mode execution privilege level and stack use options Processor Used to Privilege level for CONTROL Stack used mode execute software execution Bit 0 Bit 1 Thread Applications Privileged 0 0 Main Stack Unprivileged 1 1 Process Stack Handler Exception handlers Privileged 0 Main Stack Table 6 1 Summary of processor mode execution privilege level and stack use options 6 3 Memory Map The Cortex M3 processor has a single fixed 4GB address space Table shows how this space is used on the LPC1768 Note that the memory map is not continuous For memory regions not shown in the table they are reserved When accessing reserved memory region the processor s behavior is not defined All the peripherals are memory mapped and the LPC17xx h file defines the data structure to access the memory mapped peripherals in C 29 Address Range General Use Address range details Description 0x0000 0000 to On chip non volatile 0x0000 0000 0x0007 FFFF 512 KB flash memory Ox1FFF FFFF memory On chip SRAM 0x1000 0000 0x1000 7FFF 32 KB local SRAM Boot ROM Ox1FFF 0000 Ox1FFF 1
60. sions without incurring any penalty A group split up will consume one grace day When you use up all your grace days a 10 per day late penalty will be applied to a late submission Please be advised that to simplify the book keeping late submission is counted in a unit of day rather than hour or minute An hour late submission is one day late so does a fifteen hour late submission Unless notified otherwise we always take the latest submission from the course book system You are required to notify lab TAs preferably by email when you have used grace days Seeking Help Outside Scheduled Lab Hours e Discussion Forum We recommend students to use the Learn discussion forum to ask the teaching team questions instead of sending individual emails to lab teaching staff For a question related to a deliverable our target response time is one business day before the deadline of the particular deliverable After the deadline there is no guarantee on the response time e Office Hours During weeks where there are no scheduled labs lab teaching staff hold bi weekly office hours Table 2 gives the office hour details e Appointments Students can also make appointments with lab teaching staff should their problems are not resolved by discussion forum or during office hours When 3Grace days are calendar days Days in weekends are counted Our past experiences show that the number of questions spike when deadline is close The teaching s
61. ss should run at this level When the processor is in Handler mode it is at the privileged level When the processor is in Thread mode it can run at privileged or unprivileged user level The bit 0 in CONTROL register determines the execution privilege level Figure illustrate the mode and privilege level of the processor Exception Privileged a exit handler reset Exception Exception Exception exit Figure 6 6 Cortex M3 Operating Mode and Privilege Level 5 Privileged thread Program of CONTROL register Note that only privileged software can write to the CONTROL register to change the privilege level for software execution in Thread mode Unprivileged software can use the 28 SVC instruction to make a supervisor call to transfer control to privileged software Another way to change between Privileged Thread mode and Unprivileged thread mode is to modify the EXC_RETURN value in the LR R14 when returning from an exception You probably want to use this mechanism for context switching 6 2 3 Stacks The processor uses a full descending stack This means the stack pointer indicates the last stacked item on the stack memory When the processor pushes a new item onto the stack it decrements the stack pointer and then writes the item to the new memory location The processor implements two stacks the main stack and the process stack One of these two stacks is banked out depending on the stack in use This mean
62. t for tail chained or a late arriving exception which are not required in the RTOS lab it automatically stores the following eight registers to the SP RO R3 R12 PC Program Counter PSR Processor Status Register LR Link Register R14 31 Figure 6 7 shows the exception stack frame Note that by default the stack frame is aligned to double word address starting from Cortex M3 revision 2 The alignment feature can be turned off by programming the STKALIGN bit in the System Control Block SCB Configuration Control Register CCR to 0 On exception entry the processor uses bit 9 of the stacked PSR to indicate the stack alignment On return from the exception it uses this stacked bit to restore the correct stack alignment Stack align adjustment not required Stack align adjustment required Address Address gt Previous gt Previous Previous SP stacked Previous SP gt stacked location J data location data j Not used New SP gt Free New SP stack location 2 Free L jJ space l aak Previous stack point at double word J space een eee Previous stack point not at double word address and STKALIGN is 1 Figure 6 7 Cortex M3 Exception Stack Frame 5 e Vector Fetching While the data bus is busy stacking the registers the instruction bus fetches the exception vector the starting address of the exception handler from the vector table The stacking and vector fetch are performed on separate
63. taff will not be able to guarantee one business day response time when workload is above average though we always try our best to provide timely response Time even weeks only Location Name email ID Monday 11 00 12 00 DC 2631 Yiqing Irene Huang yqhuang Tuesday TBA Jean Christophe Petkovich j2petkovich Wednesday TBA Anas Abognah aabognah Table 2 Bi weekly Office Hour Schedule you request an appointment please specify three preferred times and roughly how long you would like the appointment to be On average an appointment is fifteen minutes per project group Lab Facility After Hour Access Policy After hour access to the lab will be given to the class when we start to use the Keil boards in lab However please be advised that the after hour access is a privilege Students are required to keep the lab equipment and furniture in good conditions to maintain this privilege No food or drink is allowed in the lab water is permitted Please be informed that you may share the lab with other classes When resources become too tight certain cooperation is required such as taking turns to use the stations in the lab Part I RTX Project Description Chapter 1 Introduction 1 1 Overview In this project you will design a small real time executive RTX and implement it on a Keil MCB1700 board populated with an NXP LPC1768 microcontroller The executive will provide a basic multiprogramming env
64. to notify the lab instructor in writing and sign the group slip up form in the appendix at least one week before the particular project deliverable is due Project Submission Policy e Project Submission and Due Dates The project is divided into four deliverables Each deliverable requires the source code and a documentation file in pdf file Archive all files for each deliverable in a single file and submit it by using the Course Book System by performing group submission Table 1 gives the weight deadline and 2Put all source code including all header files and binaries and the documentation file in a separate directory Include a README file with group identification description of directory contents Compress the directory contents into a single file For archiving you must choose zip Deliverable Weight Due Date File Name Group Sign up 4 30pm Jan 17th RTX P1 25 4 30pm Jan 30st pl_Gid zip RTX P2 30 4 30pm Mar 6th p2 Gid zip RTX P3 20 8 30am Mar 24th p3 Gid zip RTX P4 25 4 30pm Apr 3rd p4 Gid zip Table 1 Project Deliverable Weight and Deadlines Replace the id in Gid with the two digit group ID naming convention of each deliverable A 15 penalty will be applied to a deliverable that is only able to function inside the simulator but not on the actual hardware e Late Submissions There are three grace dayP that can be used for project deliver ables late submis
65. ugging the CRP should be disabled during prototyping Open up the target option window and click the Asm tab Put NO_CRP as shown in Figure 42 14 D A Users Yiging nonwin yqwork ece ece354 se350w12 manual_code HelloWorld HelloWorld uvproj pVision4 Enable Disable Break oli wy File Edit View Project Flash Debug Peripherals Tools SVCS Window Help Points Ctrl F9 7 Oe e s a Blocle e RA R FE ale Ha ey 9 eis EEC let EDS MME TIS Start Stop Debug q nica rm Mc j e Step Out Ctrl F11 Disassebly Windo Step Over F10 Step F11 Step one line Stop Stop Code Execution Run F5 Run to Cursor line Show Next Statement Ctrl F10 Show statement in PC Reset Reset the CPU Register Window Serial Window Local Variables Window Serial Windows to show or hide A PG El Project Registers 4 Command A E Locals 2 E A es w P gt ASSIGN BreakDisable BreakEnable BreakKill BreakList BreakSet A Call Stack GAlocals UART 1 a By Simulator is used for debugging 4 Simulation gt t1 0 00004850 sec L1Cc1 CAP NUM SCRL OVR Figure 7 15 Keil IDE Debugging 110 IF LNOT DEF NO_CRP 111 AREA ARM at Ox02FC CODE READONLY 112 CRP_Key DCD OxFFFFFFFE 113 ENDIF 114 115 116 AREA text CODE READONLY Figure 7 16 startup LPC17xx s excerpt Device
66. vl Variable register 1 r3 a4 argument scratch register 4 r2 a3 argument scratch register 3 rl a2 argument result scratch register 2 r0 al argument result scratch register 1 Table 8 2 Core Registers and AAPCS Usage Registers RO R3 are used to pass parameters to a function and they are not preserved The compiler does not generate assembler code to preserve the values of these registers RO is also used for return value of a function Registers R4 R11 are preserved by the called function If the compiler generated as sembler code uses registers in R4 R11 then the compiler generate assembler code to auto matically push pop the used registers in R4 R11 upon entering and exiting the function R12 R15 are special purpose registers A function that has the __svc_indirect keyword makes the compiler put the first parameter in the function to R12 followed by an SVC instruction R13 is the stack pointer SP R14 is the link register LR which normally is used to save the return address of a function R15 is the program counter PC Note that the exception stack frame automatically backs up RO R3 R12 LR and PC together with the xPSR This allows the possibility of writing the exception handler in purely C language without the need of having a small piece of assembly code to save restore RO R3 LR and PC upon entering exiting an exception handler routine 48 8 3 Cortex Microcontroller Software Interface Stan dard CMSIS
67. xx_UM for pin settings pTimer LPC_TIM_TypeDef LPC_TIMO else other timer not supported yet return 1 62 brief use CMSIS ISR for UARTO IRQ Handler NOTE This example shows how to save restore all registers rather than Step 4 Interrupts configuration Step 4 1 Prescale Register PR setting pTimer gt PR 12499 CCLK 100 MHZ PCLK CCLK 4 25 MHZ M 2 12499 A E 10 6 s 10 3 3 1 ms TC Timer Counter toggles b w 0 and 1 every 12500 PCLKs see MR setting below Step 4 2 MR setting see section 21 6 7 on page 496 of LPC17xx_UM plimer gt MRO 1 Step 4 3 MCR setting see table 429 on page 496 of LPC17xx_UM Interrupt on MRO when MRO mathches the value in the TC generate an interrupt Reset on MRO Reset TC if MRO mathches it pTimer gt MCR BIT O BIT 1 g_timer_count 0 Step 4 4 CSMSIS enable timerO IRQ NVIC_EnableIRQ TIMERO_IRQn Step 4 5 Enable the TCR See table 427 on page 494 of LPC17xx_UM pTimer gt TCR 1 return 0 just those backed up by the exception stack frame We add extra push and pop instructions in the assembly routine The actual c_UARTO_IRQHandler does the rest of irq handling 63 __asm void TIMERO_IRQHandler void PRESERVES IMPORT c_TIMERO_IRQHandler PUSH r4 rii lr BL c_TIMERO_IRQHandler POP r4 r11 per brief c UARTO IRQ Handler void c_TIMERO_IRQHandler void LPC_TIMO gt

Download Pdf Manuals

image

Related Search

Related Contents

Sprühhalsband zur Hundeerziehung  White Rodgers 1E56N-444 Installation and Operation Instructions  CAUTION - Fuji Electric GmbH  Google - A Biografia - Inovação = ideias novas em ação  パーツリスト  KALCD32FHDXA User Manual  Manual de usuario equipo depilación definitiva TS30  Manual de servicio para el usuario Logano plus SB625  MODÈLES · MODELOS · MODELS · MODELLE  Mode d`emploi  

Copyright © All rights reserved.
Failed to retrieve file