Home

Assembler/Linker/Librarian User's Guide

image

Contents

1. ELSE FILES c018i o FILES clib lib FILES p18f6722 1ib TFI FI IFDEF DEBUGCODESTART CODEPAGE NAME page START 0x0 END CODEEND CODEPAGE AME debug START DEBUGCODESTART END CEND F LSE Si CODEPAGE AME page START 0x0 END 0x1FFFF FI CODEPAGE AME idlocs START 0x200000 END 0x200007 PROTECTED CODEPAGE NAME config START 0x300000 END 0x30000D PROTECTED CODEPAGE AME devid START 0x3FFFFE END 0x3FFFFF PROTECTED CODE PAGE AME eedata START 0xF00000 END 0xF003FF PROTECTED IFDEF _EXTENDEDMODE DATABANK AME gpre START 0x0 END 0x5F ELSE ACCESSBANK NAME accessram START 0x0 END 0x5F FI DATABANK AME gpr0 START 0x60 END 0xFF DATABANK AME gpr1 START 0x100 END 0x1FF DATABANK AME gpr2 START 0x200 END 0x2FF DATABANK NAME gpr3 START 0x300 END 0x3FF DATABANK AME gpr4 START 0x400 END 0x4FF DATABANK AME gpr5 START 0x500 END 0x5FF DATABANK AME gpr6 START 0x600 END 0x6FF DATABANK AME gpr7 START 0x700 END 0x7FF DATABANK AME gpr8 START 0x800 END 0x8FF DATABANK AME gpr9 START 0x900 END 0x9FF DATABANK NAME gpr10 START 0xA00 END 0xAFF DATABANK AME gpr11 START 0xB00 END 0xBFF DATABANK AME gpr12 START 0xC00 END 0xCFF DATABANK AME gpr 13 START 0xD00 END 0xDFF IFDEF DEBUGDATASTART DATABANK AME gprl4 START 0xE00 END _DATAEND DS33014L page 248 O 1994 2013 Microchip Technology Inc Linker Scripts DATABANK
2. ns gu Ts 1994 2013 Microchip Technology Inc DS33014L page 15 Assembler Linker Librarian User s Guide NOTES DS33014L page 16 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE PIC1X MCU Language Tools and MPLAB X IDE INTRODUCTION The MPASM assembler the MPLINK object linker and the MPLIB object librarian are typically used together under MPLAB X Integrated Development Environment IDE to provide GUI development of application code for PIC1X MCU devices PIC10 12 16 18 MCUs The operation of these 8 bit language tools with MPLAB X IDE is discussed here Additionally the MPLAB C Compiler for PIC18 MCUs MPLAB C18 may be used with the above tools For more on this compiler see the Microchip website http www microchip com for additional information and documentation These language tools were initially developed for use in Microsoft Windows However the MPASMX toolchain does function in Linux and Mac OS with support available for the and characters The C18 toolchain also supports these operating systems Topics covered in this chapter MPLAB X IDE and Tools Installation MPLAB X IDE Setup MPLAB X IDE Projects Project Setup Project Example MPLAB X IDE AND TOOLS INSTALLATION MPLAB
3. A Ags O 1994 2013 Microchip Technology Inc DS33014L page 11 CONVENTIONS USED Assembler Linker Librarian User s Guide The following conventions may appear in this documentation DOCUMENTATION CONVENTIONS Description Represents Examples Arial font Italic characters Referenced books MPLAB IDE User s Guide Emphasized text is the only compiler Initial caps A window the Output window A dialog the Settings dialog A menu selection select Enable Programmer Quotes A field name in a window or Save project before build dialog Underlined italic text with A menu path File gt Save right angle bracket Bold characters A dialog button Click OK A tab Click the Power tab Text in angle brackets lt gt A key on the keyboard Press lt Enter gt lt F1 gt Courier font Plain Courier Sample source code define START Filenames autoexec bat File paths e mecl8 h Keywords _asm endasm static Command line options Opa Opa Bit values Oye T Constants OxFF A Italic Courier A variable argument file o where file can be any valid filename Square brackets Optional arguments mpasmwin options file options Curly brackets and pipe character Choice of mutually exclusive
4. DS33014L page 242 1994 2013 Microchip Technology Inc 11 5 2 The CoD Defining EPAG Linker Scripts ROM Memory Regions E directive is used for program code initialized data values constant data values and external memory It has the following format CODEPAGE NAME memName START addr END addr PROTECTED FILL fillvalue where memName Any ASCII string used to identify a CODEPAGE addr A decimal e g 30 or hexadecimal e g OXFF number specifying an address An optional keyword FILL A keyword used to specify a value which fills any unused portion of a memory block If this value is in decimal notation it is assumed to be a 16 bit quantity If it is in hexadecimal notation e g 0x2346 it may be any length divisible by full words 16 bits PROTECTED A keyword that indicates a region of memory that only can be used by program code that specifically requests it EXAMPLE 11 8 ROM EXAMPLE The program memory layout for a PIC16F877A microcontroller is shown below Memory Address Reset Vector Start 0000h Interrupt Vector Start 0004h User Memory Space 0005h 07FFh User Memory Space 0800h OFFFh User Memory Space 1000h 17FFh User Memory Space 1800h 1FFFh 1D Locations 2000h 2003h Reserved 2
5. Vil O 1994 2013 Microchip Technology Inc DS33014L page 281 Assembler Linker Librarian User s Guide 13 6 2 2 ASSEMBLER LINKER SCRIPT The modifed PIC18F8722 assembler linker script file shown below demonstrates suggested modifications for external memory applications First the CODEPAGE statements are added CODEPAGE NAME vectors START 0x0 END 0x29 PROTECTED IFDEF _DEBUGCODESTART CODEPAGE NAME page START 0x2A END _CODEEND CODEPAGE NAME debug START _DEBUGCODESTART END _CEND PROTECTED HE LS F CODEPAGE NAME page START 0x2A END 0x1FFFF TFI CODEPAGE NAME xsram START 0x020000 END 0x1FFFFF PROTECTED CODEPAGE NAME idlocs START 0x200000 END 0x200007 PROTECTED CODE PAGE NAME config START 0x300000 END 0x30000D PROTECTED CODE PAGE NAME devid START 0x3FFFFE END 0x3FFFFF PROTECTED CODE PAGE NAME eedata START 0xF00000 END 0xF003FF PROTECTED Then the vectors program and external memory section is added IFDEF _CRUNTIME SECTION AME CONFIG ROM config SECTION NAME VECTORS ROM vectors SECTION NAME PROG ROM page SECTION NAME SRAM ROM xsram IFDEF DEBUGDATASTART STACK SIZE 0x100 RAM gpr13 HE LSE STACK SIZE 0x100 RAM gpr14 TFI TFI DS3301
6. TABLE A 7 14 BIT BYTE ORIENTED FILE REGISTER OPERATIONS CONTINUED Hex Mnemonic Description Function 02df SUBWF f d Subtract W from f f W gt d 3Bdf SUBWFB f d Subtract with Borrow Wfromf f W B d OEdf SWAPF f d Swap halves f 0 3 o f 4 7 gt d 06df XORWF f d Exclusive OR W and f W XOR f d Operation in 14 bit extended instruction set but not 14 bit instruction set TABLE A 8 14 BIT BYTE ORIENTED SKIP OPERATIONS Hex Mnemonic Description Function OBd DECFSZ f d Decrement f skip if zero f 1 d skip if 0 OFdf INCFSZ f d Increment f skip if zero f 1 d skip if O TABLE A 9 14 BIT BIT ORIENTED FILE REGISTER OPERATIONS Hex Mnemonic Description Function 4b BCF f b Bit clear f 0 gt f b 5bf BSF f b Bit set f 1 gt f b TABLE A 10 14 BIT BIT ORIENTED SKIP OPERATIONS Hex Mnemonic Description Function 6bf BTFSC f b Bit test skip if clear skip if f b O 7bf BTFSS f b Bit test skip if set skip if f b 1 TABLE A 11 14 BIT LITERAL OPERATIONS Hex Mnemonic Description Function 3Ekk ADDLW kk Add literal to W kk WREG gt WREG 39kk ANDLW kk AND literal and W kk AND WREG gt WREG 38kk IORLW kk Incl OR literal and W kk OR WREG gt WREG 002k MOVLB k Move literal to BSR k gt BSR 31 1 kk MOVLP kk Move literal to PCLATH kk gt PCLATH 30kk MOVLW kk Move Literal to W kk gt WREG 3Ckk SUBLW kk Subtract W from literal kk WREG gt WREG 3Akk XORLW kk Exclusive OR literal and W kk XOR W
7. 1994 2013 Microchip Technology Inc DS33014L page 323 Assembler Linker Librarian User s Guide A8 PIC18 DEVICE INSTRUCTION SET Microchip s new high performance 8 bit microcontroller family uses a 16 bit wide instruction set This instruction set consists of 76 instructions each a single 16 bit wide word 2 bytes Most instructions operate on a file register f and the working register WREG accumulator The result can be directed either to the file register or the WREG register or to both in the case of some instructions A few instructions operate solely on a file register BSF for example The instruction set is grouped into the following categories byte oriented file register operations bit oriented file register operations control operations literal operations and memory operations Additionally extended mode instructions are shown in Section A 9 PIC18 Device Extended Instruction Set Instruction opcode is show in hex by making certain assumptions either listed in the key or as a footnote For more information on the opcode bit values for each instruction as well as the number of cycles per instruction status bits affected and complete instruction details see the relevant device data sheet TABLE A 16 PIC18 BYTE ORIENTED REGISTER OPERATIONS Hex Mnemonic Description Function 27 ADDWE f d a ADD WREG to f WREG f gt des
8. Extended mode See MPASM C17 C18 Suite tab Macro Definitions Add macro directive definitions Restore Defaults Restore tab default settings Use Alternate Settings Text Box Enter options in a command line non GUI format Memory Model Category Generate Command Line Code Model Select a code program memory ROM model Choose from small x64K bytes or large gt 64K bytes Data Model Select a data data memory RAM model Choose from large all RAM banks or small access RAM only Stack Model Select a stack model Choose from single bank or multiple bank Restore Defaults Restore tab default settings Use Alternate Settings Text Box Enter options in a command line non GUI format Optimization Category Generate Command Line Disable Disable optimization Debug Enable optimizations for debugging Enable All Enable all optimizations Custom Enable optimization and select individual optimizations Procedural Abstraction For Enable All and Custom optimizations set the desired num passes ber of passes for procedural abstraction Restore Defaults Restore tab default settings Use Alternate Settings Text Box Enter options in a command line non GUI format DS33014L page 40 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB IDE v8 Build Options Dialog MPLINK Linker Tab Select a category
9. sseem 154 4 63 udata acs Begin an Object File Access Uninitialized Data Section PIC 18 MCUs 156 4 64 udata ovr Begin an Object File Overlayed Uninitialized Data Section 158 4 65 udata_shr Begin an Object File Shared Uninitialized Data Section PIC12 16 MCUs 160 4 66 undefine Delete a Substitution Label sse emen 162 4 67 variable Declare Symbol Variable ss 163 4 68 while Perform Loop While Condition is True ssssssssssssseeeneeeeenne nennen 165 DS33014L page 4 1994 2013 Microchip Technology Inc Table of Contents Chapter 5 Assembler Examples Tips and Tricks o A A 169 5 2 Example of Displaying Count on Ports sise 170 5 3 Example of Port B Toggle and Delay Routines ss 171 5 4 Example of Calculations with Variables and Constants sssse em 178 5 5 Example of a 32 Bit Delay Routine iii 180 5 6 Example of SPI Emulated in Firmware sisi 182 5 7 Example of Hexadecimal to ASCII Conversion essen emen 184 5 8 Other Sources of Examples iii 185 5 9 Tips amc 186 Chapter 6 Relocatable Objects 6 1 Introduction a Deer men EAS He E a reed iia 189 6 2 Header Files EE 189 6 3 Program Memory Rc 190 6 4 Low High and Upper Operators rusia 191 6 5 RAM Allocation isn naa io 194 6 6 Configuration Bits and ID Locations ss 195 6 7 Accessing Labels From Oth
10. 1994 2013 Microchip Technology Inc DS33014L page 119 Assembler Linker Librarian User s Guide 4 36 idata BEGIN AN OBJECT FILE INITIALIZED DATA SECTION 4 36 1 Syntax label idata RAM address 4 36 2 Description This directive declares the beginning of a section of initialized data If 1abe1 is not specified the section is named idata The starting address is initialized to the specified address or will be assigned at link time if no address is specified No code can be placed by the user in this segment The linker will generate a look up table entry for each byte specified in an idata section You must then link or include the appropriate initialization code Examples of initialization code that may be used and modified as needed may be found with MPLINK linker sample application examples Note This directive is not available for 12 bit instruction width PIC10 some PIC12 PIC16 devices The res db and dw directives may be used to reserve space for variables res will generate an initial value of zero db will initialize successive bytes of RAM dw will initialize successive bytes of RAM one word at a time in low byte high byte order Data initialized using db or dw will be padded with 34 RETLW instead of 00 This is because the idata directive reserves space in data memory while putting the initialization values in program memory and the application code must then copy the initialization values from progra
11. Topics covered are Example of Displaying Count on Ports Example of Port B Toggle and Delay Routines Example of Calculations with Variables and Constants Example of a 32 Bit Delay Routine Example of SPI Emulated in Firmware Example of Hexadecimal to ASCII Conversion Other Sources of Examples Tips and Tricks 1994 2013 Microchip Technology Inc DS33014L page 169 Assembler Linker Librarian User s Guide 5 2 EXAMPLE OF DISPLAYING COUNT ON PORTS Directives highlighted in this example are include end 5 2 1 Program Functional Description This simple program continually increases the count on PORTA and PORTB This count may be displayed in software in the SFR or Watch es window of the IDE or in hardware on connected LEDs or a scope The count may be slowed down using a delay routine see other examples Once the count has increased to OxFF it will roll over to 0x00 and begin again The application is written as absolute code i e you use only the assembler to generate the executable not the assembler and linker The standard header file for the processor selected is included using include The port output data latches are then cleared Port A must be set up for digital I O as on power up several pins are analog Data direction registers TRISx are cleared to set port pins to outputs A loop named Loop is entered where the value of each port is increased indefinitely until the program is halted Final
12. A CODEPAGE DATABANK or SHAREBANK directive does not specify a NAME START or END attribute or another attribute is specified which is not valid Invalid attributes for SECTION in cmdfile line A SECTION directive must have a NAME and either a RAM or ROM attribute 1994 2013 Microchip Technology Inc DS33014L page 285 Assembler Linker Librarian User s Guide Invalid attributes for STACK in cmdfile line A STACK directive does not specify a SIZE attribute or another attribute is specified which is not valid k switch requires lt pathlist gt A semicolon delimited path must be specified Enclose directory names containing embedded spaces with double quotes For example k c mylkr c program files microchip mpasm suite lkr switch requires lt pathlist gt A semicolon delimited path must be specified Enclose directory names containing embedded spaces with double quotes For example l c mylib c program files microchip mpasm suite m switch requires lt filename gt A map filename must be specified For example m main map Multiple inclusion of library file filename A library file has been included multiple times either on the command line or with a FILES directive in a linker script file Remove the multiple references Multiple inclusion of linker script file emdfile A linker script file can only be included once Remove multiple INCLUDE directives to the referenced li
13. a o o v n in d O 1994 2013 Microchip Technology Inc DS33014L page 261 Assembler Linker Librarian User s Guide 13 3 2 Modifying Templates and Linker Script Files For this sample application assembly code is added to the template but the generic linker script is not edited In general you will modify templates to create your own application code but you should not need to modify the generic linker script file Still there are reasons why you might want to customize a linker script as shown in the other sample applications In addition a case where you might want to modify the linker script is when you want to use a C code data object that is larger than 256 bytes such as a large array This application is discussed in the MPLAB C Compiler for PIC18 MCUs Getting Started DS51295 FAQ 10 Modified 18F8722TMPO ASM In the template add the following udata section A Oscillator Selection CONFIG OSC LP LP Array variables array UDATA element1 RES 1 element 2 RES 1 element 3 RES 1 element 4 RES 1 element5 RES 2 KKK KKK KKK KKK KK KAR AAA ARA AAA kk kk ck kk ck ko kk kk kkkkkkkkkkkkkkkkk kk Ck ko ck ko kv kv A kv ko ko ko ko k ko Variable definitions Then in the main code portion add the following program code pORCECkCkCkckckckckckokokeckokockck KK EKER koe heck ke KK ERK KEKE KA AE heck Sk e hock ck koe koc ke ke koe heck Sk he hok ck koc ko koc EX ke ke kk Start of mai
14. check that the Hex File Format is set to INHX32 Then check the checkbox for Generate map file 3 Click on the MPASM C17 C18 Suite tab For Categories All Options check that the Build normal target invoke MPLINK is selected 4 Click OK on the bottom of the dialog to accept the build options and close the dialog 5 Select Project gt Save Project to save the current configuration of the Example project Build the Project Select Project gt Build All to build the project Note You also may right click on the project name Example mcp in the project tree and select Build All from the pop up menu The Output window should appear at the end of the build and display the build results FIGURE 4 OUTPUT WINDOW BUILD TAB Build Version Control Find in Files Clean Deleting intermediary and output files Clean Done Executing C Program Files MPLAB IDE MCHIP_Tools mpasmwin exe q p16F84A Example asm l Example Ist e E Executing C Program Files MPLAB IDE MCHIP_Tools mpasmwin exe q p16F84A Example2 asm l Example2 Ist Je Executing C Program Files MPLAB IDE MCHIP_Tools mplink exe C Program Files MPLAB IDE MCHIP_Toaols LKR 1 MPLINK 3 70 01 Linker Copyright c 2004 Microchip Technology Inc Errors SH MP2COD 3 70 01 COFF to COD File Converter Copyright c 2004 Microchip Technology Inc Errors T MP2HEX 3 70 01 COFF to HEX File Converter C
15. 264 Alida 114 196 External Label 114 External Memory 188 F TV eese needed 104 File EITOE en ER REIN RU defende 207 BI BEE 73 PIRES Sci rt rd dado 237 LR is 116 Final Frontier idee 153 G Generic Linker Script Example 248 Generic Linker Scripts eeeeeeeeeeeeene 261 global 5 unie Re 119 H Header Files 130 174 189 H x Files ingens 21 37 57 227 1994 2013 Microchip Technology Inc DS33014L page 333 Assembler Linker Librarian User s Guide Hexadecimal to Decimal Conversion 00s1110 330 Le DE 233 higlizic i a mere 69 191 qos esee ne IU E 233 l U siii e NINE a 233 N t ege Eege 233 ID Locations En 123 195 Wes e E E 233 306 idala eR 120 194 SEI n eo E 233 306 idata acsi cente cde tls 122 ENEE 233 idlocs eee nete dee ates 123 Linker Proceseing es 251 if Seales as Rinne oe ct a a E NC MER ninja ta OE Cem ee EE E ES OE 125 Linker Scripts PR MEI ES 21 A 37 226 235 EE EE 102 Debug TOO BREET 235 le EE 104 Standard 236 te e I PE 127 Linux SUpport s see er S ee i di 17 IFDEF ELSE FI in Linker Scripts 245 EE 131 le EE 129 Listing Directives cccccsscesssessessessesssseseesstesseesseeseees 73 INCLUDE seen 238 GITOD a B ue 106 nie ie nio o E E n eroe eet e dune 130 errorlevel 25m Nek A 108 Include Additional Source Pie 130 It See 131 Include File 54 SEELEN 138 te E 70 AOliSt cutie AE A T T 140
16. Command Line Example 10 2 IDE INTERFACE The MPLINK linker is commonly used with the MPASM assembler in an MPLAB X IDE or MPLAB IDE v8 project to generate relocatable code For more information on this use see the MPASM assembler on line Help file The linker may also be used in the IDE with the MPLAB C18 C compiler For more information on Microchip compilers see the MPLAB C18 C compiler documentation listed in Recommended Reading 1994 2013 Microchip Technology Inc DS33014L page 231 Assembler Linker Librarian User s Guide 10 3 COMMAND LINE INTERFACE MPLINK linker can be used in the IDE or directly from a command line When used in an IDE all of MPLINK linker s options are available through the Project Properties dialog File gt Project Properties for MPLAB X IDE or MPLINK Linker tab accessed from the Project gt Build Options dialog in MPLAB IDE v8 When using MPLINK linker in a batch file or directly from the command line the linker is invoked with the following two syntaxes mplink lkrscript partnumber objfiles libfiles options mplink partnumber objfiles libfiles options lkrscript is the name of a linker script file All linker script files must have the extension 1kr It is not necessary to add the linker script file name to the command line if you will be using the generic linker script as described in the next paragraph However if you have your own modified script you must include the name on th
17. TABLE A 1 12 BIT BYTE ORIENTED FILE REGISTER OPERATIONS Hex Mnemonic Description Function 1Ef ADDWF f d Add W and f WREG f gt dest 16f ANDWF fea AND W and f WREG AND f gt dest 06f CLRF Clear f 0f 040 CLRW Clear W 0 gt WREG 26f COMF f d Complement f NOT f dest OEf DECE f d Decrement f f 1 dest 2Ef DECFSZ f d Decrement f skip if zero f 1 gt dest skip if zero 2Af INCF f d Increment f f 1 gt dest 3Ef INCFSZ f d Increment f skip if zero f 1 gt dest skip if zero 12f IORWF f d Inclusive OR W and f WREG OR f gt dest 22f MOVF f d Move f f dest 02f MOVWF Move W to f WREG 5f 000 NOP No operation 36f RLF f d Rotate left f register f C et Tien ds 0 La 32f RRE fd Rotate right f mes m Does esee 0 OAf SUBWF f d Subtract W from f f WREG gt dest 3Af SWAPF f d Swap halves f 1 0 3 lt gt f 4 7 gt dest 1Af XORWF f d Exclusive OR W and f WREG XOR f gt dest Assuming default bit value for d TABLE A 2 12 BIT BIT ORIENTED FILE REGISTER OPERATIONS Hex Mnemonic Description Function 4pf BCF f b Bit clear f 0 gt f b 5bf BSF f b Bit set f 1 gt f b 6bf BTFSC f b Bit test skip if clear skip if f b O 7bf BTFSS f b Bit test skip if set skip if f b 1 1994 2013 Microchip Technology Inc DS3
18. to expand 4 Select MPASM Assembler mpasmwin exe Under Location a path to the executable file should be displayed If no path is displayed enter one or browse to the location of this file The default location is listed in MPASM Toolsuite Installation 5 Select MPLINK Object Linker mplink exe Under Location a path to the executable file should be displayed If no path is displayed enter one or browse to the location of this file The default location is listed in MPASM Toolsuite Installation 6 Select MPLIB Object Librarian mplib exe Under Location a path to the executable file should be displayed If no path is displayed enter one or browse to the location of this file The default location is listed in MPASM Toolsuite Installation 7 For the optional MPLAB C18 C compiler select Microchip C18 Toolsuite and expand Executables Select MPLAB C18 C Compiler ncc18 exe and check the install path Ensure the other tools in this toolsuite point to the MPLAB C18 installation subdirectories and not the directories for the Microchip MPASM Toolsuite The default location is listed in C18 Toolsuite Installation 8 Click OK 1994 2013 Microchip Technology Inc DS33014L page 35 Assembler Linker Librarian User s Guide MPLAB IDE PROJECTS A project in MPLAB IDE is a group of files needed to build an application along with their associations to va
19. 11 8 CONDITIONAL LINKER STATEMENTS Generic linker scripts contain conditional statements and macros to accommodate several different methods for linking code Debug vs Release MPLAB IDE v8 Only e g for the MPLAB REAL ICE in circuit emulator C code vs Assembly PIC18 Extended Microcontroller mode vs Traditional mode Being able to use one linker script instead of several simplifies application development MPLINK linker accepts IF ELSE type conditional statements in the linker scripts as discussed below Several macros are used in support of the conditional statements Also certain directives are useful with these conditional statements 11 81 IFDEF ELSE FI Two syntaxes are accepted for these conditional statements Conditional 1 IFDEF EI Conditional 2 IFDEF ELSE FT 11 8 1 1 IFDEF Only one macro is allowed after this directive If the macro is defined before the if clause will be parsed by the linker Complex conditions must be constructed using nested if else clauses 11 8 1 2 ELSE No macrois allowed after this directive The else clause will be parsed only in case that the if clause is not 11 8 1 3 SE No macro is allowed after this directive It identifies the end of if or else clause O 1994 2013 Microchip Technology Inc DS33014L page 245 Assembler Linker Librarian User s Guide 11 8 2 Macros Depending on what you want to do macros may be set and used
20. 4 324 See Also macro noexpand 4 32 5 Simple Example Code example Define a macro to add two numbers add macro numl num2 movlw numi movwf result moviw num2 addwf result endm expand Use macro add add 100 90 Resulting listing file 00029 expand 00030 add 100 90 0010 3064 M moviw 100 0011 00A0 M movwf result 0012 305A M movlw 90 0013 07A0 M addwf result 00031 1994 2013 Microchip Technology Inc DS33014L page 113 Assembler Linker Librarian User s Guide 4 33 extern DECLARE AN EXTERNALLY DEFINED LABEL 4 33 1 Syntax extern label label 4 33 2 Description This directive declares symbol names that may be used in the current module but are defined as global in a different module The extern statement must be included before the 1abe1 is used At least one label must be specified on the line If 1abe1 is defined in the current module MPASM assembler will generate a duplicate label error 4 33 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation As soon as you have more than one file in your project you may use this directive extern Will be used in a file when a label usually a variable is used by that file global will be used in another file so that the label may be seen by other files You must use both directives as specified or the label will not be visible to other files 4 3
21. So area will be reassigned a value equal to 50H 25H Undefine label lngth Undefine label wdth Define label lngth to 0 By using the above directives 1ngth will be reassigned a value 0 and wdth will be removed from the symbol list in the list 1st file The label 1ngth must be undefined before it can be defined as 0 O 1994 2013 Microchip Technology Inc DS33014L page 99 Assembler Linker Librarian User s Guide 4 19 dt DEFINE TABLE PIC12 16 MCUs 4 19 4 Syntax label dt expr expr expr 419 2 Description dt Define data Table Generates a series of RETLW instructions one instruction for each expr Each expr must be an 8 bit value Each character in a string is stored in its own RETLW instruction 4 19 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is used when generating a table of data for the PIC12 16 device family If you are using a PIC18 device it is recommended that you use the table read write TBLRD TBLWT features See the device data sheet for more information 4 194 See Also data db de dtm dw 4 19 5 Simple Example dt A Message 0 dt FirstValue SecondValue EndOfValues 4 20 dtm DEFINE TABLE EXTENDED PIC16 MCUS ONLY 4 20 4 Syntax label dtm expr expr expr 4 20 2 Description dtm Define data Table
22. memName is a previously defined ACCESSBANK SHAREBANK DATABANK or CODEPAGE The ROM attribute must always refer to program memory previously defined using a CODEPAGE directive The RAM attribute must always refer to data memory previously defined with a ACCESSBANK DATABANK or SHAREBANK directive EXAMPLE 11 9 LOGICAL SECTION DEFINITION To specify that a section whose name is filter coeffs be loaded into the region of program memory named constants the following line should be added to the linker script file SECTION NAME filter coeffs ROM constants EXAMPLE 11 10 LOGICAL SECTION USAGE To place MPASM source code into a section named filter coeffs use the following line prior to the desired source code filter coeffs CODE 11 7 STACK DEFINITION Only MPLAB C18 requires a software stack be set up The following statement specifies the stack size and an optional DATABANK where the stack is to be allocated STACK SIZE allocSize RAM memName where allocSize is the size in bytes of the stack and memName is the name of a memory previously declared using a ACCESSBANK DATABANK or SHAREBANK statement EXAMPLE 11 11 STACK EXAMPLE To set the stack size to be 0x20 in the RAM area previously defined by gpro the following line should be added to the linker script file STACK SIZE 0x20 RAM gpr0 DS33014L page 244 1994 2013 Microchip Technology Inc Linker Scripts
23. movlw numi result movwf movlw num2 addwf result endm ORG 0x0010 start add 100 90 end Include standard header file for the selected devic Assign value 20H to label result The following code will be placed in reset address 0 Jump to an address whose label is start add is a macro The values of numl and num2 must be passed to this macro Load W register with a literal value assigned to the label raum t Load W register to an address location assigned to the label result ER ER Load W register with a literal value assigned to the label num2 Add W register with the memory location addressed by result and load the result back to result end of add MACRO Main program starts at 10H The label start is assigned an address 10H Call add MACRO with decimal numbers 100 and 90 assigned to numl and num2 labels respectively 100 and 90 will be added and the result will be in result 1994 2013 Microchip Technology Inc DS33014L page 135 Assembler Linker Librarian User s Guide 4 46 maxram DEFINE MAXIMUM RAM LOCATION Note maxram is preceded by two underline characters 4 46 1 Syntax maxram expr 4 46 2 Description The maxramand badram directives together flag accesses to unimplemented registers maxram defines the absolute maximum valid RAM address and initializes
24. path Off Enable Disable Set Path for cross reference file x Enable xt Enable x Disable x path Enable specify path See Section 1 7 6 Cross Reference File xrf for more information y 1 Disabled Enable Disable extended instruction set y Enable y Enable y Disable Can only be enabled for processors which support the extended instruction set and for the generic processor PIC18CXXX y overrides LIST PE type directive see Section 4 43 list Listing Options Default is dependent on processor selected DS33014L page 64 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 3 Expression Syntax and Operation 3 1 INTRODUCTION Various expression formats syntax and operations used by MPASM assembler are described here Topics covered in this chapter Text Strings Reserved Words and Section Names Numeric Constants and Radix Arithmetic Operators and Precedence 3 2 TEXT STRINGS A string is a sequence of any valid ASCII character of the decimal range of 0 to 127 enclosed by double quotes It may contain double quotes or null characters The way to get special characters into a string is to escape the characters preceding them with a backslash V character The same escape sequences that apply to strings also apply to characters Strings may be of any length that will fit within a 255 column source line If
25. 3 program memory locations will be filled with ASCII equivalent of M C and gt y Directive data produces three 16 bit numbers 004Dh 0043h and 0055h 4Dh 43h and 55h are ASCII equivalents of M C and U respectively See Section 4 10 code pack Begin an Object File Packed Code Section PIC18 MCUs for better use of memory Ch stgl data MCU 2 program memory locations will be filled with two words 16 bit numbers each representing ASCI equivalent of two characters The last character will be taken as NULL in case odd number of characters are specified Directive data produces two words 434Dh and 0055h 434Dh represents C and M tbl dta data Oxffff 0xaab55 Places ffff and aa55 in two consecutive program memory locations end O 1994 2013 Microchip Technology Inc DS33014L page 93 Assembler Linker Librarian User s Guide 4 16 db DECLARE DATA OF ONE BYTE 4 16 1 Syntax label db expr expr expr 416 2 Description db Data Byte Reserve program memory words with 8 bit values Multiple expressions continue to fill bytes consecutively until the end of expressions Should there be an odd number of expressions the last byte will be zero unless in a PIC18 code pack section 4 16 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Ope
26. C Progrz HI TECH PICC v1 00 C Progrz Type mpasm HI TECH PICC18 PRO v1 00 C mpasm v5 46 C Program Base Directory C Program Files Microchip MPLABX mpasmx Y pasm v5 42 C Program Files Assembler C Program Files Microchip MPLABX mpasmx mpasmx exe E pasm C Program Files Microch XC16 v1 00 C Program Files rr 2 bin mal IXC32 v1 00 C Program Files Vv y Make Command C Program Files Microchip MPLABX gnuBins SENE _ NENNEN 1994 2013 Microchip Technology Inc DS33014L page 19 Assembler Linker Librarian User s Guide MPLAB X IDE PROJECTS A project in MPLAB X IDE is a group of files needed to build an application along with their associations to various build tools Below is a generic MPLAB X IDE project FIGURE 2 PROJECT RELATIONSHIPS MPLAB X IDE Project E e e e re ee ee ee re re ee ee re re eK zm l l l l l l l i l l l l l l l l l l l l l l l l L m mn en em em en wl rn mn en en em mm SIMULATORS EMULATORS DEBUGGERS PROGRAMMERS 1 The linker can choose the correct linker script file for your project source files ASSEMBLER COMPILER list and object files LIBRARIAN amp library file LINKER amp linker script file 1 LINKER output files Utility amp output file DS33014L page 20 1994 2013 Microchip Technology Inc PIC1X MCU Language
27. MICROCHIP MPASM Assembler MPLINK Object Linker MPLIB Object Librarian User s Guide DS33014L Note the following details of the code protection feature on Microchip devices Microchip products meet the specification contained in their particular Microchip Data Sheet Microchip believes that its family of products is one of the most secure families of its kind on the market today when used in the intended manner and under normal conditions There are dishonest and possibly illegal methods used to breach the code protection feature All of these methods to our knowledge require using the Microchip products in a manner outside the operating specifications contained in Microchip s Data Sheets Most likely the person doing so is engaged in theft of intellectual property Microchip is willing to work with the customer who is concerned about the integrity of their code Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code Code protection does not mean that we are guaranteeing the product as unbreakable Code protection is constantly evolving We at Microchip are committed to continuously improving the code protection features of 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
28. Main application code here END OF APPLICATION KCKCKCKCkCkCk kk k Ck k Ck k kCk kc k KE kc k kc I ok ke ke xe ke x 13 5 2 Assembler Usage This section discusses how to use the MPASM assembler the assembler when developing bootloader and related appliation code There are three assembler examples showing suggested linker script modifications and appropriate source code directive usage for a boot loader and application project To better understand how the code corresponds to locations in device program memory see Section 13 5 2 1 Assembler Memory Map The modified linker script file provided in this example is designed to support all three of the following examples See Section 13 5 2 2 Assembler Linker Script Example 1 shows an assembler boot loader See Section 13 5 2 3 Example 1 Assembler Boot Loader Source Code Example 2 shows a multiple module relocatable assembler application See Section 13 5 2 4 Example 2 Assembler Application Source Code Example 3 incorporates both the assembler boot loader and multiple module relocatable assembler application as a single program memory image See Section 13 5 2 5 Example 3 Assembler Boot Loader Application Source Code To build the assembler sample application refer to Section 13 2 How to Build the Sample Applications DS33014L page 272 1994 2013 Microchip Technology Inc Sample Applications 13 5 2 1 ASSEMBLER MEMORY MAP The boo
29. badram R 75 A E 76 BE iii re Mr ee ee re du 87 AS Ne Mete 123 MAAM rene aci 75 Bu TE 76 POMO iiec erre EENS 98 Allee 130 A A tete At ie 162 bankisel 77 banksel inca a nent 80 CbloOeck i tuo ce taret co DEED Rt 83 e ale 84 code pack e d erede t 85 Cconflg oi a ias 89 e 92 o 94 p lp 96 Uni PERDERE ee eee CEE ERT 100 le UE 101 O ke heed EBEN 102 Gnd a ed te HER RECO 103 COM in to ida 104 Lip MEI 105 GITOF 3 ausis E 106 Gute E iecore ete eda 108 exe o oe orn cede ted 111 GXtfern cud teg vegeta 114 Milicic rta 116 global en Mead eee ete 119 datas ns tentent data 120 122 pr IL RET 125 A ee ee 127 A O R 129 Jet ee E EES 131 ele 132 MO EE 113 134 140 Mes bo ita 138 el DEE 141 pagesel oer detener es 144 146 PIOCCSSOF x oo e eee eee 147 FAQ DC Ne eel cds 148 OS ere eee iR e rene 150 CMT 152 PA iii iiS 74 153 Subtitles cat 153 Mili it 154 EC EE 154 udata CS sise tdi nier siens 156 udata iii ini 158 EC ita 160 Variable coccion 163 While 35 2 oco ica 165 Executable Files nnnnneeeeoeee nesen neneeese nerenin 21 37 Execute If Symbol Defined 127 Execute If Symbol Not Defined 129 GXIlITI i i ree eoa crest eee he at aw tases he zee 111 SO ar 113 Exporta Label ect emeret 119 Extended Microcontroller Mode
30. code section named PGM It is a relocatable code section Since no absolute address is given along with directive CODE E start goto Go to current line loop here end O 1994 2013 Microchip Technology Inc DS33014L page 107 Assembler Linker Librarian User s Guide 4 30 errorlevel SET MESSAGE LEVEL 4 30 1 Syntax errorlevel 0 1 2 msgnum msgnum 4 30 2 Description Sets the types of messages that are printed in the listing file and error file Setting Affect 0 Messages warnings and errors printed 1 Warnings and errors printed 2 Errors printed msgnum Inhibits printing of message msgnum msgnum Enables printing of message msgnum 4 30 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation Errors cannot be disabled Warnings may be disabled using setting 2 Messages may be disabled using settings 1 or 2 Also messages may be disabled individually However the setting of 0 1 or 2 overrides individual message disabling or enabling Be careful about disabling warnings and messages as this can make debugging of your code more difficult The most common usage for this directive is to suppress MESSAGE 302 Operand Not in bank 0 check to ensure bank bits are correct See the Simple Example for how to do this 4 30 4 See Also list error 4 30 5
31. d 4 Right Parenthesis Length 1 256 Item NOT logical complement if a b Negation 2 s complement 1 Length Complement flags flags low Return low byte of address movlw low CTR Table high Return high byte of address movlw high CTR Table upper Return upper byte of address movlw upper CTR Table Multiply a b e Divide ac DJ e Modulus ntry len tot len 16 Add tot len entry len 8 1 Subtract entry len tot 1 8 lt lt Left shift flags flags lt lt 1 gt gt Right shift flags flags gt gt 1 gt Greater or equal if entry idx gt num entries gt Greater than if entry idx gt num entries lt Less than if entry idx lt num entries lt Less or equal if entry idx lt num entries Equal to if entry idx num entries l Not equal to if entry idx num entries amp Bitwise AND flags flags amp ERROR BIT A Bitwise exclusive OR flags flags ERROR BIT Bitwise inclusive OR flags flags ERROR BIT amp amp Logical AND if len 512 amp amp b c B Logical OR if len 512 b c Set equal to entry index 0 Add to set equal entry index 1 Subtract set equal entry index 1 Multiply set equal entry index entry length Divide set equal entry total entry length Modulus
32. 000000 ef16 GOTO 0x2c goto Start 1 000002 000 1 PGM code 1 00002c 0e0a MOVLW Oxa Start movlw Ox0A 1 00002e 6 80 MOVWF 0x80 0x1 movwf Dest 1 000030 9780 BCF 0x80 0x3 0x1 bcf Dest 3 1 000032 ef16 GOTO Ox2c goto Start 1 000034 000 end 1 where 1 D Projects32 PIC18F452 SourceReloc asm 2 C Program Files Microchip MPASM Suite p18f452 inc DS33014L page 228 1994 2013 Microchip Technology Inc MPLINK Linker Overview 9 7 7 Map File map The map file generated by MPLINK linker can be viewed by selecting File gt Open File in MPLAB X IDE or File gt Open in MPLAB IDE v8 and choosing the file you specified in the MPLINK linker options It provides information on the absolute location of source code symbols in the final output It also provides information on memory use indicating used unused memory This window is automatically reloaded after each rebuild The map file contains four tables The first table Section Info displays information about each section The information includes the name of the section its type beginning address whether the section resides in program or data memory and its size in bytes There are four types of sections code initialized data idata uninitialized data udata initialized ROM data romdata The following table is an example of the section table in a map file Section Info Section Type Address Location Size Bytes Reset code 0x000000 progr
33. CONFIG CPO ON An error will be issued since CPO is assigned twice 4 12 4 See Also _ config _idlocs list processor DS33014L page 88 1994 2013 Microchip Technology Inc Directives 4 12 5 Simple Example finclude p18f452 inc Include standard header file for the selected devic code protect disabled CONFIG CPO OFF Oscillator switch enabled RC oscillator with OSC2 as I O pin CONFIG OSCS ON OSC LP Brown OutReset enabled BOR Voltage is 2 5v CONFIG BOR ON BORV 25 Watch Dog Timer enable Watch Dog Timer PostScaler count 1 128 CONFIG WDT ON WDTPS 128 CCP2 pin Mux enabled CONFIG CCP2MUX ON Stack over underflow Reset enabled CONFIG STVR ON 4 13 constant DECLARE SYMBOL CONSTANT 4 13 1 Syntax constant label expr label expr 413 2 Description Creates symbols for use in MPASM assembler expressions Constants may not be reset after having once been initialized and the expression must be fully resolvable at the time of the assignment This is the principal difference between symbols declared as constant and those declared as variable or created by the set directive Otherwise constants and variables may be used interchangeably in absolute code expressions 413 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation Although equ or cblock is more generally used to create
34. DS33014L page 139 Assembler Linker Librarian User s Guide 4 49 noexpand TURN OFF MACRO EXPANSION 4 49 1 Syntax noexpand 4 49 2 Description and Usage Turns off macro expansion in the listing file This directive is used in the following types of code absolute For information on types of code see Section 1 6 Assembler Operation 4 49 3 See Also expand 4 49 4 Simple Example Code example Define a macro to add two numbers add macro numl num2 movlw numi movwf result moviw num2 addwf result endm noexpand Use macro add add E80 Oe 590 Resulting listing file 00029 noexpand 00030 add 100 90 00031 4 50 nolist TURN OFF LISTING OUTPUT 4 50 1 Syntax nolist 4 50 2 Description and Usage Turn off listing file output This directive suppresses the information required for the listing file and source level debugging This will prevent the ability to debug the source code This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation 4 50 3 See Also list DS33014L page 140 1994 2013 Microchip Technology Inc Directives 4 51 org SET PROGRAM ORIGIN 4 51 1 Syntax label org expr 4 51 2 Description Set the program origin for subsequent code at the address defined in expr If label is specified it will be given the value of the expr If no org is specified code generation w
35. Macro Language 7 1 INTRODUCTION Macros are user defined sets of instructions and directives that will be evaluated in line with the assembler source code whenever the macro is invoked Macros consist of sequences of assembler instructions and directives They can be written to accept arguments making them quite flexible Their advantages are Higher levels of abstraction improving readability and reliability Consistent solutions to frequently performed functions Simplified changes Improved testability Applications might include creating complex tables frequently used code and complex operations Topics covered in this chapter Macro Syntax Macro Directives Defined Macro Definition Macro Invocation Macro Code Examples 7 2 MACRO SYNTAX MPASM assembler macros are defined according to the following syntax label macro argl arg2 argn endm where label is a valid assembler label that will be the macro name and arg is any number of optional arguments supplied to the macro that will fit on the source line The values assigned to these arguments at the time the macro is invoked will be substituted wherever the argument name occurs in the body of the macro The body of a macro may be comprised of MPASM assembler directives PIC1X MCU assembly instructions or MPASM assembler macro directives local for example The assembler continues to process the body of the macro until an exitm or
36. Select TRISB Bank 1 clrf TRISB Set PortB as output banksel INTCON Select INTCON Bank 0 bsf INTCON GIE Enable Global Int s bsf INTCON TOIE Enable Timer0 Int Two other routines also use banksel to access the Option register OPTION RI EG For more on this directive see Section 4 7 banksel Generate Bank Selecting Code DS33014L page 176 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks 5 3 7 Interrupts The Delay 1 routine in this program uses the Timer 0 overflow interrupt as a timing mechanism Once the interrupt occurs the program branches to the interrupt vector Here code is located to jump to a location where interrupt handling code is found intrpt code 0x04 Interrupt Vector goto Servint Jump to service interrupt The interrupt handling code also known as the interrupt service routine or ISR is generated by the programmer to handle the specific requirements of the peripheral interrupt and the program In this case Timer 0 is stopped and its flag bit is cleared so it may be run again Then the program defined flag bit is cleared Finally ret fie takes the program back to the instruction that was about to be executed when the interrupt occurred iSt code 0x08 Interrupt Service Routine Servint banksel OPTION REG Select Option Reg Bank 1 bsf OPTION REG TOCS Stop Timer0 banksel INTCON Select INTCON Bank 0 bcf INTCON TOIF Clear
37. The m lt mapfile gt switch was specified more than once Multiple output files declared filename1 filename2 The o lt outfile gt switch was specified more than once Multiple STACK definitions A STACK directive occurs more than once in the linker script file or included linker script files Remove the multiple STACK directives No input object files specified No input object or library file was specified to the linker Enter files to link DS33014L page 288 O 1994 2013 Microchip Technology Inc Errors Warnings and Common Problems Overlapping definitions of SHAREBANK memName A SHAREBANK directive specifies a range of addresses that overlap a previous definition Overlaps are not permitted PCL TOSH TOSU TOSL cannot be used as the destination of a MOVFF or MOVSF instruction The MOVFF instruction has unpredictable results when its destination is the PCL TOSH TOSU or TOSL registers MPLINK will not allow the destination of a MOVFF instruction to be replaced with any of these addresses Processor types do not agree across all input files Each object module and library file specifies a processor type or a processor family All input modules processor types or families must match Section absolute access overlay share types for secName do not match across input files A section with the name secName occurs in more than one input file However in some files itis marked as either an absol
38. The assembler creates a relocatable object file from source code This object file does not yet have addresses resolved and must be linked before it can be used as an executable To generate a file that will execute after being programmed into a device see 1 7 5 Hex File Formats hex hxl hxh To prevent object file generation use the o or o option A A a JP y eii i p l AA O 1994 2013 Microchip Technology Inc DS33014L page 59 Assembler Linker Librarian User s Guide NOTES DS33014L page 60 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 2 Assembler Interfaces 2 1 INTRODUCTION There are several interfaces with which you may use the MPASM assembler depending on the assembler version These interfaces are discussed here When MPLAB X IDE or MPLAB IDE v8 is installed the MPASM assembler is also installed In addition the assembler may be obtained with the MPLAB C Compiler for PIC18 MCUs Topics covered in this chapter MPLAB X IDE Interface MPLAB IDE v8 Interface Windows Interface Command Line Interface 2 2 MPLAB X IDE INTERFACE The MPASM assembler is most commonly used with the MPLINK linker in an MPLAB X IDE project to generate relocatable code However the assembler may be used in MPLAB X IDE to generate absolute code with
39. and then set up linker options For additional options see MPLINK object linker documentation Chapter 10 Linker Interfaces All Options Category Generate Command Line Hex file format Choose the linker hex file format or suppress output of the hex file Generate map file Create a map file A map file provides information on the absolute location of source code symbols in the final output It also provides information on memory use indicating used unused memory Output file root Enter a root directory for saving output files Restore Defaults Restore tab default settings Use Alternate Settings Text Box Enter options in a command line non GUI format Build Options Dialog MPASM C17 C18 Suite Tab Select a category and then set up output build options All Options Category Generate Command Line Library Output Build normal target The files in the project will be built for normal output using the invoke MPLINK MPLINK linker hex file etc To set linker options see Build Options Dialog MPLINK Linker Tab Build library target The files in the project will be built into a library using the MPLIB invoke MPLIB librarian lib file Check Build generic library to build a library with the generic device instead of the selected device This means the library can be used with any device and not just the one currently selected For more on libraries see MPLIB object
40. arguments an OR selection errorlevel 011 Ellipses Replaces repeated text var_name var_name Represents code supplied by user void main void DS33014L page 12 1994 2013 Microchip Technology Inc Preface RECOMMENDED READING This documentation describes how to use Assembler Linker Librarian User s Guide Other useful documents are listed below The following Microchip documents are available and recommended as supplemental reference resources Readme Files readme asm and readme lkr For the latest tool information and known issues see the MPASM assembler readme file readme asm or the MPLINK object linker MPLIB object librarian readme file readme 1kr These ASCII text files may be found in the Readme folder of the MPLAB IDE installation directory On line Help Files Comprehensive help files are available for MPASM assembler and MPLINK object linker MPLIB object librarian In addition debug output format COFF information is also available in help C Compiler User s Guides and Libraries The MPLINK linker and MPLIB librarian also work with the MPLAB C Compiler for PIC18 MCUs formerly MPLAB C18 For more information on the compiler see MPLAB C Compiler for PIC18 MCUs Getting Started DS51295 MPLAB C Compiler for PIC18 MCUs User s Guide DS51288 MPLAB C Compiler for PIC18 MCUs Libraries DS51297 PIC18 Configuration Settings Addendum DS515
41. information on types of code see Section 1 6 Assembler Operation You will need at least one end directive in any assembly program to indicate the end of a build In a single assembly file program one and only one end must be used Be careful not to include files which contain end as assembly will be prematurely stopped 4 234 See Also org 4 23 5 Simple Example finclude p18f452 inc executable cod end end of instructions 4 24 endc END AN AUTOMATIC CONSTANT BLOCK 4 24 4 Syntax endc 4 24 2 Description endc terminates the end of a cblock list It must be supplied to terminate the list 4 24 3 Usage This directive is used in the following types of code absolute For information on types of code see Section 1 6 Assembler Operation For every cblock directive used there must be a corresponding endc 4 24 4 See Also cblock 4 24 5 Examples See the examples under cblock 1994 2013 Microchip Technology Inc DS33014L page 103 Assembler Linker Librarian User s Guide 4 25 endif END CONDITIONAL ASSEMBLY BLOCK 4 25 1 Syntax Preferred endif Supported fendif endif SET 4 25 2 Description This directive marks the end of a conditional assembly block endif may be used inside a regular program block or macro 4 25 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operati
42. pause for a handshake or decrease the data rate for a shared bus Longer delays are well suited for the DECFSZ and INCFSZ instructions where a variable is decremented or incremented until it reaches zero when a conditional jump is executed For shorter delays of a few cycles here a few ideas to decrease code size For a two cycle delay it is common to use two NOP instructions which uses two program memory locations The same result can be achieved by using GOTO 1 The represents the current program counter value in MPASM assembler When this instruction is encountered the MCU will jump to the next memory location This is what it would have done if two NOP s were used but since the GOTO instruction uses two instruction cycles to execute a two cycle delay was created This created a two cycle delay using only one location of program memory To create a four cycle delay add a label to an existing RETURN instruction in the code In this example the label Rtrn was added to the RETURN of subroutine that already existed somewhere in the code When executing CALL Rtrn the MCU delays two instruction cycles to execute the CALL and two more to execute the RETURN Instead of using four NOP instructions to create a four cycle delay the same result was achieved by adding a single CALL instruction DS33014L page 186 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks 5 9 2 TIP 2 Optimizing Destinations De
43. 0 3 RT 0x0 END 0x1F PROTECT RT 0x80 END 0x9F PROTECT RT 0x100 END 0x10F PROTECT RT 0x180 END 0x18F PROTECT anks 0 3 RT 0x20 END 0x6F RT 0xA0 END OxEF RT 0x110 END 0x16F RT 0x190 END 0x1EF able in all banks START 0x70 END 0x7F START 0xF0 END OxFE START 0x170 END 0x17F START 0x1F0 END 0x1FE DS33014L page 240 O 1994 2013 Microchip Technology Inc Linker Scripts EXAMPLE 11 6 RAM EXAMPLE ACCESSBANK Based on the RAM memory layout shown in PIC18F8680 Register File Map the ACCESSBANK entries in the linker script file would appear as shown in the examples below the map FIGURE 11 2 PIC18F8680 REGISTER FILE MAP Address Range Bank Data Memory Map Access Bank 000h 05Fh Bank 0 Access RAM Access RAM Low 060h 0FFh GPRs 100h 1FFh Bank 1 GPRs COOh CFFh Bank 12 GPRs DOOh DFFh Bank 13 CAN SFRs E00h EFFh Bank 14 CAN SFRs FOOh F5Fh Bank 15 CAN SFRs F60h FFFh SFRs Access RAM High RAM Memory Declarations for PIC18F8680 Access Memory ACCESSBANK NAME accessram START 0x0 END 0x5F ACCESSBANK NAME accesssfr START 0xF60 END 0xFFE PROTECTED O 1994 2013 Microchip Technology Inc DS33014L page 241 Assembler Linker Librarian User s Guide EXAMPLE 11 7 RAM EXAMPLE LINEARMEM Based on the RAM memory layout shown in PIC16F1939 Register File Map the LINEARMEM entries in the linker script file would appear as shown in
44. 105 if Begin Conditionally Assembled Code Block p 125 ifdef Execute If Symbol Has Been Defined sssssssss p 127 ifndef Execute If Symbol Has Not Been Defined p 129 while Perform Loop While Condition is Tue p 165 4 2 3 Data Directives Data directives control the allocation of memory and provide a way to refer to data items symbolically i e by meaningful names e badram Identify Unimplemented RAM p 75 e badrom Identify Unimplemented ROM p 76 e config Set Processor Configuration Bis p 86 e config Set Processor Configuration Bits PIC18 MCUS p 88 e idlocs Set Processor ID Locations sesseereeererrrrerrrerrrrrrrrsreee p 123 e maxram Define Maximum RAM Location p 136 e maxrom Define Maximum ROM Location p 137 e cblock Define a Block of Constants p 82 da Store Strings in Program Memory PIC12 16 MCUS p 90 data Create Numeric and Text Data p 92 db Declare Data of One Bytes p 94 de Declare EEPROM Data Byte ooococcoccoccccccncooncccconaonncccnnnnnnccccnnannnccnnannns p 96 dt Define Table PIC12 16 MCUs ER p 100 DS33014L page 72 O 1994 2013 Microchip Technology Inc Directives dtm Define Table Extended PIC16 MCUs Only p 100 dw Declare Data of One Word p 101 endc En
45. 4 See Also define include ifdef ifndef 4 66 5 Simple Example define length 20 undefine length 4 66 6 Application Example define undefine See this example under define DS33014L page 162 1994 2013 Microchip Technology Inc Directives 4 67 variable DECLARE SYMBOL VARIABLE 4 67 1 Syntax variable label expr label expr 4 67 2 Description Creates symbols for use in MPASM assembler expressions Variables and constants may be used interchangeably in expressions The variable directive creates a symbol that is functionally equivalent to those created by the set directive The difference is that the variable directive does not require that symbols be initialized when they are declared The variable values cannot be updated within an operand You must place variable assignments increments and decrements on separate lines 4 67 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is most used for conditional assembly code Note variable is not used to declare a run time variable but a variable that is used by the assembler To create a run time variable refer to the directives res equ or cblock 4 67 4 See Also constant set 4 67 5 Simple Example variable RecLength 64 Set Default RecLength constant BufLength 512 Init BufLength RecLength may be res
46. 45 4450 2828 Fax 45 4485 2829 France Paris Tel 33 1 69 53 63 20 Fax 33 1 69 30 90 79 Germany Munich Tel 49 89 627 144 0 Fax 49 89 627 144 44 Italy Milan Tel 39 0331 742611 Fax 39 0331 466781 Netherlands Drunen Tel 31 416 690399 Fax 31 416 690340 Spain Madrid Tel 34 91 708 08 90 Fax 34 91 708 08 91 UK Wokingham Tel 44 118 921 5869 Fax 44 118 921 5820 11 29 12 1994 2013 Microchip Technology Inc DS33014L page 338
47. 5 Simple Example mssg macro macro messg mssg macro 001 invoked without argument endm 4 48 6 Application Example messg This program demonstrates the messg assembler directive which sets a message to be printed in the listing file and error file finclude p16f877a inc Include standard header file for the selected devic variable baudrate variable used to defin required baud rate baudrate set D 5600 Enter the required value of baud rate here if baudrate D 1200 amp amp baudrate D 2400 amp amp baudrate D 4800 amp amp baudrate D 9600 amp amp baudrate D 19200 error Selected baud rate is not supported messg only baud rates 1200 2400 4800 9600 amp 19200 Hz amp amp are supported endif DS33014L page 138 1994 2013 Microchip Technology Inc Directives The if endif code outputs error and messg if the baud rate selected is other than 1200 2400 4800 9600 or 19200 Hz RST CODE 0x0 pagesel start goto start PGM CODE start goto end The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST Jumps to the location labelled phstartts This is the beginning of the code section named PGM It is a relocatable code section Since no absolute address is given along with directive CODE E Go to current line loop here O 1994 2013 Microchip Technology Inc
48. 50H 750 is in hex movlw 0x50 Another way of declaring 50 hex movlw 50 50 is in decimal EEE EEE oi EE M onm M Mc DS33014L page 148 1994 2013 Microchip Technology Inc Directives movlw radix movlw movlw movlw end 50 hex 50 500 50 750 is octal sit is not declared as hex or or decimal So by default in octal as default radix is declared as octal Now default radix is in hex 750 is 750 is 750 is octal ES declared in decimal declared in octal not declared as hex or or decimal So by default in hex as default radix is declared as hex 1994 2013 Microchip Technology Inc DS33014L page 149 Assembler Linker Librarian User s Guide 4 57 res RESERVE MEMORY 4 57 1 Syntax label res mem units 4 57 2 Description Causes the memory location pointer to be advanced from its current location by the value specified in mem units In relocatable code using MPLINK linker res can be used to reserve data storage In non relocatable code label is assumed to be a program memory address Address locations are defined in words for PIC 12 16 MCUs and bytes for PIC18 MCUs 4 57 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1
49. 6 Assembler Operation The most common usage for res is for data storage in relocatable code 4 57 4 See Also fill org equ cblock 4 57 5 Simple Example buffer res 64 reserve 64 address locations of storage 4 57 6 Application Example res This example shows the advantage of res directive in developing relocatable code The program calculates the perimeter of a rectangle Length and width of the rectangle will be stored in buffers addressed by length and width The calculated perimeter will be stored in the double precision buffer addressed by perimeter finclude p18f452 inc Include standard header file for the selected devic UDATA This directive allows the following data to be placed only in the data area perimeter res 2 Two locations of memory are reserved for the label perimeter Addresses of the memory locations will be allocated by the linker length res 1 One location of memory is reserved for the label length Address of the memory location will be allocated by the linker width res 1 One location of memory is reserved for the label width Address of the memory location will be allocated by the linker Start CODE 0x0000 Following code will be placed in address 0 DS33014L page 150 O 1994 2013 Microchip Technology Inc Directives Here the directive code has the same effect as org But org is used with MPASM assembler to generate absolute code and code is us
50. AME dbgspr START _DEBUGDATASTART ELSE no debug DATABANK AME gprl4 START 0xE00 FI DATABANK AME gpr15 START 0xF00 ACCESSBANK NAME accesssfr START 0xF60 IFDEF _CRU TIME SECTION AME CONF IG ROM config IFDEF _DEBUGDATASTART STACK SIZE 0x100 RAM gpr13 ELSE STACK SIZE 0x100 RAM gpr14 FI FI E n END DEND END O0xEFF ND 0xF5F ND 0xFFF PROTECTED PROTECTED O 1994 2013 Microchip Technology Inc DS33014L page 249 Assembler Linker Librarian User s Guide NOTES DS33014L page 250 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 12 Linker Processing INTRODUCTION Understanding how MPLINK linker processes files and information can be useful to keep in mind when writing and structuring your application code Topics covered in this chapter Linker Processing Overview Linker Allocation Algorithm Relocation Example Initialized Data Reserved Section Names 12 2 LINKER PROCESSING OVERVIEW A linker combines multiple input object modules into a single executable output module The input object modules may contain relocatable or absolute sections of code or data which the linker will allocate into target memory The target memory architecture is described in a linker script file This linker script file provides a flexible mechanism for specifying blocks of targ
51. Assembler Linker Librarian User s Guide 4 63 udata acs BEGIN AN OBJECT FILE ACCESS UNINITIALIZED DATA SECTION PIC18 MCUs 4 63 4 Syntax label udata_acs RAM address 4 63 2 Description This directive declares the beginning of a section of access uninitialized data If 22be1 is not specified the section is named udata_acs The starting address is initialized to the specified address or will be assigned at link time if no address is specified This directive is used to declare variables that are allocated in access RAM of PIC18 devices No code can be generated in this segment The res directive should be used to reserve space for data Note Two sections in the same source file are not permitted to have the same name 4 63 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation This directive is similar to udata except that it is used only for PIC18 devices and will only place variables in access RAM PIC18 devices have an area of RAM known as access RAM Variables in access memory can be used no matter where the bank select register BSR is pointing It is very useful for frequently used and global variables 4 63 4 See Also extern global idata udata udata_ovr udata_shr 4 63 5 Simple Example udata_acs Varl res 1 Double res 2 4 63 6 Application Example udata_acs This program demonstrates the udata_acs direc
52. COD file errors listed below indicate an internal error in the file s contents Please contact Microchip support if any of these errors are generated Cod file filename does not have a proper debug message table Cod file filename does not have a proper Index Cod file filename does not have a proper line info table Cod file filename does not have a proper local vars table Cod file filename does not have a proper long symbol table Cod file filename does not have a proper memory map table Cod file filename does not have a proper name table Cod file filename does not have a proper symbol table Cod file filename does not have a properly formed first directory Cod file filename does not have a properly formed linked directory Could not open Cod file filename for reading Could not open Cod file filename for writing Could not write blockname block in Cod file filename Could not write directory in Cod file filename D D D E EG lt A O A a ae DS33014L page 308 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Part 5 Appendices Appendix A Instruction Sets cccccceeeeeeeeeeeeeeeeeneeeeeeeeeeeeeeeeeeeeeeeeeseeeeeeeneasneeeees 311 Appendix B Useful Tables ss sisssssssennssss 329 1994 2013 Microchip Technology Inc DS33014L page 309 Assembler Linker Librarian User s Guide NOTES DS33014L page 310 O 1994 2013 Mic
53. CONFIG DECL pragma config or CONFIG directive TRIS argument is out of range OXHHHH not between 0xHHHH and OXHHHH Check the device data sheet to determine acceptable hex values for the TRIS register you are using Undefined CODEPAGE memName for SECTION secName A SECTION directive with a ROM attribute refers to a memory block which has not been defined Add a CODEPAGE directive to the linker script file for the undefined memory block Undefined DATABANK SHAREBANK memName for SECTION secName A SECTION directive with a RAM attribute refers to a memory block that has not been defined Add a DATABANK or SHAREBANK directive to the linker script file for the undefined memory block Undefined DATABANK SHAREBANK memName for STACK No input object files specified At least one object module must be specified either on the command line or in the linker script file using the FILES directive Unknown section type for secName The section type for secName needs to be defined O 1994 2013 Microchip Technology Inc DS33014L page 291 Assembler Linker Librarian User s Guide Unknown section type for secName in file filename An input object or library module is not of the proper file type or it may be corrupted Unsupported processor type in file filename A processor was specified that is not currently supported by the linker See the Readme file for a list of supported devices Unsu
54. For PIC16 extended devices a mov1p instruction is generated to set the page If the device contains only one page of program memory no code will be generated For PIC18 devices this command will do nothing as these devices do not use paging 4 53 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive saves you from having to manually code page bit changes Also since it automatically generates code the code is much more portable If you are using relocatable code and your device has more than 2k program memory or 0 5K for 12 bit instruction width devices it is recommended that you use this directive especially when code must jump between two or more code sections If you wish to indicate the start address of a RETLW table or a jump table for computed GOTOs you must use the pageselw directive 4 53 4 See Also bankisel banksel 4 53 5 Simple Example pagesel GotoDest goto GotoDest pagesel CallDest Call CallDest DS33014L page 144 O 1994 2013 Microchip Technology Inc 4 53 6 Directives Application Example pagesel This program demonstrates the pagesel directive which generates the appropriate code to set clear PCLATH bits This allows easier use of paged memory such as found on PIC16 devices include p16f877a inc RST CODI pagesel goto PGMO COD start pagesel goto PGM1
55. Processing icono 251 Chapter 13 Sample Applications eeeeeeeeeeeeeceseseeeeeeeeeeeee nnn 255 Chapter 14 Errors Warnings and Common Problems 285 1994 2013 Microchip Technology Inc DS33014L page 221 Assembler Linker Librarian User s Guide NOTES DS33014L page 222 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 9 MPLINK Linker Overview 9 1 INTRODUCTION An overview of the MPLINK object linker and its capabilities is presented Topics covered in this chapter MPLINK Linker Defined How MPLINK Linker Works How MPLINK Linker Helps You Linker Platforms Supported Linker Operation Linker Input Output Files 9 2 MPLINK LINKER DEFINED MPLINK object linker the linker combines object modules generated by the MPASM assembler or the MPLAB C18 C compiler into a single executable hex file The linker also accepts libraries of object files as input as generated by the MPLIB object librarian The linking process is controlled by a linker script file which is also input into MPLINK linker For more information on MPASM assembler see Chapter 1 MPASM Assembler Overview For more information on MPLAB C18 see C compiler documentation listed in Recommended Reading 9 3 HOW MPLINK LINKER WORKS MPLINK linker performs many functions Locates Code and Data The linker takes as input
56. Simple Example errorlevel 302 Turn off banking message known tested good code errorlevel 302 Enable banking message untested code a 4 30 6 Application Example errorlevel This program demonstrates the errorlevel assembler directive which sets the type of messages that are printed in the listing file and error file include p16f877a inc Include standard header file for the selected device errorlevel 0 Display print messages warnings and errors messg CAUTION This program has errors display on build DS33014L page 108 1994 2013 Microchip Technology Inc Directives This message will display print for error level 0 errorlevel 1 Display print only warnings and errors messg CAUTION This program has errors display message This message will NOT display print for error level 1 or 2 groupl udata 0x20 groupl varl res 1 Label of this directive is not at column 1 This will generate a warning number 207 Warning 207 will display print for error level O or 1 errorlevel 207 groupl var2 res 1 errorlevel 207 group2 udata errorlevel 2 group2 varl res 1 This disables warning whose number is 207 label of this directive is also not at column 1 but no warning is displayed printed This enables warning whose number is 207 Display print only errors label of this directive is not at column 1 This will generate 7a warning number
57. Technology Inc Directives 4 41 ifndef EXECUTE IF SYMBOL HAS NOT BEEN DEFINED 4 41 1 Syntax Preferred ifndef label Supported ifndef label 441 2 Description If 1abe1 has not been previously defined or has been undefined by issuing an undefine directive then the code following the directive will be assembled Assembly will be enabled or disabled until the next matching else or endif directive is encountered 4 413 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is not an instruction but used to control how code is assembled not how it behaves at run time Use this directive for removing or adding code during debugging without the need to comment out large blocks of code 4 41 4 See Also define undefin ls ndif ifdef 4 41 5 Simple Example define testingl set testing on undefine testingl set testing off ifndef testing if not in testing mode execute this path endif end end of source 4 41 6 Application Example ifndef include p16f877a inc define UsePORTB Comment out with to use PORTC ifndef UsePORTB MyPort equ PORTC Use Port C if UsePORTB not defined MyTris equ TRISC TRISC must be used to set data direction for PORTC else MyPort equ PORTB Use Port B if UsePORTB defined MyTris equ TRISB TRISB must be used to set data direct
58. Toggle f f lt b gt gt f lt b gt Assuming b 0 and default bit value for a TABLE A 18 PIC18 CONTROL OPERATIONS Hex Mnemonic Description Function E2n BC n Branch if Carry if C 1 PC 2 2 n gt PC else PC 2 gt PC E6n B n Branch if Negative if N 1 PC 2 2 n gt PC else PC 2 gt PC E3n BNC n Branch if Not Carry if C 0 PC 2 2 n PC else PC 2 gt PC E7n B n Branch if Not Negative if N 0 PC 2 2 n gt PC else PC 2 gt PC E5n BNOV n Branch if Not Overflow if OV 0 PC 2 2 n gt PC else PC 2 gt PC Eln BNZ n Branch if Not Zero if Z 0 PC 2 2 n gt PC else PC 2 gt PC E4n BOV n Branch if Overflow if OVz1 PC 2 2 n gt PC else PC 2 gt PC D O n BRA n Branch Unconditionally PC 2 2 n PC EOn BZ n Branch if Zero if Z 1 PC 2 2 n gt PC else PC 2 gt PC ECkk CALL n S Call Subroutine 1st word PC 4 gt TOS n gt PC lt 20 1 gt kkk 2nd word if s 1 WREG gt WREGs STATUS gt STATUSs BSR gt BSRs 0004 CLRWDT Clear Watchdog Timer 0 gt WDT 0 gt WDT postscaler 1 TO 1 gt PD 0007 DAW Decimal Adjust WREG if WREG lt 3 0 gt gt 9 or DC 1 WREG lt 3 0 gt 6 gt WREG lt 3 0 gt else WREG lt 3 0 gt gt WREG lt 3 0 gt if WREG lt 7 4 gt gt 9 or C 1 WREG lt 7 4 gt 6 gt WREG lt 7 4 gt else WREG lt 7 4 gt gt WREG lt 7 4 gt EFkk GOTO n Go to address 1st word n gt PC lt 20 1 gt F
59. Tools and MPLAB X IDE In this MPLAB X IDE project an assembly source file prog asm is shown with its associated assembler MPASM assembler MPLAB X IDE will use this information to generate the object file prog o for input into the MPLINK object linker For more information on the assembler see the MPASM assembler documentation The C source file main c is also shown with its associated MPLAB C18 C compiler MPLAB X IDE will use this information to generate an object file main o for input into the MPLINK object linker For more information on the compiler see the MPLAB C18 C compiler documentation listed in Recommended Reading In addition precompiled object files precomp o may be included in a project with no associated tool required MPLAB C18 requires the inclusion of a precompiled standard code module c018i o for example For more information on available Microchip precompiled object files see the MPLAB C18 C compiler documentation Some library files math 1ib are available with the compiler Others may be built using the librarian tool MPLIB object librarian For more information on the librarian see the MPLIB librarian documentation For more information on available Microchip libraries see the MPLAB C18 C compiler documentation The object files along with library files are used to generate the project output files via the linker MPLINK object linker MPLAB X IDE will automatically add the correct linker scr
60. Warnings 19 1 Introduction 2 Ended ea Sh ee td at sh ee ES E AE 307 19 2 Hex ES d ee ee La 307 19 39 COFF T COD Conversion EITOLS 2 oreet toes aida 307 19 4 COFF To COD Converter Warnings eee inerenti aaia eene aao ttd ie enne ENEE ENEE 307 19 5 COD File Errors c 308 Part 5 Appendices Appendix A Instruction Sets AA le reel tele cit id AA NN A 311 A 2 Key to 12 14 Bit Instruction Width Instruction Sets A 311 A 3 12 Bit Instruction Width Instruction Set ss 313 AA 14 Bit Instruction Width Instruction Set ss 315 A 5 14 Bit Instruction Width Extended Instruction Set 4 317 A 6 12 Bit 14 Bit Instruction Width Pseudo Instructions 4 320 A 7 Key to PIC18 Device Instruction Set sise 322 A 8 PIC18 Device Instruction Set iii 324 A 9 PIC18 Device Extended Instruction Set is 328 Appendix B Useful Tables Bal Introduction ida 329 BZ ASCIl Character Seta e a de ete atia 329 B 3 Hexadecimal to Decimal Conversion use 330 le E EE I EE 331 Worldwide Sales and Service iii once a a XRo nahiari asias GEN KR Es eB ge 337 O 1994 2013 Microchip Technology Inc DS33014L page 7 Assembler Linker Librarian User s Guide NOTES DS33014L page 8 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Preface NOTICE TO CUSTOMERS All documentation becomes dated and this manual is no exception Microchip tools and documentation are constantly evolving to meet customer needs
61. a PIC1X device with EE data FLASH finclude p16f877a inc Include standard header file for the selected devic org 0x0000 The following code will be placed in reset address 0 goto Main Jump to an address whose label is Main org 0x0004 The following code will be placed in interrupt address 4 goto int routine Jump to an address whose label is int routine org 0x0010 The following code section will placed starting from address 10H Main Write your main program here goto Main Loop back to Main ER org 0x0100 The following code section will be placed starting from address 100H int_routine Write your interrupt service routine here retfie Return from interrupt org 0x1000 You can create a data or character table starting from any address in program memory In this case the address is 71000h ch tbll da PICwithFLASH 6 program memory locations starting from 1000h will be filled with six 14 bit packed numbers each representing two 7 bit ASCII characters org 0x2100 The absolute address 2100h is mapped to the 0000 location of EE data memory in PIC16Fxxx You can create a data or character table starting from any address in EE data memory ch tbl2 de PICwithFLASH 12 EE data memory locations starting from 0 will be filled with 12 ASCII characters end DS33014L page 142 1994 201
62. an endif statement i e an if statement was used without an endif 213 The EXTERN directive should only be used when making a o file The extern directive only has meaning if an object file is being created This warning has been superseded by Error 149 214 Unmatched An unmatched parenthesis was found The warning is used if the parenthesis is not used for indicating order of evaluation 1994 2013 Microchip Technology Inc DS33014L page 215 Assembler Linker Librarian User s Guide 215 Processor superseded by command line Verify processor symbol The processor was specified on the command line as well as in the source file The command line has precedence If you are using an IDE with the assembly set the device to match the source file from File gt Project Properties MPLAB X IDE or Configure gt Select Device MPLAB IDE v8 216 Radix superseded by command line The radix was specified on the command line as well as in the source file The command line has precedence 217 Hex file format specified on command line The hex file format was specified on the command line as well as in the source file The command line has precedence 218 Expected DEC OCT HEX Will use HEX Bad radix specification 219 Invalid RAM location specified Ifthe maxramand badramdirectives are used this warning flags use of any RAM locations declared as invalid by these directives Note that the provided header files include maxrama
63. applications or combined C code and assembly applications select the Microchip C18 Toolsuite as the active toolsuite Make sure the executable paths are correct as per Table 13 1 or Table 13 3 respectively Name the project and place it in its own folder Add the sample files to your project eg sourcel c source2 asm and if customized script lkr 2 Once the project is created select Project gt Build Options Project to open the Build Options for Project dialog For MPLAB C compiler for PIC18 MCUs sample applications click the Directories tab and enter CompilerInstallationPath 1lib under Library Path where CompilerInstallationPathis the location where the C compiler is installed on your system Click the MPLINK Linker tab and then click the Generate map file checkbox to select it 3 Select from the Build Configuration list see below whether you will be develop ing your application Debug or are ready to program it into a device Release Debug lc Ge Tei Setting this control will set the value for the macro DEBUG found in the linker script file Other macros in the linker script eg CRUNTIME are automatically set by MPLAB IDE 4 Select Project gt Build All to build the application If your project contains a single assembly file with no linker script file you will be asked if you want to build absolute code or relocatable code The sample applications should be bui
64. bank3 var3 is allocated the address 0x1a0 RST CODE 0x0 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST pagesel start Jumps to the location labelled goto start start PGM CODE This is the beginning of the code section named PGM It is a relocatable code section since no absolute address is given along with directive CODE start banksel varO Select Dank moviw 0x00 movwf var var is accessible from bankO banksel varl Select bankl moviw 0x01 movwf var var is accessible from bankl also banksel var2 Select bank2 moviw 0x02 movwf var var is accessible from bank2 also banksel var3 Select bank3 movlw 0x03 movwf var var is accessible from bank3 also goto Go to current line loop here end O 1994 2013 Microchip Technology Inc DS33014L page 161 Assembler Linker Librarian User s Guide 4 66 undefine DELETE A SUBSTITUTION LABEL 4 66 1 Syntax fundefine label 4 66 2 Description label is an identifier previously defined with the define directive The symbol named is removed from the symbol table 4 66 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is most often used with the ifdef and ifndef directives which look for the presence of an item in the symbol table 4 66
65. code Enable WREG tracking Remove MOVLW instructions in instances where it can be determined Ow that the Working register already contains the correct value Enable copy propagation Replace uses of x with uses of y for x y as long as intervening Op instructions have not changed the value of either x or y This optimization by itself does not save any instructions but enables dead code removal Enable redundant store Remove redundant assignments of the form x lt y when the Or elimination assignment appears multiple times in an instruction sequence and the intervening code has not changed the value of x or y Enable dead code Remove dead code i e values computed in a function which are not od removal used on any path to the function s exit or instructions which compute only dead values Enable procedural Reduce the size of the generated code by creating a procedure Opa abstraction containing the repeated code and replacing the copies with a call to the procedure Procedural Abstraction For Enable All and Custom optimizations set the desired number of pa pass O 1994 2013 Microchip Technology Inc DS33014L page 25 Assembler Linker Librarian User s Guide TABLE 1 13 ADDITIONAL CONTROLS Option Description Additional Options Enter additional command line options See the tool documentation for more options Option Description Generated Command Click on option text to see
66. code section named INTRPT is placed at program memory location 0x4 The next two instructions are placed in code section INTRPT pagesel ISR Jumps to the location labelled goto ISR PISR fill goto start start Fill up to address OFh with instruction goto start CODE 0x0010 start Write your main program here fill nop 5 Fill 5 locations with NOPs goto Go to current line loop here ISR Write your interrupt service retfie routine here end 1994 2013 Microchip Technology Inc DS33014L page 117 Assembler Linker Librarian User s Guide 4 34 7 PIC18 Application Example i11 The fi11 directive is used to specify successive program memory locations with a constant or an assembly instruction For PIC18 devices only an even number is allowed to be specified as a count of locations to be filled finclude p18f452 inc RST goto fill HI INT goto fill LO INT goto fill start fill goto INTR H INTR L retfie end retfie CODE 0x0000 start 0 HI INT CODE INTR H goto start 6 0x0008 CODE INTR L 10a9 CODE Include standard header file Lor uh selected devic The code section named RST is placed at location 0x0 goto start code section Jumps to the P start Fills 0 in 2 locations HI INT addr Fills 6 locations is 2 bytes wide program memory The instruction is placed in RST locatio
67. constants the constant directive also works 4 134 See Also set variable equ cblock 4 13 5 Examples See the examples under variable ET 1994 2013 Microchip Technology Inc DS33014L page 89 Assembler Linker Librarian User s Guide 4 14 da STORE STRINGS IN PROGRAM MEMORY PIC12 16 MCUs 4 14 4 Syntax label da expr expr2 exprn 4 14 2 Description da Data ASCII Generates a packed 14 bit number representing two 7 bit ASCII characters 4 14 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is useful for storing strings in memory for PIC16 MCU devices 4 14 4 Simple Examples e da abcdef will put 30E2 31E4 32E6 into program memory da 12345678 0 will put 18B2 19B4 1AB6 1BB8 0000 into program memory da OxFFFF will put 0x3FFF into program memory 4 14 5 Application Example da This example shows the usefulness of directive da in storing a character string in the program memory of 14 bit architecture devices This directive generates a packed 14 bit number representing two 7 bit ASCII characters finclude p16f877a inc Include standard header file for the selected device ORG 0x0000 The following code will be programmed in reset address O0 goto start Jump to an address labelled SCA TE x start Write your main program here
68. core device programmers This file format is useful for transferring PIC1X MCU series code to Microchip programmers and third party PIC1X MCU programmers 1 7 5 1 INTEL HEX FORMAT This format produces one 8 bit hex file with a low byte high byte combination Since each address can only contain 8 bits in this format all addresses are doubled Each data record begins with a 9 character prefix and ends with a 2 character checksum Each record has the following format BBAAAATTHHHH HHHCC where BB A two digit hexadecimal byte count representing the number of data bytes that will appear on the line AAAA A four digit hexadecimal address representing the starting address of the data record TT A two digit record type that will always be 00 except for the end of file record which will be 01 HH A two digit hexadecimal data byte presented in low byte high byte combinations ec A two digit hexadecimal checksum that is the two s complement of the sum of all preceding bytes in the record DELI c H s nY e 7 O 1994 2013 Microchip Technology Inc DS33014L page 57 Assembler Linker Librarian User s Guide EXAMPLE 1 3 INHX8M file name bes 1000000000000000000000000000000000000000F0 00100000000000EC 0032000000280040006800A
69. data Clk set clock Clk Clear clock Dat Clear data Counter E test next bit Counter 7 done with byte Lup no Bus indicate not busy p kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk global SPI Out end Buffer 1994 2013 Microchip Technology Inc DS33014L page 183 Assembler Linker Librarian User s Guide 5 7 EXAMPLE OF HEXADECIMAL TO ASCII CONVERSION Directives highlighted in this example are udata res global 5 7 1 Program Functional Description This program converts a hexadecimal byte into two ASCII bytes The application is written as relocatable code i e you must use both the assembler and linker to generate the executable Program registers are assigned using the udata and res directives Sections of code are created using the code statement External code is accessed using global 5 7 2 Commented Code Listing PRRRKRREKKKRRK KK RK KKK ERK KKK KK RK KKK ERK KE KKK RR KR KEK KK KERR KR KKK RARE KK KKK KK get a hex byte in W convert to 2 ASCII bytes in ASCIIH ASCIIL req 2 stack levels PRRRKRREKKKRRK KK RK RK koc kk KKK KK heck koe ke kc ke kc KKK RK KR koc ko ek kc ke kk RK KK ke kc ke KKK KK Variables udata HexTemp res 1 ASCIIH res 1 ASCIIL res 1 pORCECKCkCkCkckckckckokokecko koc kk kk KKK hock ke koc ke KK KKK heck Sk hec heck ck kk Sek koe heck ke heck ke ke ke kk kc e ek K code Hex2ASC movf HexTemp W andlw OxOF get low nibble call
70. for address 0x300001 in more than one object module Found in foo o previously found in bar o This error is issued when MPLAB C18 s pragma config directive has been used in two separate c files e g foo c and bar c with settings specified from the same configuration byte Set configuration bits for a given byte in a single c file Conflicting types for symbol symName Symbol symName is defined in different locations as different types Could not find definition of symbol symName in file filename A symbol symName is used without being defined in file filename Could not find file filename An input object or library file was specified which does not exist or cannot be found in the linker path Could not open map file filename for writing Verify that if filename exists it is not a read only file Could not resolve section reference symName in file filename The symbol symName is an external reference No input module defines this symbol If the symbol is defined in a library module ensure that the library module is included on the command line or in the linker script file using the FILES directive Could not resolve symbol symName in file filename The symbol symName is an external reference No input module defines this symbol If the symbol is defined in a library module ensure that the library module is included on the command line or in the linker script file using the FILE
71. for relief under that Act Information contained in this publication regarding device applications and the like is provided only for your convenience and may be superseded by updates lt is your responsibility to ensure that your application meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORY OR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITS CONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSE Microchip disclaims all liability arising from this information and its use Use of Microchip devices in life support and or safety applications is entirely at the buyer s risk and the buyer agrees to defend indemnify and hold harmless Microchip from any and all damages claims suits or expenses resulting from such use No licenses are conveyed implicitly or otherwise under any Microchip intellectual property rights QUALITY MANAGEMENT SYSTEM CERTIFIED BY DNV ISO TS 16949 Trademarks The Microchip name and logo the Microchip logo dsPIC FlashFlex KEELOQ KEELOQ logo MPLAB PIC PlCmicro PICSTART PIC logo rfPIC SST SST Logo SuperFlash and UNI O are registered trademarks of Microchip Technology Incorporated in the U S A and other countries FilterLab Hampshire HI TECH C Linear Active Thermistor MTP SEEVAL and The Embedded Control Solutions Company are registered trademarks of Microc
72. goto start start PGM CODE This is the beginning of the code section named PGM It is a relocatable code section Since no absolute address is given along with directive CODE start banksel groupl varl This directive generates cod to set clear bank select bits RPO RP1 of STATUS register depending upon the address of groupl varl clrf groupl varl clrf groupl var2 banksel group2 varl This directive generates cod to set clear bank select bits RPO RP1 of STATUS register depending upon the address of group2 varl clrf group2 varl clrf group2 var2 goto Go to current line loop here end O 1994 2013 Microchip Technology Inc DS33014L page 81 Assembler Linker Librarian User s Guide 4 8 4 7 7 Application Example 2 banksel include p16f877a inc Include standard header file for the selected devic banksel TRISB Since this register is in bank 1 not default bank 0 banksel is used to ensure bank bits are correct LEE TRISB Clear TRISB Sets PORTB to outputs banksel PORTB banksel used to return to bank 0 where PORTB is located movlw 0x55 Set PORTB value movwf PORTB goto end All programs must have an end cblock DEFINE A BLOCK OF CONSTANTS 4 8 1 Syntax cblock expr label increment label increment endc 4 8 2 Description Defines a list of named sequential symbols The purpose of this directive is to assign address offsets to many labels Th
73. gt constant cfl jge macro file con jump to movlw con amp Oxff subwf file w btfsc status carry goto jump to endm and invoked by cfl jge switch val max switch switch on it would produce movlw max switch amp Oxff subwf switch val w btfsc status carry goto switch on 1994 2013 Microchip Technology Inc DS33014L page 205 Assembler Linker Librarian User s Guide NOTES DS33014L page 206 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 8 Errors Warnings Messages and Limitations 8 1 INTRODUCTION Error messages warning messages and general messages produced by the MPASM assembler are listed and detailed here These messages always appear in the listing file directly above each line in which the error occurred Limitations of the assembler tool are also listed The messages are stored in the error file err if no MPASM assembler options are specified If the e or e option is used turns error file off then the messages will appear on the screen If the q or q quiet mode option is used with the e or e then the messages will not display on the screen or in an error file The messages will still appear in the listing file Topics covered in this chapter Assembler Errors Assembler Warnings Assembler Messages Assembler Limitations 1994 2013 Microchip Technology Inc DS33014L page 207 Assembler Linker Librarian U
74. if Begin Conditionally Assembled Code Block AAA 125 4 40 ifdef Execute If Symbol Has Been Defined AAA 127 4 41 ifndef Execute If Symbol Has Not Been Defined A 129 4 42 include Include Additional Source File sisi 130 4 43 list Listing Options ee ec rere pnd UE ied eR pede de des 131 4 44 local Declare Local Macro Variable A 132 4 45 macro Declare Macro Definition sise 134 4 46 maxram Define Maximum RAM Location ee 136 4 47 maxrom Define Maximum ROM Location nenne netna 137 4 48 messg Create User Defined Message ssesseeeeeeeen emm ee nennen 138 4 49 noexpand Turn off Macro Expansion si 140 4 50 nolist Turn off Listing Output sise 140 4 51 org Set Program Origili 2 3 ien iii 141 4 52 page Insert Listing Page Eject eter edere ede nee deed 144 4 53 pagesel Generate Page Selecting Code PIC10 12 16 MCUS e 144 4 54 pageselw Generate Page Selecting Code Using WREG Commands PIC10 12 16 MCUs 146 4 55 processor Set Processor Type sushi dico 147 4 56 radix Specify Default Radix dE ENNER tee iia 148 4 57 res Reserve Memo ini REENEN iia 150 4 58 set Define an Assembler Variable ss 152 4 59 space Insert Blank Listing Lines ss 153 4 60 subtitle Specify Program Subtitle sis 153 4 61 title Specify Program Title EE 154 4 62 udata Begin an Object File Uninitialized Data Section
75. in the Output window Preprocessor macro Add macro directive definitions Dmacro definitions Include directories Enter a path to header h files I inc passes passes for procedural abstraction TABLE 1 12 OPTIMIZATION CATEGORY Option Description Command Line Optimizations Select to Olevel Enable Disable all optimizations below Select optimizations that are Debug Friendly Customize the optimizations from the selections below Enable all optimizations View whether all options enabled N A Enable duplicate string Take two or more identical literal strings and combine them into a single Om merging string table entry with a single instance of the raw data stored in program memory Enable banking optimizer Remove MOVLB instructions in instances where it can be determined On that the Bank Select register already contains the correct value Enable unreachable code Attempt to remove any code that can be provably demonstrated to not Ou removal execute during normal program flow Enable code Attempt to reorder code sequences so that they appear in the order in Os straightening which they will be executed Enable tail merging Attempt to combine multiple sequences of identical instructions into a ot single sequence Enable branch Optimize branching Some of the branch optimizations save program Ob optimization space while others may expose unreachable
76. label set expr 4 58 2 Description label is assigned the value of the valid MPASM assembler expression specified by expr The set directive is functionally equivalent to the equ directive except that set values may be subsequently altered by other set directives 4 58 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation Because set directive values may be altered by later set directives set is particularly useful when defining a variable in a loop e g a while loop 4 58 4 See Also equ variable while 4 58 5 Simple Example area set 0 width set 0x12 length set 0x14 area set length width length set length 1 4 58 6 Application Example set equ This example shows the usage of the set directive used for creating symbols which may be used in MPASM assembler expressions only The symbols created with this directive do not occupy any physical memory location on the microcontroller include p16f877a inc Include standard header file for the selected devic perimeter set 0 The label perimeter is assigned value 0 The label area is assigned area set 0 value 0 The value assigned by the set directive may be reassigned later lngth equ 50H The label lngth is assigned the value 50H wdth equ 25H The label wdth is assigned the value 25H The value assigned by the equ d
77. latest information on Microchip MPLAB IDE the Windows Integrated Development Environment for development systems tools This list is focused on the MPLAB IDE MPLAB IDE Project Manager MPLAB Editor and MPLAB SIM simulator as well as general editing and debugging features Programmers The latest information on Microchip programmers These include the device production programmers MPLAB REAL ICE in circuit emulator MPLAB ICD 3 in circuit debugger MPLAB PM3 and PRO MATE II and development nonproduction programmers MPLAB ICD 2 in circuit debugger PICSTART Plus and PICkit 1 2 and 3 Starter Demo Boards These include MPLAB Starter Kit boards PICDEM demo boards and various other evaluation boards D DS33014L page 14 O 1994 2013 Microchip Technology Inc Preface CUSTOMER SUPPORT Users of Microchip products can receive assistance through several channels Distributor or Representative Local Sales Office Field Application Engineer FAE Technical Support Customers should contact their distributor representative or field application engineer FAE for support Local sales offices are also available to help customers A listing of sales offices and locations is included in the back of this document Technical support is available through the web site at http support microchip com Documentation errors or comments may be emailed to docerrors microchip com A A
78. librarian documentation Chapter 16 Librarian Interfaces Single File Assembly Projects Ask me Pop up a dialog to ask me when a project contains a single file whether want to generate absolute or relocatable code Generate absolute code Always generate absolute code i e code generated by the assembler not requiring a linker Generate relocatable Always generate relocatable code e code generated using a code linker Other Controls Extended mode Build in extended mode The selected device must support extended mode and the correct configuration bit must be enabled See MPLAB C18 Setup for PIC18 Extended Instruction Set Use Generate stack analysis Generate a stack analysis report for use with third party application report Understand from Scientific Toolworks Inc See their web site at www scitools com for more information This option is only supported on devices that support extended mode The checkbox for Extended mode must be checked as well See the previous row in this table A Oi X A AA O 1994 2013 Microchip Technology Inc DS33014L page 41 Assembler Linker Librarian User s Guide MPLAB C18 Setup for PIC18 Extended Instruction Set Use To use the PIC18 MCU Extended Instruction set in your MPLAB C18 project do th
79. linker Section 14 5 COFF File Errors DS33014L page 302 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Part 4 Utilities Chapter 18 Utilities Overview and Usage Chapter 19 Errors and Warnings 1994 2013 Microchip Technology Inc DS33014L page 303 Assembler Linker Librarian User s Guide NOTES DS33014L page 304 O 1994 2013 Microchip Technology Inc MICROCHIP ASSEMBLER LINKER LIBRARIAN USER S GUIDE Chapter 18 Utilities Overview and Usage 18 1 INTRODUCTION An overview of the 8 bit utilities and their capabilities are presented Topics covered in this chapter What are Utilities Utilities Operation mp2hex exe Utility mp2cod exe Utility 18 2 WHAT ARE UTILITIES Utilities are tools available for use with the assembler and or linker The MPLIB object librarian is a utility that was discussed in the previous sections TABLE 18 1 AVAILABLE UTILITIES Utility Description mplib exe Creates modifies and extracts files from libraries See Part 3 MPLIB Object Librarian for more information mp2hex exe Generates a Hex file from a COF file mp2cod exe Generates a COD and list file from a COF file 18 3 UTILITIES OPERATION The utilities MP2HEX and MP2COD work with the MPLINK object linker to generate executable code hex or a linker listing file 1st from the linker COF file The Hex file
80. movff or movsf commands 174 CONFIG directives must be listed in ascending order List con ig directive configuration registers in ascending order e g CONFIG CONFIGO CP OFF 0 CONFIG _CONFIG1 _OSCS OFF 1 amp RCIO OSC 1 CONFIG CONFIG2 BOR ON 2 amp BORV 25 2 175 IDLOCS directives must be listed in ascending order List idlocs directive ID registers in ascending order e g idlocs _IDLOCO 0x1 __idlocs _IDLOC1 0x2 _ idlocs _IDLOC2 0x3 176 CONFIG Directive Error An error was found in the config directive syntax 177 _ CONFIG directives cannot be used with CONFIG directives Do not mix config directives and config directives when assigning configuration bits in your code 178 _ CONFIG Directive Error An error was found in the config directive syntax 1994 2013 Microchip Technology Inc DS33014L page 213 Assembler Linker Librarian User s Guide 179 Instruction is not supported on this device This error would occur when an instruction is used in code which is not supported on the particular family architecture 180 RES directive cannot reserve odd number of bytes in PIC18 absolute mode This error would occur if you try to reserve an odd number of bytes using a PIC18 device and assemble in absolute mode Quickbuild For example org 0x0 a res 1 end If you try to Quickbuild the above PIC18 MCU program you will see error 180 and warning 231 UNKNOWN ERROR An inter
81. must be contiguous Object file sections except udata_ovr sections cannot be stopped and restarted within a single source file To resolve this problem either name each section with its own name or move the code and data declarations such that each section is contiguous This error will also be generated if two sections of different types are given the same name 155 All overlaid sections of the same name must have the same starting address If multiple udata_ovr sections with the same name are declared they must all have the same starting address 156 Operand must be an address label When generating object files only address labels in code or data sections may be declared global Variables declared by the set or equ directives may not be exported 157 ORG at odd address For PIC18 devices you cannot place org at an odd address only even Consult your device data sheet 158 Cannot use RES directive with odd number of bytes For PIC18 devices you cannot use res to specify an odd number of bytes only even Consult your device data sheet 159 Cannot use FILL directive with odd number of bytes For PIC18 devices you cannot use 111 to fill with data an odd number of bytes only even Consult your device data sheet 160 CODE_PACK directive not available for this part substituting CODE The code_pack directive can only be used with byte addressable ROM 161 Non negative value required for this context Some contexts require n
82. not desired ifdef AlternateASM MyPort equ PORTC Use Port C if AlternateASM defined MyTris equ TRISC TRISC must be used to set data direction for PORTC else MyPort equ PORTB Use Port B if AlternateASM not defined MyTris equ TRISB TRISB must be used to set data direction for PORTB endif banksel MyTris CLrE MyTris Set port to all outputs banksel MyPort Return to bank used for port movlw 55h Move arbitrary value to W reg movwf MyPort Load port selected with 55h end ILLUC D S s M png O 1994 2013 Microchip Technology Inc DS33014L page 127 Assembler Linker Li brarian User s Guide 4 40 7 Application Example 2 ifdef This program uses the control directive define along with the ifdef else and endif directives to selectively assemble code for use with either an emulator or an actual part The co ntrol directive define is used to create a flag to indicate how to assemble the code for the emulator or for the actual device finclude p18f452 inc define EMULATED Comment out with if actual part INIT ifdef EMULATE D If emulator used add lines of movlw 0xb0 movwf Oxf9c fendif initialization code to work around table read limitation DS33014L page 128 1994 2013 Microchip
83. of the PROTECTED modifier prevents the linker from assigning random relocatable code to this region The name xs ram is arbitrary and can be any desired name What is important are the START and END addresses which should match the physical memory address reange of the external memory being used CODEPAGE NAME xsram START 0x020000 END 0x01FFFFF PROTECTED In addition to the new CODEPAGE a new logical SECTION is created and assigned to the program memory region specified in the associated CODEPAGE definition SECTION NAME SRAM BASE ROM xsram In the C compiler application s source code file the pragma romdata directive instructs the linker to allocate the SRAM s starting address to the memory region specified by the SRAM BASE logical section definition The physical address is provided by the xsram codepage directive at 20000h Since the memory region occupied by the SRAM is program memory not data memory the rom qualifier is required in the declaration of the char array variable sram In addition this memory region is beyond a 16 bit address range 64Kbyte and therefore requires the use of the far qualifier in order for C pointers to correctly access this region pragma romdata SRAM BASE Assigns this romdata space at 0x020000 rom far char sram Declare an array at starting address To build the C compiler sample application refer to Sec
84. on the Project Manager toolbar 4 Select Project gt Build All to build the application DS33014L page 258 O 1994 2013 Microchip Technology Inc Sample Applications 13 2 3 Using the Command Line The command line provides a platform independent method to develop your code 13 2 3 1 BUILDING APPLICATIONS To build an application on the command line 1 The listed Environment Variables need to be set as specified To set these vari ables go to the Command prompt and type SET to view and set the variables In Windows OS go to Start gt Settings gt Control Panel gt System Advanced tab Environment Variables button View and edit variables here a PATH Make sure the executables can be found as per Table 13 1 and Table 13 3 b MCC_INCLUDE If MPLAB C Compiler for PIC18 MCUs is used this should point to the h subdirectory of the C compiler installation directory 2 For C code compilation use the following mcc18 pdevice sourcel c where device is the device representation e g 18F8772 for the PIC18F8722 device and source1 c is the C code source file example For multiple files leave a space between each file 3 For MPASM assembly with MPLAB X IDE use the following Windows OS mpasmx pdevice source2 asm Linux or Mac OS mpasmx pdevice source2 asm where device is the device representation and source2 asmis the assembly code source file example For multiple files leave a space between each file 4 For MP
85. on the differences between absolute and relocatable object assembly O 1994 2013 Microchip Technology Inc DS33014L page 51 Assembler Linker Librarian User s Guide 1 7 ASSEMBLER INPUT OUTPUT FILES These are the default file extensions used by the assembler and the associated utility functions TABLE 1 1 INPUT FILES Source Code asm Default source file extension input to assembler Include File inc Include header file TABLE 1 2 OUTPUT FILES Listing File Ist Default output extension for listing files generated by assembler Error File err Output extension from assembler for error files Hex File Formats hex hxl hxh Output extension from assembler for hex files Cross Reference File xrf Output extension from assembler for cross reference files Object File Lo Output extension from assembler for object files 1 7 1 Source Code asm Assembly is a programming language you may use to develop the source code for your application The source code file may be created using any ASCII text file editor Note Several example source code files are included free with the IDE Your source code should conform to the following basic guidelines Each line of the source file may contain up to four types of information Labels Mnemonics Directives and Macros Operands Comments The order and position of these are important For ease of debug
86. operand scnstart high Return high byte of section start operand scnstart upper Return upper byte of section start operand Operator precedence information may be found in 3 5 Arithmetic Operators and Precedence There are some restrictions involving these operators with relocatable symbols For example the 1ow high and upper operators must be of the form low high upper relocatable symbol constant offset where relocatable symbolis any label that defines a program or data memory address e constant offset is an expression that is resolvable at assembly time to a value between 32768 and 32767 Either relocatable symbol Or constant offset may be omitted Operands of the form relocatable symbol relocatable symbol will be reduced to a constant value if both symbols are defined in the same code or data section In addition to section operators there are section pseudo instructions Pseudo Instruction Definition scnend lfsr scnend lfsr nes where n is O 1 or 2 as with the LFSR instruction and s is a string which is taken to be the name of a section This instruction loads LFSR with the end address of the section scnstart lfsr scnstart lfsr n s where nis0 1 or 2 as with the LFSR instruction and s is a string which is taken to be the name of a section This instruction loads LFSR with the start address of the section These operators and instructions only have meaning when an
87. other flags 2 Building a C project for PIC18F6722 with debug sections for code at 0x1fd80 and for data at Oxef4 Traditional non extended mode mplink exe p18F6722 u CRUNTIME u DEBUG u_DEBUGCODESTART 0x1fd80 u DEBUGCODELEN 0x280 u DEBUGDATATART 0xef4 u DEBUGDATALEN 0xc other flags 3 Building a Assembly project no debug mplink exe p18f6722 other flags E E __ _m_Q J Q H J ER O 1994 2013 Microchip Technology Inc DS33014L page 247 Assembler Linker Librarian User s Guide Generic Linker Script 1816722 g lkr File 18f6722 g lkr Generic linker script for the PIC18F6722 processor DEFINE _CODEEND _DEBUGCODESTART 1 DEFINE CEND DEBUGCODESTART DEBUGCODELEN DEFINE DATAEND DEBUGDATASTART 1 DEFINE DEND DEBUGDATASTART DEBUGDATALEN LIBPATH IFDEF _CRUNTIM IFDEF _EXTENDEDMODE FILES c018i e o FILES clib e lib FILES p18f6722 e lib
88. page 294 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Part 3 MPLIB Object Librarian Chapter 15 MPLIB Librarian Overview sise 297 Chapter 16 Librarian Interfaces ss 299 Chapter 17 Errors RE PY 301 1994 2013 Microchip Technology Inc DS33014L page 295 Assembler Linker Librarian User s Guide NOTES DS33014L page 296 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 15 MPLIB Librarian Overview 15 1 INTRODUCTION An overview of the MPLIB object librarian and its capabilities is presented Topics covered in this chapter What is MPLIB Librarian How MPLIB Librarian Works How MPLIB Librarian Helps You Librarian Operation Librarian Input Output Files 15 2 WHAT IS MPLIB LIBRARIAN MPLIB object librarian the librarian combines object modules generated by the MPASM assembler or the MPLAB C18 C compiler into a single library file This file may then be inputted into the MPLINK object linker 15 3 HOW MPLIB LIBRARIAN WORKS A librarian manages the creation and modification of library files A library file is simply a collection of object modules that are stored in a single file There are several reasons for creating library files Libraries make linking easier Since library files can contain many object files the name of a library file can be used instead of the na
89. perimeter Multiply register 20H by 2 Carry bit may be affected rd perimeter 1 Again increment register 21H if carry was generated goto Go to current line loop here end Ee O 1994 2013 Microchip Technology Inc DS33014L page 83 Assembler Linker Librarian User s Guide 49 code BEGIN AN OBJECT FILE CODE SECTION 4 9 1 Syntax label code ROM address 4 9 2 Description This directive declares the beginning of a section of program code If label is not specified the section is named code The starting address is initialized to the specified address or will be assigned at link time if no address is specified Note Two sections in a source file may not have the same name 4 9 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation There is no end code directive The code of a section ends automatically when another code or data section is defined or when the end of the file is reached 4 9 4 See Also extern code pack global idata udata udata acs udata ovr udata shr 4 9 5 Simple Example RESET code 0x01FF goto START 4 9 6 Application Example code This program demonstrates the code directive which declares the beginning of a section of program code finclude p16f877a inc Include standard header file for the selected devic RST CODI 0x0 The code section named R
90. pragma code directive to instruct the linker to place the relocated reset and interrupt vectors at the appropriate memory locations A main function must be included as this is called from the C compiler startup code that is added during the link process The linker automatically includes this C compiler initialization code provided in file c018i c and must be accessed by the application code through an in line assembly goto instruction shown below finclude lt p18cxxx h gt VECTOR MAPPING FER KKK A A A A A A KK KK Ck Kk A k KR ck kk ke ke ke ke e e x x extern void startup void See c018i c in your C18 compiler dir pragma code RESET INTERRUPT VECTOR 0x000800 void reset void _asm goto startup _endasm pragma code HIGH INTERRUPT VECTOR 0x000808 void high ISR void pragma code LOW INTERRUPT VECTOR 0x000818 void low ISR void APPLICATION CODE XX kk kk XX ARRAY fpragma code void main void while 1 S Main application code here END OF APPLICATION KCKCKCKCkCkCkCk Ck k Ck kk k kCk kc k kc k ck k kc kckckckckokckok ck ke ex e x DS33014L page 270 1994 2013 Microchip Technology Inc Sample Applications 13 5 1 4 EXAMPLE 3 MIXED LANGUAGE BOOT LOADER APPLICATION This example shows the linker script startup code and source code modifications needed to accommodate a mixed language application which employs
91. reminder message to tell you that a variable that is being accessed in not in bank 0 This message was added to remind you to check your code particularly code in banks other than 0 Review the section on banksel Section 4 7 banksel Generate Bank Selecting Code and bankisel Section 4 6 bankisel Generate Indirect Bank Selecting Code PIC12 16 MCUs and ensure that your code uses bank bits whenever changing from ANY bank to ANY other bank including bank 0 Since the assembler or linker can t tell which path your code will take you will always get this message for any variable not in bank 0 You can use the errorlevel command to turn this and other messages on and off but be careful as you may not spot a banking problem with this message turned off For more about errorlevel see Section 4 30 errorlevel Set Message Level A similar message is 306 for paging 303 Program word too large Truncated to core size The program word instruction width is too large for the selected device s core program memory size Therefore the word has been truncated to the proper size For example a 14 bit instruction would be truncated to 12 bits to be used by a PIC16F54 304 ID Locations value too large Last four hex digits used Only four hex digits are allowed for the ID locations 305 Using default destination of 1 file If no destination bit is specified the default is used Usually code that causes this message i
92. res 1 groupl var2 located at 0x21 initialized with O0 group2 IDATA Declaration of group2 data The addresses for variables under this data section are allocated automatically by the linker group2 varl db 1 2 3 4 4 bytes in RAM are reserved Values will be padded with 34 RETLW group2 var2 dw 0x1234 zl word in RAM is reserved Values will be padded with 34 RETLW RST CODE 0x0 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST pagesel start Jumps to the location labelled goto start estaria PGM CODE This is the beginning of the code section named PGM It is a relocatable code section since no absolute address is given along with directive CODE start goto Go to current line loop here end A DR a O 1994 2013 Microchip Technology Inc DS33014L page 121 Assembler Linker Librarian User s Guide 437 idata acs BEGIN AN OBJECT FILE INITIALIZED DATA SECTION IN ACCESS RAM PIC18 MCUs 4 37 1 Syntax label idata_acs RAM address 4 37 2 Description This directive declares the beginning of a section of initialized data in Access RAM If label is not specified the section is named idata_acs The starting address is initialized to the specified address or will be assigned at link time if no address is specified No code can be placed by the user in this segment The linker will
93. rita rales Bie a 292 14 5 COFF disc d SR 293 14 6 Other Errors Warnings and Messages seen nen nennen enne 294 14 7 Common Problems ner eevee dees Gee ne 294 Part 3 MPLIB Object Librarian Chapter 15 MPLIB Librarian Overview 15 1 Introduction nce ee e a LE tach Poe d A A tn c ted 297 15 2 What is MPLIB Librarian sis reete id rite e eden nee ENNER ee drea ee seine ete 297 15 3 How MPLIB Librarian Works sise 297 15 4 How MPLIB Librarian Helps YOu sise 298 15 5 Librarian TEE 298 15 6 Librarian Input Output Files sise 298 Chapter 16 Librarian Interfaces 16 1 Introducir oa freto o tt ne nn ne 299 16 2 MPLAB X IDE Interface ee SEENEN Seed NEE ENEE EEN ege 299 16 3 MPLAB IDE v8 Interface sise 299 16 4 Command Line Options insine ionii a nn Eee veter entre ne nes 300 16 5 Command Line Examples and pe 300 Chapter 17 Errors IL A use Te Le EE 301 1422 Librarian Parse Errors lada nr dadas 301 173 Library File EOTS i eL a a 302 T 4 GOFF File Errors eren eere rre RE EE RE PER de ERE dais 302 DS33014L page 6 1994 2013 Microchip Technology Inc Table of Contents Part 4 Utilities Chapter 18 Utilities Overview and Usage W DR tee LU eiO E 305 18 2 What are UE 305 19 3 Utilities Op ration ascitis li A Be ele A Ee ye et ducenda 305 18 4 le CR EE 306 18 5 mp2Zcod eelsten ot deet e the ide leida lo lada 306 Chapter 19 Errors and
94. selected devic idlocs _IDLOCO 0x1 IDLOC register 0 will be programmed to 1 idlocs _IDLOC1 0x2 IDLOC register 1 will be programmed to 2 idlocs IDLOC2 0x3 IDLOC register 2 will be programmed to 3 idlocs IDLOC3 0x4 IDLOC register 3 will be programmed to 4 _ idlocs _IDLOC4 0x5 IDLOC register 4 will be programmed to 5 idlocs IDLOC5 0x6 IDLOC register 5 will be programmed to 6 idlocs IDLOC6 0x7 IDLOC register 6 will be programmed to 7 idlocs IDLOC7 0x8 IDLOC register 7 will be programmed to 8 DS33014L page 124 1994 2013 Microchip Technology Inc Directives 4 39 if BEGIN CONDITIONALLY ASSEMBLED CODE BLOCK 4 39 1 Syntax Preferred if expr Supported if expr if expr 4 39 2 Description Begin execution of a conditional assembly block If expr evaluates to true the code immediately following the if will assemble Otherwise subsequent code is skipped until an else directive or an endif directive is encountered An expression that evaluates to zero is considered logically FALSE An expression that evaluates to any other value is considered logically TRUE The if and while directives operate on the logical value of an expression A relational TRUE expression is guaranteed to return a nonzero value FALSE a value of zero if s may be nested up to 16 deep 4 39 3 Usage This directive is used in the following types of code absolute or relocatable For
95. set equal entry index 8 lt lt Left shift set equal flags lt lt 3 gt gt Right shift set equal flags gt gt 3 amp AND set equal flags amp ERROR FLAG 1994 2013 Microchip Technology Inc DS33014L page 69 Assembler Linker Librarian User s Guide TABLE 3 1 ARITHMETIC OPERATORS IN ORDER OF PRECEDENCE Operator Example Inclusive OR set equal flags ERROR_FLAG Ge Exclusive OR set equal flags ERROR FLAG Increment A i Decrement i Note 1 This precedence is the same for the low high and upper operands which apply to sections See Section 6 4 Low High and Upper Operators for more information 2 These operators can only be used on a line by themselves they cannot be embedded within other expression evaluations A A A lt AEREA EA DS33014L page 70 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 4 Directives 4 1 INTRODUCTION Directives are assembler commands that appear in the source code but are not usually translated directly into opcodes They are used to control the assembler its input output and data allocation Note Directives are not instructions movlw btfss goto etc For instruction set information consult your device data sheet Many of the assembler directives have alternate names and formats These may exist to provide backward compati
96. subdirectory for your use Template files are provided for absolute code Code and relocatable code Object development Code examples are also included in the Example subdirectory C18 Toolsuite Installation The MPLAB C18 compiler and related tools must be acquired from Microchip standard lite and evaluation versions available The install includes the MPLAB C18 C compiler and compiler versions of tools in the MPASM Toolsuite The language tools will be installed by default in the directory e Windows OS C Program Files Microchip mplabci8 version e Mac OS Applications microchip mplabc18 version Linux OS opt microchip mplabc18 version where version is the version of the compiler The executables for each tool will be MPLAB C18 C Compiler bin mcc18 exe MPASM Assembler mpasmimpasmx exe MPLINK Object Linker bin mplink exe e MPLIB Object Librarian bin mplib exe Other Utilities bin subdirectory All device header h files are in the h subdirectory For more on these files see MPLAB C18 documentation All device include inc files are in the mpasm subdirectory For more on these files see MPASM assembler documentation All device linker script 1kr files are in the bin LKR subdirectory For more on these files see MPLINK object linker documentation All device library 11ib files and precompiled start up code 0 are in the 1ib subdirectory For more on these files s
97. the PIC18F8720 in extended microcontroller mode The file eeprom2 asm places interrupt handling code at 0x20000 external memory The assembly code directive INTHAND CODE places the code that follows into the INTHAND section The modified linker script file eeprom 1kr maps the INTHAND section to the CODE region that begins at 0x20000 The file eeprom1 c has a 0x1000 element data table in program memory in the same code page with the interrupt handlers The data table is defined in C using the pragma romdata directive to place the table in a section called DATTBL The modified linker script file maps the DATTBL section to the CODE region that begins at 0x20000 Additionally configuration bits are set in C using the pragma config directive The main function in the C file is placed in the default CODE section because there is no section directive explicitly assigned For additional information you may wish to reference PIC18F8720 Device Data Sheet DS39609 MPLAB C18 C Compiler User s Guide DS51288 External Memory Interfacing Techniques for the PIC18F8XXX AN869 Program memory sections specified by the code and linker script are compared below Specific sections highlighted in this sample application SA2 are noted TABLE 13 5 PROGRAM MEMORY MAP PIC18F8720 Program Linker Script Section SA2 Memory Address Not debug or extended Source Code Section 0x000000 page On c
98. the examples below the map FIGURE 11 3 PIC16F1939 REGISTER FILE MAP Address Range General Purpose Registers Bank Linear Data Memory Map 20h 6Fh 80 bytes GPRO Bank 0 2000h AOh EFh 80 bytes GPR1 Bank 1 2050h 120h 16Fh 80 bytes GPR2 Bank 2 20A0h 5A0h 5EFh 80 bytes GPR11 Bank 11 2370h 620h 66Fh 48 bytes and Unimplemented Bank 12 GPR12 6A0h 6EFh Unimplemented GPR13 Bank 13 F20h F6Fh Unimplemented GPR30 Bank 30 23EFh RAM Memory Declarations for PIC16F1939 Linear Memory Region INEARMEM AME linearO0 START 0x2000 END 0x23EF PROTECTED DATABANK AME gpr0 START 0x20 END 0x6F SHADOW linear0 0x2000 DATABANK AME gpr1 START 0xA0 END 0 xEF SHADOW linear0 0x2050 DATABANK AME gpr2 START 0x120 END 0x16F SHADOW linear0 0x20A0 DATABANK AME gpr3 START 0x1A0 END 0x1EF SHADOW linear0 0x20F0 DATABANK AME gpr4 START 0x220 END 0x26F SHADOW linear0 0x2140 DATABANK AME gpr5 START 0x2A0 D 0x2EF SHADOW linear0 0x2190 DATABANK AME gpr6 START 0x320 END 0x36F SHADOW linear0 0x21E0 DATABANK AME gpr7 START 0x3A0 D 0x3EF SHADOW linear0 0x2230 DATABANK AME gpr 8 START 0x420 END 0x4 6F SHADOW linear0 0x2280 DATABANK AME gpr9 START 0x4A0 D 0x4EF SHADOW 1inear0 0x22D0 DATABANK AME gpr10 START 0x520 END 0x56F SHADOW linear0 0x2320 DATABANK AME gpr11 START 0x5A0 D 0x5EF SHADOW linear0 0x2370
99. thus share the same RAM address locations 4 644 See Also extern global idata udata udata acs udata shr 4 64 5 Simple Example Temps udata ovr Templ res 1 Temp2 res 1 Temp3 res 1 Temps udata_ovr LongTempl res 2 this will be a variable at the same location as Templ and Temp2 LongTemp2 res 2 this will be a variable at the same location as Temp3 DS33014L page 158 O 1994 2013 Microchip Technology Inc Directives 4 64 6 Application Example udata_ovr This program demonstrates the udata_ovr directive This directive declares the beginning of a section of overlayed uninitialized data include p16f877a inc same var udata_ovr 0x20 varl res 1 same var udata_ovr 0x20 var2 res 1 RST CODE 0x0 pagesel start goto start PGM CODE start banksel varl movlw OxFF movwf varl comf var2 goto end Include standard header file for the selected devic Declares an overlayed uninitialized data section named same var starting at location 0x20 Declares an overlayed uninitialized data section with the same name as the on declared above Thus variables varl and var2 are allocated at the same address The code section named RST is placed at location 0x0 instructions code section program memory The next two are placed in RST Jumps to the location labelled 7 start This is the beginning of the code section named PGM It is a reloca
100. to the assembler or linker to generate the appropriate bank selecting code for an indirect access of the register address specified by label Only one 1abe1 should be specified No operations can be performed on label This label must have been previously defined The linker will generate the appropriate bank selecting code For 14 bit instruction width most PIC12 PIC16 devices the appropriate bit set clear instruction on the IRP bit in the STATUS register will be generated But for PIC16 extended instructions FSROH is modified instead of IRP bit as there is no IRP bit If the indirect address can be specified without these instructions no code will be generated 4 6 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive may be used with 14 bit instruction width PIC1X devices This excludes 12 bit instruction width devices and PIC18 devices 4 6 4 See Also banksel pagesel 4 6 5 Simple Example movlw Varl movwf FSR Load the address of Varl info FSR bankisel Varl Select the correct bank for Varl movwf INDF Indirectly write to Varl O 1994 2013 Microchip Technology Inc DS33014L page 77 Assembler Linker Librarian User s Guide 4 6 6 Application Example bankisel This program demonstrates the bankisel directive This directive generates the appropriate code to set clear the IRP bit of the
101. top level of the MPASM toolchain contains the following options TABLE 1 1 ALL OPTIONS CATEGORY Option Description Command Line Build in absolute mode For assembly code projects build using the assembler only i e ahex format do not invoke the linker TABLE 1 2 ADDITIONAL CONTROLS Option Description Additional Options Enter additional command line options See the tool documentation for more options Option Description Click on option text to see more information in this tab if available Generated Command For selectable options click this tab to see the equivalent command line option Line MPASM Select a category and then set up assembler options For additional options see MPASM assembler documentation Chapter 2 Assembler Interfaces TABLE 1 3 GENERAL CATEGORY Option Description Command Line Enable case sensitivity The assembler will distinguish between upper and lower case c letters Note Disabling case sensitivity will make all labels uppercase Default Radix Set the default radix either Hexadecimal Decimal or Octal rradix Preprocessor Macro Add macro directive definitions dmacro Definitions AAA II a a DS33014L page 22 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB X IDE TABLE 1 4 OUTPUT CATEGORY Option Description Command Line Cross reference file Create an cros
102. using MOVLW Generates a series of MOVLW instructions one instruction for each expr Each expr must be an 8 bit value Each character in a string is stored in its own MOVLW instruction 4 20 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is used when generating a table of data for the PIC16 extended device family 4 20 4 See Also data db de dt dw 4 20 5 Simple Example dtm A Message 0 dtm FirstValue SecondValue EndOfValues DS33014L page 100 O 1994 2013 Microchip Technology Inc Directives 4 21 dw DECLARE DATA OF ONE WORD 4 21 4 Syntax label dw expr expr expr 4 21 2 Description dw Data Word Reserve program memory words for data initializing that space to specific values For PIC18 devices dw functions like ab Values are stored into successive memory locations and the location counter is incremented by one Expressions may be literal strings and are stored as described in the db data directive 421 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation When generating a linkable object file this directive can also be used to declare initialized data values Refer to the idata directive for more information While db is more common to use you may u
103. was specified For a list of supported switches refer to command line options Library Filename is Required All commands require a library filename All library filenames must end with lib 1994 2013 Microchip Technology Inc DS33014L page 301 Assembler Linker Librarian User s Guide 17 3 LIBRARY FILE ERRORS Library file processing errors are listed alphabetically below Could not build member memberName in library file filename The file is not a valid library file or it is corrupted Could not open library file filename for reading Verify that filename exists and can be read Could not open library file filename for writing Verify that if filename exists it is not read only Could not write archive magic string in library file filename The file may be corrupted Could not write member header for memberName in library file filename The file may be corrupted File filename is not a valid library file Library files must end with lib Library file filename has a missing member object file The file not a valid object file or it may be corrupted memberName is not a member of library filename memberName can not be extracted or deleted from a library unless it is a member of the library Symbol symName has multiple external definitions A symbol may only be defined once in a library file 17 4 COFF FILE ERRORS For a list of COFF File Errors see MPLINK
104. when generating absolute code 148 Expanded source line exceeded 200 characters The maximum length of a source line after define and macro parameter substitution is 200 characters Note that define substitution does not include comments but macro parameter substitution does 149 Directive only allowed when generating an object file Certain directives such as global and extern only have meaning when a linkable object file is generated They cannot be used when generating absolute code 150 Labels must be defined in a code or data section when making an object file When generating a linkable object file all data and code address labels must be defined inside a data or code section Symbols defined by the equ and set directives can be defined outside of a section 151 Operand contains unresolvable labels or is too complex When generating an object file operands must be of the form hi gh 1 ow relocatable address label offsef 1994 2013 Microchip Technology Inc DS33014L page 211 Assembler Linker Librarian User s Guide 152 Executable code and data must be defined in an appropriate section When generating a linkable object file all executable code and data declarations must be placed within appropriate sections 153 Page or Bank bits cannot be evaluated for the operand The operand of a pagesel banksel or bankisel directive must be a relocatable address label or a constant 154 Each object file section
105. will be programmed starting from address 200H Write your low priority interrupt service routine here Return from interrupt You can create a data or character table starting from any address in program memory In this case the address is 1000h db PICwithFLASH Eege O 1994 2013 Microchip Technology Inc DS33014L page 143 Assembler Linker Librarian User s Guide 4 52 page INSERT LISTING PAGE EJECT 4 52 1 Syntax page 4 52 2 Description and Usage Inserts a page eject into the listing file This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation 4 52 3 See Also list subtitle title 4 53 pagesel GENERATE PAGE SELECTING CODE PIC10 12 16 MCUs 4 53 1 Syntax pagesel label 4 53 2 Description An instruction to the linker to generate page selecting code to set the page bits to the page containing the designated 1abe1 Only one Zabel should be specified No operations can be performed on label 1abe1 must have been previously defined The linker will generate the appropriate page selecting code For 12 bit instruction width PIC10F some PIC12 PIC 16 devices the appropriate bit set clear instructions on the STATUS register will be generated For 14 bit instruction width most PIC12 PIC16 devices a combination of BSF and BCF commands will be used to adjust bits 3 and 4 of the PCLATH register
106. 00 Set flag bit 0 bit of DFLAG DTEMP and DFLAG are assigned one address location in RAM each by the linker For illustrative purposes suppose the locations selected by the linker are the general purpose registers GPRs 0x20 and 0x21 DFLO is assigned the value 0x00 and will be used as the name for pin 0 in the DFLAG register FIGURE 5 1 PIC16F877A REGISTER FILE MAP r Special 9p Function lt Registers ADCONO Ox1F P DTEMP 0x20 General DFLAG Y 0x21 Purpose Registers DFLO Ke Ox7F Bank 0 Bank 1 Bank 2 Bank 3 The directives udata and res are used in relocatable code to define multiple registers instead of equ For more on these directives see Section 4 62 udata Begin an Object File Uninitialized Data Section Section 4 57 res Reserve Memory Section 4 28 equ Define an Assembler Constant 5 3 5 Program Memory CODE Sections and Paging The code directive is used to specify sections of relocatable code For absolute code the org directive is used See Chapter 6 Relocatable Objects for more on the differences between relocatable and absolute code For more on these directives see Section 4 9 code Begin an Object File Code Section Section 4 51 org Set Program Origin If no code directive is used code generation will begin at address zero For this example code is used to specify code at 0x00 reset address 0x04 in
107. 004h 2005h Device ID 2006h Configuration Memory Space 2007h Reserved 2008h 20FFh EEPROM Data 2100h 21FFh Based on this map the CODEPAGE declarations are CODEPAGE NAME page0 START 0x0000 END 0x07FF CODEPAGE NAME pagel START 0x0800 END 0x0FFF CODEPAGE NAME page2 START 0x1000 END 0x17FF CODE PAGE NAME page3 START 0x1800 END 0x1FFF CODEPAGE NAME idlocs START 0x2000 END 0x2003 PROTECTED CODEPAGE NAME config START 0x2007 END 0x2007 PROTECTED CODEPAGE NAME eedata START 0x2100 END 0x21FF PROTECTED A LA O 1994 2013 Microchip Technology Inc DS33014L page 243 Assembler Linker Librarian User s Guide 11 6 LOGICAL SECTION DEFINITION Logical sections are used to specify which of the defined memory regions should be used for a portion of source code LINEARMEM is an example of a logical section To use logical sections define the section in the linker script file with the SECTION directive and then reference that name in the source file using that language s built in mechanism e g pragma section for MPLAB C18 The section directive defines a section by specifying its name and either the block of program memory in ROM or the block of data memory in RAM which contains the section SECTION NAME secName ROM memName RAM memName where secName is an ASCII string used to identify a section
108. 0F9 18F452 00000001 MPASM 03 70 Released SOURCE ASM 4 5 2004 15 40 00 PAGE 12 MEMORY USAGE MAP X Used Unused 0000 XXXX XXXXXXXXXX All other memory blocks unused Program Memory Bytes Used 14 Program Memory Bytes Free 32754 Errors S 0 Warnings 0 reported 0 suppressed Messages 0 reported 0 suppressed DS33014L page 56 1994 2013 Microchip Technology Inc MPASM Assembler Overview 1 7 4 Error File err The MPASM assembler by default generates an error file This file can be useful when debugging your code The IDE will display the error information in the Output window The format of the messages in the error file is type number file line description For example Error 113 C PROG ASM 7 Symbol not previously defined start The error file may contain any number of MPASM assembler errors warnings and messages For more on these see Chapter 8 Errors Warnings Messages and Limitations To prevent error file generation use the e or e option 1 7 5 Hex File Formats hex hxl hxh The MPASM assembler and MPLINK linker are capable of producing ASCII text hex files in different formats Format Name Format Type File Extension Use Intel Hex Format INHX8M hex 8 bit core device programmers Intel Split Hex Format INHX8S bal hxh odd even programmers Intel Hex 32 Format INHX32 hex 16 bit
109. 1 Linker Command Line Options MacOS sucia a oit etus 53 KEE 233 Macros in Linker Script 246 Dedi odiis ufus rdiet Nee 233 A LS coc ei 67 d sussssssssensssssssssnssssssssensssssssscssssenssssscsssscsesecsesceee 233 Map File Men ES 229 256 257 258 O EE 233 Maximum RAM Location eee 136 h Ese ee ed n 233 Maximum ROM Location RRR Sete EE 137 SS IO 233 ur E aa e EEE 136 U 233 MAXTOM ss 137 lick em ck in as taie vus ls Msn 233 ME INCLUDE 26e De 259 260 Mata idas dte ted 233 Memory Deen 233 Blees 116 DS33014L page 334 O 1994 2013 Microchip Technology Inc KEE 150 Memory Regions m 239 rcr cm id 138 Messages Assembler e eee 218 Mtl E 138 Mriemohics si dee ete Lex eue pe DEG poe ts 53 mp2cod Ultime ins 306 mp2hex Utiltly 1 niente 306 MPASM Assembler 22 38 MPASM Assembler Overview ssssss 49 mpasm exe eee 220 mpasmwin exe ceeesseeeeeee eem 33 34 MPASMX NO iia rip iia 17 18 49 61 MPLAB C18 C Compiler 21 24 37 40 MPLAB IDE Build Options Dialog MPASM Assembler Tab usus 38 MPASM C17 C18 Suite Tab 41 MPLAB C17 Tab 39 MPLAB C18 Tab 40 MPLINK LinkerTab eene 41 MPLIB Librarian Overview 297 MPLIB Object Librarian 21 37 41 SA
110. 11 2 Standard Linker Scripts 2 1 2 Eege ENEE ee EES 236 11 3 Linker Script Command Line Information 237 11 4 Linker Script Caveats E 238 11 5 Memory Region Definition sisside t e to aii 239 11 6 Logical Section Definition sessen e A ia 244 411 FS PACK DOMO eriep eneren aa naa e aa lite ta 244 11 8 Conditional Linker Statements ss 245 Chapter 12 Linker Processing 12 INTO UCI e ad 251 12 2 Linker Processing OVervieW a a a ia 251 12 3 Linker Allocation Algorithm issus 252 12 4 Relocation Example ii esee nnne aer aae assit ennt anne sinere nnns nnn tenens 253 12 5 Initialized Data ote Aia 254 12 6 Reserved Section Names saii iinde iii eiieeii deii endrer ii eddie de eiiean nnne enses 254 Chapter 13 Sample Applications 13 1 Introduction WEE 255 13 2 How to Build the Sample Applications su 255 13 3 Sample Application 1 Templates and Linker Scripts ooooooocccnnnncccccnnnnccccccnccnonanncnncnonanrn nc nnncnn nono 261 13 4 Sample Application 2 Placing Code and Setting Config Bits oooooonnninincnnnncccnnnnnnncocccccnccnancnno 264 13 5 Sample Application 3 Using a Boot Loader AAA 267 13 6 Sample Application 4 Configuring External Memory cocoocccccccnonocccccccononanncnncnonnncnncnnnnn no nnnnnnnnnnnno 278 Chapter 14 Errors Warnings and Common Problems TANTO LUCIO A A dio as 285 14 2 Linker Parse Errors niee triana ao tia 285 14 3 Linker Errors setny a E cts 287 14 4 Linker AVES LL LA EE ita ita intra cone EP
111. 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 14 Errors Warnings and Common Problems 14 4 INTRODUCTION Error messages and warning messages are produced by the MPLINK linker These messages always appear in the listing file directly above each line in which the error occurred Common problems and limitations of the linker tool are also listed here Topics covered in this chapter Linker Parse Errors Linker Errors Linker Warnings COFF File Errors Other Errors Warnings and Messages Common Problems 14 2 LINKER PARSE ERRORS MPLINK linker parse errors are listed alphabetically below Could not open cmdfile A linker script file could not be opened Check that the file exists is in the current search path and is readable Illegal filename for FILES in cmdfile line An object or library filename must end with o or 1ib respectively Illegal filename for INCLUDE in cmdfile line A linker script filename must end with 1kr Illegal lt libpath gt for LIBPATH in cmdfile line The libpath must be a semicolon delimited list of directories Enclose directory name which have embedded spaces in double quotes Illegal lt Ikrpath gt for LKRPATH in cmdfile line The krpath must be a semicolon delimited list of directories Enclose directory names which have embedded spaces in double quotes Invalid attributes for memory in cmdfile line
112. 2 1994 2013 Microchip Technology Inc Directives The same name incr is used in the main code where its value is set to 2 incr set 3 clrw addlw incr endm RST CODE 0x0 pagesel start goto start PGM CODE start clrw addlw incr add incr clrw addlw incr goto end Local incr is set to 3 in contrast to incr value of 2 in main code w register is set to zero w register is added to incr and result placed back in w register The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST Jumps to the location labelled restarti This is the beginning of the code section named PGM It is a relocatable code section since no absolute address is given along with directive CODE E W register set to zero W register is added with the value of incr which is now equal sbOos24 W register is added with the value of incr which is now equal to 3 value set locally in the macro add incr W register is set to zero again incr is added to W register and result placed in W register incr value is again 2 not affected by the value set in the macro Go to current line loop here O 1994 2013 Microchip Technology Inc DS33014L page 133 Assembler Linker Librarian User s Guide 4 45 macro DECLARE MACRO DEFINITION 4 45 4 Syntax label macro arg
113. 2 Description and Usage title text isa printable ASCII string enclosed in double quotes It must be 60 characters or less This directive establishes the text to be used in the top line of each page in the listing file This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation 4 61 3 See Also list subtitle 4 61 4 Simple Example title operational code rev 5 0 4 62 udata BEGIN AN OBJECT FILE UNINITIALIZED DATA SECTION 4 62 1 Syntax label udata RAM address 4 62 2 Description This directive declares the beginning of a section of uninitialized data If 1abe is not specified the section is named udata The starting address is initialized to the specified address or will be assigned at link time if no address is specified No code can be generated in this segment The res directive should be used to reserve space for data Note Two sections in the same source file are not permitted to have the same name 4 62 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation For relocatable code this directive is used to create a data RAM section For absolute code do not use this directive Use directives equ or cblock This directive cannot be used across banks 4 62 4 See Also extern global idata udata acs udata ovr udata
114. 207 Warning 207 will NOT display print for error level 2 errorlevel 1 group2 var2 res 1 RST CODE 0x0 start start pagesel goto INTRT CODE 0x4 pagesel goto service int service int Display print warnings and errors label of this directive is not at column 1 This will generate 7a warning number 207 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST Jumps to the location labelled start The code section named INTRT is placed at 0x4 The next two instructions are placed in code section INTRT Label service int is not defined Hence this generates error 113 O 1994 2013 Microchip Technology Inc DS33014L page 109 Assembler Linker Librarian User s Guide Error 113 will always display print regardless of error level PGM CODE start movwf groupl vari goto end This is the beginning of the code section named PGM It isa relocatable code section since no absolute address is given along with directive CODE Go to current line Be loop here 1994 2013 Microchip Technology Inc DS33014L page 110 Directives 4 31 exitm EXIT FROM A MACRO 4 31 1 Syntax exitm 4 31 2 Description Force immediate return from macro expansion during assembly The effect is the same as if an endm directive had been encountered 4 31 3 Usa
115. 3 Microchip Technology Inc Directives 4 51 7 PIC18 Application Example org This example shows the usage of the org directive Code generation begins at an address specified by org address The origin of a data table also can be specified by this directive A data table may be placed either in a program memory region or in an EE data memory region as in case of a PIC1X device with EE data FLASH include p18f452 inc org goto org goto org goto org Main goto org int_hi 0x0000 Main 0x0008 int hi 0x0018 int lo 0x0020 Main 0x0100 retfie org int lo 0x0200 retfie org ch_tb11 end 0x1000 Include standard header file for the selected devic The following code will be programmed in reset address 0 Jump to an address whose label is Main The following code will be programmed in high priority interrupt address 8 Jump to an address whose label is ME nit The following code will be programmed in low priority interrupt address 18h Jump to an address whose label is Ane Lot The following code section will be programmed starting from address 20H Write your main program here Loop back to Main ER The following code section will be programmed starting from address 100H Write your high priority interrupt service routine here Return from interrupt The following code section
116. 3014L page 313 Assembler Linker Librarian User s Guide TABLE A 3 12 BIT LITERAL AND CONTROL OPERATIONS Hex Mnemonic Description Function Ekk ANDLW kk AND literal and W kk AND WREG gt WREG 9kk CALL kk Call subroutine PC 1 TOS kk PC 004 CLRWDT Clear watchdog timer 0 gt WDT and Prescaler if assigned Akk GOTO kk Goto address k is nine bits kk gt PC 9 bits Dkk IORLW kk Incl OR literal and W kk OR WREG gt WREG Ckk MOVLW kk Move Literal to W kk gt WREG 002 OPTION Load OPTION Register WREG gt OPTION Register 8kk ETLW kk Return with literal in W kk gt WREG TOS gt PC 003 EP Go into Standby Mode 0 gt WDT stop oscillator 00r TRIS f Tristate port r WREG gt I O control reg r Fkk XORLW kk Exclusive OR literal and W kk XOR WREG gt WREG DS33014L page 314 1994 2013 Microchip Technology Inc Instruction Sets AA 14 BIT INSTRUCTION WIDTH INSTRUCTION SET Microchip s midrange 8 bit microcontroller family uses a 14 bit wide instruction set This instruction set consists of 36 instructions each a single 14 bit wide word Most instructions operate on a file register f and the working register WREG accumulator The result can be directed either to the file register or the WREG register or to both in the case of some instructions A few instructions operate solely on a file register BSF for examp
117. 34 See Also global idata udata udata acs udata ovr udata shr 4 33 5 Simple Example extern Function call Function 4 33 6 Application Example extern global The program main asm along with sub asm demonstrate the global and extern directives which make it possible to use symbols in modules other than where they are defined This allows a project to be split up into multiple files two in this example for code reuse PRRRKREKKR RK KK KEK KKK ERK KKK KK RK KKK KKK KER KEKE KKK EK KK KEK KEK KK KKK main asm pPRRRKEKKKR RK KR KEK KR KE kk koe ke KK KEK KK EKER KER koc ke ke ck ke hock koc kc ke KK KKK finclude p16f877a inc Include standard header file for the selected devic UDATA delay value res 1 GLOBAL delay value The variable delay value declared GLOBAL in this module is included in an EXTERN directive in the modul sub asm EXTERN delay The variable delay declared EXTERN in this module is declared GLOBAL in the module sub asm DS33014L page 114 O 1994 2013 Microchip Technology Inc Directives RST CODE 0x0 pagesel start goto start PGM CODE start movlw D 10 movwf delay value xorlw 0x80 call delay goto start end The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST Jumps to the location labelled start This is the beginning of
118. 37 or on line help file MPLAB IDE Documenation Information on the intergrated development environment MPLAB IDE may be found in MPLAB IDE User s Guide DS51519 Comprehensive user s guide On line help file The most up to date information on MPLAB IDE PIC MCU Data Sheets and Application Notes Data sheets contain information on device operation as well as electrical specifications Applications notes demonstrate how various PIC MCU s may be used Find both of these types of documents for your device on the Microchip website O 1994 2013 Microchip Technology Inc DS33014L page 13 Assembler Linker Librarian User s Guide THE MICROCHIP WEB SITE Microchip provides online support via our web site at www microchip com This web site is used as a means to make files and information easily available to customers Accessible by using your favorite Internet browser the web site contains the following information D Product Support Data sheets and errata application notes and sample programs design resources user s guides and hardware support documents latest software releases and archived software General Technical Support Frequently Asked Questions FAQs technical support requests online discussion groups Microchip consultant program member listing Business of Microchip Product selector and ordering guides latest Microchip press releases listing of seminars and events listings of Microchip sales offi
119. 4L page 282 1994 2013 Microchip Technology Inc Sample Applications 13 6 2 3 ASSEMBLER SOURCE CODE This is a simple code example showing the definition of the external memory SRAM address at 20000h and how to write a 16 bit value to two consecutive memory locations using the table pointer register and table write instruction If you are using MPLAB IDE v8 to run this example remember to enable external memory Configure gt External Memory to see this extra memory in the Program Memory window include lt p18F8722 inc gt Microprocessor mode a memory mode that supports external memory CONFIG MODE MP define SRAM BASE ADDRS 0x20000 Base addrs for external memory devic define SRAM END vectors code bra ma prog code main Example how to write movlw movwf movlw movwf movlw movwf movlw movwf tblwt movlw movwf tblwt END in upper TBLPT TBLPT low TBLPT O0xCC TABLA 0x55 TABLA ADDRS OxlFFFFF End addrs not required 0x55CC to first word location in external SRAM memory SRAM BASE ADDRS RU SRAM BASE ADDRS RH SRAM BASE ADDRS RL T Writes OxCC to byte location 0x020000 Increments table pointer to next location T Write 0x55 to byte location 0x020001 O 1994 2013 Microchip Technology Inc DS33014L page 283 Assembler Linker Librarian User s Guide NOTES DS33014L page 284 O
120. 4MHz or 1MIPS clock Turn off in config bits WDT for long simulations finclude p16F877A inc udata 0x20 DlyO res 1 Stores 4 bytes of data for the delay count Dlyl res 1 Dly0 is the least significant byte Dly2 res 1 while Dly3 is the most significant byte Dly3 res 1 Dly32 MACRO DLY goto 1 delay 2 cycles goto delay total of 4 cycles n Take the delay value argument from the macro precalculate the required 4 RAM values and load the The RAM values Dly3 though Dl1y0 BANKSEL Dly3 movlw DLY 1 amp H FF movwf Dl1yO movlw DLY 1 gt gt D 08 H FF movwf Dlyl movlw DLY 1 gt gt D 16 H FF Bytes are shifted and anded by the assembler to make user calculations easier movwf Dly2 movlw DLY 1 gt gt D 24 amp H FF Call DoDly32 to run the delay loop movwf Dly3 call DoD1y32 END End of Macro definition RST CODE 0x00 Reset Vector pagesel TestCode goto TestCode CODE Code starts here TestCode D1y32 D 50000 Max 4 billion runs D1y32 Macro l sec in this case nop ZERO STOPWATCH put breakpoint here EEE SSS A 9 vi a P M Qu M DS33014L page 180 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks goto TestCode Go back to top of program and run the delay again Subroutine called by the
121. 8 There is an assembler command line length limit of 255 characters 8 5 4 MPASM Assembler Versions before v3 30 MPLAB IDE v8 Assembler versions before v3 30 v3 2x and earlier have limitations based on the generation a COD file for debugging and the support of a command line version mpasm exe There is a 62 character length restriction for file and path names in the debug COD file produced by MPASM assembler This can cause problems when assembling single files with long file names and or path names Work arounds Shorten your file name or move your file into a directory closer to the root directory shorten the path name and try assembling your file again Create a Mapped drive for the long directory chain Use the linker with the assembler and not the assembler alone to generate your output There is no character restriction with MPLINK linker The command line version of the assembler mpasm exe has the following limitations File names are limited to 8 3 format config directive not supported e E gt R EL a a DS33014L page 220 O 1994 2013 Microchip Technology Inc S ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Part 2 MPLINK Object Linker Chapter 9 MPLINK Linker Overview eeeeeeeeeeeee eren nennen 223 Chapter 10 Linker Interfaces iei Leni eet a 231 Chapter 11 Linker Scripts scie cere nantes tes niet entente etes 235 Chapter 12 Linker
122. 8 16 bit instruction width instruction sets tables Field Description Register Files dest Destination either the WREG register or the specified register file location See d f Register file address f 8 bit 0x00 to OxFF f 12 bit 0x000 to OxFFF This is the source address 12 bit 0x000 to OxFFF This is the destination address r 0 1 or 2 for FSR number x Don t care CO or 1 The assembler will generate code with x 0 It is the recommended form of use for compatibility with all Microchip software tools Z Indirect addressing offset z T bitoffset value for indirect addressing of register files source z T bit offset value for indirect addressing of register files destination Literals k Literal field constant data or label k 4 bit kk 8 bit kkk 12 bit Offsets Increments Decrements n The relative address 2 s complement number for relative branch instructions or the direct address for Call Branch and Return instructions The mode of the TBLPTR register for the table read and table write instructions Only used with table read TBLRD and table write TBLWT instructions No Change to register Post Increment register Post Decrement register Pre Increment register Bits a RAM access bit a 0 RAM location in Access RAM BSR register is ignored a 1 RAM bank is specified by BSR register default b Bit address
123. 8 Only 4 38 2 Description For PIC12 and PIC16 devices idlocs sets the four ID locations to the hexadecimal value of expr For example if expr evaluates to 1AF the first lowest address ID location is zero the second is one the third is ten and the fourth is fifteen For PIC18 devices idlocs sets the two byte device ID at location addr to the hexadecimal value of expr Before this directive is used the processor must be declared through the command line the list directive or the processor directive 4 38 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is not commonly used but does provide an easy method of serializing devices _idlocs can be read by a programmer PIC18 devices can read this value at run time but PIC12 16 devices cannot 4 38 4 See Also config config list processor 4 38 5 Simple Example Example 1 PIC16 Devices include p16f877a inc Include standard header file for the selected device idlocs 0x1234 Sets device ID to 1234 O 1994 2013 Microchip Technology Inc DS33014L page 123 Assembler Linker Librarian User s Guide Example 2 PIC18 Devices Note The most significant nibble of idlocs is always 0x0 according to the programming specification finclude p18f452 inc Include standard header file for the
124. 800E800C80028016D 0042006801A9018901EA01280208026A02BF02C5 005200E002E80228036803BF03E803C8030804B8 0 0 0 0620008040804030443050306E807E807FF0839 07200FF08FF08190A57 00001FF 4 0 0 0 0 6 0 CO Ca ba at CH 1 7 5 2 INTEL SPLIT HEX FORMAT The split 8 bit file format produces two output files hx1 and hxh The format is the same as the normal 8 bit format except that the low bytes of the data word are stored in the hx1 file and the high bytes of the data word are stored in the hxh file and the addresses are divided by two This is used to program 16 bit words into pairs of 8 bit EPROMs one file for low byte one file for high byte EXAMPLE 1 4 INHX8S file name hxl 0A0000000000000000000000000000F6 1000190000284068A8E8C82868A989EA28086ABFAA 10002900E0E82868BFE8C8080808034303E8E8FFDO 03003900FFFF19AD 00000001FF file name hxh 0A0000000000000000000000000000F6 1000190000000000000000010101010102020202CA 100029000202030303030304040404050607070883 0 0 0 0 0 0 0300390008080AAA 00000001FF 1 7 5 3 INTEL HEX 32 FORMAT The extended 32 bit address hex format is similar to the hex 8 format except that the extended linear address record is output also to establish the upper 16 bits of the data address This is mainly used for 16 bit core devices since their addressable program memory exceeds 64 kbytes Each data record
125. 8502 7205 China Shanghai Tel 86 21 5407 5533 Fax 86 21 5407 5066 China Shenyang Tel 86 24 2334 2829 Fax 86 24 2334 2393 China Shenzhen Tel 86 755 8864 2200 Fax 86 755 8203 1760 China Wuhan Tel 86 27 5980 5300 Fax 86 27 5980 5118 China Xian Tel 86 29 8833 7252 Fax 86 29 8833 7256 China Xiamen Tel 86 592 2388138 Fax 86 592 2388130 China Zhuhai Tel 86 756 3210040 Fax 86 756 3210049 ASIA PACIFIC India Bangalore Tel 91 80 3090 4444 Fax 91 80 3090 4123 India New Delhi Tel 91 11 4160 8631 Fax 91 11 4160 8632 India Pune Tel 91 20 2566 1512 Fax 91 20 2566 1513 Japan Osaka Tel 81 6 6152 7160 Fax 81 6 6152 9310 Japan Tokyo Tel 81 3 6880 3770 Fax 81 3 6880 3771 Korea Daegu Tel 82 53 744 4301 Fax 82 53 744 4302 Korea Seoul Tel 82 2 554 7200 Fax 82 2 558 5932 or 82 2 558 5934 Malaysia Kuala Lumpur Tel 60 3 6201 9857 Fax 60 3 6201 9859 Malaysia Penang Tel 60 4 227 8870 Fax 60 4 227 4068 Philippines Manila Tel 63 2 634 9065 Fax 63 2 634 9069 Singapore Tel 65 6334 8870 Fax 65 6334 8850 Taiwan Hsin Chu Tel 886 3 5778 366 Fax 886 3 5770 955 Taiwan Kaohsiung Tel 886 7 213 7828 Fax 886 7 330 9305 Taiwan Taipei Tel 886 2 2508 8600 Fax 886 2 2508 0102 Thailand Bangkok Tel 66 2 694 1351 Fax 66 2 694 1350 EUROPE Austria Wels Tel 43 7242 2244 39 Fax 43 7242 2244 393 Denmark Copenhagen Tel
126. A subset of command line options may be specified in MPLAB X IDE Select a category and then set up compiler options For additional options see the MPLAB C Compiler for PIC18 MCUs User s Guide DS51288 also available on the Microchip website TABLE 1 10 MEMORY MODEL CATEGORY Option Description Command Line Code model Select a code program memory ROM model Choose from small mmodel x64K bytes or large gt 64K bytes Data model Select a data data memory RAM model Choose from large all RAM Omodel banks or small access RAM only Enable multi bank stack Select a stack model Choose from single bank or multiple bank Lmodel model DS33014L page 24 O 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB X IDE TABLE 1 11 GENERAL CATEGORY Option Description Command Line Treat char as unsigned Select to make char types unsigned 0 256 instead of the default k signed 128 to 127 Enable integer Select to enable integer promotions ISO mandated arithmetic oi promotions performed at int precision or greater Enable verbose output Display all compiler outputs verbose Default storage class Select the storage class either auto ANSI standard static ANSI scclass standard or overlay non extended mode Diagnostics level Select to display errors only errors and warnings or errors warnings wvalue and messages These will be shown
127. AM This A designation can be explicitly stated by the code but is not needed since the assembler will automatically locate variables in access memory if possible O 1994 2013 Microchip Technolog y Inc DS33014L page 157 Assembler Linker Librarian User s Guide 4 64 udata ovr BEGIN AN OBJECT FILE OVERLAYED UNINITIALIZED DATA SECTION 4 64 4 Syntax label udata_ovr RAM address 4 64 2 Description This directive declares the beginning of a section of overlayed uninitialized data If label is not specified the section is named udata ovr The starting address is initialized to the specified address or will be assigned at link time if no address is specified The space declared by this section is overlayed by all other udata ovr sections of the same name It is an ideal way of declaring temporary variables since it allows multiple variables to be declared at the same memory location No code can be generated in this segment The res directive should be used to reserve space for data Note Two sections in the same source file are not permitted to have the same name 4 64 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation This directive is similar to udata except that it allows you to reuse data space by overlaying one data area on another It is used for temporary variables as each data section may overwrite and
128. ART 0x0 END 0x29 CODE PAGE NAME boot START 0x2A END 0x7FF IFDEF _DEBUGCODESTART CODEPAGE NAME page START 0x800 END _CODEEND CODEPAGE AME debug START DEBUGCODESTART END CEND PROTECTED ELS CODEPAGE AME page START 0x800 END 0x1FFFF FI CODEPAGE NAME idlocs START 0x200000 END 0x200007 PROTECTED CODEPAGE NAME config START 0x300000 END 0x30000D PROTECTED CODEPAGE NAME devid START 0x3FFFFE END Ox3FFFFF PROTECTED CODEPAGE NAME eedata START 0xF00000 END 0xF003FF DS33014L page 268 O 1994 2013 Microchip Technology Inc Sample Applications Boot Loader Source Code The C compiler boot loader code can be composed of one or more aggregate relocatable C source files that are compiled and linked together during build time In this example the source code file uses the pragma code directive to instruct the linker to place the interrupt vectors at memory locations 0008h and 0018h A main function must be included as this is called from the C compiler startup code that is added during link process include lt p18cxxx h gt define RM_HIGH_INTE define RM_LOW_INTER pragma code HIGH I void high ISR void _asm goto RM HIG define RM RESET VECTOR 0x000800 define relocated vector addresses RRUPT VECTOR 0x000808 RUPT VECTOR 0x000818 VECTOR MAPPING FER IK AK A KC KC KC KC A KK KK Kk A ko k oko kk ke ke ke ke e e e x TERRUPT VECTOR 0x000008 H IN
129. B C18 linker script Since the C compiler application code in this example has been relocated to program memory address 0200h because of the boot loader it is necessary to change the code section entry socn definition in c018i c file as shown below and to add the c018i c source file to the project for recompiling and linking pragma code entry scn 0x000200 void entry void _asm goto startup endasm NENNEN 1994 2013 Microchip Technology Inc DS33014L page 271 Assembler Linker Librarian User s Guide Mixed Language Source Code The C compiler application code can be composed of one or more relocatable C source files that are compiled and linked together during build time In the code snippet shown below the source code file uses the pragma code directive to instruct the linker to place the relocated reset and interrupt vectors at the appropriate memory locations A main function must be included as this is called from the C compiler startup code that is added during the link process finclude lt p18cxxx h gt VECTOR MAPPING CKCKCKCkCkCkCkCkCkCk kk KC KC A KK RR RARA ke e XX pragma code HIGH INTERRUPT VECTOR 0x000208 void high ISR void ISR goes here pragma code LOW INTERRUPT VECTOR 0x000218 void low ISR void E ISR goes here APPLICATION CODE XX kk kk kk kCkCkCkCkCkCkCkCk RR KR RARA ke ex ke x d fpragma code void main void while 1 S
130. COD pagel_pgm goto end E 0x0 start start E 0x500 pagel_pgm pagel_pgm E 0x900 Include standard header file for the selected devic The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST Jumps to the location labelled start The code section named PGM1 is placed at 0x500 address bits 12 amp 11 of pagel pgm are copied to PCLATH 74 amp 3 respectively The code section named PGM1 is placed at 0x900 Label pagel pgm is located in this code section Go to current line loop here ILLE S H z J em 1994 2013 Microchip Technology Inc DS33014L page 145 Assembler Linker Librarian User s Guide 4 54 pageselw GENERATE PAGE SELECTING CODE USING WREG COMMANDS PIC10 12 16 MCUs 4 54 4 Syntax pageselw label 4 54 2 Description An instruction to the linker to generate page selecting code to set the page bits to the page containing the designated 1abe1 Only one label should be specified No operations can be performed on label label must have been previously defined The linker will generate the appropriate page selecting code For 12 bit instruction width PIC10F some PIC12 PIC 16 devices the appropriate bit set c
131. CODE E If config 0x0 is true assemble the mnemonics up to the directive else Set up PORTA as output If config 0x0 is false assemble the mnemonics up to the directive endif Set up PORTB as output Go to current line loop here DS33014L page 126 1994 2013 Microchip Technology Inc Directives 4 40 ifdef EXECUTE IF SYMBOL HAS BEEN DEFINED 4 40 1 Syntax Preferred ifdef label Supported ifdef label 4 40 2 Description If label has been previously defined usually by issuing a define directive or by setting the value on the MPASM assembler command line the conditional path is taken Assembly will continue until a matching else or endif directive is encountered 4 40 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is not an instruction but used to control how code is assembled not how it behaves at run time Use this directive for removing or adding code during debugging without the need to comment out large blocks of code 4 40 4 See Also define undefin ls ndif ifndef 4 40 5 Simple Example define testing 1 set testing on ifdef testing lt execute test code gt this path would be executed endif 4 40 6 Application Example ifdef include p16f877a inc define AlternateASM Comment out with if extra features
132. Cdf RRF f d Rotate right f register f E LU gt BEE 0 02df SUBWF f d Subtract W from f f Wod OEdf SWAPF f d Swap halves f f 0 3 e f 4 7 gt d 06df XORWF f d Exclusive OR W and f W XOR f gt d TABLE A 5 14 BIT BIT ORIENTED FILE REGISTER OPERATIONS Hex Mnemonic Description Function 4b BCF f b Bit clear f 0 gt f b 5bf BSF f b Bit set f 1 gt f b 6bf BTFSC f b Bit test skip if clear skip if f b O 7bf BTFSS f b Bit test skip if set skip if f b 1 1994 2013 Microchip Technology Inc DS33014L page 315 Assembler Linker Librarian User s Guide TABLE A 6 14 BIT LITERAL AND CONTROL OPERATIONS Hex Mnemonic Description Function 3Ekk ADDLW kk Add literal to W kk WREG gt WREG 39kk ANDLW kk AND literal and W kk AND WREG gt WREG 2 O kkk CALL kkk Call subroutine PC 1 TOS kk gt PC 0064 CLRWDT Clear watchdog timer 0 WDT and Prescaler if assigned 2 l kkk GOTO kkk Goto address k is nine bits kk gt PC 9 bits 38kk IORLW kk Incl OR literal and W kk OR WREG gt WREG 30kk MOVLW kk Move Literal to W kk gt WREG 0062 OPTIO Load OPTION register WREG gt OPTION Register 0009 RETFIE Return from Interrupt TOS gt PC 1 gt GIE 34kk RETLW kk Return with literal in W kk gt WREG TOS gt PC 0008 RETUR Return from subroutine TOS 5 PC 0063 SLEEP Go into Standby Mode 0 gt WDT st
133. Ckk RETLW kk Return with literal in WREG kk gt WREG 08kk SUBLW kk Subtract WREG from literal kk WREG gt WREG OAkk XORLW kk Exclusive OR literal with WREG WREG XOR kk gt WREG TABLE A 20 PIC18 MEMORY OPERATIONS Hex Mnemonic Description Function 0008 TBLRD Table Read Prog Mem TBLPTR gt TABLAT o 009 TBLRD Table Read with post increment Prog Mem TBLPTR gt TABLAT TBLPTR 1 gt TBLPTR 000A TBLRD Table Read with post decrement Prog Mem TBLPTR gt TABLAT TBLPTR 1 gt TBLPTR 000B TBLRD Table Read with pre increment TBLPTR 1 gt TBLPTR Prog Mem TBLPTR gt TABLAT 000 BLWT Table Write TABLAT gt Prog Mem TBLPTR 000D TBLWT Table Write with post increment TABLAT gt Prog Mem TBLPTR TBLPTR 1 gt TBLPTR 000E TBLWT Table Write with post decrement TABLAT gt Prog Mem TBLPTR TBLPTR 1 gt TBLPTR 000F TBLWT Table Write with pre increment TBLPTR 1 gt TBLPTR TABLAT gt Prog Mem TBLPTR 1994 2013 Microchip Technology Inc DS33014L page 327 Assembler Linker Librarian User s Guide A 9 PIC18 DEVICE EXTENDED INSTRUCTION SET Some PIC18 devices have an extended mode of operation for use with the MPLAB C18 compiler This mode will change the operation of some instructions listed in Section A 8 PIC18 Device Instruction Set and add the instructions listed in
134. DS33014L page 194 cblock 0x20 HistoryVector Must be initialized to 0 InputGain OutputGain Control loop gains Templ Temp2 Temp3 Used for internal calculations endc Relocatable Objects Equivalent Relocatable Code Use data declarations to define register locations and initialize idata HistoryVector db 0 Initialized to 0 udata InputGain res 1 Control loop gains OutputGain res 1 udata_ovr Templ res 1 Used for internal calculations Temp2 res 1 Temp3 res 1 If necessary the location of the section may be fixed in memory by supplying the optional address parameter If more than one of each section type is specified each section must have a unique name If a name is not provided the default section names are idata udata udata acs udata shr and udata ovr When defining initialized data in an idata section the directives db dw and data can be used db will define successive bytes of data memory dw and data will define successive words of data memory in low byte high byte order The following example shows how data will be initialized EXAMPLE 6 5 RELOCATABLE CODE LISTING 00001 IDATA 0000 01 02 03 00002 Bytes DB 1 2 3 0003 34 12 78 56 00003 Words DW 0x1234 0x5678 0007 41 42 43 00 00004 String DB ABC 0 6 6 CONFIGURATION BITS AND ID LOCATIONS Configuration bits and ID locations can still be defined in a relocatable object using the following directives Section 4 11 __ config
135. DecHex movwf ASCIIL swapf HexTemp F movf HexTemp W andlw OxOF get high nibble call DecHex movwf ASCITH return PRRRKRRKKKR RK RARE RARA RRA KKK RK RRE RR RRA RK KR KEK KK KERR KR KKK EK KERR KK KKK KK DecHex sublw 0x09 9 WREG btfss STATUS C is nibble Dec goto HexC no convert hex Dec movf HexTemp W convert DEC nibble to ASCII andlw OxOF addlw A o return HexC movf HexTemp W convert HEX nibble to ASCII andlw OxOF addlw A A 0x0A return DS33014L page 184 O 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks PRERKRKKKR RK KEK KKK RAR KKK KK RK KKK KEK RR RR RR K ERK KEK KEE ke ke RAR RRA koc kc ke ko eek ek global Hex2ASC ASCIIH ASCIIL END 5 8 OTHER SOURCES OF EXAMPLES Short examples of use for each directive are listed under each directive topic See Chapter 4 Directives Examples of use for multiple directives are available from the following sources readme asm Serial EEPROM Support Application Notes Technical Briefs Website http www microchip com Code Examples and Templates MPLAB X IDE MPLAB IDE v8 installation directory Website http www microchip com S_ _ _ _ SS ey 1994 2013 Microchip Technology Inc DS33014L page 185 Assembler L
136. E ADDRS movwf TBLPTRU movlw high SRAM BASE ADDRS movwf TBLPTRH movlw low SRAM BASE ADDRS movwf TBLPTRL To build the assembler sample application refer to Section 13 2 How to Build the Sample Applications 13 6 2 1 ASSEMBLER MEMORY MAP The figure below shows the memory mapping for the PIC18F8722 when used with the 1Mbyte external SRAM device Notice that the first 128K bytes of the external memory region is overlapped with the 128K bytes of internal program memory space and therefore cannot be accessed using the external memory bus Without any additional external memory address decoding the first 128K bytes of the SRAM are not accessible and therefore the first addressable location of SRAM is 20000h as used in this example SA4 TABLE 13 9 PROGRAM MEMORY MAP PIC18F8722 AND 1MB SRAM Program SRAM SA4 Memory Linker Script Section Source Code Section Address Address 0x000000 vectors Reset Interrupts vectors 0x000029 0x000000 0x00002A OxO1FFFF page On chip Memory prog Main Program OxO1FFFF gt 0x020000 0x020000 xsram External Memory SRAM BASE ADDRS OxOFFFFF OxOFFFFF SRAM END ADDRS 0x100000 Ox1FFFFF E IEOEEECECE__Q_Q M X 2 H
137. E EXAMPLES AND TIPS Example of Use Windows OS Suppose you wanted to create a library named dsp 1ib from three object modules named fft o fir o and iir o The following command line would produce the desired results mplib c dsp lib fft o fir o iir o To display the names of the object modules contained in a library file named dsp 1ib the following command line would be appropriate mplib t dsp lib Tips MPLIB librarian creates library files that may contain only a single external definition for any symbol Therefore if two object modules define the same external symbol the librarian will generate an error if both object modules are added to the same library file To minimize the code and data space which results from linking with a library file the library s member object modules should be as small as possible Creating object modules that contain only a single function can significantly reduce code space DS33014L page 300 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 17 Errors 17 1 INTRODUCTION MPLIB librarian detects the following sources of error and reports them Topics covered in this chapter Librarian Parse Errors Library File Errors COFF File Errors 17 2 LIBRARIAN PARSE ERRORS MPLIB librarian parse errors are listed alphabetically below Invalid Object Filename All object filenames must end with o Invalid Switch An unsupported switch
138. IDE project 16 3 MPLAB IDE V8 INTERFACE The MPLIB librarian may be used with MPLAB IDE to create a library file from project object files instead of an executable hex file With your project open in MPLAB IDE select Project gt Build Options gt Project In the Build Options dialog click on the MPASM C17 C18 Suite tab Click the radio button next to Build library target invoke MPLIB Then click OK Now when you build your project you will be building a library file 1994 2013 Microchip Technology Inc DS33014L page 299 Assembler Linker Librarian User s Guide 16 4 COMMAND LINE OPTIONS MPLIB librarian is invoked with the following syntax Windows OS mplib q ctdrx LIBRARY MEMBER Linux or Mac OS mplib q ctdrx LIBRARY MEMBER Options Option TM Lor Description Detail Create library creates a new LIBRARY with the listed MEMBER s Delete member deletes MEMBER s from the LIBRARY if no MEMBER is specified the LIBRARY is not altered Quiet mode no output is displayed Add replace member if MEMBER s exist in the LIBRARY then they are replaced otherwise MEMBER is appended to the end of the LIBRARY t List members prints a table showing the names of the members in the LIBRARY x Extract member if MEMBER s exist in the LIBRARY then they are extracted If no MEMBER is specified all members will be extracted 16 5 COMMAND LIN
139. IDE includes the MPASM Toolsuite which consists of the MPASM assembler MPLINK linker MPLIB librarian and other 8 bit utilities Also MPLAB IDE may be used with the C18 Toolsuite that consists of the MPLAB C18 Compiler and compiler versions of tools in the MPASM Toolsuite MPASM Toolsuite Installation In order to use the PIC language tools with MPLAB IDE you must first install MPLAB IDE The latest version of this free software is available at our website http www microchip com or from any sales office back cover When you install MPLAB IDE you will be installing the MPASM assembler the MPLINK object linker and the MPLIB object librarian as well The language tools will be installed by default in the directory Windows OS C Program Files Microchip MPLABX mpasmx Linux OS opt microchip mplabx mpasmx MacOS Applications microchip mplabx mpasmx The executables for each tool will be MPASM Assembler mpasmx exe e MPLINK Object Linker mplink exe e MPLIB Object Librarian mplib exe Other Utilities 1994 2013 Microchip Technology Inc DS33014L page 17 Assembler Linker Librarian User s Guide All device include inc files are also in this directory For more on these files see MPASM assembler documentation All device linker script 1kr files are in the LKR subdirectory For more on these files see MPLINK object linker documentation Template files are also included in the Template
140. IDE is discussed here Additionally the MPLAB C Compiler for PIC18 MCUs MPLAB C18 may be used with the above tools For more on this compiler see the Microchip website http www microchip com for additional information and documentation Topics covered in this chapter MPLAB IDE and Tools Installation MPLAB IDE Setup MPLAB IDE Projects Project Setup Project Example MPLAB IDE AND TOOLS INSTALLATION MPLAB IDE includes the MPASM Toolsuite which consists of the MPASM assembler MPLINK linker MPLIB librarian and other 8 bit utilities Also MPLAB IDE may be used with the C18 Toolsuite that consists of the MPLAB C18 C compiler and compiler versions of tools in the MPASM Toolsuite MPASM Toolsuite Installation In order to use the PIC language tools with MPLAB IDE you must first install MPLAB IDE The latest version of this free software is available at our website http www microchip com or from any sales office back cover When you install MPLAB IDE you will be installing the MPASM assembler the MPLINK object linker and the MPLIB object librarian as well The language tools will be installed by default in the directory C Program Files Microchip MPASM Suite The executables for each tool will be MPASM Assembler mpasmwin exe MPLINK Object Linker mplink exe MPLIB Object Librarian mplib exe Other Utilities All device include inc files are also in this directory For more on these f
141. IFDEF DEBUG STACK SIZE HE LSE FI FI 1344 Building the Application To build the application see Section 13 2 How to Build the Sample Applications Then to continue development with MPLAB IDE v8 Note MPLAB X IDE does not yet support External Memory views 1 Though the configuration bits in code set the microcontroller mode to external you must tell the IDE the range of external memory you wish to use Select Con figure gt External Memory In the dialog click Use External Memory and enter Ox1FFFFF as the Address Range End Click OK 2 Select Project gt Build All to build the application again 13 4 5 Absolute Method Instead of adding SECTION lines to the linker script you could add the absolute address in code i e INTHAND code 0x20000 However if you need to place additional code in the CODEPAGE eeprom area you would need to know the disassembly code length of the interrupt handler to determine the absolute address at which to place this additional code Also if you editthe interrupt handler code you would need to remember to change the address of the additional code Therefore it is usually easier not to place code absolutely but to allow the linker script to place code for you DS33014L page 266 1994 2013 Microchip Technology Inc Sample Applications 13 5 SAMPLE APPLICATION 3 USING A BOOT LOADER A boot loader is a special program that when programmed into t
142. IZED OPERATIONS Hex Mnemonic Description Function 31 0 nk ADDFSR n k Add Literal to FSRn FSR n k gt FSR n 001 0 mn MOVIW mm n Move INDFn to W with pre post inc dec INDFn gt W 001 0 nm n mm Move INDFn to W with pre post inc dec 3F O nk k n Move INDFn to W Indexed Indirect 001 1 mn MOVWI mm n Move W to INDFn with pre post inc dec W gt INDFn 001 1 nm n mm Move W to INDFn with pre post inc dec 3F 1 nk k n Move W to INDFn Indexed Indirect Operation in 14 bit extended instruction set but not 14 bit instruction set O 1994 2013 Microchip Technology Inc DS33014L page 319 Assembler Linker Librarian User s Guide Ap 12 BIT 14 BIT INSTRUCTION WIDTH PSEUDO INSTRUCTIONS The following pseudo instructions are applicable to both the 12 bit and 14 bit instruction word devices These pseudo instructions are alternative mnemonics for standard PIC1X instructions or are macros that generate one or more PIC1X instructions Use of these pseudo instructions is not recommended for new designs These are documented mainly for historical purposes TABLE A 15 12 BIT 14 BIT SPECIAL INSTRUCTION MNEMONICS Equivalent Mnemonic Description Operation s Status ADDCF fd Add Carry to File BTFSC 3 0 Z INCF frd ADDDCF f d Add Digit Carry to File BTFSC 3 1 Z INCF Bd B k Bra
143. In the Open dialog go to the build gt default gt production directory Select example Ist Click Open to view the linker listing file in an MPLAB X IDE editor window When MPASM assembler is used with MPLINK linker this listing file may be generated For more on this file see the Utilities doc umentation Section 18 3 Utilities Operation 6 Select File Open File In the Open dialog return to the project directory and then go to the dist default production directory Notice that there is only one hex file example hex This is the primary output file used by various debug tools Click Open to view the hex file in an MPLAB X IDE editor window For more on this file see the Utilities documentation Section 18 3 Utilities Operation For this example we used a multi file project which requires the use of the linker relocatable code But if you have a project with one assembly file you could use only the assembler absolute code The assembler is capable of generating its own list and hex file DS33014L page 30 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB X IDE Further Development Usually your application code will contain errors and not work the first time Therefore you will need a debug tool to help you develop your code Using the output files previously discussed several debug tools exist that work with MPLAB X IDE to help you do this You may choose from simulators in circuit e
144. Inc Instruction Sets TABLE A 16 PIC18 BYTE ORIENTED REGISTER OPERATIONS CONTINUED Hex Mnemonic Description Function 47 RLNCF f d a Rotate left f no carry register f Has 0 lt 33 RRCF f d a Rotate right f through Carry register f ix CR Tee 0 43f RRNCF f d a Rotate right f no carry register f yn 0 69f SETF f a Setf OxFF f 57 SUBFWB f d a Subtract f from WREG with WREG f C gt dest Borrow 5Ff SUBWF f d a Subtract WREG from f f WREG dest 5Bf SUBWFB f d a Subtract WREG from f with f WREG C dest Borrow 3Bf SWAPF f d a Swap nibbles of f f lt 3 0 gt dest lt 7 4 gt f 7 4 gt dest lt 3 0 gt 67 TSTFSZ f a Test f skip if 0 PC 4 gt PC if fZ0 else PC 2 gt PC 1Bf XORWF f d a Exclusive OR WREG with f WREG XOR f gt dest Assuming default bit values for d and a 1994 2013 Microchip Technology Inc DS33014L page 325 Assembler Linker Librarian User s Guide TABLE A 17 PIC18 BIT ORIENTED REGISTER OPERATIONS Hex Mnemonic Description Function 91f BCF f b a Bit Clear f 0 gt f lt b gt 81f BSF f b a Bit Setf 1 gt f lt b gt Blf BTFSC f b a Bittestf skip if clear if f lt b gt 0 PC 4 gt PC else PC 25 PC Alf BTFSS f b a Bit test f skip if set if f lt b gt 1 PC 4 PC else PC 2 gt PC 71 BTG f b a Bit
145. Initialized D ta 2 adn 254 padecer EE 144 Input Qutput Files SPACE Me An re Me 153 Assembler EE 52 O ne 153 EE 298 A 154 A ege 226 Listing File A 54 73 227 Instruction Operands En 191 KRPATH S snos metr tte adnata 237 Instruction Sets 311 oc HE 132 12 Bit Core 313 320 Logical Sections 244 12 Biv14 Bit COTES eene 320 IDA Soc b LL id ha Ad 69 191 14 Bit Goto t hte oit e ait PIC18 Device M Internet Address Microchip 14 Mac Support a eee potes 17 Interrupt Handling Macro PIC16 Example 109 117 142 172 177 Code Examples AA 204 PIC18 Example iiissiieiaiiii ene 118 143 Eds e e dt 104 L Eat ci ee E e 111 Exp nd sesta 113 Labels ir Her reed ere 53 No Expansion aes Sates EECH 140 LIBPATA Eo dto te 237 Text Substitution sess 202 Librarian Command Line Options USage ehe ie ice te depen 203 Kee 300 A NETTE 134 Le re re rar ere E Toe vue oL cota ER 300 Macro Directives 73 0 A E O Rea eR mM eS Rr a PEE 300 Definir 202 E 300 endi Ree en ut eL SESS I NL E eo Re 104 t wassssssssssnscsssssseusesssssscssssenessesssssussssscssssessssssssenes 300 exitm MH ERE 1 1 1 Xo REM RM Eme et nme 300 SANS tou E el she 113 Library File Ee 21 37 226 298 A nan mn an cadens 132 Library Path 257 258 MAGIO lens 134 Limitations noexpand A 140 Assembler rentangan nena n 220 Macro Language cies 201 LINEARMEM ses 239 Macro Syntax e ao eaea a aaea aa aeea ES 20
146. LINK linking of files to create an application use the following The exam ple is for Windows OS and is shown on two lines but you should type on one mplink pdevice u_macro sourcel o source2 o 1 c mcc18 lib m app map or for a modified linker script mplink modified lkr pdevice u macro sourcel o source2 o 1 ci mcci8 lib m app map where Option Description device The device representation modified lkr The modified linker script file macro A conditional macro eg CRUNTIME For more details see Section 11 8 Conditional Linker Statements sourcel o A C code object file source2 o An assembly code object file e mecl8 lib The library path only needed if the MPLAB C compiler for PIC18 MCUs was used as here to generate sourcel o from sourcel c app map The map file DEE o a rn O 1994 2013 Microchip Technology Inc DS33014L page 259 Assembler Linker Librarian User s Guide 13 23 2 EXAMPLE As an example consider Sample Application 3 C code mixed boot loader application To build an application on the command line 1 The listed Environment Variables need to be set as specified a PATH Make sure the executables can be found as per Table 13 3 b MCC INCLUDE Point to the c mcc18 h subdirectory 2 ForC code compilation use the following mcc18 p18F8722 c018i mod c mixed c 3 ForMPLINK linking of files to create an application use the following The ex
147. Macro D1y32 20 Tcy per loop DoD1y32 movlw H FF Start with 1 in W addwf Dl1yO F LSB decrement btfsc STATUS C was the carry flag set clrw If so 0 is put in W addwf Dlyl F Else we continue btfsc STATUS C clrw 0in W addwf Dly2 F btfsc STATUS C clrw 0 in W addwf Dly3 F btfsc STATUS C clrw 70 in W iorwf DlyO W Inclusive OR all variables iorwf Dlyl W together to s if we have reached iorwf Dly2 W 0 on all of them iorwf Dly3 W btfss STATUS Z Test if result of Inclusive OR s is 0 goto DoD1y32 It was NOT zero so continue counting retlw 0 It WAS zero so exit this subroutine END O 1994 2013 Microchip Technology Inc DS33014L page 181 Assembler Linker Librarian User s Guide 5 6 EXAMPLE OF SPI EMULATED IN FIRMWARE Directives highlighted in this example are e 3st define udata res global 5 6 1 Program Functional Description This program is used to emulate SPI function in firmware The application is written as relocatable code i e you must use both the assembler and linker to generate the executable The 1ist directive is used to define the processor and set listing file formatting The standard header file for the processor selected is included using tinclude SPI variables are declared using define Program registers are assigned using the udata and res directives Sections of code are created using the code statement External code is accessed using glob
148. Module File cof out MPLINK linker generates a COFF file which provides debugging information to MPLAB IDE v6 xx or later 9 7 5 Hex File Formats hex hxl hxh Both the MPASM assembler and the MPLINK linker can generate a hex file For more information on this format see Section 1 7 5 Hex File Formats hex hxl hxh For MPLINK linker mp2hex exe uses the COF file to generate the hex file To prevent hex file generation use the x or x option 9 7 6 Listing File Ist An MPLINK linker listing file provides a mapping of source code to object code It also provides a list of symbol values memory usage information and the number of errors warnings and messages generated This file may be viewed in MPLAB X IDE by 1 selecting File gt Open File to launch the Open dialog 2 selecting All Files from the Files of type drop down list 3 locating the desired list file 4 clicking on the list file name 5 clicking Open This file may be viewed in MPLAB IDE v8 by selecting File gt Open to launch the Open dialog selecting List files Ist from the Files of type drop down list locating the desired list file clicking on the list file name Clicking Open Both the MPASM assembler and the MPLINK linker can generate listing files For information on the MPASM assembler listing file see Section 1 7 3 Listing File Ist An alternative to a listing file would be to use the information in the D
149. NOWN MESSAGE An internal application error has occurred is the value of the last defined message plus 1 However it is not severe enough to keep your code from assembling i e it is a message not an error O 1994 2013 Microchip Technology Inc DS33014L page 219 Assembler Linker Librarian User s Guide 8 5 ASSEMBLER LIMITATIONS 8 5 1 General Limitations If a fully qualified path is specified only that path will be searched Otherwise the search order is 1 current working directory 2 source file directory and 3 MPASM assembler executable directory There is a source file line limit expanded of 200 characters MPLAB X IDE v1 40 and above has a parallel make facility and will attempt to compile multiple source files simultaneously if your PC has a multi core processor The assembler is not compatible with parallel make and you should disable parallel make when using the assembler by itself or as part of MPLAB C18 see Tools gt Options Embedded tab Project options sub tab D 8 5 2 Directive Limitations Do not use includes in macros if directive limits Maximum nesting depth 16 include directive limits Maximum nesting depth 5 Maximum number of files 255 macro directive limits Maximum nesting depth 16 while directive limits Maximum nesting depth 8 Maximum number of lines per loop 100 Maximum iterations 256 8 5 3 MPASM Assembler Versions before v5 39 MPLAB IDE v
150. O 1994 2013 Microchip Technology Inc DS33014L page 63 Assembler Linker Librarian User s Guide Option or Default Description 1 path On Enable Disable Set Path for list file 1 Enable 1 Enable 1 Disable 1 path Enable specify path See Section 1 7 3 Listing File Ist for more information m On Enable Disable macro expansion See Section 4 32 expand Expand Macro Listing for more information path Off Enable Disable Set Path for object file o Enable o Enable o Disable o path Enable specify path See Section 1 7 7 Object File o for more information o pprocessor type None Set the processor type where processor typeis a PIC1X MCU device e g PIC18F452 q I 1 Off Enable Disable quiet mode suppress screen output rradix Hex Defines default radix where radix is one of HEX DEC OCT See Section 4 43 list Listing Options or Section 4 56 radix Specify Default Radix for more information S On Show progress window while assembling For use only on the command line not within MPLAB IDE t 8 Set the size of tabs in the list file See Section 1 7 3 Listing File Ist for more information wvalue 0 Set message level where value is one of 0 1 2 0 all messages 1 errors and warnings 2 errors only See Section 4 48 messg Create User Defined Message for more information x
151. OM Data Byte union ic 96 4 18 define Define a Text Substitution Label ssseeeeee eem 98 4 19 dt Define Table PIC12 16 MCUS sise 100 4 20 dtm Define Table Extended PIC16 MCUs Only ss 100 4 21 dw Declare Data of One Word sise 101 4 22 else Begin Alternative Assembly Block to if Conditional sss 102 4 23 end End Program Block sise 103 4 24 ende End an Automatic Constant Block ssssseeeeenene em enne 103 4 25 endif End Conditional Assembly Block essen em enne 104 4 26 endm End a Macro Definition sise 104 4 27 endw End a while Loop iii 105 4 28 equ Define an Assembler Constant us 105 429 error ss e arn Error Message died deed oe lee bet en ttd ipee Boe deoa d 106 4 30 errorlevel Set Message Level nee eei ei Ene teet nine 108 4 31 exitm Exitfrom a Macro 2 12 28 eite oth set RE eere tubus t ERR Goes nt abate curent oda 111 4 32 expand Expand Macro Listing ss 113 4 33 extern Declare an Externally Defined Label AA 114 4 34 111 Specify Program Memory Fill Value is 116 4 35 gLobal Exporta Label ri te tee i eer P ERR ERE ENNEN 119 4 36 idata Begin an Object File Initialized Data Section sss 120 4 37 idata acs Begin an Object File Initialized Data Section in Access RAM PIC18 MCUs 122 4 38 idlocs Set Processor ID Locations 123 4 39
152. OPCOUNT EQU 0x20 7 loops needed to complete routine AARGBO EQU 0x21 MSB of result out AARGB1 EQU 0x22 operand A in 8 bits BARGBO EQU 0x23 LSB of result out operand B in 8 bits TestCode clrf AARGB1 Clear partial product before testing movlw D 11 movwf AARGBO moviw D 30 movwf BARGBO call UMULO808L After loading AARGBO and BARGBO call routine goto Result now in AARGBO AARGB1 where BO is MSB END UMULO808L moviw 0x08 movwf LOOPCOUNT movf AARGBO W LOOPUMO808A rrf BARGBO F btfsc STATUS C goto LUMO 80 8NAP decfsz LOOPCOUNT F goto LOOPUM0808A GEITE AARGBO retlw 0x00 LUMO 808NAP bef STATUS C goto LUMO 80 8NA DS33014L page 198 1994 2013 Microchip Technology Inc Relocatable Objects LOOPUMO808 rrf BARGBO E btfsc STATUS C addwf AARGBO E LUMO808NA PEE AARGBO E rrf AARGB1 F decfsz LOOPCOUNT F goto LOOPUMO808 retlw 0 END EXAMPLE 6 10 RELOCATABLE CODE CALLING FILE Input fixed point arguments in AARGBO and BARGBO Output product AARGxBARG in AARGBO AARGB1 Other comments truncated See AN617 PRRRKRREKKKR RK KR KEK KK KER KKK KKK RAR ko kc ke kc RK KKK KK KR kk koc ek ce hec kc kc kk ke ke kc ek KK KKK include pl6f877a inc Use any PIC16 device you like EXTERN UMULO808L AARGBO AARGB1 BARGBO Reset CODE 0x0 pagesel TestCod goto TestCode CODE TestCode banksel AARGB1 clrf AARGB1 Clear partial product bef
153. REG gt WREG Operation in 14 bit extended instruction set but not 14 bit instruction set TABLE A 12 14 BIT CONTROL OPERATIONS Hex Mnemonic Description Function 32kk BRA kk Relative branch PC kk gt PC 000B BRW Relative branch with W PC W PC 2 O kkk CALL kkk Call subroutine PC 1 TOS kkk PC 000A CALLW Call subroutine with W PC 1 TOS W gt PC 2 1 kkk GOTO kkk Goto address k is nine bits kk PC 9 bits 0009 RETFIE Return from Interrupt TOS gt PC 1 gt GIE 34kk RETLW kk Return with literal in W kk WREG TOS gt PC 0008 RETUR Return from subroutine TOS 5 PC Operation in 14 bit extended instruction set but not 14 bit instruction set DS33014L page 318 1994 2013 Microchip Technology Inc Instruction Sets TABLE A 13 14 BIT INHERENT OPERATIONS Hex Mnemonic Description Function 0064 CLRWDT Clear watchdog timer 0 gt WDT and Prescaler if assigned 0000 NOP No operation 0062 OPTION Load OPTION register WREG gt OPTION Register 0001 RESET Software device reset TOS gt PC 0063 SLEEP Go into Standby Mode 0 gt WDT stop oscillator 006r TRIS r Tristate port r WREG gt I O control reg r Operation in 14 bit extended instruction set but not 14 bit instruction set TABLE A 14 14 BIT C COMPILER OPTIM
154. RH F addwfc TBLPTRU F DS33014L page 192 O 1994 2013 Microchip Technology Inc Relocatable Objects stan_next_char 1 tblrd movff call decfsz bra movlw movwf btfss goto movlw movwf btfss goto return SE TABLAT temp wr d write ptr count F stan next char 1 A gut TXREG TXSTA TRMT 2 NEU TXREG TXSTA TRMT 2 send MOV character to LCD move next walt move pointer to next char data into TXREG line for data TX data into TXREG carriage return walt for data TX O 1994 2013 Microchip Technology Inc DS33014L page 193 Assembler Linker Librarian User s Guide 6 5 RAM ALLOCATION RAM space must be allocated in a data section Five types of data sections are available D Note The ability to use access overlaid or shared data varies by device Consult your device data sheet for more information udata Uninitialized data This is the most common type of data section Locations reserved in this section are nat initialized and can be accessed only by the labels defined in this section or by indirect accesses See 4 62 udata Begin an Object File Uninitialized Data Section udata_acs Uninitialized access data This data section is used for variables that will be placed in access RAM of PIC18 devices Access RAM is used as quick data access for specified instructions See 4 63 udata_acs Begin a
155. ROM A free demo student version of the C compiler may be obtained on the Microchip website The full C compiler must be purchased separately By default the tool executables are located as specified in the tables below TABLE 13 1 ASSEMBLY CODE EXECUTABLES AND PATHS MPLAB IDE V8 Executables Default Paths to Executables mpasmwin exe C Program Files Microchip MPASM Suite mplink exe C Program Files Microchip MPASM Suite TABLE 13 2 ASSEMBLY CODE EXECUTABLES AND PATHS MPLAB X IDE Executables Default Paths to Executables mpasmx exe C Program Files Microchip MPLABX mpasmx mplink exe C Program Files Microchip MPLABX mpasmx 1994 2013 Microchip Technology Inc DS33014L page 255 Assembler Linker Librarian User s Guide TABLE 13 3 C CODE EXECUTABLES AND PATHS Executables Default Paths to Executables mccl8 exe C mcci8 bin mpasmwin exe C mcci8 mpasm mplink exel2 C mcci8 bin Note 1 Future C compiler versions may be located at C Program Files Microchip MPLAB C18 2 Use mplink exe and not mplink exe The executable file _mplink exe is nota stand alone program To ensure the IDE sees the installed tools For MPLAB X IDE go to Tools gt Options Embedded button Build Tools tab to check the paths For MPLAB IDE v8 go to Project gt Set Language Tool Locations Microchip MPASM Toolsuite Executables and check the tool path
156. S directive Device not specified Use p option to specify a device If the device is not specified this error will be generated For Windows OS you specify the device by pdevice For Linux or Mac OS you specify the device by pdevice device represents the device name without a PIC or dsPIC preface as in 18F8722 instead of PIC18F8722 Duplicate definition of memory memName All CODEPAGE and DATABANK directives must have unique NAME attributes Duplicate definitions of SECTION secName Each SECTION directive must have unique NAME attributes Remove duplicate definitions 1994 2013 Microchip Technology Inc DS33014L page 287 Assembler Linker Librarian User s Guide File filename section secName performs a call to symbol symName which is not in the lower half of a page For 12 bit devices the program counter PC bit 8 is cleared in the CALL instruction or any modify PCL instruction Therefore all subroutine calls or computed jumps are limited to the first 256 locations of any program memory page 512 words long Inconsistent length definitions of SHAREBANK memName All SHAREBANK definitions which have the same NAME attribute must be of equal length Internal Coff output file is corrupt The linker cannot write to the COFF file Memory memName overlaps memory nemName All CODEPAGE blocks must specify unique memory ranges which do not overlap Similarly DATABANK and
157. SHAREBANK blocks may not overlap Mixing extended and non extended mode modules not allowed The linker cannot link a mixture of extended mode modules and non extended mode modules Extended and non extended memory modes apply to PIC18 devices When using MPASM to create object file modules extended memory mode is enabled disabled on the command line using the y or y option In the IDE select File gt Project Properties MPLAB X IDE or Project gt Build Options MPASM Assembly tab MPLAB IDE v8 and check uncheck the option Extended Mode When using MPLAB C18 to create object file modules extended memory mode is enabled disabled on the command line using the extended option In the IDE select File gt Project Properties MPLAB X IDE or Project gt Build Options MPLAB C18 tab MPLAB IDE v8 and check uncheck the option Extended Mode When using linker scripts those with the suffix e apply to extended mode use MPASM s CONFIG directive found in bar o cannot be used with either MPLAB C18 s pragma config directive or MPASM s CONFIG directive found in foo o This error message is issued when MPASM assemblers CONFIG directive is specified in a asm file e g bar asm and MPLAB C18 s pragma config directive is specified in a c file e g foo c Set configuration bits using either MPASM assembler s CONFIG directive or MPLAB C18 s pragma config directive Multiple map files declared filename1 filename2
158. ST is placed at program memory location 0x0 The next two instructions are placed in code section RST pagesel start Jumps to the location labelled goto start start El PGM CODI This is the beginning of the code section named PGM It is a relocatable code section since no absolute address is given along with directive CODE El start clrw goto Go to current line loop here El CODI This is a relocatable code nop Section since no address is Specified The section name will be by default code end DS33014L page 84 1994 2013 Microchip Technology Inc Directives 4 10 code pack BEGIN AN OBJECT FILE PACKED CODE SECTION PIC18 MCUs 4 10 4 Syntax label code pack ROM address 410 2 Description This directive declares the beginning of a section of program code or ROM data where a padding byte of zero is not appended to an odd number of bytes If 2abe1 is not specified the section is named code The starting address is initialized to ROM address or will be assigned at link time if no address is specified If ROM address is specified it must be word aligned If padded data is desired use db Note Two sections in a source file may not have the same name 410 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation This directive is commonly used when
159. STATUS register for an indirect access include p16f877a inc Include stan dard header file for the selected devic groupl udata 0x20 groupl data stored at locations starting at 0x20 IRP bit 0 groupl varl res 1 groupl varl located at 0x20 groupl var2 res 1 groupl var2 located at 0x21 group2 udata 0x120 group2 data stored at locations starting at 0x120 IRP bit 1 group2 varl res 1 group2 varl located at 0x120 group2 var2 res 1 group2 var2 located at 0x121 RST CODE 0x0 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST pagesel start Jumps to the location labelled goto start start PGM CODE This is the beginning of the code section named PGM It is a relocatable code section Since no absolute address is given along with directive CODE start movlw 0x20 This part of the code addresses movwf FSR variables groupl varl amp bankisel groupl varli groupl var2 indirectly clrf INDF incf FSR F clrf INDF movwf FSR bankisel group2 varl clrf INDF incf FSR F clrf INDF goto Go to current line loop here end DS33014L page 78 1994 2013 Microchip Technology Inc Directives 4 6 7 Application Example 2 bankisel include p16f877a inc Include standard header file for the selected devic bankisel EEADR This register is at location 100h in banks 2 or 3 so the IRP b
160. Set Processor Configuration Bits Section 4 12 config Set Processor Configuration Bits PIC18 MCUs Section 4 38 idlocs Set Processor ID Locations Only one linked module can specify these directives They should be used prior to declaring any code sections After using these directives the current section is undefined O 1994 2013 Microchip Technology Inc DS33014L page 195 Assembler Linker Librarian User s Guide 6 7 ACCESSING LABELS FROM OTHER MODULES Labels that are defined in one module for use in other modules must be exported using the global directive see 4 35 global Export a Label Modules that use these labels must use the extern directive see 4 33 extern Declare an Externally Defined Label to declare the existence of these labels An example of using the global and extern directives is shown below EXAMPLE 6 6 RELOCATABLE CODE DEFINING MODULE udata InputGain res 1 OutputGain res 1 global InputGain OutputGain code Filter global Filter Filter code EXAMPLE 6 7 RELOCATABLE CODE REFERENCING MODULE extern InputGain OutputGain Filter udata Reading res 1 code movlw GAIN1 movwf InputGain movlw GAIN2 movwf OutputGain movf Reading W call Filter EE EE EE DS33014L page 196 O 1994 2013 Microchip Technology Inc Relocatable Objects 6 8 PAGING AND BANKING ISSUES In many cases RAM allocation will span multiple banks and executable code will span multiple pa
161. TERRUPT VECTOR endasm pragma code LOW INTERRUPT VECTOR 0x000018 void low ISR void I asm goto RM LOW INTERRUPT VECTOR _endasm BOOT LOADER CODE pragma code void main void Check Bootload if PORTBbits RB4 AA Mode Entry Condition 1 If not pressed User Mod _asm goto RM RESET VECTOR endasm Else continue with bootloader code here pragma code user or END OF BOOT LOAD RM RESET VECTOR This address defined as 0x800 above can be defined in header fil ER KCKCKCKCKCKCkCkCk Ck Ck k Ck k kCk Ck k kk kc k kc k I I ke ke ke x kx O 1994 2013 Microchip Technology Inc DS33014L page 269 Assembler Linker Librarian User s Guide 13 5 1 3 EXAMPLE 2 C COMPILER APPLICATION This example shows a section of linker script modified to accomodate the application code Application Linker Script The boot loader linker script file may be used when building the C compiler application source code files The linker will use this configuration to link the compiled source code into the pagel program memory region above the protected boot loader region Application Source Code The C compiler application code can be composed of one or more aggregate relocatable C source files that are compiled and linked together during build time In the code snippet shown below the source code file uses the
162. Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 13 Sample Applications 13 4 INTRODUCTION You can learn the basics of how to use MPLINK linker from the four sample applications listed below These sample applications can be used as templates for your own application How to Build the Sample Applications Sample Application 1 Templates and Linker Scripts How to find and use template files When to modify the generic linker script file e Sample Application 2 Placing Code and Setting Config Bits How to place program code in different memory regions How to place data tables in ROM memory How to set configuration bits in C Sample Application 3 Using a Boot Loader How to partition memory for a boot loader How to compile code that will be loaded into external RAM and executed e Sample Application 4 Configuring External Memory How to create new linker script memory section How to declare external memory through pragma code directive How to access external memories using C pointers 13 2 HOW TO BUILD THE SAMPLE APPLICATIONS To build the sample applications you will need the MPASM assembler the MPLINK linker and for some sample applications the MPLAB C compiler for PIC18 MCUs formerly MPLAB C18 installed on your PC The assembler and linker are automatically installed with MPLAB X IDE and MPLAB IDE v8 or may be acquired separately on the Microchip website or the C compiler CD
163. Text Strings A Gla eles 65 3 3 Reserved Words and Section Names ss 67 3 4 Numeric Constants and Radix sise 67 3 5 Arithmetic Operators and Precedence iii 69 Chapter 4 Directives AA Introduction sister AA Deedee be ev ces M oe ese sd eee handed Merl Baden at ee eet 71 4 2 Directives Dy Ty POs iin ir eee ede Ee De S EHE Herb ia datado 71 4 3 access ovr Begin an Object File Overlay Section in Access RAM PIC18 MCUs 74 4 4 badram Identify Unimplemented RAM ss 75 4 5 badrom Identify Unimplemented ROM nennen 76 4 6 bankisel Generate Indirect Bank Selecting Code PIC12 16 MCUS eee 77 4 7 banksel Generate Bank Selecting Code AAA 80 4 8 cblock Define a Block of Constants sss eene nennen enne 82 4 9 code Begin an Object File Code Section ss 84 4 10 code pack Begin an Object File Packed Code Section PIC18 MCUs ssessss 85 4 11 config Set Processor Configuration Bits sssssssssssee ee 86 4 12 config Set Processor Configuration Bits PIC18 MCUS see em 88 4 13 constant Declare Symbol Constant ss 89 4 14 da Store Strings in Program Memory PIC12 16 MCUS sseee mem 90 4 15 data Create Numeric and Text Data ie 92 4 16 ab Declare Data of One Byte serene oi uns 94 1994 2013 Microchip Technology Inc DS33014L page 3 Assembler Linker Librarian User s Guide 4 17 de Declare EEPR
164. To COD Converter Warnings COD File Errors 19 2 HEX FILE ERRORS Selected hex format does not support byte addresses above 64kb use INHX32 format Your code addresses more than 64 Kbytes of program memory but your selected hex format cannot support this Switch to INHX32 format Could not open hex file filename for writing The hex file was never created due to other errors or an existing hex file is write protected 19 3 COFF TO COD CONVERSION ERRORS Source file filename name exceeds file format maximum of 63 characters The COD file name including the path has a 63 character limit Coff file filename must contain at least one code or romdata section In order to convert a COFF file to a COD file the COFF file must have either a code or a romdata section Could not open list file filename for writing Verify that if filename exists and that it is not a read only file 19 4 COFF TO COD CONVERTER WARNINGS Could not open source file filename This file will not be present in the list file The referenced source file could not be opened This can happen if an input object library module was built on a machine with a different directory structure If Source level debugging for the file is desired rebuild the object or library on the current machine 1994 2013 Microchip Technology Inc DS33014L page 307 Assembler Linker Librarian User s Guide 19 5 COD FILE ERRORS All the
165. Warnings and Common Problems symbol symName out of range of relative branch instruction A relative branch instruction had symName as its target but a 2 s compliment encoding of the offset to symName wouldn t fit in the limited number of instruction bits used for the target of a branch instruction The _CONFIG_DECL macro can only be specified in one module Found in foo o previously found in bar o This error is issued when MPLAB C18 s CONFIG DECL macro is specified in two separate c files e g foo c and bar c Set configuration bits by using the CONFIG DECL macro in only one c file The CONFIG DECL macro found in foo o cannot be used with MPASM s __CONFIG directive found in bar o This error is issued when MPLAB C18 s CONFIG DECL macro is used in a c file e g foo c and MPASM assemblers _ CONFIG directive is used in a asm file e g bar asm Set configuration bits using either the CONFIG DECL macro from MPLAB C18 or the CONFIG directive in MPASM assembler The CONFIG DECL macro found in foo o cannot be used with either MPLAB C18 s pragma config directive or MPASM s CONFIG directive found in bar o This error is issued when MPLAB C18 s CONFIG DECL macro is used in a c file e g foo c with either MPLAB C18 s pragma config directive in a second c file e g bar c or MPASM assemblers CONFIG directive in a asm file e g bar asm Set configuration bits by using only one of
166. a Program Memory location WREG Working register accumulator Named Bits C DC Z OV N ALU Status bits Carry Digit Carry Zero Overflow Negative TO Time out bit PD Power down bit GIE Global Interrupt Enable bit s Named Device Features PC Program Counter TOS Top of Stack WDT Watchdog Timer Misc Descriptors o Contents gt e Assigned to lt gt Register bit field EE ERE Ro ER ee DS33014L page 312 O 1994 2013 Microchip Technology Inc Instruction Sets AA 12 BIT INSTRUCTION WIDTH INSTRUCTION SET Microchip s baseline 8 bit microcontroller family uses a 12 bit wide instruction set All instructions execute in a single instruction cycle unless otherwise noted Any unused opcode is executed as a NOP The instruction set is grouped into the following categories byte oriented file register operations bit oriented file register operations and core literal and control operations Instructions Additionally instructions that apply to both 12 bit and 14 bit devices are shown in Section A 6 12 Bit 14 Bit Instruction Width Pseudo Instructions Instruction opcode is show in hex by making certain assumptions either listed in the key or as a footnote For more information on the opcode bit values for each instruction as well as the number of cycles per instruction status bits affected and complete instruction details see the relevant device data sheet
167. a boot loader Mixed Language Linker Script The partial C compiler linker script file shown below demonstrates the required modifications when building the mixed assembly boot loader C code application The linker will use this configuration to link the compiled source code into the user program memory region above the protected boot loader In this linker script example the C compiler start up file c018i 0 has been remarked out preventing the linker from linking this object file to the project Instead it will use the modified file in the next section IFDEF _CRUNTIME IFDEF EXTENDEDMODE FILES c018i e o FILES clib e lib FILES p18f8722 e lib ELSE FILES G 181 5 lt Note this line to be ignored by linker FILES clib lib FILES p18f8722 1ib TFI TFI CODEPAGE NAME vectors START 0x0 END 0x29 CODE PAGE NAME boot START 0x2A END 0x1FF IFDEF _DEBUGCODESTART CODEPAGE NAME page START 0x200 END _CODEEND CODEPAGE NAME debug START _DEBUGCODESTART END _CEND PROTECTED HELS CODEPAGE NAME page START 0x200 END 0x1FFFF TFI Mixed Language c018i c Modifications For a typical C compiler application the c018i c startup code normally specifies program memory location 0000h as the entry section and is linked into the project by the linker when specified in the MPLA
168. a matching quote mark is found the string ends If none is found before the end of the line the string will end at the end of the line While there is no direct provision for continuation onto a second line it is generally no problem to use a second dw directive for the next line The dw directive will store the entire string into successive words If a string has an odd number of characters bytes the dw and data directives will pad the end of the string with one byte of zero 00 If a string is used as a literal operand it must be exactly one character long or an error will occur 1994 2013 Microchip Technology Inc DS33014L page 65 Assembler Linker Librarian User s Guide 3 2 1 Escape Characters The assembler accepts the ANSI C escape sequences to represent certain special control characters TABLE 3 1 ANSI C ESCAPE SEQUENCES Escape Description Hex Character Value a Bell alert character 07 b Backspace character 08 yf Form feed character 0C in New line character 0A Nr Carriage return character OD NG Horizontal tab character 09 v Vertical tab character OB Backslash 5C Question mark character 3F ME Single quote apostrophe 27 Kee Double quote character 22 000 Octal number zero Octal digit Octal digit xHH Hexadecimal number 3 2 2 Code Examples See the examples below for the object code generated by different statement
169. al 5 6 2 Commented Code Listing PRERRRRRRAREA ARA RARA RARA RARE RRE RRA RR RRA ke KK KEK kk Sek koe heck ke hock ke ke kc ke ko e ek ek Emulates SPI in firmware Place byte in Buffer call SPI Out sends MSB first PRKKKEK KE KA AK koe ke koe KKK hock koe ko kc ke KK KKK RK KR hc kk ko ek ce ec khe kc kk ko kc ke ko e ek ek LIST P 18F4520 define processor finclude lt P18F4520 INC gt include file list c 132 n 0 7132 col no paging PRRRKEKKKR EK KR KK KKK ERK KKK ck heck ko kk kc ke kc heck khe EKER ko ke ke koe kc ko ke hock ke heck ke KKK KK define Clk LATB 0 SPI clock output define Dat LATB 1 SPI data output define Bus LATB 2 busy indicator PRKKKEK KE HAE HA KK koc ke KKK KKK RK KKK ERK kc KKK KEK koc kk koc ek che ke kk heck ke ke kc ck ko e ek ek Variable definitions udata Buffer res 1 SPI transmit data Counter res 1 SPI transmit bit counter DelayCtr res 1 PRRRKRREKKKR EK KKK KKK KEE KKK KK KKK KK KER KKK ke ko ke KK khe hock kk ko ke ke koe kc ko ke hock ck ko ke kc ke KK ek ek code SPI Out clrf Counter init bit counter bsf Counter 7 bcf Clk clear clock bcf Dat Clear data out bsf Bus indicate busy DS33014L page 182 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks Lup movf andwf bt ss bsf bsf bcf bcf rrncf btfss bra bcf return Counter W get mask Buffer W test selected bit STATUS Z was result zero Dat set
170. al force immediate return from macro during assembly If num2 gt 255 decimal force immediate return from macro during assembly Load W register with a literal value assigned to the label P numl Load W register to an address location assigned to the label result Se 5 ER Load W register with a literal value assigned to the label num2 Add W register with the memory location addressed by result and load the result back to result End of add MACRO ER My main program starts at 10H The label start is assigned an address 10H Call add MACRO with decimal numbers 100 and 256 assigned to numl and num2 labels respactively EXTIM directive in macro will force return Remember means decimal not floating point DS33014L page 112 O 1994 2013 Microchip Technology Inc Directives 4 32 expand EXPAND MACRO LISTING 4 32 1 Syntax expand 4 32 2 Description Expand all macros in the listing file This is the default behavior This directive is roughly equivalent to the m or m MPASM assembler command line option but may be disabled by the occurrence of a subsequent noexpand 4 32 3 Usage This directive is used in the following types of code absolute For information on types of code see Section 1 6 Assembler Operation This directive may be useful when exploring a small range of code with many macros in it
171. allocated into these regions if an absolute address is specified for the section or if the section is assigned to the region using a SECTION directive in the linker script file 11 5 4 Defining RAM Memory Regions The following directives are used for variable data in internal RAM The formats for these directives are as follows Banked Registers DATABANK NAME memName START addr END addr PROTECTED Unbanked Registers SHAREBANK NAME memName START addr END addr PROTECTED Access Registers PIC18 devices only ACCESSBANK NAME memName START addr END addr PROTECTED Linear Data Memory PIC16F1xxx devices only LINEARMEM NAME linear0 START addr END addr PROTECTED DATABANK NAME memName START addr END addr SHADOWED linear0 addr where memName Any ASCII string used to identify an area in RAM addr A decimal e g 30 or hexadecimal e g OXFF number specifying an address Pe An optional keyword PROTECTED A keyword that indicates a region of memory that only can be used when specifically identified in the source code The linker will not use the protected area SHADOWED A keyword that maps a data memory range to the specified linear data region 1inName at an address in that region 1994 2013 Microchip Technology Inc DS33014L page 239 Assembler Link
172. am ple is for Windows OS and is shown on two lines but you should type on one mplink mixed lkr pdevice u CRUNTIME c018i mod o mixed o 1 c mecl18 lib m mixed map If you want to link for debug mode or PIC18 extended mode see Section 11 8 Conditional Linker Statements DS33014L page 260 O 1994 2013 Microchip Technology Inc Sample Applications 13 3 SAMPLE APPLICATION 1 TEMPLATES AND LINKER SCRIPTS In the MPLAB X IDE or MPLAB IDE v8 installation assembly source code templates and generic linker script files are provided for most devices supported by the IDE The source code templates give you a starting point from which to begin coding The generic linker scripts are used automatically by the linker to simplify application development Or you may modify a linker script and then manually add it on the linker command line or to the project This first general example will discuss templates and linker scripts 13 3 1 Locating Templates and Linker Script Files For MPLAB X IDE or MPLAB IDE v8 installed in the default location source code templates may be found at C Program Files Microchip MPASM Suite Template in the following subdirectories Code Contains absolute assembly code examples by device Object Contains relocatable assembly code examples by device The relocatable source code template 18F8722TMPO ASM for the PIC18F8722 may be found in the Object directory This template provides oscillator setup ex
173. am 0x000002 cinit romdata 0x000021 program 0x000004 code code 0x000023 program 0x000026 udata udata 0x000020 data 0x000005 The second table Program Memory Usage lists program memory addresses that were used and provides a total usage statistic For example Program Memory Usage Start End 0x000000 0x000005 0x00002a 0x00002b 0x0000bc 0x001174 0x001176 0x002895 10209 out of 32786 program addresses used program memory utilization is 31 The third table in the map file Symbols Sorted by Name provides information about the symbols in the output module The table is sorted by the symbol name and includes the address of the symbol whether the symbol resides in program or data memory whether the symbol has external or static linkage and the name of the file where defined The following table is an example of the symbol table sorted by symbol name in a map file Symbols Sorted by Name Name Address Location Storage File call m 0x000026 program static C PROGRA 1 MPLAB ASMFOO sampobj asm loop 0x00002e program static C MPASM assemblerV2 MUL8X8 AS main 0x000024 program static C PROGRA 1 MPLAB ASMFOO sampobj asm mpy 0x000028 program extern C MPASM assemblerV2 MUL8X8 AS start 0x000023 program static C PROGRA 1 MPLAB ASMFOO sampobj asm H byte 0x000022 data extern C MPASM assemblerV2 MUL8X8 AS L byte 0x000023 data extern C MPASM assemblerV2 MUL8X8 AS count 0x000024 data static C MPASM assemblerV21MUL8X8 AS mulcnd 0x000020 data
174. ample variable and EEPROM setup reset and interrupt handling routines and a section main for application code For MPLAB X IDE installed in the default location the generic linker script files may be found at C Program Files Microchip MPASM Suite LKR The generic linker script file for the PIC18F8722 would be 18 8722 g lkr This file defines initialization files program code sections GPR sections and access memory sections These definitions are grouped based on debugger or programmer usage and regular or extended memory usage Program memory sections specified by the template code and linker script are compared below TABLE 13 4 PROGRAM MEMORY MAP PIC18F8722 Program E Memory Linker Script Section Template Source Code Section Not debug or extended Address 0x0000 page ROM code space RESET_VECTOR Reset vector 0x0007 0x0008 HI_INT_VECTOR High priority interrupt 0x0017 vector 0x0018 LOW_INT_VECTOR Low priority interrupt vector 0x0019 High Int High priority interrupt handler OxO1FFFF Low Int Low priority interrupt handler Main Main application code 0x200000 idlocs ID locations 0x200007 0x300000 config Configuration bits CONFIG Configuration settings 0x30000D Ox3FFFFE devid Device ID Ox3FFFFF OxF00000 eedata EEPROM data DATA EEPROM Data EEPROM OxFOO3FF PPP EpC ECC JyNypanc MM H
175. andler AZ 85224 6199 Tel 480 792 7200 Fax 480 792 7277 Technical Support http www microchip com support Web Address www microchip com Atlanta Duluth GA Tel 678 957 9614 Fax 678 957 1455 Boston Westborough MA Tel 774 760 0087 Fax 774 760 0088 Chicago Itasca IL Tel 630 285 0071 Fax 630 285 0075 Cleveland Independence OH Tel 216 447 0464 Fax 216 447 0643 Dallas Addison TX Tel 972 818 7423 Fax 972 818 2924 Detroit Farmington Hills MI Tel 248 538 2250 Fax 248 538 2260 Indianapolis Noblesville IN Tel 317 773 8323 Fax 317 773 5453 Los Angeles Mission Viejo CA Tel 949 462 9523 Fax 949 462 9608 Santa Clara Santa Clara CA Tel 408 961 6444 Fax 408 961 6445 Toronto Mississauga Ontario Canada Tel 905 673 0699 Fax 905 673 6509 ASIA PACIFIC Asia Pacific Office Suites 3707 14 37th Floor Tower 6 The Gateway Harbour City Kowloon Hong Kong Tel 852 2401 1200 Fax 852 2401 3431 Australia Sydney Tel 61 2 9868 6733 Fax 61 2 9868 6755 China Beijing Tel 86 10 8569 7000 Fax 86 10 8528 2104 China Chengdu Tel 86 28 8665 5511 Fax 86 28 8665 7889 China Chongqing Tel 86 23 8980 9588 Fax 86 23 8980 9500 China Hangzhou Tel 86 571 2819 3187 Fax 86 571 2819 3189 China Hong Kong SAR Tel 852 2943 5100 Fax 852 2401 3431 China Nanjing Tel 86 25 8473 2460 Fax 86 25 8473 2470 China Qingdao Tel 86 532 8502 7355 Fax 86 532
176. ange in your label MyLabel is not the same as Mylabel unless case sensitivity is turned off it is on by default Additionally goto MyLabel will never locate the code at My1ab1 or Mylable Check for these sorts of mistakes first As a general rule put your include files at the top of each file If this seems to cluttered you may include files within other include files 114 Divide by zero Division by zero encountered during an expression evaluation 115 Duplicate label A label was declared as a constant e g with the equ or cblock directive in more than one location 116 Address label duplicated or different in second pass The same label was used in two locations Alternately the label was used only once but evaluated to a different location on the second pass This often happens when users try to write page bit setting macros that generate different numbers of instructions based on the destination 117 Address wrapped around 0 For PIC12 16 devices the location counter can only advance to OxFFFF After that it wraps back to 0 Error 117 is followed by error 118 118 Overwriting previous address contents Code was previously generated for this address 119 Code too fragmented The code is broken into too many pieces This error is very rare and will only occur in source code that references addresses above 32K including configuration bits 120 Call or jump not allowed at this address A call or jump cannot be ma
177. arg 4 45 2 Description A macro is a sequence of instructions that can be inserted in the assembly source code by using a single macro call The macro must first be defined then it can be referred to in subsequent source code Arguments are read in from the source line stored in a linked list and then counted The maximum number of arguments would be the number of arguments that would fit on the source line after the label and macro terms Therefore the maximum source line length is 200 characters A macro can call another macro or may call itself recursively The maximum number of nested macro calls is 16 Please refer to Chapter 7 Macro Language for more information 4 45 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation 4 45 4 See Also endm exitm local 4 45 5 Simple Example Define macro Read Read macro device buffer count movlw device movwf ram 20 movlw buffer buffer address movwf ram 21 movlw count byte count call sys 21 subroutine call endm Use macro Read Read 0x0 0x55 0x05 DS33014L page 134 O 1994 2013 Microchip Technology Inc Directives 4 45 6 Application Example macro endm This code demonstrates the utility of macro directive which is used to define a macro include p16f877a inc result equ 0x20 ORG 0x0000 goto start add MACRO numl num2
178. as in the source file The command line has precedence 309 Macro expansion superseded by command line Macro expansion was specified on the command line as well as in the source file The command line has precedence 310 Superseding current maximum RAM and RAM map The maxram directive has been used previously 311 Operand of HIGH operator was larger than H FFFF High byte of address returned by high directive was greater than OxFFFF 312 Page or Bank selection not needed for this device No code generated If a device contains only one ROM page or RAM bank no page or bank selection is required and any pagesel banksel or bankisel directives will not generate any code 313 CBLOCK constants will start with a value of 0 If the first cblock in the source file has no starting value specified this message will be generated 314 LFSR instruction is not supported on some versions of the 18Cxx2 devices See message 315 for more information 315 Please refer to Microchip document DS80058A for more details A downloadable pdf of this document PIC18CXX2 Silicon Data Sheet Errata is available from the Microchip website 316 W Register modified The working W register has been modified 317 W Register not modified BSF BCF STATUS instructions used instead The working W register has not been modified 318 Superseding current maximum ROM and ROM map Operation will cause maximum ROM to be exceeded UNK
179. ating a macro expansion During a macro expansion this directive causes expansion of the current macro to stop and all code between the exi tm and the endm directives for this macro to be ignored If macros are nested exitm causes code generation to return to the previous level of macro expansion DS33014L page 202 1994 2013 Microchip Technology Inc Macro Language 7 5 MACRO INVOCATION Once the macro has been defined it can be invoked at any point within the source module by using a macro call as described below macro name arg arg where macro name is the name of a previously defined macro and arguments are supplied as required The macro call itself will not occupy any locations in memory However the macro expansion will begin at the current memory location Commas may be used to reserve an argument position In this case the argument will be an empty string The argument list is terminated by white space or a semicolon EXAMPLE 7 1 MACRO CODE GENERATION The following macro define table macro local a 0 while a 3 entry v a dw 0 a 1 endw endm When invoked would generate entry0 dw 0 entryl dw 0 entry2 dw 0 entry3 dw 0 1994 2013 Microchip Technology Inc DS33014L page 203 Assembler Linker Librarian User s Guide 7 6 MACRO CODE EXAMPLES The following are examples of macros Literal to RAM Conversion Constant Compare 7 6 1 Literal to RAM Conversion This code conver
180. ations click MCC18 and enter CompilerInstallationPath 1lib under Include Path where CompilerInstallationPathis the location where the C compiler is installed on your system Select MPLINK and then enter a map file name next to Generate map file DS33014L page 256 1994 2013 Microchip Technology Inc Sample Applications 4 Right click on the project name in the project tree and select Build to build the application If your project contains a single assembly file with no linker script file you will be asked if you want to build absolute code or relocatable code The sample applications should be built as relocatable code 5 Ifthe application fails to build check that the environment variables discussed in the next section were set correctly during tool installation 6 Ifthe application build successfully use Debug gt Debug Project to run and debug your application or Run gt Run Project to run your application To program it into a device click the Program Target Progect button on the debug toolbar 13 2 2 Using MPLAB IDE v8 MPLAB IDE provides a GUI method of developing your code 13 2 2 1 BUILDING APPLICATIONS To build an application with MPLAB IDE 1 Use the Project Wizard under the Project menu to create a project Select the device specified in the sample application For assembly applications select the Microchip MPASM Toolsuite as the active toolsuite For C code
181. be added unless in a code pack section See the description for code pack for more infomation For all other PIC1X MCU devices reserve memory words with 8 bit data Each expr must evaluate to an 8 bit value The upper bits of the program word are zeroes Each character in a string is stored in a separate word 4 17 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is designed mainly for initializing data in the EE data memory region of PIC1X MCU devices with EE data FLASH Make sure to specify the start of EEPROM data memory in your code The table below shows start addresses for different device families However always check your device programming specification for the correct address TABLE 4 1 EEPROM START ADDRESS BY DEVICE Device Address Most PIC1X MCUs 0x2100 PIC18 MCUs OxF00000 PIC16F19XX MCUs OxF000 4 17 4 See Also data db dt dtm dw code pack 4 17 5 Simple Example Initialize EEPROM data on a PIC16 device org 0x2100 de My Program v1 0 0 DS33014L page 96 O 1994 2013 Microchip Technology Inc Directives 4 17 6 PIC16 Application Example de finclude pl6f877a inc Include standard header file for the selected devic org 0x2100 The absolue address 2100h is mapped to the 0000 location of EE data memory You can create a da
182. begins with a 9 character prefix and ends with a 2 character checksum Each record has the following format BBAAAATTHHHH HHHCC where BB A two digit hexadecimal byte count representing the number of data bytes that will appear on the line AAAA A four digit hexadecimal address representing the starting address of the data record TT A two digit record type 00 Data record 01 End of File record 02 Segment address record 04 Linear address record HH A two digit hexadecimal data byte presented in low byte high byte combinations CE A two digit hexadecimal checksum that is the two s complement of the sum of all preceding bytes in the record DS33014L page 58 1994 2013 Microchip Technology Inc MPASM Assembler Overview 1 7 6 Cross Reference File xrf A cross reference file contains a listing of all symbols used in the assembly code The file has the following format The symbols are listed in the Label column sorted by name The Type column defines the type of symbol A list of Label Types is provided at the end of the file The File Name column lists the names of the files that use the symbol The Source File References column lists the line number of the corresponding file in the File Name column where the symbol is defined referenced An asterisk means a definition To prevent cross reference file generation use the x or x option 1 7 7 Object File Lo
183. bility with previous assemblers from Microchip and to be compatible with individual programming practices If portable code is desired it is recommended that programs be written using the specifications contained here Note Although MPASM assembler is often used with MPLINK object linker MPASM assembler directives are not supported in MPLINK linker scripts See MPLINK object linker documentation for more information on linker options to control listing and hex file output Information on individual directives includes syntax description usage and related directives as well as simple and in some cases expanded examples of use In most cases simple examples may be assembled and run by adding an end statement Expanded examples may be assembled and run as is to give an demonstration of an application using the directive s Individual directives may be found alphabetically in the following sections or by type Section 4 2 Directives by Type Note Directives are not case sensitive e g cblock may be executed as CBLOCK cblock Cblock etc 4 2 DIRECTIVES BY TYPE There are six basic types of directives provided by the assembler Control Directives Conditional Assembly Directives Data Directives Listing Directives Macro Directives Object File Directives ov ord o m 1994 2013 Microchip Technology Inc DS33014L page 71 Assembler Linker Librarian User s Guide 4 2 1 Control Directives Control di
184. cc EE 1994 2013 Microchip Technology Inc DS33014L page 331 Assembler Linker Librarian User s Guide A Een 232 Comments eene ee enne 54 Common Problems LiniKer SAAS e ste T ege 294 Compiler n a aeaee ea 21 24 37 39 40 Conditional Assembly Direchhves 72 CISC maa RE ati a A 102 A ee he TENE 104 ea m 105 jc EE 104 Pastis a is 125 CA te eS 127 lt Le ENEE 129 While aci 165 Conditional Linker Statements 245 GOD Ig DEE 88 Config Bits rre 86 88 195 Configuration Bis 86 88 195 constant a di 89 Constant Compare sseeeeeee 205 Constants Block RE 82 103 Declare irn cre Rer e Eryx 89 RE e 105 Control Directives oso nes Pe pete coe tee iria 72 A S ettet 98 Alle 130 HUNCEPING 162 constants 5 ere a tonte te 89 Te BEE 103 GU 105 or ee 141 upset 147 ia recen re a e EE 148 SOL idc n avum statt sterben beet 152 Variable ai e eter to etae e Seen 163 Create Numeric and Text Data 92 Customer Support s sesesoseneeeeeeeereeeseere ne reeennesseeennee 15 D e ENEE 90 Data Bleu een 94 EEPROM Byte cocococooccccccnoccnccnncnnnnnnnnnonananocnnnnanns 96 L A folio A 101 OLEO A A er errs 65 92 Data Directives nnnoessenesnnnnnnnnnessnsrnrnnrrrrresesnns 72 BW TE EE 75 Da Mia hector eee been Yee ye do 76 el BEE 86 A o 86 EB 123 MAA cti di
185. ces distributors and factory representatives D D myMICROCHIP PERSONALIZED NOTIFICATION SERVICE Microchip s personal notification service helps keep customers current on their Microchip products of interest Subscribers will receive e mail notification whenever there are changes updates revisions or errata related to a specified product family or development tool Please visit http www microchip com pcn to begin the registration process and select your preferences to receive personalized notifications A FAQ and registration details are available on the page which can be opened by selecting the link above When you are selecting your preferences choosing Development Systems will populate the list with available development tools The main categories of tools are listed below Compilers The latest information on Microchip C compilers assemblers linkers and other language tools These include all MPLAB C compilers all MPLAB assemblers including MPASM assembler all MPLAB linkers including MPLINK object linker and all MPLAB librarians including MPLIB object librarian Emulators The latest information on Microchip in circuit emulators These include the MPLAB REAL ICE and MPLAB ICE 2000 in circuit emulators In Circuit Debuggers The latest information on Microchip in circuit debuggers These include the MPLAB ICD 2 and 3 in circuit debuggers and PICkit 2 and 3 debug express MPLAB IDE The
186. code from C Documents and Settings c08227 MPLABXProjects MyASMProject X dist de Loading symbols from C Documents and Settings c08227 MPLABXProjects MyASMProject X dist Loading completed vv AAA s Build Errors If the build did not complete successfully check these items 1 Review the previous steps in this example Make sure you have set up the lan guage tools correctly and have all the correct project files and build options 2 If you modified the sample source code examine the Build results in the Output window for syntax errors in the source code If you find any correct the error and then try to build again Some errors provide links to go to the source code line that contains that error Output Files View the project output files by opening the files in MPLAB X IDE 1 Select File gt Open File In the Open dialog find the project directory 2 Under Files of type select All Files to see all project files 3 Select example xrf Click Open to view the assembler cross reference file in an MPLAB X IDE editor window For more on this file see the MPASM assembler documentation Section 1 7 6 Cross Reference File xrf 4 Select File gt Open File In the Open dialog select example map Click Open to view the linker map file in an MPLAB X IDE editor window For more on this file see the MPLINK linker documentation Section 9 7 7 Map File map 5 Select File gt Open File
187. cript file INCLUDE cmdfile where cmdfi le is the name of the linker script file to include EXAMPLE 11 4 INCLUDE EXAMPLE To include the linker script file named my1inkx 1kr the following line should be added to the linker script file INCLUDE mylink lkr 11 4 LINKER SCRIPT CAVEATS Some linker script caveats You may need to modify the linker script files included with MPLINK linker before using them You may wish to reconfigure stack size to use MPLAB C18 with MPLINK linker You will need to split up memory pages if your code contains goto or call instructions without pagesel pseudo instructions directives You must not combine data memory regions when using MPLINK linker with MPLAB C18 C compiler MPLAB C18 requires that any section be located within a single bank See MPLAB C18 documentation for directions on creating variables larger then a single bank AAA AA A M X A Q9 99 3 J M cxr a DS33014L page 238 1994 2013 Microchip Technology Inc Linker Scripts 11 5 MEMORY REGION DEFINITION The linker script describes the memory architecture of the PIC1X MCU This allows the linker to place code in available ROM space and variables in available RAM space Regions that are marked PROTECTED will not be used for general allocation of program or data Code or data will only be
188. d 136 A nie need 137 A CK EE 82 CONTIG senc en ic 88 dara ER ER RL EE tae aaa 90 Co lE EE 92 NN TO 94 TAS 96 At O EE 100 DS33014L page 332 didicere ED b ee 100 e VE 101 endG 2 dal RAR eS Tore reddas 103 ER ENTE 116 POS cte RAE A A AEA 150 Data Section Access Uninitialized 156 Initialized EE 120 Initialized Access 122 Overlayed Uninitialized 158 Shared Uninitialized 160 LUnmnttialtzed sees 154 Data Inttalzed 254 DATABANK iai sion drones nr ace 239 244 le 94 Le 96 Debug Command Line 247 MPLAB IDE rne o erede ee vta 235 Decremeribts iin codes ints prr vos tr rs rbd cha retos 70 A xt 98 Delete a Substitution Label 162 Bleu 53 Directives Assembler nana 71 Directives Linker Masse 237 Documentation Conventions 12 E Ve Ee 9 n MUT 100 Mii 100 OW PEE 65 101 E EEPROM sex nIRSe ipe In Aen 264 Data Pe ege ee EES Ee 96 Start Address 96 Eight by Eight Multiply sssnsasaanasanaeeen neee nae ernennen 204 A As 102 ENA EE 103 ne E 103 endif RE 104 nell RE 104 A ere reine ere cadeau re 105 Environment Variables 259 260 GO ne cce ege eg Eni a Ses 105 LEE 106 Error Alea ii EE 57 207 A
189. d an Automatic Constant Block s ssssssssesennsnrnnsseeserenrrrnrrnneeeeo p 103 e fill Specify Program Memory Fill Value p 116 res Reserve Memory p 150 4 2 4 Listing Directives Listing directives control the MPASM assembler listing file format These directives allow the specification of titles pagination and other listing control Some listing directives also control how code is assembled error Issue an Error Message eme p 106 e errorlevel Set Message Level ssssssseee e p 108 list Listing AOI E EA E E p 131 messg Create User Defined Message cooccccccccnncncononccnccnncnnncnicnnannnnnnnons p 138 e nolist Turn off Listing Output p 140 page Insert Listing Page iect p 144 space Insert Blank Listing Lines p 153 e subtitle Specify Program Subtitle p 153 title Specify Program Title p 154 4 2 5 Macro Directives Macro directives control the execution and data allocation within macro body definitions endm End a Macro Definition p 104 exitm Exit from a Macro p 111 expand Expand Macro Listing p 113 e local Declare Local Macro Variable ssesssesseeeerenrrnnseessreenrrrrrrnnseee p 132 macro Declare Macro Definition sssssssssssseeeee p 134 e noexpand Turn off Macro Expansion oooococccccccccccccncnnonnnonnnnonnnnnnnnnnnnannnnns p 140 4 2 6 Object File Directives Object file directi
190. dc 4 8 6 Application Example cblock endc This example shows the usage of CBLOCK and ENDC directives for defining constants or variables in data memory space The same directives can be used for program memory space also The program calculates the perimeter of a rectangle Length and width of the rectangle will be stored in buffers addressed by length 22H and width 23H The calculated perimeter will be stored in the double precision buffer addressed by perimeter i e 20H and 21H include p16f877a inc Include standard header file for the selected devic CBLOCK 0x20 Define a block of variables starting at 20H in data memory perimeter 2 The label perimeter is 2 bytes wide Address 20H and 21H is assigned to the label perimeter length Address 22H is assigned to the label length width Address 23H is assigned to the label width ENDC This directive must be supplied to terminate the CBLOCK list clrf perimeter 1 Clear perimeter high byte at address 21H mov length w Move the data present in the register addressed by length to w addwf width w Add data in w with data in the register addressed by width STATUS register carry bit C may be affected movwf perimeter Move w to the perimeter low byte at address 20H Carry bit is unaffected rlf perimeter 1 Increment register 21H if carry was generated Also clear carry if bit was set rlf
191. de to this address For example CALL destinations on the PIC16C5x family must be in the lower half of the page 121 Illegal label Labels are not allowed on certain directive lines Simply put the label on its own line above the directive Also high low page and bank are not allowed as labels 122 Illegal opcode Token is not a valid opcode 1994 2013 Microchip Technology Inc DS33014L page 209 Assembler Linker Librarian User s Guide 123 Illegal directive Directive is not allowed for the selected processor for example the idlocs directive on devices with ID locations 124 Illegal argument An illegal directive argument for example list foobar 125 Illegal condition A bad conditional assembly For example an unmatched endi f 126 Argument out of range Opcode or directive argument out of the valid range for example TRIS 10 127 Too many arguments Too many arguments specified for a macro call 128 Missing argument s Not enough arguments for a macro call or an opcode 129 Expected Expected a certain type of argument The expected list will be provided 130 Processor type previously defined A different family of processor is being selected 131 Processor type is undefined Code is being generated before the processor has been defined Note that until the processor is defined the opcode set is not known 132 Unknown processor The selected processor is not a valid processor 133 Hex file forma
192. demonstrates suggested modifications for external memory applications First the CODEPAGE statement is added CODEPAGE NAME xsram CODEPAGE NAME idlocs CODEPAGE NAME config CODE PAGE NAME devid CODEPAGE NAME eedata START 0x020000 START 0x200000 START 0x300000 START 0x3FFFFE START 0xF00000 Then the external memory section is added IFDEF _CRUNTIME SECTION SECTION HIFDE F DE B ELSE STACK SIZI FI FI STACK SIZI NA NA UG E CONFIG E 0x100 RAM gpr14 ROM config E SRAM BASE ROM xsram DATASTART E 0x100 RAM gpr13 END 0x1FFFFF END 0x200007 END 0x30000D END 0x3FFFFF END 0xF003FF PROTECTED PROTECTED PROTECTED PROTECTED PROTECTED m 1994 2013 Microchip Technology Inc DS33014L page 279 Assembler Linker Librarian User s Guide 13 6 1 3 C COMPILER SOURCE CODE This is a simple code example showing the use of fpragma romdata for declaration of external memory and the use of C pointers for accessing this memory region If you are using MPLAB IDE v8 to run this example remember to enable externa
193. dr sets the configuration bits to the value described by expr Note Configuration bits must be listed in ascending order Although this directive may be used to set configuration bits for PIC18 MCU devices it is recommended that you use the config directive no underline characters For PIC18FXXJ devices you must use the config directive Note Do not mix config and config directives in the same code 4 11 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is placed in source code so that when the code is assembled into a hex file the configuration values are preset to desired values in your application This is useful when giving your files to a third party programming house as this helps insure the device is configured correctly when programmed Place configuration bit assignments at the beginning of your code Use the configuration options names in the standard include inc file These names can be bitwise ANDed together using amp to declare multiple configuration bits 4 11 4 See Also config idlocs list processor DS33014L page 86 1994 2013 Microchip Technology Inc Directives 411 5 Simple Examples Example 1 PIC16 Devices include p16f877a inc include file with config bit definitions _ config HS OSC amp WDT OFF amp LVP OFF Set oscillator to HS
194. e command line partnumber indicates the part number for the device as in 184520 for PIC18F4520 For Windows OS you specify the part number by ppartnumber For Linux or Mac OS you specify the part number by ppartnumber If no linker script name is provided the part number will be used to determine the generic linker script to build the project The linker will search the 1kr directory to find the generic linker script for that part The 1kr directory is located at the same location as the MPLINK linker executable The linker will construct the name of the generic linker script by adding an _g 1kr to the string value of the part number as in 18f4520 g lkr As of MPLINK linker v4 38 even is a linker script is provided the part number must also be provided obj fileis the name of an assembler or compiler generated object file All object files must have the extension o libfile is the name of a librarian created library file All library files must have the extension lib option is one of the linker command line options described below For Windows OS use a backslash and then the option For Linux or Mac OS use a dash and then the option EE EE EE DS33014L page 232 O 1994 2013 Microchip Technology Inc Linker Interfaces Option or Description a hexformat Specify format of hex output file d Do not generate a list file g Generate report file for stack analysis h 7 Di
195. e following Enable Extended Instruction Set in the configuration bits Incode use CONFIG XINST 0N In the Configurations Bits window under XINST select Enabled Select Project gt Build Options gt Project On the MPASM C17 C18 Suite tab check the Extended Mode checkbox For a list of available instructions in the Extended Instruction set see Section A 9 PIC18 Device Extended Instruction Set EE EEE lt A gt DB _ _ RK g 9 EE DS33014L page 42 O 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB IDE v8 PROJECT EXAMPLE In this example you will create an MPLAB IDE project with multiple assembly files Therefore you will need to use the MPASM assembler and the MPLINK linker to create the final output executable nex file Run the Project Wizard Set Build Options Build the Project Build Errors Output Files Further Development Run the Project Wizard In MPLAB IDE select Project Project Wizard to launch the wizard Click Next gt at the Welcome screen 1 Select PIC16F84A as the Device Click Next to continue 2 Set up the language tools if you haven t already Refer to MPLAB IDE Setup Click Next to continue 3 Enter Example for the name of the project Then Browse to select a location for your project Click Next gt to continue 4 Add files to the project In the file listing box on the left of
196. e and the endw are assembled as long as expr evaluates to TRUE An expression that evaluates to zero is considered logically FALSE An expression that evaluates to any other value is considered logically TRUE A relational TRUE expression is guaranteed to return a non zero value FALSE a value of zero A while loop can contain at most 100 lines and be repeated a maximum of 256 times while loops can be nested up to 8 deep 4 68 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is not an instruction but used to control how code is assembled not how it behaves at run time Use this directive for conditional assembly 4 68 4 See Also endw if 4 68 5 Simple Example while is not executed at run time but produces assembly code based on a condition View the list file 1st or disassembly window to see the results of this example test_mac macro count variable i i 0 while i lt count moviw i i 1 endw endm start test mac 5 end 1994 2013 Microchip Technology Inc DS33014L page 165 Assembler Linker Librarian User s Guide 4 68 6 Application Example while endw This example shows the usefulness of directive while to perform a loop while a certain condition is true This directive is used with the endw directive include p16f877a inc variable i mydata udata 0x20 reg hi re
197. e list file name 5 clicking Open This file may be viewed in MPLAB IDE v8 by selecting File gt Open to launch the Open dialog selecting List files Ist from the Files of type drop down list locating the desired list file clicking on the list file name clicking Open Both the MPASM assembler and the MPLINK linker can generate listing files For information on the MPLINK linker listing file see 9 7 6 Listing File Ist To prevent assembler list file generation use the 1 or 1 option or use with MPLINK linker The linker list file overwrites the assembler list file Set the size of tabs in the list file using the t or t option ERIN EEC gt E DS33014L page 54 O 1994 2013 Microchip Technology Inc MPASM Assembler Overview EXAMPLE 1 2 ABSOLUTE MPASM ASSEMBLER LISTING FILE The product name and version the assembly date and time and the page number appear at the top of every page The first column contains the base address in memory where the code will be placed The second column displays the 32 bit value of any symbols created with the set equ variable constant or cblock directives The third column is reserved for the machine instruction This is the code that will be executed by the PIC1X MCU The fourth column lists the associated source file line number for this line The remainder of the line is reserved for the source code line that generated the machine code Errors warnings a
198. e list of names end when an endc directive is encountered expr indicates the starting value for the first name in the block If no expression is found the first name will receive a value one higher than the final name in the previous cblock If the first cblock in the source file has no expr assigned values start with Zero If increment is specified then the next label is assigned the value of increment higher than the previous label Multiple names may be given on a line separated by commas cblockis useful for defining constants in program and data memory for absolute code generation 4 8 3 Usage This directive is used in the following types of code absolute For information on types of code see Section 1 6 Assembler Operation Use this directive in place of or in addition to the equ directive When creating non relocatable absolute code cblock is often used to define variable address location names Do not use cblock or equ to define variable location names for relocatable code 4 8 4 See Also endc equ DS33014L page 82 1994 2013 Microchip Technology Inc Directives 4 8 5 Simple Example cblock 0x20 name 1 will be assigned 20 name 1 name 2 name 2 21 and so on name 3 name 4 name 4 is assigned 23 endc cblock 0x30 TwoByteVar 0 TwoByteHigh TwoByteLow TwoByteVar 0x30 TwoByteHigh 0x30 a TwoByteLow 0x31 Queue QUEUE SIZE QueueHead QueueTail Doublel 2 Double2 2 en
199. e symbol table The define directive was used to define two substitution strings Taistance1 to substitute for 50 and Tdistance2 to substitute for 25 Then undefine was used to remove Tdistance2 from the symbol table i e Tdistance2 can no longer be used to substitute for 25 udata 0x20 Set up distance reg distance reg res 1 at GPR 0x20 The udata and res directives are used to assign distance reg to register 0x20 For more on these directives see example 1 rst code 0x00 Reset Vector pagesel Start goto Start code Start Program Start clrf distance reg Clear register movlw Tdistancel Move value of Tdistancel movwf distance reg into distance reg constant distancel 10 Declare distancel 7a constant symbol DS33014L page 178 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks Declare a constant symbol distance1 with a value of 10 Once a constant is declared its value cannot be altered variable distance2 Declare distance2 a variable symbol Declare a variable symbol distance2 The variable directive does not require the symbol to be initialized when declared distance3 set 10 Define a value for the symbol distance3 Define symbol distances as 10 distance2 15 Give distance2 an initial value distance2 distancel distance2 Add distancel to distance2 Variable assignments increments and decrements must be placed on separate lines distance3 set 15 Change value o
200. e words of program memory with data The data may be in the form of constants relocatable or external labels or expressions of any of the above The data may also consist of ASCII character strings text string enclosed in single quotes for one character or double quotes for strings Single character items are placed into the low byte of the word while strings are packed two to a word If an odd number of characters are given in a string the final byte is zero On all families except the PIC18 device family the first character is in the most significant byte of the word On the PIC18 device family the first character is in the least significant byte of the word 4 15 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation When generating a linkable object file this directive can also be used to declare initialized data values Refer to the idata directive for more information db and other data directives are more commonly used than data 4 15 4 See Also db de dt dtm dw idata 4 15 5 Simple Example data reloc label 10 constants data 1 2 ext label constants externals data testing 1 2 3 text string data N Single character data start of program relocatable label 4 15 6 PIC16 Application Example data This example shows the usefulness of directive data in storing one or more words in program memory f
201. eat steps 1 and 2 Select Example Ist Click Open to view the linker listing file in an MPLAB IDE editor window When MPASM assembler is used with MPLINK linker the listing file is generated by the linker For more on this file see the MPLINK linker documentation Section 9 7 6 Listing File Ist 6 Repeat steps 1 and 2 Notice that there is only one hex file Example hex This is the primary output file used by various debug tools You do not view this file for debugging use View gt Program Memory or View gt Disassembly Listing Further Development Usually your application code will contain errors and not build the first time Therefore you will need a debug tool to help you develop your code Using the output files previously discussed several debug tools exist that work with MPLAB IDE to help you do this You may choose from simulators in circuit emulators or in circuit debuggers either manufactured by Microchip Technology or third party developers Please see the documentation for these tools to determine how they can help you When debugging you will need to set the Build Configuration to Debug Please see MPLAB IDE documentation concerning this control Once you have developed your code you will want to program it into a device Again there are several programmers that work with MPLAB IDE to help you do this Please see the documentation for these tools to see how they can help you When programming you will need to
202. ection Ck ck ck kk ck ck ck kk kk Ck Ck Ck Ck Ck ck Ck Ck kk Ck Ck Ck ck kk kk Ck kk kk Ck kk kk kk kk kk Sk kk Sk kk Sk kk kk ck kk Sk kk KKK Mk ko ko ko XX END 1994 2013 Microchip Technology Inc DS33014L page 277 Assembler Linker Librarian User s Guide 13 6 SAMPLE APPLICATION 4 CONFIGURING EXTERNAL MEMORY Most of the larger pin count PIC microcontrollers have the ability to interface to external Note MPLAB X IDE does not yet support External Memory views 8 or 16 bit data FLASH or SRAM memories through the External Memory Bus EMB The PIC18F8722 for example has 128K bytes of internal program memory 00000h 1FFFFh But when configured for Extended Microcontroller mode external program memory space from locations 20000h through 1FFFFFh becomes externally addressable through the EMB created from the I O pins The use of a linker script file can be extended to other external memory mapped devices such as programmable I O peripherals real time clocks or any device that has multiple configuration or control registers that can be accessed through an 8 or 16 bit data bus 13 6 1 C Compiler Usage This section discusses how to use the MPLAB C Compiler for PIC18 MCUs the C compiler when developing external memory appliation code The C compiler linker script file for the PIC18F8722 is modified to instruct the linker that anew memory region is available by adding a CODEPAGE definition as shown below The use
203. ed by the code and linker script are compared below Specific sections highlighted in these sample application SA3 examples are noted O 1994 2013 Microchip Technology Inc DS33014L page 267 Assembler Linker Librarian User s Guide TABLE 13 6 PROGRAM MEMORY MAP PIC18F8722 Program Linker Script Section Memory Address Not debug or extended SA3 Source Code Section 0x000000 vectors Reset Interrupts Vectors IntH IntL 0x000029 gt 0x00002A boot Boot Loader Boot 0x0007FF 0x000800 page Remapped Vectors R vectors R_IntH R IntL Boot Ox1FFFFF and User Code Loader Updated Application Code 13 5 1 2 EXAMPLE 1 C COMPILER BOOT LOADER This example shows a section of linker script modified to accomodate the boot loader code Boot Loader Linker Script The partial C compiler linker script file shown below demonstrates the modifications required to the generic linker script when building the C compiler boot loader source code files The MPLINK linker will use this configuration to link the compiled source code into the boot program memory region starting at 002Ah The vector locations will be specified in the boot loader source code using the appropriate pragma code directives CODEPAGE NAME vectors ST
204. ed with MPLINK linker to generate an object file code is also different in that an address is not normally specified the linker handles the allocation of space both in program Flash and data RAM memory goto PER CAL CODI E PER_CAL clrf perimetertl movf length w addwf width w movw perimeter rlf perimeter 1 rlf perimeter rlf perimeter 1 Jump to label PER CAL CODE directive here dictates that the following lines of code will be placed in program memory but the starting address will be decided by the linker Clear the high byte of the label perimeter Move the data present in the register addressed by length to w Add data in w with data in the register addressed by width STATUS register carry bit C may be affected Move w to the perimeter low byte at address 20H Carry bit is unaffected Increment register 21H if carry was generated Also clear carry if bit was set Multiply register 20H by 2 Carry bit may be affected Again increment register 21H if carry was generated The previous two lines of code will multiply by left shifting one bit the intermediate result by 2 goto end Go to current line loop here O 1994 2013 Microchip Technology Inc DS33014L page 151 Assembler Linker Librarian User s Guide 4 58 set DEFINE AN ASSEMBLER VARIABLE 4 58 1 Syntax Preferred label set expr Supported
205. ee i 21 37 227 Bank Selecting BE 80 Ro Ee 21 37 227 Bank Selecting die cotas red cos 77 IVO NDA UR Le node oy 227 Banking e 176 197 SMASH A DOM MGR CN oan Le 227 bankiselz sie EE Dee Qe oce os fre 77 EE EE 80 197 ae ENEE EE Ss s Ss Bit Assignments c oooococccccccncconccnncnnonannnncnnnncnnnccnnnnns 175 ist EE DS e O Ee 207 Blank Listing Lines ooooccccnninicccnnnnnnccccccnccoccnnccccnnnns 153 A ME E RS ER dua a UM destin Block of Constants 82 103 oA eo easier ieee EEN 21 37 Boot Loader etes Een 267 O T E j3 p Opina ae PT aie 22 38 MM O S Build Project de Command O 259 PUNGSTING ii ee 162 OE eine 230 257 ee ee ee E OE ap nt 69 C A Caveats Linker Script 238 e COlOCk a t aaa Nata 82 Ee 90 TEE 220 ar SC e Ee 84 190 195 Le Fo aio I dE d Code Seront 84 175 ACCESSBANK atestado ras 239 244 SE E Ee E Accessing Labels From Other Modules 198 Gogg Apagiie 80180 194 187 1e d ue Se Code Relocatable 50 190 195 197 Roloratable Ree 252 Calling File ei ds 199 EE 252 Defining Module EE AE 196 AND logical ud M M A ASE 69 Library Routine 199 AR CLAU Referencing Module 196 Arithmatic Operators sssssssssee 69 CODEPAGE LLL LLL 243 244 ASGII Character Get ENEE 329 COF File 24 37 Assembler Command Line Options corr Oia Module i LOL 227 MT Em E Corimand Line Infertses SE e NEG EE EEN 63 Ne M Aint tect EE jr cece
206. ee MPLAB C18 libraries documentation Code examples are also included in the example subdirectory DS33014L page 18 O 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB X IDE MPLAB X IDE SETUP Once MPLAB X IDE is installed on your PC check the settings below to ensure that the PIC1X language tools are properly recognized under MPLAB X IDE 1 From the MPLAB X IDE menu bar select Too s gt Options to open the Options dia log Click on the Embedded button and select the Build Tools tab 2 Click on MPASMX under Tool Collection Ensure that the paths are correct for your installation of the MPASM assembler This will ensure that the paths to the linker librarian and utilities are correct as all of these tools are part of the MPASM Suite 3 For the optional MPLAB C18 C compiler click on C18 under Tool Collection Ensure that the paths are correct for your installation of the compiler This will ensure that the paths to the compiler and related assembler linker librarian and utilities are correct as all of these tools are part of the C18 Suite 4 Click OK FIGURE 1 MPASM SUITE TOOL LOCATIONS 5 a ER e e Gp General Editor Fonts amp Colors Keymap C C Embedded Miscellaneous Build Tools Project Options Generic Settings Suppressible Messages Other Toolchain HI TECH PICC v9 82 C Progra HI TECH PICC v9 80 C Progre HI TECH PICC v9 81
207. endm directive is encountered Note Macros must be defined before they are used i e forward references to macros are not permitted 1994 2013 Microchip Technology Inc DS33014L page 201 Assembler Linker Librarian User s Guide 7 3 MACRO DIRECTIVES DEFINED There are directives that are unique to macro definitions They cannot be used out of the macro context 4 45 macro Declare Macro Definition 4 31 exitm Exit from a Macro 4 26 endm End a Macro Definition 4 32 expand Expand Macro Listing 4 49 noexpand Turn off Macro Expansion 4 44 local Declare Local Macro Variable When writing macros you can use any of these directives PLUS any other directives supported by the assembler Note The previous syntax of the dot format for macro specific directives is no longer supported 7 4 MACRO DEFINITION String replacement and expression evaluation may appear within the body of a macro Command Description arg Substitute the argument text supplied as part of the macro invocation tv expr Return the integer value of expr Typically used to create unique variable names with common prefixes or suffixes Cannot be used in conditional assembly directives e g ifdef while Arguments may be used anywhere within the body of the macro except as part of normal expression The exitm directive provides an alternate method for termin
208. eprom2 asm list p 18f8720 include p18f8720 inc INTHAND code place interrupt handling code in here end O 1994 2013 Microchip Technology Inc DS33014L page 265 Assembler Linker Librarian User s Guide 1343 Linker Script eeprom Ikr The linker script file eeprom 1kr is a modified version of the generic linker script file 1818720 g 1lkr Modify the generic linker script as follows to create eeprom 1kr Add EEPROM codepage information IFDEF _DEBUGCODESTART CODEPAGE NAME page START 0x0 END _CODEEND CODEPAGE NAME debug START _DEBUGCODESTART END _CEND PROTECTED HE LSE CODEPAGE NAME page START 0x0 END 0x1FFFF FI EEPROM codepage CODE PAGE NAME eeprom START 0x20000 END 0x1FFFFF PROTECTED CODEPAGE NAME idlocs START 0x200000 END 0x200007 PROTECTED CODE PAGE NAME config START 0x300000 END 0x30000D PROTECTED CODE PAGE NAME devid START 0x3FFFFE END 0x3FFFFF PROTECTED CODE PAGE NAME eedata START 0xF00000 END 0xF003FF PROTECTED Then add section information for the EEPROM sections IFDEF _CRUNTIME D E CONFIG ROM config E INTHAND ROM eeprom Interrupt handlers E DATTBL ROM eeprom Data tables DATASTART 0x100 RAM gpr13 STACK SIZE 0x100 RAM gpr14 SECTION A SECTION NA SECTION NA
209. equence requires four instructions A more efficient technique is to assume the bit in REGA is clear and clear the REGB bit and test if the REGA bit is clear If so the assumption was correct and the BSF instruction is skipped otherwise the REGB bit is set The sequence in the second example uses three instructions because one bit test was not needed One important point is that the second example will create a two cycle glitch if REGB is a port outputting a high This is caused by the BCF and BTFSC instructions that will be executed regardless of the bit value in REGA 1994 2013 Microchip Technology Inc DS33014L page 187 Assembler Linker Librarian User s Guide 5 9 4 TIP 4 Swap File Register with W The following macro swaps the contents of W and REG without using a second register SWAPWF MACRO REG XORWF REG F XORWF REG W XORWF REG F ENDM Needs 0 TEMP registers 3 Instructions 3 Tcy An efficient way of swapping the contents of a register with the working register is to use three XORWF instructions It requires no temporary registers and three instructions Here s an example W REG Instruction 10101100 01011100 XORWF REG F 10101100 11110000 XORWF REG W 01011100 11110000 XORWF REG F 01011100 10101100 Result 5 9 5 TIP 5 Bit Shifting Using Carry Bit Rotate a byte through carry without using RAM variable for loop count Easily adapted to serial interface transmit routines Carry bit is cleared
210. er Librarian User s Guide EXAMPLE 11 5 RAM EXAMPLE DATABANK AND SHAREBANK Based on the RAM memory layout shown in PIC16F877A Register File Map the DATABANK and SHARI the examples below the map EBANK entries in the linker script file would appear as shown in FIGURE 11 1 PIC16F877A REGISTER FILE MAP Address Bank 0 Bank 1 Bank 2 Bank 3 00h INDFO INDFO INDFO INDFO 01h TMRO OPTION_REG TMRO OPTION_REG 02h PCL PCL PCL PCL 03h STATUS STATUS STATUS STATUS 04h FSR FSR FSR FSR 05h PORTA TRISA OFh TMR1H EEADRH 10h T1CON 1Fh ADCONO ADCON1 General Purpose General Purpose 20h RAM Banked RAM Banked General Purpose General Purpose _ RAM Banked RAM Banked 6Fh 70h General Purpose RAM Unbanked 7Fh RAM Memory Declarations for PIC16F877A Banked Memory Special Function Registers in Banks DATABA DATABA DATABANK DATABANK General DATABA DATABA DATABA DATABA K K DN D D MN RAM Memory Declarations for PIC16F877A Unbanked Memory General Purpose RAM avail SHAREBANK SHAREBANK SHAREBANK SHAREBANK AME sfr0 STA AME sfrl STA AME sfr2 STA AME sfr3 STA Purpose RAM in B AME gpr0 STA AME gpr 1 STA AME gpr2 STA AME gpr3 STA NAME gprnobnk NAME gprnobnk NAME gprnobnk NAME gprnobnk UUUU
211. er Modules A 196 6 8 Paging and Banking Issues usa est Re ert ti 197 6 9 Generating the Object Module 1 teetetn nth ette ener inniti denen 198 6 10 Code Example susi M 198 Chapter 7 Macro Language TA Introduction dd 201 TM MM A A Ee 201 7 3 Macro Directives Defined miii A enr er ten iii 202 1 4 Macro Definitlon 3 1 repone ticas 202 7 5 Macro Invocation cette nte eie cr dee Mann enr 203 7 6 Macro Code ExXampl s isc aida 204 Chapter 8 Errors Warnings Messages and Limitations Nullen n 207 le el 208 9 39 Assembler WamingS n toi cest teen ecrire eg ic ba bi Pipe oat ds ee dois cidos 215 9 4 Assembler Messages EE 218 8 5 Assembler Limitations 2 irent intret riot 220 Part 2 MPLINK Object Linker Chapter 9 MPLINK Linker Overview 9T Introduction nod tette etes stamet oii 223 9 2 MPLINK Linker Defined cerit a iaa 223 9 3 How MPLINK Linker Works 223 9 4 How MPLINK Linker Helps You iii 224 9 5 Linker Platforms Supported ss 224 9 6 Linker Operation onere pepe rp vt e A i ee 225 9 7 Linker Input Output Files users 226 Chapter 10 Linker Interfaces a Lo PMA ay coo tee NEE 231 10 2 IDE InterfaCe o A dur dee EE 231 103 Comm nd Line Interface chicas da 232 104 Command ENA Example uti e ee edu RR 234 O 1994 2013 Microchip Technology Inc DS33014L page 5 Assembler Linker Librarian User s Guide Chapter 11 Linker Scripts TINTO UCHI N WEE 235
212. er is a single source file that will not be linked with any other source code at build time The CODE directives used in the boot loader source code instructs the linker to place the reset and interrupt vectors at their appropriate program memory locations for the PIC microcontroller and to place the starting location of the boot loader executable code just above this region starting at location 002Ah The program memory section names Vectors IntH and IntL are used with the CODE directive to instruct the linker to place the assembled code that follows each directive at the specified program memory location In this case the boot loader is not linked with any application code so the relocated reset and interrupt vectors 0208h 0218h and 022Ah are assumed and therefore are explicitly coded 18Fboot asm This is an example of how the startup portion of a boot loader could be configured when designing and programming only the boot loader code into the target PIC microcontroller KKK KKK KKK KKK KKK KKK KKK KKK KK KK KKK KKK KKK KKK KKK KKK KKK KK KKK KK KKK KKK KKK AAA ko ko ko 18Fboot asm Ck ck ck kk ck kk KK KK KK KK KKK KK KK KK KK KKK KKK KKK KK KK KK KK kk KK KK KKK KKKKKKKKKKKKKKKKKKKKKKK LIST P 18F8720 include P18cxxx inc KKK KKK KKK KKK KKK KKK KKK KKK KK KK KKK KKK KKK KKK KKK KK KK KKK KKK KKK KKK KKK KKK kk ko ko ko ko ko ko ko kokok Vectors code 0x0000 VReset bra Boot Start IntH code 0x0008 VIntH bra 0x0208 Re map Int
213. eration For every while directive used there must be a corresponding endw while and endw are not instructions but used for code assembly only 4 27 4 See Also while 4 27 5 Examples See the example under while 4 28 equ DEFINE AN ASSEMBLER CONSTANT 4 28 1 Syntax label equ expr 4 28 2 Description The value of expr is assigned to label 4 28 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation In a single assembly file program equ is commonly used to assign a variable name to an address location in RAM Do not use this method for assigning variables when building a linked project use a res directive inside a data section directive idata udata 4 28 4 See Also set cblock res idata udata udata acs udata ovr udata shr 4 28 5 Simple Example four equ 4 assigned the numeric value of 4 to label four 4 28 6 Application Example set equ See this example under set O 1994 2013 Microchip Technology Inc DS33014L page 105 Assembler Linker Librarian User s Guide 4 29 error ISSUE AN ERROR MESSAGE 4 29 1 Syntax error text_string 4 29 2 Description text stringis printed in a format identical to any MPASM assembler error message text string may be from 1 to 80 characters 4 293 Usage This directive is used in the following types of code absolute or relocatable For information on typ
214. errupt vector to app s code space IntL code 0x0018 VIntL bra 0x0218 Re map Interrupt vector to app s code space Ck ck ck kk ck kk KK KK KK KK KKK KK KK KK KKK KKK ck kk kk ck Sk kk kk Sk kk kk KK AAA RARA AAA AAA Sk Sk Sk Sk kc k kA ko ko ko XX Boot code 0x002A Boot loader executable code starts here Boot Start Logic to determine if bootloader executes or branch to user s code bra 0x022A Branch to user s application code end of boot loader code section KKEKKKKKKK kk kk kk Ck Ck Ck kk Ck Ck kk kk kk ck kk ck ck kk kk kk kk Sk kk Sk ck ck kk Sk kk kk kk kk kk ck ko Sk kv Sk Sk Sk Sk Sk kA ko ko kokok END DS33014L page 274 O 1994 2013 Microchip Technology Inc Sample Applications 13 5 2 4 EXAMPLE 2 ASSEMBLER APPLICATION SOURCE CODE In this example the application code is composed of several relocatable source files that are assembled and linked together during build time The relocatable reset and interrupt vector locations are defined in main asm and are assigned to a specific program memory location by the CODE directive main asm This is a sample of the startup portion of a main source code file that contains the relocated reset and interrupts and is the main entry point into the application Ck ck ck kk ck ck ck KK KK KK KK KKK KK KK KKK KKK KK KKK KK KK KK KK KK kk KK KK KKK KK kk KK kk ck ko ko Sk kk ck Sk Sk kA k ko ko XX main aam dee dede dece RARA dek zk de dek zk ER der de AN eege dle dee e
215. es of code see Section 1 6 Assembler Operation You can use this directive to generate errors for yourself or others who build your code You can create any error message you wish as long as it is no longer than 80 characters 4 294 See Also messg if 4 29 5 Simple Example error checking macro argl if argl gt 55 if arg is out of range error error checking 01 arg out of range endif endm 4 29 6 Application Example error This program demonstrates the error assembler directive which sets an error message to be printed in the listing file and error file include p16f877a inc Include standard header file for the selected devic variable baudrate variable used to defin required baud rate baudrate set D 5600 Enter the required value of baud rate here if baudrate D 1200 amp amp baudrate D 2400 amp amp baudrate D 4800 amp amp baudrate D 9600 amp amp baudrate D 19200 error Selected baud rate is not supported endif DS33014L page 106 O 1994 2013 Microchip Technology Inc Directives The if endif code above outputs error if the baud rate selected is other than 1200 2400 4800 9600 or 19200 Hz RST CODE 0x0 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST pagesel start Jumps to the location labelled goto start phstartts PGM CODE This is the beginning of the
216. estore tab default settings Use Alternate Settings Text Box Enter options in a command line non GUI format 1994 2013 Microchip Technology Inc DS33014L page 39 Assembler Linker Librarian User s Guide Build Options Dialog MPLAB C18 Tab If Installed Although the MPLAB C18 C compiler works with MPLAB IDE it must be acquired separately The full version may be purchased or a student limited feature version may be downloaded for free See the Microchip website www microchip com for details This compiler supports PIC18X MCU devices A subset of command line options may be specified in MPLAB IDE in the Build Options dialog MPLAB C18 tab Select a category and then set up compiler options For additional options see the MPLAB C Compiler for PIC18 MCUs User s Guide DS51288 also available on the Microchip website General Category Generate Command Line Diagnostics level Select to display errors only errors and warnings or errors warnings and messages These will be shown in the Output window Default storage class Select the storage class either auto ANSI standard static ANSI standard or overlay non extended mode Enable integer promo Select to enable integer promotions ISO mandated arithmetic per tions formed at int precision or greater Treat char as unsigned Select to make char types unsigned 0 256 instead of the default signed 128 to 127
217. et later in RecLength 128 constant MaxMem RecLength BufLength CalcMaxMem 1994 2013 Microchip Technology Inc DS33014L page 163 Assembler Linker Librarian User s Guide 4 67 6 Application Example variable constant This example shows the the usage of the variable directive used for creating symbols which may be used in MPASM assembler expressions only The symbols created with this directive do not occupy any physical memory location of microcontroller include p16f877a inc Include standard header file for the selected devic variable perimeter 0 The symbol perimeter is initialized to 0 variable area If a symbol is declared as variable then initialization is optional i e it may or may not be initialized constant lngth 50H The symbol lngth is initialized to 50H constant wdth 25H The symbol wdth is initialized to 25H constant symbol always needs to be initialized perimeter 2 lngth wdth The value of a CONSTANT cannot be reassigned after having been initialized once So lngth and wdth cannot be reassigned But perimeter has been declared as variable and so can be reassigned area 1ngth wdth end DS33014L page 164 O 1994 2013 Microchip Technology Inc Directives 4 68 while PERFORM LOOP WHILE CONDITION IS TRUE 4 68 1 Syntax Preferred while expr Supported while expr endw 4 68 2 Description The lines between the whil
218. et memory and for mapping sections to the specified memory blocks If the linker cannot find a block of target memory in which to allocate a section an error is generated The linker combines like named input sections into a single output section The linker allocation algorithm is described in Section 12 3 Linker Allocation Algorithm Once the linker has allocated all sections from all input modules into target memory it begins the process of symbol relocation The symbols defined in each input section have addresses dependent upon the beginning of their sections The linker adjusts the symbol addresses based upon the ultimate location of their allocated sections After the linker has relocated the symbols defined in each input section it resolves external symbols The linker attempts to match all external symbol references with a corresponding symbol definition If any external symbol references do not have a corresponding symbol definition an attempt is made to locate the corresponding symbol definition in the input library files If the corresponding symbol definition is not found an error is generated If the resolution of external symbols was successful the linker then proceeds to patch each section s raw data Each section contains a list of relocation entries which associate locations in a section s raw data with relocatable symbols The addresses of the relocatable symbols are patched into the raw data The process of relocating symb
219. except last cycle and the cycle repeats until the zero bit sets indicating the end list p 12f629 finclude p12f629 inc buffer equ 0x20 bsf STATUS C Set end of loop flag rlf buffer E Place first bit into C Send Loop bef GPIO Dout Precondition output btfsc STATUS C Check data 0 or 1 bsf GPIO Dout bcf STATUS C Clear data in C rlf buffer F Place next bit into C movf buffer F Force Z bit btfss STATUS Z Exit goto Send Loop Related Topic TIP 3 Conditional Bit Set Clear 5 9 6 TIP 6 Using External Memory To use external memory the maximum allowable address must be redefined by using the MAXROM directive For example when using the PIC18F87J10 in extended microcontroller mode the MAXROM directive must be used as follows finclude lt P18cxxx inc gt __MAXROM Ox1FFFFF 87310 Configuration for external memory CONFIG MODE XM20 EASHFT OFF BW 16 WAIT OFF org 0x0000 goto 0x10000 END DS33014L page 188 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 6 Relocatable Objects INTRODUCTION MPASM assembler used with MPLINK object linker has the ability to generate and link precompiled object modules Writing source code that will be assembled to an object module is slightly different from writing code used to generate an executable hex file directly MPASM assembler routines designed for absolute address assembly wil
220. extern C MPASM assemblerV2 MUL8X8 AS mulplr 0x000021 data extern C MPASM assemblerV2 MUL8X8 AS 1994 2013 Microchip Technology Inc DS33014L page 229 Assembler Linker Librarian User s Guide The fourth table in the map file Symbols Sorted by Address provides the same information that the third table provides but it is sorted by symbol address rather than symbol name If a linker error is generated a complete map file can not be created However if the m or m option was supplied an error map file will be created The error map file contains only section information no symbol information is provided The error map file lists all sections that were successfully allocated when the error occurred This file in conjunction with the error message should provide enough context to determine why a section could not be allocated Ag AAA w H2 99 EE H QRc n Q mnce DS33014L page 230 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 10 Linker Interfaces 10 1 INTRODUCTION MPLINK object linker usage is discussed When MPLAB X IDE MPLAB IDE v8 or MPLAB C18 is installed the MPLINK linker mplink exe is also installed Topics covered in this chapter IDE Interface Command Line Interface
221. f distance3 distance2 distance2 distance3 Add distance to distance2 movlw distance2 Move value of distance2 movwf distance reg into distance reg goto Start Loop back to Start end 5 4 3 Using Watch es Windows Once the program begins the value of Tdistancel is placed into distance reg This can be observed in a Watches window in MPLAB X IDE or a Watch window in MPLAB IDE v8 The value of distance_reg will become 50 The symbol Tdistancel will not be found in the Watch es window symbol list as symbols defined using the define directive are not available for viewing in the IDE because they are not RAM variables The final lines of the example program write the final value of distance2 to distance reg If you had a Watch es window open to see distance reg loaded with the value of 50 you will see it change to 3A Remember that the radix is hexadecimal so hex addition was used to determine the distance2 value 1994 2013 Microchip Technology Inc DS33014L page 179 Assembler Linker Librarian User s Guide 5 5 EXAMPLE OF A 32 BIT DELAY ROUTINE Directives highlighted in this example are macro endm banksel 5 5 1 Program Functional Description A delay routine is needed in many applications For this example delay increments are 20 us with the routine having a range of 40 us to 23 8 hours This assumes a 4 MHz clock 5 5 2 Commented Code Listing Each loop takes 20 clocks or 20 us per loop at
222. file filename could not read string table Coff file filename could not read string table length Coff file filename could not read symbol table Coff file filename could not write file header Coff file filename could not write lineinfo Coff file filename could not write optional file header Coff file filename could not write raw data Coff file filename could not write reloc Coff file filename could not write section header Coff file filename could not write string Coff file filename could not write string table length Coff file filename could not write symbol Coff file filename cScnHdr size cScnNum size Coff file filename does not appear to be a valid COFF file Coff file filename has relocation entries but an empty symbol table Coff file filename missing optional file header Coff file filename section xx has an invalid s offset Coff file filename section secName line xx has an invalid fcnndx Coff file filename section secName line xx has an invalid srcndx Coff file filename section secName reloc xx has an invalid r symndx Coff file filename symbol xx has an invalid n offset Coff file filename symbol xx has an invalid n scnum Coff file filename symbol xx has an invalid index Could not find section name secName in string table Could not find symbol name symName in string table Could not o
223. fk SUBFSR f k Subtract literal from FSR FSR f k gt FSR f E9Ck SUBULNK k Subtract literal from FSR2 and return FSR2 k gt FSR2 TOS gt PC DS33014L page 328 O 1994 2013 Microchip Technology Inc S ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Appendix B Useful Tables B 1 INTRODUCTION Some useful tables are included for reference here The tables are ASCII Character Set Hexadecimal to Decimal Conversion B 2 ASCII CHARACTER SET This table displays the standard ASCII character set in nibbles Most Significant Nibble expe CI RC RC EC ES CS A o N Space P Sa SOH DC1 1 A Q a q EN STX DC2 2 B R b r 3 ETX DC3 3 C S c s NN EOT pc4 4 D T d t ED ENQ NAK 96 5 E U e u Nod EU ACK SYN amp 6 F V f v Nibble Bel ETB 7 G w g w ES BS CAN 8 H X h x RS HT EM 9 Y i y LF SUB J Z j z B vt ESC K k FF FS lt L Em CR GS S M m NA so RS gt N 2 E EM SI US O 7 o DEL O 1994 2013 Microchip Technology Inc DS33014L page 329 Assembler Linker Librarian User s Guide B 3 HEXADECIMAL TO DECIMAL CONVERSION This table describes how to convert hexadecimal to decimal For each HEX digit find the associated decimal value Add the numbers together Hi
224. formation Reloc index gt address 0x0001 symbol varl type bank Reloc index gt address 0x0002 symbol varl type offset Once the linker has placed every section into target memory the final addresses are known Once all identifier symbols have their final addresses assigned the linker must patch all references to these symbols using the relocation entries In the example above the updated symbol might now be at location 0x125 Symbol index gt name varl value 0x125 section data class extern If the code section above were relocated to begin at address 0x50 the updated relocation entries would now begin at location 0x51 Reloc index gt address 0x0051 symbol varl type bank Reloc index gt address 0x0052 symbol varl type offset The linker will step through the relocation entries and patch their corresponding sections The final assembly equivalent output for the above example would be 0x0050 MOVLW OxFF 0x0051 MOVLB 0x1 Patched with varl s bank 0x0052 MOVWF 0x25 Patched with varl s offset 1994 2013 Microchip Technology Inc DS33014L page 253 Assembler Linker Librarian User s Guide 12 5 INITIALIZED DATA MPLINK linker performs special processing for input sections with initialized data Initialized data sections contain initial values initializers for the variables and constants defined within them Because the variables and constants within an initialized data section reside in RAM thei
225. formation This option is only supported on devices that support extended mode The checkbox for Enable extended instruction set must be checked as well See the previous row in this table TABLE 1 9 ADDITIONAL CONTROLS Option Description Additional Options Enter additional command line options See the tool documentation for more options Option Description Click on option text to see more information in this tab if available Generated Command For selectable options click this tab to see the equivalent command line option Line MPLAB C18 Setup for PIC18 Extended Instruction Set Use To use the PIC18 MCU Extended Instruction set in your MPLAB C18 project do the following Enable Extended Instruction Set in the configuration bits by doing one of the following Incode use CONFIG XINST ON In the Configurations Bits window under XINST select Enabled Select File gt Project Properties click on C18 and check Enable extended instruction set Click OK For a list of available instructions in the Extended Instruction set see Section A 9 PIC18 Device Extended Instruction Set MCC18 Although the MPLAB C18 C compiler works with MPLAB X IDE it must be acquired separately The standard version may be purchased or a free limited feature version may be downloaded See the Microchip website www microchip com for details This compiler supports PIC18X MCU devices
226. ge This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation Use this directive to prematurely end a macro usually for a specific condition This is similar to the C language command break 4 314 See Also endm macro 4 31 5 Simple Example test macro filereg if filereg 1 check for valid file exitm else error bad file assignment endif endm 4 31 6 Application Example exitm This program demonstrates the exitm assembler directive which causes an immediate exit from a macro It is used in the example to exit from the macro when certain conditions are met finclude p16f877a inc Include standard header file for the selected devic result equ 0x20 Assign value 20H to label result RST CODE 0x0 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST pagesel start Jumps to the location labelled goto start ne stant add MACRO numl num2 add is a macro The values of numl and num2 must be passed to this macro O 1994 2013 Microchip Technology Inc DS33014L page 111 Assembler Linker Librarian User s Guide if numl gt 0xff exitm else if num2 gt 0xff exitm else movlw numl movwf result moviw num2 addwf result endif endif endm org 0010 start add 100 256 end If num1 5255 decim
227. generate a look up table entry for each byte specified in an idata section You must then link or include the appropriate initialization code Examples of initialization code that may be used and modified as needed may be found with MPLINK linker sample application examples The res db and dw directives may be used to reserve space for variables res will generate an initial value of zero db will initialize successive bytes of RAM dw will initialize successive bytes of RAM one word at a time in low byte high byte order 4 37 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation Use this directive to initialize your variables or use a udata directive and then initialize your variables with values in code It is recommended that you always initialize your variables Relying on RAM initialization can cause problems especially when using an emulator as behavioral differences between the emulator and the actual part may occur 4 37 4 See Also extern global udata udata_acs udata_ovr udata_shr 4 37 5 Simple Example idata_acs LimitL dw 0 LimitH dw D 300 Gain dw D 5 Flags db 0 String db Hi there DS33014L page 122 1994 2013 Microchip Technology Inc Directives 4 38 _ idlocs SET PROCESSOR ID LOCATIONS Note idlocs is preceded by two underline characters 4 38 1 Syntax __idlocs expr __idlocs addr expr PIC1
228. ges In these cases it is necessary to perform proper bank and page set up to properly access the labels However since the absolute addresses of these variable and address labels may not be known at assembly time it is not always possible to place the proper code in the source file For these situations two directives banksel 4 7 banksel Generate Bank Selecting Code and pagesel 4 53 pagesel Generate Page Selecting Code PIC10 12 16 MCUs have been added These directives instruct the linker to generate the correct bank or page selecting code for a specified label An example of how code should be converted is shown below EXAMPLE 6 8 BANKSEL AND PAGESEL Hard Coded Banking and Paging Use indirect addressing FSR and the Status register for banking and paging respectively include p12f509 inc Varl equ 0x10 Declare variables Var2 equ 0x30 movlw InitialValue bcf FSR 5 Data memory Varl bank 0 movwf Varl bsf FSR 5 Data memory Var2 bank 1 movwf Var2 bsf STATUS PAO Program memory page 1 call Subroutine Subroutine clrw On Page 1 retlw O0 BANKSEL for Banking and PAGESEL for Paging Use banksel and pagesel for banking and paging respectively finclude p12f509 inc extern Varl Var2 Declare variables code moviw InitialValue banksel Varl Select data memory Varl bank movwf Varl banksel Var2 Select data memory Var2 bank movwf Var2 pagesel Subroutine Select program memory page call Subrou
229. gh Byte Low Byte HEX 1000 Dec HEX 100 Dec HEX 10 Dec HEX 1 Dec 0 0 0 0 0 0 0 0 1 4096 1 256 1 16 1 1 2 8192 2 512 2 32 2 2 3 12288 3 768 3 48 3 3 4 16384 4 1024 4 64 4 4 5 20480 5 1280 5 80 5 5 6 24576 6 1536 6 96 6 6 7 28672 7 1792 7 112 7 7 8 32768 8 2048 8 128 8 8 9 36864 9 2304 9 144 9 9 A 40960 A 2560 A 160 A 10 B 45056 B 2816 B 176 B 11 C 49152 C 3072 C 192 C 12 D 53248 D 3328 D 208 D 13 E 57344 E 3584 E 224 E 14 F 61440 F 3840 F 240 F 15 For example HEX A38F converts to 41871 as follows HEX 1000 s Digit HEX 100 s Digit HEX 10 s Digit HEX 1 s Digit Result 40960 768 128 15 41871 Decimal DS33014L page 330 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Index Symbols nn dat e den bi pre P ei b dda 63 We TEEN 75 TUE UP PR 63 badrom SM SO EM MERE RU Pom REOR REED PET 76 h AEREA AA AAA AAA AEREA A A ARE 63 config EE 86 195 l EPEE ea AAA AAA ROG AIRE 64 ENEE 86 WEED 64 NM ANA 123 195 Le WEE 64 EU EE 136 A E 64 ED o cT 137 eH LEE 64 _CRUNTIME A OIE ENIE eo Byam e name Ra 246 gea 64 DEBUG dw xat AS ted iP oa diac OA UIT Usos usto fT 246 LEE 64 _DEBUGCODELEN AER A 246 t WS Eed AA IAS 64 DEBUGCODESTART see 246 aM EE 64 _DEBUGDATALEN eene 246 y AE EEE ad LEM icu Ael RS DE TREES SEPT OT 64 _DEBUGDATASTART mere 246 Vanne tien tin nement 64 ESTENDEDMODE seen 246 B Bue il SE 256 SE CTP QE 21 37 deba ER PERPE ERU A ARS A A Ant nn D 75 ee 21 37 SE en
230. ging it is recommended that labels start in column one and mnemonics start in column two or beyond Operands follow the mnemonic Comments may follow the operands mnemonics or labels and can start in any column The maximum column width is 255 characters White space or a colon must separate the label and the mnemonic and white space must separate the mnemonic and the operand s Multiple operands must be separated by commas White space is one or more spaces or tabs White space is used to separate pieces of a source line White space should be used to make your code easier for people to read Unless within character constants any white space means the same as exactly one Space AAA AAA n c 99 s AE DS33014L page 52 1994 2013 Microchip Technology Inc MPASM Assembler Overview EXAMPLE 1 1 ABSOLUTE MPASM ASSEMBLER SOURCE CODE SHOWS MULTIPLE OPERANDS Mnemonics Directives Labels Macros Operands Comments l l l l list p 18f452 include p18f452 inc Dest equ 0x0B Define constant org 0x0000 Reset vector goto Start org 0x0020 Begin program Start movlw 0x0A movwf Dest bcf Dest 3 This line uses 2 operands goto Start end 1 7 1 1 LABELS A label is used to represent a line or group of code or a constant value It is needed for branching instructions Example 1 1 Labels should start
231. goto Go to current line loop here ORG 0x1000 Store the string starting from 1000H Ch stng da PICmicro DS33014L page 90 1994 2013 Microchip Technology Inc Directives Directive da produces four 14 bit numbers 2849 21ED 34E3 and 396F representing the ASCII equivalent of Pl Cm ic and ro See below for more information Sngl_ch da A 77 bit ASCII equivalents of A and a NULL character will be packed in a 14 bit number da Oxff55 Places 3f55 in program memory No packing end Determining 14 Bit Numbers For the following statement Ch_stng da PICmicro directive da produces four 14 bit numbers 2849 21ED 34E3 and 396F representing the ASCII equivalent of Pl Cm ic and ro To see how the 14 bit numbers are determined look at the ASCII values of P and I which are 50h 01010000 and 49h 01001001 respectively Each is presented in 7 bit as 0 1010000 and 0 1001001 respectively The packed 14 bit number is 101000 01001001 which is stored as 00 101000 01001001 or 2849 A A a a IiealA c S A i E AA O 1994 2013 Microchip Technology Inc DS33014L page 91 Assembler Linker Librarian User s Guide 4 15 data CREATE NUMERIC AND TEXT DATA 4 15 4 Syntax label data expr expr expr label data text string text string 4 15 2 Description Initialize one or mor
232. goto main Our sample main is just an infinite loop service Interrupt routine called from example2 asm global service Define as global so can be used in example2 asm nop Interrupt code would go here nop retfie IDLOCS CODE ID location data address is in 16 877 1kr dw 0x0102 dw 0x0304 CONBITS CODE Set config bits from defines in p16f877 inc Config address for device programmer is in 16 877 1kr dw LP OSC amp PWRTE OFF amp WDT OFF CP OFF end DS33014L page 28 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB X IDE example2 asm File example2 asm This is the second file in the MPASM assembler MPLINK linker example Use with example asm finclude p16f877 inc extern main service These routines are in Example asm STARTUP CODE This area is defined in 16f877 1kr the linker script goto main Jump to main code defined in example asm nop Pad out so interrupt service routine gets nop put at address 0x0004 nop goto service Points to interrupt service routine end Set Build Options Select File gt Project Properties or right click on the project name and select Properties to open the Project Properties dialog 1 2 Under default MPASMX select MPASMX Select General from the Option Categories Ensure that the Default Radix is Hex Select Output from the Option Categories Ensu
233. gram memory location end 4 16 7 PIC18 Application Example db This example shows the usefulness of directive db in storing one or more byte or character in program memory finclude p18f452 inc Include standard header file for the selected devic ORG 0x0000 The following code will be programmed in reset address O0 goto start Jump to an address labelled Ae SCALE wa start Write your main program here goto Go to current line loop here ORG 0x1000 Store the string starting from 1000H In PIC18 devices the first character is in least significant byte Ch stng db M C U Ch strng contains three 16 bit numbers 004Dh 0043h and 0055h These are ASCII equivalents of M C and U respectively Information on storing data in both bytes of a program word on the PIC18 architecture can be found under the code pack directive tbl dta db 0 0xff Places ff00 in program memory location end Section 4 10 code pack Begin an Object File Packed Code Section PIC18 MCUs A nz DM QRQ 0 ey O 1994 2013 Microchip Technology Inc DS33014L page 95 Assembler Linker Librarian User s Guide 4 17 de DECLARE EEPROM DATA BYTE 4 17 4 Syntax label de expr expr expr 417 2 Description de Data EEPROM This directive can be used at any location for any processor For PIC18 devices reserve memory word bytes are packed Ifan odd number of bytes is specified a O will
234. gram memory section must be contiguous within a single source file A section may not be broken into pieces within a singe source file The physical address of the code can be fixed by supplying the optional address parameter of the code directive Situations where this might be necessary are Specifying Reset and interrupt vectors Ensuring that a code segment does not overlap page boundaries EXAMPLE 6 2 RELOCATABLE CODE Reset code OxOlFF Fixed address goto Start Pgm code Address determined by the linker clrw option DS33014L page 190 1994 2013 Microchip Technology Inc Relocatable Objects 6 4 LOW HIGH AND UPPER OPERATORS Low high and upper operators are used to return one byte of a multi byte label value If low is used only bits 0 through 7 of the expression will be used If high is used only bits 8 through 15 of the expression will be used If upper is used only bits 16 through 21 of the expression will be used Operator Definition low Return low byte of operand high Return high byte of operand upper Return upper byte of operand scnsz low Return low byte of section size scnsz high Return high byte of section size scnsz upper Return upper byte of section size scnend low Return low byte of section end operand scnend high Return high byte of section end operand scnend upper Return upper byte of section end operand scnstart low Return low byte of section start
235. gs Text Box Enter options in a command line non GUI format Output Category Generate Command Line Diagnostics level Select to display errors only errors and warnings or errors warnings and messages These will be shown in the Output window Generate cross reference file Create an cross reference file A cross reference file contains a listing of all symbols used in the assembly code Hex file format for single file assemblies When assembling a single file the assembler may be used to generate a hex file Choose the format here When assembling multiple files the assembler generates object files which must be linked with the linker to generate a hex file Choose the hex file format for the linker in this case Restore Defaults Restore tab default settings Use Alternate Settings Text Box Enter options in a command line non GUI format DS33014L page 38 O 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB IDE v8 Build Options Dialog MPLAB C17 Tab If Installed Although the MPLAB C17 C compiler works with MPLAB IDE it is no longer sold or supported See the Microchip website www microchip com for details Note PIC17C MCUs are end of life devices Consider migrating to PIC18X MCU devices A subset of command line options may be specified in MPLAB IDE in the Build Options dialog MPLAB C17 tab Select a category a
236. he target PIC microcontroller is responsible for downloading and programming relocatable application code into the same target PIC microcontroller The relocatable application or user code is typically transferred to the boot loader through serial communications such as RS232 13 5 1 C Compiler Usage This section discusses how to use the MPLAB C Compiler for PIC18 MCUs the C compiler when developing bootloader and related appliation code There are three examples showing how to modify the C compiler linker scripts and how to use the pragma code directive in the source code for the C compiler boot loader project To better understand how the code corresponds to locations in device program memory see 13 5 1 1 C Compiler Memory Map Example 1 shows how to configure the C compiler linker script and suggests how to use code directives for the C compiler boot loader See 13 5 1 2 Example 1 C Compiler Boot Loader Example 2 shows the C compiler linker script configuration and suggested code directives for the C compiler application targeted for a microcontroller that is running the C compiler boot loader See 13 5 1 3 Example 2 C Compiler Application Example 3 is a mixed language example using the C compiler application targeted for a microcontroller such as the PIC18F8720 with a limited boot block size running an MPASM boot loader A boot loader written in C code will typically require more program memory than a boot l
237. hes hae ee ee 67 Flia ata ake ache 148 Radix Sel z 3 coena ne mien 131 148 171 RAM Allocation 194 RAM Memory Regions Defining 239 Reading Recommended sss 13 Register Assignments 175 relocatable issue tinca 59 Relocatable Code Generating 50 Relocatable Objects 189 gc Mcd 150 Reserved Section Names Assembler 67 Reserved Words Assembler 67 ROM Memory Regions Defining 243 S Sample Applications Linker 255 Scripts Linker 2 245 235 Search Order Include Files 130 SECTION oia 239 244 SOL ee ed e o eee t ete nee 152 Set Program Origin seeee 141 SHAREBANK e 239 244 Simple eR REG ee er dieta 75 76 Source Code ere 21 37 Source Code File Assembly 52 SAC ciere bent eoe 153 SLACK iouis eet d e er te t coss aae Seed es 244 STAOKSIZE id reete iin 244 Standard Linker Scripts 236 Store Strings in Program Memory 90 subtitle oeste torte eU 153 Symbol Constant 89 Symbols In Expressions 69 T Table Define nar ioter eed fa ceci dana didas 100 Temiplates diner eee te jede ode eres 261 Text Strings re EH eitis 65 Text Substitution Label 98 Tips and Tricks Bit Shifting Using Carry Bi
238. hip Memory STARTUP 0x01FFFF PROG Main Application Code gt 0x020000 eeprom External Memory INTHAND Interrupt Handler Ox1FFFFF DATTBL Data Table 0x200000 idlocs ID Locations 0x200007 gt 0x300000 config Configuration Bits CONFIG Configuration Settings 0x30000D Ox3FFFFE devid Device ID Ox3FFFFF OxF00000 eedata EE Data OxFOO3FF DS33014L page 264 1994 2013 Microchip Technology Inc Sample Applications 13 4 1 C Source Code eeprom1 c eeproml c include lt p18f8720 h gt define DATA SIZE 0x1000 Data Table Setup pragma romdata DATTBL Put following romdata into section DATTBL unsigned rom data DATA SIZE pragma romdata Set back to default romdata section Configuration Bits Setup The pragma config directive specifies the processor specific configuration settings i e configuration bits to be used by the application For more on this directive s the MPLAB C18 C Compiler User s Guide DS51288 pragma config OSCS ON OSC LP Enable OSC switching and LP pragma config PWRT ON Enable POR pragma config BOR ON BORV 42 Enable BOR at 4 2v pragma config WDT OFF Disable WDT pragma config MODE EM Use Extended MCU mode Main application code for default CODE section void main void while 1 end while end main 13 4 2 Assembler Source Code eeprom2 asm e
239. hip Technology Incorporated in the U S A Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries Analog for the Digital Age Application Maestro BodyCom chipK IT chipKIT logo CodeGuard dsPICDEM dsPICDEM net dsPlCworks dsSPEAK ECAN ECONOMONITOR FanSense HI TIDE In Circuit Serial Programming ICSP Mindi MiWi MPASM MPF MPLAB Certified logo MPLIB MPLINK mTouch Omniscient Code Generation PICC PICC 18 PICDEM PICDEM net PICkit PICtail REAL ICE rfLAB Select Mode SQI Serial Quad I O Total Endurance TSHARC UniWinDriver WiperLock ZENA and Z Scale 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 GestlC and ULPP are registered trademarks of Microchip Technology Germany Il GmbH amp Co KG a subsidiary of Microchip Technology Inc in other countries All other trademarks mentioned herein are property of their respective companies O 1994 2013 Microchip Technology Incorporated Printed in the U S A All Rights Reserved G Printed on recycled paper ISBN 978 1 62077 002 3 Microchip received ISO TS 16949 2009 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 i
240. ile format Choose the linker hex file format ahex format Library directories Browse to the path s of any libraries you want the linker to include 1 lib in the output Manage the list of paths in the dialog TABLE 1 7 ADDITIONAL CONTROLS Option Description Additional Options Enter additional command line options See the tool documentation for more options Option Description Click on option text to see more information in this tab if available Generated Command For selectable options click this tab to see the equivalent command line option Line ILLE A a a J 1994 2013 Microchip Technology Inc DS33014L page 23 Assembler Linker Librarian User s Guide C18 TOP The top level of the C18 toolchain contains the following options TABLE 1 8 ALL OPTIONS CATEGORY Option Description Command Line Enable extended Build in extended mode The selected device must support extended instruction set extended mode and the correct configuration bit must be enabled no extended See MPLAB C18 Setup for PIC18 Extended Instruction Set Use Enable stack analysis Generate a stack analysis report for use with third party application g Understand from Scientific Toolworks Inc See their web site at www scitools com for more in
241. iles see MPASM assembler documentation All device linker script 1 kx files are in the LKR subdirectory For more on these files see MPLINK object linker documentation Code examples and template files are included in the Template subdirectory Template files are provided for absolute code Code and relocatable code Object development Code examples are also included in the Example subdirectory 1994 2013 Microchip Technology Inc DS33014L page 33 Assembler Linker Librarian User s Guide C18 Toolsuite Installation The MPLAB C18 compiler and related tools must be acquired from Microchip standard lite and evaluation versions available The install includes the MPLAB C18 C compiler and compiler versions of tools in the MPASM Toolsuite The language tools will be installed by default in the directory e C Program Files Microchip mplabc18 version where version is the version of the compiler The executables for each tool will be MPLAB C18 C Compiler bin mcc18 exe e MPASM Assembler mpasm mpasmwin exe e MPLINK Object Linker bin mplink exe e MPLIB Object Librarian bin mplib exe Other Utilities bin subdirectory All device header h files are in the n subdirectory For more on these files see MPLAB C18 documentation All device include inc files are in the mpasm subdirectory For more on these files see MPASM assembler documentation All device linker script 1kr files are in the b
242. ill begin at address zero For PIC18 devices only even numbered expr values are allowed When generating an object file the org directive is interpreted as introducing an absolute CODE section with an internally generated name For example L1 org 0x200 is interpreted as Scnname CODE 0x200 L1 where scnname is generated by the assembler and will be distinct from every name previously generated in this context 4 51 3 Usage This directive is used in the following types of code absolute For information on types of code see Section 1 6 Assembler Operation org is commonly used in single file assembly programs whenever code needs to be placed at a particular location Commonly used values are 0x0 reset 0x4 PIC16 device interrupt vector 0x8 PIC18 device high priority interrupt vector and 0x18 PIC18 device low priority interrupt vector 4 51 4 See Also fill res end 4 51 5 Simple Example int 1 org 0x20 Vector 20 code goes here int 2 org int 1 0x10 Vector 30 code goes here O 1994 2013 Microchip Technology Inc DS33014L page 141 Assembler Linker Librarian User s Guide 4 51 6 PIC16 Application Example org This example shows the usage of the org directive Code generation begins at an address specified by org address The origin of a data table also can be specified by this directive A data table may be placed either in a program memory region or in an EE data memory region as in case of
243. in LKR subdirectory For more on these files see MPLINK object linker documentation All device library 1ib files and precompiled start up code o are in the lib subdirectory For more on these files see MPLAB C18 libraries documentation Code examples are also included in the example subdirectory DS33014L page 34 O 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB IDE v8 MPLAB IDE SETUP Once MPLAB IDE is installed on your PC check the settings below to ensure that the language tools are properly recognized under MPLAB IDE 1 From the MPLAB IDE menu bar select Project gt Set Language Tool Locations to open a dialog to set check language tool executable location FIGURE 1 SET LANGUAGE TOOL LOCATIONS Set Language Tool Locations E xj m Registered Tools Microchip C17 Toolsuite Microchip C18 Toolsuite E Microchip C30 Toolsuite E Microchip MPASM Toolsuite E Executables MPASM Assembler mpasmwin exe MPLIB Librarian mplib exe MPLINK Object Linker mplink exe E Default Search Paths amp Directories E microEngineering PicBasic Pro Toolsuite E microE ngineering PicBasic T oolsuite e Location C Program Files MPLAB IDEAMCHIP_T oolsimpasmwin exe Browse Help OK Cancel Apply 2 Inthe dialog under Registered Tools select Microchip MPASM Toolsuite Click the to expand 3 Select Executables Click the
244. in column 1 They may be followed by a colon space tab or the end of line Labels must not begin with number Labels may be up to 32 characters long By default they are case sensitive but case sensitivity may be overridden by a command line option c or c If a colon is used when defining a label it is treated as a label operator and not part of the label itself 1 7 1 2 MNEMONICS DIRECTIVES AND MACROS Mnemonics tell the assembler what machine instructions to assemble For example addition add branches goto or moves movw Unlike labels that you create yourself mnemonics are provided by the assembly language Mnemonics are not case sensitive Directives are assembler commands that appear in the source code but are not usually translated directly into opcodes They are used to control the assembler its input output and data allocation Directives are not case sensitive Macros are user defined sets of instructions and directives that will be evaluated in line with the assembler source code whenever the macro is invoked Assembler instruction mnemonics directives and macro calls should begin in column two or greater If there is a label on the same line instructions must be separated from that label by a colon or by one or more spaces or tabs 1 7 1 8 OPERANDS Operands give information to the instruction on the data that should be used and the storage location for the instruction Operands must be separated f
245. in the key or as a footnote For more information on the opcode bit values for each instruction as well as the number of cycles per instruction status bits affected and complete instruction details see the relevant device data sheet TABLE A 7 14 BIT BYTE ORIENTED FILE REGISTER OPERATIONS Hex Mnemonic Description Function O7df ADDWF f d Add W and f W f gt d 3Ddf ADDWFC f d Add with Carry W and f W f C gt d 05df ANDWF f d AND W with f WAND f d 37df ASRE f d Arithmetic Right Shift register f msb gt C 35df LSLE f d Logical Left Shift register f C a pP 0 ra 0 36df LSRE f d Logical Right Shift register f 0 y NR 0 Le C 01 1 f CLRF f Clear f 0f 01xx CLRW Clear W 0 gt W 09df COMF f d Complement f NOT f gt d 03af DECF f d Decrement f f 1 gt d OAdf INCF f d Increment f f 1 gt d 04df IORWF f d Inclusive OR W with f W OR f gt d REISE MOVE f d Move f fod 00 1 f MOVWE f Move W to f Wf ODdf RLF f d Rotate left f register f C ra Tersus 0 ra 0Cdf RRF f d Rotate right f register f E C gt Tesis 0 O 1994 2013 Microchip Technology Inc DS33014L page 317 Assembler Linker Librarian User s Guide
246. include p16f877a inc Include standard header file for the selected devic ORG 0x0000 The following code will be programmed in reset address 0 goto start Jump to an address labelled p statt start Write your main program here goto Go to current line loop here ORG 0x1000 Store the string starting from 1000H Ch stng data M C U 3 program memory locations will be filled with ASCII equivalent of M C and d ng A DS33014L page 92 1994 2013 Microchip Technology Inc Directives Directive data produces three 14 bit numbers 004Dh 0043h and 0055h 4Dh 43h and 55h are ASCII equivalents of M C and U respectively tbl dta data Oxffff 0xaa55 Places 3fffh and 2a55h in two consecutive program memory locations As program memory is 14 bit wide the last nibble can store a maximum value 3 end 4 15 7 PIC18 Application Example data This example shows the usefulness of directive data in storing one or more words in program memory include p18f452 inc Include standard header file for the selected devic ORG 0x0000 The following code will be programmed in reset address 0 goto start Jump to an address labelled A Start start Write your main program here goto Go to current line loop here ORG 0x1000 Store the string starting from 1000H In PIC18 devices the first character is in least Significant byte Ch stng data M C U
247. information on types of code see Section 1 6 Assembler Operation This directive is not an instruction but used to control how code is assembled not how it behaves at run time Use this directive for conditional assembly or to check for a condition such as to generate an error message 4 39 4 See Also else endif 4 39 5 Simple Example if version 100 check current version moviw 0x0a movwf io 1 else moviw 0x0la movwf io 2 endif O 1994 2013 Microchip Technology Inc DS33014L page 125 Assembler Linker Librarian User s Guide 4 39 6 Application Example if else endif This program demonstrates the utility of if else and endif assembly directives include p16f877a inc variable cfab cfab set 1 RST CODE 0x0 pagesel start goto start PGM CODE start banksel TRISA if cfab 0x0 clrw movwf TRISA moviw Oxff movwf TRISB else clrw movwf TRISB moviw Oxff movwf TRISA endif goto end Include standard header file for the selected devic variable used to defin required configuration of PORTA PORTB Set config to decimal 1 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST Jumps to the location labelled 7 Stank This is the beginning of the code section named PGM It is a relocatable code section since no absolute address is given along with directive
248. ing the order of directories may change which file is selected The o or o option is used to supply the name of the generated output COFF file for the IDE debugging Also generated is an Intel format hex file for programming This file has the same name as the output COFF file but with the file extension hex If this option is not supplied the default output COFF file is named a out and the corresponding hex file is named a hex O 1994 2013 Microchip Technology Inc DS33014L page 233 Assembler Linker Librarian User s Guide 10 4 COMMAND LINE EXAMPLE An example of an MPLINK linker command line is shown below Windows OS mplink myscript lkr p18f452 main o funct o math lib m main map o main out Linux or Mac OS mplink myscript lkr p18f452 main o funct o math lib m main map o main out This instructs MPLINK linker to use the myscript 1kr linker script file to link the input modules main o funct o and the precompiled library math 1ib It also instructs the linker to produce a map file named main map main o and funct o must have been previously compiled or assembled The output files main cof and main hex will be produced if no errors occur during the link process The project applies to a PIC18F452 device DS33014L page 234 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 11 Linker Scripts INTRODUCTION Linker script files are used by the linker to generate a
249. ing types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation You should use the include directive once to include that standard header file for your selected processor This file contains defined register bit and other names for a specific processor so there is no need for you to define all of these in your code 4 42 4 See Also define undefin 4 42 5 Simple Example include p18f452 inc standard include file include c Program Files mydefs inc user defines EE EE EE DS33014L page 130 O 1994 2013 Microchip Technology Inc Directives 4 43 list LISTING OPTIONS 4 43 1 Syntax list list option list option 4 43 2 Description Occurring on a line by itself the list directive has the effect of turning listing output on if it had been previously turned off Otherwise one of a list of options can be supplied to control the assembly process or format the listing file 4 43 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation TABLE 4 2 LIST DIRECTIVE OPTIONS Option Default Description b nnn 8 Set tab spaces c nnn 132 Set column width f format INHX8 Set the hex file output format can be INHX32 INHX8M or M INHX8S Note Hex file format is set in the IDE Build Options dialog free FIXED Use free fo
250. inker Librarian User s Guide 5 9 TIPS AND TRICKS To reduce costs designers need to make the most of the available program memory in MCUs Program memory is typically a large portion of the MCU cost Optimizing the code helps to avoid buying more memory than needed Here are some ideas that can help reduce code size For more information see Tips n Tricks DS40040 TIP 1 Delay Techniques TIP 2 Optimizing Destinations TIP 3 Conditional Bit Set Clear TIP 4 Swap File Register with W TIP 5 Bit Shifting Using Carry Bit TIP 6 Using External Memory 5 9 1 TIP 1 Delay Techniques Use GOTO Next Instruction instead of two NOPs e Use CALL Rtrn as quad 1 instruction NOP where Rt rn is the exit label from existing subroutine pOCKCKCk kk KE K KR KK KK KER KKK KKK RK KEKE RK UK UK UK RK KARR KK KKK NOP NOP 2 instructions 2 cycles PRRRKRREKKKR RK KKK KKK KEE HAE ke KK hock ko kc ke koc ke kc kk koe koc kk ke KKK GOTO 41 l instruction 2 cycles pORCECKCk kc kckckckckokokockockockock koc k KKK KK RK KEKE RK koc ke ko ke heck ko ke hok KEK KKK Call Rtrn l instruction 4 cycles Rtrn RETURN PRRRKEKK EEK KR KK KEK KER KKK KKK RK KK KK RR KEK KEK KKK EK KEK KKK MCUs are commonly used to interface with the outside world by means of a data bus LED s buttons latches etc Because the MCU runs at a fixed frequency it will often need delay routines to meet setup hold times of other devices
251. inker script See the data sheet for the PIC16F873A for a specific example 4 65 4 See Also extern global idata udata udata_acs udata_ovr 4 65 5 Simple Example Temps udata_shr Templ res 1 Temp2 res 1 Temp3 res 1 4 65 6 Application Example udata_shr This program demonstrates the udata_shr directive This directive declares the beginning of a section of shared uninitialized data This directive is used to declare variables that are allocated in RAM that is shared across all RAM banks i e unbanked RAM finclude p16f877a inc Include standard header file for the selected device shared data udata shr Declares the beginning of a data section named shared data var res 1 which is shared by all banks var is the location which can be accessed irrespective of banksel bits bank0 var udata 0X20 Declares beginning of a data var0 res 1 section named bank0_var which is in bank0 var is allocated the address 0x20 DS33014L page 160 1994 2013 Microchip Technology Inc Directives bankl var udata Oxa0 Declares beginning of a data varl res 1 section named bankl var which is in bankl varl is allocated the address 0xa0 bank2 var udata 0x120 Declares beginning of a data var2 res 1 section named bank2 var which is in bank2 var2 is allocated the address 0x120 bank3 var udata 0x1a0 Declares beginning of a data var3 res 1 section named bank3 var which is in
252. ion for PORTB endif banksel MyTris clerk MyTris Set port to all outputs banksel MyPort Return to bank used for port movlw 55h Move arbitrary value to W reg movwf MyPort Load port selected with 55h end ILLE SS OOo0uw0 M f n 1994 2013 Microchip Technology Inc DS33014L page 129 Assembler Linker Librarian User s Guide 4 42 include INCLUDE ADDITIONAL SOURCE FILE 4 42 1 Syntax Preferred include include file include include file include include file gt Supported include include file include include file include lt include file gt 4 42 2 Description The specified file is read in as source code The effect is the same as if the entire text of the included file were inserted into the file at the location of the include statement Upon end of file source code assembly will resume from the original source file Up to 5 levels of nesting are permitted Up to 255 include files are allowed If include file contains any spaces it must be enclosed in quotes or angle brackets If a fully qualified path is specified only that path will be searched Otherwise the search order is current working directory source file directory MPASM assembler executable directory 4 42 3 Usage This directive is used in the follow
253. ipt file device 1kr for your project For more information on using linker script files and the linker see the MPLINK linker documentation The main output file generated by the MPLINK linker is the COF file prog cof The linker then uses the utility MP2HEX to generate the Hex file prog hex used by simulators emulators debuggers and programmers For more information on linker output files see the MPLINK linker documentation For more information on utilities see the related documentation For more on projects see MPLAB X IDE documentation 1994 2013 Microchip Technology Inc DS33014L page 21 Assembler Linker Librarian User s Guide PROJECT SETUP To set up an MPLAB X IDE project for the first time use the built in Project Wizard File gt New Project In this wizard you will be able to select a language toolsuite For more on the wizard and MPLAB X IDE projects see MPLAB X IDE documentation Once you have a project set up you may then set up properties of the tools in MPLAB X IDE 1 Fromthe MPLAB X IDE menu bar select File gt Project Properties to open a dialog to set check project build options 2 MPASM For Conf default gt MPASMX select a tool from the tool collection to set up a MPASM TOP b MPASM c MPLINK 3 MPLAB C18 For Conf default gt C18 select a tool from the tool collection to set up a C18 TOP MPASM MCC18 MPLINK a0 aS MPASM TOP The
254. irective may not be reassigned later perimeter set 2 lngth wdth Both perimeter and area set Ingth wdth area values are reassigned end EE EE DS33014L page 152 O 1994 2013 Microchip Technology Inc Directives 4 59 space INSERT BLANK LISTING LINES 4 59 1 Syntax Preferred space expr Supported spac expr 4 59 2 Description and Usage Insert expr number of blank lines into the listing file This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation 4 59 3 See Also list 4 59 4 Simple Example space 3 Inserts three blank lines 4 60 subtitle SPECIFY PROGRAM SUBTITLE 4 60 1 Syntax Preferred subtitle sub_text Supported stitle sub_text subtitl sub text 4 60 2 Description and Usage sub textis an ASCII string enclosed in double quotes 60 characters or less in length This directive establishes a second program header line for use as a subtitle in the listing output This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation 4 60 3 See Also list title 4 60 4 Simple Example subtitle diagnostic section 1994 2013 Microchip Technology Inc DS33014L page 153 Assembler Linker Librarian User s Guide 4 61 title SPECIFY PROGRAM TITLE 4 61 1 Syntax title ttle text 4 61
255. is designed for use with the badrom directive Once the maxrom directive is used strict ROM address checking is enabled using the ROM map specified by badrom maxrom can be used more than once in a source file Each use redefines the maximum valid ROM address and resets the ROM map to all locations 4 47 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is not commonly used in user code as RAM and ROM details are handled by the include files inc or linker script files 1 kx 4 474 See Also badrom 4 47 5 Simple Example See the examples for badrom 1994 2013 Microchip Technology Inc DS33014L page 137 Assembler Linker Librarian User s Guide 4 48 messg CREATE USER DEFINED MESSAGE 4 48 1 Syntax messg message_text 4 48 2 Description Causes an informational message to be printed in the listing file The message text can be up to 80 characters Issuing a messg directive does not set any error return codes 4 48 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive may be used to generate any desired message It can be useful with conditional assembly to verify in the assembled program which code was built 4 48 4 See Also error 4 48
256. is used by simulators emulators debuggers and programmers FIGURE 18 1 UTILITIES OPERATION LINKER output file Utility output files 1994 2013 Microchip Technology Inc DS33014L page 305 Assembler Linker Librarian User s Guide 18 4 MP2HEX EXE UTILITY Use this utility to take the MPLINK linker output COF file and create a Hex file A Hex file contains no debug information but may be programmed directly into a device The MPLINK linker x or x option will result in the linker not using this utility 18 5 MP2COD EXE UTILITY Use this utility to take the MPLINK linker output COF file and create a COD file and a list file A COD file is a legacy debug file that is no longer used A list file generated by this utility is specific to the linker see Section 9 7 6 Listing File Ist The MPLINK linker w or w option will result in the linker not using this utility EEE EEE 9 E s s J J st Qu ae DS33014L page 306 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 19 Errors and Warnings INTRODUCTION Error messages and warning messages are produced by the 8 bit utilities These messages always appear in the listing file directly above each line in which the error occurred Hex File Errors COFF To COD Conversion Errors COFF
257. isassembly window View gt Disassembly in MPLAB IDE v8 or Window Debugging Disassembly in MPLAB X IDE The MPLINK linker uses the mp2cod exe utility to generate the linker list file from the COF file To prevent linker list file generation use the w or w option ARON 1994 2013 Microchip Technology Inc DS33014L page 227 Assembler Linker Librarian User s Guide EXAMPLE 9 1 MPLINK LINKER LISTING FILE The MP2COD utility version and list file generation data appear at the top of each page The first column contains the base address in memory where the code will be placed The second column is reserved for the machine instruction This is the code that will be executed by the PIC MCU The third column displays disassembly code The fourth column lists the associated source code line The fifth column lists the file associated for the source code line Note Dueto page width restrictions some comments have been shortened indi cated by Also associated file names have been replaced by numbers i e 1 and 2 See the end of the listing of the actual file paths and names MP2COD 3 80 03 COFF to COD File Converter Copyright c 2004 Microchip Technology Inc Listing File Generated Tue Nov 02 14 33 23 2004 Address Value Disassembly Source File include p18f452 inc 1 LIST 2 P18F452 1NC Standard Header File 2 LIST 2 udata 1 Dest res 1 1 1 RST code 0x0 1
258. it must be set bankisel will set it but only where it is used movlw EEADR W Put the address of the register to be accessed indirectly into W movwf FSR Copy address from W to FSR to set up pointer to EEADR clrf INDF Clear EEADR through indirect accessing of EEADR through FSR INDF It would have cleared PIR2 00Dh if bankisel had not been used to set the IRP bit goto Prevents fall off end of code end All code must have an end statement DELI c J X d ET O 1994 2013 Microchip Technology Inc DS33014L page 79 Assembler Linker Librarian User s Guide 4 7 banksel GENERATE BANK SELECTING CODE 4 7 1 Syntax banksel label 4 7 2 Description This directive is an instruction to the assembler and linker to generate bank selecting code to set the bank to the bank containing the designated 1a5e1 Only one label should be specified No operations can be performed on 1abe1 This label must have been previously defined The linker will generate the appropriate bank selecting code For 12 bit instruction width PIC10F some PIC12 PIC16 devices the appropriate bit set clear instructions on the FSR will be generated For 14 bit instruction width most PIC12 PIC16 devices bit set clear instructions on the STATUS regi
259. itialized to the specified address or will be assigned at link time if no address is specified The space declared by this section is overlayed by all other access ovr sections of the same name No code can be placed by the user in this segment 4 3 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation access ovr is similar to udata acs and udata ovr except that it declares a PIC18 Access RAM uninitialized data section that can be overlayed with other overlay access sections of the same name Overlaying access sections allows you to reuse access bank data space 4 3 4 See Also extern global udata udata ovr udata acs 4 3 5 Simple Example The 2 identically named sections are overlayed in PIC18 Access RAM In this example ul6a is overlaid with memory locations used by ua8 and u8b ul6b is overlaid with memory locations used by u8c and u8d myaoscn access ovr u8a res 1 u8b res 1 u8c res 1 u8d res 1 myaoscn access ovr ul6a res 2 ul6b res 2 DS33014L page 74 O 1994 2013 Microchip Technology Inc Directives 44 __badram IDENTIFY UNIMPLEMENTED RAM Note badram is preceded by two underline characters 44 1 Syntax badram expr expr expr expr 4 4 2 Description The maxramand _badram directives together flag accesses to unimplemented registers _ badram defines the locations of invalid RAM addresse
260. ker can find original source files This file is generated by the utility MP2COD Map File map Shows the memory layout after linking Indicates used and unused memory regions 9 7 1 Object File o Object files are the relocatable code produced from source files The MPLINK linker combines object files and library files according to a linker script into a single output file Object files may be created from source files by MPASM assembler and library files may be created from object files by MPLIB librarian 9 7 2 Library File lib Libraries are a convenient way of grouping related object modules A library file may be created from object files by MPLIB librarian For more on the librarian see Chapter 15 MPLIB Librarian Overview 9 7 3 Linker Script File Ikr Linker script files are the command files of MPLINK linker For more information on linker scripts see Chapter 11 Linker Scripts Standard linker script files are located in C Program Files Microchip MPASM Suite LKR During the link process if MPLINK linker is unable to resolve a reference to a symbol it will search libraries specified on the command line or in the linker script in an attempt to resolve the reference If a definition is found in a library file the object file containing that definition will be included in the link DS33014L page 226 1994 2013 Microchip Technology Inc MPLINK Linker Overview 9 7 4 COFF Object
261. kkk 2nd word 0000 OP No Operation No Operation FXXX OP No Operation No Operation 2 word instructions 0006 POP Pop top of return stack TOS TOS 1 gt TOS 0005 PUSH Push top of return stack TOS PC 2 gt TOS D 1 n RCA n Relative Call PC 2 gt TOS PC 2 2 n gt PC OOFE RESET Software device reset Same as MCLR reset 0010 FIE S Return from interrupt TOS gt PC 1 gt GIE GIEH or PEIE GIEL and enable interrupts if s 1 WREGs gt WREG STATUSs gt STATUS BSRs gt BSR PCLATU PCLATH are unchanged 0012 RETUR S Return from subroutine TOS gt PC if s 1 WREGs gt WREG STATUSs STATUS BSRs BSR PCLATU PCLATH are unchanged 0003 SLEEP Enter SLEEP Mode 0 WDT 0 gt WDT postscaler 1o TO 0 PD Assuming default bit value for s DS33014L page 326 1994 2013 Microchip Technology Inc Instruction Sets TABLE A 19 PIC18 LITERAL OPERATIONS Hex Mnemonic Description Function OFkk ADDLW kk Add literal to WREG WREG kk gt WREG OBkk ANDLW kk AND literal with WREG WREG AND kk gt WREG 09kk IORLW kk Inclusive OR literal with WREG WREG OR kk WREG EErk LFSR r kk Move literal 12 bit 2nd word kk gt FSRr FOkk to FSRr 1st word 010k MOVLB k Move literal to BSR lt 3 0 gt kk gt BSR OEkk MOVLW kk Move literal to WREG kk gt WREG ODkk MULLW kk Multiply literal with WREG WREG kk gt PRODH PRODL O
262. l memory Configure gt External Memory to see this extra memory in the Program Memory window finclude lt p18F8722 h gt Microprocessor mode a memory mode pragma config MODE MP pragma romdata SRAM BASE rom far char sram pragma code void main void rom far char dataPtr dataPtr sram dataPtr OxCC dataPtr 0x55 Assigns Declare Create a that supports external memory this romdata space at 0x20000 an array at starting address far pointer Assign this pointer to the memory array Write low byte of 16 bit word to SRAM Write high byte of 16 bit word to SRAM DS33014L page 280 O 1994 2013 Microchip Technology Inc Sample Applications 13 6 2 Assembler Usage This section discusses how to use the MPASM assembler the assembler when developing external memory appliation code In an assembler application s source file using a simple define or equ directive provides an easy way to define the SRAM starting address which can be used to set up the table pointers prior to a table read or table write operation define SRAM BASE ADDRS 0x20000 Base addrs for external memory device define SRAM END ADDRS Ox1FFFFF End addrs not required Accessing the external program memory through table reads and table writes requires the table pointer register be set up with the appropriate address as shown by the following example movlw upper SRAM BAS
263. l require minor modifications to compile correctly into relocatable object modules Topics covered in this chapter Header Files Program Memory Low High and Upper Operators RAM Allocation Configuration Bits and ID Locations Accessing Labels From Other Modules Paging and Banking Issues Generating the Object Module Code Example HEADER FILES The Microchip supplied standard header files e g p18 8720 inc should be used when generating object modules These header files define the special function registers for the target processor EXAMPLE 6 1 INCLUDE HEADER FILE include p18f8720 inc See 4 42 include Include Additional Source File for more information O 1994 2013 Microchip Technology Inc DS33014L page 189 Assembler Linker Librarian User s Guide 6 3 PROGRAM MEMORY Program memory code must be organized into a logical code section To do this the code must be preceded by a code section declaration See 4 9 code Begin an Object File Code Section to make it relocatable Absolute Code Equivalent Relocatable Code Start clrw code Address determined option by the linker Start clrw option Progl org 0x0100 Progl code 0x0100 Start at 0x0100 moviw 0x0A moviw 0x0A movwf varl movwf varl If more than one code section is defined in a source file each section must have a unique name If the name is not specified it will be given the default name code Each pro
264. label Supported local label label 4 44 2 Description Declares that the specified data elements are to be considered in local context to the macro label may be identical to another label declared outside the macro definition there will be no conflict between the two If the macro is called recursively each invocation will have its own local copy 4 44 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation If you use a macro more than once and there is a label in it you will get a Duplicate Label error unless you use this directive 4444 See Also endm macro 4 445 Simple Example lt main code segment gt len equ 10 global version size equ 20 note that a local variable may now be created and modified test macro size local len label local len and label len set size modify local len label res len reserve buffer len set len 20 endm end macro 4 446 Application Example local This code demonstrates the utility of local directive which declares that the specified data elements are to be considered in local context to the macro include p16f877a inc Include standard header file for the selected devic incr equ 2 Assembler variable incr is set equal to 2 add incr macro Declaration of macro add incr local incr Local assembler variable incr DS33014L page 13
265. lay 0xFF longest delay DLoop Use a simple countdown to decfsz DTEMP F create delay goto DLoop End loop when DTEMP 0 return Use the time it takes to decrement a register DTEMP from an initial value to 0x00 as Delay 2 This method requires no timers or interrupts end End of the program i e tells the assembler no further code needs to be assembled 5 3 3 Header Files A header file is included in the program flow with the 4 include directive include pl6f877a inc Include header file Angle brackets quotes or nothing at all may used to enclose the name of the header file You may specify the complete path to the included file or let the assembler search for it For more on search order see the discussion of the include directive in Section 4 42 include Include Additional Source File A header file is extremely useful for specifying often used constants such as register and pin names This information can be typed in once and then the file can be included in any code using the processor with those registers and pins DS33014L page 174 O 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks 5 3 4 Register and Bit Assignments You can specify your own registers and bits by using the udata res and equ directives as is done in the following lines udata Declare storage of RAM variables DTEMP res 1 Reserve 1 address location DFLAG res 1 Reserve 1 address location DFLO equ 0x
266. le The instruction set is grouped into the following categories byte oriented file register operations bit oriented file register operations and core literal and control operations Additionally instructions that apply to both 12 bit and 14 bit devices are shown in Section A 6 12 Bit 14 Bit Instruction Width Pseudo Instructions Instruction opcode is show in hex by making certain assumptions either listed in the key or as a footnote For more information on the opcode bit values for each instruction as well as the number of cycles per instruction status bits affected and complete instruction details see the relevant device data sheet TABLE A 4 14 BIT BYTE ORIENTED FILE REGISTER OPERATIONS Hex Mnemonic Description Function 07df ADDWF f d Add W and f W f gt d 05df ANDWF f d AND W and f WAND f d 01 1 f CLRF f Clear f 0f 01xx CLRW Clear W 0 gt W 09df COMF f d Complement f NOT f gt d 03df DECF f d Decrement f f 1 gt d OBdf DECFSZ f d Decrement f skip if zero f 1 gt d skip if 0 0Adf INCF f d Increment f f 1 gt d OFAf INCFSZ f d Increment f skip if zero f 1 gt d skip if O 04df IORWF f d Inclusive OR W and f W OR f d 08df MOVE f d Move f fod 00 1 f MOVWE Move W to f Wf 0000 NOP No operation ODdf RLF f d Rotate left f register f C ra Hs 0 ra O
267. lear instructions on the STATUS register will be generated For 14 bit instruction width most PIC12 PIC16 devices MOVLW and MOVWF instructions will be generated to modify the PCLATH If the device contains only one page of program memory no code will be generated For PIC18 devices this command will do nothing as these devices do not use paging 4 54 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive saves you from having to manually code page bit changes Also since it automatically generates code the code is much more portable If you are using relocatable code and your device has more than 2k program memory or 0 5K for 12 bit instruction width devices it is recommended that you use this directive especially when code must jump between two or more code sections You must use this directive instead of pagese1 if you wish to indicate the start address of a RETLW table or a jump table for computed GOTOs Only then will all the 5 top most bits of the PC will be loaded with the appropriate value when an 8 bit offset is added to the PC The 256 word boundaries will still have to be considered as discussed in Application Note AN586 4 54 4 See Also bankisel banksel 4 54 5 Simple Example pageselw CommandTableStart Get the byte read and use it to movlw CommandTableStart index into our ju
268. ler and its capabilities is presented Topics covered in this chapter MPASM Assembler Defined How MPASM Assembler Helps You Assembler Migration Path Assembler Compatibility Issues Assembler Operation Assembler Input Output Files 1 2 MPASM ASSEMBLER DEFINED The MPASM assembler the assembler is a command line or GUI application that provides a platform for developing assembly language code for Microchip s PIC1X microcontroller MCU families The assembler comes with and is used by MPLAB X IDE mpasmx exe and MPLAB IDE v8 mpasmwin exe The MPLAB IDE v8 assembler is also available with the MPLAB C Compiler for PIC18 MCUs aka MPLAB C18 The assembler may also be used in a stand alone application Windows OS only or on the command line The MPASM assembler supports all PIC1X MCU devices as well as memory and KeeLoq secure data products from Microchip Technology Inc Some memory and Keel og devices were not supported in MPLAB IDE after v5 70 40 1 3 HOW MPASM ASSEMBLER HELPS YOU The MPASM assembler provides a universal solution for developing assembly code for all of Microchip s PIC1X MCUs Notable features include MPLAB X IDE and MPLAB IDE v8 Compatibility e Windows Command Line Interfaces Rich Directive Language Flexible Macro Language 1 4 ASSEMBLER MIGRATION PATH Since the MPASM assembler is a universal assembler for all PIC1X MCU devices application code developed for the PIC16F877A can be t
269. ler included with MPLAB X IDE Windows OS mpasmx optioni optionN filename Linux OS and Mac OS mpasmx optioni optionN filename where option refers to one of the command line options filename is the file being assembled For example if test asm exists in the current directory it can be assembled with the following command mpasmx e l test asm If the source filename is omitted the appropriate shell interface is invoked i e a Windows OS interface is displayed which includes a Help button Option or Default Description orh N A Display the assembler help screen ahex format INHX32 Generate hex output directly from assembler where hex format is one of INHX8M INHX8S INHX32 See 1 7 5 Hex File Formats hex hxl hxh for more information c On Enable Disable case sensitivity If enabled the assembler will distiguish between upper and lower case letters dlabel value N A Define a text string substitution i e assign value to label e path CON On Enable Disable Set Path for error file e Enable e Enable e Disable e path Enable specify path e CON Enable to console no file output Overrides q option See Section 1 7 4 Error File err for more information Default is dependent on processor selected A A a a J Oo A AZ
270. lt as relocatable code 5 Ifthe application fails to build check that the environment variables discussed in the next section were set correctly during tool installation O 1994 2013 Microchip Technology Inc DS33014L page 257 Assembler Linker Librarian User s Guide 13 2 2 2 EXAMPLE As an example consider Sample Application 3 C code mixed boot loader application To build an application with MPLAB IDE 1 Use the Project Wizard under the Project menu to create a project Select PIC18F8722 as the device Select the Microchip C18 Toolsuite as the active toolsuite Make sure the executable paths are correct as per Table 13 3 Name the project and place it in its own folder Add the sample files to your project i e c018i mod c mixed asm and mixed lkr View the Project window View gt Project to see your project files sa3_mixed mcw BAX Ld sa3_mixed mcp Y Source Files S cO18i_mod c B mixed c CN Header Files CN Object Files CN Library Files U Linker Script mixed lkr C Other Files 94 Symbols 2 Once the project is created select Project gt Build Options gt Project to open the Build Options for Project dialog Click the Directories tab and enter C mcc18 1lib under Library Path Click the MPLINK Linker tab and then click the Generate map file checkbox to select it 3 Select Debug from the Build Configuration list
271. ly the program is finished with an end 5 2 2 Commented Code Listing Toggles Port pins with count on PIC18F8720 PortA pins on POR RA5 RA3 0 analog inputs RA6 RA4 digital inputs PortB pins on POR RB7 0 digital inputs include p18f8720 inc Include file needed to referenc data sheet names clrf PORTA Clear output data latches on Ports clrf PORTB movlw OxOF Configure Port A for digital I O movwf ADCON1 clrf TRISA Set data direction of Ports as outputs clrf TRISB Loop incf PORTA F Read PORTA add 1 and save back incf PORTB F Read PORTB add 1 and save back goto Loop Do this repeatedly count end All programs must have an end directive DS33014L page 170 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks 5 3 EXAMPLE OF PORT B TOGGLE AND DELAY ROUTINES Directives highlighted in this example are udata res equ code banksel pagesel Items covered in this example are Program Functional Description Commented Code Listing Header Files Register and Bit Assignments Program Memory CODE Sections and Paging Banking Interrupts 5 3 1 Program Functional Description This program continually alternates the output on the Port B pins from 1 s to O s Two delay routines using interrupts provide the timing for the alternating output If LEDs were attached to Port B they would flash 1 on O off The type of PIC1X MCU is se
272. m memory to data memory at runtime 4 36 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation Use this directive to initialize your variables or use a udata directive and then initialize your variables with values in code lt is recommended that you always initialize your variables Relying on RAM initialization can cause problems especially when using an emulator as behavioral differences between the emulator and the actual part may occur This directive cannot be used across banks 4 36 4 See Also extern global udata udata_acs udata_ovr udata_shr 4 36 5 Simple Example idata LimitL dw 0 LimitH dw D 300 Gain dw D 5 Flags db 0 String db Hi there DS33014L page 120 1994 2013 Microchip Technology Inc Directives 4 36 6 Application Example idata This directive reserves RAM locations for variables and directs the linker to generate a lookup table that may be used to initialize the variables specified in this section The Starting Address of the lookup table can be obtained from the Map map file If you don t specify a value in the idata section the variables will be initialized with 0 finclude p16f877a inc Include standard header file for the selected devic groupl IDATA 0x20 Initialized data at location 20h groupl varl res 1 groupl varl located at 0x20 initialized with O0 groupl var2
273. mal base 16 dec decimal base 10 oct octal base 8 You may also specify a radix using the 1ist directive For specifying the radix of constants see Section 3 4 Numeric Constants and Radix 4 56 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation For many programs the default radix hex is used and there is no need to set the radix However if you need to change the radix in your program you should exercise care as all numeric values following the radix declaration will use that radix value See the radix example for more on the implications of changing the radix Use the radix directive or the List directive option r to change the radix in your code 4 56 4 See Also list 4 56 5 Simple Example radix dec 4 56 6 Application Example radix This example shows the usage of the radix directive for data presentation If not declared then the default radix is in hex adecimal list r dec Set the radix as decimal include p16f877a inc Include standard header file for the selected devic moviw 50H 750 is in hex movlw 0x50 Another way of declaring 50 hex movlw 500 750 is in octal movlw 50 750 is not declared as hex or octal or decimal So by default it is in decimal as default radix is declared as decimal radix oct Use radix to declare default radix as octal moviw
274. mbler Linker Librarian User s Guide 11 2 STANDARD LINKER SCRIPTS Standard linker script files are provided for each device and are located by default in the directory C Program Files Microchip MPASM Suite LKR Standard linker scripts are named with the following convention partnumber g lkr For example the standard linker script for PIC16F872 is 16F872 g lkr The standard linker scripts contain conditional linker statements and the IDE uses the u command line flag to utilize these statements for different builds such as debug or no debug You can modify a local copy of the standard linker script and use it in your project AAA JM XX 9 99 M AAA DS33014L page 236 1994 2013 Microchip Technology Inc Linker Scripts 11 3 LINKER SCRIPT COMMAND LINE INFORMATION The MPLAB Project Manager can set this information directly You probably only need to use these if you are linking from the command line e LIBPATH LKRPATH FILES INCLUDE 11 31 LIBPATH Library and object files which do not have a path are searched using the library object search path The following directive appends additional search directories to the 1ibrary object search path LIBPATH libpath where 1ibpath is a semicolon delimited list of directories EXAMPLE 11 1 LIBPATH EXAMPLE To ap
275. mem 17 18 33 34 MPLINK Linker Overview ssesssessseseneesssrrensernne 223 MPLINK Object Linker 21 23 37 41 mplink exe ter tend 17 18 33 34 myMicrochip Personalized Notification Service 14 N A aleae 140 im olaa tee 140 NOT logical EE E A E 69 O Object Fil cnica ea 59 226 298 Object File Directives A 73 ACCESS O Mur ad 74 bankisel 2 1 inner s 77 pel re st M nr trs 80 e ale 84 Gode Dack A etre mme ete 85 AIR EON TUTTI 114 global iia ida lali 119 E A A M E A 120 E ET 122 Dagesel 4 Rte pete SA tea nine 144 pageselw 2 erinnere tere 146 ET ES LEE aiii etre ari ba Doro EP ras 154 die RE 156 udata_ovr udata_shr Object Files Precompiled 21 37 Object Module Generating s nsesesseneeeeeee nenene 198 Operarids en aves i nn nn ee cn 53 Operators Arithmatic sessssssssss 69 Options Command Line Assembler ce in nat eee 63 Librarian ree 300 LINKET ienr rro rto erect reete 232 OR Te EE 69 MN MEE 141 P page oid Rt evene e p tee 144 Page Eject u i epo laica 144 Page Selection eniin 144 Page Selection WEG 146 e EE 144 197 pageselw 5e Vn iia 146 Paging certet iR eene dct n 175 197 PATE eene ege 259 260 Processing Linker 251 Process Otal NE 147 Processor Set 131 147 171 Program Memory sse 190 Projects cit euo EE 20 36 PROTECTED uva 239 R RA os ates t eae s
276. mes of many separate object files when linking Libraries help keep code small Since a linker only uses the required object files contained in a library not all object files which are contained in the library necessarily wind up in the linker s output module Libraries make projects more maintainable If a library is included in a project the addition or removal of calls to that library will not require a change to the link process Libraries help to convey the purpose of a group of object modules Since libraries can group together several related object modules the purpose of a library file is usually more understandable than the purpose of its individual object modules For example the purpose of a file named math 1ib is more apparent than the purpose of power o ceiling o and floor o 1994 2013 Microchip Technology Inc DS33014L page 297 Assembler Linker Librarian User s Guide 15 4 HOW MPLIB LIBRARIAN HELPS YOU The MPLIB librarian can help you in the following ways The librarian makes linking easier because single libraries can be included instead of many smaller files The librarian helps keep code maintainable by grouping related modules together The librarian commands allow libraries to be created and modules to be added listed replaced deleted or extracted 15 5 LIBRARIAN OPERATION The librarian combines multiple input object modules generated by the MPASM assembler or MPLAB C18 C compilers into a
277. more information in this tab if available Line For selectable options click this tab to see the equivalent command line option EE EE RE a a ae DS33014L page 26 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB X IDE PROJECT EXAMPLE In this example you will create an MPLAB X IDE project with multiple assembly files Therefore you will need to use the MPASM assembler and the MPLINK linker to create the final output executable hex file Run the Project Wizard Add Files to the Project Set Build Options Build the Project Build Errors Output Files Further Development Run the Project Wizard In MPLAB X IDE select File gt New Project to launch the wizard 1 Choose Project Select Embedded for the category and C ASM Standalone Project for the project Click Next to continue 2 Select Device Select the PIC16F877 Click Next to continue 3 Select Header There is no header for this device so this is skipped 4 Select Tool Choose a development tool from the list Tool support for the selected device is shown as a colored circle next to the tool Mouse over the cir cle to see the support as text Click Next to continue 5 Select Compiler Choose a version of the MPASMX assembler Click Next to continue 6 Select Project Name and Folder Enter a project name such as MyAsmProject Then select a location for the project folder Click Fi
278. mp table If addwf Comm RxTxByte w we crossed a 256 byte boundary btfsc STATUS C then increment PCLATH Then load the incf PCLATH f program counter with computed goto movwf PCL CommandTableStart goto GetVersion 0x00 Get Version goto GetRTSample 0x01 Get Real Time sampl goto Configure 0x02 stub goto Go 70x03 stub goto ReadBuffer 70x04 Read Buffer just sends Vout goto AreYouThroughYet 0x05 goto CommDone 70x06 goto CommDone 70x07 DS33014L page 146 1994 2013 Microchip Technology Inc Directives 4 55 processor SET PROCESSOR TYPE 4 55 1 Syntax processor processor type 4 55 2 Description Sets the processor type to processor type 4 55 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is not generally used as the processor is set in MPLAB IDE or MPLAB X IDE projects If it must be set in code use processor or the list directive option p to set the processor 4 55 4 See Also list 4 55 5 Simple Example processor 16f877a Sets processor to PIC16F877A 1994 2013 Microchip Technology Inc DS33014L page 147 Assembler Linker Librarian User s Guide 4 56 radix SPECIFY DEFAULT RADIX 4 56 1 Syntax radix default_radix 4 56 2 Description Sets the default radix for data expressions The default radix is hex Valid radix values are hex hexadeci
279. mulators or in circuit debuggers either manufactured by Microchip Technology or third party developers Please see the documentation for these tools to learn how they can help you When debugging you will use Debug gt Debug Project to run and debug your code Please see MPLAB X IDE documenation for more information Once you have developed your code you will want to program it into a device Again there are several programmers that work with MPLAB X IDE to help you do this Please see the documentation for these tools to see how they can help you When programming you will use Program Target Project button on the debug toolbar Please see MPLAB X IDE documenation concerning this control MPLAB C18 example code that may be used to create a C code project may be found in the compiler install example subdirectory See also the MPLAB C Compiler for PIC18 MCUs User s Guide DS51288 As A a a a E AA O 1994 2013 Microchip Technology Inc DS33014L page 31 Assembler Linker Librarian User s Guide NOTES DS33014L page 32 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE PIC1X MCU Language Tools and MPLAB IDE v8 INTRODUCTION The MPASM assembler the MPLINK object linker and the MPLIB object librarian are typically used together under MPLAB IDE to provide GUI development of application code for PIC1X MCU devices PIC10 12 16 18 MCUs The operation of these 8 bit language tools with MPLAB
280. n Object File Access Uninitialized Data Section PIC18 MCUs udata_ovr Uninitialized overlaid data This data section is used for variables that can be declared at the same address as other variables in the same module or in other linked modules A typical use of this section is for temporary variables See 4 64 udata_ovr Begin an Object File Overlayed Uninitialized Data Section udata_shr Uninitialized shared data This data section is used for variables that will be placed in RAM of PIC12 16 devices that is unbanked or shared across all banks See 4 65 udata_shr Begin an Object File Shared Uninitialized Data Section PIC12 16 MCUs idata Initialized data The linker will generate a lookup table that can be used to initialize the variables in this section to the specified values When linked with MPLAB C17 or C18 code these locations will be initialized during execution of the startup code The locations reserved by this section can be accessed only by the labels defined in this section or by indirect accesses See 4 36 idata Begin an Object File Initialized Data Section The following example shows how a data declaration might be created EXAMPLE 6 4 RAM ALLOCATION Absolute Code Use cblock to define variable register locations See 4 8 cblock Define a Block of Constants Variable values will need to be specified in code EEE_EEQQEEEE lt gt gt Re 1994 2013 Microchip Technology Inc
281. n deprecated for PIC18 devices Use directive CONFIG Although you may still use the con ig directive for PIC18 MCU devices it is strongly recommended that you use the config directive no leading underscores instead For PIC18FXXJ MCUs you must user the config directive 231 No memory has been reserved by this instruction This warning would appear if an instruction which is meant to reserve memory cannot actually reserve that memory For example org 0x0 a res 1 end The above PIC18 assembly program is attempting to reserve one byte a res 1 but this is not valid for a PIC18 MCU as each word size is two bytes 232 STATUS register has no IRP or RP1 or RPO bits For PIC16 extended instruction devices you are trying to access a non existent bit of the STATUS register IRP or RP1 or RPO bits UNKNOWN WARNING An internal application error has occurred is the value of the last defined warning plus 1 However it is not severe enough to keep your code from assembling i e it is a warning not an error O 1994 2013 Microchip Technology Inc DS33014L page 217 Assembler Linker Librarian User s Guide 8 4 ASSEMBLER MESSAGES MPASM assembler messages are listed numerically below 301 MESSAGE User definable message invoked with the messg directive see Section 4 48 messg Create User Defined Message 302 Register in operand not in bank 0 Ensure that bank bits are correct This is a commonly seen
282. n illegal digit in a number Valid digits are 0 1 for binary 0 7 for octal 0 9 for decimal and 0 9 a f and A F for hexadecimal 108 Illegal character An illegal character in a label Valid characters for labels are alphabetic a f A F numeric 0 9 the underscore and the question mark Labels may not begin with a numeric 109 Unmatched An open parenthesis did not have a matching close parenthesis For example DATA 1 2 110 Unmatched An close parenthesis did not have a matching open parenthesis For example DATA 1 2 111 Missing symbol An equ Or set directive did not have a symbol to which to assign the value DS33014L page 208 O 1994 2013 Microchip Technology Inc Errors Warnings Messages and Limitations 112 Missing operator An arithmetic operator was missing from an expression For example DATA 1 2 113 Symbol not previously defined A symbol was referenced that has not yet been defined Check the spelling and location of the declaration of any symbols used in your code Only addresses may be used as forward references Constants and variables must be declared before they are used This sometimes happens when include files are used in your project Since the text from an include file is inserted at the location of the include statement and you may have labels used before that point you can get this error Also the error may occur due to a typing error spelling mistake or case ch
283. n labelled program memory 0004 and 0006 minus current addr each location with 3 numbers Of 2 word wide instructions lt goto start Fills 10a9h Write Pus NOP Go to Write 2 locations current line address 1Ch and 1Eh with your main program here 4 bytes with loop here your high interrupt ISR here Write your low interrupt ISR here DS33014L page 118 O 1994 2013 Microchip Technology Inc Directives 4 35 global EXPORT A LABEL 4 35 1 Syntax global label label 4 35 2 Description This directive declares symbol names that are defined in the current module and should be available to other modules At least one label must be specified on the line 4 35 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation When your project uses more than one file you will be generating linkable object code When this happens you may use the global and extern directives global is used to make a label visible to other files extern must be used in the file that uses the label to make it visible in that file 4 35 4 See Also extern idata udata udata_acs udata_ovr udata_shr 4 35 5 Simple Example global Varl Var2 global AddThree udata Varl res 1 Var2 res 1 code AddThree addlw 3 return 4 35 6 Application Example extern global See this example under extern
284. n octal integer is o or O followed by one or more of the octal digits 01234567 in single quotes 3 Adecimal integer is d or D followed by one or more decimal digits 0123456789 in single quotes Or a decimal integer is followed by one or more decimal digits 0123456789 4 A hexadecimal integer is h or H followed by one or more hexadecimal digits 0123456789abcdefABCDEF in single quotes Or a hexadecimal integer is Ox or OX followed by one or more hexadecimal digits 0123456789abcdefABCDEF 5 An ASCII character is a or A followed by one character in single quotes Or an ASCII character is one character in single quotes DS33014L page 68 O 1994 2013 Microchip Technology Inc Expression Syntax and Operation ARITHMETIC OPERATORS AND PRECEDENCE Arithmetic operators may be used with directives and their variables as specified in the table below Note These operators cannot be used with program variables They are for use with directives only The operator order in the table also corresponds to its precedence where the first operator has the highest precedence and the last operator has the lowest precedence Precedence refers to the order in which operators are executed in a code statement TABLE 3 1 ARITHMETIC OPERATORS IN ORDER OF PRECEDENCE Operator Example Current Return program counter goto 3 Left Parenthesis 1
285. n program The main program code is placed here Main main code goes here banksel elementl Select elementl bank movlw 0x55 Move literal movwf element1 1 to elementi movff elementl element2 Move elementi rrcf element2 1 1 to element2 right shift movff element2 WREG element2 move to WREG movwf element3 Move WREG to element3 rrcf element3 1 1 eight shift and movff element3 element4 move to element4 rrcf element4 1 1 Right shift element4 movff element4 elements and move to element low byte rrcf element4 1 1 Right shift element4 movff element4 element5 1 again and move to element5 high byte Loop goto Loop KKK KKK KK KK KKK KKK KK KKK KKK KKK KK KKK KKK kk ko ko k ckock ko ko KKK KKK KKK KKK KKK AAA ko Sk ko ko kc kv ko k kA ko A ko ko End of program END DS33014L page 262 1994 2013 Microchip Technology Inc Sample Applications 13 3 3 Building the Application To build the application see Section 13 2 How to Build the Sample Applications Then to continue development with the IDE you could place the element variables in a Watch es window to see their values remembering to change element 5 to a 16 bit value Properties dialog Watch Properties tab O 1994 2013 Microchip Technology Inc DS33014L page 263 Assembler Linker Librarian User s Guide 13 4 SAMPLE APPLICATION 2 PLACING CODE AND SETTING CONFIG BITS This example is for
286. n small reusable modules Libraries You can make libraries of related functions which can be used in creating efficient readily compilable applications MPLAB C18 The Microchip compiler for PIC18 devices requires the use of MPLINK linker and can be used with precompiled libraries and MPASM assembler Centralized Memory Allocation By using application specific linker scripts precompiled objects and libraries can be combined with new source modules and placed efficiently into available memory at link time Accelerated Development Since tested modules and libraries don t have to be recompiled each time a change is made in your code compilation time may be reduced 9 5 LINKER PLATFORMS SUPPORTED MPLINK linker is supported under Windows 2000 XP Windows Vista Linux and Mac platforms L 229 4 9 s c uu n ae DS33014L page 224 1994 2013 Microchip Technology Inc MPLINK Linker Overview 9 6 LINKER OPERATION The MPLINK linker combines multiple input object modules and library files per the linker script file into a single output COF file Utilities can be used to generate executable code hex or a linker listing file 1st from the COF file A map file can also be generated to aid in debugging FIGURE 9 1 MPLINK LINKER OPERATION precomp o Fide precomp o file
287. nal application error has occurred is the value of the last defined error plus 1 Contact your Microchip Field Application Engineer FAE or Microchip support if you cannot debug this error EE a ae DS33014L page 214 1994 2013 Microchip Technology Inc Errors Warnings Messages and Limitations 8 3 ASSEMBLER WARNINGS MPASM assembler warnings are listed numerically below 201 Symbol not previously defined The symbol being undefined was not previously defined 202 Argument out of range Least significant bits used Argument did not fit in the allocated space For example literals must be 8 bits 203 Found opcode in column 1 An opcode was found in column one which is reserved for labels 204 Found pseudo op in column 1 A pseudo op was found in column one which is reserved for labels 205 Found directive in column 1 A directive was found in column one which is reserved for labels 206 Found call to macro in column 1 A macro call was found in column one which is reserved for labels 207 Found label after column 1 A label was found after column one which is often due to a misspelled opcode 208 Label truncated at 32 characters Maximum label length is 32 characters 209 Missing quote A text string or character was missing a quote For example DATA a 210 Extra An extra comma was found at the end of the line 211 Extraneous arguments on the line Extra arguments were found on the line 212 Expected ENDIF Expected
288. nch GOTO k BC k Branch on Carry BTFSC 3 0 x GOTO k BDC k Branch on Digit Carry BTFSC 3 1 i GOTO k BNC k Branch on No Carry BTFSS 3 0 i GOTO k BNDC k Branch on No Digit Carry BTFSS 3 1 GOTO k BNZ k Branch on No Zero BTFSS 342 GOTO k BZ k Branch on Zero BTFSC 3 2 GOTO k CLRC Clear Carry BCF 3 0 CLRDC Clear Digit Carry BCF 3 1 CLRZ Clear Zero BCF 3 2 LCALL k Long Call BCF BSF Ox0A 3 BCF BSF Ox0A 4 CALL k LGOTO k Long GOTO BCF BSF 0x0A 3 BCF BSF Ox0A 4 GOTO k MOVEW Move File to W MOVE 0 Z NEGF f d Negate File COMF Eyl Z INCF f d ETC Set Carry BSF 3 0 ETDC Set Digit Carry BSF 3 1 ETZ Set Zero BSF 3 2 SKPC Skip on Carry BTFSS 3 0 SKPDC Skip on Digit Carry BTFSS 3 1 S SKPNC Skip on No Carry BTFSC 3 0 SKPNDC Skip on No Digit Carry BTFSC SL SKPNZ Skip on Non Zero BTFSC 3 2 SKPZ Skip on Zero BTFSS 35 2 SUBCF f d Subtract Carry from File BTFSC 3 0 Z DECF f d DS33014L page 320 1994 2013 Microchip Technology Inc Instruction Sets TABLE A 15 12 BIT 14 BIT SPECIAL INSTRUCTION MNEMONICS CONTINUED Mnemonic Description Equivalent Status Operation s SUBDCF f d Subtract Digit Carry from File BTFSC 354 Z DECF f d TSTF f Test File MOVF f Z 1994 2013 Microchip Technology Inc DS33014L page 321 Assembler Linker Librarian User s Guide A 7 KEY TO PIC18 DEVICE INSTRUCTION SET Use this key to determine the meaning of abbreviations in the PIC1
289. nd badram for each processor 220 Address exceeds maximum range for this processor A ROM location was specified that exceeds the processor s memory size 221 Invalid message number The message number specified for displaying or hiding is not a valid message number 222 Error messages cannot be disabled Error messages cannot be disabled with the errorlevel command 223 Redefining processor The selected processor is being reselected by the list or processor directive 224 Use of this instruction is not recommended The instruction is being obsoleted and is not recommended for current use However it is still supported for legacy reasons 225 Invalid label in operand Operand was not a valid address For example if the user tried to issue a CALL toa MACRO name 226 Destination address must be word aligned The destination address is not aligned with the start of a program memory word For this device use even bytes to specify address 227 Substituting RETLW 0 for RETURN pseudo op Using retlw 0 instead of return to resume program execution DS33014L page 216 1994 2013 Microchip Technology Inc Errors Warnings Messages and Limitations 228 Invalid ROM location specified The data memory location specified is not valid for the operation specified or is non existent 229 extended mode is not in effect overridden by command line A command line option has disabled extended mode operation 230 _ CONFIG has bee
290. nd messages are embedded between the source lines and pertain to the following source line Also there is a summary at the end of the listing The symbol table lists all symbols defined in the program The memory usage map gives a graphical representation of memory usage X marks a used location and marks memory that is not used by this object The map also displays program memory usage The memory map is not printed if an object file is generated Note Due to page width restrictions some comments have been shortened indi o cated by Also some symbol table listings have been removed indicated by See the standard header p18 452 inc for a complete list of symbols 1994 2013 Microchip Technology Inc DS33014L page 55 Assembler Linker Librarian User s Guide MPASM 03 70 Released SOURCE ASM 4 5 2004 15 40 00 PAGE 1 LOC OBJECT CODE LINE SOURCE TEXT VALUE 00001 list p 18f452 00002 include p18f452 inc 00001 LIST 00002 P18F452 INC Standard Header File Version 1 4 00845 LIST 0000000B 00003 Dest equ 0x0B 00004 000000 00005 org 0x0000 000000 EF10 F000 00006 goto Start 000020 00007 org 0x0020 000020 OEOA 00008 Start movlw 0x0A 000022 6EOB 00009 movwf Dest 000024 960B 00010 bcf Dest 3 This line uses 2 op 000026 EF10 F000 00011 goto Start 00012 end MPASM 03 70 Released SOURCE ASM 4 5 2004 15 40 00 PAGE 2 SYMBOL TABLE LABEL VALUE A 00000000 ACCESS 00000000 _XT_OSC_1H 00000
291. nd then set up compiler options General Category Generate Command Line Diagnostics level Select to display errors only errors and warnings or errors warnings and messages These will be shown in the Output window Default storage class Select the storage class either ANSI standard auto or static Macro Definitions Add macro directive definitions Restore Defaults Restore tab default settings Use Alternate Settings Text Box Enter options in a command line non GUI format Memory Model Category Generate Command Line Small near rom program memory lt 8K near ram data memory lt 256 Medium far rom program memory gt 8K near ram data memory lt 256 Compact near rom program memory lt 8K far ram data memory gt 256 Large far rom program memory gt 8K far ram data memory gt 256 Restore Defaults Restore tab default settings Use Alternate Settings Text Box Enter options in a command line non GUI format Optimization Category Generate Command Line Bank Selection Optimiza Select the level of bank selection optimization Removes MOVLB tion instruction in instances where it can be determined that the Bank Select register already contains the correct value Level 0 None Level 1 Equivalent to On1 Level 2 Equivalent to On2 Other Optimizations Select individual optimizations Restore Defaults R
292. nder the MPLAB X IDE This is how most developers will use these tools PIC1X MCU Language Tools and MPLAB IDE v 8 provides an overview of how to use all of the tools in this manual together under the MPLAB IDE v 8 1994 2013 Microchip Technology Inc DS33014L page 9 Assembler Linker Librarian User s Guide Part 1 MPASM Assembler e D D Chapter 1 MPASM Assembler Overview describes what the MPASM assembler is what it does and how it works with other tools Also gives an overview of operation and discusses input output files Chapter 2 Assembler Interfaces reviews how to use the MPASM assembler with MPLAB IDE and describes how to use the assembler on the command line or in a Windows shell interface Chapter 3 Expression Syntax and Operation provides guidelines for using complex expressions in MPASM assembler source files Chapter 4 Directives lists each MPASM assembler directive alphabetically and describes the directive in detail with examples Chapter 5 Assembler Examples Tips and Tricks provides examples of how to use the MPASM assembler directives together in applications Chapter 6 Relocatable Objects describes how to use the MPASM assembler in conjunction with MPLINK object linker Chapter 7 Macro Language describes how to use the MPASM assembler s built in macro processor Chapter 8 Errors Warnings Messages and Limitatio
293. ngs Addendum DS51537 Multiple settings may be defined on a single line separated by commas Settings for a single Configuration byte may also be defined on separate lines Before this directive is used a PIC18 MCU must be declared through the command line the list directive the processor directive a project if using MPLAB X IDE or Configure gt Select Device if using MPLAB IDE Another directive that may be used to set configuration bits for PIC18 MCU devices is the con ig directive but this is not recommended for new code Note Do not mix config and config directives in the same code 412 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is placed in source code so that when the code is compiled assembled into a hex file the configuration values are preset to desired values in your application This is useful when giving your files to a third party programming house as this helps insure the device is configured correctly when programmed Place configuration bit assignments at the beginning of your code Use the configuration options set ting value pairs listed in the standard include inc file or the addendum The config directive can be used multiple times in the source code but an error will be generated if the same bit is assigned a value more than once Le CONFIG CPO OFF WDT ON
294. nish to complete the project creation and setup Once the Project Wizard has completed the Project window should contain the project tree For more on projects see the MPLAB X IDE documentation FIGURE 3 NEW PROJECT TREE NENNEN 1994 2013 Microchip Technology Inc DS33014L page 27 Assembler Linker Librarian User s Guide Add Files to the Project Right click on the Source Files folder in the project tree Select New gt Other to open the File wizard 1 Choose File Type Expand Microchip Embedded to see available file types Click MPASM assembler and select main asm Click Next gt to continue 2 Name and Location Enter the name for the new file in this case example asm The location is the current project by default Leave this for now Click Finish to create file Repeat the above steps to add another file example2 asm to the project When you are done the project tree should now look as in Figure 4 The code for each file follows FIGURE 4 PROJECT TREE WITH SOURCE FILES example asm File example asm This is the main file in the MPASM assembler MPLINK linker example Use with example2 asm include p16f877 inc PROG CODE Set the start of code from 16f877 1kr script main Min code entry called from example2 asm global main Define as global so can be used in example2 asm nop Main does nothing Put your code here
295. nker script file may or may not assign the stack to a specific target memory block If the stack is assigned a target memory block it gets allocated just before the relocatable assigned sections are allocated If the stack is unassigned then it gets allocated after the relocatable assigned sections and before the other relocatable unassigned sections are allocated DS33014L page 252 1994 2013 Microchip Technology Inc Linker Processing 12 4 RELOCATION EXAMPLE The following example illustrates how the linker relocates sections Suppose the following source code fragment occurred in a file File ref c char varl Line 1 void setVarl void Line 2 varl OxFF Line 3 Suppose this compiles into the following assembly instructions Note This example deliberately ignores any code generated by MPLAB C18 to handle the function s entry and exit 0x0000 MOVLW OxFF 0x0001 MOVLB Need to patch with varl s bank 0x0002 MOVWF Need to patch with varl s offset When the compiler processes source line 1 it creates a symbol table entry for the identifier var1 which has the following information Symbol index gt name varl value 0 section data class extern When the compiler processes source line 3 it generates two relocation entries in the code section for the identifier symbol var1 since its final address is unknown until link time The relocation entries have the following in
296. nker script file Multiple inclusion of object file filename An object file has been included multiple times either on the command line or with a FILES directive in a linker script file Remove the multiple references n switch requires length The number of source lines per listing file page must be specified A length of zero will suppress pagination of the listing file O switch requires filename A COFF output filename must be specified For example o main out Unknown switch cmdline token An unrecognized command line switch was supplied Refer to the Usage documentation for the list of supported switches Unrecognized input in cmdfile line All statements in a linker script file must begin with a directive keyword or the comment Delimiter R EL c 2 w HM H J r H DS33014L page 286 1994 2013 Microchip Technology Inc Errors Warnings and Common Problems 14 3 LINKER ERRORS MPLINK linker errors are listed alphabetically below Absolute code section secName must start at a word aligned address Program code sections will only be allocated at word aligned addresses MPLINK will give this error message if an absolute code section address is specified that is not word aligned Configuration settings have been specified
297. ns contains a descriptive list of the errors warnings and messages generated by the MPASM assembler as well as tool limitations Part 2 MPLINK Object Linker D Chapter 9 MPLINK Linker Overview describes what the MPLINK object linker is what it does and how it works with other tools Also gives an overview of operation and discusses input output files Chapter 10 Linker Interfaces reviews how to use the MPLINK linker with MPLAB IDE and describes how to use the linker on the command line Chapter 11 Linker Scripts discusses how to generate and use linker scripts to control linker operation Chapter 12 Linker Processing describes how the linker processes files Chapter 13 Sample Applications provides examples of how to use the linker to create applications Sample Application 1 explains how to find and use template files and when to modify the generic linker script file Sample Application 2 explains how to place program code in different memory regions how to place data tables in ROM memory and how to set configuration bits in C Sample Application 3 explains how to partition memory for a boot loader and how to compile code that will be loaded into external RAM and executed Sample Application 4 explains how to create new linker script memory section how to declare external memory through pragma code directive and how to access external memo
298. oader written in assembly and therefore requires a microcontroller with a larger boot block region such as the PIC18F8722 See 13 5 1 4 Example 3 Mixed Language Boot Loader Application Boot loader and application code written for the C compiler must use the C compiler linker scripts to command the linker to place the compiled C source code into appropriate program memory sections Typically boot loader code is compiled and linked for a destination in the boot section of the target microcontroller s program memory The application code is compiled and linked for a destination inside the user section of program memory To build the C compiler sample application refer to Section 13 2 How to Build the Sample Applications 13 5 1 1 C COMPILER MEMORY MAP The first two C compiler boot loader examples are demonstrated using a PIC18F8722 which offers a configurable boot block size of 2K 4K or 8K bytes The remaining program memory is available for the relocatable application code and data tables For these two examples it is assumed the boot block is configured for 2K bytes and requires modification to the C compiler linker script file in order to accommodate the selected boot block size The third example a mix of an MPASM assembler boot loader and C compiler source code uses the PIC18F8720 For the corresponding memory map see Section 13 5 2 1 Assembler Memory Map For the first two examples program memory sections specifi
299. object file is generated they cannot be used when generating absolute code O 1994 2013 Microchip Technology Inc DS33014L page 191 Assembler Linker Librarian User s Guide EXAMPLE 6 3 GENERAL OPERATOR USE The general operators low high and upper may be used to access data in tables The following code example was taken the p18demo asm file provided with PICDEM 2 Plus demo board The excerpt shows how Microchip is read from the table and displayed on the demo board LCD include p18f452 inc PROG1 CODI stan_table table for standard code H XXXXXXXXXXXXXXXX d ptr data Voltmeter 0 data Buzzer 716 data Temperature Ve 232 data Clock 48 data RA4 Next RBO Now 64 data de Microchip T 80 data PICDEM 2 PLUS H 796 data RA4 Set RBO Menu 551 12 data RA4 gt RBO 128 data 5 RBO Exit 7144 data Volts 7160 Prd 128 DC 128 FETO data pXECKkCkckckckck kk Kk KR STANDARD CODE MENU SELECTION KKKKKKKKKKKXKKKKkkkxk movlw 80 send Microchip to LCD movwf ptr pos call stan char 1 Standard code Place characters on line 1 stan char 1 call CDLine 1 move cursor to line 1 moviw 16 l full line of LCD movwf ptr count movlw UPPER stan table use operators to load movwf TBLPTRU table pointer values movlw HIGH stan table movwf TBLPTRH movlw LOW stan table movwf TBLPTRL movf ptr pos W addwf TBLPTRL F clrf WREG addwfc TBLPT
300. ocumentation Some library files math 1ib are available with the compiler Others may be built using the librarian tool MPLIB object librarian For more information on the librarian see the MPLIB librarian documentation For more information on available Microchip libraries see the MPLAB C18 C compiler documentation The object files along with library files are used to generate the project output files via the linker MPLINK object linker Depending on your project you may or may not need to add a linker script file device 1kr For more information on using linker script files and the linker see the MPLINK linker documentation The main output file generated by the MPLINK linker is the COF file prog cof The linker then uses the utility MP2HEX to generate the Hex file prog hex used by simulators emulators debuggers and programmers For more information on linker output files see the MPLINK linker documentation For more information on utilities see the related documentation For more on projects and related workspaces see MPLAB IDE documentation 1994 2013 Microchip Technology Inc DS33014L page 37 Assembler Linker Librarian User s Guide PROJECT SETUP To set up an MPLAB IDE project for the first time it is advisable to use the built in Project Wizard Project gt Project Wizard In this wizard you will be able to select a language toolsuite that uses MPASM assembler e g the Microchip MPASM Toolsuite F
301. ode with x 0 It is the recommended form of use for compatibility with all Microchip software tools Literals k Literal field constant data or label k 4 bit kk 8 bit kkk 12 bit mm Pre post increment decrement mode selection 1994 2013 Microchip Technology Inc DS33014L page 311 Assembler Linker Librarian User s Guide Field Description Bits b Bit address within an 8 bit file register 0 to 7 d Destination select bit d 0 store result in WREG d 1 store result in file register f default a Table pointer control i 0 do not change i 1 increment after instruction execution s Destination select bit s 0 store result in file register f and WREG s 1 store result in file register f default E Table byte select t 0 perform operation on lower byte t 1 perform operation on upper byte KA Bit values as opposed to Hex value Named Registers BSR Bank Select Register Used to select the current RAM bank OPTION OPTION Register PCL Program Counter Low Byte PCH Program Counter High Byte PCLATH Program Counter High Byte Latch PCLATU Program Counter Upper Byte Latch PRODH Product of Multiply High Byte PRODL Product of Multiply Low Byte TBLATH Table Latch TBLAT High Byte TBLATL Table Latch TBLAT Low Byte TBLPTR 16 bit Table Pointer TBLPTRH TBLPTRL Points to
302. of code see Section 1 6 Assembler Operation define is useful for defining values for constants in your program Note A processor specific include file exists with predefined SFR names It is recommended that you use this file instead of defining the variables yourself See include for how to include a file in your program This directive is also useful with the ifdef and ifndef directives which look for the presence of an item in the symbol table 4 184 See Also fundefine include ifdef ifndef 4 18 5 Simple Example define length 20 define control 0x19 7 define position X Y Z Y 2 Z X test label dw position 1 length 512 bsf control set bit 7 in 19 DS33014L page 98 1994 2013 Microchip Technology Inc Directives 4 18 6 Application Example define undefine This example shows the the usage of define and undefine directives A symbol name previously defined with the define directive is removed from the symbol table if undefine directive is used include p16f877a inc area set 0 define Ingth 50H define wdth 25H area set lngth wdth fundefine lngth undefine wdth define Ingth 0 end The same symbol may be redefined again Include standard header file for the selected devic The label area is assigned the value 0 ER Label lngth is assigned the value 50H Label wdth is assigned the value 25H Reassignment of label area
303. ology Inc Directives shift_right 3 Shift right 3 times the 16 bit data in reg hi and reg lo This is an example A value 8 will shift data 8 times goto Go to current line loop here end O 1994 2013 Microchip Technology Inc DS33014L page 167 Assembler Linker Librarian User s Guide NOTES DS33014L page 168 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 5 Assembler Examples Tips and Tricks 5 1 INTRODUCTION The usage of multiple MPASM assembler directives is shown through examples Directives are assembler commands that appear in the source code but are not opcodes They are used to control the assembler its input output and data allocation Many of the assembler directives have alternate names and formats These may exist to provide backward compatibility with previous assemblers from Microchip and to be compatible with individual programming practices If portable code is desired it is recommended that programs be written using the specifications contained within this document For areference listing of all directives discussed in examples here please see Chapter 4 Directives Note Although MPASM assembler is often used with MPLINK object linker MPASM assembler directives are not supported in MPLINK linker scripts See MPLINK object linker documentation for more information on linker options to control listing and hex file output
304. ols and patching section is described in Section 12 4 Relocation Example After the linker has processed all relocation entries it generates the executable output module 1994 2013 Microchip Technology Inc DS33014L page 251 Assembler Linker Librarian User s Guide 12 3 LINKER ALLOCATION ALGORITHM The linker allocates memory areas to allow maximum control over the location of code and data called sections in target memory There are four kinds of sections that the linker handles 1 Absolute Assigned 2 Absolute Unassigned 3 Relocatable Assigned 4 Relocatable Unassigned An absolute section is a section with a fixed absolute address that cannot be changed by the linker A relocatable section is a section that will be placed in memory based on the linker allocation algorithm An assigned section is a section that has been assigned a target memory block in the linker script file An unassigned section is a section that has been left unassigned in this file The linker performs allocation of absolute assigned and unassigned sections first relocatable assigned sections next and relocatable unassigned sections last The linker also handles stack allocation 12 3 4 Absolute Allocation Absolute sections may be assigned to target memory blocks in the linker script file But since the absolute section s address is fixed the linker can only verify that if there is an assigned target memory block for an absolute sec
305. on For every if directive used there must be a corresponding endif if and endif are not instructions but used for code assembly only 4 25 4 See Also else if 4 25 5 Examples See the examples under if 4 26 endm END A MACRO DEFINITION 4 26 1 Syntax endm 4 26 2 Description Terminates a macro definition begun with macro 4 26 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation For every macro directive used there must be a corresponding endm 4 26 4 See Also macro exitm 4 26 5 Simple Example make table macro argl arg2 dw argl 0 null terminate table nam res arg2 reserve storage endm 4 26 6 Application Example macro endm See this example under macro DS33014L page 104 O 1994 2013 Microchip Technology Inc Directives 4 27 endw END A while LOOP 4 27 1 Syntax Preferred endw Supported endw 4 27 2 Description endw terminates a whi le loop As long as the condition specified by the while directive remains true the source code between the while directive and the endw directive will be repeatedly expanded in the assembly source code stream This directive may be used inside a regular program block or macro 4 27 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Op
306. on negative values 162 Expected a section name Some operators and pseudo operators take section names as operands The lexical form of a section name is that of an identifier optionally prefixed with a 163 CONFIG directives must be contiguous Do not place other code between config directive declarations 164 IDLOC directives must be contiguous Do not place other code between idloc directive declarations DS33014L page 212 1994 2013 Microchip Technology Inc Errors Warnings Messages and Limitations 165 extended mode not available for this device This PIC18 device does not support extended mode 166 left bracket missing from offset operand The left bracket is missing from an offset e g 0x55 167 right bracket missing from offset operand The right bracket is missing from an offset e g 0x55 168 square brackets required around offset operand Square brackets are required around an offset e g 0x55 169 access bit cannot be specified with indexed mode When using indexed mode the access bit cannot be specified 170 expression within brackets must be constant The expression specified within brackets is not a constant value 171 address specified is not in access ram range of 0x60 OxFF When making use of Access RAM addressing must occur within the specified Access Bank range 172 PCL TOSL TOSH or TOSU cannot be destination of MOVFF or MOVSF These registers cannot be written to with
307. op oscillator 3Ckk SUBLW kk Subtract W from literal kk WREG gt WREG 006r TRIS d Tristate port r WREG gt UO control reg r 3Akk XORLW kk Exclusive OR literal and W kk XOR WREG gt WREG DS33014L page 316 1994 2013 Microchip Technology Inc Instruction Sets A 5 14 BIT INSTRUCTION WIDTH EXTENDED INSTRUCTION SET Some of Microchip s midrange 8 bit microcontroller family use a 14 bit wide extended instruction set Consult your device data sheet to see if you device uses an extended instruction set This instruction set consists of 41 instructions each a single 14 bit wide word Most instructions operate on a file register f and the working register WREG accumulator The result can be directed either to the file register or the WREG register or to both in the case of some instructions A few instructions operate solely on a file register BSF for example The instruction set is grouped into the following categories byte oriented file register operations byte oriented skip operations bit oriented file register operations bit oriented skip operations core literal operations core control operations core inherent operations and C compiler optimized operations Additionally instructions that apply to both 12 bit and 14 bit devices are shown in Section A 6 12 Bit 14 Bit Instruction Width Pseudo Instructions Instruction opcode is show in hex by making certain assumptions either listed
308. opyright c 2004 Microchip Technology Inc Errors perm Loaded D Projects32 Example cof BUILD SUCCEEDED Mon May 17 14 41 31 2004 Build Errors If the build did not complete successfully check these items 1 Review the previous steps in this example Make sure you have set up the lan guage tools correctly and have all the correct project files and build options 2 If you modified the sample source code examine the Build tab of the Output win dow for syntax errors in the source code If you find any double click on the error to go to the source code line that contains that error Correct the error and then try to build again DS33014L page 44 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB IDE v8 Output Files View the project output files by opening the files in MPLAB IDE 1 Select File gt Open In the Open dialog find the project directory 2 Under Files of type select All files to see all project files 3 Select Example xrf Click Open to view the assembler cross reference file for Example asm in an MPLAB IDE editor window For more on this file see the MPASM assembler documentation Section 1 7 6 Cross Reference File xrf 4 Repeat steps 1 and 2 Select Example map Click Open to view the linker map file in an MPLAB IDE editor window For more on this file see the MPLINK linker documentation Section 9 7 7 Map File map 5 Rep
309. or more on the wizard and MPLAB IDE projects see MPLAB IDE documentation When a project is set up set up properties of the tools in MPLAB IDE 1 Fromthe MPLAB IDE menu bar select Project gt Build Options gt Project to open a dialog to set check project build options Note MPASM assembler does not recognize include path information specified in MPLAB IDE 2 Click on the tool tab to modify tool settings Build Options Dialog Build Options Dialog Build Options Dialog Build Options Dialog MPASM Assembler Tab MPLAB C17 Tab If Installed MPLAB C18 Tab If Installed MPLINK Linker Tab Build Options Dialog MPASM C17 C18 Suite Tab 3 Perform additional setup as required MPLAB C18 Setup for PIC18 Extended Instruction Set Use Build Options Dialog MPASM Assembler Tab Select a category and th MPASM assembler docu General Category en set up assembler options For additional options see mentation Chapter 2 Assembler Interfaces Generate Command Line Disable case sensitivity The assembler accepts upper and lower case letters equally Note Disabling case sensitivity will make all labels uppercase Extended mode Enable PIC18F extended instruction support Default Radix Set the default radix either Hexadecimal Decimal or Octal Macro Definitions Add macro directive definitions Restore Defaults Restore tab default settings Use Alternate Settin
310. ore testing movlw D 11 Load in 2 test values movwf AARGBO moviw D 30 movwf BARGBO pagesel UMUL0808L call UMULO808L After loading AARGBO and BARGBO call routine goto Result now in AARGBO AARGB1 where AARGBO is MSB EXAMPLE 6 11 RELOCATABLE CODE LIBRARY ROUTINE Input fixed point arguments in AARGBO and BARGBO Output product AARGxBARG in AARGBO AARGB1 Other comments truncated See AN617 PRRRRRKKK RK KK KEK KK KK RK KKK KK KEK KEK KE EK KE RK KEK KK KK KEK KEE ke RARA RK KK KK KK KK KKK include pl6f877a inc Use any PIC16 device you like GLOBAL UMULO808L AARGBO AARGB1 BARGBO UDATA LOOPCOUNT RES I 7 loops needed to complete routine AARGBO RES T MSB of result out AARGB1 RES 1 operand A in 8 bits BARGBO RES 1 LSB of result out operand B in 8 bits O 1994 2013 Microchip Technology Inc DS33014L page 199 Assembler Linker Librarian User s Guide CODE UMULO808L moviw 0x08 movwf LOOPCOUNT movf AARGBO W LOOPUMO808A rrf BARGBO F btfsc STATUS C goto LUMO 80 8NAP decfsz LOOPCOUNT F goto LOOPUMO808A Cir AARGBO retlw 0x00 LUMO 808NAP bef STATUS C goto LUMO 808NA LOOPUMO808 rrf BARGBO F btfsc STATUS C addwf AARGBO F LUMO808NA rrf AARGBO F EE AARGB1 F decfsz LOOPCOUNT F goto LOOPUMO808 retlw 0 END DS33014L page 200 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 7
311. out the use of the MPLINK linker For more information on this use see PIC1X MCU Language Tools and MPLAB X IDE 2 3 MPLAB IDE V8 INTERFACE The MPASM assembler is most commonly used with the MPLINK linker in an MPLAB IDE project to generate relocatable code For more information on this use see PIC1X MCU Language Tools and MPLAB IDE v8 The assembler may also be used in MPLAB IDE to generate absolute code without the use of the MPLINK linker or MPLAB IDE project by using the QuickBuild feature To do this 1 From the MPLAB IDE menu bar select Project Set Language Tool Locations to open a dialog to set check language tool executable location 2 Inthe dialog under Registered Tools select Microchip MPASM Toolsuite Click the to expand 3 Select Executables Click the to expand 4 Select MPASM Assembler mpasmwin exe Under Location a path to the mpasmwin exe file should be displayed If no path is displayed enter one or browse to the location of this file By default it is located at C Program Files Microchip MPASM Suite mpasmwin exe 5 Click OK 6 From the MPLAB IDE menu bar select Project Quickbuild to assemble the specified asm file using the MPASM assembler 1994 2013 Microchip Technology Inc DS33014L page 61 Assembler Linker Librarian User s Guide 2 4 WINDOWS INTERFACE MPASM assembler for Windows provides a graphical interface for setting assembler options It is in
312. overflow flag bcf DFLAG DFLO Clear flag bit retfie Return from interrupt When the program code begins to execute again the cleared flag bit DFLO now causes the delay loop TLOOP to end thus ending Delay 1 routine 1994 2013 Microchip Technology Inc DS33014L page 177 Assembler Linker Librarian User s Guide 5 4 EXAMPLE OF CALCULATIONS WITH VARIABLES AND CONSTANTS Directives highlighted in this example are define undefin set constant variable Items covered in this example are Program Functional Description Commented Code Listing Using Watch es Windows 5 4 1 Program Functional Description This program performs several calculations using defined constants and variables The application is written as relocatable code i e you must use both the assembler and linker to generate the executable The standard header file for the processor selected is included using include Sections of code are created using the code statement 5 4 2 Commented Code Listing pORCECKCkCkckckckckckokokckokokck koc k koe RARA KR ko ke koc ke ke MPASM Assembler Control Directives Example Program 2 e Perform calculations i PRRRKRREKKRKR RK KR RK KE koc ke koe k ck hock ke ke ke ke ko ke ek ek include p16f877a inc Include header file define Tdistancel 50 Define the symbol Tdistancel define Tdistance2 25 Define the symbol Tdistance2 undefine Tdistance2 Remove Tdistance2 from th
313. overlap another section Use the m mapfile switch to generate an error map file The error map will show the sections which were allocated prior to the error Section secName has a memory nemName which is not defined in the linker script file Add a CODEPAGE DATABANK or SHAREBANK directive for the undefined memory to the linker script file Section secName type is non overlay and absolute but occurs in more than one input file An absolute section with the name secName may only occur in a single input file Relocatable sections with the same name may occur in multiple input files Either remove the multiple absolute sections in the source files or use relocatable sections instead Starting addresses for absolute overlay section secName do not match across all input files A section with the name secName occurs in more than one input file However its absolute overlay starting address varies between files Change the section s address in the source files and rebuild the object modules Symbol symName has multiple definitions A symbol may only be defined in a single input module Symbol symName is not word aligned It cannot be used as the target of a branch call or goto instruction The target of a branch call or goto instruction was at an odd address but the instruction encoding cannot reference addresses that are not word aligned DS33014L page 290 1994 2013 Microchip Technology Inc Errors
314. pen Coff file filename for reading Could not open Coff file filename for writing Could not read archive magic string in library file filename Unable to find aux file name in string table Unable to find section name in string table Unable to find symbol name in string table O 1994 2013 Microchip Technology Inc DS33014L page 293 Assembler Linker Librarian User s Guide 14 6 OTHER ERRORS WARNINGS AND MESSAGES If you are using the linker with any of the utilities i e MPLIB librarian or you have not used the linker options w or x Windows OS or w or x Linux or Mac OS then you may need to look in the utility troubleshooting sections for your error MPLIB Librarian Chapter 17 Errors MP2COD and or MP2HEX Chapter 19 Errors and Warnings 14 7 COMMON PROBLEMS Although set up listing file properties with MPASM assembler directives none of these properties is appearing in my listing file Although MPASM assembler is often used with MPLINK object linker MPASM assembler directives are not supported in MPLINK linker scripts See Section 10 3 Command Line Interface for control of listing and hex file output How do split up linear memory in the linker script file Currently the only name linear memory can be is 1inear0 and nothing else due a limitation in the linker This prevents your from splitting the linear memory region because names other than 1inear0 cannot be used DS33014L
315. pend the current directory and the directory C PROJECTS INCLUDE to the library object search path the following line should be added to the linker script file LIBPATH C PROJECTS INCLUDE 11 3 2 LKRPATH Linker script files that are included using a linker script INCLUDE directive are searched for using the linker script file search path The following directive appends additional search directories to the linker script file search path LKRPATH lkrpath where 1krpath is a semicolon delimited list of directories EXAMPLE 11 2 LKRPATH EXAMPLE To append the current directory s parent and the directory C PROJECTS SCRIPTS to the linker script file search path the following line should be added to the linker script file LKRPATH C PROJECTS SCRIPTS 11 3 3 FILES The following directive specifies object or library files for linking FILES objfile libfile objfile libfile where objfile libfileis either an object or library file Note More than one object or library file can be specified in a single FILES directive EXAMPLE 11 3 FILES EXAMPLE To specify that the object module main o be linked with the library file math lib the following line should be added to the linker script file FILES main o math lib O 1994 2013 Microchip Technology Inc DS33014L page 237 Assembler Linker Librarian User s Guide 11 34 INCLUDE The following directive includes an additional linker s
316. pplication code You no longer need to add a device specific linker script file to the command line or your MPLAB X IDE or MPLAB IDE v8 project the linker will find the appropriate file for you as long as a device has been specified However if you want to use a non standard linker script file you will have to add that manually Depending on the hardware debug tool you want to use you may need to set certain conditional symbols on the command line see Example 11 8 4 or to select the Build Configuration as Debug in MPLAB IDE v8 only Linker script files are the command files of the linker They specify Program and data memory regions for the target part Stack size and location for MPLAB C18 A mapping of logical sections in source code into program and data regions Linker script directives form the command language that controls the linker s behavior There are four basic categories of linker script directives Each of these directives plus some useful linker script caveats are discussed in the topics listed below Note Linker script comments are specified by Le any text between a and the end of a line is ignored Topics covered in this chapter Standard Linker Scripts Linker Script Command Line Information Linker Script Caveats Memory Region Definition Logical Section Definition STACK Definition Conditional Linker Statements 1994 2013 Microchip Technology Inc DS33014L page 235 Asse
317. pported relocation type A relocation type was specified that is not currently supported by the linker 14 4 LINKER WARNINGS MPLINK linker warnings are listed alphabetically below Fill pattern for memory memName doesn t divide evenly into unused section locations Last value was truncated If a fill pattern is specified for a ROM section but the free space in that section isn t evenly divisible by the fill pattern size this warning will be issued to warn of incomplete patterns la command line option ignored with x x or x prevents the generation of a hex file Therefore specifying the format of hex output file with a or a is irrelevant In command line option ignored with w w or w prevents the generation of a Ist file Therefore specifying the number of lines per listing page with n or n is irrelevant DS33014L page 292 1994 2013 Microchip Technology Inc Errors Warnings and Common Problems 14 5 COFF FILE ERRORS All the COFF errors listed below indicate an internal error in the file s contents Please contact Microchip support if any of these errors are generated Coff file filename could not read file header Coff file filename could not read line numbers Coff file filename could not read optional file header Coff file filename could not read raw data Coff file filename could not read relocation info Coff file filename could not read section header Coff
318. pt below shows how the linker can assign the relocatable application code to the user code memory region page that is not protected The other program memory regions can only be populated if the CODE directive used in the source files specifies placement of code within these protected memory regions This linker script file is designed to accommodate all three boot loader design considerations demonstrated in this chapter boot lkr The linker script file for boot loader and application code example projects CODEPAGE NAME vectors START 0x0 END 0x29 PROTECTED CODE PAGE NAME boot START 0x2A END 0x1FF PROTECTED LFDEF __DEBUGCODESTART CODEPAGE NAME page START 0x200 END _CODEEND CODEPAGE NAME debug START _DEBUGCODESTART END _CEND PROTECTED HE LSE CODEPAGE NAME page START 0x200 END 0x1FFFF TFI CODEPAGE NAME idlocs START 0x200000 END 0x200007 PROTECTED CODE PAGE NAME config START 0x300000 END 0x30000D PROTECTED CODE PAGE NAME devid START 0x3FFFFE END 0x3FFFFF PROTECTED CODE PAGE NAME eedata START 0xF00000 END 0xF003FF tee O 1994 2013 Microchip Technology Inc DS33014L page 273 Assembler Linker Librarian User s Guide 13 5 2 3 EXAMPLE 1 ASSEMBLER BOOT LOADER SOURCE CODE In this example the boot load
319. r data must be stored in nonvolatile program memory ROM For each initialized data section the linker creates a section in program memory The data is moved by initializing code supplied with MPLAB C18 and MPASM assembler to the proper RAM location s at start up The names of the initializer sections created by the linker are the same as the initialized data sections with a_i appended For example if an input object module contains an initialized data section named idata_main o the linker will create a section in program memory with the name idata_main o_i which contains the data In addition to creating initializer sections the linker creates a section named cinit in program memory The cinit section contains a table with entries for each initialized data section Each entry is a triple which specifies where in program memory the initializer section begins where in data memory the initialized data section begins and how many bytes are in the initialized data section The boot code accesses this table and copies the data from ROM to RAM 12 6 RESERVED SECTION NAMES Both the MPASM assembler and the MPLAB C18 C compiler have reserved names for certain types of sections Please see the documentation for these tools to ensure that you do not use a reserved name for your own section The linker will be unable to generate the application if there is a section naming conflict E KE EEA lt A ER ae DS33014L page 254 O 1994 2013 Microchip
320. ranslated into a program for the PIC18F452 This may require changing the instruction mnemonics that are not the same between the devices assuming that register and peripheral usage were similar Also configuration settings may be different The CONFIG syntax with one operand is not recognized by PIC18 and PIC16F1XXX MCUs The rest of the directive and macro language will be the same 1994 2013 Microchip Technology Inc DS33014L page 49 Assembler Linker Librarian User s Guide 1 5 ASSEMBLER COMPATIBILITY ISSUES The MPASM assembler is compatible with the MPLAB X IDE and MPLAB IDE v8 integrated development environments and all Microchip PIC1X MCU development systems currently in production The MPASM assembler supports a clean and consistent method of specifying radix see Section 3 4 Numeric Constants and Radix You are encouraged to develop using the radix and other directive methods described within this document even though certain older syntaxes may be supported for compatibility reasons 1 6 ASSEMBLER OPERATION The MPASM assembler can be used in two ways To generate absolute code that can be executed directly by a microcontroller To generate relocatable code that can be linked with other separately assembled or compiled modules 1 6 1 Generating Absolute Code Absolute code is the default output from the MPASM assembler This process is shown below K gt code asm MPASM code hex Programmer a
321. ration When generating a linkable object file this directive can also be used to declare initialized data values In this case the values will be padded with 34 RETLW instead of 00 as in examples Refer to the idata directive for more information For PIC18 devices use code pack with db since it is desired to not have bytes padded with zeroes See the description of code pack for more information 4 164 See Also data de dt dtm dw idata code pack 4 16 5 Simple Examples Example1 PIC16 Devices db OxOf t 0xOf e OxOtf s Ox0f Er in ASCII 0x0F74 OxOF65 OxOF73 OxOF74 0x0a00 Example 2 PIC18 Devices DATE ME Gig MEN font ASCII 0x6574 0x7473 0x000a 4 16 6 PIC16 Application Example db This example shows the usefulness of directive db in storing one or more bytes or characters in program memory finclude p16f877a inc Include standard header file for the selected device ORG 0x0000 The following code will be programmed in reset address 0 goto start Jump to an address labelled start start Write your main program here goto Go to current line loop here ORG 0x1000 Store the string starting from 1000H DS33014L page 94 1994 2013 Microchip Technology Inc Directives Ch_stng db 0 M 0 C 0 U Ch strng contains 3 14 bit numbers 004Dh 0043h and 0055h These are ASCII equivalents of M C and U respectively tbl dta db 0 0xff Places 00ff in pro
322. re that the Diagnostics level is set to Errors Only Then enter a file name for a Cross reference file i e example xrf Under default gt MPASMX select MPLINK Ensure that the Hex File Format is set to INHX32 Then enter a file name to Generate map file e example map Click OK on the bottom of the dialog to accept the build options and close the dialog O 1994 2013 Microchip Technology Inc DS33014L page 29 Assembler Linker Librarian User s Guide Build the Project Right click on the project name MyASMProject in the project tree and select Build from the pop up menu The Output window should appear at the end of the build and display the build results FIGURE 5 OUTPUT WINDOW BUILD RESULTS tput MyASMProject Build Load Y X Tasks make f nbproject Makefile default mk SUBPROJECTS build conf make 1 Entering directory C Documents and Settings c08227 MPLABXProjects MyASMProjec make f nbproject Makefile default mk dist default production MyASMProject X production make 2 Entering directory C Documents and Settings c08227 MPLABXProjects MyASMProjec make 2 dist default production MyASMProject X production hex is up to date make 2 Leaving directory C Documents and Settings c08227 MPLABXProjects MyASMProject make 1 Leaving directory C Documents and Settings c08227 MPLABXProjects MyASMProject BUILD SUCCESSFUL total time 281ms Loading
323. rectives control how code is assembled e define Define a Text Substitution Label p 98 e include Include Additional Gource tie p 130 e undefine Delete a Substitution Label p 162 bankisel Generate Indirect Bank Selecting Code PIC12 16 MCUs p 77 banksel Generate Bank Selecting Code sssssesssss p 80 e constant Declare Symbol Constant p 89 send Eng Program BIOCK Leere ted exp hPa p 103 equ Define an Assembler Constant p 105 org Set Program Origin p 141 e pagesel Generate Page Selecting Code PIC10 12 16 MCUS p 144 pageselw Generate Page Selecting Code Using WREG Commands PIC10 12H6 MCUS toe erre te ere mee eee p 146 processor Set Processor Type eee p 147 e radix Specify Default Rad p 148 set Define an Assembler Variable nnnnsnnsseeseeenrrnrrnnsreestrenrrnrnennnen p 152 e variable Declare Symbol Variable sseseeeeeeseeeeesseerssseernseserrnsesreens p 163 4 2 2 Conditional Assembly Directives Conditional assembly directives permit sections of conditionally assembled code These are not run time instructions like their C language counterparts They define which code is assembled not how the code executes e D else Begin Alternative Assembly Block to if Conditional p 102 endif End Conditional Assembly Block see p 104 endw End a while Loop p
324. relocatable object files Using the linker script it decides where the code will be placed in program memory and where variables will be placed in RAM Resolves Addresses External references in a source file generate relocation entries in the object file After the linker locates code and data it uses this relocation information to update all external references with the actual addresses Generates an Executable Produces a hex file that can be programmed into a PIC1X MCU or loaded into an emulator or simulator to be executed Configures Stack Size and Location Allows MPLAB C18 to set aside RAM space for dynamic stack usage Identifies Address Conflicts Checks to ensure that program data do not get assigned to space that has already been assigned or reserved Provides Symbolic Debug Information Outputs a file that the IDE uses to track address labels variable locations and line file information for source level debugging 1994 2013 Microchip Technology Inc DS33014L page 223 Assembler Linker Librarian User s Guide 9 4 HOW MPLINK LINKER HELPS YOU MPLINK linker allows you to produce modular reusable code Control over the linking process is accomplished through a linker script file and with command line options The linker ensures that all symbolic references are resolved and that code and data fit into the available PIC1X MCU device MPLINK linker can help you with Reusable Source Code You can build up your application i
325. rger le de ge de eee de der ede ede der de db ee dee ARRE dee de te te deier de der ger LIST P 18F8720 include P18cxxx inc koe de dece che de deck ke deo E RE rk e KK e deck sk ecc M e Ak cn e c EK REKRRKRRARRRRERRREKRRRRERE gege de dee de de ce de de de R vectors code 0x200 RVReset Re mapped RESET vector bra main R IntH code 0x208 Re mapped HI priority interrupt vector RVIntH High priority interrupt vector code here retfie R IntL code 0x218 Re mapped LOW priority interrupt vector RVIntL Low priority interrupt vector code here Toro retfie user cod cod 0x22A main Entry into application code starts here end of main code section Ck Ck ck ck ck ck ck ck KK kk kk ck ck Ck Ck ck Ck Ck kk Sk KK kk kk kk Ck kk kk Ck ck kk Sk kk Sk Ck ck kk Sk kk kk kk kk kk ck ko ko kv kk kk AAA XX END 1994 2013 Microchip Technology Inc DS33014L page 275 Assembler Linker Librarian User s Guide 13 5 2 5 EXAMPLE 3 ASSEMBLER BOOT LOADER APPLICATION SOURCE CODE The final example demonstrates the possibility of combining both the boot loader and application code into a single program memory image that can be programmed into a target microcontroller at the same time Since the boot loader will be assembled and linked with the application source code files any references to external labels defined in the application code must be resolved by the linker To accomplish this the GLOBAL directive
326. ries using C pointers Chapter 14 Errors Warnings and Common Problems contains a descriptive list of the errors and warnings generated by the MPLINK linker as well as common problems and tool limitations DS33014L page 10 1994 2013 Microchip Technology Inc Preface Part 3 MPLIB Object Librarian Chapter 15 MPLIB Librarian Overview decribes what the MPLIB object librarian is what it does and how it works with other tools Also gives an overview of operation and discusses input output files Chapter 16 Librarian Interfaces reviews how to use the MPLIB librarian with MPLAB IDE and describes how to use the librarian on the command line Chapter 17 Errors contains a descriptive list of the errors generated by the MPLIB librarian Part 4 Utilities Chapter 18 Utilities Overview and Usage lists the available utilities and describes their usage Chapter 19 Errors and Warnings contains a descriptive list of the errors generated by the utilities Part 5 Appendices Appendix A Instruction Sets lists PIC MCU device instruction sets Appendix B Useful Tables provides some useful tables for code development ASCII Character Set lists the ASCII Character Set Hexadecimal to Decimal Conversions shows how to convert from hexadecimal to decimal numbers A A M
327. rious build tools Below is a generic MPLAB IDE project FIGURE 2 PROJECT RELATIONSHIPS MPLAB IDE Project SIMULATORS EMULATORS DEBUGGERS PROGRAMMERS The linker can choose the correct linker script file for your project source files ASSEMBLER COMPILER list and object files LIBRARIAN amp library file LINKER amp linker script file LINKER output files Utility amp output file DS33014L page 36 1994 2013 Microchip Technology Inc PIC1X MCU Language Tools and MPLAB IDE v8 In this MPLAB IDE project an assembly source file prog asm is shown with its associated assembler MPASM assembler MPLAB IDE will use this information to generate the object file prog o for input into the MPLINK object linker For more information on the assembler see the MPASM assembler documentation The C source file main c is also shown with its associated MPLAB C18 C compiler MPLAB IDE will use this information to generate an object file main o for input into the MPLINK object linker For more information on the compiler see the MPLAB C Compiler for PIC18 MCUs User s Guide DS51288 In addition precompiled object files precomp o may be included in a project with no associated tool required MPLAB C18 requires the inclusion of a precompiled standard code module c018i o for example For more information on available Microchip precompiled object files see the MPLAB C18 C compiler d
328. rmat parser Provided for backward compatibility fixed FIXED Use fixed format parser mm ON OFF On Print memory map in list file n nnn 60 Set lines per page p type None Set processor type for example PIC16F877 See also processor Note Processor type is set in MPLAB IDE or MPLAB X IDE projects pe type None Set processor type and enable extended instruction set for example LIST pe PIC18F4620 Only valid with processors which support the extended instruction set and the generic processor PIC18XXX Is overridden by command line option y or y disable extended instruction set Note Processor type is set in MPLAB IDE or MPLAB X IDE projects r radix hex Set radix hex dec oct See also radix st ON OFF On Print symbol table in list file t ON OFF _ Off Truncate lines of listing otherwise wrap w 0 1 2 0 Set the message level See also errorlevel x ON OFF On Turn macro expansion on or off Note All list options are evaluated as decimal numbers by default 4 43 4 See Also errorlevel expand noexpand nolist processor radix 4 43 5 Simple Example Set the processor type to PIC18F452 the hex file output format to INHX32 and the radix to decimal list p 18f452 f INHX32 r DEC 1994 2013 Microchip Technology Inc DS33014L page 131 Assembler Linker Librarian User s Guide 4 44 local DECLARE LOCAL MACRO VARIABLE 4 44 4 Syntax Preferred local label
329. rochip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Appendix A Instruction Sets A 1 INTRODUCTION PIC1X MCU instruction sets are used in developing applications with MPASM assembler MPLINK object linker and MPLIB object librarian Instructions listed here are grouped either by instruction width or device number ee Devices Supported 12 Bit PIC10F2XX PIC12C5XX PIC12CE5XX PIC16X5X PIC16C505 14 Bit PIC12C67X PIC12CE67X PIC12F629 675 PIC16X 16 Bit PIC18X Topics covered are Key to 12 14 Bit Instruction Width Instruction Sets 12 Bit Instruction Width Instruction Set 14 Bit Instruction Width Instruction Set 14 Bit Instruction Width Extended Instruction Set 12 Bit 14 Bit Instruction Width Pseudo Instructions Key to PIC18 Device Instruction Set PIC18 Device Instruction Set PIC18 Device Extended Instruction Set A 2 KEY TO 12 14 BIT INSTRUCTION WIDTH INSTRUCTION SETS Use this key to determine the meaning of abbreviations in the 12 and 14 bit instruction width instruction sets tables Field Description Register Files dest Destination either the WREG register or the specified register file location See d f Register file address 5 bit 7 bit or 8 bit n FSR or INDF number 0 or 1 p Peripheral register file address 5 bit r Port for TRIS x Don t care CO or 1 The assembler will generate c
330. rom mnemonics by one or more spaces or tabs Multiple operands must be separated by commas 1994 2013 Microchip Technology Inc DS33014L page 53 Assembler Linker Librarian User s Guide 1 7 14 COMMENTS Comments are text explaining the operation of a line or lines of code The MPASM assembler treats anything after a semicolon as a comment All characters following the semicolon are ignored through the end of the line String constants containing a semicolon are allowed and are not confused with comments 1 7 2 Include File inc An assembler include or header file is any file containing valid assembly code Usually the file contains device specific register and bit assignments This file may be included in the code so that it may be reused by many programs As an example to add the standard header file for the PIC18F452 device to your assembly code use include p18f452 inc Standard header files are located in C Program Files Microchip MPASM Suite 1 7 3 Listing File Ist An MPASM assembler listing file provides a mapping of source code to object code It also provides a list of symbol values memory usage information and the number of errors warnings and messages generated This file may be viewed in MPLAB X IDE by 1 selecting File gt Open File to launch the Open dialog 2 selecting All Files from the Files of type drop down list 3 locating the desired list file 4 clicking on th
331. s linker script file device lkr library file output files The linker will select this file for you The linker is executed after assembling or compiling relocatable object modules with the MPASM assembler and or MPLAB C18 C compiler The actual addresses of data and the location of functions will be assigned when the MPLINK linker is executed This means that you may instruct the linker via a linker script to place code and data somewhere within named regions of memory or if not specified to place into any available memory The linker script must also tell the MPLINK linker about the ROM and RAM memory regions available in the target PIC1X MCU device Then it can analyze all the input files and try to fit the application s routines into ROM and assign its data variables into available RAM If there is too much code or too many variables to fit the linker will give an error message The MPLINK linker also provides flexibility for specifying that certain blocks of data memory are reusable so that different routines which never call each other and which don t depend upon this data to be retained between execution can share limited RAM space When using a C compiler libraries are available for most PIC MCU peripheral functions as well as for many standard C functions The linker will only extract and link individual object files that are needed for the current application from the included libraries Thi
332. s Section 4 56 radix Specify Default Radix Section 3 4 Numeric Constants and Radix Warning Level Override any source file message level settings Reference Section 4 48 messg Create User Defined Message Hex Output Override any source file hex file format settings Reference Section 1 7 5 Hex File Formats hex hxl hxh Generated Files Enable disable various output files Reference Section 1 7 Assembler Input Output Files Case Sensitivity Enable disable case sensitivity If enabled the assembler will distinguish between upper and lower case letters DS33014L page 62 1994 2013 Microchip Technology Inc Assembler Interfaces Option Description Tab Size Set the list file tab size Reference Section 1 7 3 Listing File Ist Macro Expansion Override any source file macro expansion settings Reference Section 4 32 expand Expand Macro Listing Processor Override any source file processor settings Extended Mode Enable PIC18F extended instruction support Extra Options Any additional command line options Reference Section 2 5 Command Line Interface Save Settings on Exit Save these settings in mplab ini They will be used the next time you run the assembler 2 5 COMMAND LINE INTERFACE MPASM assembler can be invoked through the command line interface command prompt For the assemb
333. s To use the examples see Using MPLAB X IDE Using MPLAB IDE v8 Using the Command Line 13 2 1 Using MPLAB X IDE MPLAB X IDE provides a GUI method of developing your code 13 2 1 1 BUILDING APPLICATIONS To build an application with MPLAB X IDE 1 Use the Project wizard to create a project File gt New Project a Choose Project Select Embedded for the category and C ASM Stand alone Project for the project Click Next gt to continue b Select Device Select the device Click Next gt to continue c Select Header Select the header for this device if used d Select Tool Choose a development tool from the list Tool support for the selected device is shown as a colored circle next to the tool Mouse over the circle to see the support as text Click Next gt to continue e Select Compiler For assembly applications select MPASMX For C code applications or combined C code and assembly applications select C18 Click Next gt to continue f Select Project Name and Folder Enter a project name and then select a location for the project folder Click Finish to complete the project creation and setup 2 Once the project is created add the sample files to your project e g sourcel c source2 asm and if customized script lkr 3 Right click on the project name in the project tree and then select Properties to set up language tool options For MPLAB C compiler for PIC18 MCUs sample applic
334. s This directive is designed for use withthe maxram directive maxram directive must precede any badram directive Each expr must be less than or equal to the value specified by maxram Oncethe maxram directive is used strict RAM address checking is enabled using the RAM map specified by badram To specify a range of invalid locations use the syntax minloc maxloc 4 4 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation badramis not commonly used as RAM and ROM details are handled by the include files inc or linker script files 1 kr 4 4 4 See Also maxram 4 4 5 Simple Example include pl6c622 inc _ maxram OxOBF badram 0x07 0x09 0x0D 0xE badram 0x87 0x89 0x8D Ox8F 0x9E movwf 0x07 Generates invalid RAM warning movwf 0x87 Generates invalid RAM warning and truncation message 1994 2013 Microchip Technology Inc DS33014L page 75 Assembler Linker Librarian User s Guide 45 badrom IDENTIFY UNIMPLEMENTED ROM Note badrom is preceded by two underline characters 4 5 1 Syntax _ badrom expr expr expr expr 4 5 2 Description The maxromand _badrom directives together flag accesses to unimplemented registers _badrom defines the locations of invalid ROM addresses This directive is designed for use with the maxrom directive maxrom directi
335. s involving strings 7465 7374 696E 6720 6F75 7470 7574 2073 7472 696E 6720 6F6E dw testing output string one n 650A define str testing output string two BO61 movlw a 7465 7374 696E data testing first output string 6720 6669 7273 7420 6F75 7470 7574 2073 7472 696E 6700 DS33014L page 66 1994 2013 Microchip Technology Inc Expression Syntax and Operation 3 3 RESERVED WORDS AND SECTION NAMES You may not use the following words for label constant or variable names Directives see Chapter 4 Directives Instructions see Appendix A Instruction Sets The word main when using the assembler with an IDE Do not use a main label that cannot be reached by a simple reset and run for example a data label named main or a routine named main that will only be accessed under certain conditions as with an interrupt In addition the assembler has the following reserved section names TABLE 3 2 RESERVED SECTION NAMES Section Name Purpose access ovr Default section name for access ovr directive code Default section name for code directive idata Default section names for idata and idata acs directives idata acs respectively udata Default section names for udata udata acs udata ovr and udata acs udata shr directives respectively udata ovr udata shr 3 4 NUMERIC CONSTANTS AND RADIX MPASM assembler s
336. s means that relatively large libraries can be used in a highly efficient manner The MPLINK linker combines all input files and ensure that all addresses are resolved Any function in the various input modules that attempts to access data or call a routine that has not been allocated or created will cause the linker to generate an error Finally the linker calls the MP2HEX utility to generate the executable output The MPLINK linker also generates symbolic information for debugging your application with the IDE cof and map files A list file 1st can also be generated by calling the MP2COD utility O 1994 2013 Microchip Technology Inc DS33014L page 225 Assembler Linker Librarian User s Guide 9 7 LINKER INPUT OUTPUT FILES The MPLINK linker combines multiple object files into one executable hex file Input Files Object File Lo Relocatable code produced from a source file Library File lib A collection of object files grouped together for convenience Linker Script File Ikr Description of memory layout for a particular processor project Output Files COFF Object Module File Debug file used by MPLAB IDE v6 xx and later cof out Hex File Formats hex hxl Hexadecimal file with no debug information Suitable for use hxh in programming This file is generated by the utility MP2HEX Listing File Ist Original source code side by side with final binary code Note Requires lin
337. s 1 reg lo res 1 RST CODE 0x0 start start pagesel goto shift right macro by n i 0 while i lt by n Include standard header file for the selected devic Define the symbol i as a variable Allocate RAM for labels reg hi and reg lo The code section named RST is placed at program memory location 0x0 The next two are placed in ROT location labelled instructions code section Jumps to the anstatt Beginning of a macro which shifts register data n times Code length generated after assembly varies depending upon the value of parameter by n Initialize variable i Following 3 lines of assembly code are repeated as long as i lt by n Up to 100 lines of codes are allowed inside a while loop bcf STATUS C rrf reg hi F rrf reg_lo F i 1 Clear carry bit reg hi and reg lo contains 16 bit data which is rotated right through carry Increment loop counter i i cannot increment to more than 255 decimal endw endm PGM CODE start moviw 0x88 movwf reg hi movlw 0x44 movwf reg lo End while loop The loop will break here after i by n End of shift right macro This is the beginning of the code section named PGM It is a relocatable code section Since no absolute address is given along with directive CODE E Initialize reg hi and reg lo for observation DS33014L page 166 O 1994 2013 Microchip Techn
338. s code bra RVReset Branch to user s application code Else Bootloader execution starts here Ck Ck ck ck ck ck ck ck kk KK KK KK KKK KK kk Sk kk kk AAA KK AAA KK KK KK KK KK KK kk kk kk Sk kk kk ck ko ko Sk Sk Sk kv KK KK ko ko kok END DS33014L page 276 O 1994 2013 Microchip Technology Inc Sample Applications main_r asm This is a sample version of a main source code file that uses the GLOBAL directive to make the relocatable reset and interrupt vector labels available to the boot loader 3c 3e dece de ee dece dede deck dec dec eec eo dece ko ERRE REE de dees eode hec dece echec ecce de e dek de dere deed deer deck de ge de x main r asm dk ck ok X ITOK IER ke de e e dede ee Xe KO A IES IAEA IEK A C CK de eek e eK de ek e KC CR eee XL e eR e Ke LIST P 18F8720 include P18cxxx inc Define labels here but used outside this module global RVReset RVIntH RVIntL Ck Ck kk ck ck ck ck kk kk kk Ck Ck KKK KK kk Ck Sk KK KK KK KK KKK KKK KKK kk KK AAA RARA AAA AAA Sk Sk AAA k kA ko ko ko XX R vectors code 0x200 RVReset Re mapped RESET vector bra main R_IntH code 0x208 Re mapped HI priority interrupt vector RVIntH High priority interrupt vector code here retfie R_IntL code 0x218 Re mapped LOW priority interrupt vector RVIntL Low priority interrupt vector code here Toro retfie user cod cod 0x22A main Entry into application code starts here p by end of main code s
339. s missing the w or F after the register name but sometimes the bug is due to typing mov instead of movwf It is bestto fix any code that is causing this message The default destination could not be where you want the value stored and could cause the code to operate strangely 306 Crossing page boundary ensure page bits are set Generated code is crossing a page boundary This is a reminder message to tell you that code is being directed to a label that is on a page other than page O It is not an error or warning but a reminder to check your page bits Use the pagesel directive Section 4 53 pagesel Generate Page Selecting Code PIC10 12 16 MCUs before this point and remember to use another pagesel if returning to page 0 The assembler can t tell what path your code will take so this message is generated for any label in a page other than 0 You can use the errorlevel command to turn this and other messages on and off but be careful as you may not spot a paging problem with this message turned off For more about errorlevel see Section 4 30 errorlevel Set Message Level A similar message is 302 for banking DS33014L page 218 1994 2013 Microchip Technology Inc Errors Warnings Messages and Limitations 307 Setting page bits Page bits are being set with the LCALL or LGOTO pseudo op 308 Warning level superseded by command line value The warning level was specified on the command line as well
340. s reference file A cross reference file contains a x xrf listing of all symbols used in the assembly code Diagnostic level Select to display errors only errors and warnings or errors wvalue warnings and messages These will be shown in the Output window Hex file format absolute When assembling a single file the assembler may be used to ahex format assembly only generate a hex file Choose the format here When assembling multiple files the assembler generates object files which must be linked with the linker to generate a hex file Choose the hex file format for the linker in this case TABLE 1 5 ADDITIONAL CONTROLS Option Description Additional Options Enter additional command line options See the tool documentation for more options Option Description Click on option text to see more information in this tab if available Generated Command For selectable options click this tab to see the equivalent command line option Line MPLINK Select a category and then set up linker options For additional options see MPLINK object linker documentation Chapter 10 Linker Interfaces TABLE 1 6 ALL OPTIONS CATEGORY Option Description Command Line Generate map file Create a map file A map file provides information on the m map absolute location of source code symbols in the final output It also provides information on memory use indicating used unused memory Hex f
341. s to be specifically placed on page 0 See Section 5 3 7 Interrupts for more on the ISR code REIR R KE ER AE RE RRA KEK KE KKK KEK KR RR ko ke ek KK Main Program PRRRKREKKE RK KEKE KEK KE EK KEK koe hok RARA koc kk ke KK KK code Start Program DS33014L page 172 1994 2013 Microchip Technology Inc Assembler Examples Tips and Tricks Begin program code Because no address is specified the program memory location will be determined by the linker See Section 5 3 5 Program Memory CODE Sections and Paging for more on code Start GI E banksel CEE banksel bsf bsf PORTB TRISB TRISB INTCON INTCON INTCON GIE TOIE Clear PortB Select TRISB Bank 1 Set all PortB pins as outputs Select INTCON Bank 0 Enable Global Int s Enable TimerO Int First set up Port B pins to be all outputs using the data direction TRISB register Then set up Timer 0 and interrupts for later use Loop movlw movwf Call clrf pagesel call pagesel goto OxFF PORTB Delayl PORTB Delay2 Delay2 Loop Loop Set PortB Walt Clear PortB Select Delay2 Page Walt Select Loop Page Repeat Set all Port B pins high and wait Delay 1 Then set all Port B pins low and wait Delay 2 Repeat until program halted This will have the effect of flashing the pins of Port B PRERKEKKRKE RK KERR KEK KEE kc KEK KERR KK EK KR ko kc ke ke ek e Delay 1 Ro
342. se dw to store data in Flash PIC16FXXX devices as many of these devices can read all 14 bits of a program memory word at run time See the PIC16F877A data sheet for examples and more information 4 214 See Also data db idata 4 24 5 Simple Example dw 39 diagnostic 39 0x123 dw diagbase 1 O 1994 2013 Microchip Technology Inc DS33014L page 101 Assembler Linker Librarian User s Guide 4 22 else BEGIN ALTERNATIVE ASSEMBLY BLOCK TO if CONDITIONAL 4 22 4 Syntax Preferred else Supported else else 4 22 2 Description Used in conjunction with an if directive to provide an alternative path of assembly code should the i f evaluate to false e1 se may be used inside a regular program block or macro 4 223 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is not an instruction It is used to perform conditional assembley of code 4 22 4 See Also endif if 4 22 5 Simple Example if rate lt 50 incf speed F else decf speed F endif 4 22 6 Application Example if else endif See this example under if DS33014L page 102 1994 2013 Microchip Technology Inc Directives 4 23 end END PROGRAM BLOCK 4 23 1 Syntax end 4 23 2 Description Indicates the end of the program 4 233 Usage This directive is used in the following types of code absolute or relocatable For
343. seca 108 Errors Assembler 208 GOFF cT 293 COFF to COD Converter 307 Librarian Parse cooooononnconoconcnnnnnncconocancnanonnnnns 301 ideo 287 Linker Parse uiis petne oti eter store tae 285 Escape Sequences 66 Examples Application 3 Oefllie oa EE 99 178 182 include 170 HUNDA iia 99 178 bankiselzs ann nine lens 78 79 1994 2013 Microchip Technology Inc banksel 81 82 171 180 CDOS IN 83 CO Re t ee e EIE A 84 171 Constant 164 178 e KE 90 E EE 92 93 dp tonis tn oet iat Gone de Gene P t Gale 94 95 0 snnt Rete teet ee TE vec eere des 97 CILIATIS TTE 126 Cop 170 OG sudes idonee back te ad 83 CTI eMe Ud UN o AE ERN 126 MAMI erre terrere E EA cann 135 180 le EE 166 UE 152 171 EES 106 errorlevel 108 EXT a ee 111 externi kaki A eee tr de 114 jm 117 118 global 114 182 184 Ida ta en cdas 121 A RER RE RAR 126 def re ns ne te te 127 128 148 182 A S aA NEA E A Es 132 Tee ctt edu t RRE 135 180 MESS EE 138 Mii Ros 142 143 pagesel see eee 145 171 Te AR EE 148 E 150 171 182 184 Ee 152 178 e bie 155 171 182 184 Udala alisar 156 ie RE E 159 Ud da EE 160 variable 164 178 A Sn A te ee ERE 166 Examples Simple
344. ser s Guide 8 2 ASSEMBLER ERRORS MPASM assembler errors are listed numerically below 101 ERROR User error invoked with the error directive 102 Out of memory Not enough memory for macros define s or internal processing 103 Symbol table full No more memory available for the symbol table 104 Temp file creation error Could not create a temporary file Check the available disk space 105 Cannot open file Could not open a file If it is a source file the file may not exist If it is an output file the old version may be write protected To check for write protect right click on the file named by MPLAB X IDE or MPLAB IDE v8 in Windows Choose Properties and see if read only is checked If it is it cannot be modified by the IDE and will generate this error message This often happens when you save your project to a CD R or similar write once media as a backup and then copy the data to your computer Copying to a CD marks all files as read only they cannot be changed on a CD R and when you copy the files the attributes move with them making them all read only on your hard drive A good way to prevent this is to archive all of the files in one file such as a ZIP and then restore them from CD The archive will preserve the original file attributes 106 String substitution too complex A string substitution was attempted that was too complex Check for nesting of fdefine s 107 Illegal digit A
345. set the Build Configuration to Release Please see MPLAB IDE documentation concerning this control For more information on using MPLAB IDE consult the on line help that comes with this application or download printable documents from our website MPLAB C18 example code that may be used to create a C code project may be found in the MPLAB C Compiler for PIC18 MCUs User s Guide DS51288 1994 2013 Microchip Technology Inc DS33014L page 45 Assembler Linker Librarian User s Guide NOTES DS33014L page 46 O 1994 2013 Microchip Technology Inc S ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Part 1 MPASM Assembler Chapter 1 MPASM Assembler Overview cecceeeeeeeeeeeeeeneeeeeeeeeeeeeeeeeeeeeeeeeeanees 49 Chapter 2 Assembler Interfaces sine 61 Chapter 3 Expression Syntax and Operation sise 65 Chapter 4 DirectiveS ns ER 71 Chapter 5 Assembler Examples Tips and Tricks esssssss 169 Chapter 6 Relocatable Objects esse 189 Chapter 7 Macro Language is 201 Chapter 8 Errors Warnings Messages and Limitations 207 1994 2013 Microchip Technology Inc DS33014L page 47 Assembler Linker Librarian User s Guide NOTES DS33014L page 48 O 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 1 MPASM Assembler Overview 1 1 INTRODUCTION An overview of the MPASM assemb
346. shr 4 62 5 Simple Example udata Varl res 1 Double res 2 DS33014L page 154 O 1994 2013 Microchip Technology Inc Directives 4 62 6 Application Example udata This program demonstrates the udata directive which declares the beginning of a section of uninitialized data udata does not set initialize the starting value of the variables you must do this in code include p16f877a inc groupl udata 0x20 groupl varl res 1 groupl var2 res 1 group2 udata group2 varl res 1 group2 var2 res 1 RST CODE 0x0 pagesel start goto start PGM CODE start banksel groupl varl clrf groupl varl clrf groupl var2 banksel group2 varl clrf group2 varl clrf group2 var2 goto end Include standard header file for the selected devic stored at locations 0x20 located at 0x20 located at 0x21 groupl data starting at groupl varl groupl var2 Declaration of group2 data The addresses for variables under this data section are allocated automatically by the linker The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST Jumps to the location labelled start This is the beginning of the code section named PGM It is a relocatable code section since no absolute address is given along with directive CODE E Go to current line loop here O 1994 2013 Microchip Technology Inc DS33014L page 155
347. single output library 115 file Library files are used in conjunction with the MPLINK linker to produce executable code FIGURE 15 1 MPLIB LIBRARIAN OPERATION files library file math lib 15 6 LIBRARIAN INPUT OUTPUT FILES The MPLIB librarian combines multiple object files into one library lib file Input Files Object File Lo Relocatable code produced from source files Output Files Library File lib A collection of object files grouped together for convenience 15 6 1 Object File o Object files are the relocatable code produced from source files The MPLIB librarian combines several object files into a single library file 15 6 2 Library File lib A library file may be created from object files by the MPLIB librarian or may be an existing standard library DS33014L page 298 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Chapter 16 Librarian Interfaces 16 1 INTRODUCTION How to use MPLIB librarian is discussed here For information on how librarian output can be used with the MPASM assembler and the MPLINK linker see the documentation for these tools Topics covered in this chapter MPLAB X IDE Interface MPLAB IDE v8 Interface Command Line Options Command Line Examples and Tips 16 2 MPLAB X IDE INTERFACE The MPLIB librarian may be used to create library files to be used in an MPLAB X
348. so some actual dialogs and or tool descriptions may differ from those in this document Please refer to our web site www microchip com to obtain the latest documentation available Documents are identified with a DS number This number is located on the bottom of each page in front of the page number The numbering convention for the DS number is DSXXXXXA where XXXXX is the document number and A is the revision level of the document For the most up to date information on development tools see the MPLAB IDE on line help Select the Help menu and then Topics to open a list of available on line help files INTRODUCTION This chapter contains general information that will be useful to know before using Assembler Linker Librarian User s Guide Items discussed include Document Layout Conventions Used Recommended Reading The Microchip Web Site myMicrochip Personalized Notification Service Customer Support DOCUMENT LAYOUT This document describes how to use the MPASM assembler the MPLINK object linker and the MPLIB object librarian to develop code for PIC microcontroller MCU applications All of these tools can work within the MPLAB Integrated Development Environment IDE For a detailed discussion about basic MPLAB IDE functions refer to MPLAB IDE documentation PIC1X MCU Language Tools and MPLAB X IDE provides an overview of how to use all of the tools in this manual together u
349. splay help screen i Generate a list file without a COD file k pathlist Add directories to linker search path 1 pathlist Add directories to library search path m filename Create map file filename n length Specify number of lines per listing page 0 No pagination o filename Specify output file filename Default is a out q Quiet mode no errors or warnings u sym value Specify multiple macros where symis a macro with alphanumeric characters and value is a numerical value If a value is not provided 0 will be used Verbose mode all errors and warnings Suppress the mp2cod exe utility Using this option will prevent the generation of a list file 1st and a COD file cod x Suppress the mp2hex exe utility Using this option will prevent the generation of a hex file hex hx1 hxh zsymbol value Adds the symbol defined into the symbol table For example z__ICD2RAM 1 adds ICD2RAM to the symbol table with a value of 1 There is no required order for the command line arguments however changing the order can affect the operation of the linker Specifically additions to the library object directory search path are appended to the end of the current library object directory search path as they are encountered on the command line and in command files Library and object files are searched for in the order in which directories occur in the library object directory search path Therefore chang
350. ssembler 9 0000000 When a source file is assembled in this manner all variables and routines used in the source file must be defined within that source file or in files that have been explicitly included by that source file If assembly proceeds without errors a hex file will be generated containing the executable machine code for the target device This file can then be used with a debugger to test code execution or with a device programmer to program the microcontroller 1 6 2 Generating Relocatable Code The MPASM assembler also has the ability to generate a relocatable object module that can be linked with other modules using Microchip s MPLINK linker to form the final executable code This method is very useful for creating reusable modules DS33014L page 50 1994 2013 Microchip Technology Inc MPASM Assembler Overview units lib ES main asm MCU MPASM assembler 0000000 ES more asm MPASM assembler Related modules can be grouped and stored together in a library using Microchip s MPLIB librarian Required libraries can be specified at link time and only the routines that are needed will be included in the final executable MPASM MPLIB unit1 asm assembler librarian N unit2 asm MPASM MPLIB units lib assembler librarian ES unit3 asm MPASM MPLIB assembler librarian unit3 o Refer to Chapter 6 Relocatable Objects for more information
351. ster will be generated For PIC16 extended and PIC18 devices a mov1b will be generated If the device contains only one bank of RAM no instructions will be generated 4 7 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive may be used with all PIC1X devices This directive is not needed for variables in access RAM PIC18 devices 4 7 4 See Also bankisel pagesel 4 7 5 Simple Example banksel Varl Select the correct bank for Varl movwf Varl Write to Varl DS33014L page 80 O 1994 2013 Microchip Technology Inc Directives 4 7 6 This program demonstrates the bankse1 directive This directive generates the appropriate code to set clear the RPO and RP1 bits of the STATUS register include p16f877a inc Application Example banksel Include standard header file for the selected devic groupl udata 0x20 groupl data stored at locations starting at 0x20 bank 0 groupl varl res 1 groupl varl located at 0x20 groupl var2 res 1 groupl var2 located at 0x21 group2 udata 0xA0 group2 data stored at locations starting at OxAO bank 1 group2 varl res 1 group2 var2 res 1 RST CODE 0x0 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST pagesel start Jumps to the location labelled
352. stination bit determines w or F for result Look at data movement and restructure Example A B gt A MOVF A WMOVF B W ADDWF B WADDWF A F MOVWF A 3 instructions2 instructions Careful use of the destination bits in instructions can save program memory Here register A and register B are summed and the result is put into the A register A destination option is available for logic and arithmetic operations In the first example the result of the ADDWF instruction is placed in the working register A MOVWF instruction is used to move the result from the working register to register A In the second example the ADDWE instruction uses the destination bit to place the result into the A register saving an instruction 5 9 3 TIP Z3 Conditional Bit Set Clear To move single bit of data from REGA to REGB Precondition REGB bit Test REGA bit and fix REGB if necessary BTFSS REGA 2BCE REGB 5 BCE REGB 5BTFSC REGA 2 BTFSC REGA 2BSE REGB 5 BSF REGB 5 4 instructions3 instructions One technique for moving one bit from the REGA register to REGB is to perform bit tests In the first example the bit in REGA is tested using a BTFSS instruction If the bit is clear the BCF instruction is executed and clears the REGB bit and if the bit is set the instruction is skipped The second bit test determines if the bit is set and if so will execute the BSF and set the REGB bit otherwise the instruction is skipped This s
353. storing data into program memory use with db or the EEPROM data memory use with de of a PIC18 device 4 10 4 See Also extern code global idata udata udata acs udata ovr udata shr 4 10 5 Simple Example 00001 LIST P 18Cxx 00002 00003 packed code pack 0x1F0 0001F0 01 02 03 00004 DB l1 2 3 0001F3 04 05 00005 DB 4 5 00006 00007 padded code 000000 0201 0003 00008 DB 14 2 3 000004 0504 00009 DB 4 5 00010 00011 END 1994 2013 Microchip Technology Inc DS33014L page 85 Assembler Linker Librarian User s Guide 4 101 config SET PROCESSOR CONFIGURATION BITS Note config is preceded by two underline characters 4 11 1 Syntax Preferred config expr config addr expr Note PIC18FXXJ devices do not support this directive Use config directive no underline characters Supported _ fuses expr 4 11 2 Description Sets the processor s configuration bits Before this directive is used the processor must be declared through the command line the list directive the processor directive a project if using MPLAB X IDE or Configure gt Select Device if using MPLAB IDE Refer to individual PIC1X microcontroller data sheets for a description of the configuration bits MCUs with a single configuration register Sets the processor s configuration bits to the value described by expr MCUs with multiple configuration registers For the address of a valid configuration byte specified by ad
354. t 188 O 1994 2013 Microchip Technology Inc DS33014L page 335 Assembler Linker Librarian User s Guide Conditional Bit Set Clear 187 Delay Techniques 186 Optimizing Destinations sssssss 187 Swap File Register with W 188 Using External Memory 188 lile en sore ee en iere eit i reis 154 Troubleshooting esses 207 U udatac e etas te ct teretes tre 154 194 data AS 156 194 udata O ion 158 194 udata ehr 160 194 undefined nan da 162 Unimplemented RAM 75 Unimplemented ROM 76 ele 69 191 Utilities Overview and Usage 305 V Variable D clarer nettes 163 Define ie dana Men ini 152 Local iii a a 132 W Warnings Assembler cce ehe tems 215 COFF to COD Converter 307 INKS oe ica nat nes eae 292 Watch Window 179 Watches Window 179 Web Site Microchip 14 Wet e octies Ox 165 White Space tee eene petras 52 Windows Shell Interface 62 Windows Support 17 DS33014L page 336 1994 2013 Microchip Technology Inc Index NOTES O 1994 2013 Microchip Technology Inc DS33014L page 337 MICROCHIP Worldwide Sales and Service AMERICAS Corporate Office 2355 West Chandler Blvd Ch
355. t 23f ADDWFC f d a ADD WREG and Carry bit to f WREG f C gt dest 17f ANDWF f d a AND WREG with f WREG AND f gt dest 6Bf CLRF ta Clear f 0f 1Ff COMF f d a Complementf NOT f gt dest 63f CPFSEQ f a Compare f with WREG skip if f WREG if fZWREG PC 4 gt PC fFWREG else PC 2 gt PC 65f CPFSGT f a Compare f with WREG skip if f gt f WREG if f gt WREG PC 4 gt PC WREG else PC 2 gt PC 61f CPFSLT f a Compare f with WREG skip if f lt f WREG if f lt WREG PC 4 gt PC WREG else PC 2 gt PC 07 DECF f d a Decrement f f 1 gt dest 2Ff DECFSZ f d a Decrement f skip if O f 1 dest if dest 0 PC 4 gt PC else PC 2 gt PC 4Ff DCFSNZ f d a Decrement f skip if not O f 1 gt dest if dest 0 PC 4 PC else PC 2 5 PC 2Bf INCF f d a Increment f f 1 dest 3Ff INCFSZ f d a Increment f skip if O f 1 gt dest if dest 0 PC 4 gt PC else PC 2 5 PC 4Bf INFSNZ f d a Increment f skip if not 0 f 1 gt dest if dest 0 PC 4 gt PC else PC 2 gt PC 13f IORWF f d a Inclusive OR WREG with f WREG OR f gt dest SIEF OVF f d a Move f f gt dest Cf OVFF f Movef to fd second word fof Ff 6Ff OVWE f a Move WREG to f WREG gt f 03 ULWF f a Multiply WREG with f WREG f gt PRODH PRODL 6Df EGF fya Negate f fof 37f RLCF d a Rotate left f through Carry register f C ra yo 0 ra DS33014L page 324 O 1994 2013 Microchip Technology
356. t INHX32 required An address above 32K was specified 134 Illegal hex file format An illegal hex file format was specified in the 1ist directive 135 Macro name missing A macro was defined without a name 136 Duplicate macro name A macro name was duplicated 137 Macros nested too deep The maximum macro nesting level was exceeded 138 Include files nested too deep The maximum include file nesting level was exceeded DS33014L page 210 1994 2013 Microchip Technology Inc Errors Warnings Messages and Limitations 139 Maximum of 100 lines inside WHILE ENDW A whi le endw can contain at most 100 lines 140 WHILE must terminate within 256 iterations A while endw loop must terminate within 256 iterations This is to prevent infinite assembly 141 WHILEs nested too deep The maximum while endw nesting level was exceeded 142 IFs nested too deep The maximum if nesting level was exceeded 143 Illegal nesting Macros if s and while s must be completely nested they cannot overlap If you have an if within a while loop the endif must come before the endw 144 Unmatched ENDC endc found without a cblock 145 Unmatched ENDM endm found without a macro definition 146 Unmatched EXITM exitm found without a macro definition 147 Directive operation only allowed when generating an object file The instruction operand shown only has meaning when a linkable object file is generated It cannot be used
357. t in the IDE so does not need to be set in code However if you wish to specify the MCU as well as radix in code you may do so using the processor and radix directives or list command i e list p 16f877a r hex The application is written as relocatable code i e you must use both the assembler and linker to generate the executable See PIC1X MCU Language Tools and MPLAB X IDE or PIC1X MCU Language Tools and MPLAB IDE v8 for information on how to set up a project using assembler files and a linker script The standard header file for the processor selected is included using include Registers are assigned using the udata res and equ directives Sections of code are created using the code statement Data memory banking and program memory paging is accomplished as needed using banksel and pagesel directives Finally the program is finished with an end 5 3 2 Commented Code Listing ck kk Ck kk Ck Ck Ck ck Ck kk Sk Ck Ck Ck Ck kk ko Sk kk ke Sk KA AA AA AAA MPASM Assembler Control Directives Example Program 1 i Alternate output on Port B between 1 s and O s PRRRKRRKKRRK KR EKER KK EKK KK KK hock e ke kk ke ko e ke ke ek include p16f877a inc Include header file O 1994 2013 Microchip Technology Inc DS33014L page 171 Assembler Linker Librarian User s Guide MPLAB X IDE and MPLAB IDE v8 have many header files inc available for supported devices These can be found in the installation director
358. t loader typically resides in the boot block region of the PIC18F8720 s program memory which is the first 512 bytes of memory from location 0000h to 01FFh The remaining program memory starting at location 0200h is available for relocatable application code and data lookup tables Other PIC18F microcontrollers offer larger boot block regions and will require slightly different linker script modifications than what is represented in this example However the concepts shown here can be migrated to these other PIC microcontrollers For this example program memory sections specified by the code and linker script are compared below Specific sections highlighted in this sample application SA3 example are noted TABLE 13 7 PROGRAM MEMORY MAP PIC18F8720 Program L e SA3 Memory Address Linker Script Section Source Code Section 0x000000 vectors Reset Interrupts Vectors IntH IntL 0x000029 gt 0x00002A boot_code Boot Loader Boot 0x0001FF 0x000200 page Remapped Vectors R_vectors R_IntH R_IntL Ox1FFFFF User Code Data Tables user code 13 5 2 2 ASSEMBLER LINKER SCRIPT To protect the boot block and vector memory regions the linker script file uses modified CODEPAGE directives to establish these memory regions and uses the PROTECTED modifier to prevent the linker from assigning any relocatable code that is not explicitly assigned to these regions The section of modified generic linker scri
359. ta or character table starting from any address in EE data memory ch tbl2 de PICmicro 8 EE data memory locations starting from 0 will be filled with 8 ASCII characters end 4 17 7 PIC18 Application Example de finclude p18f452 inc Include standard header file for the selected devic org OxF00000 The absolue address F00000h is mapped to the 0000 location of EE data memory for PIC18 devices You can create a data or character table starting from any address in EE data memory ch tbl2 de PICmicro 8 EE data memory locations starting from 0 will be filled with 8 ASCII characters end A SS a n AA O 1994 2013 Microchip Technology Inc DS33014L page 97 Assembler Linker Librarian User s Guide 4 18 define DEFINE A TEXT SUBSTITUTION LABEL 4 18 1 Syntax define name string 4 18 2 Description This directive defines a text substitution string Wherever name is encountered in the assembly code string will be substituted Using the directive with no string causes a definition of name to be noted internally and may be tested for using the ifdef directive This directive emulates the ANSI C standard for define Symbols defined with this method are not available for viewing using MPLAB X IDE or MPLAB IDE v8 418 3 Usage This directive is used in the following types of code absolute or relocatable For information on types
360. table code section since no absolute address is given along with directive CODE Any operation on varl affects var2 also since both variables are overlaid Go to current line loop here O 1994 2013 Microchip Technology Inc DS33014L page 159 Assembler Linker Librarian User s Guide 4 65 udata shr BEGIN AN OBJECT FILE SHARED UNINITIALIZED DATA SECTION PIC12 16 MCUs 4 65 4 Syntax label udata shr RAM address 4 65 2 Description This directive declares the beginning of a section of shared uninitialized data If 22be1 is not specified the section is named udata_shr The starting address is initialized to the specified address or will be assigned at link time if no address is specified This directive is used to declare variables that are allocated in RAM that is shared across all RAM banks i e unbanked RAM No code can be generated in this segment The res directive should be used to reserve space for data Note Two sections in the same source file are not permitted to have the same name 4 65 3 Usage This directive is used in the following types of code relocatable For information on types of code see Section 1 6 Assembler Operation This directive is similar to udata except that it is only used on parts with memory accessible from multiple banks udata shr sections are used with SHAREBANK locations in the linker script where as udata sections are used with DATABANK locations in the l
361. terrupt address 0x08 interrupt service routine and 0x1000 Delay 2 address It does not explicitly set the program start address but allows the linker to place the code appropriately Since the linker places addressed code first and then attempts to place the relocatable code based on size the likely program memory usage is shown below O 1994 2013 Microchip Technology Inc DS33014L page 175 Assembler Linker Librarian User s Guide FIGURE 5 2 PIC16F877A PROGRAM MEMORY MAP frst 0x0000 intrpt 0x0004 PageO lt isr 0x0008 code Start 0x0010 i 0x0800 Page 1 lt Page 2 2 pe Delay2 0x1000 r 0x1800 Page 3 lt a OxlFFF Since the actual location of the main code code section is unknown pagese l directives must be used to ensure that program branches to other sections are correct rst code 0x00 Reset Vector pagesel Start goto Start code Start Program pagesel Delay2 Select Delay2 Page call Delay2 Wait pagesel Loop Select Loop Page goto Loop Repeat For more on this directive see Section 4 53 pagesel Generate Page Selecting Code PIC10 12 16 MCUs 5 3 6 Banking In this example Port B must be configured causing a switch to data memory ban k 1 to access the TRISB register This change to bank 1 and subsequent return to bank 0 is easily accomplished using the bankse1 directive banksel TRISB
362. the code section named PGM It is a relocatable code section since no absolute address is given along with directive CODE El pORCECKCk kc kckck RK KR KEK KK KK KKK KKK KKK RARE RR KK EKER KKK EK KK KK KK KK KKK sub asm RER ER KE EH AK HR RARE RR RR KK KK RARE RRA RR RR RARA KE RK KK KK ke ke include p16f877a inc GLOBAL delay EXTERN delay value PGM COD El delay decfsz goto return delay value 1 delay end Include standard header file for the selected devic The variable delay declared GLOBAL in this module is included in an EXTERN directive in the module main asm The variable delay value declared EXTERN in this module is declared GLOBAL in the module main asm O 1994 2013 Microchip Technology Inc DS33014L page 115 Assembler Linker Librarian User s Guide 4 34 fill SPECIFY PROGRAM MEMORY FILL VALUE 4 34 4 Syntax label fill expr count 4 34 2 Description Generates count occurrences of the program word or byte PIC18 devices expr If bounded by parentheses expr can be an assembler instruction 4 343 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation Note For relocatable code do not use a symbol in another section in the expression expr This directive is often used to force known data in
363. the dialog find the following directory C Program FilesMMicrochipMMPASM Suite Example Select Example asm and Example2 asm Click Add gt gt to add these files to the project Click Next gt to continue 5 Review the summary of information If anything is in error use lt Back to go back and correct the entry Click Finish to complete the project creation and setup Once the Project Wizard has completed the Project window should contain the project tree The workspace name is Example mcw the project name is Example mcp and all the project files are listed under their respective file type For more on workspaces and projects see MPLAB IDE documentation FIGURE 3 EXAMPLE PROJECT TREE CSC Example mcp E Source Files Example asm Example2 asm Header Files Object Files Library Files Linker Scripts Other Files NENNEN 1994 2013 Microchip Technology Inc DS33014L page 43 Assembler Linker Librarian User s Guide Set Build Options Select Project gt Build Options gt Project to open the Build Options dialog 1 Click on the MPASM Assembler tab For Categories General check that the Default Radix is set to Hexadecimal For Categories Output check that the Diagnostics level includes all errors warnings and messages Then check the checkbox for Generate cross reference file 2 Click on the MPLINK Linker tab For Categories All Options
364. the map of valid RAM addresses to all addresses valid at and below expr expr must be greater than or equal to the maximum page 0 RAM address and less than 1000H This directive is designed for use with the badram directive Once the maxram directive is used strict RAM address checking is enabled using the RAM map specified by badram maxram can be used more than once in a source file Each use redefines the maximum valid RAM address and resets the RAM map to all locations 4 46 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation This directive is not commonly used in user code as RAM and ROM details are handled by the include files inc or linker script files 1 kx 4 46 4 See Also badram 4 46 5 Simple Example See the examples for badram DS33014L page 136 1994 2013 Microchip Technology Inc Directives 4 47 maxrom DEFINE MAXIMUM ROM LOCATION Note maxrom is preceded by two underline characters 4 47 1 Syntax maxrom expr 4 47 2 Description The maxromand badronm directives together flag accesses to unimplemented registers maxrom defines the absolute maximum valid ROM address and initializes the map of valid ROM addresses to all addresses valid at and below expr expr must be greater than or equal to the maximum ROM address of the target device This directive
365. this section In general you should not need to use the extended instruction set However if needed the extended mode is set using a special device configuration bit For more on extended mode see the MPLAB C18 C Compiler User s Guide DS51288 and your device data sheet To set up your IDE project for use with extended mode see the MPASM online help for Section MPLAB C18 Setup for PIC18 Extended Instruction Set Use MPLAB X IDE or Section MPLAB C18 Setup for PIC18 Extended Instruction Set Use MPLAB IDE v8 Instruction opcode is shown in hex by making certain assumptions either listed in the key or as a footnote For more information on the opcode bit values for each instruction as well as the number of cycles per instruction status bits affected and complete instruction details see the relevant device data sheet TABLE A 21 PIC18 EXTENDED INSTRUCTIONS Hex Mnemonic Description Function E8fk ADDFSR Ede Add literal to FSR FSR f k gt FSR f E8Ck ADDULNK k Add literal to FSR2 and return FSR2 k gt FSR2 TOS gt PC 0014 CALLW Call subroutine using WREG PC 2 gt TOS W gt PCL PCLATH gt PCH PCLATU gt PCU EB 0 z MOVSF z f MoveZ source to 1st word FSR2 z f Ffff f destination 2nd word EB 1 z MOVSS z z Move z source to 1st word FSR2 z gt FSR2 z Fxzz z destination 2nd word EAkk PUSHL k Store literal at FSR2 k gt FSR2 decrement FSR2 FSR2 1 gt FSR2 E9
366. tine Subroutine clrw Page unknown at assembly time retlw 0 E IEEE PO GOOQLEeEEQeA AzmMME Q TrRI r A e xo o_o oRrVm_ __ a E O 1994 2013 Microchip Technology Inc DS33014L page 197 Assembler Linker Librarian User s Guide 6 9 GENERATING THE OBJECT MODULE Once the code conversion is complete the object module is generated automatically in the IDE or by requesting an object file on the command line or in the shell interface When using MPASM assembler for Windows check the checkbox labeled Object File When using the command line interface specify the o or o option The output file will have a o extension 6 10 CODE EXAMPLE Since an eight by eight bit multiply is a useful generic routine it would be handy to break this off into a separate object file that can be linked in when required The absolute code file can be broken into two relocatable code files a calling file representing an application and a generic routine that could be incorporated in a library This code was adapted from application note AN617 Please see the Microchip website for a downloadable pdf of this app note EXAMPLE 6 9 ABSOLUTE CODE Input fixed point arguments in AARGBO and BARGBO Output product AARGxBARG in AARGBO AARGB1 Other comments truncated See AN617 PRRRKRREKKKRK KK KEK KKK ERK KKK KK hock koe ko ERK koc ke koc KEK RAR RARA koe heck ke hock kk koc kk KKK KK include pl6f877a inc Use any PIC16 device you like LO
367. tion the target memory block has enough space and the absolute section does not overlap other sections If no target memory block is assigned to an absolute section the linker tries to find the one for it If one can not be located an error is generated Since absolute sections can only be allocated at a fixed address assigned and unassigned sections are performed in no particular order 12 3 2 Relocatable Allocation Once all absolute sections have been allocated the linker allocates relocatable assigned sections For relocatable assigned sections the linker checks the assigned target memory block to verify that there is space available otherwise an error is generated The allocation of relocatable assigned sections occurs in the order in which they were specified in the linker script file After all relocatable assigned sections have been allocated the linker allocates relocatable unassigned sections The linker starts with the largest relocatable unassigned section and works its way down to the smallest relocatable unassigned section For each allocation it chooses the target memory block with the smallest available space that can accommodate the section By starting with the largest section and choosing the smallest accommodating space the linker increases the chances of being able to allocate all the relocatable unassigned sections 12 3 3 Stack Allocation The stack is not a section but gets allocated along with the sections The li
368. tion 13 2 How to Build the Sample Applications The large memory model must be used in this project At the end of Step 2 click the MPLAB C18 tab and chose the Category of Memory Model from the drop down list Under Code Model click Large code mode 64K For the command line use the m1 option when compiling DS33014L page 278 1994 2013 Microchip Technology Inc Sample Applications 13 6 1 1 C COMPILER MEMORY MAP The table below shows the memory mapping for the PIC18F8722 when used with the 1Mbyte external SRAM device Notice that the first 128K bytes of the external memory region is overlapped with the 128K bytes of internal program memory space and therefore cannot be accessed using the external memory bus Without any additional external memory address decoding the first 128K bytes of the SRAM are not accessible and therefore the first addressable location of SRAM is 20000h as used in this example SA4 TABLE 13 8 PROGRAM MEMORY MAP PIC18F8722 AND 1MB SRAM Program SRAM SA4 Memory Linker Script Section Source Code Section Address Address 0x000000 page Reset Interrupt 0x000000 OxO1FFFF Ox01FFFF vectors and On chip Memory gt 0x020000 0x020000 xsram External Memory SRAM_BASE romdata OxOFFFFF OxOFFFFF space 0x100000 Ox1FFFFF 13 6 1 2 C COMPILER LINKER SCRIPT The sections of modifed PIC18F8722 C compiler generic linker script file shown below
369. tive This directive declares the beginning of a section of uninitialized data finclude p18f452 inc Include standard header file for the selected device groupl udata acs 0x20 groupl data stored at access RAM locations starting at 0x20 groupl vari res 1 groupl varl located at 0x20 groupl var2 res 1 groupl var2 located at 0x21 group2 udata acs Declaration of group2 data The addresses for data under this Section are allocated automatically by the linker group2 varl res 1 All addresses be will allocated group2 var2 res 1 in access RAM space only DS33014L page 156 1994 2013 Microchip Technology Inc Directives RST goto PGM Start clrf clrf ELE clrf goto end CODE 0x0 start CODE groupl varl A groupl var2 A group2 varl A group2 var2 A The code sec is placed at location 0x0 goto start code section Jumps to the a start tion named RST program memory The instruction is placed in RST location labelled This is the beginning of the code section named PGM It is a relocatable code section since no absolute address is given along with directive CODE EM Q roupl varl roupl var2 EM Q Q roup2_var1 group2 var2 Go to curren initialized to initialized to initialized to initialized to El Zero Zero Zero Zero t line loop here In the code above A references the access R
370. to unused program memory This helps ensure that if code ever branches to an unused area at run time a fail safe condition occurs For example it is not uncommon to see this used with the watchdog timer WDT on a PIC16 device Unused program memory would be filled with goto or branch instructions to prevent execution of the c1rwdt instruction in code which would cause the device to reset See the device data sheet for more information on the WDT 4 34 4 See Also data dw org 4 34 5 Simple Examples Example 1 PIC10 12 16 MCU s fill 0x1009 5 fill with a constant fill GOTO RESE T VE CTOR NEXT BLOCK Example 2 PIC18 Devices include p18f252 inc org 0x12 failsafe goto org 0x100 fill goto failsafe 0x8000 2 Divide by 2 for 2 word instructions end DS33014L page 116 1994 2013 Microchip Technology Inc Directives 4 34 6 PIC16 Application Example i11 The fi11 directive is used to specify successive program memory locations with a constant or an assembly instruction include p16f877a inc Include standard header file for the selected devic RST CODE 0x0000 The code section named RST is placed at program memory location 0x0 The next two instructions are placed in code section RST pagesel start Jumps to the location labelled goto start start fill 0 INTRPT Fill with 0 up to address 3 INTRPT addr minus current addr INTRPT CODE 0x0004 The
371. ts 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 DS33014L page 2 1994 2013 Microchip Technology Inc ASSEMBLER LINKER LIBRARIAN MICROCHIP USER S GUIDE Table of Contents in II 9 PIC1X MCU Language Tools and MPLAB X IDE oooonnncccccccccccnnnncnccccnnonnnnnnnancnnnnnnnnnnnnnnannnnnnns 17 PIC1X MCU Language Tools and MPLAB IDE V8 ere 33 Part 1 MPASM Assembler Chapter 1 MPASM Assembler Overview 11 Introduction ucro p atch ete te ie i ec nee e Pede as 49 1 2 MPASM Assembler Defined 1 rettet er EE ir 49 1 3 How MPASM Assembler Helps You sie 49 1 4 Assembler Migration Pather issaraen etei aeaaeai eaaa net nn nn cnn tenens tenere retirer nenne sensn 49 1 5 Assembler Compatibility ISSUES issue 50 116 Assembler Operation s tre io t ttc eec ect p cete e ed c e eec treo bh Odo e qoc Sue atadas ELE 50 1 7 Assembler Input Output Files c Une tea dide nn 52 Chapter 2 Assembler Interfaces 2 1 Introduction n nh Ero eet e oae ei a 61 2 2 MPPAB XIIDE Interface Rupe ea 61 2 3 MPLAB IDE v8 Interface iii 61 2 4 Windows Interface iison ei mans A Fu diee ca IP pee danger nn saec iude dedere cedes 62 2 5 Commiand EineInterface siirre ree it 63 Chapter 3 Expression Syntax and Operation Kale WEE 65 3 2
372. ts any literal of 32 bits to 4 separate RAM data values In this example the literal 0x12345678 is put in the desired 8 bit registers as 0x12 0x34 0x56 and 0x78 Any literal can be unpacked this way using this macro include p16F877A inc udata 0x20 Out 0 res 1 LSB Outl res 1 B Out2 res 1 ME Out3 res 1 MSB Unpack32 MACRO Var Address Var 32 bit literal to be unpacked BANKSEL Address Address specifies the LSB start movlw Address Use FSR and INDF for indirect movwf FSR access to desired address movlw Var amp H FF Mask to get LSB movwf INDF Put in first location movlw Var gt gt D 08 amp H FF Mask to get next byte of literal incf FSR F Point to next byte movwf INDF Write data to next byte movlw Var gt gt D 16 amp H FF Mask to get next byte of literal incf FSR F Point to next byte movwf INDF Write data to next byte movlw Var gt gt D 24 amp H FF Mask to get last byte of literal incf FSR F Point to last byte movwf INDF Write data to last byte ENDM End of the Macro Definition ORG 0 Start TEST CODE for Unpack32 MACRO Unpack32 0x12345678 0ut0 Put Unpack Macro here goto Do nothing loop forever END DS33014L page 204 O 1994 2013 Microchip Technology Inc Macro Language 7 6 2 Constant Compare As another example if the following macro were written include picl6f877a inc compare file to constant and jump if file
373. ttribute when defining the section in the linker script file Section secName contains initialized data and can not have a ROM memory attribute specified in the linker script file Use only the RAM attribute when defining the section in the linker script file O 1994 2013 Microchip Technology Inc DS33014L page 289 Assembler Linker Librarian User s Guide Section secName contains initialized rom data and can not have a RAM memory attribute specified in the linker script file Use only the ROM attribute when defining the section in the linker script file Section secName contains uninitialized data and can not have a ROM memory attribute specified in the linker script file Use only the RAM attribute when defining the section in the linker script file Section secName has a memory memName which can not fit the absolute section Section secName start 0xHHHH length 0xHHHH The memory which was assigned to the section in the linker script file either does not have space to fit the section or the section will overlap another section Use the m mapfile switch to generate an error map file The error map will show the sections which were allocated prior to the error Section secName has a memory memName which can not fit the section Section secName length 0xHHHH The memory which was assigned to the section in the linker script file either does not have space to fit the section or the section will
374. upports the following radix forms for constants hexadecimal decimal octal binary and ASCII The default radix is hexadecimal the default radix determines what value will be assigned to constants in the object file when a radix is not explicitly specified by a base descriptor Note Theradixfor numeric constants can be made different from the default radix specified with the directives radix or list r Also allowable default radices are limited to hexadecimal decimal and octal Constants can be optionally preceded by a plus or minus sign If unsigned the value is assumed to be positive Note Intermediate values in constant expressions are treated as 32 bit unsigned integers Whenever an attempt is made to place a constant in a field for which it is too large a truncation warning will be issued As a a n 1994 2013 Microchip Technology Inc DS33014L page 67 Assembler Linker Librarian User s Guide The following table presents the various radix specifications TABLE 4 RADIX SPECIFICATIONS MPASM ASSEMBLER MPLINK LINKER Note Type Syntax Example 1 Binary B binary digits B 00111001 2 Octal O octal digits 0 771 3 Decimal D digits D 100 digits 100 4 Hexadecimal H hex digits H 9f Oxhex digits Ox9f 5 ASCII A character A C character LG 1 A binary integer is b or B followed by one or more of the binary digits 01 in single quotes 2 A
375. used in main asm and the EXTERN directive used in the boot loader source file allow the linker to resolve the relocated reset and interrupt vector labels defined in main asm and referenced in the 18Fboot_r asm For this example the same boot Ikr linker script file used in the previous examples is used to link the boot loader and application files together 18Fboot_r asm This sample version of the boot loader allows for relocatable vectors that are defined not in the boot loader but in the application source code Ck ck ck kk ck ck ck kk kk Ck Ck Ck Ck ck Ck Ck KK KK Ck ck kk kk kk ck Sk Ck ck kk kk kk Ck ck kk kk kk kk Sk kk kk ck kk Sk Sk Sk kv Sk k Mk ko ko ko kok 18Fboot r asm ERAS deed oue x cud xke dex exeo xxkwvxweWwkudeuwuxkueux dw weh w ux LIST P 18F8720 include P18cxxx inc Declare labels used here but defined outside this module extern RVReset RVIntH RVIntL KKEKKKKKKKKKKKKK KK KKK KK KK KK KK KK RA KKK KK KK kk kk KK KK KKK Sk kk Sk kk kk ck ko ko Sk Sk Sk kv kc k Mk ko ko ko kok Vectors code 0x0000 VReset bra Boot Start IntH code 0x0008 VIntH bra RVIntH Re map Interrupt vector IntL code 0x0018 VIntL bra RVIntL Be map Interrupt vector Ck ck kk ck ock kk kk kk kk Ck Ck ck ck Ck Ck KK KK KK KK KK KK KK AAA AAA RARA kk AA AAA AAA AAA AA AAA AAA KA ko ko kok Boot code 0x002A Define explicit Bootloader location Boot_Start Determine if bootloader should execute or branch to user
376. ute access overlay or shared section and in some itis not Change the section s type in the source files and rebuild the object modules Section secName can not fit the absolute section Section secName start 0xHHHH length 0xHHHH A section which has not been assigned to a memory in the linker script file can not be allocated Use the m lt mapfile gt switch to generate an error map file The error map will show the sections which were allocated prior to the error More memory must be made available by adding a CODEPAGE SHAREBANK or DATABANK directive or by removing the PROTECTED attribute or the number of input sections must be reduced Section romName can not have a RAM memory attribute specified in the linker script file Use only the ROM attribute when defining the section in the linker script file Section secName can not fit the section Section secName length 0xHHHH A section which has not been assigned to a memory in the linker script file can not be allocated Use the m lt mapfile gt switch to generate an error map file The error map will show the sections which were allocated prior to the error More memory must be made available by adding a CODEPAGE SHAREBANK or DATABANK directive or by removing the PROTECTED attribute or the number of input sections must be reduced Section secName contains code and can not have a RAM memory attribute specified in the linker script file Use only the ROM a
377. utine Timer0 delay loop x p kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk Delay1 movlw movwf Clr bsf banksel bcf banksel TLoop btfsc goto return OxFO TMRO DFLAG DFLAG OPTION_ OPTION_ DFLAG DFLAG TLoop DFLO R R G G TOCS F D Rm D DFLO Set Timer0 value 70x00 longest delay OxFF shortest delay Set flag bit Select Option Reg Bank 1 Start TimerO0 Select DFLAG Bank 0 Wait for overflow OxFF gt 0x00 After interrupt DFLO 0 1994 2013 Microchip Technology Inc DS33014L page 173 Assembler Linker Librarian User s Guide Use Timer 0 to create Delay 1 First give the timer an initial value Then enable the timer and wait for it to overflow from OxFF to 0x00 This will generate an interrupt which will end the delay See Section 5 3 7 Interrupts for more information ck kk KKK KK KK KK KK KK KK kk kk kk Sk kk Sk kk kk AAA ko ko ko k kk Delay 2 Routine Decrement delay loop ok ck Ck Ck kk Ck Sk Ck Ck Ck kk Sk kk Ck Ck kk kk kk Sk Sk Sk kA ko ko A ko ko ko kk kk decdly code 0x1000 Page 2 Place Delay2 routine at program memory location 0x1000 on page 2 See Section 5 3 5 Program Memory CODE Sections and Paging for more on code This code was placed on a page other than 0 to demonstrate how a program functions across pages Delay2 moviw OxFF Set DTEMP value movwf DTEMP 0x00 shortest de
378. ve must precede any badronm directive Each expr must be less than or equal to the value specified by maxrom Once the _maxrom directive is used strict ROM address checking is enabled using the ROM map specified by badrom To specify a range of invalid locations use the syntax minloc maxloc Specifically a warning will be raised in the following circumstances the target of a GOTO or CALL instruction is evaluated by the assembler to a constant and falls in a bad ROM region the target of an LGOTO or LCALL pseudo op is evaluated by the assembler to a constant and falls in a bad ROM region a hex file is being generated and part of an instruction falls in a bad ROM region 4 5 3 Usage This directive is used in the following types of code absolute or relocatable For information on types of code see Section 1 6 Assembler Operation badromis not commonly used as RAM and ROM details are handled by the include files inc or linker script files 1kr 4 5 4 See Also maxrom 4 5 5 Simple Example include p12c508 inc _ maxrom OxlFF badrom 0x2 0x4 OxA org 0x5 goto 0x2 generates a warning call 0x3 generates a warning org OxA moviw 5 generates a warning DS33014L page 76 1994 2013 Microchip Technology Inc Directives 4 6 bankisel GENERATE INDIRECT BANK SELECTING CODE PIC12 16 MCUs 4 6 1 Syntax bankisel label 4 6 2 Description This directive is an instruction
379. ves are used only when creating an object file access ovr Begin an Object File Overlay Section in Access RAM PIC18 MEUS riti ete t teet eerte es ette eb o eto e ie Rue ee p 74 e code Begin an Object File Code Section p 84 e code pack Begin an Object File Packed Code Section PIC18 MCUs p 85 e extern Declare an Externally Defined Label p 114 e dlobal ExportaLEab el dud e pte gat p 119 e idata Begin an Object File Initialized Data Section p 120 e idata acs Begin an Object File Initialized Data Section in Access RAM PIC18 MIS vista Gave Pea exa So ee ta etre d aa til p 122 e udata Begin an Object File Uninitialized Data Section p 154 udata acs Begin an Object File Access Uninitialized Data Section PIC18 MOUSE ere ant ed ded de aet e de te e eee p 156 udata ovr Begin an Object File Overlayed Uninitialized Data Section p 158 udata shr Begin an Object File Shared Uninitialized Data Section PIC12 16 le EE p 160 O 1994 2013 Microchip Technology Inc DS33014L page 73 Assembler Linker Librarian User s Guide 4 3 access ovr BEGIN AN OBJECT FILE OVERLAY SECTION IN ACCESS RAM PIC18 MCUs 4 3 1 Syntax label access ovr RAM address 4 3 2 Description This directive declares the beginning of a section of overlay data in Access RAM If label is not specified the section is named access ovr The starting address is in
380. voked by executing either mpasmx exe MPLAB X IDE or mpasmwin exe MPLAB IDE v8 in Windows Explorer or from a command prompt FIGURE 2 1 MPASM ASSEMBLER WINDOWS SHELL INTERFACE Source File Name Browse ES MPASM v5 46 Microchip Technology Inc Options MICROCHIP Rad Warning Level Hex Output Generated Files Default GG Default Default M Error File C Hexadecimal C All Messages C INHX8M F List File C Decimal C Warnings and Errors C INHX8S Cross Reference File C Octal C Errors Only C INHX32 I Object File Tab Size Extra Options X Exit Additional assembly options V Case Sensitive r Macro Expansion Default C On C Off Processor Default Extended Mode Select a source file by typing in the name or using the Browse button Set the various options as described below Default options are read from the source file Then click Assemble to assemble the source file Note When MPASM assembler is invoked through an IDE this options screen is not available For MPLAB X IDE use the project properties dialog File gt Properties to set options For MPLAB IDE v8 use the MPASM Assembler tab of the Build Options dialog in MPLAB IDE Project gt Build Options gt Project to set options Option Description Radix Override any source file radix settings Reference Section 4 43 list Listing Option
381. watchdog time off low voltage prog off Example 2 PIC17X Devices MPLAB IDE v8 Support Only include pl7c42 inc include file with config bit definitions config OxFFFF default configuration bits Example 3 PIC18 Devices include p18c452 inc Include standard header file for the selected devic code protect disabled __ CONFIG _CONFIGO CP OFF 0 Oscillator switch disabled RC oscillator with OSC2 as I O pin _ CONFIG _CONFIGI OSCS OFF 1 amp RCIO OSC 1 Brown OutReset enabled BOR Voltage is 2 5v _ CONFIG _CONFIG2 BOR ON 2 amp BORV 252 Watch Dog Timer enable Watch Dog Timer PostScaler count 1 128 _ CONFIG _CONFIG3 WDT ON 3 amp WDTPS 128 3 CCP2 pin Mux enabled __CONFIG _CONFIG5 CCP2MX ON 5 Stack over underflow Reset enabled _ CONFIG _CONFIG6 _STVR ON 6 1994 2013 Microchip Technology Inc DS33014L page 87 Assembler Linker Librarian User s Guide 4 12 config SET PROCESSOR CONFIGURATION BITS PIC18 MCUs 4 12 4 Syntax config setting value setting value 4 12 2 Description Defines a list of Configuration bit setting definitions This list sets the PIC18 processor s Configuration bits represented by setting to a value described by value Refer to individual PIC18 microcontroller data sheets for a description of the Configuration bits Available settings and values maybe found in both the standard processor include inc files and the P C18 Configuration Setti
382. with conditional statements to determine how the linker script will be interpreted by the linker If you are using MPLAB X IDE or MPLAB IDE v8 all macros listed in Table 11 1 will automatically be set for you For MPLAB IDE v8 the only exception is Debug vs Release which must be selected under the Build Configuration See MPLAB IDE documentation for more on how to set the Build Configuration If you are using the command line you must set the macros yourself The macros that are available for you to set are listed below On the command line precede the macro with u See Section 11 8 4 Examples of Use for some examples TABLE 11 1 LINKER SCRIPT MACROS Macro Use _CRUNTIME Link C code or mixed C code and assembly _ EXTENDEDMODE Use PIC18 extended microcontroller mode _DEBUG Specify debug mode as opposed to release or production mode _DEBUGCODESTART Set the start in program memory of the debug executive l e u_DEBUGCODESTART address _DEBUGCODELEN Set the size of the debug executive l e u_DEBUGCODELEN hexvalue _DEBUGDATASTART Set the start of data memory reserved registers l e u_DEBUGDATASTART address _DEBUGDATALEN Set the amount of data memory reserved l e u_DEBUGCODELEN hexvalue 11 8 3 Supporting Directives The DEFINE directive may be used to define a macro or define it and set its value The ERROR directive can be used
383. within an 8 bit file register 0 to 7 d Destination select bit d 0 store result in WREG d 1 store result in file register f default Fast Call Return mode select bit s 0 do not update into from shadow registers default S 1 certain registers loaded into from shadow registers Fast mode ro Bit values as opposed to Hex value Named Registers BSR Bank Select Register Used to select the current RAM bank FSR File Select Register PCL Program Counter Low Byte PCH Program Counter High Byte PCLATH Program Counter High Byte Latch PCLATU Program Counter Upper Byte Latch PRODH Product of Multiply High Byte DS33014L page 322 O 1994 2013 Microchip Technology Inc Instruction Sets Field Description PRODL Product of Multiply Low Byte STATUS Status Register TABLAT 8 bit Table Latch TBLPTR 21 bit Table Pointer points to a Program Memory location WREG Working register accumulator Named Bits C DC Z OV N ALU Status bits Carry Digit Carry Zero Overflow Negative TO Time out bit PD Power down bit PEIE Peripheral Interrupt Enable bit GIE GIEL H Global Interrupt Enable bit s Named Device Features MCLR Master clear device reset PC Program Counter TOS Top of Stack WDT Watchdog Timer Misc Descriptors Contents gt Assigned to lt gt Register bit field
384. within an if else clause 11 8 3 1 DEFINE This directive is used in the generic linker scripts to calculate the beginning and end of the debug sections in code and data memory Through this directive you can define an macro and associate a numerical value to it The value can only be calculated using an or operator over two previously defined macros Complex calculations must be constructed using combination of multiple DEFINE directives The following syntaxes are accepted DEFINE newmacro macrol macro2 DEFINE newmacro macrol macro2 DEFINE newmacro macrol macro2 DEFINE newmacro macrol macro2 newmacro may not be a previously defined macro macrol and macro are previously defined macros The numerical values associated to these macros will be used to calculate a numerical value for newmacro 11 8 3 2 ERROR An ERROR directive has been added to MPLINK linker This directive allows you to stop the linker and emit the message in front of it on the standard output The syntax of this directive is ERROR msg DS33014L page 246 1994 2013 Microchip Technology Inc Linker Scripts 11 8 4 Examples of Use In these examples the generic linker script for PIC18F6722 is used to demonstrate how different options for building a project can be selected 1 Building a C project Extended mode mplink exe p18F6722 u CRUNTIME u EXTENDEDMODE
385. y See Section 5 3 3 Header Files for more on headers udata Declare storage of RAM variables DTEMP res 1 Reserve 1 address location DFLAG res 1 Reserve 1 address location DFLO equ 0x00 Set flag bit 0 bit of DFLAG Set DTEMP to be a temporary register at a location in RAM determined at by the linker Set DFLAG to be the flag register at a location following the DTEMP register Set DFLO to a value to represent a bit in the DFLAG register in this case 0 See the Additional Comments section for more information rst code 0x00 Reset Vector pagesel Start Ensure correct page selected goto Start Jump to Start code Place the reset vector at program memory location 0x00 When the program resets the program will branch to Start intrpt code 0x04 Interrupt Vector goto ServInt Jump to service interrupt Place interrupt vector code at program memory location 0x04 since this device automatically goes to this address for interrupts When an interrupt occurs the program will branch to the ServInt routine isr code 0x08 Interrupt Service Routine ServInt banksel OPTION REG Select Option Reg Bank 1 bsf OPTION REG TOCS Stop Timer0 banksel INTCON Select INTCON Bank 0 bcf INTCON TOIF Clear overflow flag bet DFLAG DFLO Clear flag bit retfie Return from interrupt For the PIC16F877A there is not enough memory to add a pagesel Servint statement to insure proper paging Therefore the ISR code need

Download Pdf Manuals

image

Related Search

Related Contents

  Tecumseh AWF5524EXT Drawing Data  NPCA Detention/Retention Calculator User Manual Version 3.0  LED LENSER®*  TG3 Electronics TG-CMS-W-801 mice  

Copyright © All rights reserved.
Failed to retrieve file