Copyright: Copyright © 2000 by Microchip Technology, Inc.


Contents

MPASM Assembler Overview

What is MPASM Assembler

Migration Path

Compatibility Issues

How MPASM Assembler Helps You

Getting Started with MPASM Assembler

Overview of Assembler

Assembler Input/Output Files

Installation

Using MPASM Assembler

MPLAB IDE Project Tutorial

Directive Usage

Relocatable Objects

Macro Language

Troubleshooting

Errors/Warnings/Messages

Assembler Limitations

Reference

Command Line Options

Directive Summary

Expression Syntax and Operation

Instruction Sets

Hexadecimal to Decimal Conversion

ASCII Character Set

Glossary


What is MPASM Assembler

MPASM assembler (the assembler) is a DOS or Windows-based PC application that provides a platform for developing assembly language code for Microchip's PICmicro microcontroller (MCU) families. Generically, MPASM assembler will refer to the entire development platform including the macro assembler and utility functions.

Use of the Microchip MPASM assembler requires an IBM PC/AT® or compatible computer, running MS-DOS® V5.0 or greater, or Microsoft® Windows  95/98/NT/2000.

MPASM assembler supports all PICmicro MCU, memory, and secure data products from Microchip.

Reference Documents


How MPASM Assembler Helps You

MPASM assembler provides a universal solution for developing assembly code for all of Microchip's 12-bit, 14-bit, 16-bit, and Enhanced 16-bit core PICmicro MCUs. Notable features include:

All PICmicro MCU Instruction Sets

Command Line Interface

Command Shell Interfaces

Rich Directive Language

Flexible Macro Language

MPLAB IDE Compatibility


Migration Path

Since MPASM assembler is a universal assembler for all PICmicro MCU devices, an application developed for the PIC16C54 can be easily translated into a program for the PIC16C71. This would require changing the instruction mnemonics that are not the same between the devices (assuming that register and peripheral usage were similar). The rest of the directive and macro language will be the same.


Compatibility Issues

MPASM assembler is compatible with all Microchip development systems currently in production. This includes MPLAB SIM (PICmicro MCU discrete-event simulator), MPLAB ICE (PICmicro MCU Universal In-Circuit Emulator), PRO  MATE II (the Microchip Universal Programmer), and PICSTART Plus (the Microchip low-cost development programmer).

MPASM assembler supports a clean and consistent method of specifying radix. You are encouraged to develop new code using the methods described within this document, even though certain older syntaxes may be supported for compatibility reasons.


Installation

There are three versions of MPASM assembler:

a DOS version, MPASM.EXE, for DOS 5.0 or greater

a DOS-extender version, MPASM_DP.EXE

a Windows version, MPASMWIN.EXE (Recommended)

MPASM.EXE has a command line interface. MPASM.EXE may be used with DOS or a DOS window in Windows 3.x, Windows 95/98 or Windows NT/2000. You can use it with MPLAB IDE, though MPASMWIN.EXE is recommended.

MPASM_DP.EXE has a DOS shell interface. MPASM_DP.EXE may be used with DOS or a DOS window in Windows 3.x. You can use it with MPLAB IDE running under Windows 3.x, though MPASMWIN.EXE is recommended.

MPASMWIN.EXE has a Windows shell interface. MPASMWIN.EXE may be used with Windows 3.x, Windows 95/98 or Windows NT/2000. You can use this version with MPLAB IDE (recommended) or stand-alone.

If you are going to use MPLAB IDE with MPASM assembler, you do not need to install the assembler and supporting files separately. When MPLAB IDE is installed, MPASM assembler is also installed. To find out how to install MPLAB IDE, please refer to the MPLAB IDE User's Guide. You may obtain the MPLAB IDE software and user's guide either from the Microchip Technical Library CD or from our website.

If you are not going to use MPLAB IDE with MPASM assembler, you can obtain the assembler and supporting files separately either from the Microchip Technical Library CD or from our website. MPASM assembler will be in a zip file. To install:

Create a directory in which to place the files

Unzip the assembler files using either WinZip or PKZIP


Overview of Assembler

MPASM assembler can be used in two ways:

To generate absolute code that can be executed directly by a microcontroller.

To generate object code that can be linked with other separately assem bled or compiled modules.

Generating Absolute Code

Absolute code is the default output from MPASM assembler. This process is shown below.

When a source file is assembled in this manner, all values used in the source file must be defined within that source file, or in files that have been explicitly included. 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 in conjunction with a device programmer to program the microcontroller.

Generating Object Code

MPASM assembler also has the ability to generate an 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 that do not have to be retested each time they are used.

Related modules can also 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.

Refer to Relocatable Objects for more information on the differences between absolute and object assembly.


Assembler Input/Output Files

These are the default file extensions used by the assembler and the associated utility functions.

Input Files
Source Code (.asm)	Default source file extension input to assembler.
Include File (.inc)	Include (header) file
Output Files
Listing File (.lst)	Default output extension for listing files generated by assembler.
Error File (.err)	Output extension from assembler for error files.
Hex File (.hex, .hxl, .hxh)	Output extension from assembler for hex files.
Symbol and Debug File (.cod)	Output extension for the symbol and debug file. This file may be output from assembler or MPLINK linker.
Object File (.o)	Output extension from assembler for object files.


Source Code Format (.ASM)

The source code file may be created using any ASCII text file editor. It should conform to the following basic guidelines.

Each line of the source file may contain up to four types of information:

labels

mnemonics

operands

comments

The order and position of these are important. Labels must start in column one. Mnemonics may 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.

Whitespace or a colon must separate the label and the mnemonic, and the mnemonic and the operand(s). Multiple operands must be separated by a comma.

Sample MPASM Source Code (Shows multiple operands)

;

; Sample MPASM Source Code.  For illustration only.

;

         list    p=16c54

 Dest    equ     H'0B'

         org     H'01FF'

         goto    Start

         org     H'0000'

 Start   movlw   H'0A'

         movwf   Dest

         bcf     Dest, 3

         goto    Start

         end

Labels

A label must start in column 1. It may be followed by a colon (:), space, tab or the end of line.

Labels must begin with an alpha character or an under bar (_) and may contain alphanumeric characters, the under bar and the question mark.

Note: Do not use labels with a leading underscore and number, e.g., _2NDLOOP.

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. If a colon is used when defining a label, it is treated as a label operator and not part of the label itself.

Mnemonics

Assembler instruction mnemonics, assembler directives and macro calls must 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.

Operands

Operands must be separated from mnemonics by one or more spaces, or tabs. Multiple operands must be separated by commas.

Comments

MPASM 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.


Listing File Format (.LST)

The listing file has the following format.

The product name and version, the assembly date and time, and the page number appear at the top of every page.

The first column of numbers 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 PICmicro 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, and messages are embedded between the source lines, and pertain to the following source line.

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 memory map is not printed if an object file is generated.

Sample MPASM Listing File

MPASM 01.99.21 Intermediate   MANUAL.ASM   5-30-1997  15:31:05 PAGE  1

LOC  OBJECT CODE  LINE SOURCE TEXT

  VALUE

          00001 ;

          00002 ; Sample MPASM Source Code. For illustration only.

          00003 ;

          00004       list p=16c54

0000000B  00005 Dest  equ H'0B'

          00006

01FF      00007       org H'01FF'

01FF 0A00 00008       goto Start

          00009

0000      00010       org H'0000'

          00011

0000 0C0A 00012 Start movlw H'0A'

0001 002B 00013       movwf Dest

0002 0A00 00014       goto Start

          00015

          00016       end

MPASM 01.99.21 Intermediate   MANUAL.ASM   5-30-1997  15:31:05 PAGE  2

SYMBOL TABLE

  LABEL                             VALUE

Dest                              0000000B

Start                             00000000

__16C54                           00000001

MEMORY USAGE MAP ('X' = Used,  '-' = Unused)

0000 : XXX------------- ---------------- ---------------- ----------------

01C0 : ---------------- ---------------- ---------------- ---------------X

All other memory blocks unused.

Program Memory Words Used:     4

Program Memory Words Free:   508

Errors   :     0

Warnings :     0 reported,     0 suppressed

Messages :     0 reported,     0 suppressed

See also MPLINK Absolute Listing File (.LST)


Error File Format (.ERR)

MPASM by default generates an error file. This file can be useful when debugging your code. The MPLAB Source Level Debugger will automatically open this file in the case of an error. 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 will contain MPASM errors, warnings and messages.


Hex File Formats
Hex File Formats (.HEX, .HXL, .HXH)

This tool is capable of producing different hex file formats.

Format Name	Format Type	File Extension	Use
Intel Hex Format	INHX8M	.HEX	for standard programmers
Intel Split Hex Format	INHX8S	.HXL, .HXH	for odd/even ROM programmers
Intel Hex 32 Format	INHX32	.HEX	for 16-bit core programmers


Symbol and Debug File Format (.COD)

When MPASM is used to generate absolute code, it produces a COD file for use in MPLAB IDE debugging of code. The COD file name, including the path, has a 63 character limit.


Object File Format (.O)

Object files are the relocatable code produced from source files.


Intel Hex Format
Intel Hex Format - INHX8M (.HEX)

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. This file format is useful for transferring PICmicro MCU series code to PRO MATE II, PICSTART Plus and third party PICmicro MCU programmers.

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 - is a two digit hexadecimal byte count representing the number of data bytes that will appear on the line.

AAAA - is a four digit hexadecimal address representing the starting address of the data record.

TT - is a two digit record type record type that will always be '00' except for the end-of-file record, which will be '01'.

HH - is a two digit hexadecimal data byte, presented in low-byte/high-byte combinations.

CC - is a two digit hexadecimal checksum that is the two's complement of the sum of all preceding bytes in the record.

Example:

<file_name>.HEX

:1000000000000000000000000000000000000000F0

:0400100000000000EC

:100032000000280040006800A800E800C80028016D

:100042006801A9018901EA01280208026A02BF02C5

:10005200E002E80228036803BF03E803C8030804B8

:1000620008040804030443050306E807E807FF0839

:06007200FF08FF08190A57

:00000001FF


Intel Split Hex Format
Intel Split Hex Format - INHX8S (.HXL, .HXH)

The split 8-bit file format produces two output files: .HXL 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 .HXL 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:

<file_name>.HXL

:0A0000000000000000000000000000F6

:1000190000284068A8E8C82868A989EA28086ABFAA

:10002900E0E82868BFE8C8080808034303E8E8FFD0

:03003900FFFF19AD

:00000001FF

<file_name>.HXH

:0A0000000000000000000000000000F6

:1000190000000000000000010101010102020202CA

:100029000202030303030304040404050607070883

:0300390008080AAA

:00000001FF


Intel Hex 32 Format
Intel Hex 32 Format - INHX32 (.HEX)

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
32 k words.

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 - is a two digit hexadecimal byte count representing the number of data bytes that will appear on the line.

AAAA - is a four digit hexadecimal address representing the starting address of the data record.

TT - is a two digit record type:

00 - Data record

01 - End of File record

02 - Segment address record

04 - Linear address record

HH - is a two digit hexadecimal data byte, presented in low byte, high byte combinations.

CC - is a two digit hexadecimal checksum that is the two's complement of the sum of all preceding bytes in the record.


Errors

101	ERROR:

User error, invoked with the ERROR directive.

102	Out of memory.

Not enough memory for macros, #defines or internal processing. Eliminate any TSR's, close any open applications, and try assembling the file again. If this error was obtained using the Real Mode DOS executable, try using either the Windows version (MPASMWIN) or DPMI version (MPASM_DP)

103	Symbol table full.

No more memory available for the symbol table. Eliminate any TSR's, close any open applications, and try assembling the file again. If this error was obtained using the Real Mode DOS executable, try using either the Windows version (MPASMWIN) or DPMI version (MPASM_DP)

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.

106	String substitution too complex.

Too much nesting of #defines.

107	Illegal digit.

An 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 statement did not have a symbol to assign the value to.

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. Only addresses may be used as forward references. Constants and variables must be declared before they are used.

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.

The location counter can only advance to FFFF. After that, it wraps back to 0.

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 made 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.

123	Illegal directive.

Directive is not allowed for the selected processor; for example, the
_ _IDLOCS directive on the PIC17C42.

124	Illegal argument.

An illegal directive argument; for example, LIST STUPID.

125	Illegal condition.

A bad conditional assembly. For example, an unmatched ENDIF.

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 format INHX32 required.

An address above 32K was specified. For example, specifying the configuration bits on the PIC17CXXX family.

134	Illegal hex file format.

An illegal hex file format was specified in the LIST 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.

139	Maximum of 100 lines inside WHILE-ENDW.

A WHILE-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 not allowed when generating an object file.

The ORG directive is not allowed when generating an object file. Instead, declare a data or code section, specifying the address if necessary.

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 section.

Certain directives, such as GLOBAL and EXTERN, only have meaning when an 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 an 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 [HIGH|LOW]([<relocatable address label>]+[<offset>]).

152	Executable code and data must be defined in an appropriate section.

When generating an 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 of the form <relocatable address label> or <constant>.

154	Each object file section 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	UNKNOWN ERROR.

An error has occurred which the assembler cannot understand. It is not any of the errors described in this appendix. Contact your Microchip Field Application Engineer (FAE) if you cannot debug this error.


Warnings

201	Symbol not previously defined.

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. These warnings should be investigated, since they are often indications of the free-format parser interpreting something in a manner other than was intended (try assembling OPTION EQU 0x81 with LIST FREE).

212	Expected

Expected a certain type of argument. A description should be provided. For the warning, an assumption is made about the argument.

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.

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.

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.

If the _ _MAXRAM and _ _BADRAM directives are used, this warning flags use of any RAM locations declared as invalid by these directives. Note that the provided header files include _ _MAXRAM and _ _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.

Use of the TRIS and OPTION instructions is not recommended for a PIC16CXXX device.

225	Invalid label in operand.

Operand was not a valid address. For example, if the user tried to issue a CALL to a MACRO name.

226	UNKNOWN WARNING

A warning has occurred which the assembler cannot understand. It is not any of the warnings described in this appendix. Contact your Microchip Field Application Engineer (FAE) if you cannot debug this warning.


Messages

301	MESSAGE:

User message, invoked with the MESSG directive.

302	Register in operand not in bank 0. Ensure that bank bits are correct.

Register address was specified by a value that included the bank bits. For example, RAM locations in the PIC16CXXX are specified with 7 bits in the instruction and one or two bank bits.

303	Program word too large. Truncated to core size.

Program words for the PIC16C5X may only be 12-bits; program words for the PIC16CXXX may only be 14-bits.

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.

306	Crossing page boundary - ensure page bits are set.

Generated code is crossing a page boundary.

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 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.

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	UNKNOWN MESSAGE

A message has occurred which the assembler cannot understand. It is not any of the messages described in this appendix. Contact your Microchip Field Application Engineer (FAE) if you cannot debug this message.


Relocatable Objects

Since the introduction of MPASM assembler v2.00 and MPLINK linker v1.00, you have had the ability to generate and link precompiled object modules. Writing source code that will be assembled to an object module is slightly different from generating executable code directly to a hex file. MPASM assembler routines designed for absolute address assembly will require minor modifications to compile correctly into relocatable object modules.

Header Files

Program Memory

Instruction Operands

RAM Allocation

Configuration Bits and ID Locations

Accessing Labels from Other Modules

Paging and Banking Issues

Unavailable Directives

Generating the Object Module

Code Examples


Relocatable Objects - Header Files
Header Files

The Microchip supplied standard header files (e.g., p17c756.inc) should be used when generating object modules. These header files define the special function registers for the target processor.


Relocatable Objects - Program Memory
Program Memory

Program memory code must be preceded by a CODE section declaration.

Absolute Code:

Start  CLRW

       OPTION

       :

Relocatable Code:

CODE

Start CLRW

      OPTION

      :

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 program 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 interrupt vectors

Ensuring that a code segment does not overlap page boundaries

Example Relocatable Code:

Reset CODE  H'0lFF'

      GOTO  Start

Main  CODE

      CLRW

      OPTION


Relocatable Objects - Instruction Operands
Instruction Operands

There are some restrictions involving instruction operands. Instruction operands must be of the form:

[HIGH|LOW|UPPER] (<relocatable symbol> + <constant offset>)

where:

<relocatable symbol> is any label that defines a program or data memory address

<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.

If HIGH is used, only bits 8 through15 of the expression will be used. If LOW is used, only bits 0 through 7 of the expression will be used. If UPPER is used, only bits 16 through 21 of the expression will be used.


Relocatable Objects - RAM Allocation
RAM Allocation

RAM space must be allocated in a data section. Five types of data sections are available:

UDATA - Uninitialized data. This is the most common type of data section. Locations reserved in this section are not initialized and can be accessed only by the labels defined in this section or by indirect accesses.

UDATA_ACS - Uninitialized access data. This data section is used for variables that will be placed in access RAM of PIC18CXXX devices. Access RAM is used as quick data access for specified instructions.

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 sec tion is for temporary variables.

UDATA_SHR - Uninitialized shared data. This data section is used for variables that will be placed in RAM that is unbanked or shared across all banks.

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. The locations reserved by this section can be accessed only by the labels defined in this section or by indirect accesses.

The following example shows how a data declaration might be created.

Absolute Code:

CBLOCK   0x20

  InputGain, OutputGain  ;Control loop gains

  HistoryVector          ;Must be initialized to 0

  Templ, Temp2, Temp3    ;Used for internal calculations

ENDC

Relocatable Code:

               IDATA

HistoryVector  DB    0

               UDATA

InputGain      RES  1

OutputGain     RES  1

               UDATA_OVR

Templ          RES 1

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.

Relocatable Code:

                 00001         LIST p=17C44

                 00002         IDATA

0000 01 02 03    00003  Bytes  DB 1,2,3

0003 34 12 78 56 00004  Words  DW H'1234',H'5678'

0007 41 42 43 00 00005  String DB "ABC", 0


Relocatable Objects - Config Bits and ID Locations
Configuration Bits and ID Locations

Configuration bits and ID locations can still be defined in a relocatable object using the _ _CONFIG and _ _IDLOCS directives. 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.


Accessing Labels From Other Modules

Labels that are defined in one module for use in other modules must be exported using the GLOBAL directive. Labels must be defined before they are declared GLOBAL. Modules that use these labels must use the EXTERN directive to declare the existence of these labels. An example of using the GLOBAL and EXTERN directives is shown below.

Relocatable Code, Defining Module:

            UDATA

InputGain   RES 1

OutputGain  RES 1

            GLOBAL  InputGain, OutputGain

            CODE

Filter

            GLOBAL  Filter

            :       ; Filter code

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


Relocatable Objects - Paging and Banking
Paging and Banking Issues

In many cases, RAM allocation will span multiple banks, and executable code will span multiple pages. 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 are not known at assembly time, it is not always possible to place the proper code in the source file. For these situations, two new directives, BANKSEL and PAGESEL 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.

Absolute Code:

           LIST P=12C509

#include   "P12C509.INC"

Varl       EQU  H'10'

Var2       EQU  H'30'

           ...

           MOVLW  InitialValue

           BCF  FSR, 5

           MOVWF  Varl

           BSF  FSR, 5

           MOVWF  Var2

           BSF STATUS,  PA0

           CALL  Subroutine

           ...

Subroutine CLRW     ;In Page 1

           ...

           RETLW 0

Relocatable Code:

           LIST P=12C509

#include   "P12C509.INC"

           UDATA

Varl       RES 1

Var2       RES 1

           ...

           CODE

           MOVLW  InitialValue

           BANKSEL Varl

           MOVWF  Varl

           BANKSEL Var2

           MOVWF  Var2

           PAGESEL Subroutine

           CALL  Subroutine

           ...

Subroutine CLRW

           ...

           RETLW 0


Relocatable Objects - No ORG
Unavailable Directives

Macro capability and nearly all directives are available when generating an object file. The only directive that is not allowed is the ORG directive. This can be replaced by specifying an absolute CODE segment, as shown below.

Absolute Code:

Reset ORG H'01FF'

      GOTO Start

Relocatable Code:

Reset CODE H'0lFF'

      GOTO Start


Relocatable Objects - Generating the Module
Generating the Object Module

Once the code conversion is complete, the object module is generated 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 DOS command line interface, specify the /o option and toggle "Assemble to Object File" to "Yes." The output file will have a .o extension.


Relocatable Objects - Code Examples
Code Examples

The following is extracted from the example multiply routines given as a sample with MPASM assembler. Most of the comments have been stripped for brevity.

Absolute Code becomes

Relocatable Code, Calling File and

Relocatable Code, Library Routine

Absolute Code:

        LIST  P=16C54

        #INCLUDE  "P16C5X.INC"

        cblock H '020'

mulcnd                ; 8 bit multiplicand

mulplr                ; 8 bit multiplier

H_byte                ; High byte of the 16 bit result

L_byte                ; Low byte of the 16 bit result

count                 ; loop counter

        endc

mpy     clrf H_byte

        clrf L_byte

        movlw 8

        movwf count

        movf mulcnd,w

        bcf STATUS,C  ;Clear carry bit

Loop    rrf mulplr,F

        btfsc STATUS,C

        addwf H_byte,F

        rrf H_byte,F

        rrf L_byte,F

        decfsz count,F

        goto loop

        retlw  0

;*******************************************************

;          Test Program

;*******************************************************

start   clrw

        option

main    movf PORTB,w

        movwf mulplr  ; multiplier (in mulplr) = 05

        movf PORTB,W

        movwf mulcnd

call_m  call mpy      ; The result is in F12 & F13

                      ; H_byte & L_byte

        goto main

        ORG  01FFh

        goto start

END

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 above file can be broken into two files: a calling file representing an application and a generic routine that could be incorporated in a library.

Relocatable Code, Calling File

       LIST  P=16C54

       #INCLUDE "P16C5x.INC"

       EXTERN  mulcnd, mulplr, H_byte, L_byte

       EXTERN  mpy

       CODE

start  clrw

       option

main   movf  PORTB, W

       movwf mulplr

       movf  PORTB, W

       movwf mulcnd

call_m call  mpy    ; The result is in H_byte & L_byte

       goto main

Reset  CODE  H'0lFF'

       goto start

END

Relocatable Code, Library Routine:

        LIST  P=16C54

        #INCLUDE "P16C5x.INC"

        UDATA

mulcnd  RES l ; 8 bit multiplicand

mulplr  RES 1 ; 8 bit multiplier

H_byte  RES 1 ; High byte of the 16 bit result

L_byte  RES 1 ; Low byte of the 16 bit result

count   RES 1 ; loop counter

        GLOBAL mulcnd, mulplr, H_byte, L_byte

        CODE

mpy

        GLOBAL  mpy

        clrf H_byte

        clrf L_byte

        movlw 8

        movwf count

        movf muland, W

        bcf STATUS, C   ; Clear carry bit

loop    rrf mulplr, F

        btfsc STATUS, C

        addwf H_byte, F

        rrf H_byte, F

        rrf L_byte, F

        decfsz  count, F

        goto  loop

        retlw 0

END


Macro Language

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.

Macro Syntax

Macro Directives

Text Substitution

Macro Usage

Code Examples


Macro Syntax

MPASM assembler macros are defined according to the following syntax:

<label> macro [<arg1>,<arg2> ..., <argn>]

:

:

endm

where <label> is a valid assembler label 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, PICmicro 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 ENDM directive is encountered.

NOTE: Forward references to macros are not permitted.


Macro Directives Defined

There are directives that are unique to macro definitions. They cannot be used out of the macro context.

Macro Directives

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. For compatibility reasons, old ASM17 code that uses this format will assemble by MPASM assembler, but as mentioned before, you are encouraged to write new code based on the constructs defined within this help file to ensure upward compatibility.


Macro Text Substitution
Text Substitution

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.
#v(<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. For example, 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

     entry1   dw 0

     entry2   dw 0

     entry3   dw 0


Macro Usage

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.

The EXITM directive provides an alternate method for terminating a macro expansion. During a macro expansion, this directive causes expansion of the current macro to stop and all code between the EXITM 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.


Macro Code Examples
Code Examples

The following are examples of macros:

Eight-by-Eight Multiply

Constant Compare

Eight-by-Eight Multiply

  subtitle "macro definitions"

  page

;

;   multiply - is an eight by eight multiply macro,

; executing in program memory, optimized for speed,

; straight line code.

;

; This macro has five parameters as defined here:

;   arg1 - first eight bit literal to be multiplied

;   arg2 - second eight bit literal to be multiplied

;   dest_hi - memory location for high byte of result

;   dest_lo - memory location for low byte of result

;   temp - memory location for temporary storage

;

;   During the execution of this macro, the w register is

; destroyed.

;

;   The result of multiply is a 16 bit value stored in the

; two eight bit registers (dest_hi, dest_lo)

;

;   This macro is written for the PIC17C42.

;

;

multiply   macro arg1, arg2, dest_hi, dest_lo, temp

;

     local i = 0      ;   Establish a local index

                      ; variable and initialize it.

                      ;

     movlw arg1       ;   Setup the eight bit

     movwf temp       ; literal multiplier in the

                      ; memory location temp.

                      ;

     movlw arg2       ;   Setup the eight bit

                      ; literal multiplicand in the

                      ; w register.

                      ;

     clrf  dest_hi, F ;   Clear both the high and

     clrf  dest_lo, F ; the low destination

                      ; registers.

                      ;

     bcf  ALUSTA, C   ;   Clear the carry bit.

                      ;

     while  i < 8     ;   Use the loop to check all

                      ; eight bits of the

                      ; multiplier (temp).

                      ;

     btfsc temp, i    ;   Test the current

     addwf dest_hi, F ; multiplier bit, if temp,I

                      ; then add the multiplicand

                      ; to the high register.

                      ;

     rrcf dest_hi, F  ;   For each pass in the

     rrcf dest_lo, F  ; loop, right shift each

                      ; destination register using

                      ; the carry bit.

                      ;

i += 1                ;   Place this increment in

                      ; column 1 to avoid

                      ; Warning [207].

     endw             ;

     endm             ;

The macro declares all of the required arguments. In this case, there are five.  The LOCAL directive then establishes a local variable "i" that will be used as an index counter. It is initialized to zero.  A number of assembler instructions are then included.  When the macro is executed, these instructions will be written in line with the rest of the assembler source code.  The macro writes the multiplication code using an algorithm that adds for each bit set in the eight bits of the multiplier and uses right shifts. The WHILE directive is used for this function, continuing the loop until "I" is greater than or equal to eight.

Constant Compare

As another example, if the following macro were written:

include  "16cxx.reg"

;

; compare file to constant and jump if file

; >= constant.

;

cfl_jge  macro  file, con, jump_to

         movlw  con & 0xff

         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 & 0xff

         subwf  switch_val, w

         btfsc  status, carry

         goto   switch_on


Text Strings

A "string" is a sequence of any valid ASCII character (of the decimal range of 0 to 127) enclosed by double quotes.

Strings may be of any length that will fit within a 255 column source line. If 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.

Code Examples

See the examples below for the object code generated by different statements involving strings.

7465 7374 696E     dw  "testing output string one\n"

6720 6F75 7470

7574 2073 7472

696E 6720 6F6E

650A

               #define  str  "testing output string two"

B061                    movlw  "a"

7465 7374 696E          data  "testing first output string"

6720 6669 7273

7420 6F75 7470

7574 2073 7472

696E 6700

ANSI 'C' Escape Sequences

The assembler accepts the ANSI 'C' escape sequences to represent certain special control characters.

Escape Character	Description	Hex Value
\a	Bell (alert) character	07
\b	Backspace character	08
\f	Form feed character	0C
\n	New line character	0A
\r	Carriage return character	0D
\t	Horizontal tab character	09
\v	Vertical tab character	0B
\\	Backslash	5C
\?	Question mark character	3F
\'	Single quote (apostrophe)	27
\"	Double quote character	22
\0OO	Octal number (zero, Octal digit, Octal digit)
\xHH	Hexadecimal number


Numeric Constants and Radix

MPASM assembler supports the following radix forms: 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.

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.

The following table presents the various radix specifications.

Type	Syntax	Example
Decimal	D'<digits>' .<digits>	D'100' .100
Hexadecimal	H'<hex_digits>' 0x<hex_digits>	H'9f' 0x9f
Octal	O'<octal_digits>'	O'777'
Binary	B'<binary_digits>'	B'00111001'
ASCII	A'<character>' '<character>'	A'C' 'C'


High/Low/Upper Operators

Syntax

high  <operand>

low   <operand>

upper <operand>

Description

These operators are used to return one byte of a multi-byte label value. This is done to handle dynamic pointer calculations as might be used with table read and write instructions.

Example

movlw  low  size     ; handle the lsb's

movpf  wreg, low size_lo

movlw  high  size    ; handle the msb's

movpf  wreg,  high size_hi


Expression Syntax and Op
Expression Syntax and Operation

The following expression formats, syntax and operations are used by MPASM.

Text Strings

Numeric Constants and Radix

Arithmetic Operators and Precedence

High/Low/Upper Operators

Increment/Decrement (++/--) Operators


Arithmatic Operators and Precedence

Arithmatic operators and their precedence are listed below.

Operator	Example
$	Current/Return program counter	goto $ + 3
(	Left Parenthesis	1 + (d * 4)
)	Right Parenthesis	(Length + 1) * 256
!	Item NOT (logical complement)	if ! (a == b)
-	Negation (2's complement)	-1 * Length
~	Complement	flags = ~flags
high	Return high byte	movlw high CTR_Table
low	Return low byte	movlw low CTR_Table
upper	Return upper byte	movlw upper CTR_Table
*	Multiply	a = b * c
/	Divide	a = b / c
%	Modulus	entry_len = tot_len % 16
+	Add	tot_len = entry_len * 8 + 1
-	Subtract	entry_len = (tot - 1) / 8
<<	Left shift	flags = flags << 1
>>	Right shift	flags = flags >> 1
>=	Greater or equal	if entry_idx >= num_entries
>	Greater than	if entry_idx > num_entries
<	Less than	if entry_idx < num_entries
<=	Less or equal	if entry_idx <= num_entries
==	Equal to	if entry_idx == num_entries
=	Not equal to	if entry_idx != num_entries
&	Bitwise AND	flags = flags & ERROR_BIT
^	Bitwise exclusive OR	flags = flags ^ ERROR_BIT
|	Bitwise inclusive OR	flags = flags | ERROR_BIT
&&	Logical AND	if (len == 512) && (b == c)
||	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, set equal	entry_index %= 8
<<=	Left shift, set equal	flags <<= 3
>>=	Right shift, set equal	flags >>= 3
&=	AND, set equal	flags &= ERROR_FLAG
|=	Inclusive OR, set equal	flags |= ERROR_FLAG
^=	Exclusive OR, set equal	flags ^= ERROR_FLAG
++	Increment	i ++
- -	Decrement	i --


Incr/Decr Operators
Increment/Decrement (++/--) Operators

Syntax

<variable>++

<variable>--

Description

Increments or decrements a variable value. These operators can only be used on a line by themselves; they cannot be embedded within other expression evaluation.

Example

LoopCount  = 4

  while LoopCount > 0

        rlf Reg, f

LoopCount --

  endw


Directive Usage

Directives are assembler commands that appear in the source code but are not translated directly into 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 in this help file.

There are several basic types of directives provided by MPASM assembler. Each of these is listed below.  For a definition of the directive, click under Directive Type. For a list of directives for each type, click under Directive Summary.  For examples on how to use each type of directive, click under Examples of Use.

Directive Type	Directive Summary	Examples of Use
Control	Control	Example 1 Example 2
Conditional Assembly	Conditional Assembly	Examples
Data	Data	Examples
Listing	Listing	Examples
Macro	Macro	Examples
Object File	Object File	Examples
All	All	Examples


Directive Summary By Type
Directive by Type

The table below contains a summary of assembler directives by type.

Control Directives

Conditional Assembly Directives

Data Directives

Listing Directives

Macro Directives

Object File Directives

Click on any directive type for a definition of that type. Click on any directive to jump to that directive's  topic showing syntax, a detailed description, an example and related directives.

NOTE: Directives are not case-sensitive, e.g., cblock may be executed as CBLOCK, cblock, Cblock, etc.

Directive	Description	Syntax
CONTROL

CONSTANT	Declare Symbol Constant	constant <label> [= <expr>,...,<label> [= <expr>]  ]
#DEFINE	Define a Text Substitution Label	#define <name> [[(<arg>,...,<arg>)]<value>]
END	End Program Block	end
EQU	Define an Assembly Constant	<label>  equ <expr>
#INCLUDE	Include Additional Source File	include  <<include_file>> include "<include_file>"
ORG	Set Program Origin	<label>  org  <expr>
PROCESSOR	Set Processor Type	processor <processsor_type>
RADIX	Specify Default Radix	radix  <default_radix>
SET	Define an Assembler Variable	<label>  set  <expr>
#UNDEFINE	Delete a Substitution Label	#undefine <label>
VARIABLE	Declare Symbol Variable	variable <label> [= <expr>,...,   <label> [= <expr>] ]
CONDITIONAL ASSEMBLY

ELSE	Begin Alternative Assembly Block to IF	else
ENDIF	End Conditional Assembly Block	endif
ENDW	End a While Loop	endw
IF	Begin Conditionally Assembled Code Block	if  <expr>
IFDEF	Execute If Symbol is Defined	ifdef  <label>
IFNDEF	Execute If Symbol is Not Defined	ifndef <label>
WHILE	Perform Loop While Condition is True	while <expr>
DATA

_ _BADRAM	Specify invalid RAM locations	_ _badram <expr>
CBLOCK	Define a Block of Constants	cblock  [<expr>]
_ _CONFIG	Set configuration fuses	_ _config <expr> OR _ _config <addr>, <expr>
DA	Store Strings in Program Memory	[<label>] da <expr> [, <expr2>, ..., <exprn>]
DATA	Create Numeric and Text Data	data <expr>,[,<expr>,...,<expr>] data "<text_string>"[,"<text_string>",...]
DB	Declare Data of One Byte	db <expr>[,<expr>,...,<expr>]
DE	Declare EEPROM Data	de <expr>[,<expr>,...,<expr>]
DT	Define Table	dt <expr>[,<expr>,...,<expr>]
DW	Declare Data of One Word	dw  <expr> [,<expr>,...,<expr>]
ENDC	End an Automatic Constant Block	endc
FILL	Specify Memory Fill Value	fill  <expr>, <count>
_ _IDLOCS	Set ID locations	_ _idlocs <expr>
_ _MAXRAM	Specify maximum RAM address	_ _maxram <expr>
RES	Reserve Memory	res  <mem_units>
LISTING
ERROR	Issue an Error Message	error "<text_string>"
ERRORLEVEL	Set Messge Level	errorlevel 0|1|2|<+-><msg>
LIST	Listing Options	list [<option>[,...,<option>]]
MESSG	Create User Defined Message	messg "<message_text>"
NOLIST	Turn off Listing Output	nolist
PAGE	Insert Listing Page Eject	page
SPACE	Insert Blank Listing Lines	space  [<expr>]
SUBTITLE	Specify Program Subtitle	subtitl  "<sub_text>"
TITLE	Specify Program Title	title  "<title_text>"
MACRO

ENDM	End a Macro Definition	endm
EXITM	Exit from a Macro	exitm
EXPAND	Expand Macro Listing	expand
LOCAL	Declare Local Macro Variable	local  <label> [,<label>]
MACRO	Declare Macro Definition	<label> macro [<arg>,...,<arg>]
NOEXPAND	Turn off Macro Expansion	noexpand
OBJECT FILE

BANKISEL	Generate RAM bank selecting code for indirect addressing	bankisel <label>
BANKSEL	Generate RAM bank selecting code	banksel <label>
CODE	Begins executable code section	[<name>] code [<address>]
EXTERN	Declares an external label	extern <label> [ ,<label>]
GLOBAL	Exports a defined label	extern <label> [ .<label>]
IDATA	Begins initialized data section	[<name>] idata [<address>]
PAGESEL	Generate ROM page selecting code	pagesel <label>
UDATA	Begins uninitialized data section	[<name>] udata [<address>]
UDATA_ACS	Begins access uninitialized data section	[<name>] udata_acs [<address>]
UDATA_OVR	Begins overlayed uninitialized data section	[<name>] udata_ovr [<address>]
UDATA_SHR	Begins shared uninitialized data section	[<name>] udata_shr [<address>]


_ _BADRAM - Identify Unimplemented RAM

NOTE: badram is preceded by two underline characters, with no space in between these characters.  A space is added here for readibility only.

Syntax

_ _badram    <expr>[-<expr>][, <expr>[-<expr>]]

Description

The _ _maxram and _ _badram directives together flag accesses to unimplemented registers.  _ _badram defines the locations of invalid RAM addresses. This directive is designed for use with the _ _maxram directive. A _ _maxram directive must proceed any _ _badram directive. Each <expr> must be less than or equal to the value specified by _ _maxram. Once the _ _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>.

Example

See the example for _ _maxram.

See Also

_ _MAXRAM


BANKISEL - Generate Indirect Bank Selecting Code

Syntax

bankisel <label>

Description

For use when generating an object file. This directive is an instruction to the linker to generate the appropriate bank selecting code for an indirect access of the address specified by <label>. 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 bank selecting code. For 14-bit core devices, the appropriate bit set/clear instruction on the IRP bit in the STATUS register will be generated. For the 16-bit core devices, MOVLB or MOVLR will be generated. If the user can completely specify the indirect address without these instructions, no code will be generated.

For more information, refer to Create Relocatable Objects.

Example

movlw    Var1

movwf    FSR

bankisel Var1

:

movwf    INDF

See Also

BANKSEL PAGESEL


BANKSEL - Generate Bank Selecting Code

Syntax

banksel <label>

Description

For use when generating an object file. This directive is an instruction to the linker to generate bank selecting code to set the bank to the bank containing the designated <label>. 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 bank selecting code. For 12-bit core devices, the appropriate bit set/clear instructions on the FSR will be generated. For 14-bit devices, bit set/clear instructions on the STATUS register will be generated. For the 16-bit core devices, MOVLB or MOVLR will be generated. For the enhanced 16-bit core devices, MOVLB will be generated. If the device contains only one bank of RAM, no instructions will be generated.

For more information, refer to Create Relocatable Objects.

Example

banksel  Var1

movwf    Var1

See Also

BANKISEL PAGESEL


CBLOCK - Define a Block of Constants

Syntax

cblock [<expr>]

       <label>[:<increment>][,<label>[:<increment>]]

endc

Description

Define a list of named constants. Each <label> is assigned a value of one higher than the previous <label>. The purpose of this directive is to assign address offsets to many labels. The 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.

cblock is useful for defining constants in program and data memory.

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

  Queue: QUEUE_SIZE

  QueueHead, QueueTail

  Double1:2, Double2:2

endc

See Also

ENDC


CODE - Begin an Object File Code Section

Syntax

[<label>]    code    [<ROM address>]

Description

For use when generating an object file. 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 the same source file may not have the same name.

For more information, refer to Create Relocatable Objects.

Example

RESET     code    H'01FF'

          goto    START

See Also

EXTERN GLOBAL IDATA UDATA UDATA_ACS UDATA_OVR UDATA_SHR


_ _CONFIG - Set Processor Configuration Bits

NOTE: config is preceded by two underline characters, with no space in between these characters.  A space is added here for readibility only.

Syntax

_ _config <expr> OR _ _config <addr>, <expr>

Description

Sets the processor's configuration bits to the value described by <expr>. For PIC18CXXX devices, the address of a valid configuration byte must also be specified by <addr>. Refer to individual PICmicro microcontroller data sheets for a description of the configuration bits.

Before this directive is used, the processor must be declared through the command line, the list directive, or the processor directive. If this directive is used with the PIC17CXXX family, the Hex file output format must be set to INHX32 through the command line or the list directive.

Example

list p=17c42,f=INHX32

_ _config H'FFFF'   ;Default configuration bits

See Also

_ _IDLOCS LIST PROCESSOR


CONSTANT - Declare Symbol Constant

Syntax

constant <label>=<expr> [...,<label>=<expr>]

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 expressions.

Example

variable RecLength=64               ; Set Default

                                    ;   RecLength

constant BufLength=512              ; Init BufLength

         .                          ; RecLength may

         .                          ; be reset later

         .                          ; in RecLength=128

         .                          ;

constant MaxMem=RecLength+BufLength ;CalcMaxMem

See Also

SET VARIABLE


DA - Store Strings in Program Memory

Syntax

[<label>] da <expr> [, <expr2>, ..., <exprn>]

Description

Generates a packed 14-bit number representing two 7-bit ASCII characters. This is useful for storing strings in memory for the PICmicro MCU Flash ROM devices.

Examples

da "abcdef"

will put 30E2 31E4 32E6 3380 into program memory

da "12345678" ,0

will put 18B2 19B4 1AB6 0000 into program memory

da 0xFFFF

will put 0x3FFF into program memory


DATA - Create Numeric and Text Data

Syntax

[<label>] data <expr>,[,<expr>,...,<expr>]

[<label>] data "<text_string>"[,"<text_string>",...]

Description

Initialize one or more 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 PIC18CXXX, the first character is in the most significant byte of the word. On the PIC18CXXX, the first character is in the least significant byte of the word.

When generating an object file, this directive can also be used to declare initialized data values. Refer to the idata directive for more information.

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

See Also

DB DE DT DW IDATA


DB - Declare Data of One Byte

Syntax

[<label>] db <expr>[,<expr>,...,<expr>]

Description

Reserve program memory words with packed 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.

When generating an object file, this directive can also be used to declare initialized data values. Refer to the idata directive for more information.

Example

db 't', 0x0f, 'e', 0x0f, 's', 0x0f, 't', '\n'

See Also

DATA DE DT DW IDATA


DE - Declare EEPROM Data Byte

Syntax

[<label>] de <expr> [, <expr>, ..., <expr>]

Description

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.

When using de, make sure to specify the start of data memory at 0x2100 (org H'2100'), for use with programmers.

Although designed for initializing EEPROM data on the PIC16X8X, the directive can be used at any location for any processor.

Example

org H'2100'    ; Initialize EEPROM Data

de  "My Program, v1.0", 0

See Also

DATA DB DT DW


#DEFINE - Define a Text Substitution Label

Syntax

#define <name> [<string>]

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 IDE.

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 f19

See Also

#UNDEFINE #INCLUDE IFDEF IFNDEF


DT - Define Table

Syntax

[<label>] dt <expr> [, <expr>, ..., <expr>]

Description

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.

Example

dt  "A Message", 0

dt  FirstValue, SecondValue, EndOfValues

See Also

DATA DB DE DW


DW - Declare Data of One Word

Syntax

[<label>] dw <expr>[,<expr>,...,<expr>]

Description

Reserve program memory words for data, initializing that space to specific values. For PIC18CXXX devices, dw functions like db. 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 data directive.

When generating an object file, this directive can also be used to declare initialized data values. Refer to the idata directive for more information.

Example

dw 39, "diagnostic 39", (d_list*2+d_offset)

dw diagbase-1

See Also

DATA DB IDATA


ELSE - Begin Alternative Assembly Block to IF

Syntax

else

Description

Used in conjunction with an if directive to provide an alternative path of assembly code should the if evaluate to false. else may be used inside a regular program block or macro.

Example

speed macro rate

      if rate < 50

        dw slow

      else

        dw fast

      endif

      endm

See Also

ENDIF IF


END - End Program Block

Syntax

end

Description

Indicates the end of the program.

Example

list p=17c42

:      ; executable code

:      ;

end    ; end of instructions

See Also

ORG


ENDC - End an Automatic Constant Block

Syntax

endc

Description

endc terminates the end of a cblock list. It must be supplied to terminate the list.

See Also

CBLOCK


ENDIF - End Conditional Assembly Block

Syntax

endif

Description

This directive marks the end of a conditional assembly block. endif may be used inside a regular program block or macro.

See Also

ELSE IF


ENDM - End a Macro Definition

Syntax

endm

Description

Terminates a macro definition begun with macro.

Example

make_table macro arg1, arg2

           dw arg1, 0 ; null terminate table name

           res arg2   ; reserve storage

           endm

See Also

MACRO  EXITM


ENDW - End a While Loop

Syntax

endw

Description

endw terminates a while 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.

Example

See the example for WHILE.

See Also

WHILE


EQU - Define an Assembler Constant

Syntax

<label> equ <expr>

Description

The value of <expr> is assigned to <label>.

Example

four equ 4 ; assigned the numeric value of 4

           ; to label four

See Also

SET


ERROR - Issue an Error Message

Syntax

error "<text_string>"

Description

<text_string> is printed in a format identical to any MPASM assembler error message. <text_string> may be from 1 to 80 characters.

Example

error_checking macro arg1

    if arg1 >= 55 ; if arg is out of range

       error "error_checking-01 arg out of range"

   endif

endm

See Also

MESSG


ERRORLEVEL - Set Message Level

Syntax

errorlevel {0|1|2|+<msgnum>|-<msgnum>} [, ...]

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>
Error messages cannot be disabled. The setting of 0, 1, or 2 overrides individual message disabling or enabling.

Example

errorlevel 1, -202

See Also

LIST  ERROR


EXITM - Exit from a Macro

Syntax

exitm

Description

Force immediate return from macro expansion during assembly. The effect is the same as if an endm directive had been encountered.

Example

test macro filereg

     if filereg == 1 ; check for valid file

        exitm

     else

        error "bad file assignment"

     endif

endm

See Also

ENDM  MACRO


EXPAND - Expand Macro Listing

Syntax

expand

Description

Expand all macros in the listing file. This directive is roughly equivalent to the /m MPASM assembler command line option, but may be disabled by the occurrence of a subsequent noexpand.

See Also

MACRO NOEXPAND


EXTERN - Declare an Externally Defined Label

Syntax

extern     <label> [, <label>...]

Description

For use when generating an object file. 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 <label> is used. At least one label must be specified on the line. If <label> is defined in the current module, MPASM assembler will generate a duplicate label error.

For more information, refer to Create Relocatable Objects.

Example

extern   Function

:

call     Function

See Also

GLOBAL IDATA UDATA UDATA_ACS UDATA_OVR UDATA_SHR


FILL - Specify Memory Fill Value

Syntax

[<label>] fill <expr>,<count>

Description

Generates <count> occurrences of the program word or byte (PIC18CXXX devices), <expr>. If bounded by parentheses, <expr> can be an assembler instruction.

Example

fill 0x1009, 5  ; fill with a constant

fill (GOTO RESET_VECTOR), NEXT_BLOCK-$

See Also

DATA DW ORG


GLOBAL - Export a Label

Syntax

global     <label>  [, <label>...]

Description

For use when generating an object file. 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.

For more information, refer to Creating Relocatable Objects.

Example

         udata

Var1     res    1

Var2     res    1

         global Var1, Var2

         code

AddThree

         global AddThree

         addlw  3

         return

See Also

EXTERN IDATA UDATA UDATA_ACS UDATA_OVR UDATA_SHR


IDATA - Begin an Object File Initialized Data Section

Syntax

[<label>]     idata   [<RAM address>]

Description

For use when generating an object file. Declares the beginning of a section of initialized data. If <label> 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 generated 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 core 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.

For more information, refer to Create Relocatable Objects.

Example

       idata

LimitL dw   0

LimitH dw D'300'

Gain   dw D'5'

Flags  db 0

String db 'Hi there!'

See Also

EXTERN GLOBAL UDATA UDATA_ACS UDATA_OVR UDATA_SHR


_ _IDLOCS - Set Processor ID Locations

NOTE: idlocs is preceded by two underline characters, with no space in between these characters.  A space is added here for readibility only.

Syntax

_ _idlocs <expr> or _ _idlocs <expr1>, <expr2>

Description

For PIC12CXXX, PIC14000, and PIC16CXXX devices, _ _idlocs sets the four ID locations to the hexadecimal value of <expr>. For PIC18CXXX devices, _ _idlocs sets the two-byte device ID <expr1> to the hexadecimal value of <expr2>. This directive is not valid for the PIC17CXXX family.

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.

Before this directive is used, the processor must be declared through the command line, the list directive, or the processor directive.

Example

_ _idlocs H'1234'

See Also

_ _CONFIG LIST PROCESSOR


IF - Begin Conditionally Assembled Code Block

Syntax

if <expr>

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.

Example

if version == 100; check current version

   movlw 0x0a

   movwf io_1

else

   movlw 0x01a

   movwf io_2

endif

See Also

ELSE ENDIF


IFDEF - Execute If Symbol has Been Defined

Syntax

ifdef <label>

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.

Example

#define testing 1           ; set testing "on"

:

ifdef   testing

        <execute test code> ; this path would

endif                       ; be executed.

See Also

#DEFINE #UNDEFINE ELSE ENDIF IFNDEF


IFNDEF - Execute If Symbol has not Been Defined

Syntax

ifndef <label>

Description

If <label> 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.

Example

#define   testing1       ; set testing on

          :

          :

#undefine testing1       ; set testing off

          ifndef testing ; if not in testing mode

          :              ; execute

          :              ; this path

          endif          ;

                         ;

          end            ; end of source

See Also

#DEFINE #UNDEFINE ELSE ENDIF IFDEF


#INCLUDE - Include Additional Source File

Syntax

#include <<include_file>>

#include "<include_file>"

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.

<include_file> may 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.

Example

#include "c:\sys\sysdefs.inc" ; system defs

#include <regs.h>             ; register defs

See Also

#DEFINE #UNDEFINE


LIST - Listing Options

Syntax

list [<list_option>, ..., <list_option>]

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 the following list options can be supplied to control the assembly process or format the listing file.

List Directive Options

Option	Default	Description
b=nnn	8	Set tab spaces.
c=nnn	132	Set column width.
f=<format>	INHX8M	Set the hex file output. <format> can be INHX32, INHX8M, or INHX8S.
free	FIXED	Use free-format 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, PIC16C54.
r=<radix>	hex	Set default radix: hex, dec, oct.
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 ERRORLEVEL.
x={ON|OFF}	On	Turn macro expansion on or off.
NOTE: All list options are evaluated as decimal numbers.

Example

list p=17c42, f=INHX32, r=DEC

See Also

ERRORLEVEL EXPAND NOEXPAND NOLIST PROCESSOR RADIX


LOCAL - Declare Local Macro Variable

Syntax

local <label>[,<label>...]

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.

Example

<main code segment>

      :

      :

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

See Also

ENDM MACRO


MACRO - Declare Macro Definition

Syntax

<label> macro [<arg>, ..., <arg>]

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. The maximum source line length is 200.

A macro can call another macro, or may call itself recursively. The maximum number of nested macro calls is 16.

Please refer to Macro Language for more information.

Example

Read macro device, buffer, count

     movlw device

     movwf ram_20

     movlw buffer ; buffer address

     movwf ram_21

     movlw count  ; byte count

     call  sys_21 ; read file call

endm

See Also

ENDM EXITM LOCAL


_ _MAXRAM - Define Maximum RAM Location

NOTE: maxram is preceded by two underline characters, with no space in between these characters.  A space is added here for readibility only.

Syntax

_ _maxram    <expr>

Description

The _ _maxram and _ _badram directives together flag accesses to unimplemented registers. _ _maxram defines the absolute maximum valid RAM address and initializes 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.

Example

list p=16c622

_ _maxram H'0BF'

_ _badram H'07'-H'09', H'0D'-H'1E'

_ _badram H'87'-H'89', H'8D', H'8F'-H'9E'

movwf     H'07' ; Generates invalid RAM warning

movwf     H'87' ; Generates invalid RAM warning

                ;   and truncation message

See Also

_ _BADRAM


MESSG - Create User Defined Message

Syntax

messg "<message_text>"

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.

Example

mssg_macro macro

           messg "mssg_macro-001 invoked without argument"

endm

See Also

ERROR


NOEXPAND - Turn off Macro Expansion

Syntax

noexpand

Description

Turns off macro expansion in the listing file.

See Also

EXPAND


NOLIST - Turn off Listing Output

Syntax

nolist

Description

Turn off listing file output.

See Also

LIST


ORG - Set Program Origin

Syntax

[<label>] org <expr>

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 will begin at address zero.

For PIC18CXXX devices, only even <expr> values are allowed.

This directive may not be used when generating an object file.

Example

int_1 org 0x20

      ; Vector 20 code goes here

int_2 org int_1+0x10

      ; Vector 30 code goes here

See Also

FILL RES END


PAGE - Insert Listing Page Eject

Syntax

page

Description

Inserts a page eject into the listing file.

See Also

LIST SUBTITLE TITLE


PAGESEL - Generate Page Selecting Code

Syntax

pagesel  <label>

Description

For use when generating an object file. An instruction to the linker to generate page selecting code to set the page bits to the page containing the designated <label>. 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 core devices, the appropriate bit set/clear instructions on the STATUS register will be generated. For 14-bit and 16-bit core 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 PIC18CXXX devices, this command will do nothing.

For more information, refer to Create Relocatable Objects.

Example

pagesel GotoDest

goto    GotoDest

....

pagesel CallDest

call    CallDest

See Also

BANKISEL BANKSEL


PROCESSOR - Set Processor Type

Syntax

processor <processor_type>

Description

Sets the processor type to <processor_type>.

Example

processor 16C54

See Also

LIST


RADIX - Specify Default Radix

Syntax

radix <default_radix>

Description

Sets the default radix for data expressions. The default radix is hex. Valid radix values are:

hex - hexadecimal (base 16)

dec - decimal (base 10)

oct - octal (base 8)

There are various ways to specify a radix.

Example

radix dec

See Also

LIST


RES - Reserve Memory

Syntax

[<label>] res <mem_units>

Description

Causes the memory location pointer to be advanced from its current location by the value specified in <mem_units>. In non-relocatable code, <label> is assumed to be a program memory address. In relocatable code (using MPLINK linker), res can also be used to reserve data storage.

Address locations are defined in words for 12-, 14- and 16-bit PICmicro MCUs, and bytes for enhanced 16-bit PICmicro MCUs.

Example

buffer res 64 ; reserve 64 address locations of storage

See Also

FILL ORG


SET - Define an Assembler Variable

Syntax

<label> set <expr>

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.

Example

area   set 0

width  set 0x12

length set 0x14

area   set length * width

length set length + 1

See Also

EQU VARIABLE


SPACE - Insert Blank Listing Lines

Syntax

space <expr>

Description

Insert <expr> number of blank lines into the listing file.

Example

space 3 ;Inserts three blank lines

See Also

LIST


SUBTITLE - Specify Program Subtitle

Syntax

subtitle "<sub_text>"

Description

<sub_text> is 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.

Example

subtitle "diagnostic section"

See Also

LIST  TITLE


TITLE - Specify Program Title

Syntax

title "<title_text>"

Description

<title_text> is a 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.

Example

title "operational code, rev 5.0"

See Also

LIST SUBTITLE


UDATA - Begin an Object File Uninitialized Data Section

Syntax

[<label>]    udata    [<RAM address>]

Description

For use when generating an object file. Declares the beginning of a section of uninitialized data. If <label> 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 may not have the same name.

For more information, refer to Create Relocatable Objects.

Example

       udata

Var1   res 1

Double res 2

See Also

EXTERN GLOBAL IDATA UDATA_ACS UDATA_OVR UDATA_SHR


UDATA_ACS - Begin an Object File Access Uninitialized Data Section

Syntax

[<label>]    udata_acs    [<RAM address>]

Description

For use when generating an object file. Declares the beginning of a section of access uninitialized data. If <label> 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 PIC18CXXX 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 may not have the same name.

For more information, refer to Create Relocatable Objects.

Example

       udata

Var1   res 1

Double res 2

See Also

EXTERN GLOBAL IDATA UDATA UDATA_OVR UDATA_SHR


UDATA_OVR - Begin an Object File Overlayed Uninitialized Data Section

Syntax

[<label>]    udata_ovr    [<RAM address>]

Description

For use when generating an object file. 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 may not have the same name.

For more information, refer to Create Relocatable Objects.

Example

Temps     udata_ovr

Temp1     res 1

Temp2     res 1

Temp3     res 1

Temps     udata_ovr

LongTemp1 res 2 ; this will be a variable at the

                ; same location as Temp1 and Temp2

LongTemp2 res 2 ; this will be a variable at the

                ; same location as Temp3

See Also

EXTERN GLOBAL IDATA UDATA UDATA_ACS UDATA_SHR


UDATA_SHR - Begin an Object File Shared Uninitialized Data Section

Syntax

[<label>]    udata_shr    [<RAM address>]

Description

For use when generating an object file. Declares the beginning of a section of shared uninitialized data. If <label> 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 may not have the same name.

For more information, refer to Create Relocatable Objects.

Example

Temps udata_shr

Temp1 res 1

Temp2 res 1

Temp3 res 1

See Also

EXTERN GLOBAL IDATA UDATA UDATA_ACS UDATA_OVR


#UNDEFINE - Delete a Substitution Label

Syntax

#undefine <label>

Description

<label> is an identifier previously defined with the #define directive. It must be a valid MPASM assembler label. The symbol named is removed from the symbol table.

Example

#define   length 20

:

#undefine length

See Also

#DEFINE #INCLUDE IFDEF IFNDEF


VARIABLE - Declare Symbol Variable

Syntax

variable <label>[=<expr>][,<label>[=<expr>]...]

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.

Example

Please refer to the example given for the constant directive.

See Also

CONSTANT SET


WHILE - Perform Loop While Condition is True

Syntax

while <expr>

:

endw

Description

The lines between the while 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.

Example

test_mac macro count

         variable i

i = 0

         while  i  < count

         movlw  i

i += 1

         endw

         endm

start

         test_mac  5

         end

See Also

ENDW IF


Command Line Options

MPASM assembler can be invoked through the command line interface as follows:

mpasm [/<Option>[ /<Option>...]]   [<filename>]

or

mpasm_dp [/<Option>[ /<Option>...]]  [<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 following command:

mpasm /e /l test

The assembler defaults (noted below) can be overridden with options:

Option	Result
/<option>	Enables the option
/<option>+	Enables the option
/<option>-	Disables the option
/<option><filename>	If appropriate, enables the option and directs the output to the specified file
If the source filename is omitted, the appropriate shell interface is invoked.

Option	Default	Description
?	N/A	Displays the assembler help panel
a	INHX8M	Generate absolute .cod and .hex output directly from assembler: /a<hex-format>, where <hex-format> is one of [INHX8M | INHX8S | INHX32]
c	On	Enables/Disables case sensitivity
d	N/A	Define a text string substitution: /d<label>[=<value>]
e	On	Enable/Disable/Set Path for error file /e Enable /e + Enable /e - Disable /e <path>error.file Enables/sets path
h	N/A	Displays the assembler help panel
l	On	Enable/Disable/Set Path for list file /l Enable /l + Enable /l - Disable /l <path>list.file Enables/sets path
m	On	Enable/Disable macro expansion
o	Off	Enable/Disable/Set Path for object file /o Enable /o + Enable /o - Disable /o <path>object.file Enables/sets path
p	None	Set the processor type: /p<processor_type>, where <processor_type> is a PICmicro MCU device. For example, PIC16C54.
q	Off	Enable/Disable quiet mode (suppress screen output)
r	Hex	Defines default radix: /r<radix>, where <radix> is one of [ HEX | DEC | OCT ]
t	8	List file tab size: /t<size>
w	0	Set message level: /w<value>, where <value> is one of [0|1|2] 0 -all messages 1 -errors and warnings 2 -errors only
x	Off	Enable/Disable/Set Path for cross reference file /x Enable /x + Enable /x - Disable /x <path>xref.file Enables/sets path


Hex to Dec Conversion
Hexadecimal to Decimal Conversion

Byte	Byte
Hex	Dec	Hex	Dec	Hex	Dec	Hex	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
Using This Table: For each Hex digit, find the associated decimal value. Add the numbers together. 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


ASCII Character Set

Least Significant	Most Significant Character --->
Character	Hex	0	1	2	3	4	5	6	7
|	0	NUL	DLE	Space	0	@	P	`	p
|	1	SOH	DC1	!	1	A	Q	a	q
V	2	STX	DC2	"	2	B	R	b	r
	3	ETX	DC3	#	3	C	S	c	s
	4	EOT	DC4	$	4	D	T	d	t
	5	ENQ	NAK	%	5	E	U	e	u
	6	ACK	SYN	&	6	F	V	f	v
	7	Bell	ETB	'	7	G	W	g	w
	8	BS	CAN	(	8	H	X	h	x
	9	HT	EM	)	9	I	Y	i	y
	A	LF	SUB	*	:	J	Z	j	z
	B	VT	ESC	+	;	K	[	k	{
	C	FF	FS	,	<	L	\	l	|
	D	CR	GS		=	M	]	m	}
	E	SO	RS	.	>	N	^	n	~
	F	SI	US	/	?	O	_	o	DEL


Err/Warn/Msg
Errors, Warning and Messages

The following messages are produced by MPASM assembler. These messages always appear in the listing file directly above each line in which the error occurred.

The messages are stored in the error file (.err) if no MPASM assembler options are specified. If the /e- option is used (turns error file off), then the messages will appear on the screen. If the /q (quiet mode) option is used with the /e-, then the messages will not display on the screen or in an error file. The messages will still appear in the listing file.

Errors

Warnings

Messages


pop control
Control directives control how code is assembled.


pop conditional assembly
Conditional assembly directives permit sections of conditionally assembled code.


pop data
Data Directives are those that control the allocation of memory and provide a way to refer to data items symbolically; that is, by meaningful names.


pop macro
These directives control the execution and data allocation within macro body definitions.


pop object file
These directives are used only when creating an object file.


pop listing
Listing Directives are those directives that control the MPASM listing file format. They allow the specification of titles, pagination, and other listing control. Some listing directives also control how code is assembled.


Directive Examples

Multiple Directive Examples

Examples of use for multiple directives are available from the following sources:

This help file and related user's guide (Examples for all directives not yet available)

readme.asm - Serial EEPROM Support

Application Notes, Technical Briefs

Embedded Control Handbook, Volume 1 (DS00092)

Embedded Control Handbook, Volume 2 Math Library (DS00167)

Embedded Control Handbook, Update 2000 (DS00711)

Website - http://www.microchip.com

Code Examples and Templates

MPLAB IDE installation directory

Website - http://www.microchip.com

Individual Directive Examples

Examples of use for each directive are listed under each directive topic. To go to a directive topic, choose a Directive Summary and then click on the name of the directive to jump to its topic.


Directive Summary

A listing of all MPASM assembler directives may be found sorted as follows.

Directive Alphabetic Listing

Directive by Type


Directive Summary By Alpha
Directive Alphabetic Listing

The table below contains an alphabetic summary of assembler directives.

Click on any directive to jump to that directive's  topic showing syntax, a detailed description, an example and related directives.

NOTE: Directives are not case-sensitive, e.g., cblock may be executed as CBLOCK, cblock, Cblock, etc.

Directive	Description	Syntax
_ _BADRAM	Specify invalid RAM locations	_ _badram <expr>[-<expr>] [, <expr>[-<expr>]]
BANKISEL	Generate RAM bank selecting code for indirect addressing	Bankisel <label>
BANKSEL	Generate RAM bank selecting code	Banksel <label>
CBLOCK	Define a Block of Constants	Cblock  [<expr>]
CODE	Begins executable code section	[<name>] code [<address>]
_ _CONFIG	Specify configuration bits	_ _config <expr> OR  _ _config <addr>, <expr>
CONSTANT	Declare Symbol Constant	Constant <label> [=<expr>,...,<label> [=<expr>]  ]
DA	Store Strings in Program Memory	[<label>] da <expr>  [, <expr2>, ..., <exprn>]
DATA	Create Numeric and Text Data	[<label>] data <expr>, [,<expr>,...,<expr>] [<label>] data "<text_string>" [,"<text_string>",...]
DB	Declare Data of One Byte	[<label>] db  <expr> [,<expr>,...,<expr>] [<label>] db "<text_string>" [,"<text_string>",...]
DE	Define EEPROM Data	[<label>] de <expr> [,<expr>,...,<expr>] [<label>] de "<text_string>" [,"<text_string>",...]
#DEFINE	Define a Text Substitution Label	Define <name> [<value>] define <name> [<arg>,...,<arg>] <value>
DT	Define Table	[<label>] dt <expr> [,<expr>,...,<expr>] [<label>] dt "<text_string>" [,"<text_string>",...]
DW	Declare Data of One Word	[<label>] dw  <expr> [,<expr>,...,<expr>] [<label>] dw "<text_string>" [,"<text_string>",...]
ELSE	Begin Alternative Assembly Block to IF	Else
END	End Program Block	End
ENDC	End an Automatic Constant Block	Endc
ENDIF	End conditional Assembly Block	Endif
ENDM	End a Macro Definition	Endm
ENDW	End a While Loop	Endw
EQU	Define an Assembly Constant	<label>  equ <expr>
ERROR	Issue an Error Message	error "<text_string>"
ERRORLEVEL	Set Error Level	Errorlevel 0|1|2|  <+|-><message number>
EXITM	Exit from a Macro	Exitm
EXPAND	Expand Macro Listing	Expand
EXTERN	Declares an external label	Extern <label>[ ,<label>]
FILL	Fill Memory	[<label>] fill  <expr>, <count>
GLOBAL	Exports a defined label	Global <label>[ ,<label>]
IDATA	Begins initialized data section	[<name>] idata [<address>]
_ _IDLOCS	Specify ID locations	_ _idlocs <expr>
IF	Begin Conditionally Assembled Code Block	if  <expr>
IFDEF	Execute If Symbol has Been Defined	ifdef  <label>
IFNDEF	Execute If Symbol has not Been Defined	Ifndef <label>
#INCLUDE	Include Additional Source File	Include  <<include_file>> |"<include_file>"
LIST	Listing Options	list  [<list_option>,..., <list_option>]
LOCAL	Declare Local Macro Variable	local  <label>[,<label>]
MACRO	Declare Macro Definition	<label>  macro  [<arg>,...,<arg>]
_ _MAXRAM	Specify maximum RAM address	_ _maxram <expr>
MESSG	Create User Defined Message	messg "<message_text>"
NOEXPAND	Turn off Macro Expansion	Noexpand
NOLIST	Turn off Listing Output	Nolist
ORG	Set Program Origin	<label>  org  <expr>
PAGE	Insert Listing Page Eject	Page
PAGESEL	Generate ROM page selecting code	Pagesel <label>
PROCESSOR	Set Processor Type	Processor <processsor_type>
RADIX	Specify Default Radix	radix  <default_radix>
RES	Reserve Memory	[<label>]  res  <mem_units>
SET	Define an Assembler Variable	<label>  set  <expr>
SPACE	Insert Blank Listing Lines	space  <expr>
SUBTITLE	Specify Program Subtitle	Subtitle  "<sub_text>"
TITLE	Specify Program Title	title  "<title_text>"
UDATA	Begins uninitialized data section	[<name>] udata [<address>]
UDATA_ACS	Begins access uninitialized data section	[<name>] udata_acs [<address>]
UDATA_OVR	Begins overlayed uninitialized data section	[<name>] udata_ovr [<address>]
UDATA_SHR	Begins shared uninitialized data section	[<name>] udata_shr [<address>]
#UNDEFINE	Delete a Substitution Label	#undefine <label>
VARIABLE	Declare Symbol Variable	Variable <label> [=<expr>,...,<label> [=<expr>] ]
WHILE	Perform Loop While Condition is True	while <expr>


Include File (.INC)

Assembler include, or header, file.  Usually contains device-specific register and bit assignments.


Reference Documents

This help file describes how to use MPASM assembler. Other useful documents are listed below.

README.ASM

For the latest information on using MPASM assembler, read the readme.asm file (an ASCII text file) on the MPLAB IDE CD-ROM. The README file contains update information that may not be included in the MPASM User's Guide with MPLINK and MPLIB.

MPASM User's Guide with MPLINK and MPLIB (DS33014)

This user's guide describes how to use the Microchip PICmicro MCU MPASM assembler, MPLINK object linker and MPLIB object librarian.

MPASM and MPLINK PICmicro Quick Reference Card (DS30400)

A quick reference card (QRC) containing MPASM assembler directive language summary, MPASM assembler radix types supported, MPLINK object linker command line options, MPLIB object librarian usage format and examples, PIC18CXXX core special function register files, ASCII character set, and PICmicro MCU instruction set summaries.

Other Recommended Reading


Control Directives - Example 1

Directives Used

Control directives highlighted in this example are:

processor

radix

#include

equ

org

end

Code Listing

;**************************************

;* MPASM Assembler Control Directives *

;* Example Program 1                  *

;* Alternate output on Port B between *

;* 1's and 0's                        *

;**************************************

  processor 16f877          ;Set the processor

  radix     hex             ;Set the radix

  #include <p16f877.inc>    ;Include header file

DTEMP  equ  0x20            ;Set temp register

DFLAG  equ  0x21            ;Set flag register

DFL0   equ  0x00            ;Set flag bit

  org     0x00              ;Reset Vector

  goto    Start

  org     0x04              ;Interrupt Vector

  goto    ServInt

  org     0x06              ;Start Program

Start

  clrf    PORTB             ;Clear PortB

  bsf     STATUS, RP0       ;Select Bank 1

  clrf    TRISB             ;Set PortB as output

  bcf     STATUS, RP0       ;Select Bank 0

  bsf     INTCON, GIE       ;Enable Global Int's

  bsf     INTCON, T0IE      ;Enable Timer0 Int

Loop

  movlw   0xFF

  movwf   PORTB             ;Set PortB

  call    Delay1            ;Wait

  clrf    PORTB             ;Clear PortB

  bsf     PCLATH,3          ;Select Page 3

  bsf     PCLATH,4

  call    Delay2            ;Wait

  bcf     PCLATH,3          ;Select Page 0

  bcf     PCLATH,4

  goto    Loop              ;Repeat

ServInt                     ;Interrupt Serice Routine

  bsf     STATUS, RP0       ;Select Bank 1

  bsf     OPTION_REG, T0CS  ;Stop Timer0

  bcf     STATUS, RP0       ;Select Bank 0

  bcf     INTCON, T0IF      ;Clear overflow flag

  bcf     DFLAG, DFL0       ;Clear flag bit

  retfie

;***************************************

;* Delay 1 Routine - Timer0 delay loop *

;***************************************

Delay1

  movlw   0xF0              ;Set Timer0 value

  movwf   TMR0              ;0x00-longest delay

                            ;0xFF-shortest delay

  clrf    DFLAG

  bsf     DFLAG, DFL0       ;Set flag bit

  bsf     STATUS, RP0       ;Select Bank 1

  bcf     OPTION_REG, T0CS  ;Start Timer0

  bcf     STATUS, RP0       ;Select Bank 0

TLoop

  btfsc   DFLAG, DFL0       ;Wait for overflow

  goto    TLoop             ;Timer0 0xFF->0x00

  return

;******************************************

;* Delay 2 Routine - Decrement delay loop *

;******************************************

  org     0x1900          ;Page 3

Delay2

  movlw   0xFF            ;Set DTEMP value

  movwf   DTEMP           ;0x00-shortest delay

                          ;0xFF-longest delay

DLoop

  decfsz  DTEMP, F

  goto    DLoop           ;End loop when DTEMP=0

  return

  end

Code Development

Example program 1 was developed under MPLAB IDE using MPLAB SIM. A Watch window and breakpoints were used to monitor the value of PortB. For information on using MPLAB IDE, refer to the MPLAB IDE User’s Guide.


Control Directives - Example 2

Directives Used

Control directives highlighted in this example are:

#define

#undefine

constant

variable

set

Code Listing

;**************************************

;* MPASM Assembler Control Directives *

;* Example Program 2                  *

;* Perform calculations               *

;**************************************

  processor 16f877              ;Set the processor

  radix     hex                 ;Set the radix

  #include <p16f877.inc>        ;Include header file

  #define    Tdistance1  50     ;Define the symbol

                                ;Tdistance1

  #define    Tdistance2  25     ;Define the symbol

                                ;Tdistance2

  #undefine  Tdistance2         ;Remove Tdistance2 from

                                ;the symbol table

distance_reg equ 0x20           ;Set up distance_reg

                                ;at GPR 0x20

  org     0x00                  ;Reset Vector

  goto    Start

  org     0x06                  ;Start Program

Start

  movlw  Tdistance1             ;Move value of Tdistance1

  movwf  distance_reg           ;into distance_reg

  constant  distance1=10        ;Declare distance1

                                ;a constant symbol

  variable  distance2           ;Declare distance2

                                ;a variable symbol

distance3 set 10                ;Define a value for

                                ;the symbol distance3

distance2=15                    ;Give distance2 an

                                ;initial value

distance2=distance1+distance2   ;Add distance1

                                ;to distance2

distance3 set 15                ;Change value of distance3

distance2=distance2+distance3   ;Add distance3

                                ;to distance2

  movlw  distance2              ;Move value of distance2

  movwf  distance_reg           ;into distance_reg

  end

Code Development

Example program 2 was developed under MPLAB IDE using MPLAB SIM. A Watch window and single stepping were used to monitor the value of distance_reg. For information on using MPLAB IDE, refer to the MPLAB IDE User’s Guide.


pop control ex1 processor
The processor type is set to the PIC16C877. Code execution requires that the processor be specified. The listing directive list p=16c877 may also be used to accomplish this.


pop control ex1 radix
The radix is set to hexadecimal. The default radix setting is hex, so it is not necessary to specify radix if you wish to use hex.  It is shown here for demonstative purposes only. A listing directive, list r=hex, may also be used to set the radix.


pop control ex1 include
A header file is included in the program flow. Angle brackets are used to enclose the name of the file to be included, although quotes may also be used.  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.

A header file is extremely useful for specifying often-used constants, such as register and pin names. You can type these in once, and then include the file in any code using the processor with those registers and pins. MPLAB IDE has many header files available for supported devices in its installtion directory for your use.


pop control ex1 equ
You can specify your own registers and bits by using the equ directive, as is done in these lines. DTEMP and DFLAG are assigned to the values 0x20 and 0x21 respectively. They will be used in delay loops in the program to stand for the general purpose registers (GPRs) 0x20 and 0x21. DFL0 is assigned the value 0x00 and will be used as the name for pin 0 in the DFLAG register.


pop control ex1 org
The org directive is used to specify the program origin for specific sections of code. If no org is used, code generation begins at address zero. For Example 1, org is used to specify code at 0x00 (reset address), 0x04 (interrupt address), 0x06 (program start address) and 0x1900 (Delay2 address).


pop control ex1 end
The final directive for this and most programs is the end directive. It simply indicates the end of the program, i.e., tells the assembler no further code needs to be assembled.


pop control ex2 define
The #define directive was used to define two substitution strings: Tdistance1 to substitute for 50 and Tdistance2 to substiture for 25. Then #undefine was used to remove Tdistance2 from the symbol table, i.e., Tdistance2 can no longer be used to substiture for 25.


pop control ex2 equ
The equ directive is used to assign distance_reg to register 0x20. For more on this directive see example 1.


pop control ex2 watch1
Once the program begins, the value of Tdistance1 is placed into distance_reg. This can be observed in a watch window, where the value of distance_reg will become 50. The symbol Tdistance1 will not be found in the watch window symbol list, as symbols defined using the #define directive are not available for viewing in MPLAB IDE.


pop control ex2 constant
A constant symbol, distance1, is declared with a value of 10. Once a constant is declared, its value cannot be altered.


pop control ex2 variable
A variable symbol, distance2, is declared. Variables do not have to be given an initial value when declared. Also, the value of a variable may be changed later in the program.


pop control ex2 set
Symbol distance3 is declared and set to 10. The value of symbols declared using the set directive may have their initial value changed later in the program.


pop control ex2 variable2
The variable distance2 is initialized on one line, and then assigned a value of distance1 + distance2 on the next line. Variable assignments, increments and decrements must be placed on seperate lines.


pop control ex2 set2
The value of distance3 is reset to 15, and then it is added to distance2 to give distance2 a new value.


pop control ex2 watch2
These lines of the example program write the final value of distance2 to distance_reg. If you had a watch 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.

Looking in the watch window symbol list, you will find the symbols distance1, distance2 and distance3. However, they will have no values.  These symbol values are not actually stored on the PICmicro MCU, but implemented only in the assembler.


pop control ex1 page
Most of the program is contained on page 0.  However, the code for delay routine Delay2 has been placed on page 3. When calling this routine, you must remember to use the paging bits in the PCLATH to select page 3, and then use them to switch back to page 0 on the return.


Assembler Limitations

General Limitations

MPASM assembler only looks in the path of the executable (mpasm.exe) or the file being assembled for included files.  Therefore, Include Path information entered in the MPLAB IDE Edit Project dialog will NOT be used by the assembler.

Source line limit (expanded) = 200 characters

Directive Limitations

while nest limit = 8 deep
while loop limit = 100 lines
while iteration limit = 256

if nest limit = 16 deep

include nest limit = 5 levels
include max. number of files = 255

macro nest limit = 16 deep
macro source line limit (expanded) = 200 characters

Do not use #includes in macros.