Question? Leave a message!




Microcontroller lab manual pdf

microcontrollers and applications with lab manual and microprocessor and microcontroller lab manual for cse
KomalMittal Profile Pic
KomalMittal,India,Teacher
Published Date:13-07-2017
Website URL
Comment
Introduction to Microcontrollers Lab Manual Featuring the PIC24F Family  2011 Microchip Technology Inc. DS51963ANote 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 our products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts allow 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 device Trademarks applications and the like is provided only for your convenience The Microchip name and logo, the Microchip logo, dsPIC, and may be superseded by updates. It is your responsibility to KEELOQ, KEELOQ logo, MPLAB, PIC, PICmicro, PICSTART, ensure that your application meets with your specifications. 32 PIC logo, rfPIC and UNI/O are registered trademarks of MICROCHIP MAKES NO REPRESENTATIONS OR Microchip Technology Incorporated in the U.S.A. and other WARRANTIES OF ANY KIND WHETHER EXPRESS OR countries. IMPLIED, WRITTEN OR ORAL, STATUTORY OR FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor, OTHERWISE, RELATED TO THE INFORMATION, MXDEV, MXLAB, SEEVAL and The Embedded Control INCLUDING BUT NOT LIMITED TO ITS CONDITION, Solutions Company are registered trademarks of Microchip QUALITY, PERFORMANCE, MERCHANTABILITY OR Technology Incorporated in the U.S.A. FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip Analog-for-the-Digital Age, Application Maestro, chipKIT, devices in life support and/or safety applications is entirely at chipKIT logo, CodeGuard, dsPICDEM, dsPICDEM.net, the buyer’s risk, and the buyer agrees to defend, indemnify and dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, hold harmless Microchip from any and all damages, claims, FanSense, HI-TIDE, In-Circuit Serial Programming, ICSP, suits, or expenses resulting from such use. No licenses are Mindi, MiWi, MPASM, MPLAB Certified logo, MPLIB, conveyed, implicitly or otherwise, under any Microchip MPLINK, mTouch, Omniscient Code Generation, PICC, intellectual property rights. PICC-18, PICDEM, PICDEM.net, PICkit, PICtail, 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. © 2011, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved. Printed on recycled paper. ISBN: 978-1-61341-251-0 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. DS51963A-page 2 2011 Microchip Technology Inc.INTRODUCTION TO MICROCONTROLLERS LAB MANUAL Lab Manual Introduction INTRODUCTION The purpose of these labs is to introduce the basic concepts of designing microcon- troller based systems. Each lab will introduce a new concept and provide a starting template that will guide the student toward creating a successful project. Each lab includes a pre-lab section that the student should study prior to entering the lab. It includes a basic description of the topics under consideration, as well as links to many other resources that can be used for further study. DEVELOPMENT ENVIRONMENT This document describes how to use one of the starter kits as a development tool to emulate and debug firmware on a target board. ® The MPLAB Integrated Development Environment (IDE) is a free, integrated toolset for ® the development of embedded applications employing Microchip's PIC MCUs and ® ® dsPIC DSCs. MPLAB IDE runs as a 32-bit application on MS Windows (XP, Vista, or Windows 7), and is an easy-to-use tool that includes a host of free software components for fast application development and super-charged debugging. MPLAB IDE also serves as a single, unified graphical user interface for additional Microchip and third party software and hardware development tools. Moving between tools is easy, and upgrading from the free software simulator to hardware debug and programming tools is done quickly because MPLAB IDE has the same user interface for all tools. These labs will use Microchip MPLAB IDE v8.63. It is available from the lab instructor or as a free download from www.microchip.com. Future versions may work, but the exact instructions may no longer be accurate. Each lab will include a project template. This template will include all the settings required for a suitable solution on the target hardware. There are many different ways to solve each problem. Comments in the code like: ; ; CODE GOES HERE ; will guide the student to locations where code will typically need to be added for a successful outcome. Motivated students may choose to ignore those comments and come up with a different solution to the same problem.  2011 Microchip Technology Inc. DS51963A-page 5Introduction to Microcontrollers Lab Manual DEVELOPMENT HARDWARE These labs are based on the MX Module series manufactured by Stratford Digital. The MX Series includes modules from across all Microchip embedded controller families, and provides a common mechanical and electrical interface. The modules are suitable for a rapid-development environment, but are also engineered to be used in a produc- tion environment. The MX PIC24F EDU Module (STR001) is specifically designed for this lab. The main processor on this module is the Microchip PIC24FJ256GB110. This 16-bit controller has 256 Kb of internal flash memory and many useful peripheral modules. Each lab will explore various aspects of this controller. The MX PIC24F EDU Module also includes the PICkit™ on-board circuit that allows the board to connect to MPLAB IDE with only a standard USB cable. The debugging and programming resources normally found in an external PICkit 3, MPLAB ICD 3, or MPLAB REAL ICE™ in-circuit emulator are included on board for an optimal develop- ment environment. All labs require the MX PIC24F EDU Module to be inserted into the MX Educational Target Board (STR002). The MX Educational Target Board provides the power and I/O required by the MX PIC24F EDU Module. This board connects the various I/Os of the module to easy-to-use interface connectors including RS232 DB9 connectors, a breadboarding area, and common headers for other electrical busses. The MX Series is intended to provide an infrastructure that will allow the user to quickly develop their application on a known-good hardware platform. The commercial mod- ules come with on-board Ethernet and USB (device, host, and on-the-go), as well as various options for external memory. In addition, template projects are provided for MPLAB IDE that include fully working TCP/IP and USB stacks along with demo appli- cations. Only the custom firmware required for the specific application needs to be added. Note: Although the labs presented here are based on the MX Module series man- ufactured by Stratford Digital, they can easily be implemented on a variety of other development platforms from Microchip and third parties with minor modifications. Many of the labs are also applicable to other 16-bit Microchip products, including the PIC24H, dsPIC30F and dsPIC33F. For more information, visit www.microchip.com/academic. DS51963A-page 6 2011 Microchip Technology Inc.LABS Lab 0. Introduction to Microcontrollers 0.1 OBJECTIVE This lab is an introduction to the following concepts required to complete the labs: • MX PIC24F EDU Module • Microchip PIC24FJ256GB110 MCU • 16-bit MCU Assembly Instruction Set • Microchip MPLAB IDE Software v8.63 0.2 PRE-LAB 0.2.1 Reference Material • PIC24FJ256GB110 Family Data Sheet (DS39897) • 16-Bit MCU and DSC Programmer’s Reference Manual (DS70157) • MPLAB IDE User’s Guide (DS51519) 0.2.2 Assembly Language All labs will be written in assembly language. Assembly language is a low-level language for programming computers, microproces- sors, and microcontrollers. It is specific to a particular device or family of devices and is not typically portable between different processors. A utility program called an assembler is used to translate assembly language into the target hardware machine code. These labs will use Microchip's MPLAB ASM30 assem- bler to generate machine code for the PIC24FJ256GB110. Assembly language uses simple instructions, symbols, and numeric characters usually defined by either the assembler utility or the device hardware manufacturer. The assembler then performs a translation from the mnemonic assembly statements into hardware specific machine instructions and data. The machine instructions can then be programmed into the controller's memory and executed on the specific hard- ware. The “16-bit MCU and DSC Programmer's Reference Manual” (DS70157) from Micro- chip is a complete list of all assembler instructions for the Microchip 16-bit processor family, including the PIC24FJ256GB110. A further suggestion from Microchip: Microchip Technology Inc. strongly suggests a .s extension for assembly source files. This will enable you to easily use the C com- piler driver without having to specify the option to tell the driver that the file should be treated as an assembly file. See the “MPLAB C Compiler for PIC24 MCUs and dsPIC DSCs User's Guide” (DS51284) for more details on the C compiler driver. 0.2.3 Timing The project initializes the PIC24FJ256GB110 to run from its internal Fast RC oscillator. It configures the use of the internal PLL to create an internal clock running at 32 MHz (Fosc). The architecture of the PIC24 specifies that an instruction cycle (Fcy) is com-  2011 Microchip Technology Inc. DS51963A-page 7LABS prised of two internal clock cycles, i.e. 16 MHz. This represents an instruction period of 62.5 ns. Most instructions are executed in a single instruction cycle. This means that most instructions will execute in exactly 62.5 ns. The exception to this is when a conditional test is true or the program counter is changed as a result of the instruction. In these cases, the execution takes two instruc- tion cycles, with the additional instruction cycle(s) executed as a NOP. Common forms of these exceptions are the BRA (unconditional / computed branch), indirect CALL/ GOTO, all table reads and writes, and RETURN/RETFIE instructions. Certain instructions that involve skipping over the subsequent instruction require either two or three cycles if the skip is performed, depending on whether the instruction being skipped is a single-word or two-word instruction. Moreover, double-word moves require two cycles. The double-word instructions execute in two instruction cycles. 0.2.4 Delay Loops Because the instruction period is so small (62.5 ns), it is often necessary to slow pro- cessing down when human interaction is required. In this lab we will blink an LED. If we toggled the LED at anything close to the instruction frequency the human eye would not be able to detect the flashing. A typical delay loop looks like this: MOV 0xFFFF, W4 DELAY: NOP DEC W4, W4 BRA NZ, DELAY The way this loop works is that the first instruction, MOV 0xFFFF, W4, loads the W4 (this is an arbitrary working register and could be any register other than W15, which is the stack pointer) register with the value 65535, which is the number of times we want to loop. This instruction only gets executed once. The next instruction is the NOP instruction, which is a “no operation” instruction, the purpose of which is to waste a pro- cessor cycle. Next the DEC W4, W4 instruction decrements the value in W4, and finally the BRA NZ, DELAY checks if the value in W4 has reached zero. If the value in W4 has not reached zero, a branch is executed and we jump back to the NOP instruction and repeat until the W4 register eventually hits zero. At this point the branch is not taken and we fall out of the loop. Timing calculation for this delay loop: Instruction Cycles MOV 0xFFFF, W4 1 NOP 1 DEC W4, W4 1 BRA NZ, DELAY 2, if the branch is taken, and 1 if the branch is not taken. • The MOV instruction is executed once, 1 cycle • The loop consists of the NOP, DEC, and BRA instructions and gets executed 65535 times. Each time through the loop takes 4 cycles, except for the last time, which only takes 3 cycles since the branch is not taken • The total delay for this code is 1 cycle + (65535 x 4 cycles) – 1 cycle = 262140 cycles With a 16 MHz instruction frequency, the loop will take 262140 cycles x 62.5 ns/cycle = 0.01638375 sec to execute fully. DS51963A-page 8 2011 Microchip Technology Inc.0.2.5 I/O Ports The ability of the microcontroller to execute code is meaningless unless it can take inputs from its environment and drive outputs to control the environment. The digital I/O port is a primary method of doing just this. Microchip's PIC microcontrollers organize the digital I/Os into “ports”. Each port on the PIC24 is a collection of up to 16 individual I/Os, and they are named PORTA, PORTB, PORTC, etc. These I/Os are easily configurable and can be accessed individually or as a group. For now, we will discuss the ability to use them as digital inputs or digital outputs. All port pins have at least three registers directly associated with their operation as dig- ital I/Os. The Data Direction register (TRISA, TRISB, TRISC, …) determines whether the pin is an input or an output. If the data direction bit is a ‘1’, then the pin is an input. If the data direction bit is a ‘0’, then the pin is an output. Hint: Think “I” for Input and change “I” (letter I) to “1” (one) in your mind. Think “O” for Output and change “O” (letter O) to “0” (zero) in your mind. All port pins are defined as inputs by default. To write data to a digital output, a write to the appropriate Output Latch Register (LATA, LATB, LATC, …) is required. To read data from a digital input read the appropriate Input Port Register (PORTA, PORTB, PORTC, …). Example code to configure port C bit 2 as output and set it low: BCLR TRISC, 2 Configure port C bit 2 as output BCLR PORTC, 2 Set port C bit 2 latch low Example code to configure port C bit 0 as input and perform a bit compare on that input: BSET TRISC, 0 Configure port C bit 0 as an input NOP Required between a port direction change and port write BTSS PORTC, 0 Check if port C bit 0 is low One instruction cycle is required between a port direction change or port write opera- tion and a read operation of the same port. Typically, this instruction would be a NOP. 0.3 THE LAB 0.3.1 Objective Program the PIC24 microcontroller to blink an LED at a one second interval (LED on for one second, then off for one second). 0.3.2 Bonus Modify the code so that when one of the push buttons is held, the LED blinks at twice the frequency. You may choose any of the four push buttons. Note the push buttons are mapped to the following ports: ® Push Button PIC MCU Port SW1 Port G Bit 12 SW2 Port G Bit 13 SW3 Port G Bit 15 SW4 Port C Bit 1  2011 Microchip Technology Inc. DS51963A-page 9LABS 0.3.3 Pertinent Information The basic program flow is depicted in Figure 0-1. FIGURE 0-1: LAB 0 BASIC PROGRAM FLOW The template assembly file sets up this basic program flow. The student will need to add the appropriate code to the relevant sections of the file lab0-intro.s. As noted in the Pre-Lab, the maximum delay of a delay loop is about 0.016 seconds. Further delaying will be required to obtain the interval of one second. A nested loop (burying one loop within another loop) is one way to accomplish this. Hint: We advise that you start by writing simple code to initialize the LED port pin and turn the LED on before you dive in and write the delay loop. This will ensure that the project compiles and the device is programmed properly with the simplest code. Debugging of the delay loops will then be confined to just that section of code. 0.3.4 Creating a New Project See Appendix A. “Creating an MPLAB IDE Project” for details about using the Proj- ect Wizard to create a new project from scratch. The examples show the three files required to add to the project. In order to view the various files in the project, ensure that you have the Project Toolbar enabled. This is done by selecting ViewProject in the menu. It is also useful to be able to view the output window. This will display various status messages during the process of assembling and linking the project. To enable this window, make sure ViewOutput is selected in the menu. To run the assembler and linker to create the application binary, use the “Make” com- mand. You can access this through the menu ProjectMake or using the shortcut “F10” function key. If the make command is successful, the “BUILD SUCCEEDED” message will display at the end of the output window. DS51963A-page 10 2011 Microchip Technology Inc.0.3.5 Programming the Device In order to program the device, the build must complete successfully. This will create the binary image that is required to load into the device Flash. You must configure MPLAB IDE to use the licensed debugger circuit that resides on the MX PIC24F EDU module, see Figure 0-2. In MPLAB IDE, select “Licensed Debugger” from the menu ProgrammerSelect ProgrammerLicensed Debugger. FIGURE 0-2: SELECT PROGRAMMER Now all that is needed is to program the device. To do this, ensure the programming USB cable is connected, and select ProgrammerProgram from the menu. The output window will display the status of the process. Any errors will be noted in this window. Once programming is complete, the device should immediately begin to execute the code. If successful, you will see the LED blink at the intended rate.  2011 Microchip Technology Inc. DS51963A-page 11LABS NOTES: DS51963A-page 12 2011 Microchip Technology Inc.LABS Lab 1. Timers 1.1 OBJECTIVE The lab covers the following concepts: • PIC24F hardware timer modules • Assembly language CALL and RCALL instructions • Using MPLAB IDE to measure code execution time 1.2 PRE-LAB 1.2.1 Reference Material • PIC24FJ256GB110 Family Data Sheet (DS39897) • 16-Bit MCU and DSC Programmer’s Reference Manual (DS70157) • MPLAB IDE User’s Guide (DS51519) • PIC24F Reference Manual – Section 14. Timers (DS39704) 1.2.2 Timers The PIC24FJ256GB110 device offers five (5) 16-bit timers/counters designated as Timer1, Timer2, … With certain exceptions, all of the 16-bit timers have the same functional circuitry. The 16-bit timers are classified into three types to account for their functional differences: • Timer1 is a Type A timer • Timer2 and Timer4 are Type B timers • Timer3 and Timer5 are Type C timers Type B and Type C timers can be combined to form a 32-bit timer. Each timer module consists of the following readable/writable registers: • TMRx: 16-bit Timer Count register • PRx: 16-bit Timer Period register associated with the timer • TxCON: 16-bit Timer Control register associated with the timer Timers can be run from either an external clock connected to the TxCK pin, or the inter- nal clock (Fosc/2). This lab will use the internal clock as the MX PIC24F EDU Module does not connect an external clock to the TxCLK pins. 1.2.3 Subroutine CALL A subroutine CALL in assembly is a powerful tool for reusing code and keeping your code clean and legible. Low-level functions can be abstracted into higher level func- tions by the use of subroutine. This is similar to the use of a function in the 'C' language. In fact, 'C' functions make use of the RCALL assembly instruction. A CALL is similar to a GOTO or BRA instruction except that it stores the address of the next instruction and allows you to return to it with the RETURN instruction.  2011 Microchip Technology Inc. DS51963A-page 13LABS The 16-bit MCU and DSC device families have two types of calls: • CALL – Call subroutine • RCALL – Relative call When performing function calls, it is recommended that RCALL be used instead of CALL, since RCALL only consumes 1 word of program memory. Table 1-1 highlights some of the main differences in the behavior of CALL and RCALL in modifying the program flow. TABLE 1-1: LAB 1 METHODS OF MODIFYING PROGRAM FLOW Condition/Instruction PC Modification Software Stack Usage Sequential Execution PC = PC + 2 None (1) BRA Expr PC = PC + 2Slit16 None (Branch Unconditionally) (1) BRA Condition, Expr PC = PC + 2 (condition false) None (Branch Conditionally) PC = PC + 2Slit16 (condition true) (1) PC = lit23 PC + 4 is PUSHed on the CALL Expr (2) (Call Subroutine) stack CALL Wn PC = Wn PC + 2 is PUSHed on the (2) (Call Subroutine Indirect) stack (1) GOTO Expr PC = lit23 None (Unconditional Indirect Jump) GOTO Wn PC = Wn None (Unconditional Indirect Jump) (1) RCALL Expr PC = PC + 2Slit16 PC + 2 is PUSHed on the (2) (Relative Call) stack RCALL Wn PC = PC + 2Wn PC + 2 is PUSHed on the (2) (Computed Relative Call) stack Exception Handling PC = address of the exception PC + 2 is PUSHed on the (3) handler (read from vector table) stack PC = Target REPEAT instruction PC not modified (if REPEAT None (REPEAT Looping) active) Note 1: For BRA, CALL and GOTO, the Expr may be a label, absolute address or expression, which is resolved by the linker to a 16-bit or 23-bit value (Slit16 or lit23). 2: After CALL or RCALL is executed, RETURN or RETLW will POP the Top-of-Stack (TOS) back into the PC. 3: After an exception is processed, RETFIE will POP the Top-of-Stack (TOS) back into the PC. 1.2.4 IDE Concepts: Stopwatch The Stopwatch is useful for simple timing between program halts to time the execution of sections of code. Several debug tools have a stopwatch feature including. • MPLAB SIM Simulator: DebuggerStopwatch • MPLAB ICD 3 in-circuit debugger: DebuggerBreakpoints, Stopwatch To use the StopWatch with MPLAB SIM Simulator, select DebuggerSelect Tool4 MPLAB SIM. DS51963A-page 14 2011 Microchip Technology Inc.Setup the Simulator processor frequency: 1. Select DebuggerSettings and then click on the Osc/Trace tab. This is where the clock speed of your hardware is set. These values will also be used to set certain fields in the Stopwatch. 2. Select the units of frequency. 3. Enter the processor frequency value. The lab project initializes the PIC24FJ256GB110 to run from its internal Fast RC oscil- lator and configures the use of the internal PLL to create an internal clock running at 32 MHz. FIGURE 1-1: LAB 1 STOPWATCH SETUP Now the Stopwatch is configured. Start the Stopwatch using the menu item. Select DebuggerStopwatch. FIGURE 1-2: LAB 1 STOPWATCH USE  2011 Microchip Technology Inc. DS51963A-page 15LABS To use the Stopwatch, insert two breakpoints around the section of code you wish to time. Run the code to the first breakpoint, “Zero” the StopWatch and then run the code to the next breakpoint. The Stopwatch will show the number of instruction cycles and time between the two breakpoints. Hint: When using the Stopwatch with MPLAB SIM Simulator, it is important to set the Simulator Processor Frequency correctly. Otherwise the Stopwatch time will be incor- rect. An easy way to test if this has been set properly is to set breakpoints around a simple instruction such as MOV. This should execute in 0.062500 uSecs. 1.2.5 The Lab 1.2.5.1 OBJECTIVE Program the PIC24 microcontroller to use a hardware timer to blink an LED at a 1 sec- ond interval (LED on for 1 second then off for 1 second). Show your calculations for the Timer delay. Use a subroutine CALL or RCALL somewhere in the code. A common use would be to move the configuration instructions for the timer into a subroutine. This keeps the main line code cleaner with only one line required to initialize the timer module at the start of the code. Use the stopwatch to check your timer and verify it is actually running at 1 sec (5 sec for the bonus). Hint: Use one breakpoint at your LED toggle instruction (BTG PORTC, 2), run the code to that breakpoint, then “Zero” the stopwatch and run it again. 1.2.5.2 BONUS Modify the code and setup a 32-bit TIMER to blink the LED at a 5 sec interval. Show your calculations for the timer delay. 1.2.5.3 PERTINENT INFORMATION The basic program flow is illustrated in Figure 1-3. DS51963A-page 16 2011 Microchip Technology Inc.FIGURE 1-3: LAB 1 BASIC PROGRAM FLOW The template assembly file sets up this basic program flow. The student will need to add the appropriate code to the relevant sections of the file lab1-timers.s.  2011 Microchip Technology Inc. DS51963A-page 17LABS NOTES: DS51963A-page 18 2011 Microchip Technology Inc.LABS Lab 2. Interrupts 2.1 INTERRUPTS 2.1.1 Objective This lab covers the following concepts: • Using interrupts on the PIC24F • Using the MPLAB IDE Watch window to inspect real-time register values during programming debugging 2.2 PRE-LAB 2.2.1 Reference Material • PIC24FJ256GB110 Family Data Sheet (DS39897) • 16-Bit MCU and DSC Programmer’s Reference Manual (DS70157) • MPLAB IDE User’s Guide (DS51519) • PIC24F Family Reference Manual – Section 8. Interrupts (DS39707) • PIC24F Family Reference Manual – Section 14. Timers (DS39704) 2.2.2 Interrupts An interrupt (also called an exception) is an asynchronous signal or a synchronous software event intended to inform the processor that there is a need for a change in execution. Interrupts were introduced to avoid wasting the processor’s time in a polling loop. This method means the processor is fully executing while waiting for an external event, often without the ability to handle other system events. When an interrupt occurs, it causes the processor to save its current state on the soft- ware stack and then execute a special subroutine. The Interrupt Vector Table is a list of the addresses to these special routines. The PIC24F allows for the possibility of a unique subroutine for each interrupt source. The special subroutines are known as Interrupt Service Routines (ISRs). It is good design practice for an ISR to execute as quickly as possible, so the processor should spend as little time in the ISR as possible. This becomes an issue when you have mul- tiple, real-time, nested interrupts. In all cases, loops and polling should be avoided in any ISR. The main difference between an ISR and a normal subroutine is that before executing an ISR, the processor saves its current state so that when the ISR is complete, the pro- cessor state can be exactly reproduced and program flow will continue as if the inter- rupt did not occur (with the exception of any changes caused by the ISR itself). As a result, the last instruction of an ISR must be a RETFIE instruction. This restores the processor state.  2011 Microchip Technology Inc. DS51963A-page 19LABS The processor saves the following information on the software stack as illustrated in Figure 2-1: • The current PC value • The low byte of the processor STATUS register (SRL) • The IPL3 Status bit (CORCON3) FIGURE 2-1: LAB 2 STACK LOCATION The RETFIE (Return from Interrupt) instruction will unstack the PC return address, IPL3 status bit and SRL register, to return the processor to the state and priority level prior to the interrupt sequence. For the PIC24F, the Interrupt Vector Table (IVT) resides in program memory, starting at location 0x000004. It contains 126 vectors, consisting of 8 non-maskable trap vectors, plus up to 118 sources of interrupt. Each interrupt vector contains a 24-bit wide address. The value programmed into each interrupt vector location is the starting address of the associated Interrupt Service Routine (ISR). The Alternate Interrupt Vector Table (AIVT) is located after the IVT, as shown in Figure 2-2. Access to the AIVT is provided by the ALTIVT control bit (INTCON215). If the ALTIVT bit is set, all interrupt and exception processes will use the alternate vec- tors instead of the default vectors. The alternate vectors are organized in the same manner as the default vectors. DS51963A-page 20 2011 Microchip Technology Inc.FIGURE 2-2: LAB 2 PRIMARY AND ALTERNATE INTERRUPT VECTOR TABLE Note: A device Reset is not a true exception because the interrupt controller is not involved in the Reset process. The PIC24F device clears its registers in response to a Reset, which forces the PC to zero. The processor then begins program execution at location 0x000000. When a UART1 Receiver interrupt occurs, the processor stores its current state on the software stack and then jumps to the address stored in the vector table for that inter- rupt. For the PIC24FJ256GB110, the UART1 Receiver uses interrupt 11, Interrupt Vec- tor Table Address 0x00002A. The processor would therefore branch to and execute the code located at the address stored at 0x00002A when a UART1 Receiver interrupt occurs. Refer to the Microchip “PIC24FJ256GB110 Family Data Sheet” (DS39897) for a com- plete list of “implemented interrupt vectors”. Setting up interrupts in assembly for the PIC24FJ256GB110 is actually quite easy. MPLAB IDE does a lot of the overhead work and each interrupt has a predefined label. Table 2-1 lists some of these predefined labels.  2011 Microchip Technology Inc. DS51963A-page 21LABS TABLE 2-1: LAB 2 LIST OF SOME DEFINED INTERRUPTS Label Interrupt Source Address __INT0Interrupt External Interrupt 0 0x00014 __IC1Interrupt Input Capture 1 0x00016 __OC1Interrupt Output Compare 1 0x00018 __T1Interrupt TIMER1 0x0001A __Interrupt4 Interrupt 4 0x0001C __I2CInterrupt Input Compare 2 0x0001E __OC2Inerrupt Output Compare 2 0x00020 __T2Interrupt TIMER2 0x00022 __T3Interrupt TIMER3 0x00024 __SPI1ErrInterrupt SPI1 Error 0x00026 __SPI1Interrupt SPI1 Event 0x00028 __U1RXInterrupt UART1 Receiver 0x0002A __U1TXInterrupt UART1 Transmitter 0x0002C __ADC1Interrupt ADC1 Conversion Done 0x0002E __Interrupt14 Interrupt 14 0x00030 __Interrupt15 Interrupt 15 0x00032 __SI2C1Interrupt I2C1 Slave Event 0x00034 __MI2C1Interrupt I2C1 Master Event 0x00036 __CompInterrupt Comparator Event 0x00038 __CNInterrupt Input Change Notification 0x0003A __INT1Interrupt External Interrupt 0 0x0003C __U2RxInterrupt UART2 Receiver 000050h To setup an interrupt in assembly, an interrupt label must first be declared. Next, the label must be used to indicate the desired ISR, not unlike any other label for a normal subroutine. The only difference between a subroutine and ISR, is that for an ISR the label is unique and it must end with a RETFIE instruction. .global __T1Interrupt ; Declare Timer1 ISR name global __T1Interrupt: ; Timer1 ISR code goes here RETFIE ; Return from Interrupt Service Routine To verify that the ISR label is at the correct memory location in program memory, select ViewProgram Memory and choose the Machine tab. DS51963A-page 22 2011 Microchip Technology Inc.