Page 1
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MPASMAssemblerOverview
AnoverviewofMPASMassembleranditscapabilitiesispresented.
WhatisMPASMAssembler
AssemblerMigrationPathAssemblerCompatibilityIssuesHowMPASMAssemblerHelpsYou
Page 2
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
WhatisMPASMAssembler
MPASMassembler(theassembler)isacommand-lineorWindows-basedPCapplicationthatprovidesaplatformfordevelopingassemblylanguagecodeforMicrochip'sPICmicromicrocontroller(MCU)families.Generically,MPASMassemblerwillrefertotheentiredevelopmentplatformincludingthemacroassemblerandutilityfunctions.
MPASMassemblersupportsallPICmicroMCU,memory,andsecuredata(KeeLoq))productsfromMicrochipTechnologyInc.
Page 3
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
AssemblerMigrationPath
SinceMPASMassemblerisauniversalassemblerforallPICmicroMCUdevices,anapplicationdevelopedforthePIC16C54canbeeasilytranslatedintoaprogramforthePIC16C71.Thiswouldrequirechangingtheinstructionmnemonicsthatarenotthesamebetweenthedevices(assumingthatregisterandperipheralusageweresimilar).Therestofthedirectiveandmacrolanguagewillbethesame.
Page 4
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
AssemblerCompatibilityIssues
MPASMassembleriscompatiblewithallMicrochipPICmicroMCUdevelopmentsystemscurrentlyinproduction.ThisincludesMPLABSIM(PICmicroMCUdiscrete-eventsimulator),MPLABICE2000(PICmicroMCUin-circuitemulator),MPLABICD2(in-circuitdebugger-PIC18parts),PROMATEII(deviceprogrammer)andPICSTARTPlus(low-costdevelopmentprogrammer).
MPASMassemblersupportsacleanandconsistentmethodofspecifyingradix.Youareencouragedtodevelopnewcodeusingthemethodsdescribedwithinthisdocument,eventhoughcertainoldersyntaxesmaybesupportedforcompatibilityreasons.
Page 5
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
HowMPASMAssemblerHelpsYou
MPASMassemblerprovidesauniversalsolutionfordevelopingassemblycodeforallofMicrochip's12-bit,14-bit,16-bit,andEnhanced16-bitcorePICmicroMCUs.Notablefeaturesinclude:
AllPICmicroMCUInstructionSets
CommandLineInterfaceCommandShellInterfacesRichDirectiveLanguageFlexibleMacroLanguageMPLABIDECompatibility
Page 6
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
GettingStartedwithMPASMAssembler
Anoverviewofassembler(MPASMassembler)operationandinstructionsfortheinstallationofMPASMassembleronyoursystemisshown.
OverviewofAssembler
AssemblerInput/OutputFilesAssemblerInstallation
Page 7
OverviewofAssembler
MPASMassemblercanbeusedintwoways:
Togenerateabsolutecodethatcanbeexecuteddirectlybyamicrocontroller.
Togenerateobjectcodethatcanbelinkedwithotherseparatelyassembledorcompiledmodules.
GeneratingAbsoluteCode
AbsolutecodeisthedefaultoutputfromMPASMassembler.Thisprocessisshownbelow.
Whenasourcefileisassembledinthismanner,allvaluesusedinthesourcefilemustbedefinedwithinthatsourcefile,orinfilesthathavebeenexplicitlyincluded.Ifassemblyproceedswithouterrors,aHEXfilewillbegenerated,containingtheexecutablemachinecodeforthetargetdevice.Thisfilecanthenbeusedinconjunctionwithadeviceprogrammertoprogramthemicrocontroller.
GeneratingObjectCode
MPASMassembleralsohastheabilitytogenerateanobjectmodulethatcanbelinkedwithothermodulesusingMicrochip'sMPLINKlinkertoformthefinalexecutablecode.Thismethodis
Page 8
veryusefulforcreatingreusablemodulesthatdonothavetoberetestedeachtimetheyareused.
RelatedmodulescanalsobegroupedandstoredtogetherinalibraryusingMicrochip'sMPLIBlibrarian.Requiredlibrariescanbespecifiedatlinktime,andonlytheroutinesthatareneededwillbeincludedinthefinalexecutable.
RefertoRelocatableObjectsformoreinformationonthe
Page 9
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
differencesbetweenabsoluteandobjectassembly.
Page 10
AssemblerInput/OutputFiles
Thesearethedefaultfileextensionsusedbytheassemblerandtheassociatedutilityfunctions.
TABLE:INPUTFILESSourceCode(.asm) Defaultsourcefileextensioninputtoassembler.IncludeFile(.inc) Include(header)file
TABLE:OUTPUTFILESListingFile(.lst) Defaultoutputextensionforlistingfilesgeneratedbyassembler.ErrorFile(.err) Outputextensionfromassemblerforerrorfiles.HexFileFormats(.hex,.hxl,.hxh) Outputextensionfromassemblerforhexfiles.
SymbolandDebugFile(.cod)
Outputextensionforthesymbolanddebugfile.ThisfilemaybeoutputfromassemblerorMPLINKlinker.
ObjectFile(.o) Outputextensionfromassemblerforobjectfiles.
SourceCode(.asm)
Assemblysourcecodeisoneprogramminglanguageyoumayusetodevelopyourapplication.ThesourcecodefilemaybecreatedusinganyASCIItextfileeditor.Itshouldconformtothefollowingbasicguidelines.
Eachlineofthesourcefilemaycontainuptofourtypesofinformation:
Labels
MnemonicsOperandsComments
Theorderandpositionoftheseareimportant.Labelsmuststartincolumnone.Mnemonicsmaystartincolumntwoorbeyond.
Page 11
Operandsfollowthemnemonic.Commentsmayfollowtheoperands,mnemonicsorlabels,andcanstartinanycolumn.Themaximumcolumnwidthis255characters.
Whitespaceoracolonmustseparatethelabelandthemnemonic,andthemnemonicandtheoperand(s).Multipleoperandsmustbeseparatedbyacomma.
SampleMPASMAssemblerSourceCode(Showsmultipleoperands)
;;SampleMPASMSourceCode.Forillustrationonly.;listp=16c54DestequH'0B'orgH'01FF'gotoStartorgH'0000'StartmovlwH'0A'movwfDestbcfDest,3gotoStartend
Labels
Alabelmuststartincolumn1.Itmaybefollowedbyacolon(:),space,tabortheendofline.
Labelsmustbeginwithanalphacharacteroranunderbar(_)andmaycontainalphanumericcharacters,theunderbarandthequestionmark.
Note:Donotuselabelswithaleadingunderscoreandnumber,e.g.,_2NDLOOP.Also,donotusetheassemblerreservedwordHaltasalabel.
Page 12
Labelsmaybeupto32characterslong.Bydefaulttheyarecasesensitive,butcasesensitivitymaybeoverriddenbyacommandlineoption.Ifacolonisusedwhendefiningalabel,itistreatedasalabeloperatorandnotpartofthelabelitself.
Mnemonics
Assemblerinstructionmnemonics,assemblerdirectivesandmacrocallsmustbeginincolumntwoorgreater.Ifthereisalabelonthesameline,instructionsmustbeseparatedfromthatlabelbyacolon,orbyoneormorespacesortabs.
Operands
Operandsmustbeseparatedfrommnemonicsbyoneormorespaces,ortabs.Multipleoperandsmustbeseparatedbycommas.
Comments
MPASMassemblertreatsanythingafterasemicolonasacomment.Allcharactersfollowingthesemicolonareignoredthroughtheendoftheline.Stringconstantscontainingasemicolonareallowedandarenotconfusedwithcomments.
IncludeFile(.inc)
Assemblerinclude,orheader,file.Usuallycontainsdevice-specificregisterandbitassignments.
Asanexample,toaddthestandardheaderfileforthePIC18F452devicetoyourassemblycode,use:
#include<p18f452.inc>
Page 13
ListingFile(.lst)
Alistingfileprovidesamappingofsourcecodetomachineinstructions.MPASMassemblerandMPLINKlinkercangeneratelistingfiles.
SampleMPASMAssemblerListingFile
Theproductnameandversion,theassemblydateandtime,andthepagenumberappearatthetopofeverypage.
Thefirstcolumnofnumberscontainsthebaseaddressinmemorywherethecodewillbeplaced.Thesecondcolumndisplaysthe32-bitvalueofanysymbolscreatedwiththeSET,EQU,VARIABLE,CONSTANT,orCBLOCKdirectives.Thethirdcolumnisreservedforthemachineinstruction.ThisisthecodethatwillbeexecutedbythePICmicroMCU.Thefourthcolumnliststheassociatedsourcefilelinenumberforthisline.Theremainderofthelineisreservedforthesourcecodelinethatgeneratedthemachinecode.
Errors,warnings,andmessagesareembeddedbetweenthesourcelinesandpertaintothefollowingsourceline.
Thesymboltablelistsallsymbolsdefinedintheprogram.Thememoryusagemapgivesagraphicalrepresentationofmemoryusage.'X'marksausedlocationand'-'marksmemorythatisnotusedbythisobject.Thememorymapisnotprintedifanobjectfileisgenerated.
MPASM01.99.21IntermediateMANUAL.ASM5-30-199715:31:05PAGE1LOCOBJECTCODELINESOURCETEXTVALUE00001;00002;SampleMPASMSourceCode.Forillustrationonly.00003;
Page 14
00004listp=16c540000000B00005DestequH'0B'0000601FF00007orgH'01FF'01FF0A0000008gotoStart00009000000010orgH'0000'0001100000C0A00012StartmovlwH'0A'0001002B00013movwfDest00020A0000014gotoStart0001500016endMPASM01.99.21IntermediateMANUAL.ASM5-30-199715:31:05PAGE2SYMBOLTABLELABELVALUEDest0000000BStart00000000__16C5400000001MEMORYUSAGEMAP('X'=Used,'-'=Unused)0000:XXX-------------------------------------------------------------01C0:---------------------------------------------------------------XAllothermemoryblocksunused.ProgramMemoryWordsUsed:4ProgramMemoryWordsFree:508Errors:0Warnings:0reported,0suppressedMessages:0reported,0suppressed
ErrorFile(.err)
MPASMassembler,bydefault,generatesanerrorfile.Thisfilecanbeusefulwhendebuggingyourcode.TheMPLABIDESourceLevelDebuggerwillautomaticallyopenthisfileinthecaseofanerror.Theformatofthemessagesintheerrorfileis:
Page 15
<type>[<number>]<file><line><description>
Forexample:
Error[113]C:\PROG.ASM7:Symbolnotpreviouslydefined(start)
TheerrorfilewillcontainMPASMassemblererrors,warningsandmessages.
HexFileFormats(.hex,.hxl,.hxh)
MPASMAssembleriscapableofproducingdifferenthexfileformats.
FormatName FormatType FileExtension UseIntelHexFormat INHX8M .HEX forstandardprogrammersIntelSplitHexFormat INHX8S .HXL,.HXH forodd/evenROMprogrammersIntelHex32Format INHX32 .HEX for16-bitcoreprogrammers
IntelHexFormat
Thisformatproducesone8-bithexfilewithalowbyte,highbytecombination.Sinceeachaddresscanonlycontain8bitsinthisformat,alladdressesaredoubled.ThisfileformatisusefulfortransferringPICmicroMCUseriescodetoPROMATEII,PICSTARTPlusandthirdpartyPICmicroMCUprogrammers.
Eachdatarecordbeginswitha9-characterprefixandendswitha2-characterchecksum.Eachrecordhasthefollowingformat:
:BBAAAATTHHHH....HHHCC
where:
BB-isatwodigithexadecimalbytecountrepresentingthenumberofdatabytesthatwillappearontheline.
Page 16
AAAA-isafourdigithexadecimaladdressrepresentingthestartingaddressofthedatarecord.
TT-isatwodigitrecordtyperecordtypethatwillalwaysbe'00'exceptfortheend-of-filerecord,whichwillbe'01'.
HH-isatwodigithexadecimaldatabyte,presentedinlow-byte/high-bytecombinations.
CC-isatwodigithexadecimalchecksumthatisthetwo'scomplementofthesumofallprecedingbytesintherecord.
Example
<file_name>.HEX:1000000000000000000000000000000000000000F0:0400100000000000EC:100032000000280040006800A800E800C80028016D:100042006801A9018901EA01280208026A02BF02C5:10005200E002E80228036803BF03E803C8030804B8:1000620008040804030443050306E807E807FF0839:06007200FF08FF08190A57:00000001FF
IntelSplitHexFormat
Thesplit8-bitfileformatproducestwooutputfiles:.HXLand.HXH.Theformatisthesameasthenormal8-bitformat,exceptthatthelowbytesofthedatawordarestoredinthe.HXLfile,andthehighbytesofthedatawordarestoredinthe.HXHfile,andtheaddressesaredividedbytwo.Thisisusedtoprogram16-bitwordsintopairsof8-bitEPROMs,onefileforLowByte,onefileforHighByte.
Example
<file_name>.HXL
Page 17
:0A0000000000000000000000000000F6:1000190000284068A8E8C82868A989EA28086ABFAA:10002900E0E82868BFE8C8080808034303E8E8FFD0:03003900FFFF19AD:00000001FF<file_name>.HXH:0A0000000000000000000000000000F6:1000190000000000000000010101010102020202CA:100029000202030303030304040404050607070883:0300390008080AAA:00000001FF
IntelHex32Format
Theextended32-bitaddresshexformatissimilartothehex8format,exceptthattheextendedlinearaddressrecordisoutputalsotoestablishtheupper16bitsofthedataaddress.Thisismainlyusedfor16-bitcoredevicessincetheiraddressableprogrammemoryexceeds32kwords.
Eachdatarecordbeginswitha9-characterprefixandendswitha2-characterchecksum.Eachrecordhasthefollowingformat:
:BBAAAATTHHHH....HHHCC
where:
BB-isatwodigithexadecimalbytecountrepresentingthenumberofdatabytesthatwillappearontheline.
AAAA-isafourdigithexadecimaladdressrepresentingthestartingaddressofthedatarecord.
TT-isatwodigitrecordtype:
00-Datarecord
Page 18
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
01-EndofFilerecord
02-Segmentaddressrecord
04-Linearaddressrecord
HH-isatwodigithexadecimaldatabyte,presentedinlowbyte,highbytecombinations.
CC-isatwodigithexadecimalchecksumthatisthetwo'scomplementofthesumofallprecedingbytesintherecord.
SymbolandDebugFile(.cod)
ACODfileisusedbyMPLABIDEtodebugcode.TheCODfilename,includingthepath,hasa63characterlimit.MPASMassemblerandMPLINKlinkercangenerateaCODfile.
ObjectFile(.o)
Objectfilesaretherelocatablecodeproducedfromsourcefiles.
MPASMassemblerassemblessourcefilesintoobjectfiles.
MPLINKlinkercombinesobjectfilesandlibraryfiles,accordingtoalinkerscript,intoasingleoutputfile.MPLIBlibrariancombinesseveralobjectfilesintoasinglelibrary
file.
Page 19
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
AssemblerInstallation
WhenMPLABIDEisinstalled,thewindowedversionofMPASMassemblerisalsoinstalled.YoumayobtaintheMPLABIDEsoftwareeitherfromthelatestMPLABIDECD-ROMorfromourwebsite.
Actually,therearetwoversionsofMPASMassembler:
aWindowsversion,MPASMWIN.EXE(Recommended)
aDOSversion,MPASM.EXE,forDOS5.0orgreater
AvailablefreewithMPLABIDE
MPASMWIN.EXEhasaWindowsshellinterface.MPASMWIN.EXEmaybeusedwithWindows95/98/ME,WindowsNT/2000orWindowsXP.YoucanusethisversionwithMPLABIDE(recommended)orstand-alone.
AvailablefreewithMPLABC1Xcompilers
MPASM.EXEhasacommandlineinterface.MPASM.EXEmaybeusedwithDOSoraDOSwindowinWindows3.x,Windows95/98/ME,WindowsNT/2000orWindowsXP.YoucanuseitwithMPLABIDE,thoughMPASMWIN.EXEisrecommended.
Page 20
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
AssemblerUsagewithMPLABIDE
HowtouseMPASMassemblerwithMPLABIDEv6.xxandlaterisdiscussedhere.Thewindowsversion(mpasmwin.exe)oftheassemblershouldbeusedwithMPLABIDE.
MPLABIDEInterface
MPLABIDEProjectsProjectandAssemblerSetup
Page 21
MPLABIDEInterface
MPASMassemblermaybeusedwiththeMPLABIDEintegrateddevelopmentenvironmenttoprovideGUIdevelopmentofyourapplication.InordertouseMPASMassemblerwithMPLABIDE,youmustfirstinstallMPLABIDE.Thelatestversionofthisfreesoftwareisavailableatourwebsite(http://www.microchip.com)orfromanysalesoffice(backcover).WhenyouinstallMPLABIDE,youwillbeinstallingMPASMassembleraswell.
OnceMPLABIDEisinstalledonyourPC,checkthesettingsbelowtoensurethattheassemberisinstalledproperlyasalanguagetool.
1. FromtheMPLABIDEmenubar,selectProject>SetLanguageToolLocationstoopenadialogtoset/checklanguagetoolexecutablelocation.
Page 22
FIGURE:MPASMASSEMBLEREXECUTABLELOCATION
Page 23
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
1. Inthedialog,underRegisteredTools,select"MicrochipMPASMToolsuite".Clickthe"+"toexpand.
SelectExecutables.Clickthe"+"toexpand.
SelectMPASMAssembler(mpasmwin.exe).UnderLocation,apathtothempasmwin.exefileshouldbedisplayed.Ifnopathisdisplayed,enteroneorbrowsetothelocationofthisfile.Bydefault,itislocatedat:
C:\ProgramFiles\MPLABIDE\MCHIP_Tools\mpasmwin.exe
ClickOK.
Page 24
MPLABIDEProjects
AprojectinMPLABIDEisagroupoffilesneededtobuildanapplication,alongwiththeirassociationstovariousbuildtools.BelowagenericMPLABIDEProjectusingtheMPASMassemblertoolisshown.
Page 25
FIGURE:PROJECTRELATIONSHIPS
Page 26
InthisMPLABIDEProject,anassemblysourcefile(prog.asm)isshownwithitsassociatedassembler(MPASMassembler).MPLABIDEwillusethisinformationtogeneratetheobjectfileprog.oforinputintoMPLINKlinker.
TheCsourcefilemain.cisalsoshownwithitsassociatedMPLABC1Xcompiler.MPLABIDEwillusethisinformationtogenerateanobjectfile(main.o)forinputintothelinker(MPLINKlinker).SeeeithertheMPLABC17CompilerUser'sGuide(DS51290)forPIC17CXXXdevicesortheMPLABC18CompilerUser'sGuide(DS51288)forPIC18XXXXXdevicesformoreinformationonusingthesecompilers.
Inaddition,precompiledobjectfiles(precomp.o)maybeincludedinaproject,withnoassociatedtoolrequired.Typesofprecompiledobjectfilesthataregenerallyrequiredinaprojectare:
Startupcode
InitializationcodeInterruptserviceroutinesRegisterdefinitions
Precompiledobjectfilesareoftendeviceand/ormemorymodeldependent.FormoreinformationonavailableMicrochipprecompiledobjectfiles,seeeithertheMPLABC17CompilerLibraries(DS51296)forPIC17CXXXdevicesortheMPLABC18CompilerLibraries(DS51297)forPIC18XXXXXdevices.
Somelibraryfiles(math.lib)areavailablewiththecompiler.Othersmaybebuiltoutsidetheprojectusingthelibrariantool(MPLIBlibrarian).SeetheMPLIBObjectLibrariansectionlaterinthismanualformoreinformationonusingthelibrarian.FormoreinformationonavailableMicrochiplibraries,seetheMPLABC1Xlibrarydocumentspreviouslymentioned.
Page 27
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Theobjectfiles,alongwithlibraryfilesandalinkerscriptfile(device.lkr)areusedtogeneratetheprojectoutputfilesviathelinker(MPLINKlinker).SeetheMPLINKObjectLinkersectionlaterinthismanualformoreinformationonlinkerscriptfilesandusingthelinker.
ThemainoutputfilegeneratedbyMPLINKlinkeristheHexfile(prog.hex),usedbysimulators(MPLABSIM),emulators(MPLABICE2000)andprogrammers(PROMATEIIandPICSTARTPlus).Theotheroutputfilesare:
COFFfile(.out).IntermediatefileusedbyMPLINKlinkertogenerateCodefile,Hexfile,andListingfile.
Codefile(.cod).DebugfileusedbyMPLABIDE.Listingfile(.lst).Originalsourcecode,side-by-sidewithfinal
binarycode.Mapfile(.map).Showsthememorylayoutafterlinking.
Indicatesusedandunusedmemoryregions.
Page 28
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ProjectandAssemblerSetup
TosetupanMPLABIDEprojectforthefirsttime,itisadvisabletousethebuilt-inProjectWizard(Project>ProjectWizard.)Inthiswizard,youwillbeabletoselectalanguagetoolsuitethatusesMPASMassembler,e.g.,theMicrochipMPASMToolsuite.Formoreonthewizard,andMPLABIDEprojects,seeMPLABIDEdocumentation.
Onceyouhaveaprojectsetup,youmaythensetuppropertiesofMPASMassemblerinMPLABIDE.
1. FromtheMPLABIDEmenubar,selectProject>BuildOptions>Projecttoopenadialogtoset/checkprojectbuildoptions.
Note:MPASMassemblerdoesnotrecognizeincludepathinformationspecifiedinMPLABIDE.
ClickontheMPASMAssemblertabandenter/changeassemblersettings.
Page 29
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
AssemblerUsagewithoutMPLABIDE
HowtouseMPASMassemblerwithoutMPLABIDEisdiscussedhere.
Thecommand-lineversion(mpasm.exe)mayberunfromthecommandlineoracommandshell.Thewindowsversion(mpasmwin.exe)maybefromthecommandlineoraWindowsshell.
CommandLineInterface
CommandShellInterfaceWindowsShellInterfaceTroubleshooting
Page 30
CommandLineInterface
MPASMassemblercanbeinvokedthroughthecommandlineinterface(commandprompt)asfollows:
mpasmwin[/<Option>[/<Option>...]][<filename>]
or
mpasm[/<Option>[/<Option>...]][<filename>]
where
/<Option>-referstooneofthecommandlineoptions
<filename>-isthefilebeingassembled
Forexample,iftest.asmexistsinthecurrentdirectory,itcanbeassembledwithfollowingcommand:
mpasmwin/e/ltest
Theassemblerdefaults(notedbelow)canbeoverriddenwithoptions:
Option Result/<option> Enablestheoption
/<option>+ Enablestheoption
/<option>- Disablestheoption
/<option><filename>
Ifappropriate,enablestheoptionanddirectstheoutputtothespecifiedfile
Ifthesourcefilenameisomitted,theappropriateshellinterfaceisinvoked,i.e.,
mpasmwin-aWindowsinterfaceisdisplayed,whichincludesaHelpbutton
Page 31
mpasm-theassemblerhelppanelisdisplayed(sameasmpasm/?)
Option Default Description? N/A Displaystheassemblerhelppanel(mpasm.exe).
a INHX8M Generateabsolute.codand.hexoutputdirectlyfromassembler;/a<hex-format>,where<hex-format>isoneof[INHX8M|INHX8S|INHX32].
c On Enables/Disablescasesensitivity.
d N/A Defineatextstringsubstitution;/d<label>[=<value>].
e On
Enable/Disable/SetPathforerrorfile./eEnable/e+Enable/e-Disable/e<path>error.fileEnables/setspath
h N/A Displaystheassemblerhelppanel.
l On
Enable/Disable/SetPathforlistfile/lEnable/l+Enable/l-Disable/l<path>list.fileEnables/setspath
m On Enable/Disablemacroexpansion.
o Off
Enable/Disable/SetPathforobjectfile./oEnable/o+Enable/o-Disable/o<path>object.fileEnables/setspath
p None Settheprocessortype;/p<processor_type>,where<processor_type>isaPICmicroMCUdevice,e.g.,PIC16C54.
q Off Enable/Disablequietmode(suppressscreenoutput).
r Hex Definesdefaultradix;/r<radix>,where<radix>isoneof[HEX|DEC|OCT].
t 8 Listfiletabsize;/t<size>.
w 0
Setmessagelevel;/w<value>,where<value>isoneof[0|1|2].0allmessages1errorsandwarnings2errorsonly
x Off
Enable/Disable/SetPathforcrossreferencefile./xEnable/x+Enable/x-Disable/x<path>xref.fileEnables/setspath
y Disabled
Enable/Disableextendedinstructionset./yEnable/y+Enable/y-DisableCanonlybeenabledforprocessorswhichsupporttheextendedinstructionsetand
Page 32
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
thegenericprocessorPIC18CXX./y-overridesLISTPE=<type>directive.(Specifyprocessortypeandenableextendedinstructionset.)
Page 33
CommandShellInterface
TheMPASMassemblercommandshellinterfacedisplaysascreeninTextGraphicsmode.Itisinvokedbyexecutingmpasm.exeinWindowsExplorer.
Onthisscreen,youcanfillinthenameofthesourcefileyouwanttoassembleandotherinformation.
Page 34
FIGURE:TEXTGRAPHICSMODEDISPLAY
Page 35
SourceFile
Typethenameofyoursourcefile.ThenamecanincludeaDOSpathandwildcards.Ifyouusewildcards(oneof*or?),alistofallmatchingfilesisdisplayedforyoutoselectfrom.Toautomaticallyenter*.ASMinthisfield,press<TAB>.
ProcessorType
Ifyoudonotspecifytheprocessorinyoursourcefile,usethisfieldtoselecttheprocessor.Enterthefieldbyusingthearrowkeys,thentogglethroughtheprocessorsbypressing<RET>.
ErrorFile
Anerrorfile(<sourcename>.err)iscreatedbydefault.Toturntheerrorfileoff,usethe<Ã>tomovetotheYESandpress<RET>tochangeittoNO.Theerrorfilenamecanbechangedbypressingthe<TAB>keytomovetotheshadedareaandtypinganewname.Wildcardsarenotallowedintheerrorfilename.
CrossReferenceFile
Acrossreferencefile(<sourcename>.xrf)isnotgeneratedbydefault.Tocreateacrossreferencefile,usethekeyboardarrowkeystomovetotheNOandpress<RET>tochangeittoYES.Thecrossreferencefilenamecanbechangedbypressingthe<TAB>keytomovetotheshadedareaandtypinganewname.Wildcardsarenotallowedinthecrossreferencefilename.
ListingFile
Page 36
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Alistingfile(<sourcename>.lst)iscreatedbydefault.Toturnthelistingfileoff,usethe<Ã>tomovetotheYESandpress<RET>tochangeittoNO.Thelistingfilenamecanbechangedbypressingthe<TAB>keytomovetotheshadedareaandtypinganewname.Wildcardsarenotallowedinthelistingfilename.
HEXDumpType
Setthisvaluetogeneratethedesiredhexfileformat.Changingthisvalueisaccomplishedbymovingtothefieldwiththe<Ã>keyandpressingthe<RET>keytoscrollthroughtheavailableoptions.Tochangethehexfilename,pressthe<TAB>keytomovetheshadedarea,andtypeinthenewname.
AssembletoObjectFile
Enablingthisoptionwillgeneratetherelocatableobjectcodethatcanbeinputtothelinkerandsuppressgenerationofthehexfile.Thefilenamemaybemodifiedinthesamemannerastheerrorfile.
Page 37
WindowsShellInterface
MPASMassemblerforWindowsprovidesagraphicalinterfaceforsettingassembleroptions.Itisinvokedbyexecutingmpasmwin.exeinWindowsExplorer.
Page 38
FIGURE:MPASMASSEMBLERWINDOWSSHELLINTERFACE
Page 39
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SelectasourcefilebytypinginthenameorusingtheBrowsebutton.Setthevariousoptionsasdescribedbelow.ThenclickAssembletoassemblethesourcefile.
Note:WhenMPASMassemblerforWindowsisinvokedthroughMPLABIDE,theoptionsscreenisnotavailable.RefertotheMakeSetupoptionintheMPLABIDEUser'sGuideforselectingassemblyoptionsinMPLABIDE.
Option UsageRadix Overrideanysourcefileradixsettings.WarningLevel Overrideanysourcefilemessagelevelsettings.HexOutput Overrideanysourcefilehexfileformatsettings.GeneratedFiles Enable/disablevariousoutputfiles.CaseSensitivity Enable/disablecasesensitivity.MacroExpansion Overrideanysourcefilemacroexpansionsettings.Processor Overrideanysourcefileprocessorsettings.TabSize Setthelistfiletabsize.
ExtraOptions Anyadditionalcommandlineoptions.SeeCommandLineInterfaceformoredetails.
SaveSettingsonExit
Savethesesettingsinmplab.ini.Theywillbeusedthenexttimeyourunmpasmwin.exe.
ExtendedMode Enableextendedmode.
Page 40
Troubleshooting
Ifyouareusingmpasm.exeandgetamessagesayingthatyouhaverunoutofenvironmentspace,useMicrosoftWindowsInternetExplorertoselectthempasm.exefileintheMPLABIDEinstallationdirectory,andclickontherightmousebuttontobringupthePropertiesdialog.
Page 41
FIGURE:PROPERTIESDIALOG-MPASM.EXE
Page 42
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
IncreasethesizeoftheInitialEnvironment.Usuallyasettingof2048willsuffice,butifyouhavealotofapplicationsthatsetvariablesandaddtoyourpathstatementinyourAUTOEXEC.BATfile,youmayneedtomakeitlarger.
Page 43
Directives
Directivesareassemblercommandsthatappearinthesourcecodebutarenottranslateddirectlyintoopcodes.Theyareusedtocontroltheassembler:itsinput,output,anddataallocation.
Manyoftheassemblerdirectiveshavealternatenamesandformats.ThesemayexisttoprovidebackwardcompatibilitywithpreviousassemblersfromMicrochipandtobecompatiblewithindividualprogrammingpractices.Ifportablecodeisdesired,itisrecommendedthatprogramsbewrittenusingthespecificationscontainedhere.
Note:AlthoughMPASMassemblerisoftenusedwithMPLINKobjectlinker,MPASMassemblerdirectivesarenotsupportedbyMPLINKlinker.SeeMPLINKobjectlinkerdocumentationformoreinformationonlinkeroptionstocontrollistingandhexfileoutput.
Directivesdiscussedare:
Note:Directivesarenotcase-sensitive,e.g.,cblockmaybeexecutedasCBLOCK,cblock,Cblock,etc
__BADRAM-IdentifyUnimplementedRAM
__BADROM-IdentifyUnimplementedROM__CONFIG-SetProcessorConfigurationBits__IDLOCS-SetProcessorIDLocations__MAXRAM-DefineMaximumRAMLocation__MAXROM-DefineMaximumROMLocation#DEFINE-DefineaTextSubstitutionLabel#INCLUDE-IncludeAdditionalSourceFile
Page 44
#UNDEFINE-DeleteaSubstitutionLabelBANKISEL-GenerateIndirectBankSelectingCodeBANKSEL-GenerateBankSelectingCodeCBLOCK-DefineaBlockofConstantsCODE-BeginanObjectFileCodeSectionCODE_PACK-BeginanObjectFilePackedCodeSectionCONSTANT-DeclareSymbolConstantDA-StoreStringsinProgramMemoryData-CreateNumericandTextDataDB-DeclareDataofOneByteDE-DeclareEEPROMDataByteDT-DefineTableDW-DeclareDataofOneWordELSE-BeginAlternativeAssemblyBlocktoIFEND-EndProgramBlockENDC-EndanAutomaticConstantBlockENDIF-EndConditionalAssemblyBlockENDM-EndaMacroDefinitionENDW-EndaWhileLoopEQU-DefineanAssemblerConstantERROR-IssueanErrorMessageERRORLEVEL-SetMessageLevelEXITM-ExitfromaMacroEXPAND-ExpandMacroListingEXTERN-DeclareanExternallyDefinedLabelFILL-SpecifyMemoryFillValueGLOBAL-ExportaLabelIDATA-BeginanObjectFileInitializedDataSection
Page 45
IF-BeginConditionallyAssembledCodeBlockIFDEF-ExecuteIfSymbolhasBeenDefinedIFNDEF-ExecuteIfSymbolhasnotBeenDefinedLIST-ListingOptionsLOCAL-DeclareLocalMacroVariableMACRO-DeclareMacroDefinitionMESSG-CreateUserDefinedMessageNOEXPAND-TurnoffMacroExpansionNOLIST-TurnoffListingOutputORG-SetProgramOriginPAGE-InsertListingPageEjectPAGESEL-GeneratePageSelectingCodePROCESSOR-SetProcessorTypeRADIX-SpecifyDefaultRadixRES-ReserveMemorySET-DefineanAssemblerVariableSPACE-InsertBlankListingLinesSUBTITLE-SpecifyProgramSubtitleTITLE-SpecifyProgramTitleUDATA-BeginanObjectFileUninitializedDataSectionUDATA_ACS-BeginanObjectFileAccessUninitializedData
SectionUDATA_OVR-BeginanObjectFileOverlayedUninitializedData
SectionUDATA_SHR-BeginanObjectFileSharedUninitializedData
SectionVARIABLE-DeclareSymbolVariableWHILE-PerformLoopWhileConditionisTrue
Page 46
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 47
__BADRAM-IdentifyUnimplementedRAM
Note:badramisprecededbytwounderlinecharacters,withnospaceinbetweenthesecharacters.Aspaceisaddedhereforreadibilityonly.
Syntax
__badram<expr>[-<expr>][,<expr>[-<expr>]]
Description
The__maxramand__badramdirectivestogetherflagaccessestounimplementedregisters.__badramdefinesthelocationsofinvalidRAMaddresses.Thisdirectiveisdesignedforusewiththe__maxramdirective.A__maxramdirectivemustproceedany__badramdirective.Each<expr>mustbelessthanorequaltothevaluespecifiedby__maxram.Oncethe__maxramdirectiveisused,strictRAMaddresscheckingisenabled,usingtheRAMmapspecifiedby__badram.Tospecifyarangeofinvalidlocations,usethesyntax<minloc>-<maxloc>.
Example
Seetheexamplefor__maxram.
SeeAlso
__MAXRAM
Page 48
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 49
__BADROM-IdentifyUnimplementedROM
Note:badromisprecededbytwounderlinecharacters,withnospaceinbetweenthesecharacters.Aspaceisaddedhereforreadibilityonly.
Syntax
__badrom<expr>[-<expr>][,<expr>[-<expr>]]
Description
The__maxromand__badromdirectivestogetherflagaccessestounimplementedregisters.__badromdefinesthelocationsofinvalidROMaddresses.Thisdirectiveisdesignedforusewiththe__maxromdirective.A__maxromdirectivemustproceedany__badromdirective.Each<expr>mustbelessthanorequaltothevaluespecifiedby__maxrom.Oncethe__maxromdirectiveisused,strictROMaddresscheckingisenabled,usingtheROMmapspecifiedby__badrom.Tospecifyarangeofinvalidlocations,usethesyntax<minloc>-<maxloc>.
Specifically,awarningwillberaisedinthefollowingcircumstances:
thetargetofaGOTOorCALLinstructionisevaluatedbytheassemblertoaconstant,andfallsinabadROMregion
thetargetofanLGOTOorLCALLpsuedo-opisevaluatedbytheassemblertoaconstant,andfallsinabadROMregion
a.hexfileisbeinggenerated,andpartofaninstructionfallsinabadROMregion
Page 50
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Example
Seetheexamplefor__maxrom.
SeeAlso
__MAXROM
Page 51
__CONFIG-SetProcessorConfigurationBits
Note:configisprecededbytwounderlinecharacters,withnospaceinbetweenthesecharacters.Aspaceisaddedhereforreadabilityonly.
Syntax
__config<expr>OR__config<addr>,<expr>
Description
Setstheprocessor'sconfigurationbitstothevaluedescribedby<expr>.ForPIC18CXXXdevices,theaddressofavalidconfigurationbytemustalsobespecifiedby<addr>.RefertoindividualPICmicromicrocontrollerdatasheetsforadescriptionoftheconfigurationbits.
Beforethisdirectiveisused,theprocessormustbedeclaredthroughthecommandline,thelistdirective,ortheprocessordirective.IfthisdirectiveisusedwiththePIC17CXXXfamily,theHexfileoutputformatmustbesettoINHX32throughthecommandlineorthelistdirective.
Examples
example1:listp=17c42,f=INHX32;defineprocessorandselectoutputformat__configH'FFFF';defaultconfigurationbits
example2:listp=16f877a;listdirectivetodefineprocessor
Page 52
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
#include<p16f877a.inc>;includefilewithconfigbitdefinitions__config_HS_OSC&_WDT_OFF&_LVP_OFF;SetoscillatortoHS,;watchdogtimeoff,;low-voltageprog.off
example3:listp=18f8720;listdirectivetodefineprocessor#include<p18f8720.inc>;includefilewithconfigbitdefinitions__CONFIG_CONFIG1H,_OSCS_OFF_1H&_HS_OSC_1H;Setoscinfo__CONFIG_CONFIG2L,_BOR_OFF_2L&_PWRT_OFF_2L;Setpowerinfo
SeeAlso
__IDLOCSLISTPROCESSOR
Page 53
__IDLOCS-SetProcessorIDLocations
Note:idlocsisprecededbytwounderlinecharacters,withnospaceinbetweenthesecharacters.Aspaceisaddedhereforreadibilityonly.
Syntax
__idlocs<expr>or__idlocs<expr1>,<expr2>
Description
ForPIC12CXXXandPIC16CXXXdevices,__idlocssetsthefourIDlocationstothehexadecimalvalueof<expr>.ForPIC18CXXXdevices,__idlocssetsthetwo-bytedeviceID<expr1>tothehexadecimalvalueof<expr2>.ThisdirectiveisnotvalidforthePIC17CXXXfamily.
Forexample,if<expr>evaluatesto1AF,thefirst(lowestaddress)IDlocationiszero,thesecondisone,thethirdisten,andthefourthisfifteen.
Beforethisdirectiveisused,theprocessormustbedeclaredthroughthecommandline,thelistdirective,ortheprocessordirective.
Example
__idlocsH'1234'
SeeAlso
__CONFIGLISTPROCESSOR
Page 54
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 55
__MAXRAM-DefineMaximumRAMLocation
Note:maxramisprecededbytwounderlinecharacters,withnospaceinbetweenthesecharacters.Aspaceisaddedhereforreadibilityonly.
Syntax
__maxram<expr>
Description
The__maxramand__badramdirectivestogetherflagaccessestounimplementedregisters.__maxramdefinestheabsolutemaximumvalidRAMaddressandinitializesthemapofvalidRAMaddressestoalladdressesvalidatandbelow<expr>.<expr>mustbegreaterthanorequaltothemaximumpage0RAMaddressandlessthan1000H.Thisdirectiveisdesignedforusewiththe__badramdirective.Oncethe__maxramdirectiveisused,strictRAMaddresscheckingisenabled,usingtheRAMmapspecifiedby__badram.
__maxramcanbeusedmorethanonceinasourcefile.EachuseredefinesthemaximumvalidRAMaddressandresetstheRAMmaptoalllocations.
Example
listp=16c622__maxramH'0BF'__badramH'07'-H'09',H'0D'-H'1E'__badramH'87'-H'89',H'8D',H'8F'-H'9E'
Page 56
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
movwfH'07';GeneratesinvalidRAMwarningmovwfH'87';GeneratesinvalidRAMwarning;andtruncationmessage
SeeAlso
__BADRAM
Page 57
__MAXROM-DefineMaximumROMLocation
Note:maxromisprecededbytwounderlinecharacters,withnospaceinbetweenthesecharacters.Aspaceisaddedhereforreadibilityonly.
Syntax
__maxrom<expr>
Description
The__maxromand__badromdirectivestogetherflagaccessestounimplementedregisters.__maxromdefinestheabsolutemaximumvalidROMaddressandinitializesthemapofvalidROMaddressestoalladdressesvalidatandbelow<expr>.<expr>mustbegreaterthanorequaltothemaximumROMaddressofthetargetdevice.Thisdirectiveisdesignedforusewiththe__badromdirective.Oncethe__maxromdirectiveisused,strictROMaddresscheckingisenabled,usingtheROMmapspecifiedby__badrom.
__maxromcanbeusedmorethanonceinasourcefile.EachuseredefinesthemaximumvalidROMaddressandresetstheROMmaptoalllocations.
Example
listp=12c508__maxrom0x1FF__badrom0x2-0x4,0xAorg0x5
Page 58
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
goto0x2;generatesawarningcall0x3;generatesawarningorg0xAmovlw5;generatesawarning
SeeAlso
__BADROM
Page 59
#DEFINE-DefineaTextSubstitutionLabel
Syntax
#define<name>[<string>]
Description
Thisdirectivedefinesatextsubstitutionstring.Wherever<name>isencounteredintheassemblycode,<string>willbesubstituted.
Usingthedirectivewithno<string>causesadefinitionof<name>tobenotedinternallyandmaybetestedforusingtheifdefdirective.
ThisdirectiveemulatestheANSI'C'standardfor#define.SymbolsdefinedwiththismethodarenotavailableforviewingusingMPLABIDE.
Example
#definelength20#definecontrol0x19,7#defineposition(X,Y,Z)(Y-(2*Z+X))::test_labeldwposition(1,length,512)bsfcontrol;setbit7inf19
SeeAlso
Page 60
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
#UNDEFINE#INCLUDEIFDEFIFNDEF
Page 61
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
#INCLUDE-IncludeAdditionalSourceFile
Syntax
#include<<include_file>>#include"<include_file>"
Description
Thespecifiedfileisreadinassourcecode.Theeffectisthesameasiftheentiretextoftheincludedfilewereinsertedintothefileatthelocationoftheincludestatement.Uponend-of-file,sourcecodeassemblywillresumefromtheoriginalsourcefile.Upto5levelsofnestingarepermitted.Upto255includefilesareallowed.
<include_file>maybeenclosedinquotesoranglebrackets.Ifafullyqualifiedpathisspecified,onlythatpathwillbesearched.Otherwise,thesearchorderis:currentworkingdirectory,sourcefiledirectory,MPASMassemblerexecutabledirectory.
Example
#include"c:\sys\sysdefs.inc";systemdefs#include<regs.h>;registerdefs
SeeAlso
#DEFINE#UNDEFINE
Page 62
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
#UNDEFINE-DeleteaSubstitutionLabel
Syntax
#undefine<label>
Description
<label>isanidentifierpreviouslydefinedwiththe#definedirective.ItmustbeavalidMPASMassemblerlabel.Thesymbolnamedisremovedfromthesymboltable.
Example
#definelength20:#undefinelength
SeeAlso
#DEFINE#INCLUDEIFDEFIFNDEF
Page 63
BANKISEL-GenerateIndirectBankSelectingCode
Syntax
bankisel<label>
Description
Forusewhengeneratinganobjectfile.Thisdirectiveisaninstructiontothelinkertogeneratetheappropriatebankselectingcodeforanindirectaccessoftheaddressspecifiedby<label>.Onlyone<label>shouldbespecified.Nooperationscanbeperformedon<label>.<label>musthavebeenpreviouslydefined.
Thelinkerwillgeneratetheappropriatebankselectingcode.For14-bitcoredevices,theappropriatebitset/clearinstructionontheIRPbitintheSTATUSregisterwillbegenerated.Forthe16-bitcoredevices,MOVLBorMOVLRwillbegenerated.Iftheusercancompletelyspecifytheindirectaddresswithouttheseinstructions,nocodewillbegenerated.
Formoreinformation,refertoRelocatableObjects.
Example
movlwVar1movwfFSRbankiselVar1:movwfINDF
Page 64
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SeeAlso
BANKSELPAGESEL
Page 65
BANKSEL-GenerateBankSelectingCode
Syntax
banksel<label>
Description
Forusewhengeneratinganobjectfile.Thisdirectiveisaninstructiontothelinkertogeneratebankselectingcodetosetthebanktothebankcontainingthedesignated<label>.Onlyone<label>shouldbespecified.Nooperationscanbeperformedon<label>.<label>musthavebeenpreviouslydefined.
Thelinkerwillgeneratetheappropriatebankselectingcode.For12-bitcoredevices,theappropriatebitset/clearinstructionsontheFSRwillbegenerated.For14-bitdevices,bitset/clearinstructionsontheSTATUSregisterwillbegenerated.Forthe16-bitcoredevices,MOVLBorMOVLRwillbegenerated.Fortheenhanced16-bitcoredevices,MOVLBwillbegenerated.IfthedevicecontainsonlyonebankofRAM,noinstructionswillbegenerated.
Formoreinformation,refertoRelocatableObjects.
Example
bankselVar1movwfVar1
SeeAlso
BANKISELPAGESEL
Page 66
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 67
CBLOCK-DefineaBlockofConstants
Syntax
cblock[<expr>]<label>[:<increment>][,<label>[:<increment>]]endc
Description
Definealistofnamedconstants.Each<label>isassignedavalueofonehigherthantheprevious<label>.Thepurposeofthisdirectiveistoassignaddressoffsetstomanylabels.Thelistofnamesendwhenanendcdirectiveisencountered.
<expr>indicatesthestartingvalueforthefirstnameintheblock.Ifnoexpressionisfound,thefirstnamewillreceiveavalueonehigherthanthefinalnameinthepreviouscblock.Ifthefirstcblockinthesourcefilehasno<expr>,assignedvaluesstartwithzero.
If<increment>isspecified,thenthenext<label>isassignedthevalueof<increment>higherthantheprevious<label>.
Multiplenamesmaybegivenonaline,separatedbycommas.
cblockisusefulfordefiningconstantsinprogramanddatamemory.
Example
cblock0x20;name_1willbeassigned20name_1,name_2;name_2,21andsoon
Page 68
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
name_3,name_4;name_4isassigned23.endccblock0x30TwoByteVar:0,TwoByteHigh,TwoByteLowQueue:QUEUE_SIZEQueueHead,QueueTailDouble1:2,Double2:2endc
SeeAlso
ENDC
Page 69
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
CODE-BeginanObjectFileCodeSection
Syntax
[<label>]code[<ROMaddress>]
Description
Forusewhengeneratinganobjectfile.Declaresthebeginningofasectionofprogramcode.If<label>isnotspecified,thesectionisnamed.code.Thestartingaddressisinitializedtothespecifiedaddressorwillbeassignedatlinktimeifnoaddressisspecified.
Note:Twosectionsinthesamesourcefilemaynothavethesamename.
Formoreinformation,refertoRelocatableObjects.
Example
RESETcodeH'01FF'gotoSTART
SeeAlso
EXTERNCODE_PACKGLOBALIDATAUDATAUDATA_ACSUDATA_OVRUDATA_SHR
Page 70
CODE_PACK-BeginanObjectFilePackedCodeSection
Syntax
[<label>]code_pack[<ROMaddress>]
Description
Forusewhengeneratinganobjectfile.DeclaresthebeginningofasectionofprogramcodeorROMdatawhereapaddingbyteofzeroisnotappendedtoanoddnumberofbytes.If<label>isnotspecified,thesectionisnamed.code.Thestartingaddressisinitializedto<ROMaddress>orwillbeassignedatlinktimeifnoaddressisspecified.If<ROMaddress>isspecified,itmustbeword-aligned.
Note:Twosectionsinthesamesourcefilemaynothavethesamename
Formoreinformation,refertoRelocatableObjects.
Note:ThisdirectiveisonlyavailableforthePIC18familyofdevices.
Example
00001LISTP=18Cxx0000200003packedcode_packH'1F0'0001F001020300004DB1,2,30001F3040500005DB4,50000600007paddedcode
Page 71
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
0000000201000300008DB1,2,3000004050400009DB4,50001000011END
SeeAlso
EXTERNCODEGLOBALIDATAUDATAUDATA_ACSUDATA_OVRUDATA_SHR
Page 72
MicrochipTechnologyInc.
CONSTANT-DeclareSymbolConstant
Syntax
constant<label>=<expr>[...,<label>=<expr>]
Description
CreatessymbolsforuseinMPASMassemblerexpressions.Constantsmaynotberesetafterhavingoncebeeninitialized,andtheexpressionmustbefullyresolvableatthetimeoftheassignment.Thisistheprincipaldifferencebetweensymbolsdeclaredasconstantandthosedeclaredasvariable,orcreatedbythesetdirective.Otherwise,constantsandvariablesmaybeusedinterchangeablyinexpressions.
Example
variableRecLength=64;SetDefault;RecLengthconstantBufLength=512;InitBufLength.;RecLengthmay.;beresetlater.;inRecLength=128.;constantMaxMem=RecLength+BufLength;CalcMaxMem
SeeAlso
SETVARIABLE
Page 73
Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 74
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DA-StoreStringsinProgramMemory
Syntax
[<label>]da<expr>[,<expr2>,...,<exprn>]
Description
Generatesapacked14-bitnumberrepresentingtwo7-bitASCIIcharacters.ThisisusefulforstoringstringsinmemoryforthePICmicroMCUFlashROMdevices.
Examples
da"abcdef"
willput30E231E432E63380intoprogrammemory
da"12345678",0
willput18B219B41AB60000intoprogrammemory
da0xFFFF
willput0x3FFFintoprogrammemory
Page 75
Data-CreateNumericandTextData
Syntax
[<label>]data<expr>,[,<expr>,...,<expr>][<label>]data"<text_string>"[,"<text_string>",...]
Description
Initializeoneormorewordsofprogrammemorywithdata.Thedatamaybeintheformofconstants,relocatableorexternallabels,orexpressionsofanyoftheabove.ThedatamayalsoconsistofASCIIcharacterstrings,<text_string>,enclosedinsinglequotesforonecharacterordoublequotesforstrings.Singlecharacteritemsareplacedintothelowbyteoftheword,whilestringsarepackedtwotoaword.Ifanoddnumberofcharactersaregiveninastring,thefinalbyteiszero.OnallfamiliesexceptthePIC18CXXX,thefirstcharacterisinthemostsignificantbyteoftheword.OnthePIC18CXXX,thefirstcharacterisintheleastsignificantbyteoftheword.
Whengeneratinganobjectfile,thisdirectivecanalsobeusedtodeclareinitializeddatavalues.Refertotheidatadirectiveformoreinformation.
Example
datareloc_label+10;constantsdata1,2,ext_label;constants,externalsdata"testing1,2,3";textstringdata'N';singlecharacterdatastart_of_program;relocatablelabel
Page 76
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SeeAlso
DBDEDTDWIDATA
Page 77
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DB-DeclareDataofOneByte
Syntax
[<label>]db<expr>[,<expr>,...,<expr>]
Description
Reserveprogrammemorywordswithpacked8-bitvalues.Multipleexpressionscontinuetofillbytesconsecutivelyuntiltheendofexpressions.Shouldtherebeanoddnumberofexpressions,thelastbytewillbezero.
Whengeneratinganobjectfile,thisdirectivecanalsobeusedtodeclareinitializeddatavalues.Refertotheidatadirectiveformoreinformation.
Example
db't',0x0f,'e',0x0f,'s',0x0f,'t','\n'
SeeAlso
DATADEDTDWIDATA
Page 78
DE-DeclareEEPROMDataByte
Syntax
[<label>]de<expr>[,<expr>,...,<expr>]
Description
AlthoughdesignedforinitializingEEPROMdataonthePIC16F8X,thedirectivecanbeusedatanylocationforanyprocessor.
PIC18XXXX
Reservememorywordbytesarepacked.
Whenusingde,makesuretospecifythestartofdatamemoryat0xF00000forusewithprogrammers.
OtherPICmicro's
Reservememorywordswith8-bitdata.Each<expr>mustevaluatetoan8-bitvalue.Theupperbitsoftheprogramwordarezeroes.Eachcharacterinastringisstoredinaseparateword.
Whenusingde,makesuretospecifythestartofdatamemoryat0x2100forusewithprogrammers.
Example
orgH'2100';InitializeEEPROMDatade"MyProgram,v1.0",0
Page 79
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SeeAlso
DATADBDTDW
Page 80
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DT-DefineTable
Syntax
[<label>]dt<expr>[,<expr>,...,<expr>]
Description
GeneratesaseriesofRETLWinstructions,oneinstructionforeach<expr>.Each<expr>mustbean8-bitvalue.EachcharacterinastringisstoredinitsownRETLWinstruction.
Example
dt"AMessage",0dtFirstValue,SecondValue,EndOfValues
SeeAlso
DATADBDEDW
Page 81
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DW-DeclareDataofOneWord
Syntax
[<label>]dw<expr>[,<expr>,...,<expr>]
Description
Reserveprogrammemorywordsfordata,initializingthatspacetospecificvalues.ForPIC18CXXXdevices,dwfunctionslikedb.Valuesarestoredintosuccessivememorylocationsandthelocationcounterisincrementedbyone.Expressionsmaybeliteralstringsandarestoredasdescribedinthedatadirective.
Whengeneratinganobjectfile,thisdirectivecanalsobeusedtodeclareinitializeddatavalues.Refertotheidatadirectiveformoreinformation.
Example
dw39,"diagnostic39",(d_list*2+d_offset)dwdiagbase-1
SeeAlso
DATADBIDATA
Page 82
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ELSE-BeginAlternativeAssemblyBlocktoIF
Syntax
else
Description
Usedinconjunctionwithanifdirectivetoprovideanalternativepathofassemblycodeshouldtheifevaluatetofalse.elsemaybeusedinsidearegularprogramblockormacro.
Example
speedmacrorateifrate<50dwslowelsedwfastendifendm
SeeAlso
ENDIFIF
Page 83
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
END-EndProgramBlock
Syntax
end
Description
Indicatestheendoftheprogram.
Example
listp=17c42:;executablecode:;end;endofinstructions
SeeAlso
ORG
Page 84
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ENDC-EndanAutomaticConstantBlock
Syntax
endc
Description
endcterminatestheendofacblocklist.Itmustbesuppliedtoterminatethelist.
SeeAlso
CBLOCK
Page 85
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ENDIF-EndConditionalAssemblyBlock
Syntax
endif
Description
Thisdirectivemarkstheendofaconditionalassemblyblock.endifmaybeusedinsidearegularprogramblockormacro.
SeeAlso
ELSEIF
Page 86
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ENDM-EndaMacroDefinition
Syntax
endm
Description
Terminatesamacrodefinitionbegunwithmacro.
Example
make_tablemacroarg1,arg2dwarg1,0;nullterminatetablenameresarg2;reservestorageendm
SeeAlso
MACROEXITM
Page 87
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ENDW-EndaWhileLoop
Syntax
endw
Description
endwterminatesawhileloop.Aslongastheconditionspecifiedbythewhiledirectiveremainstrue,thesourcecodebetweenthewhiledirectiveandtheendwdirectivewillberepeatedlyexpandedintheassemblysourcecodestream.Thisdirectivemaybeusedinsidearegularprogramblockormacro.
Example
SeetheexampleforWHILE.
SeeAlso
WHILE
Page 88
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
EQU-DefineanAssemblerConstant
Syntax
<label>equ<expr>
Description
Thevalueof<expr>isassignedto<label>.
Example
fourequ4;assignedthenumericvalueof4tolabelfour
SeeAlso
SET
Page 89
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ERROR-IssueanErrorMessage
Syntax
error"<text_string>"
Description
<text_string>isprintedinaformatidenticaltoanyMPASMassemblererrormessage.<text_string>maybefrom1to80characters.
Example
error_checkingmacroarg1ifarg1>=55;ifargisoutofrangeerror"error_checking-01argoutofrange"endifendm
SeeAlso
MESSG
Page 90
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ERRORLEVEL-SetMessageLevel
Syntax
errorlevel{0|1|2|+<msgnum>|-<msgnum>}[,...]
Description
Setsthetypesofmessagesthatareprintedinthelistingfileanderrorfile.
Setting Affect0 Messages,warnings,anderrorsprinted
1 Warningsanderrorsprinted
2 Errorsprinted
-<msgnum> Inhibitsprintingofmessage<msgnum>+<msgnum> Enablesprintingofmessage<msgnum>
Errormessagescannotbedisabled.Thesettingof0,1,or2overridesindividualmessagedisablingorenabling.
Example
errorlevel1,-202
SeeAlso
LISTERROR
Page 91
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
EXITM-ExitfromaMacro
Syntax
exitm
Description
Forceimmediatereturnfrommacroexpansionduringassembly.Theeffectisthesameasifanendmdirectivehadbeenencountered.
Example
testmacrofileregiffilereg==1;checkforvalidfileexitmelseerror"badfileassignment"endifendm
SeeAlso
ENDMMACRO
Page 92
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
EXPAND-ExpandMacroListing
Syntax
expand
Description
Expandallmacrosinthelistingfile.Thisdirectiveisroughlyequivalenttothe/mMPASMassemblercommandlineoption,butmaybedisabledbytheoccurrenceofasubsequentnoexpand.
SeeAlso
MACRONOEXPAND
Page 93
MicrochipTechnologyInc.Microchip'sWebSite
EXTERN-DeclareanExternallyDefinedLabel
Syntax
extern<label>[,<label>...]
Description
Forusewhengeneratinganobjectfile.Declaressymbolnamesthatmaybeusedinthecurrentmodulebutaredefinedasglobalinadifferentmodule.
Theexternstatementmustbeincludedbeforethe<label>isused.Atleastonelabelmustbespecifiedontheline.If<label>isdefinedinthecurrentmodule,MPASMassemblerwillgenerateaduplicatelabelerror.
Formoreinformation,refertoRelocatableObjects.
Example
externFunction:callFunction
SeeAlso
GLOBALIDATAUDATAUDATA_ACSUDATA_OVRUDATA_SHR
Page 94
Voice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 95
FILL-SpecifyMemoryFillValue
Syntax
[<label>]fill<expr>,<count>
Description
Generates<count>occurrencesoftheprogramwordorbyte(PIC18CXXXdevices),<expr>.Ifboundedbyparentheses,<expr>canbeanassemblerinstruction.
Examples
example1fill0x1009,5;fillwithaconstantfill(GOTORESET_VECTOR),NEXT_BLOCK-$
example2listp=18f252org0x12foogoto$org0x100fill(gotofoo),(h'8000'-$)/2;Divideby2for2-word;instructionsend
SeeAlso
DATADWORG
Page 96
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 97
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200
GLOBAL-ExportaLabel
Syntax
global<label>[,<label>...]
Description
Forusewhengeneratinganobjectfile.Declaressymbolnamesthataredefinedinthecurrentmoduleandshouldbeavailabletoothermodules.Atleastonelabelmustbespecifiedontheline.
Formoreinformation,refertoRelocatableObjects.
Example
udataVar1res1Var2res1globalVar1,Var2codeAddThreeglobalAddThreeaddlw3return
SeeAlso
EXTERNIDATAUDATAUDATA_ACSUDATA_OVRUDATA_SHR
Page 98
Fax:(480)899-9210Microchip'sE-mailAddress
Page 99
IDATA-BeginanObjectFileInitializedDataSection
Syntax
[<label>]idata[<RAMaddress>]
Description
Forusewhengeneratinganobjectfile.Declaresthebeginningofasectionofinitializeddata.If<label>isnotspecified,thesectionisnamed.idata.Thestartingaddressisinitializedtothespecifiedaddressorwillbeassignedatlinktimeifnoaddressisspecified.Nocodecanbegeneratedinthissegment.
Thelinkerwillgeneratealook-uptableentryforeachbytespecifiedinanidatasection.Youmustthenlinkorincludetheappropriateinitializationcode.ExamplesofinitializationcodethatmaybeusedandmodifiedasneededmaybefoundwithMPLINKlinkersampleapplicationexamples.
Note:Thisdirectiveisnotavailablefor12-bitcoredevices.
Theres,dbanddwdirectivesmaybeusedtoreservespaceforvariables.reswillgenerateaninitialvalueofzero.dbwillinitializesuccessivebytesofRAM.dwwillinitializesuccessivebytesofRAM,onewordatatime,inlow-byte/high-byteorder.
Formoreinformation,refertoRelocatableObjects.
Example
Page 100
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
idataLimitLdw0LimitHdwD'300'GaindwD'5'Flagsdb0Stringdb'Hithere!'
SeeAlso
EXTERNGLOBALUDATAUDATA_ACSUDATA_OVRUDATA_SHR
Page 101
IF-BeginConditionallyAssembledCodeBlock
Syntax
if<expr>
Description
Beginexecutionofaconditionalassemblyblock.If<expr>evaluatestotrue,thecodeimmediatelyfollowingtheifwillassemble.Otherwise,subsequentcodeisskippeduntilanelsedirectiveoranendifdirectiveisencountered.
AnexpressionthatevaluatestozeroisconsideredlogicallyFALSE.AnexpressionthatevaluatestoanyothervalueisconsideredlogicallyTRUE.Theifandwhiledirectivesoperateonthelogicalvalueofanexpression.ArelationalTRUEexpressionisguaranteedtoreturnanonzerovalue,FALSEavalueofzero.
if'smaybenestedupto16deep.
Example
ifversion==100;checkcurrentversionmovlw0x0amovwfio_1elsemovlw0x01amovwfio_2endif
Page 102
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SeeAlso
ELSEENDIF
Page 103
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
IFDEF-ExecuteIfSymbolhasBeenDefined
Syntax
ifdef<label>
Description
If<label>hasbeenpreviouslydefined,usuallybyissuinga#definedirectiveorbysettingthevalueontheMPASMassemblercommandline,theconditionalpathistaken.Assemblywillcontinueuntilamatchingelseorendifdirectiveisencountered.
Example
#definetesting1;settesting"on":ifdeftesting<executetestcode>;thispathwouldbeexecuted.endif
SeeAlso
#DEFINE#UNDEFINEELSEENDIFIFNDEF
Page 104
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200
IFNDEF-ExecuteIfSymbolhasnotBeenDefined
Syntax
ifndef<label>
Description
If<label>hasnotbeenpreviouslydefined,orhasbeenundefinedbyissuingan#undefinedirective,thenthecodefollowingthedirectivewillbeassembled.Assemblywillbeenabledordisableduntilthenextmatchingelseorendifdirectiveisencountered.
Example
#definetesting1;settestingon:#undefinetesting1;settestingoffifndeftesting;ifnotintestingmode:;executethispathendifend;endofsource
SeeAlso
#DEFINE#UNDEFINEELSEENDIFIFDEF
Page 105
Fax:(480)899-9210Microchip'sE-mailAddress
Page 106
LIST-ListingOptions
Syntax
list[<list_option>,...,<list_option>]
Description
Occurringonalinebyitself,thelistdirectivehastheeffectofturninglistingoutputon,ifithadbeenpreviouslyturnedoff.Otherwise,oneofthefollowinglistoptionscanbesuppliedtocontroltheassemblyprocessorformatthelistingfile.
ListDirectiveOptions
Option Default Descriptionb=nnn 8 Settabspaces.
c=nnn 132 Setcolumnwidth.
f=<format> INHX8M Setthehexfileoutput.<format>canbeINHX32,INHX8M,orINHX8S.
free FIXED Usefree-formatparser.Providedforbackwardcompatibility.
fixed FIXED Usefixed-formatparser.
mm={ON|OFF} On Printmemorymapinlistfile.
n=nnn 60 Setlinesperpage.
p=<type> None Setprocessortype;forexample,PIC16C54.
pe=<type> None
Setprocessortypeandenableextendedinstructionset,forexample;LISTpe=PIC18F4620OnlyvalidwithprocessorswhichsupporttheextendedinstructionsetandthegenericprocessorPIC18CXX.Isoverriddenbycommand-lineoption/y-(disableextendedinstructionset).
r=<radix> hex Setdefaultradix:hex,dec,oct.
st={ON|OFF} On Printsymboltableinlistfile.
t={ON|OFF} Off Truncatelinesoflisting(otherwisewrap).
Page 107
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
w={0|1|2}
0 Setthemessagelevel.SeeERRORLEVEL.
x={ON|OFF} On Turnmacroexpansiononoroff.
Note:Alllistoptionsareevaluatedasdecimalnumbers.
Example
listp=17c42,f=INHX32,r=DEC
SeeAlso
ERRORLEVELEXPANDNOEXPANDNOLISTPROCESSORRADIX
Page 108
LOCAL-DeclareLocalMacroVariable
Syntax
local<label>[,<label>...]
Description
Declaresthatthespecifieddataelementsaretobeconsideredinlocalcontexttothemacro.<label>maybeidenticaltoanotherlabeldeclaredoutsidethemacrodefinition;therewillbenoconflictbetweenthetwo.
Ifthemacroiscalledrecursively,eachinvocationwillhaveitsownlocalcopy.
Example
<maincodesegment>::lenequ10;globalversionsizeequ20;notethatalocalvariable;maynowbecreatedandmodifiedtestmacrosizelocallen,label;locallenandlabellensetsize;modifylocallenlabelreslen;reservebufferlensetlen-20endm;endmacro
SeeAlso
Page 109
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ENDMMACRO
Page 110
MACRO-DeclareMacroDefinition
Syntax
<label>macro[<arg>,...,<arg>]
Description
Amacroisasequenceofinstructionsthatcanbeinsertedintheassemblysourcecodebyusingasinglemacrocall.Themacromustfirstbedefined,thenitcanbereferredtoinsubsequentsourcecode.
Argumentsarereadinfromthesourceline,storedinalinkedlistandthencounted.Themaximumnumberofargumentswouldbethenumberofargumentsthatwouldfitonthesourceline,afterthelabelandmacroterms.Themaximumsourcelinelengthis200.
Amacrocancallanothermacro,ormaycallitselfrecursively.Themaximumnumberofnestedmacrocallsis16.
PleaserefertoMacroLanguageformoreinformation.
Example
Readmacrodevice,buffer,countmovlwdevicemovwfram_20movlwbuffer;bufferaddressmovwfram_21movlwcount;bytecountcallsys_21;readfilecallendm
Page 111
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SeeAlso
ENDMEXITMLOCAL
Page 112
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MESSG-CreateUserDefinedMessage
Syntax
messg"<message_text>"
Description
Causesaninformationalmessagetobeprintedinthelistingfile.Themessagetextcanbeupto80characters.Issuingamessgdirectivedoesnotsetanyerrorreturncodes.
Example
mssg_macromacromessg"mssg_macro-001invokedwithoutargument"endm
SeeAlso
ERROR
Page 113
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
NOEXPAND-TurnoffMacroExpansion
Syntax
noexpand
Description
Turnsoffmacroexpansioninthelistingfile.
SeeAlso
EXPAND
Page 114
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
NOLIST-TurnoffListingOutput
Syntax
nolist
Description
Turnofflistingfileoutput.
SeeAlso
LIST
Page 115
ORG-SetProgramOrigin
Syntax
[<label>]org<expr>
Description
Settheprogramoriginforsubsequentcodeattheaddressdefinedin<expr>.If<label>isspecified,itwillbegiventhevalueofthe<expr>.Ifnoorgisspecified,codegenerationwillbeginataddresszero.
ForPIC18CXXXdevices,onlyeven<expr>valuesareallowed.
Whengeneratinganobjectfile,theorgdirectiveisinterpretedasintroducinganabsoluteCODEsectionwithaninternallygeneratedname.Forexample:
L1:org0x200
isinterpretedas:
.scnnameCODE0x200L1:
where.scnnameisgeneratedbytheassembler,andwillbedistinctfromeverynamepreviouslygeneratedinthiscontext.
Example
int_1org0x20;Vector20codegoeshereint_2orgint_1+0x10
Page 116
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;Vector30codegoeshere
SeeAlso
FILLRESEND
Page 117
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
PAGE-InsertListingPageEject
Syntax
page
Description
Insertsapageejectintothelistingfile.
SeeAlso
LISTSUBTITLETITLE
Page 118
PAGESEL-GeneratePageSelectingCode
Syntax
pagesel<label>
Description
Forusewhengeneratinganobjectfile.Aninstructiontothelinkertogeneratepageselectingcodetosetthepagebitstothepagecontainingthedesignated<label>.Onlyone<label>shouldbespecified.Nooperationscanbeperformedon<label>.<label>musthavebeenpreviouslydefined.
Thelinkerwillgeneratetheappropriatepageselectingcode.For12-bitcoredevices,theappropriatebitset/clearinstructionsontheSTATUSregisterwillbegenerated.For14-bitand16-bitcoredevices,MOVLWandMOVWFinstructionswillbegeneratedtomodifythePCLATH.Ifthedevicecontainsonlyonepageofprogrammemory,nocodewillbegenerated.
ForPIC18CXXXdevices,thiscommandwilldonothing.
Formoreinformation,refertoRelocatableObjects.
Example
pageselGotoDestgotoGotoDest:pageselCallDestcallCallDest
Page 119
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SeeAlso
BANKISELBANKSEL
Page 120
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
PROCESSOR-SetProcessorType
Syntax
processor<processor_type>
Description
Setstheprocessortypeto<processor_type>.
Example
processor16C54
SeeAlso
LIST
Page 121
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
RADIX-SpecifyDefaultRadix
Syntax
radix<default_radix>
Description
Setsthedefaultradixfordataexpressions.Thedefaultradixishex.Validradixvaluesare:
hex-hexadecimal(base16)
dec-decimal(base10)oct-octal(base8)
Youmayalsospecifyaradixusingthelistdirective.Forspecifyingtheradixofconstants,seeNumericConstantsandRadix.
Example
radixdec
SeeAlso
LIST
Page 122
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
RES-ReserveMemory
Syntax
[<label>]res<mem_units>
Description
Causesthememorylocationpointertobeadvancedfromitscurrentlocationbythevaluespecifiedin<mem_units>.Innon-relocatablecode,<label>isassumedtobeaprogrammemoryaddress.Inrelocatablecode(usingMPLINKlinker),rescanalsobeusedtoreservedatastorage.
Addresslocationsaredefinedinwordsfor12-,14-and16-bitPICmicroMCUs,andbytesforenhanced16-bitPICmicroMCUs.
Example
bufferres64;reserve64addresslocationsofstorage
SeeAlso
FILLORG
Page 123
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SET-DefineanAssemblerVariable
Syntax
<label>set<expr>
Description
<label>isassignedthevalueofthevalidMPASMassemblerexpressionspecifiedby<expr>.Thesetdirectiveisfunctionallyequivalenttotheequdirectiveexceptthatsetvaluesmaybesubsequentlyalteredbyothersetdirectives.
Example
areaset0widthset0x12lengthset0x14areasetlength*widthlengthsetlength+1
SeeAlso
EQUVARIABLE
Page 124
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SPACE-InsertBlankListingLines
Syntax
space<expr>
Description
Insert<expr>numberofblanklinesintothelistingfile.
Example
space3;Insertsthreeblanklines
SeeAlso
LIST
Page 125
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
SUBTITLE-SpecifyProgramSubtitle
Syntax
subtitle"<sub_text>"
Description
<sub_text>isanASCIIstringenclosedindoublequotes,60charactersorlessinlength.Thisdirectiveestablishesasecondprogramheaderlineforuseasasubtitleinthelistingoutput.
Example
subtitle"diagnosticsection"
SeeAlso
LISTTITLE
Page 126
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
TITLE-SpecifyProgramTitle
Syntax
title"<title_text>"
Description
<title_text>isaprintableASCIIstringenclosedindoublequotes.Itmustbe60charactersorless.Thisdirectiveestablishesthetexttobeusedinthetoplineofeachpageinthelistingfile.
Example
title"operationalcode,rev5.0"
SeeAlso
LISTSUBTITLE
Page 127
MicrochipTechnologyInc.
UDATA-BeginanObjectFileUninitializedDataSection
Syntax
[<label>]udata[<RAMaddress>]
Description
Forusewhengeneratinganobjectfile.Declaresthebeginningofasectionofuninitializeddata.If<label>isnotspecified,thesectionisnamed.udata.Thestartingaddressisinitializedtothespecifiedaddressorwillbeassignedatlinktimeifnoaddressisspecified.Nocodecanbegeneratedinthissegment.Theresdirectiveshouldbeusedtoreservespacefordata.
Note:Twosectionsinthesamesourcefilemaynothavethesamename.
Formoreinformation,refertoRelocatableObjects.
Example
udataVar1res1Doubleres2
SeeAlso
EXTERNGLOBALIDATAUDATA_ACSUDATA_OVRUDATA_SHR
Page 128
Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 129
UDATA_ACS-BeginanObjectFileAccessUninitializedDataSection
Syntax
[<label>]udata_acs[<RAMaddress>]
Description
Forusewhengeneratinganobjectfile.Declaresthebeginningofasectionofaccessuninitializeddata.If<label>isnotspecified,thesectionisnamed.udata_acs.Thestartingaddressisinitializedtothespecifiedaddressorwillbeassignedatlinktimeifnoaddressisspecified.ThisdirectiveisusedtodeclarevariablesthatareallocatedinaccessRAMofPIC18CXXXdevices.Nocodecanbegeneratedinthissegment.Theresdirectiveshouldbeusedtoreservespacefordata.
Note:Twosectionsinthesamesourcefilemaynothavethesamename.
Formoreinformation,refertoRelocatableObjects.
Example
udata_acsVar1res1Doubleres2
SeeAlso
EXTERNGLOBALIDATAUDATAUDATA_OVRUDATA_SHR
Page 130
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 131
UDATA_OVR-BeginanObjectFileOverlayedUninitializedDataSection
Syntax
[<label>]udata_ovr[<RAMaddress>]
Description
Forusewhengeneratinganobjectfile.Declaresthebeginningofasectionofoverlayeduninitializeddata.If<label>isnotspecified,thesectionisnamed.udata_ovr.Thestartingaddressisinitializedtothespecifiedaddressorwillbeassignedatlinktimeifnoaddressisspecified.Thespacedeclaredbythissectionisoverlayedbyallotherudata_ovrsectionsofthesamename.Itisanidealwayofdeclaringtemporaryvariablessinceitallowsmultiplevariablestobedeclaredatthesamememorylocation.Nocodecanbegeneratedinthissegment.Theresdirectiveshouldbeusedtoreservespacefordata.
Note:Twosectionsinthesamesourcefilemaynothavethesamename.
Formoreinformation,refertoRelocatableObjects.
Example
Tempsudata_ovrTemp1res1Temp2res1Temp3res1Tempsudata_ovrLongTemp1res2;thiswillbeavariableatthe
Page 132
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;samelocationasTemp1andTemp2LongTemp2res2;thiswillbeavariableatthe;samelocationasTemp3
SeeAlso
EXTERNGLOBALIDATAUDATAUDATA_ACSUDATA_SHR
Page 133
UDATA_SHR-BeginanObjectFileSharedUninitializedDataSection
Syntax
[<label>]udata_shr[<RAMaddress>]
Description
Forusewhengeneratinganobjectfile.Declaresthebeginningofasectionofshareduninitializeddata.If<label>isnotspecified,thesectionisnamed.udata_shr.Thestartingaddressisinitializedtothespecifiedaddressorwillbeassignedatlinktimeifnoaddressisspecified.ThisdirectiveisusedtodeclarevariablesthatareallocatedinRAMthatissharedacrossallRAMbanks(i.e.unbankedRAM).Nocodecanbegeneratedinthissegment.Theresdirectiveshouldbeusedtoreservespacefordata.
Note:Twosectionsinthesamesourcefilemaynothavethesamename.
Formoreinformation,refertoRelocatableObjects.
Example
Tempsudata_shrTemp1res1Temp2res1Temp3res1
SeeAlso
EXTERNGLOBALIDATAUDATAUDATA_ACSUDATA_OVR
Page 134
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 135
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
VARIABLE-DeclareSymbolVariable
Syntax
variable<label>[=<expr>][,<label>[=<expr>]...]
Description
CreatessymbolsforuseinMPASMassemblerexpressions.Variablesandconstantsmaybeusedinterchangeablyinexpressions.
Thevariabledirectivecreatesasymbolthatisfunctionallyequivalenttothosecreatedbythesetdirective.Thedifferenceisthatthevariabledirectivedoesnotrequirethatsymbolsbeinitializedwhentheyaredeclared.
Thevariablevaluescannotbeupdatedwithinanoperand.Youmustplacevariableassignments,increments,anddecrementsonseparatelines.
Example
Pleaserefertotheexamplegivenfortheconstantdirective.
SeeAlso
CONSTANTSET
Page 136
WHILE-PerformLoopWhileConditionisTrue
Syntax
while<expr>:endw
Description
Thelinesbetweenthewhileandtheendwareassembledaslongas<expr>evaluatestoTRUE.AnexpressionthatevaluatestozeroisconsideredlogicallyFALSE.AnexpressionthatevaluatestoanyothervalueisconsideredlogicallyTRUE.ArelationalTRUEexpressionisguaranteedtoreturnanon-zerovalue;FALSEavalueofzero.
Awhileloopcancontainatmost100linesandberepeatedamaximumof256times.whileloopscanbenestedupto8deep.
Example
test_macmacrocountvariableii=0whilei<countmovlwii+=1endwendmstarttest_mac5
Page 137
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
end
SeeAlso
ENDWIF
Page 138
DirectiveUsage
HowtousetheMPASMassemblerdirectivelanguageisshownusingexamples.
Directivesareassemblercommandsthatappearinthesourcecodebutarenottranslateddirectlyintoopcodes.Theyareusedtocontroltheassembler:itsinput,output,anddataallocation.
Manyoftheassemblerdirectiveshavealternatenamesandformats.ThesemayexisttoprovidebackwardcompatibilitywithpreviousassemblersfromMicrochipandtobecompatiblewithindividualprogrammingpractices.Ifportablecodeisdesired,itisrecommendedthatprogramsbewrittenusingthespecificationscontainedwithinthisdocument.
Forareferencelistingofalldirectivesdiscussedinexampleshere,pleaseseeDirectives.
Note:AlthoughMPASMassemblerisoftenusedwithMPLINKobjectlinker,MPASMassemblerdirectivesarenotsupportedbyMPLINKlinker.SeeMPLINKobjectlinkerdocumentationformoreinformationonlinkeroptionstocontrollistingandhexfileoutput.
Therearesixbasictypesofdirectivesprovidedbytheassembler:
Note:Directivesarenotcase-sensitive,e.g.,cblockmaybeexecutedasCBLOCK,cblock,Cblock,etc.
ControlDirectives
ConditionalAssemblyDirectivesDataDirectivesListingDirectives
Page 139
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MacroDirectivesObjectFileDirectives
Foralldirectivetypes:
AdditionalDirectiveExamples
Page 140
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ControlDirectives
Controldirectivescontrolhowcodeisassembled.
ListofControlDirectives
Controldirectiveexamplesavailable:
MultipleDirectiveExample1
MultipleDirectiveExample2ORGPIC16CXXXExampleORGPIC18CXXXExampleRADIXExampleSET/EQUExampleUNDEFINE/DEFINEExampleVARIABLE/CONSTANTExample
Page 141
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ConditionalAssemblyDirectives
Conditionalassemblydirectivespermitsectionsofconditionallyassembledcode.
ListofConditionalAssemblyDirectives
Conditionalassemblydirectiveexamplesavailable:
IF/ELSE/ENDIFExample
IFDEFExampleWHILE/ENDWExample
Page 142
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DataDirectives
DataDirectivesarethosethatcontroltheallocationofmemoryandprovideawaytorefertodataitemssymbolically,thatis,bymeaningfulnames.
ListofDataDirectives
Datadirectiveexamplesavailable:
CBLOCK/ENDCExample
CONFIGPIC16CXXXExampleCONFIGPIC18CXXXExampleDAExampleDATAPIC16CXXXExampleDATAPIC18CXXXExampleDBPIC16CXXXExampleDBPIC18CXXXExampleDEPIC16CXXXExampleDEPIC18CXXXExampleFILLPIC16CXXXExampleFILLPIC18CXXXExampleIDLOCPIC16CXXXExampleIDLOCPIC18CXXXExampleRESExample
Page 143
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ListingDirectives
ListingDirectivesarethosedirectivesthatcontroltheMPASMassemblerlistingfileformat.Theyallowthespecificationoftitles,pagination,andotherlistingcontrol.Somelistingdirectivesalsocontrolhowcodeisassembled.
ListofListingDirectives
Listingdirectiveexamplesavailable:
ERRORExample
ERRORLEVELExampleMESSGExample
Page 144
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MacroDirectives
Thesedirectivescontroltheexecutionanddataallocationwithinmacrobodydefinitions.
ListofMacroDirectives
Macrodirectiveexamplesavailable:
EXITMExample
LOCALExampleMACRO/ENDMExample
Page 145
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ObjectFileDirectives
Thesedirectivesareusedonlywhencreatinganobjectfile.
ListofObjectFileDirectives
Objectfiledirectiveexamplesavailable:
BANKISELExample
BANKSELExampleCODEExampleGLOBAL/EXTERNExampleIDATAExamplePAGESELExampleUDATAExampleUDATA_ACSExampleUDATA_OVRExampleUDATA_SHRExample
Page 146
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
AdditionalDirectiveExamples
Shortexamplesofuseforeachdirectivearelistedundereachdirectivetopic.SeeDirectives.
Examplesofuseformultipledirectivesareavailablefromthefollowingsources:
readme.asm-SerialEEPROMSupport
ApplicationNotes,TechnicalBriefs
EmbeddedControlHandbook,Volume1(DS00092)
EmbeddedControlHandbook,Volume2MathLibrary(DS00167)EmbeddedControlHandbook,Update2000(DS00711)Website-http://www.microchip.comCodeExamplesandTemplates
MPLABIDEinstallationdirectory
Website-http://www.microchip.com
Page 147
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
RelocatableObjects
SincetheintroductionofMPASMassemblerv2.00andMPLINKlinkerv1.00,youhavehadtheabilitytogenerateandlinkprecompiledobjectmodules.Writingsourcecodethatwillbeassembledtoanobjectmoduleisslightlydifferentfromgeneratingexecutablecodedirectlytoahexfile.MPASMassemblerroutinesdesignedforabsoluteaddressassemblywillrequireminormodificationstocompilecorrectlyintorelocatableobjectmodules.
HeaderFiles
ProgramMemoryInstructionOperandsRAMAllocationConfigurationBitsandIDLocationsAccessingLabelsFromOtherModulesPagingandBankingIssuesUnavailableDirectivesGeneratingtheObjectModuleCodeExamples
Page 148
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
HeaderFiles
TheMicrochip-suppliedstandardheaderfiles(e.g.,p17c756.inc)shouldbeusedwhengeneratingobjectmodules.Theseheaderfilesdefinethespecialfunctionregistersforthetargetprocessor.
Page 149
ProgramMemory
ProgrammemorycodemustbeprecededbyaCODEsectiondeclaration.
AbsoluteCode
StartCLRWOPTION:
RelocatableCode
CODEStartCLRWOPTION:
IfmorethanoneCODEsectionisdefinedinasourcefile,eachsectionmusthaveauniquename.Ifthenameisnotspecified,itwillbegiventhedefaultname.code.
Eachprogrammemorysectionmustbecontiguouswithinasinglesourcefile.Asectionmaynotbebrokenintopieceswithinasingesourcefile.
ThephysicaladdressofthecodecanbefixedbysupplyingtheoptionaladdressparameteroftheCODEdirective.Situationswherethismightbenecessaryare:
Specifyinginterruptvectors
Ensuringthatacodesegmentdoesnotoverlappageboundaries
Page 150
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ExampleRelocatableCode
ResetCODEH'0lFF'GOTOStartMainCODECLRWOPTION
Page 151
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
InstructionOperands
Therearesomerestrictionsinvolvinginstructionoperands.Instructionoperandsmustbeoftheform:
[HIGH|LOW|UPPER](<relocatablesymbol>+<constantoffset>)
where:
<relocatablesymbol>isanylabelthatdefinesaprogramordatamemoryaddress
<constantoffset>isanexpressionthatisresolvableatassemblytimetoavaluebetween-32768and32767
Either<relocatablesymbol>or<constantoffset>maybeomitted.
Operandsoftheform:
<relocatablesymbol>-<relocatablesymbol>
willbereducedtoaconstantvalueifbothsymbolsaredefinedinthesamecodeordatasection.
IfHIGHisused,onlybits8through15oftheexpressionwillbeused.IfLOWisused,onlybits0through7oftheexpressionwillbeused.IfUPPERisused,onlybits16through21oftheexpressionwillbeused.
Page 152
RAMAllocation
RAMspacemustbeallocatedinadatasection.Fivetypesofdatasectionsareavailable:
UDATA-Uninitializeddata.Thisisthemostcommontypeofdatasection.Locationsreservedinthissectionarenotinitializedandcanbeaccessedonlybythelabelsdefinedinthissectionorbyindirectaccesses.
UDATA_ACS-Uninitializedaccessdata.ThisdatasectionisusedforvariablesthatwillbeplacedinaccessRAMofPIC18CXXXdevices.AccessRAMisusedasquickdataaccessforspecifiedinstructions.UDATA_OVR-Uninitializedoverlaiddata.Thisdatasectionis
usedforvariablesthatcanbedeclaredatthesameaddressasothervariablesinthesamemoduleorinotherlinkedmodules.Atypicaluseofthissectionisfortemporaryvariables.UDATA_SHR-Uninitializedshareddata.Thisdatasectionis
usedforvariablesthatwillbeplacedinRAMthatisunbankedorsharedacrossallbanks.IDATA-Initializeddata.Thelinkerwillgeneratealookuptable
thatcanbeusedtoinitializethevariablesinthissectiontothespecifiedvalues.Thelocationsreservedbythissectioncanbeaccessedonlybythelabelsdefinedinthissectionorbyindirectaccesses.
Thefollowingexampleshowshowadatadeclarationmightbecreated.
AbsoluteCode
CBLOCK0x20InputGain,OutputGain;Controlloopgains
Page 153
HistoryVector;Mustbeinitializedto0Templ,Temp2,Temp3;UsedforinternalcalculationsENDC
RelocatableCode
IDATAHistoryVectorDB0UDATAInputGainRES1OutputGainRES1UDATA_OVRTemplRES1Temp2RES1Temp3RES1
Ifnecessary,thelocationofthesectionmaybefixedinmemorybysupplyingtheoptionaladdressparameter.Ifmorethanoneofeachsectiontypeisspecified,eachsectionmusthaveauniquename.Ifanameisnotprovided,thedefaultsectionnamesare:.idata,.udata,.udata_acs,.udata_shr,and.udata_ovr.
WhendefininginitializeddatainanIDATAsection,thedirectivesDB,DW,andDATAcanbeused.DBwilldefinesuccessivebytesofdatamemory.DWandDATAwilldefinesuccessivewordsofdatamemoryinlow-byte/high-byteorder.Thefollowingexampleshowshowdatawillbeinitialized.
RelocatableCode
00001LISTp=17C4400002IDATA000001020300003BytesDB1,2,300033412785600004WordsDWH'1234',H'5678'00074142430000005StringDB"ABC",0
Page 154
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 155
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ConfigurationBitsandIDLocations
ConfigurationbitsandIDlocationscanstillbedefinedinarelocatableobjectusingthe__CONFIGand__IDLOCSdirectives.Onlyonelinkedmodulecanspecifythesedirectives.TheyshouldbeusedpriortodeclaringanyCODEsections.Afterusingthesedirectives,thecurrentsectionisundefined.
Page 156
AccessingLabelsFromOtherModules
LabelsthataredefinedinonemoduleforuseinothermodulesmustbeexportedusingtheGLOBALdirective.LabelsmustbedefinedbeforetheyaredeclaredGLOBAL.ModulesthatusetheselabelsmustusetheEXTERNdirectivetodeclaretheexistenceoftheselabels.AnexampleofusingtheGLOBALandEXTERNdirectivesisshownbelow.
RelocatableCode,DefiningModule
UDATAInputGainRES1OutputGainRES1GLOBALInputGain,OutputGainCODEFilterGLOBALFilter:;Filtercode
RelocatableCode,ReferencingModule
EXTERNInputGain,OutputGain,FilterUDATAReadingRES1CODE...MOVLWGAIN1MOVWFInputGainMOVLWGAIN2MOVWFOutputGainMOVFReading,WCALLFilter
Page 157
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 158
PagingandBankingIssues
Inmanycases,RAMallocationwillspanmultiplebanks,andexecutablecodewillspanmultiplepages.Inthesecases,itisnecessarytoperformproperbankandpageset-uptoproperlyaccessthelabels.However,sincetheabsoluteaddressesofthesevariableandaddresslabelsarenotknownatassemblytime,itisnotalwayspossibletoplacethepropercodeinthesourcefile.Forthesesituations,twonewdirectives,BANKSELandPAGESELhavebeenadded.Thesedirectivesinstructthelinkertogeneratethecorrectbankorpageselectingcodeforaspecifiedlabel.Anexampleofhowcodeshouldbeconvertedisshownbelow.
AbsoluteCode
LISTP=12C509#include"P12C509.INC"VarlEQUH'10'Var2EQUH'30'...MOVLWInitialValueBCFFSR,5MOVWFVarlBSFFSR,5MOVWFVar2BSFSTATUS,PA0CALLSubroutine...SubroutineCLRW;InPage1...RETLW0
RelocatableCode
Page 159
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
LISTP=12C509#include"P12C509.INC"UDATAVarlRES1Var2RES1...CODEMOVLWInitialValueBANKSELVarlMOVWFVarlBANKSELVar2MOVWFVar2PAGESELSubroutineCALLSubroutine...SubroutineCLRW...RETLW0
Page 160
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
UnavailableDirectives
Macrocapabilityandnearlyalldirectivesareavailablewhengeneratinganobjectfile.TheonlydirectivethatisnotallowedistheORGdirective.ThiscanbereplacedbyspecifyinganabsoluteCODEsegment,asshownbelow.
AbsoluteCode
ResetORGH'01FF'GOTOStart
RelocatableCode
ResetCODEH'0lFF'GOTOStart
Page 161
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
GeneratingtheObjectModule
Oncethecodeconversioniscomplete,theobjectmoduleisgeneratedbyrequestinganobjectfileonthecommandlineorintheshellinterface.WhenusingMPASMassemblerforWindows,checkthecheckboxlabeled"ObjectFile."WhenusingtheDOScommandlineinterface,specifythe/ooptionandtoggle"AssembletoObjectFile"to"Yes."Theoutputfilewillhavea.oextension.
Page 162
CodeExamples
ThefollowingisextractedfromtheexamplemultiplyroutinesgivenasasamplewithMPASMassembler.Mostofthecommentshavebeenstrippedforbrevity.
AbsoluteCodebecomesRelocatableCode,CallingFileandRelocatableCode,LibraryRoutine.
AbsoluteCode
LISTP=16C54#INCLUDE"P16C5X.INC"cblockH'020'mulcnd;8bitmultiplicandmulplr;8bitmultiplierH_byte;Highbyteofthe16bitresultL_byte;Lowbyteofthe16bitresultcount;loopcounterendcmpyclrfH_byteclrfL_bytemovlw8movwfcountmovfmulcnd,wbcfSTATUS,C;ClearcarrybitLooprrfmulplr,FbtfscSTATUS,CaddwfH_byte,FrrfH_byte,FrrfL_byte,Fdecfszcount,Fgotoloopretlw0;*******************************************************
Page 163
;TestProgram;*******************************************************startclrwoptionmainmovfPORTB,wmovwfmulplr;multiplier(inmulplr)=05movfPORTB,Wmovwfmulcndcall_mcallmpy;TheresultisinF12&F13;H_byte&L_bytegotomainORG01FFhgotostartEND
Sinceaneight-by-eightbitmultiplyisauseful,genericroutine,itwouldbehandytobreakthisoffintoaseparateobjectfilethatcanbelinkedinwhenrequired.Theabovefilecanbebrokenintotwofiles:acallingfilerepresentinganapplicationandagenericroutinethatcouldbeincorporatedinalibrary.
RelocatableCode,CallingFile
LISTP=16C54#INCLUDE"P16C5x.INC"EXTERNmulcnd,mulplr,H_byte,L_byteEXTERNmpyCODEstartclrwoptionmainmovfPORTB,WmovwfmulplrmovfPORTB,Wmovwfmulcndcall_mcallmpy;TheresultisinH_byte&L_bytegotomain
Page 164
MicrochipTechnologyInc.Microchip'sWebSite
ResetCODEH'0lFF'gotostartEND
RelocatableCode,LibraryRoutine
LISTP=16C54#INCLUDE"P16C5x.INC"UDATAmulcndRESl;8bitmultiplicandmulplrRES1;8bitmultiplierH_byteRES1;Highbyteofthe16bitresultL_byteRES1;Lowbyteofthe16bitresultcountRES1;loopcounterGLOBALmulcnd,mulplr,H_byte,L_byteCODEmpyGLOBALmpyclrfH_byteclrfL_bytemovlw8movwfcountmovfmuland,WbcfSTATUS,C;Clearcarrybitlooprrfmulplr,FbtfscSTATUS,CaddwfH_byte,FrrfH_byte,FrrfL_byte,Fdecfszcount,Fgotoloopretlw0END
Page 165
Voice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 166
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MacroLanguage
Macrosareuserdefinedsetsofinstructionsanddirectivesthatwillbeevaluatedin-linewiththeassemblersourcecodewheneverthemacroisinvoked.
Macrosconsistofsequencesofassemblerinstructionsanddirectives.Theycanbewrittentoacceptarguments,makingthemquiteflexible.Theiradvantagesare:
Higherlevelsofabstraction,improvingreadabilityandreliability.
Consistentsolutionstofrequentlyperformedfunctions.Simplifiedchanges.Improvedtestability.
Applicationsmightincludecreatingcomplextables,frequentlyusedcode,andcomplexoperations.
MacroSyntax
MacroDirectivesDefinedMacroTextSubstitutionMacroUsageMacroCodeExamples
Page 167
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MacroSyntax
MPASMassemblermacrosaredefinedaccordingtothefollowingsyntax:
<label>macro[<arg1>,<arg2>...,<argn>]::endm
where<label>isavalidassemblerlabeland<arg>isanynumberofoptionalargumentssuppliedtothemacro(thatwillfitonthesourceline.)Thevaluesassignedtotheseargumentsatthetimethemacroisinvokedwillbesubstitutedwherevertheargumentnameoccursinthebodyofthemacro.
ThebodyofamacromaybecomprisedofMPASMassemblerdirectives,PICmicroMCUassemblyinstructions,orMPASMassemblermacrodirectives(LOCALforexample.)TheassemblercontinuestoprocessthebodyofthemacrountilanEXITMorENDMdirectiveisencountered.
Note:Forwardreferencestomacrosarenotpermitted.
Page 168
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MacroDirectivesDefined
Therearedirectivesthatareuniquetomacrodefinitions.Theycannotbeusedoutofthemacrocontext.
MacroDirectives
Whenwritingmacros,youcanuseanyofthesedirectivesPLUSanyotherdirectivessupportedbytheassembler.
Note:Theprevioussyntaxofthe"dot"formatformacrospecificdirectivesisnolongersupported.Forcompatibilityreasons,oldASM17codethatusesthisformatwillassemblebyMPASMassembler,butasmentionedbefore,youareencouragedtowritenewcodebasedontheconstructsdefinedwithinthishelpfiletoensureupwardcompatibility.
Page 169
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MacroTextSubstitution
Stringreplacementandexpressionevaluationmayappearwithinthebodyofamacro.
Command Description<arg> Substitutetheargumenttextsuppliedaspartofthemacroinvocation.
#v(<expr>)Returntheintegervalueof<expr>.Typically,usedtocreateuniquevariablenameswithcommonprefixesorsuffixes.Cannotbeusedinconditionalassemblydirectives(e.g.IFDEF,WHILE).
Argumentsmaybeusedanywherewithinthebodyofthemacro,exceptaspartofnormalexpression.Forexample,thefollowingmacro:
define_tablemacrolocala=0whilea<3entry#v(a)dw0a+=1endwendmwheninvoked,wouldgenerate:entry0dw0entry1dw0entry2dw0entry3dw0
Page 170
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MacroUsage
Oncethemacrohasbeendefined,itcanbeinvokedatanypointwithinthesourcemodulebyusingamacrocall,asdescribedbelow:
<macro_name>[<arg>,...,<arg>]
where<macro_name>isthenameofapreviouslydefinedmacroandargumentsaresuppliedasrequired.
Themacrocallitselfwillnotoccupyanylocationsinmemory.However,themacroexpansionwillbeginatthecurrentmemorylocation.Commasmaybeusedtoreserveanargumentposition.Inthiscase,theargumentwillbeanemptystring.Theargumentlististerminatedbywhitespaceorasemicolon.
TheEXITMdirectiveprovidesanalternatemethodforterminatingamacroexpansion.Duringamacroexpansion,thisdirectivecausesexpansionofthecurrentmacrotostopandallcodebetweentheEXITMandtheENDMdirectivesforthismacrotobeignored.Ifmacrosarenested,EXITMcausescodegenerationtoreturntothepreviouslevelofmacroexpansion.
Page 171
MacroCodeExamples
Thefollowingareexamplesofmacros:
Eight-by-EightMultiply
ConstantCompare
Eight-by-EightMultiply
subtitle"macrodefinitions"page;;multiply-isaneightbyeightmultiplymacro,;executinginprogrammemory,optimizedforspeed,;straightlinecode.;;Thismacrohasfiveparametersasdefinedhere:;arg1-firsteightbitliteraltobemultiplied;arg2-secondeightbitliteraltobemultiplied;dest_hi-memorylocationforhighbyteofresult;dest_lo-memorylocationforlowbyteofresult;temp-memorylocationfortemporarystorage;;Duringtheexecutionofthismacro,thewregisteris;destroyed.;;Theresultofmultiplyisa16bitvaluestoredinthe;twoeightbitregisters(dest_hi,dest_lo);;ThismacroiswrittenforthePIC17C42.;;multiplymacroarg1,arg2,dest_hi,dest_lo,temp;
Page 172
locali=0;Establishalocalindex;variableandinitializeit.;movlwarg1;Setuptheeightbitmovwftemp;literalmultiplierinthe;memorylocationtemp.;movlwarg2;Setuptheeightbit;literalmultiplicandinthe;wregister.;clrfdest_hi,F;Clearboththehighandclrfdest_lo,F;thelowdestination;registers.;bcfALUSTA,C;Clearthecarrybit.;whilei<8;Usethelooptocheckall;eightbitsofthe;multiplier(temp).;btfsctemp,i;Testthecurrentaddwfdest_hi,F;multiplierbit,iftemp,I;thenaddthemultiplicand;tothehighregister.;rrcfdest_hi,F;Foreachpassintherrcfdest_lo,F;loop,rightshifteach;destinationregisterusing;thecarrybit.;i+=1;Placethisincrementin;column1toavoid;Warning[207].endw;endm;
Page 173
Themacrodeclaresalloftherequiredarguments.Inthiscase,therearefive.TheLOCALdirectivethenestablishesalocalvariable"i"thatwillbeusedasanindexcounter.Itisinitializedtozero.Anumberofassemblerinstructionsarethenincluded.Whenthemacroisexecuted,theseinstructionswillbewritteninlinewiththerestoftheassemblersourcecode.Themacrowritesthemultiplicationcodeusinganalgorithmthataddsforeachbitsetintheeightbitsofthemultiplierandusesrightshifts.TheWHILEdirectiveisusedforthisfunction,continuingtheloopuntil"I"isgreaterthanorequaltoeight.
ConstantCompare
Asanotherexample,ifthefollowingmacrowerewritten:
include"16cxx.reg";;comparefiletoconstantandjumpiffile;>=constant.;cfl_jgemacrofile,con,jump_tomovlwcon&0xffsubwffile,wbtfscstatus,carrygotojump_toendm
andinvokedby:
cfl_jgeswitch_val,max_switch,switch_on
itwouldproduce:
movlwmax_switch&0xffsubwfswitch_val,wbtfscstatus,carrygotoswitch_on
Page 174
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 175
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ExpressionSyntaxandOperation
Variousexpressionformats,syntax,andoperationsusedbyMPASMassembleraredescribedhere.
TextStrings
NumericConstantsandRadixArithmeticOperatorsandPrecedence
Page 176
TextStrings
A"string"isasequenceofanyvalidASCIIcharacter(ofthedecimalrangeof0to127)enclosedbydoublequotes.
Stringsmaybeofanylengththatwillfitwithina255columnsourceline.Ifamatchingquotemarkisfound,thestringends.Ifnoneisfoundbeforetheendoftheline,thestringwillendattheendoftheline.Whilethereisnodirectprovisionforcontinuationontoasecondline,itisgenerallynoproblemtouseasecondDWdirectiveforthenextline.
TheDWdirectivewillstoretheentirestringintosuccessivewords.Ifastringhasanoddnumberofcharacters(bytes),theDWandDATAdirectiveswillpadtheendofthestringwithonebyteofzero(00).
Ifastringisusedasaliteraloperand,itmustbeexactlyonecharacterlong,oranerrorwilloccur.
CodeExamples
Seetheexamplesbelowfortheobjectcodegeneratedbydifferentstatementsinvolvingstrings.
74657374696Edw"testingoutputstringone\n"67206F757470757420737472696E67206F6E650A#definestr"testingoutputstringtwo"B061movlw"a"74657374696Edata"testingfirstoutputstring"67206669727374206F757470
Page 177
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
757420737472696E6700
EscapeCharacters
TheassembleracceptstheANSI`C'escapesequencestorepresentcertainspecialcontrolcharacters:
TABLE:ANSI`C'ESCAPESEQUENCESEscapeCharacter Description Hex
Value\a Bell(alert)character 07\b Backspacecharacter 08\f Formfeedcharacter 0C\n Newlinecharacter 0A\r Carriagereturncharacter 0D\t Horizontaltabcharacter 09\v Verticaltabcharacter 0B\\ Backslash 5C\? Questionmarkcharacter 3F\' Singlequote(apostrophe) 27\" Doublequotecharacter 22
\0OO Octalnumber(zero,Octaldigit,Octaldigit) \xHH Hexadecimalnumber
Page 178
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
NumericConstantsandRadix
MPASMassemblersupportsthefollowingradixformsforconstants:hexadecimal,decimal,octal,binary,andASCII.Thedefaultradixishexadecimal;thedefaultradixdetermineswhatvaluewillbeassignedtoconstantsintheobjectfilewhenaradixisnotexplicitlyspecifiedbyabasedescriptor.
Note:Theradixfornumericconstantscanbedifferentfromthedefaultradixspecifedwiththedirectivesradixorlistr=.Also,allowabledefaultradicesarelimitedtohexadecimal,decimal,andoctal.
Constantscanbeoptionallyprecededbyaplusorminussign.Ifunsigned,thevalueisassumedtobepositive.
Note:Intermediatevaluesinconstantexpressionsaretreatedas32-bitunsignedintegers.Wheneveranattemptismadetoplaceaconstantinafieldforwhichitistoolarge,atruncationwarningwillbeissued.
Thefollowingtablepresentsthevariousradixspecifications:
TABLE:RADIXSPECIFICATIONSType 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'
Page 179
ArithmeticOperatorsandPrecedence
ArithmaticoperatorsandtheirprecedencearelistedinTable:ArithmeticOperatorsandPrecedence.
Selectedoperatorsarediscussedingreaterdetailinsubsectionsfollowingthetable.
TABLE:ARITHMETICOPERATORSANDPRECEDENCEOperator Example
$ Current/Returnprogramcounter goto$+3( LeftParenthesis 1+(d*4)) RightParenthesis (Length+1)*256! ItemNOT(logicalcomplement) if!(a==b)- Negation(2'scomplement) -1*Length~ Complement flags=~flagshigh Returnhighbyte movlwhighCTR_Tablelow Returnlowbyte movlwlowCTR_Tableupper Returnupperbyte movlwupperCTR_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<< Leftshift flags=flags<<1>> Rightshift flags=flags>>1>= Greaterorequal ifentry_idx>=num_entries> Greaterthan ifentry_idx>num_entries< Lessthan ifentry_idx<num_entries<= Lessorequal ifentry_idx<=num_entries== Equalto ifentry_idx==num_entries= Notequalto ifentry_idx!=num_entries& BitwiseAND flags=flags&ERROR_BIT^ BitwiseexclusiveOR flags=flags^ERROR_BIT| BitwiseinclusiveOR flags=flags|ERROR_BIT&& LogicalAND if(len==512)&&(b==c)|| LogicalOR if(len==512)||(b==c)= Setequalto entry_index=0+= Addto,setequal entry_index+=1
Page 180
-= Subtract,setequal entry_index-=1*= Multiply,setequal entry_index*=entry_length/= Divide,setequal entry_total/=entry_length%= Modulus,setequal entry_index%=8<<= Leftshift,setequal flags<<=3>>= Rightshift,setequal flags>>=3&= AND,setequal flags&=ERROR_FLAG|= InclusiveOR,setequal flags|=ERROR_FLAG^= ExclusiveOR,setequal flags^=ERROR_FLAG++ Increment i++-- Decrement i--
High/Low/Upper
Syntax
high<operand>low<operand>upper<operand>
Description
Theseoperatorsareusedtoreturnonebyteofamulti-bytelabelvalue.Thisisdonetohandledynamicpointercalculationsasmightbeusedwithtablereadandwriteinstructions.
Example
movlwlowsize;handlethelsb'smovpfwreg,lowsize_lomovlwhighsize;handlethemsb'smovpfwreg,highsize_hi
Increment/Decrement(++/--)
Page 181
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Syntax
<variable>++<variable>--
Description
Incrementsordecrementsavariablevalue.Theseoperatorscanonlybeusedonalinebythemselves;theycannotbeembeddedwithinotherexpressionevaluation.
Example
LoopCount=4whileLoopCount>0rlfReg,fLoopCount--endw
Page 182
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Troubleshooting
Errormessages,warningmessagesandgeneralmessagesareproducedbytheMPASMassembler.Thesemessagesalwaysappearinthelistingfiledirectlyaboveeachlineinwhichtheerroroccurred.
Themessagesarestoredintheerrorfile(.err)ifnoMPASMassembleroptionsarespecified.Ifthe/e-optionisused(turnserrorfileoff),thenthemessageswillappearonthescreen.Ifthe/q(quietmode)optionisusedwiththe/e-,thenthemessageswillnotdisplayonthescreenorinanerrorfile.Themessageswillstillappearinthelistingfile.
Limitationsoftheassemblertoolarealsolistedhere.
AssemblerErrors
AssemblerWarningsAssemblerMessagesAssemblerLimitations
Page 183
AssemblerErrors
MPASMassemblererrorsarelistednumericallybelow:
101ERROR:
Usererror,invokedwiththeERRORdirective.
102Outofmemory.
Notenoughmemoryformacros,#definesorinternalprocessing.EliminateanyTSR's,closeanyopenapplications,andtryassemblingthefileagain.IfthiserrorwasobtainedusingtheRealModeDOSexecutable,tryusingeithertheWindowsversion(MPASMWIN)orDPMIversion(MPASM_DP)
103Symboltablefull.
Nomorememoryavailableforthesymboltable.EliminateanyTSR's,closeanyopenapplications,andtryassemblingthefileagain.IfthiserrorwasobtainedusingtheRealModeDOSexecutable,tryusingeithertheWindowsversion(MPASMWIN)orDPMIversion(MPASM_DP)
104Tempfilecreationerror.
Couldnotcreateatemporaryfile.Checktheavailablediskspace.
105Cannotopenfile.
Couldnotopenafile.Ifitisasourcefile,thefilemaynotexist.Ifitisanoutputfile,theoldversionmaybewriteprotected.
Page 184
106Stringsubstitutiontoocomplex.
Toomuchnestingof#defines.
107Illegaldigit.
Anillegaldigitinanumber.Validdigitsare0-1forbinary,0-7foroctal,0-9fordecimal,and0-9,a-f,andA-Fforhexadecimal.
108Illegalcharacter.
Anillegalcharacterinalabel.Validcharactersforlabelsarealphabetic(a..f,A..F),numeric(0-9),theunderscore(_),andthequestionmark(?).Labelsmaynotbeginwithanumeric.
109Unmatched(
Anopenparenthesisdidnothaveamatchingcloseparenthesis.Forexample,"DATA(1+2".
110Unmatched)
Ancloseparenthesisdidnothaveamatchingopenparenthesis.Forexample,DATA1+2).
111Missingsymbol.
AnEQUorSETstatementdidnothaveasymboltoassignthevalueto.
112Missingoperator.
Page 185
Anarithmeticoperatorwasmissingfromanexpression.Forexample,DATA12.
113Symbolnotpreviouslydefined.
Asymbolwasreferencedthathasnotyetbeendefined.Onlyaddressesmaybeusedasforwardreferences.Constantsandvariablesmustbedeclaredbeforetheyareused.
114Dividebyzero.
Divisionbyzeroencounteredduringanexpressionevaluation.
115Duplicatelabel.
Alabelwasdeclaredasaconstant(e.g.,withtheEQUorCBLOCKdirective)inmorethanonelocation.
116Addresslabelduplicatedordifferentinsecondpass.
Thesamelabelwasusedintwolocations.Alternately,thelabelwasusedonlyoncebutevaluatedtoadifferentlocationonthesecondpass.Thisoftenhappenswhenuserstrytowritepage-bitsettingmacrosthatgeneratedifferentnumbersofinstructionsbasedonthedestination.
117Addresswrappedaround0.
ThelocationcountercanonlyadvancetoFFFF.Afterthat,itwrapsbackto0.
Page 186
118Overwritingpreviousaddresscontents.
Codewaspreviouslygeneratedforthisaddress.
119Codetoofragmented.
Thecodeisbrokenintotoomanypieces.Thiserrorisveryrare,andwillonlyoccurinsourcecodethatreferencesaddressesabove32K(includingconfigurationbits).
120Callorjumpnotallowedatthisaddress.
Acallorjumpcannotbemadetothisaddress.Forexample,CALLdestinationsonthePIC16C5xfamilymustbeinthelowerhalfofthepage.
121Illegallabel.
Labelsarenotallowedoncertaindirectivelines.Simplyputthelabelonitsownline,abovethedirective.Also,HIGH,LOW,PAGE,andBANKarenotallowedaslabels.
122Illegalopcode.
Tokenisnotavalidopcode.
123Illegaldirective.
Directiveisnotallowedfortheselectedprocessor;forexample,the
__IDLOCSdirectiveonthePIC17C42.
Page 187
124Illegalargument.
Anillegaldirectiveargument;forexample,LISTSTUPID.
125Illegalcondition.
Abadconditionalassembly.Forexample,anunmatchedENDIF.
126Argumentoutofrange.
Opcodeordirectiveargumentoutofthevalidrange;forexample,TRIS10.
127Toomanyarguments.
Toomanyargumentsspecifiedforamacrocall.
128Missingargument(s).
Notenoughargumentsforamacrocalloranopcode.
129Expected.
Expectedacertaintypeofargument.Theexpectedlistwillbeprovided.
130Processortypepreviouslydefined.
Adifferentfamilyofprocessorisbeingselected.
131Processortypeisundefined.
Page 188
Codeisbeinggeneratedbeforetheprocessorhasbeendefined.Notethatuntiltheprocessorisdefined,theopcodesetisnotknown.
132Unknownprocessor.
Theselectedprocessorisnotavalidprocessor.
133HexfileformatINHX32required.
Anaddressabove32Kwasspecified.Forexample,specifyingtheconfigurationbitsonthePIC17CXXXfamily.
134Illegalhexfileformat.
AnillegalhexfileformatwasspecifiedintheLISTdirective.
135Macronamemissing.
Amacrowasdefinedwithoutaname.
136Duplicatemacroname.
Amacronamewasduplicated.
137Macrosnestedtoodeep.
Themaximummacronestinglevelwasexceeded.
138Includefilesnestedtoodeep.
Themaximumincludefilenestinglevelwasexceeded.
Page 189
139Maximumof100linesinsideWHILE-ENDW.
AWHILE-ENDWcancontainatmost100lines.
140WHILEmustterminatewithin256iterations.
AWHILE-ENDWloopmustterminatewithin256iterations.Thisistopreventinfiniteassembly.
141WHILEsnestedtoodeep.
ThemaximumWHILE-ENDWnestinglevelwasexceeded.
142IFsnestedtoodeep.
ThemaximumIFnestinglevelwasexceeded.
143Illegalnesting.
Macros,IF'sandWHILE'smustbecompletelynested;theycannotoverlap.IfyouhaveanIFwithinaWHILEloop,theENDIFmustcomebeforetheENDW.
144UnmatchedENDC.
ENDCfoundwithoutaCBLOCK.
145UnmatchedENDM.
Page 190
ENDMfoundwithoutaMACROdefinition.
146UnmatchedEXITM.
EXITMfoundwithoutaMACROdefinition.
147Directivenotallowedwhengeneratinganobjectfile.
TheORGdirectiveisnotallowedwhengeneratinganobjectfile.Instead,declareadataorcodesection,specifyingtheaddressifnecessary.
148Expandedsourcelineexceeded200characters.
Themaximumlengthofasourceline,after#DEFINEandmacroparametersubstitution,is200characters.Notethat#DEFINEsubstitutiondoesnotincludecomments,butmacroparametersubstitutiondoes.
149Directiveonlyallowedwhengeneratinganobjectfilesection.
Certaindirectives,suchasGLOBALandEXTERN,onlyhavemeaningwhenanobjectfileisgenerated.Theycannotbeusedwhengeneratingabsolutecode.
150Labelsmustbedefinedinacodeordatasectionwhenmakinganobjectfile.
Whengeneratinganobjectfile,alldataandcodeaddresslabels
Page 191
mustbedefinedinsideadataorcodesection.SymbolsdefinedbytheEQUandSETdirectivescanbedefinedoutsideofasection.
151Operandcontainsunresolvablelabelsoristoocomplex.
Whengeneratinganobjectfile,operandsmustbeoftheform[HIGH|LOW]([<relocatableaddresslabel>]+[<offset>]).
152Executablecodeanddatamustbedefinedinanappropriatesection.
Whengeneratinganobjectfile,allexecutablecodeanddatadeclarationsmustbeplacedwithinappropriatesections.
153PageorBankbitscannotbeevaluatedfortheoperand.
TheoperandofaPAGESEL,BANKSELorBANKISELdirectivemustbeoftheform<relocatableaddresslabel>or<constant>.
154Eachobjectfilesectionmustbecontiguous.
Objectfilesections,exceptUDATA_OVRsections,cannotbestoppedandrestartedwithinasinglesourcefile.Toresolvethisproblem,eithernameeachsectionwithitsownnameormovethecodeanddatadeclarationssuchthateachsectioniscontiguous.Thiserrorwillalsobegeneratediftwosectionsofdifferenttypesaregiventhesamename.
155Alloverlaidsectionsofthesamename
Page 192
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
musthavethesamestartingaddress.
IfmultipleUDATA_OVRsectionswiththesamenamearedeclared,theymustallhavethesamestartingaddress.
156Operandmustbeanaddresslabel.
Whengeneratingobjectfiles,onlyaddresslabelsincodeordatasectionsmaybedeclaredglobal.VariablesdeclaredbytheSETorEQUdirectivesmaynotbeexported.
157UNKNOWNERROR.
Anerrorhasoccurredwhichtheassemblercannotunderstand.Itisnotanyoftheerrorsdescribedinthisappendix.ContactyourMicrochipFieldApplicationEngineer(FAE)ifyoucannotdebugthiserror.
Page 193
AssemblerWarnings
MPASMassemblerwarningsarelistednumericallybelow:
201Symbolnotpreviouslydefined.
Symbolbeing#undefinedwasnotpreviouslydefined.
202Argumentoutofrange.Leastsignificantbitsused.
Argumentdidnotfitintheallocatedspace.Forexample,literalsmustbe8bits.
203Foundopcodeincolumn1.
Anopcodewasfoundincolumnone,whichisreservedforlabels.
204Foundpseudo-opincolumn1.
Apseudo-opwasfoundincolumnone,whichisreservedforlabels.
205Founddirectiveincolumn1.
Adirectivewasfoundincolumnone,whichisreservedforlabels.
206Foundcalltomacroincolumn1.
Amacrocallwasfoundincolumnone,whichisreservedforlabels.
Page 194
207Foundlabelaftercolumn1.
Alabelwasfoundaftercolumnone,whichisoftenduetoamisspelledopcode.
208Labeltruncatedat32characters.
Maximumlabellengthis32characters.
209Missingquote.
Atextstringorcharacterwasmissingaquote.Forexample,DATA'a.
210Extra),
Anextracommawasfoundattheendoftheline.
211Extraneousargumentsontheline.
Extraargumentswerefoundontheline.Thesewarningsshouldbeinvestigated,sincetheyareoftenindicationsofthefree-formatparserinterpretingsomethinginamannerotherthanwasintended(tryassemblingOPTIONEQU0x81withLISTFREE).
212Expected
Expectedacertaintypeofargument.Adescriptionshouldbeprovided.Forthewarning,anassumptionismadeabouttheargument.
213TheEXTERNdirectiveshouldonlybe
Page 195
usedwhenmakinga.ofile.
TheEXTERNdirectiveonlyhasmeaningifanobjectfileisbeingcreated.ThiswarninghasbeensupersededbyError149.
214Unmatched(
Anunmatchedparenthesiswasfound.Thewarningisusediftheparenthesisisnotusedforindicatingorderofevaluation.
215Processorsupersededbycommandline.Verifyprocessorsymbol.
Theprocessorwasspecifiedonthecommandlineaswellasinthesourcefile.Thecommandlinehasprecedence.
216Radixsupersededbycommandline.
Theradixwasspecifiedonthecommandlineaswellasinthesourcefile.Thecommandlinehasprecedence.
217Hexfileformatspecifiedoncommandline.
Thehexfileformatwasspecifiedonthecommandlineaswellasinthesourcefile.Thecommandlinehasprecedence.
218ExpectedDEC,OCT,HEX.WilluseHEX.
Badradixspecification.
Page 196
219InvalidRAMlocationspecified.
Ifthe__MAXRAMand__BADRAMdirectivesareused,thiswarningflagsuseofanyRAMlocationsdeclaredasinvalidbythesedirectives.Notethattheprovidedheaderfilesinclude__MAXRAMand__BADRAMforeachprocessor.
220Addressexceedsmaximumrangeforthisprocessor.
AROMlocationwasspecifiedthatexceedstheprocessor'smemorysize.
221Invalidmessagenumber.
Themessagenumberspecifiedfordisplayingorhidingisnotavalidmessagenumber.
222Errormessagescannotbedisabled.
ErrormessagescannotbedisabledwiththeERRORLEVELcommand.
223Redefiningprocessor
TheselectedprocessorisbeingreselectedbytheLISTorPROCESSORdirective.
224Useofthisinstructionisnotrecommended.
UseoftheTRISandOPTIONinstructionsisnotrecommendedfor
Page 197
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
aPIC16CXXXdevice.
225Invalidlabelinoperand.
Operandwasnotavalidaddress.Forexample,iftheusertriedtoissueaCALLtoaMACROname.
226UNKNOWNWARNING
Awarninghasoccurredwhichtheassemblercannotunderstand.Itisnotanyofthewarningsdescribedinthisappendix.ContactyourMicrochipFieldApplicationEngineer(FAE)ifyoucannotdebugthiswarning.
Page 198
AssemblerMessages
MPASMassemblermessagesarelistednumericallybelow:
301MESSAGE:
Usermessage,invokedwiththeMESSGdirective.
302Registerinoperandnotinbank0.Ensurethatbankbitsarecorrect.
Registeraddresswasspecifiedbyavaluethatincludedthebankbits.Forexample,RAMlocationsinthePIC16CXXXarespecifiedwith7bitsintheinstructionandoneortwobankbits.
303Programwordtoolarge.Truncatedtocoresize.
ProgramwordsforthePIC16C5Xmayonlybe12-bits;programwordsforthePIC16CXXXmayonlybe14-bits.
304IDLocationsvaluetoolarge.Lastfourhexdigitsused.
OnlyfourhexdigitsareallowedfortheIDlocations.
305Usingdefaultdestinationof1(file).
Ifnodestinationbitisspecified,thedefaultisused.
Page 199
306Crossingpageboundary-ensurepagebitsareset.
Generatedcodeiscrossingapageboundary.
307Settingpagebits.
PagebitsarebeingsetwiththeLCALLorLGOTOpseudo-op.
308Warninglevelsupersededbycommandlinevalue.
Thewarninglevelwasspecifiedonthecommandlineaswellasinthesourcefile.Thecommandlinehasprecedence.
309Macroexpansionsupersededbycommandline.
Macroexpansionwasspecifiedonthecommandlineaswellasinthesourcefile.Thecommandlinehasprecedence.
310SupersedingcurrentmaximumRAMandRAMmap.
The__MAXRAMdirectivehasbeenusedpreviously.
312PageorBankselectionnotneededforthisdevice.Nocodegenerated.
IfadevicecontainsonlyoneROMpageorRAMbank,nopageorbankselectionisrequired,andanyPAGESEL,BANKSEL,or
Page 200
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
BANKISELdirectiveswillnotgenerateanycode.
313CBLOCKconstantswillstartwithavalueof0.
IfthefirstCBLOCKinthesourcefilehasnostartingvaluespecified,thismessagewillbegenerated.
314UNKNOWNMESSAGE
Amessagehasoccurredwhichtheassemblercannotunderstand.Itisnotanyofthemessagesdescribedinthisappendix.ContactyourMicrochipFieldApplicationEngineer(FAE)ifyoucannotdebugthismessage.
Page 201
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
AssemblerLimitations
GeneralLimitations
MPASMassembleronlylooksinthepathoftheexecutableorthefilebeingassembledforincludedfiles.Therefore,IncludePathinformationenteredintheMPLABIDEEditProjectdialogwillNOTbeusedbytheassembler.
Sourcelinelimit(expanded)=200charactersFilenamelimit=8.3format
DirectiveLimitations
whilenestlimit=8deepwhilelooplimit=100lineswhileiterationlimit=256
ifnestlimit=16deepincludenestlimit=5levelsincludemax.numberoffiles=255macronestlimit=16deepmacrosourcelinelimit(expanded)=
200charactersDonotuse#includesinmacros.
Page 202
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
InstructionSets
PICmicroMCUinstructionsetsareusedindevelopingapplicationswithMPASMassembler,MPLINKobjectlinkerandMPLIBobjectlibrarian.
Instructionsarelistedherebasedondevicecoresize.Asofthetimeofpublicationofthisdocument,thefollowingcoresizesmaptothefollowingdevices:
12-BitCoreDevices:PIC12C5XX,PIC12CE5XX,PIC16X5X,PIC16C505
14-BitCoreDevices:PIC12C67X,PIC12CE67X,PIC12F629/675,PIC16XXXX16-BitCoreDevices:PIC17CXXXExtended16-BitCoreDevices:PIC18XXXXX
Topicscoveredare:
KeytoPICmicroFamilyInstructionSets
12-BitCoreInstructionSet14-BitCoreInstructionSet16-BitCoreInstructionSetKeytoExtended16-BitCoreInstructionSetExtended16-BitCoreInstructionSet
Page 203
KeytoPICmicroFamilyInstructionSets
Field DescriptionRegisterFiles
dest DestinationeithertheWREGregisterorthespecifiedregisterfilelocation.Seed.f Registerfileaddress(5-bit,7-bitor8-bit).p Peripheralregisterfileaddress(5-bit).r PortforTRIS.
xDon'tcare(`0'or`1').Theassemblerwillgeneratecodewithx=0.ItistherecommendedformofuseforcompatibilitywithallMicrochipsoftwaretools.
Literals
k
Literalfield,constantdataorlabel.k4-bit.kk8-bit.kkk12-bit.
Bits
b Bitaddresswithinan8-bitfileregister(0to7).
dDestinationselectbit.d=0:storeresultinWREGd=1:storeresultinfileregisterf(default)
iTablepointercontrol.i=0:donotchange.i=1:incrementafterinstrucitonexecution.
sDestinationselectbit.s=0:storeresultinfileregisterfandWREGs=1:storeresultinfileregisterf(default)
tTablebyteselect.t=0:performoperationonlowerbyte.t=1:performoperationonupperbyte.
'' Bitvalues,asopposedtoHexvalue.NamedRegistersBSR BankSelectRegister.UsedtoselectthecurrentRAMbank.OPTION OPTIONRegister.PCL ProgramCounterLowByte.PCH ProgramCounterHighByte.PCLATH ProgramCounterHighByteLatch.PCLATU ProgramCounterUpperByteLatch.PRODH ProductofMultiplyHighByte.PRODL ProductofMultiplyLowByte.TBLATH TableLatch(TBLAT)HighByte.TBLATL TableLatch(TBLAT)LowByte.
Page 204
TBLPTR 16-bitTablePointer(TBLPTRH:TBLPTRL).PointstoaProgramMemorylocation.WREG Workingregister(accumulator).NamedBitsC,DC,Z,OV,N ALUStatusbits:Carry,DigitCarry,Zero,Overflow,Negative.
TO Time-outbit.PD Power-downbit.GIE GlobalInterruptEnablebit(s).NamedDeviceFeaturesPC ProgramCounter.TOS Top-of-Stack.WDT WatchdogTimer.Misc.Descriptors() Contents.→,↔ Assignedto.<> Registerbitfield.
Page 205
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 206
12-BitCoreInstructionSet
Microchip'sbase-line8-bitmicrocontrollerfamilyusesa12-bitwideinstructionset.Allinstructionsexecuteinasingleinstructioncycleunlessotherwisenoted.AnyunusedopcodeisexecutedasaNOP.
Theinstructionsetisgroupedintothefollowingcatagories:Byte-orientedfileregisteroperations,bit-orientedfileregisteroperations,andcoreliteralandcontroloperations.Instructionsarelistedbycatagoryinthetablesbelow.InstructionopcodeisshowinHexbycertainmakingassumptions,eitherlistedinthekeyorasafootnote.Formoreinformationontheopcodebitvaluesforeachinstruction,aswellasthenumberofcyclesperinstruction,statusbitsaffectedandcompleteinstructiondetails,seethereleventdevicedatasheet.
TABLE:12-BITCOREBYTE-ORIENTEDFILEREGISTEROPERATIONS
Hex Mnemonic Description Function1Ef* ADDWF f,d AddWandf WREG+f→dest
16f* ANDWF f,d ANDWandf WREG.AND.f→dest
06f CLRF f Clearf 0→f
040 CLRW ClearW 0→WREG
26f* COMF f,d Complementf .NOT.f→dest
0Ef* DECF f,d Decrementf f-1→dest
2Ef* DECFSZ f,d Decrementf,skipifzero f-1→dest,skipifzero
2Af* INCF f,d Incrementf f+1→dest
3Ef* INCFSZ f,d Incrementf,skipifzero f+1→dest,skipifzero
12f* IORWF f,d InclusiveORWandf WREG.OR.f→dest
22f* MOVF f,d Movef f→dest
02f MOVWF f MoveWtof WREG→f
000 NOP Nooperation
36f* RLF f,d Rotateleftf
Page 207
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
32f* RRF f,d Rotaterightf
0Af* SUBWF f,d SubtractWfromf f-WREG→dest
3Af* SWAPF f,d Swaphalvesf f(0:3)↔f(4:7)→dest
1Af* XORWF f,d ExclusiveORWandf WREG.XOR.f→dest*Assumingdefaultbitvalueford.
TABLE:12-BITCOREBIT-ORIENTEDFILEREGISTEROPERATIONS
Hex Mnemonic Description Function4bf BCF f,b Bitclearf 0→f(b)
5bf BSF f,b Bitsetf 1→f(b)
6bf BTFSC f,b Bittest,skipifclear skipiff(b)=0
7bf BTFSS f,b Bittest,skipifset skipiff(b)=1
TABLE:12-BITCORELITERALANDCONTROLOPERATIONSHex Mnemonic Description FunctionEkk ANDLW kk ANDliteralandW kk.AND.WREG→WREG
9kk CALL kk Callsubroutine PC+1→TOS,kk→PC
004 CLRWDT Clearwatchdogtimer 0→WDT(andPrescalerifassigned)
Akk GOTO kk Gotoaddress(kisninebits) kk→PC(9bits)
Dkk IORLW kk Incl.ORliteralandW kk.OR.WREG→WREG
Ckk MOVLW kk MoveLiteraltoW kk→WREG
002 OPTION LoadOPTIONRegister WREG→OPTIONRegister
8kk RETLW kk ReturnwithliteralinW kk→WREG,TOS→PC
003 SLEEP GointoStandbyMode 0→WDT,stoposcillator
00r TRIS r Tristateportr WREG→I/Ocontrolregr
Fkk XORLW kk ExclusiveORliteralandW kk.XOR.WREG→WREG
Page 208
14-BitCoreInstructionSet
Microchip'smid-range8-bitmicrocontrollerfamilyusesa14-bitwideinstructionset.Thisinstructionsetconsistsof36instructions,eachasingle14-bitwideword.Mostinstructionsoperateonafileregister,f,andtheworkingregister,WREG(accumulator).TheresultcanbedirectedeithertothefileregisterortheWREGregisterortobothinthecaseofsomeinstructions.Afewinstructionsoperatesolelyonafileregister(BSF,forexample).
Theinstructionsetisgroupedintothefollowingcatagories:Byte-orientedfileregisteroperations,bit-orientedfileregisteroperations,andcoreliteralandcontroloperations.Instructionsarelistedbycatagoryinthetablesbelow.InstructionopcodeisshowinHexbycertainmakingassumptions,eitherlistedinthekeyorasafootnote.Formoreinformationontheopcodebitvaluesforeachinstruction,aswellasthenumberofcyclesperinstruction,statusbitsaffectedandcompleteinstructiondetails,seethereleventdevicedatasheet.
TABLE:14-BITCOREBYTE-ORIENTEDFILEREGISTEROPERATIONS
Hex Mnemonic Description Function07df ADDWF f,d AddWandf W+f→d
05df ANDWF f,d ANDWandf W.AND.f→d
01'1'f CLRF f Clearf 0→f
01xx CLRW ClearW 0→W
09df COMF f,d Complementf .NOT.f→d
03df DECF f,d Decrementf f-1→d
0Bdf DECFSZ f,d Decrementf,skipifzero f-1→d,skipif0
0Adf INCF f,d Incrementf f+1→d
0Fdf INCFSZ f,d Incrementf,skipifzero f+1→d,skipif0
04df IORWF f,d InclusiveORWandf W.OR.f→d
08df MOVF f,d Movef f→d
00'1'f MOVWF f MoveWtof W→f
0000 NOP Nooperation
Page 209
0Ddf RLF f,d Rotateleftf
0Cdf RRF f,d Rotaterightf
02df SUBWF f,d SubtractWfromf f-W→d
0Edf SWAPF f,d Swaphalvesf f(0:3)↔f(4:7)→d
06df XORWF f,d ExclusiveORWandf W.XOR.f→d
TABLE:14-BITCOREBIT-ORIENTEDFILEREGISTEROPERATIONS
Hex Mnemonic Description Function4bf BCF f,b Bitclearf 0→f(b)
5bf BSF f,b Bitsetf 1→f(b)
6bf BTFSC f,b Bittest,skipifclear skipiff(b)=0
7bf BTFSS f,b Bittest,skipifset skipiff(b)=1
TABLE:14-BITCORELITERALANDCONTROLOPERATIONSHex Mnemonic Description Function
3Ekk ADDLW kk AddliteraltoW kk+WREG→WREG
39kk ANDLW kk ANDliteralandW kk.AND.WREG→WREG
2'0'kkk CALL kkk Callsubroutine PC+1→TOS,kk→PC
0064 CLRWDT Clearwatchdogtimer 0→WDT(andPrescalerifassigned)
2'1'kkk GOTO kkk Gotoaddress(kisninebits) kk→PC(9bits)
38kk IORLW kk Incl.ORliteralandW kk.OR.WREG→WREG
30kk MOVLW kk MoveLiteraltoW kk→WREG
0062 OPTION LoadOPTIONregister WREG→OPTIONRegister
0009 RETFIE ReturnfromInterrupt TOS→PC,1→GIE
34kk RETLW kk ReturnwithliteralinW kk→WREG,TOS→PC
0008 RETURN Returnfromsubroutine TOS→PC
0063 SLEEP GointoStandbyMode 0→WDT,stoposcillator
3Ckk SUBLW kk SubtractWfromliteral kk-WREG→WREG
006r TRIS r Tristateportr WREG→I/Ocontrolregr
3Akk XORLW kk ExclusiveORliteralandW kk.XOR.WREG→WREG
TABLE:12-BIT/14-BITCORESPECIALINSTRUCTIONMNEMONICS
Mnemonic Description EquivalentOperation(s) Status
BTFSC 3,0
Page 210
ADDCF f,d AddCarrytoFile INCF f,d Z
ADDDCF f,d AddDigitCarrytoFile BTFSCINCF
3,1f,d Z
B k Branch GOTO k -
BC k BranchonCarry BTFSCGOTO
3,0k -
BDC k BranchonDigitCarry BTFSCGOTO
3,1k -
BNC k BranchonNoCarry BTFSSGOTO
3,0k -
BNDC k BranchonNoDigitCarry BTFSSGOTO
3,1k -
BNZ k BranchonNoZero BTFSSGOTO
3,2k -
BZ k BranchonZero BTFSCGOTO
3,2k -
CLRC ClearCarry BCF 3,0 -
CLRDC ClearDigitCarry BCF 3,1 -
CLRZ ClearZero BCF 3,2 -
LCALL k LongCallBCF/BSFBCF/BSFCALL
0x0A,30x0A,4k
LGOTO k LongGOTOBCF/BSFBCF/BSFGOTO
0x0A,30x0A,4k
MOVFW f MoveFiletoW MOVF f,0 Z
NEGF f,d NegateFile COMFINCF
f,1f,d Z
SETC SetCarry BSF 3,0 -
SETDC SetDigitCarry BSF 3,1 -
SETZ SetZero BSF 3,2 -
SKPC SkiponCarry BTFSS 3,0 -
SKPDC SkiponDigitCarry BTFSS 3,1 -
SKPNC SkiponNoCarry BTFSC 3,0 -
SKPNDC SkiponNoDigitCarry BTFSC 3,1 -
SKPNZ SkiponNonZero BTFSC 3,2 -
SKPZ SkiponZero BTFSS 3,2 -
SUBCF f,d SubtractCarryfromFile BTFSCDECF
3,0f,d Z
SUBDCF f,d SubtractDigitCarryfromFile BTFSC 3,1 Z
Page 211
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DECF f,dTSTF f TestFile MOVF f,1 Z
Page 212
16-BitCoreInstructionSet
Microchip'shigh-performance8-bitmicrocontrollerfamilyusesa16-bitwideinstructionset.Thisinstructionsetconsistsof55instructions,eachasingle16-bitwideword.Mostinstructionsoperateonafileregister,f,andtheworkingregister,WREG(accumulator).TheresultcanbedirectedeithertothefileregisterortheWREGregisterortobothinthecaseofsomeinstructions.Somedevicesinthisfamilyalsoincludehardwaremultiplyinstructions.Afewinstructionsoperatesolelyonafileregister(BSFforexample).
Theinstructionsetisgroupedintothefollowingcatagories:Byte-orientedfileregisteroperations,bit-orientedfileregisteroperations,andcoreliteralandcontroloperations.Instructionsarelistedbycatagoryinthetablesbelow.InstructionopcodeisshowinHexbycertainmakingassumptions,eitherlistedinthekeyorasafootnote.Formoreinformationontheopcodebitvaluesforeachinstruction,aswellasthenumberofcyclesperinstruction,statusbitsaffectedandcompleteinstructiondetails,seethereleventdevicedatasheet.
TABLE:16-BITBYTE-ORIENTEDFILEREGISTEROPERATIONSHex Mnemonic Description Function0Ff* ADDWF f,d AddWREGtoF (WREG+f)→dest
11f* ADDWFC f,d AddWREGandCarrytof (WREG+f+C)→dest
0Bf* ANDWF f,d ANDWREGwithf (WREG.AND.f)→dest
29f* CLRF f,s Cleardest 0x00→dest
13f* COMF f,d Complementf .NOT.f→dest
31f CPFSEQ f Comparef,WREG,skipiff=WREG f-WREG,skipiff=WREG
32f CPFSGT f Comparef,WREG,skipiff>WREG f-WREG,skipiff>WREG
30f CPFSLT f Comparef,WREG,skipiff<WREG f-WREG,skipiff<WREG
2Ff* DAW f,s Dec.adjustWREG,storeindest WREGadjusted→dest
07f* DECF f,d Decrementf (f-1)→dest
17f* DECFSZ f,d Decrementf,skipif0 (f-1)→dest,skipif0
27f* DCFSNZ f,d Decrementf,skipifnot0 (f-1)→dest,skipifnot0
Page 213
15f* INCF f,d Incrementf (f+1)→dest
1Ff* INCFSZ f,d Incrementf,skipifzero (f+1)→dest,skipif0
25f* INFSNZ f,d Incrementf,skipifnotzero (f+1)→dest,skipifnot0
09f* IORWF f,d InclusiveorWREGwithf (WREG.OR.f)→dest
6pf MOVFP f,p Moveftop f→p
4pf MOVPF p,f Moveptof p→f
01f MOVWF f MoveWREGtoF WREG→f
34f MULWF f MultiplyWREGandf (WREGxf)→PRODH:PRODL
2Df* NEGW f,s NegateWREG,storeindest -WREG→dest
0000 NOP Nooperation Nooperation
1Bf* RLCF f,d Rotateleftthroughcarry
23f* RLNCF f,d Rotateleft(nocarry)
19f* RRCF f,d Rotaterightthroughcarry
21f* RRNCF f,d Rotateright(nocarry)
2Af* SETF f,s Setdest 0xFF→dest
05f* SUBWF f,d SubtractWREGfromf (f-WREG)→d
03f* SUBWFB f,d Subtractfromfwithborrow (f-WREG-c)→d
1Df* SWAPF f,d Swapf f(0:3)→d(4:7),f(4:7)→d(0:3)
A8f TABLRD t,i,f
Readdatafromtablelatchintofilef,thenupdatetablelatchwith16-bitcontentsofmemorylocationaddressedbytablepointer
TBLATH→fift=1,TBLATL→fift=0;ProgMem(TBLPTR)→TBLAT;TBLPTR+1→TBLPTRifi=1
ACf TABLWT t,i,f
Writedatafromfileftotablelatchandthenwrite16-bittablelatchtoprogrammemorylocationaddressedbytablepointer
f→TBLATHift=1,f→TBLATLift=0;TBLAT→ProgMem(TBLPTR);TBLPTR+1→TBLPTRifi=1
A0f TLRD t,f Readdatafromtablelatchintofilef(tablelatchunchanged)
TBLATH→fift=1TBLATL→fift=0
A4f TLWT t,f Writedatafromfilefintotablelatch f→TBLATHift=1f→TBLATLift=0
33f TSTFSZ f Testf,skipifzero skipiff=0
0Df* XORWF f,d ExclusiveORWREGwithf (WREG.XOR.f)→dest
Page 214
*Assumingdefaultbitvaluesfordands.
TABLE:16-BITCOREBIT-ORIENTEDFILEREGISTEROPERATIONS
Hex Mnemonic Description Function8'1'bf BCF f,b Bitclearf 0→f(b)
8'0'bf BSF f,b Bitsetf 1→f(b)
9'1'bf BTFSC f,b Bittest,skipifclear skipiff(b)=0
9'0'bf BTFSS f,b Bittest,skipifset skipiff(b)=1
3'1'bf BTG f,b Bittogglef .NOT.f(b)→f(b)
TABLE:16-BITCORELITERALANDCONTROLOPERATIONSHex Mnemonic Description FunctionB1kk ADDLW kk AddliteraltoWREG (WREG+kk)→WREG
B5kk ANDLW kk ANDLiteralandWREG (WREG.AND.kk)→WREG
Ekkk CALL kkk Subroutinecall(within8kpage)PC+1→TOS,k→PC(12:0),k(12:8)→PCLATH(4:0),PC(15:13)→PCLATH(7:5)
0004 CLRWT Clearwatchdogtimer 0→WDT,0→WDTprescaler,1→PD,1→TO
Ckkk GOTO kkk Unconditionalbranch(within8k)k→PC(12:0)k(12:8)→PCLATH(4:0),PC(15:13)→PCLATH(7:5)
B3kk IORLW kk InclusiveORliteralwithW (WREG.OR.kk)→WREG
B7kk LCALL kk LongCall(within64k) (PC+1)→TOS;kk→PCL,(PCLATH)→PCH
B8xk MOVLB k MoveliteraltolownibbleinBSR k→BSR(3:0)
BAkx MOVLR k MoveliteraltohighnibbleinBSR k→BSR(7:4)
B0kk MOVLW kk MoveliteraltoWREG kk→WREG
BCkk MULLW kk MultiplyliteralandWREG (kkxWREG)→PRODH:PRODL
0005 RETFIE Returnfrominterrupt,enableinterrupt (PCLATH)→PCH:k→PCL0→GLINTD
B6kk RETLW kk ReturnwithliteralinWREG kk→W,TOS→PC,(PCLATHunchanged)
0002 RETURN Returnfromsubroutine TOS→PC(PCLATHunchanged)
0003 SLEEP EnterSleepModeStoposcillator,powerdown,0→WDT,0→WDTPrescaler1→PD,1→TO
B2kk SUBLW kk SubtractWREGfromliteral (kk-WREG)→WREG
B4kk XORLW kk ExclusiveORliteralwithWREG (WREG.XOR.kk)→WREG
Page 215
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 216
KeytoExtended16-BitCoreInstructionSet
Field DescriptionRegisterFiles
dest DestinationeithertheWREGregisterorthespecifiedregisterfilelocation.Seed.
f
Registerfileaddress.f8-bit(0x00to0xFF).f'12-bit(0x000to0xFFF).Thisisthesourceaddress.f"12-bit(0x000to0xFFF).Thisisthedestinationaddress.
r 0,1or2forFSRnumber.
xDon'tcare(`0'or`1').Theassemblerwillgeneratecodewithx=0.ItistherecommendedformofuseforcompatibilitywithallMicrochipsoftwaretools.
Literals
k
Literalfield,constantdataorlabel.k4-bit.kk8-bit.kkk12-bit.
Offsets,Increments/Decrements
n Therelativeaddress(2'scomplementnumber)forrelativebranchinstructions,orthedirectaddressforCall/BranchandReturninstructions.
**+*-+*
ThemodeoftheTBLPTRregisterforthetablereadandtablewriteinstructions.Onlyusedwithtableread(TBLRD)andtablewrite(TBLWT)instructions:NoChangetoregisterPost-IncrementregisterPost-DecrementregisterPre-Incrementregister
Bits
aRAMaccessbita=0:RAMlocationinAccessRAM(BSRregisterisignored)a=1:RAMbankisspecifiedbyBSRregister(default)
b Bitaddresswithinan8-bitfileregister(0to7).
dDestinationselectbitd=0:storeresultinWREGd=1:storeresultinfileregisterf(default)
sFastCall/Returnmodeselectbits=0:donotupdateinto/fromshadowregisters(default)s=1:certainregistersloadedinto/fromshadowregisters(Fastmode)
'' Bitvalues,asopposedtoHexvalue.NamedRegistersBSR BankSelectRegister.UsedtoselectthecurrentRAMbank.FSR FileSelectRegister.PCL ProgramCounterLowByte.PCH ProgramCounterHighByte.
Page 217
PCLATH ProgramCounterHighByteLatch.PCLATU ProgramCounterUpperByteLatch.PRODH ProductofMultiplyHighByte.PRODL ProductofMultiplyLowByte.STATUS StatusRegisterTABLAT 8-bitTableLatch.TBLPTR 21-bitTablePointer(pointstoaProgramMemorylocation).WREG Workingregister(accumulator).NamedBitsC,DC,Z,OV,N ALUStatusbits:Carry,DigitCarry,Zero,Overflow,Negative.
TO Time-outbit.PD Power-downbit.PEIE PeripheralInterruptEnablebit.GIE,GIEL/H GlobalInterruptEnablebit(s).
NamedDeviceFeaturesMCLR Mastercleardevicereset.PC ProgramCounter.TOS Top-of-Stack.WDT WatchdogTimer.Misc.Descriptors() Contents.→ Assignedto.<> Registerbitfield.
Page 218
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 219
Extended16-BitCoreInstructionSet
Microchip'snewhigh-performance8-bitmicrocontrollerfamilyusesa16-bitwideinstructionset.Thisinstructionsetconsistsof76instructions,eachasingle16-bitwideword(2bytes).Mostinstructionsoperateonafileregister,f,andtheworkingregister,WREG(accumulator).TheresultcanbedirectedeithertothefileregisterortheWREGregisterortobothinthecaseofsomeinstructions.Afewinstructionsoperatesolelyonafileregister(BSFforexample).
TABLE:EXTENDED16-BITCOREBYTE-ORIENTEDREGISTEROPERATIONSHex Mnemonic Description Function27f* ADDWF f,d,a ADDWREGtof WREG+f→dest
23f* ADDWFC f,d,a ADDWREGandCarrybittof WREG+f+C→dest
17f* ANDWF f,d,a ANDWREGwithf WREG.AND.f→dest
6Bf* CLRF f,a Clearf 0→f
1Ff* COMF f,d,a Complementf .NOT.f→dest
63f* CPFSEQ f,a ComparefwithWREG,skipiff=WREG
f-WREG,iff=WREG,PC+4→PCelsePC+2→PC
65f* CPFSGT f,a ComparefwithWREG,skipiff>WREG
f-WREG,iff>WREG,PC+4→PCelsePC+2→PC
61f* CPFSLT f,a ComparefwithWREG,skipiff<WREG
f-WREG,iff<WREG,PC+4→PCelsePC+2→PC
07f* DECF f,d,a Decrementf f-1→dest
2Ff* DECFSZ f,d,a Decrementf,skipif0 f-1→dest,ifdest=0,PC+4→PCelsePC+2→PC
4Ff* DCFSNZ f,d,a Decrementf,skipifnot0 f-1→dest,ifdest¼0,PC+4→PCelsePC+2→PC
2Bf* INCF f,d,a Incrementf f+1→dest
3Ff* INCFSZ f,d,a Incrementf,skipif0 f+1→dest,ifdest=0,PC+4→PCelsePC+2→PC
4Bf* INFSNZ f,d,a Incrementf,skipifnot0 f+1→dest,ifdest¼0,PC+4→PCelsePC+2→PC
13f* IORWF f,d,a InclusiveORWREGwithf WREG.OR.f→dest
53f* MOVF f,d,a Movef f→dest
Cf'Ff" MOVFF f',f" Movef'tofd"(secondword) f'→f"
6Ff* MOVWF f,a MoveWREGtof WREG→f
03f* MULWF f,a MultiplyWREGwithf WREG*f→PRODH:PRODL
Page 220
6Df* NEGF f,a Negatef -f→f
37f* RLCF f,d,a RotateleftfthroughCarry
47f* RLNCF f,d,a Rotateleftf(nocarry)
33f* RRCF f,d,a RotaterightfthroughCarry
43f* RRNCF f,d,a Rotaterightf(nocarry)
69f* SETF f,a Setf 0xFF→f
57f* SUBFWB f,d,a SubtractffromWREGwithBorrow WREG-f-C→dest
5Ff* SUBWF f,d,a SubtractWREGfromf f-WREG→dest
5Bf* SUBWFB f,d,a SubtractWREGfromfwithBorrow f-WREG-C→dest
3Bf* SWAPF f,d,a Swapnibblesoff f<3:0>→dest<7:4>,f<7:4>→dest<3:0>
67f* TSTFSZ f,a Testf,skipif0 PC+4→PC,iff=0,elsePC+2→PC
1Bf* XORWF f,d,a ExclusiveORWREGwithf WREG.XOR.f→dest*Assumingdefaultbitvaluesfordanda.
TABLE:EXTENDED16-BITCOREBIT-ORIENTEDREGISTEROPERATIONS
Hex Mnemonic Description Function91f* BCF f,b,a BitClearf 0→f<b>
81f* BSF f,b,a BitSetf 1→f<b>
B1f* BTFSC f,b,a Bittestf,skipifclear iff<b>=0,PC+4→PC,elsePC+2→PC
A1f* BTFSS f,b,a Bittestf,skipifset iff<b>=1,PC+4→PC,elsePC+2→PC
71f* BTG f,b,a BitTogglef f<b>→f<b>*Assumingb=0anddefaultbitvaluefora.
TABLE:EXTENDED16-BITCORECONTROLOPERATIONSHex Mnemonic Description Function
E2n BC n BranchifCarry ifC=1,PC+2+2*n→PC,elsePC+2→PC
E6n BN n BranchifNegative ifN=1,PC+2+2*n→PC,elsePC+2→PC
E3n BNC n BranchifNotCarry ifC=0,PC+2+2*n→PC,elsePC+2→PC
E7n BNN n BranchifNotNegative ifN=0,PC+2+2*n→PC,elsePC+2→PC
E5n BNOV n BranchifNotOverflow ifOV=0,PC+2+2*n→PC,elsePC+2→PC
Page 221
E1n BNZ n BranchifNotZero ifZ=0,PC+2+2*n→PC,elsePC+2→PC
E4n BOV n BranchifOverflow ifOV=1,PC+2+2*n→PC,elsePC+2→PC
D'0'n BRA n BranchUnconditionally PC+2+2*n→PC
E0n BZ n BranchifZero ifZ=1,PC+2+2*n→PC,elsePC+2→PC
ECkk*Fkkk CALL n,s CallSubroutine1stword
2ndword
PC+4→TOS,n→PC<20:1>,ifs=1,WREG→WREGs,STATUS→STATUSs,BSR→BSRs
0004 CLRWDT ClearWatchdogTimer 0→WDT,0→WDTpostscaler,1→TO,1→PD
0007 DAW DecimalAdjustWREG
ifWREG<3:0>>9orDC=1,WREG<3:0>+6→WREG<3:0>,elseWREG<3:0>→WREG<3:0>;ifWREG<7:4>>9orC=1,WREG<7:4>+6→WREG<7:4>,elseWREG<7:4>→WREG<7:4>;
EFkkFkkk GOTO n Gotoaddress1stword
2ndword n→PC<20:1>
0000 NOP NoOperation NoOperation
Fxxx NOP NoOperation NoOperation(2-wordinstructions)
0006 POP Poptopofreturnstack(TOS) TOS-1→TOS
0005 PUSH Pushtopofreturnstack(TOS) PC+2→TOS
D'1'n RCALL n RelativeCall PC+2→TOS,PC+2+2*n→PC
00FF RESET Softwaredevicereset SameasMCLRreset
0010* RETFIE s Returnfrominterrupt(andenableinterrupts)
TOS→PC,1→GIE/GIEHorPEIE/GIEL,ifs=1,WREGs→WREG,STATUSs→STATUS,BSRs→BSR,PCLATU/PCLATHunchngd.
0012* RETURN s ReturnfromsubroutineTOS→PC,ifs=1,WREGs→WREG,STATUSs→STATUS,BSRs→BSR,PCLATU/PCLATHareunchanged
0003 SLEEP EnterSLEEPMode 0→WDT,0→WDTpostscaler,1→TO,0→PD
*Assumingdefaultbitvaluefors.
TABLE:EXTENDED16-BITCORELITERALOPERATIONSHex Mnemonic Description Function0Fkk ADDLW kk AddliteraltoWREG WREG+kk→WREG
0Bkk ANDLW kk ANDliteralwithWREG WREG.AND.kk→WREG
09kk IORLW kk InclusiveORliteralwithWREG WREG.OR.kk→WREG
EErkF0kk LFSR r,kk Moveliteral(12bit)2ndword
toFSRr1stword kk→FSRr
010k MOVLB k MoveliteraltoBSR<3:0> kk→BSR
0Ekk MOVLW kk MoveliteraltoWREG kk→WREG
Page 222
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
0Dkk MULLW kk MultiplyliteralwithWREG WREG*kk→PRODH:PRODL
0Ckk RETLW kk ReturnwithliteralinWREG kk→WREG
08kk SUBLW kk SubtractWREGfromliteral kk-WREG→WREG
0Akk XORLW kk ExclusiveORliteralwithWREG WREG.XOR.kk→WREG
TABLE:EXTENDED16-BITCOREMEMORYOPERATIONSHex Mnemonic Description Function0008 TBLRD* TableRead ProgMem(TBLPTR)→TABLAT
0009 TBLRD*+ TableReadwithpost-increment ProgMem(TBLPTR)→TABLATTBLPTR+1→TBLPTR
000A TBLRD*- TableReadwithpost-decrement ProgMem(TBLPTR)→TABLATTBLPTR-1→TBLPTR
000B TBLRD+* TableReadwithpre-increment TBLPTR+1→TBLPTRProgMem(TBLPTR)→TABLAT
000C TBLWT* TableWrite TABLAT→ProgMem(TBLPTR)
000D TBLWT*+ TableWritewithpost-increment TABLAT→ProgMem(TBLPTR)TBLPTR+1→TBLPTR
000E TBLWT*- TableWritewithpost-decrement TABLAT→ProgMem(TBLPTR)TBLPTR-1→TBLPTR
000F TBLWT+* TableWritewithpre-increment TBLPTR+1→TBLPTRTABLAT→ProgMem(TBLPTR)
Page 223
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
UsefulTables
Someusefultablesareincludedforreferencehere.
ASCIICharacterSet
HexadecimaltoDecimalConversion
Page 224
ASCIICharacterSet
LeastSignificantNibble
MostSignificantNibbleHEX 0 1 2 3 4 5 6 70 NUL DLE Space 0 @ P ` p1 SOH DC1 ! 1 A Q a q2 STX DC2 " 2 B R b r3 ETX DC3 # 3 C S c s4 EOT DC4 $ 4 D T d t5 ENQ NAK % 5 E U e u6 ACK SYN & 6 F V f v7 Bell ETB ' 7 G W g w8 BS CAN ( 8 H X h x9 HT EM ) 9 I Y i yA LF SUB * : J Z j zB 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
Page 225
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 226
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
HexadecimaltoDecimalConversion
Thisappendixdescribeshowtoconverthexadecimaltodecimal.ForeachHEXdigit,findtheassociateddecimalvalue.Addthenumberstogether.
HighByte LowByteHEX1000 Dec HEX100 Dec HEX10 Dec HEX1 Dec
0 0 0 0 0 0 0 01 4096 1 256 1 16 1 12 8192 2 512 2 32 2 23 12288 3 768 3 48 3 34 16384 4 1024 4 64 4 45 20480 5 1280 5 80 5 56 24576 6 1536 6 96 6 67 28672 7 1792 7 112 7 78 32768 8 2048 8 128 8 89 36864 9 2304 9 144 9 9A 40960 A 2560 A 160 A 10B 45056 B 2816 B 176 B 11C 49152 C 3072 C 192 C 12D 53248 D 3328 D 208 D 13E 57344 E 3584 E 224 E 14F 61440 F 3840 F 240 F 15
Forexample,HEXA38Fconvertsto41871asfollows:
HEX1000'sDigit HEX100'sDigit HEX10'sDigit HEX1'sDigit Result
40960 768 128 15 41871Decimal
Page 227
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Support
ThegeneralinformationcontainedherewillbeusefultoknowwhenworkingwithMicrochipTechnology'sMPASMassembler(theassembler),MPLINKobjectlinker(thelinker),andMPLIBobjectlibrarian(thelibrarian).
RecommendedReading
TheMicrochipWebSiteDevelopmentSystemsCustomerNotificationServiceCustomerSupport
Page 228
RecommendedReading
Otherusefuldocumentsarelistedbelow.
ReadmeFile-readme.asm
ForthelatestinformationonusingMPASMassembler,readthereadme.asmfile(anASCIItextfile)intheMPLABIDEdirectory.TheREADMEfilecontainsupdateinformationandknownissuesthatmaynotbeincludedintheuser'sguideortheon-linehelpfile.
ReadmeFile-readme.lkr
ForthelatestinformationonusingMPLINKlinkerandMPLIBlibrarian,readthereadme.lkrfile(anASCIItextfile)intheMPLABIDEdirectory.TheREADMEfilecontainsupdateinformationandknownissuesthatmaynotbeincludedintheuser'sguideortheon-linehelpfile.
MPASMAssembler,MPLINKObjectLinker,andMPLIBObjectLibrarianUser'sGuide(DS00000)
Thisuser'sguidedescribeshowtousetheMicrochipPICmicroMCUMPASMassembler,MPLINKobjectlinkerandMPLIBobjectlibrarian.
MPASMandMPLINKPICmicroQuickReferenceCard(DS30400)
Aquickreferencecard(QRC)containingMPASMassemblerdirectivelanguagesummary,MPASMassemblerradixtypessupported,MPLINKobjectlinkercommandlineoptions,MPLIBobjectlibrarianusageformatandexamples,PIC18CXXXcorespecialfunctionregisterfiles,ASCIIcharacterset,andPICmicroMCUinstructionsetsummaries.
Page 229
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
MicrochipTechnicalLibraryCD-ROM(DS00161)
ThisCD-ROMcontainscomprehensiveapplicationnotes,datasheets,andtechnicalbriefsforallofMicrochipproducts.ToobtainthisCD-ROM,contactthenearestMicrochipSalesandServicelocation(seebackpage).
EmbeddedControlHandbookVol.1&2andtheEmbeddedControlHandbookUpdate2000(DS00092,DS00167,andDS00711)
Thesehandbookscontainawealthofinformationaboutmicrocontrollerapplications.Toobtainthesedocuments,contactthenearestMicrochipsalesandservicelocation(seebackpage).
TheapplicationnotesdescribedinthesemanualsarealsoobtainablefromMicrochipsalesandservicelocationsorfromtheMicrochipwebsite(http://www.microchip.com).
Microsoft®Windows®Manuals
ThismanualassumesthatusersarefamiliarwiththeMicrosoftWindowsoperatingsystem.Manyexcellentreferencesexistforthissoftwareprogram,andshouldbeconsultedforgeneraloperationofWindows.
Page 230
TheMicrochipWebSite
MicrochipprovidesonlinesupportontheMicrochipWorldWideWeb(WWW)site.ThewebsiteisusedbyMicrochipasameanstomakefilesandinformationeasilyavailabletocustomers.Toviewthesite,youmusthaveaccesstotheInternetandawebbrowsersuchasNetscapeNavigatororMicrosoftInternetExplorer.
TheMicrochipwebsiteisavailablebyusingyourfavoriteInternetbrowsertoattachto:
http://www.microchip.com
Thewebsiteprovidesavarietyofservices.Usersmaydownloadfilesforthelatestdevelopmenttools,datasheets,applicationnotes,user'sguides,articles,andsampleprograms.AvarietyinformationspecifictothebusinessofMicrochipisalsoavailable,includinglistingsofMicrochipsalesoffices,distributorsandfactoryrepresentatives.
TechnicalSupport
FrequentlyAskedQuestions(FAQ)
OnlineDiscussionGroups-Conferencesforproducts,DevelopmentSystems,technicalinformationandmoreMicrochipConsultantProgramMemberListingLinkstootherusefulwebsitesrelatedtoMicrochipproducts
Developer'sToolbox
DesignTips
DeviceErrata
Otheravailableinformation
Page 231
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
LatestMicrochipPressReleases
ListingofseminarsandeventsJobPostings
Page 232
DevelopmentSystemsCustomerNotificationService
MicrochipstartedthecustomernotificationservicetohelpourcustomerskeepcurrentonMicrochipproductswiththeleastamountofeffort.Onceyousubscribe,youwillreceiveemailnotificationwheneverwechange,update,reviseorhaveerratarelatedtoyourspecifiedproductfamilyordevelopmenttoolofinterest.
GototheMicrochipWWWwebpage(http://www.microchip.com)andclickonCustomerChangeNotificationunderItemsofInterest.Followtheinstructionstoregister.
TheDevelopmentSystemsproductgroupcategoriesare:
Compilers
EmulatorsIn-CircuitDebuggersMPLABProgrammers
Hereisadescriptionofthesecategories:
COMPILERS-ThelatestinformationonMicrochipCcompilersandotherlanguagetools.TheseincludetheMPLABC17,MPLABC18andMPLABC30Ccompilers;MPASMandMPLABASM30assemblers;MPLINKandMPLABLINK30objectlinkers;andMPLIBandMPLABLIB30objectlibrarians.
EMULATORS-ThelatestinformationonMicrochipin-circuitemulators.ThisincludestheMPLABICE2000andMPLABICE4000.
Page 233
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
IN-CIRCUITDEBUGGERS-ThelatestinformationonMicrochipin-circuitdebuggers.TheseincludetheMPLABICDandMPLABICD2.
MPLAB-ThelatestinformationonMicrochipMPLABIDE,theWindowsIntegratedDevelopmentEnvironmentfordevelopmentsystemstools.ThislistisfocusedontheMPLABIDE,MPLABSIMandMPLABSIM30simulators,MPLABIDEProjectManagerandgeneraleditinganddebuggingfeatures.
PROGRAMMERS-ThelatestinformationonMicrochipdeviceprogrammers.TheseincludethePROMATEIIdeviceprogrammerandPICSTARTPlusdevelopmentprogrammer.
Page 234
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
CustomerSupport
UsersofMicrochipproductscanreceiveassistancethroughseveralchannels:
DistributororRepresentative
LocalSalesOfficeFieldApplicationEngineer(FAE)CorporateApplicationsEngineer(CAE)Hotline
Customersshouldcalltheirdistributor,representativeorfieldapplicationengineer(FAE)forsupport.Localsalesofficesarealsoavailabletohelpcustomers.Seethebackcoverforalistingofsalesofficesandlocations.
CorporateApplicationsEngineers(CAEs)maybecontactedat(480)792-7627.
Inaddition,thereisaSystemsInformationandUpgradeLine.ThislineprovidessystemusersalistingofthelatestversionsofallofMicrochip'sdevelopmentsystemssoftwareproducts.Plus,thislineprovidesinformationonhowcustomerscanreceiveanycurrentlyavailableupgradekits.
TheHotlineNumbersare:
1-800-755-2345forU.S.andmostofCanada.
1-480-792-7302fortherestoftheworld.
Page 235
Glossary
AbsoluteSection
Asectionwithafixed(absolute)addressthatcannotbechangedbythelinker.
AccessMemory(PIC18Only)
SpecialregistersonPIC18XXXXXdevicesthatallowaccessregardlessofthesettingofthebankselectregister(BSR).
Address
Valuethatidentifiesalocationinmemory.
AlphabeticCharacter
Alphabeticcharactersarethosecharactersthatarelettersofthearabicalphabet(a,b,...,z,A,B,...,Z).
Alphanumeric
Alphanumericcharactersarecomprisedofalphabeticcharactersanddecimaldigits(0,1,...,9).
AnonymousStructure
AnunnamedstructurethatisamemberofaCunion.Themembersofananonymousstructuremaybeaccessedasiftheyweremembersoftheenclosingunion.Forexample,inthefollowingcode,hiandloaremembersofananonymousstructureinsidetheunioncaster.
unioncastawayintintval;
Page 236
struct{charlo;//accessibleascaster.locharhi;//accessibleascaster.hi};}caster;ANSI
AmericanNationalStandardsInstituteisanorganizationresponsibleforformulatingandapprovingstandardsintheUnitedStates.
Application
AsetofsoftwareandhardwarethatmaybecontrolledbyaPICmicromicrocontroller.
Archive
Acollectionofrelocatableobjectmodules.Itiscreatedbyassemblingmultiplesourcefilestoobjectfiles,andthenusingthearchivertocombinetheobjectfilesintoonelibraryfile.Alibrarycanbelinkedwithobjectmodulesandotherlibrariestocreateexecutablecode.
Archiver
Atoolthatcreatesandmanipulateslibraries.
ASCII
AmericanStandardCodeforInformationInterchangeisacharactersetencodingthatuses7binarydigitstorepresenteachcharacter.Itincludesupperandlowercaseletters,digits,symbolsandcontrolcharacters.
Assembler
Alanguagetoolthattranslatesassemblylanguagesourcecode
Page 237
intomachinecode.
AssemblyLanguage
Aprogramminglanguagethatdescribesbinarymachinecodeinasymbolicform.
AssignedSection
Asectionwhichhasbeenassignedtoatargetmemoryblockinthelinkercommandfile.
AsynchronousEvents
Multipleeventsthatdonotoccuratthesametime.Thisisgenerallyusedtorefertointerruptsthatmayoccuratanytimeduringprocessorexecution.
AsynchronousStimulus
Datageneratedtosimulateexternalinputstoasimulatordevice.
Binary
Thebasetwonumberingsystemthatusesthedigits0-1.Theright-mostdigitcountsones,thenextcountsmultiplesof2,then22=4,etc.
Breakpoint,Hardware
Aneventwhoseexecutionwillcauseahalt.
Breakpoint,Software
Anaddresswhereexecutionofthefirmwarewillhalt.Usuallyachievedbyaspecialbreakinstruction.
Build
Page 238
Compileandlinkallthesourcefilesforanapplication.
C
Ageneral-purposeprogramminglanguagewhichfeatureseconomyofexpression,moderncontrolflowanddatastructures,andarichsetofoperators.
CalibrationMemory
AspecialfunctionregisterorregistersusedtoholdvaluesforcalibrationofaPICmicromicrocontrolleron-boardRCoscillatororotherdeviceperipherals.
CentralProcessingUnit
Thepartofadevicethatisresponsibleforfetchingthecorrectinstructionforexecution,decodingthatinstruction,andthenexecutingthatinstruction.Whennecessary,itworksinconjunctionwiththearithmeticlogicunit(ALU)tocompletetheexecutionoftheinstruction.Itcontrolstheprogrammemoryaddressbus,thedatamemoryaddressbus,andaccessestothestack.
COFF
CommonObjectFileFormat.Anobjectfileofthisformatcontainsmachinecode,debuggingandotherinformation.
CommandLineInterface
Ameansofcommunicationbetweenaprogramanditsuserbasedsolelyontextualinputandoutput.
Compiler
Aprogramthattranslatesasourcefilewritteninahigh-levellanguageintomachinecode.
Page 239
ConditionalCompilation
Theactofcompilingaprogramfragmentonlyifacertainconstantexpression,specifiedbyapreprocessordirective,istrue.
ConfigurationBits
Special-purposebitsprogrammedtosetPICmicromicrocontrollermodesofoperation.Aconfigurationbitmayormaynotbepreprogrammed.
ControlDirectives
Directivesinassemblylanguagecodethatcausecodetobeincludedoromittedbasedontheassembly-timevalueofaspecifiedexpression.
CPU
SeeCentralProcessingUnit.
CrossReferenceFile
Afilethatreferencesatableofsymbolsandalistoffilesthatreferencesthesymbol.Ifthesymbolisdefined,thefirstfilelistedisthelocationofthedefinition.Theremainingfilescontainreferencestothesymbol.
DataDirectives
Datadirectivesarethosethatcontroltheassembler'sallocationofprogramordatamemoryandprovideawaytorefertodataitemssymbolically;thatis,bymeaningfulnames.
DataMemory
OnMicrochipMCUandDSCdevices,datamemory(RAM)iscomprisedofgeneralpurposeregisters(GPRs)andspecial
Page 240
functionregisters(SFRs).SomedevicesalsohaveEEPROMdatamemory.
DeviceProgrammer
Atoolusedtoprogramelectricallyprogrammablesemiconductordevicessuchasmicrocontrollers.
Directives
Statementsinsourcecodethatprovidecontrolofthelanguagetool'soperation.
Download
Downloadistheprocessofsendingdatafromahosttoanotherdevice,suchasanemulator,programmerortargetboard.
EEPROM
ElectricallyErasableProgrammableReadOnlyMemory.AspecialtypeofPROMthatcanbeerasedelectrically.Dataiswrittenorerasedonebyteatatime.EEPROMretainsitscontentsevenwhenpoweristurnedoff.
Emulation
Theprocessofexecutingsoftwareloadedintoemulationmemoryasifitwerefirmwareresidingonamicrocontrollerdevice.
EmulationMemory
Programmemorycontainedwithintheemulator.
Emulator
Hardwarethatperformsemulation.
EmulatorSystem
Page 241
TheMPLABICE2000and4000emulatorsystemsincludethepod,processormodule,deviceadapter,cables,andMPLABIDEsoftware.
Endianess
Describesorderofbytesinamulti-byteobject.
EPROM
ErasableProgrammableReadOnlyMemory.Aprogrammableread-onlymemorythatcanbeerasedusuallybyexposuretoultravioletradiation.
ErrorFile
Afilecontainingerrormessagesanddiagnosticsgeneratedbyalanguagetool.
Event
Adescriptionofabuscyclewhichmayincludeaddress,data,passcount,externalinput,cycletype(fetch,R/W),andtimestamp.Eventsareusedtodescribetriggers,breakpointsandinterrupts.
Export
SenddataoutoftheMPLABIDEinastandardizedformat.
ExtendedMicrocontrollerMode
Inextendedmicrocontrollermode,on-chipprogrammemoryaswellasexternalmemoryisavailable.ExecutionautomaticallyswitchestoexternaliftheprogrammemoryaddressisgreaterthantheinternalmemoryspaceofthePIC17CXXXorPIC18CXXXdevice.
ExternalLabel
Page 242
Alabelthathasexternallinkage.
ExternalLinkage
Afunctionorvariablehasexternallinkageifitcanbereferencedfromoutsidethemoduleinwhichitisdefined.
ExternalSymbol
Asymbolforanidentifierwhichhasexternallinkage.Thismaybeareferenceoradefinition.
ExternalSymbolResolution
Aprocessperformedbythelinkerinwhichexternalsymboldefinitionsfromallinputmodulesarecollectedinanattempttoresolveallexternalsymbolreferences.Anyexternalsymbolreferenceswhichdonothaveacorrespondingdefinitioncausealinkererrortobereported.
ExternalInputLine
Anexternalinputsignallogicprobeline(TRIGIN)forsettinganeventbaseduponexternalsignals.
ExternalRAM
Off-chipRead/Writememory.
FileRegisters
On-chipdatamemory,includinggeneralpurposeregisters(GPRs)andspecialfunctionregisters(SFRs).
Flash
AtypeofEEPROMwheredataiswrittenorerasedinblocksinsteadofbytes.
Page 243
FNOP
ForcedNoOperation.AforcedNOPcycleisthesecondcycleofatwo-cycleinstruction.SincethePICmicromicrocontrollerarchitectureispipelined,itprefetchesthenextinstructioninthephysicaladdressspacewhileitisexecutingthecurrentinstruction.However,ifthecurrentinstructionchangestheprogramcounter,thisprefetchedinstructionisexplicitlyignored,causingaforcedNOPcycle.
FramePointer
Apointerthatreferencesthelocationonthestackthatseparatesthestack-basedargumentsfromthestack-basedlocalvariables.Providesaconvenientbasefromwhichtoaccesslocalvariablesandothervaluesforthecurrentfunction.
Free-Standing
ACcompilerimplementationthatacceptsanystrictlyconformingprogramthatdoesnotusecomplextypesandinwhichtheuseofthefeaturesspecifiedintheISOlibraryclauseisconfinedtothecontentsofthestandardheaders<float.h>,<iso646.h>,<limits.h>,<stddef.h>,and<stdint.h>.
GPR
GeneralPurposeRegister.Theportionofdevicedatamemory(RAM)avaliableforgeneraluse.
Halt
Astopofprogramexecution.ExecutingHaltisthesameasstoppingatabreakpoint.
HEXCode
Executableinstructionsstoredinahexadecimalformatcode.HEX
Page 244
codeiscontainedinaHEXfile.
HEXFile
AnASCIIfilecontaininghexadecimaladdressesandvalues(HEXcode)suitableforprogrammingadevice.
Hexadecimal
Thebase16numberingsystemthatusesthedigits0-9plusthelettersA-F(ora-f).ThedigitsA-Frepresenthexadecimaldigitswithvaluesof(decimal)10to15.Theright-mostdigitcountsones,thenextcountsmultiplesof16,then162=256,etc.
HighLevelLanguage
Alanguageforwritingprogramsthatisfurtherremovedfromtheprocessorthanassembly.
ICD
In-CircuitDebugger.MPLABICDandMPLABICD2areMicrochip'sin-circuitdebuggersforPIC16F87XandPIC18FXXXdevices,respectively.TheseICDsworkwithMPLABIDE.
ICE
In-CircuitEmulator.MPLABICE2000and4000areMicrochip'sin-circuitemulatorsthatworkwithMPLABIDE.
IDE
IntegratedDevelopmentEnvironment.MPLABIDEisMicrochip'sintegrateddevelopmentenvironment.
IEEE
InstituteofElectricalandElectronicsEngineers.
Page 245
Import
BringdataintotheMPLABIDEfromanoutsidesource,suchasfromaHEXfile.
InstructionSet
Thecollectionofmachinelanguageinstructionsthataparticularprocessorunderstands.
Instructions
Asequenceofbitsthattellsacentralprocessingunittoperformaparticularoperationandcancontaindatatobeusedintheoperation.
InternalLinkage
Afunctionorvariablehasinternallinkageifitcannotbeaccessedfromoutsidethemoduleinwhichitisdefined.
InternationalOrganizationforStandardization
Anorganizationthatsetsstandardsinmanybusinessesandtechnologies,includingcomputingandcommunications.
Interrupt
AsignaltotheCPUthatsuspendstheexecutionofarunningapplicationandtransferscontroltoanInterruptServiceRoutine(ISR)sothattheeventmaybeprocessed.
InterruptHandler
Aroutinethatprocessesspecialcodewhenaninterruptoccurs.
InterruptRequest
Aneventwhichcausestheprocessortotemporarilysuspend
Page 246
normalinstructionexecutionandtostartexecutinganinterrupthandlerroutine.Someprocessorshaveseveralinterruptrequesteventsallowingdifferentpriorityinterrupts.
InterruptServiceRoutine
Afunctionthatisinvokedwhenaninterruptoccurs.
InterruptServiceRoutine
User-generatedcodethatisenteredwhenaninterruptoccurs.Thelocationofthecodeinprogrammemorywillusuallydependonthetypeofinterruptthathasoccurred.
IRQ
SeeInterruptRequest.
ISO
SeeInternationalOrganizationforStandardization.
ISR
SeeInterruptServiceRoutine.
Latency
Thetimebetweenaneventanditsresponse.
Librarian
SeeArchiver.
Library
SeeArchive.
Linker
Page 247
Alanguagetoolthatcombinesobjectfilesandlibrariestocreateexecutablecode,resolvingreferencesfromonemoduletoanother.
LinkerScriptFiles
Linkerscriptfilesarethecommandfilesofalinker.Theydefinelinkeroptionsanddescribeavailablememoryonthetargetplatform.
ListingDirectives
Listingdirectivesarethosedirectivesthatcontroltheassemblerlistingfileformat.Theyallowthespecificationoftitles,paginationandotherlistingcontrol.
ListingFile
AlistingfileisanASCIItextfilethatshowsthemachinecodegeneratedforeachCsourcestatement,assemblyinstruction,assemblerdirective,ormacroencounteredinasourcefile.
LittleEndianess
Adataorderingschemeformultibytedatawherebytheleastsignificantbyteisstoredattheloweraddresses.
LocalLabel
AlocallabelisonethatisdefinedinsideamacrowiththeLOCALdirective.Theselabelsareparticulartoagiveninstanceofamacro'sinstantiation.Inotherwords,thesymbolsandlabelsthataredeclaredaslocalarenolongeraccessibleaftertheENDMmacroisencountered.
LogicProbes
Upto14logicprobescanbeconnectedtosomeMicrochipemulators.Thelogicprobesprovideexternaltraceinputs,trigger
Page 248
outputsignal,+5V,andacommonground.
MachineCode
Therepresentationofacomputerprogramthatisactuallyreadandinterpretedbytheprocessor.Aprograminbinarymachinecodeconsistsofasequenceofmachineinstructions(possiblyinterspersedwithdata).Thecollectionofallpossibleinstructionsforaparticularprocessorisknownasits"instructionset".
MachineLanguage
Asetofinstructionsforaspecificcentralprocessingunit,designedtobeusablebyaprocessorwithoutbeingtranslated.
Macro
Macroinstruction.Aninstructionthatrepresentsasequenceofinstructionsinabbreviatedform.
MacroDirectives
Directivesthatcontroltheexecutionanddataallocationwithinmacrobodydefinitions.
MakeProject
Acommandthatrebuildsanapplication,re-compilingonlythosesourcefilesthathavechangedsincethelastcompletecompilation.
MCU
MicrocontrollerUnit.Anabbreviationformicrocontroller.AlsouC.
MemoryModels
Versionsoflibrariesand/orprecompiledobjectfilesbasedonadevice'smemory(RAM/ROM)sizeandstructure.
Page 249
MemoryModels
Adescriptionthatspecifiesthesizeofpointersthatpointtoprogrammemory.
Message
Textdisplayedtoalertyoutopotentialproblemsinlanguagetooloperation.Amessagewillnotstopoperation.
Microcontroller
AhighlyintegratedchipthatcontainsaCPU,RAM,programmemory,I/Oports,andtimers.
MicrocontrollerMode
OneofthepossibleprogrammemoryconfigurationsofthePIC17CXXXandPIC18CXXXfamiliesofmicrocontrollers.Inmicrocontrollermode,onlyinternalexecutionisallowed.Thus,onlytheon-chipprogrammemoryisavailableinmicrocontrollermode.
MicroprocessorMode
OneofthepossibleprogrammemoryconfigurationsofthePIC17CXXXandPIC18CXXXfamiliesofmicrocontrollers.Inmicroprocessormode,theon-chipprogrammemoryisnotused.Theentireprogrammemoryismappedexternally.
Mnemonics
Textinstructionsthatcanbetranslateddirectlyintomachinecode.AlsoreferredtoasOpcodes.
MPASMAssembler
MicrochipTechnology'srelocatablemacroassemblerforPICmicromicrocontrollerdevices,KeeLoqdevicesandMicrochipmemory
Page 250
devices.
MPLABASM30
Microchip'srelocatablemacroassemblerfordsPIC30Fdigitialsignalcontrollerdevices.
MPLABC1X
ReferstoboththeMPLABC17andMPLABC18CcompilersfromMicrochip.MPLABC17istheCcompilerforPIC17CXXXdevicesandMPLABC18istheCcompilerforPIC18CXXXandPIC18FXXXXdevices.
MPLABC30
Microchip'sCcompilerfordsPIC30Fdigitialsignalcontrollerdevices.
MPLABICD2
Microchip'sin-circuitdebuggerforPIC16F87X,PIC18FXXXanddsPIC30FXXXXdevices.TheICDworkswithMPLABIDE.ThemaincomponentofeachICDisthemodule.Acompletesystemconsistsofamodule,header,demoboard,cables,andMPLABIDESoftware.
MPLABICE2000
Microchip'sin-circuitemulatorforPICmicroMCU'sthatworkswithMPLABIDE.
MPLABICE4000
Microchip'sin-circuitemulatorfordsPICDSC'sthatworkswithMPLABIDE.
MPLABIDE
Page 251
Microchip'sIntegratedDevelopmentEnvironment.
MPLABLIB30
MPLABLIB30archiver/librarianisanobjectlibrarianforusewithCOFFobjectmodulescreatedusingeitherMPLABASM30orMPLABC30Ccompiler.
MPLABLINK30
MPLABLINK30isanobjectlinkerfortheMicrochipMPLABASM30assemblerandtheMicrochipMPLABC30Ccompiler.
MPLABSIM
Microchip'ssimulatorthatworkswithMPLABIDEinsupportofPICmicroMCUdevices.
MPLABSIM30
Microchip'ssimulatorthatworkswithMPLABIDEinsupportofdsPICDSCdevices.
MPLIBObjectLibrarian
MPLIBlibrarianisanobjectlibrarianforusewithCOFFobjectmodulescreatedusingeitherMPASMassembler(mpasmormpasmwinv2.0)orMPLABC1XCcompilers.
MPLINKObjectLinker
MPLINKlinkerisanobjectlinkerfortheMicrochipMPASMassemblerandtheMicrochipMPLABC17orC18Ccompilers.MPLINKlinkeralsomaybeusedwiththeMicrochipMPLIBlibrarian.MPLINKlinkerisdesignedtobeusedwithMPLABIDE,thoughitdoesnothavetobe.
MRU
Page 252
MostRecentlyUsed.ReferstofilesandwindowsavailabletobeselectedfromMPLABIDEmainpulldownmenus.
NestingDepth
Themaximumleveltowhichmacroscanincludeothermacros.
Node
MPLABIDEprojectcomponent.
NonReal-Time
ReferstotheprocessoratabreakpointorexecutingsinglestepinstructionsorMPLABIDEbeingruninsimulatormode.
Non-VolatileStorage
Astoragedevicewhosecontentsarepreservedwhenitspowerisoff.
NOP
NoOperation.Aninstructionthathasnoeffectwhenexecutedexcepttoadvancetheprogramcounter.
ObjectCode
Themachinecodegeneratedbyanassemblerorcompiler.
ObjectFile
Afilecontainingmachinecodeandpossiblydebuginformation.Itmaybeimmediatelyexecutableoritmayberelocatable,requiringlinkingwithotherobjectfiles,e.g.libraries,toproduceacompleteexecutableprogram.
ObjectFileDirectives
Page 253
Directivesthatareusedonlywhencreatinganobjectfile.
Octal
Thebase8numbersystemthatonlyusesthedigits0-7.Theright-mostdigitcountsones,thenextdigitcountsmultiplesof8,then8^2=64,etc.
Off-ChipMemory
Off-chipmemoryreferstothememoryselectionoptionforthePIC17CXXXorPIC18CXXXdevicewherememorymayresideonthetargetboard,orwhereallprogrammemorymaybesuppliedbytheEmulator.TheMemorytabaccessedfromOptions>DevelopmentModeprovidestheOff-ChipMemoryselectiondialogbox.
Opcodes
OperationalCodes.SeeMnemonics.
Operators
Symbols,liketheplussign`+'andtheminussign`-',thatareusedwhenformingwell-definedexpressions.Eachoperatorhasanassignedprecedencethatisusedtodetermineorderofevaluation.
OTP
OneTimeProgrammable.EPROMdevicesthatarenotinwindowedpackages.SinceEPROMneedsultravioletlighttoeraseitsmemory,onlywindoweddevicesareerasable.
PassCounter
Acounterthatdecrementseachtimeanevent(suchastheexecutionofaninstructionataparticularaddress)occurs.Whenthepasscountvaluereacheszero,theeventissatisfied.Youcan
Page 254
assignthePassCountertobreakandtracelogic,andtoanysequentialeventinthecomplextriggerdialog.
PC
PersonalComputerorProgramCounter.
PCHost
AnyIBM™orcompatiblepersonalcomputerrunningasupportedWindowsoperatingsystem.
PICmicroMCUs
PICmicromicrocontrollers(MCUs)referstoallMicrochipmicrocontrollerfamilies.
PICSTARTPlus
AdevelopmentaldeviceprogrammerfromMicrochip.Programs8-,14-,28-,and40-pinPICmicromicrocontrollers.MustbeusedwithMPLABIDESoftware.
Pod,Emulator
Theexternalemulatorboxthatcontainsemulationmemory,tracememory,eventandcycletimers,andtrace/breakpointlogic.
Power-on-ResetEmulation
AsoftwarerandomizationprocessthatwritesrandomvaluesindataRAMareastosimulateuninitializedvaluesinRAMuponinitialpowerapplication.
Pragma
Adirectivethathasmeaningtoaspecificcompiler.Oftenapragmaisusedtoconveyimplementation-definedinformationtothe
Page 255
compiler.MPLABC30usesattributestoconveythisinformation.
PROMATEII
AdeviceprogrammerfromMicrochip.ProgramsallPICmicromicrocontrollersandmostmemoryandKeeloqdevices.CanbeusedwithMPLABIDEorstand-alone.
ProgramCounter
Thelocationthatcontainstheaddressoftheinstructionthatiscurrentlyexecuting.
ProgramMemory
Thememoryareainadevicewhereinstructionsarestored.Also,thememoryintheemulatororsimulatorcontainingthedownloadedtargetapplicationfirmware.
Project
Asetofsourcefilesandinstructionstobuildtheobjectandexecutablecodeforanapplication.
PrototypeSystem
Atermreferringtoauser'stargetapplication,ortargetboard.
PWMSignals
PulseWidthModulationSignals.CertainPICmicroMCUdeviceshaveaPWMperipheral.
Qualifier
AnaddressoranaddressrangeusedbythePassCounterorasaneventbeforeanotheroperationinacomplextrigger.
Radix
Page 256
Thenumberbase,HEX,ordecimal,usedinspecifyinganaddress.
RAM
RandomAccessMemory(DataMemory).Memoryinwhichinformationcanbeaccessedinanyorder.
RawData
Thebinaryrepresentationofcodeordataassociatedwithasection.
Real-Time
WhenreleasedfromthehaltstateintheemulatororMPLABICDmode,theprocessorrunsinreal-timemodeandbehavesexactlyasthenormalchipwouldbehave.Inreal-timemode,thereal-timetracebufferofMPLABICEisenabledandconstantlycapturesallselectedcycles,andallbreaklogicisenabled.IntheemulatororMPLABICD,theprocessorexecutesinreal-timeuntilavalidbreakpointcausesahalt,oruntiltheuserhaltstheemulator.Inthesimulatorreal-timesimplymeansexecutionofthemicrocontrollerinstructionsasfastastheycanbesimulatedbythehostCPU.
RecursiveCalls
Afunctionthatcallsitself,eitherdirectlyorindirectly.
Recursion
Theconceptthatafunctionormacro,havingbeendefined,cancallitself.Greatcareshouldbetakenwhenwritingrecursivemacros;itiseasytogetcaughtinaninfiniteloopwheretherewillbenoexitfromtherecursion.
Reentrant
Afunctionthatmayhavemultiple,simultaneouslyactiveinstances.
Page 257
Thismayhappenduetoeitherdirectorindirectrecursionorthroughexecutionduringinterruptprocessing.
Relocatable
Anobjectfilewhosesectionshavenotbeenassignedtoafixedlocationinmemory.
ROM
ReadOnlyMemory(ProgramMemory).Memorythatcannotbemodified.
Run
Thecommandthatreleasestheemulatorfromhalt,allowingittoruntheapplicationcodeandchangeorrespondtoI/Oinrealtime.
RuntimeModel
Describestheuseoftargetarchitectureresources.
Section
Anamedsequenceofcodeordata.
SectionAttribute
Acharacteristicascribedtoasection(e.g.,anaccesssection).
SFR
SeeSpecialFunctionRegisters.
Shell
TheMPASMassemblershellisapromptedinputinterfacetothemacroassembler.TherearetwoMPASMassemblershells:onefortheDOSversionandonefortheWindowsversion.
Page 258
Simulator
Asoftwareprogramthatmodelstheoperationofdevices.
SingleStep
Thiscommandstepsthoughcode,oneinstructionatatime.Aftereachinstruction,MPLABIDEupdatesregisterwindows,watchvariables,andstatusdisplayssoyoucananalyzeanddebuginstructionexecution.YoucanalsosinglestepCcompilersourcecode,butinsteadofexecutingsingleinstructions,MPLABIDEwillexecuteallassemblylevelinstructionsgeneratedbythelineofthehighlevelCstatement.
Skew
Theinformationassociatedwiththeexecutionofaninstructionappearsontheprocessorbusatdifferenttimes.Forexample,theexecutedOpcodesappearsonthebusasafetchduringtheexecutionofthepreviousinstruction,thesourcedataaddressandvalueandthedestinationdataaddressappearwhentheOpcodesisactuallyexecuted,andthedestinationdatavalueappearswhenthenextinstructionisexecuted.Thetracebuffercapturestheinformationthatisonthebusatoneinstance.Therefore,onetracebufferentrywillcontainexecutioninformationforthreeinstructions.Thenumberofcapturedcyclesfromonepieceofinformationtoanotherforasingleinstructionexecutionisreferredtoastheskew.
Skid
Whenahardwarebreakpointisusedtohalttheprocessor,oneormoreadditionalinstructionsmaybeexecutedbeforetheprocessorhalts.Thenumberofextrainstructionsexecutedaftertheintendedbreakpointisreferredtoastheskid.
SourceCode
Theforminwhichacomputerprogramiswrittenbythe
Page 259
programmer.Sourcecodeiswritteninsomeformalprogramminglanguagewhichcanbetranslatedintoormachinecodeorexecutedbyaninterpreter.
SourceFile
AnASCIItextfilecontainingsourcecode.
SpecialFunctionRegisters
Theportionofdatamemory(RAM)dedicatedtoregistersthatcontrolI/Oprocessorfunctions,I/Ostatus,timers,orothermodesorperipherals.
Stack,Hardware
LocationsinPICmicromicrocontrollerwherethereturnaddressisstoredwhenafunctioncallismade.
Stack,Software
Memoryusedbyanapplicationforstoringreturnaddresses,functionparameters,andlocalvariables.Thismemoryistypicallymanagedbythecompilerwhendevelopingcodeinahigh-levellanguage.
StaticRAMorSRAM
StaticRandomAccessMemory.ProgrammemoryyoucanRead/Writeonthetargetboardthatdoesnotneedrefreshingfrequently.
StatusBar
TheStatusBarislocatedonthebottomoftheMPLABIDEwindowandindicatessuchcurrentinformationascursorposition,developmentmodeanddevice,andactivetoolbar.
Page 260
StepInto
ThiscommandisthesameasSingleStep.StepInto(asopposedtoStepOver)followsaCALLinstructionintoasubroutine.
StepOver
StepOverallowsyoutodebugcodewithoutsteppingintosubroutines.WhensteppingoveraCALLinstruction,thenextbreakpointwillbesetattheinstructionaftertheCALL.Ifforsomereasonthesubroutinegetsintoanendlessloopordoesnotreturnproperly,thenextbreakpointwillneverbereached.TheStepOvercommandisthesameasSingleStepexceptforitshandlingofCALLinstructions.
Stimulus
Inputtothesimulator,i.e.,datageneratedtoexercisetheresponseofsimulationtoexternalsignals.Oftenthedataisputintotheformofalistofactionsinatextfile.Stimulusmaybeasynchronous,synchronous(pin),clockedandregister.
Stopwatch
Acounterformeasuringexecutioncycles.
StorageClass
Determinesthelifetimeofanobject.
StorageQualifier
Indicatesspecialpropertiesofanobject(e.g.,volitile).
Symbol
Asymbolisageneralpurposemechanismfordescribingthevariouspieceswhichcompriseaprogram.Thesepiecesinclude
Page 261
functionnames,variablenames,sectionnames,filenames,struct/enum/uniontagnames,etc.SymbolsinMPLABIDErefermainlytovariablenames,functionnamesandassemblylabels.Thevalueofasymbolafterlinkingisitsvalueinmemory.
SystemWindowControl
Thesystemwindowcontrolislocatedintheupperleftcornerofwindowsandsomedialogs.Clickingonthiscontrolusuallypopsupamenuthathastheitems"Minimize,""Maximize,"and"Close."
Target
Referstouserhardware.
TargetApplication
Softwareresidingonthetargetboard.
TargetBoard
Thecircuitryandprogrammabledevicethatmakesupthetargetapplication.
TargetProcessor
Themicrocontrollerdeviceonthetargetapplicationboard.
Template
Linesoftextthatyoubuildforinsertingintoyourfilesatalatertime.TheMPLABEditorstorestemplatesintemplatefiles.
ToolBar
AroworcolumnoficonsthatyoucanclickontoexecuteMPLABIDEfunctions.
Trace
Page 262
Anemulatororsimulatorfunctionthatlogsprogramexecution.TheemulatorlogsprogramexecutionintoitstracebufferwhichisuploadedtoMPLABIDE'stracewindow.
TraceMemory
Tracememorycontainedwithintheemulator.Tracememoryissometimescalledthetracebuffer.
TriggerOutput
Triggeroutputreferstoanemulatoroutputsignalthatcanbegeneratedatanyaddressoraddressrange,andisindependentofthetraceandbreakpointsettings.Anynumberoftriggeroutputpointscanbeset.
UninitializedData
Datawhichisdefinedwithoutaninitialvalue.InC,
intmyVar;
definesavariablewhichwillresideinanuninitializeddatasection.
Upload
TheUploadfunctiontransfersdatafromatool,suchasanemulatororprogrammer,tothehostPCorfromthetargetboardtotheemulator.
Vector
Thememorylocationsfromwhichanapplicationstartsexecutionwhenaspecificeventoccurs,suchasaresetorinterrupt.
Warning
Analertthatisprovidedtowarnyouofasituationthatwouldcausephysicaldamagetoadevice,softwarefile,orequipment.
Page 263
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
WatchVariable
Avariablethatyoumaymonitorduringadebuggingsessioninawatchwindow.
WatchWindow
Watchwindowscontainalistofwatchvariablesthatareupdatedateachbreakpoint.
WatchdogTimer
AtimeronaPICmicromicrocontrollerthatresetstheprocessorafteraselectablelengthoftime.TheWDTisenabledordisabledandsetupusingconfigurationbits.
WDT
SeeWatchdogTimer.
Page 264
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ListofControlDirectives
Directive Description Syntax
CONSTANT DeclareSymbolConstant constant<label>[=<expr>,...,<label>[=<expr>]]
#DEFINE DefineaTextSubstitutionLabel
#define<name>[[(<arg>,...,<arg>)]<value>]
END EndProgramBlock end
EQU DefineanAssemblyConstant <label>equ<expr>
#INCLUDE IncludeAdditionalSourceFile
include<<include_file>>include"<include_file>"
ORG SetProgramOrigin <label>org<expr>PROCESSOR SetProcessorType processor<processsor_type>RADIX SpecifyDefaultRadix radix<default_radix>
SET DefineanAssemblerVariable <label>set<expr>
#UNDEFINE DeleteaSubstitutionLabel #undefine<label>
VARIABLE DeclareSymbolVariable variable<label>[=<expr>,...,<label>[=<expr>]]
Page 265
MultipleDirectiveExample1
Directiveshighlightedinthisexampleare:
processor
radix#includeequorgend
ProgramFunctionalDescription
ThisprogramcontinuallyalternatestheoutputonthePortBpinsfrom1'sto0's.Twodelayroutinesusinginterruptsprovidethetimingforthealternatingoutput.IfLEDswereattachedtoPortB,theywouldflash(1=on,0=off).
ThetypeofPICmicroMCUissetusingprocessor,andtheradixissettohexadecimalusingradix.Thestandardheaderfilefortheprocessorselectedisincludedusing#include.Registersareassignedusingtheequdirective.Sectionsofcodeareblockedoutusingtheorgstatement.Finally,theprogramisfinishedwithanend.
CommentedCodeListing
;**************************************;*MPASMAssemblerControlDirectives*;*ExampleProgram1*;*AlternateoutputonPortBbetween*
Page 266
;*1'sand0's*;**************************************processor16f877;Settheprocessorradixhex;Settheradix#include<p16f877.inc>;IncludeheaderfileDTEMPequ0x20;SettempregisterDFLAGequ0x21;SetflagregisterDFL0equ0x00;Setflagbitorg0x00;ResetVectorgotoStartorg0x04;InterruptVectorgotoServIntorg0x06;StartProgramStartclrfPORTB;ClearPortBbsfSTATUS,RP0;SelectBank1clrfTRISB;SetPortBasoutputbcfSTATUS,RP0;SelectBank0bsfINTCON,GIE;EnableGlobalInt'sbsfINTCON,T0IE;EnableTimer0IntLoopmovlw0xFFmovwfPORTB;SetPortBcallDelay1;WaitclrfPORTB;ClearPortBbsfPCLATH,3;SelectPage3bsfPCLATH,4callDelay2;WaitbcfPCLATH,3;SelectPage0bcfPCLATH,4gotoLoop;RepeatServInt;InterruptSericeRoutinebsfSTATUS,RP0;SelectBank1bsfOPTION_REG,T0CS;StopTimer0bcfSTATUS,RP0;SelectBank0bcfINTCON,T0IF;ClearoverflowflagbcfDFLAG,DFL0;Clearflagbit
Page 267
retfie;***************************************;*Delay1Routine-Timer0delayloop*;***************************************Delay1movlw0xF0;SetTimer0valuemovwfTMR0;0x00-longestdelay;0xFF-shortestdelayclrfDFLAGbsfDFLAG,DFL0;SetflagbitbsfSTATUS,RP0;SelectBank1bcfOPTION_REG,T0CS;StartTimer0bcfSTATUS,RP0;SelectBank0TLoopbtfscDFLAG,DFL0;WaitforoverflowgotoTLoop;Timer00xFF->0x00return;******************************************;*Delay2Routine-Decrementdelayloop*;******************************************org0x1900;Page3Delay2movlw0xFF;SetDTEMPvaluemovwfDTEMP;0x00-shortestdelay;0xFF-longestdelayDLoopdecfszDTEMP,FgotoDLoop;EndloopwhenDTEMP=0returnend
AdditionalComments
HeaderFiles
Aheaderfileisincludedintheprogramflowwiththe#include
Page 268
directive.
#include<p16f877.inc>;Includeheaderfile
Anglebracketsareusedtoenclosethenameofthefiletobeincluded,althoughquotesmayalsobeused.Youmayspecifythecompletepathtotheincludedfile,orlettheassemblersearchforit.Formoreonsearchorder,seethediscussionofthe#includedirective().
Aheaderfileisextremelyusefulforspecifyingoften-usedconstants,suchasregisterandpinnames.Thisinformationcanbetypedinonce,andthenthefilecanbeincludedinanycodeusingtheprocessorwiththoseregistersandpins.
RegisterandBitAssignments
Youcanspecifyyourownregistersandbitsbyusingtheequdirective,asisdoneinthefollowinglines.
DTEMPequ0x20;SettempregisterDFLAGequ0x21;SetflagregisterDFL0equ0x00;Setflagbit
DTEMPandDFLAGareassignedtothevalues0x20and0x21respectively.Theywillbeusedindelayloopsintheprogramtostandforthegeneralpurposeregisters(GPRs)0x20and0x21.DFL0isassignedthevalue0x00andwillbeusedasthenameforpin0intheDFLAGregister.
Page 269
FIGURE:PIC16F877REGISTERFILEMAP
Page 270
UsingORG
Theorgdirectiveisusedtospecifytheprogramoriginforspecificsectionsofcode.Ifnoorgisused,codegenerationbeginsataddresszero.ForExample1,orgisusedtospecifycodeat0x00(resetaddress),0x04(interruptaddress),0x06(programstartaddress)and0x1900(Delay2address).
Page 271
FIGURE:PIC16F877PROGRAMMEMORYMAP
Page 272
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Mostoftheprogramiscontainedonpage0.However,thecodefordelayroutineDelay2hasbeenplacedonpage3.Whencallingthisroutine,youmustremembertousethepagingbitsinthePCLATHtoselectpage3,andthenusethemtoswitchbacktopage0onthereturn.
bsfPCLATH,3;SelectPage3bsfPCLATH,4callDelay2;WaitbcfPCLATH,3;SelectPage0bcfPCLATH,4
Page 273
MultipleDirectiveExample2
Directiveshighlightedinthisexampleare:
#define
#undefineequconstantvariableset
ProgramFunctionalDescription
Thisprogramperformsseveralcalculationsusingdefindedconstantsandvariables.Asincontroldirectives-example1,processorisusedtospecifytheprocessortype,radixisusedtospecifytheradixused,and#includeisusedtoincludeaheaderfile.Seeexample1formoreonthesedirectives.
CommentedCodeListing
;**************************************;*MPASMAssemblerControlDirectives*;*ExampleProgram2*;*Performcalculations*;**************************************processor16f877;Settheprocessorradixhex;Settheradix#include<p16f877.inc>;Includeheaderfile#defineTdistance150;Definethesymbol;Tdistance1
Page 274
#defineTdistance225;Definethesymbol;Tdistance2#undefineTdistance2;RemoveTdistance2from;thesymboltabledistance_regequ0x20;Setupdistance_reg;atGPR0x20org0x00;ResetVectorgotoStartorg0x06;StartProgramStartmovlwTdistance1;MovevalueofTdistance1movwfdistance_reg;intodistance_regconstantdistance1=10;Declaredistance1;aconstantsymbolvariabledistance2;Declaredistance2;avariablesymboldistance3set10;Defineavaluefor;thesymboldistance3
Setsymboldistance3to10.
distance2=15;Givedistance2an;initialvaluedistance2=distance1+distance2;Adddistance1;todistance2distance3set15;Changevalueofdistance3distance2=distance2+distance3;Adddistance3;todistance2movlwdistance2;Movevalueofdistance2movwfdistance_reg;intodistance_regend
AdditionalComments
UsingWatchWindows
Oncetheprogrambegins,thevalueofTdistance1isplaced
Page 275
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
intodistance_reg.Thiscanbeobservedinawatchwindow,wherethevalueofdistance_regwillbecome50.ThesymbolTdistance1willnotbefoundinthewatchwindowsymbollist,assymbolsdefinedusingthe#definedirectivearenotavailableforviewinginMPLABIDE.
Thefinallinesoftheexampleprogramwritethefinalvalueofdistance2todistance_reg.Ifyouhadawatchwindowopentoseedistance_regloadedwiththevalueof50,youwillseeitchangeto3A.Rememberthattheradixishexadecimal,sohexadditionwasusedtodeterminethedistance2value.
Lookinginthewatchwindowsymbollist,youwillfindthesymbolsdistance1,distance2anddistance3.However,theywillhavenovalues.ThesesymbolvaluesarenotactuallystoredonthePICmicrodevice,butimplementedonlyintheassembler.
Page 276
ORGPIC16CXXXExample
DirectiveshighlightedinthisexampleforPIC16CXXXdevicesare:
org
ProgramFunctionalDescription
Thisexampleshowstheusageoftheorgdirective.Codegenerationbeginsatanaddressspcifiedbyorg<address>.Theoriginofadatatablealsocanbespecifiedbythisdirective.AdatatablemaybeplacedeitherinaprogrammemoryregionorinanEEdatamemoryregion,asincaseofPICmicrodevicewithEEdataFLASH.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.org0000;Thefollowingcodewillbe;placedinresetaddress0.gotoMain;Jumptoanaddresswhoselabel;is'Main'.org0004;Thefollowingcodewillbe;placedininterruptaddress4.gotoint_routine;Jumptoanaddresswhoselabel;is'int_routine'.org0010;Thefollowingcodesectionwill;placedstartingfromaddress10H.Main;;Writeyourmainprogramhere.;;
Page 277
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
gotoMain;Loopbackto'Main'.org0100;Thefollowingcodesectionwill;beplacedstartingfromaddress;100H.int_routine;;;Writeyourinterruptservice;;routinehere.retfie;Returnfrominterrupt.org1000;Youcancreateadataor;charactertablestartingfrom;anyaddressinprogrammemory.;Inthiscasetheaddressis;1000h.ch_tbl1da"PICwithFLASH";6programmemorylocations;(startingfrom1000h)will;befilledwithsix14-bit;packednumbers,each;representingtwo7-bitASCII;characters.org2100;Theabsolueaddress2100his;mappedtothe0000locationof;EEdatamemoryinPIC16Fxxx.;Youcancreateadataor;charactertablestartingfrom;anyaddressinEEdatamemory.ch_tbl2de"PICwithFLASH";12EEdatamemorylocations;(startingfrom0)willbe;filledwith12ASCII;characters.end
Page 278
ORGPIC18CXXXExample
DirectiveshighlightedinthisexampleforPIC18CXXXdevicesare:
org
ProgramFunctionalDescription
Thisexampleshowstheusageoftheorgdirective.Codegenerationbeginsatanaddressspcifiedbyorg<address>.Theoriginofadatatablealsocanbespecifiedbythisdirective.AdatatablemaybeplacedeitherinaprogrammemoryregionorinanEEdatamemoryregion,asincaseofPICmicrodevicewithEEdataFLASH.
CommentedCodeListing
listp=18c452;Selectthedevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.org0000;Thefollowingcodewillbe;programmedinresetaddress0.gotoMain;Jumptoanaddresswhoselabelis;'Main'.org0008;Thefollowingcodewillbe;programmedinhighpriority;interruptaddress8.gotoint_hi;Jumptoanaddresswhoselabelis;'int_hi'.org0018;Thefollowingcodewillbe;programmedinlowpriority;interruptaddress18h.gotoint_lo;Jumptoanaddresswhoselabelis;'int_lo'.
Page 279
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
org0010;Thefollowingcodesectionwill;beprogrammedstartingfrom;address10H.Main;;Writeyourmainprogramhere.;;gotoMain;Loopbackto'Main'org0100;Thefollowingcodesectionwill;beprogrammedstartingfrom;address100H.int_hi;;;Writeyourhighpriority;;interruptserviceroutinehere.retfie;Returnfrominterrupt.org0200;Thefollowingcodesectionwill;beprogrammedstartingfrom;address200H.int_lo;;;Writeyourlowpriority;;interruptserviceroutinehere.retfie;Returnfrominterrupt.org1000;Youcancreateadataor;charactertablestartingfromany;addressinprogrammemory.In;thiscasetheaddressis1000h.ch_tbl1db"PICwithFLASH"end
Page 280
RADIXExample
Directiveshighlightedinthisexampleare:
listr=
radix
ProgramFunctionalDescription
Thisexampleshowstheusageoftheradixdirectivefordatapresentation.Ifnotdeclared,thenthedefaultradixisinhex(adecimal).
CommentedCodeListing
listp=16f877,r=dec;Selectthedeviceandset;radixasdecimal.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.movlw50H;50isinhexmovlw0x50;Anotherwayofdeclaring50hexmovlw50O;50isinoctalmovlw50;50isnotdeclaredashexor;octalordecimal.Sobydefault;itisindecimalasdefaultradix;isdeclaredasdecimal.radixoct;Use`radix'todeclaredefault;radixasoctal.movlw50H;50isinhex.movlw0x50;Anotherwayofdeclaring50hex.movlw.50;50isindecimal.movlw50;50isnotdeclaredashexor;octalordecimal.Sobydefault
Page 281
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;itisinoctalasdefaultradix;isdeclaredasoctal.radixhex;Nowdefaultradixisinhex.movlw.50;50isdeclaredindecimal.movlw50O;50isdeclaredinoctalmovlw50;50isnotdeclaredashexor;octalordecimal.Sobydefault;itisinhexasdefaultradix;isdeclaredashex.end
Page 282
SET/EQUExample
Directiveshighlightedinthisexampleare:
set
equ
ProgramFunctionalDescription
Thisexampleshowsthetheusageofthesetdirective,usedforcreatingsymbolswhichmaybeusedinMPASMassemblerexpressionsonly.Thesymbolscreatedwiththisdirectivedonotoccupyanyphysicalmemorylocationofmicrocontroller.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.perimeterset0;Thelabel'perimeter'is;assignedvalue0.areaset0;Thelabel'area'isassigned;value0.lngthequ50H;Thelabel'lngth'isassigned;thevalue50H.wdthequ25H;Thelabel'wdth'isassigned;thevalue25H.perimeterset2*(lngth+wdth);Both'perimeter'andareasetlngth*wdth;'area'valuesare;reassigned.end
Page 283
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 284
UNDEFINE/DEFINEExample
Directiveshighlightedinthisexampleare:
#undefine
#define
ProgramFunctionalDescription
Thisexampleshowsthetheusageof#UNDEFINEdirective.Asymbolnamepreviouslydefinedwiththe#DEFINEdirective,isremovedfromthesymboltableif#UNDEFINEdirectiveisused.Thesamesymbolmayberedefinedagain.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.areaset0;Thelabel'area'isassigned;thevalue0.#definelngth50H;Label'lngth'isassigned;thevalue50H.#definewdth25H;Label'wdth'isassigned;thevalue25Hareasetlngth*wdth;Reassignmentoflabel'area'.;So'area'willbereassigneda;valueequalto50H*25H.#undefinelngth;Undefinelabel'lngth'.#undefinewdth;Undefinelabel'wdth'#definelngth0;Definelabel'lngth'to'0'.end
Page 285
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 286
VARIABLE/CONSTANTExample
Directiveshighlightedinthisexampleare:
variable
constant
ProgramFunctionalDescription
Thisexampleshowsthetheusageofthevariabledirective,usedforcreatingsymbolswhichmaybeusedinMPASMassemblerexpressionsonly.Thesymbolscreatedwiththisdirectivedonotoccupyanyphysicalmemorylocationofmicrocontroller.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.variableperimeter=0;Thesymbol'perimeter'is;initializedto0variablearea;Ifasymbolisdeclaredas;variable,theninitialization;isoptional,i.e.itmayormay;notbeinitialized.constantlngth=50H;Thesymbol'lngth'is;initializedto50H.constantwdth=25H;Thesymbol'wdth'is;initializedto25H.;Aconstantsymbolalwaysneeds;tobeinitialized.perimeter=2*(lngth+wdth);ThevalueofaCONSTANTcannot
Page 287
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;bereassignedafterhavingbeen;initializedonce.So'lngth'and;'wdth'cannotbereassigned.But;'perimeter'hasbeendeclared;asvariable,andsocanbe;reassigned.area=lngth*wdthend
Page 288
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ListofConditionalAssemblyDirectives
Directive Description SyntaxELSE BeginAlternativeAssemblyBlocktoIF elseENDIF EndConditionalAssemblyBlock endifENDW EndaWhileLoop endwIF BeginConditionallyAssembledCodeBlock if<expr>IFDEF ExecuteIfSymbolisDefined ifdef<label>IFNDEF ExecuteIfSymbolisNotDefined ifndef<label>WHILE PerformLoopWhileConditionisTrue while<expr>
Page 289
IF/ELSE/ENDIFExample
Directiveshighlightedinthisexampleare:
if
elseendif
ProgramFunctionalDescription
ThisprogramdemonstratestheutilityofIF,ELSEandENDIFassemblydirectives.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.variableconfig;variableusedtodefine;requiredconfigurationof;PORTA&PORTBconfigsetD'1'RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.The;instruction'gotostart'is;placedincodesectionRSTgotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled
Page 290
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;'service_int'.PGMCODE;Thisisthebeginingofthecode;sectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgiven;alongwithdirective'CODE'.startifconfig==H'0';Ifconfig==H'0'istrue,clrw;assemblethemnemonicsuptomovwfTRISA;thedirective'else'.movlwH'ff'movwfTRISBelseclrw;Ifconfig==H'0'isfalse,movwfTRISB;assemblethemnemonicsuptomovlwH'ff';thedirective'endif'.movwfTRISAendifgoto$service_intretfieend
Page 291
IFDEFExample
Directiveshighlightedinthisexampleare:
#define
ifdefelseendif
ProgramFunctionalDescription
Thisprogramusesthecontroldirective#define,alongwiththeifdef,elseandendifdirectivestoseletivelyassemblecodeforusewitheitheranemulatororanacutalpart.Thelistdirectivestitleandlistp=areusedtosetthetitleandprocessoranddisplaythisinformationinthelistfile.Thecontroldirective#includeisusedtoincludethestandardheaderfilefortheselecteddevice.
CommentedCodeListing
title"PICmicrowithFlashEEdatamemoryInterface"listp=12ce518#include<p12ce518.inc>;#defineEMULATED...;EmulationRequires:;MPLAB-ICE;PCM16XA0processormodule;DVA12XP80DeviceAdapter
Page 292
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;DefineEMULATORatthetopofthisfile;(#defineEMULATOR);ThiswillsettheI2C_PORT,SDAandSCLlines;tocommunicateoverPortA,pins0and1.It;alsoassemblesinthenecessaryTRIS;instructionstoallowreadingfromtheSDAline.;;Toconvertthecodefortheactualpart,simplycomment;outthe#defineEMULATORlineandreassemble....#ifdefEMULATEDI2C_PORTEQU5;PortAcontrolregister,;usedforI2CSCLEQU01H;EEPROMClock,SCL(I/Obit7)SDAEQU00H;EEPROMData,SDA(I/Obit6)#elseI2C_PORTEQUGPIO;PortBcontrolregister,;usedforI2CSCLEQU07H;EEPROMClock,SCL(I/Obit7)SDAEQU06H;EEPROMData,SDA(I/Obit6)#endif...START_BITBCFI2C_PORT,SDA;Startbit,SDAandSCL;presetto"1"
Page 293
WHILE/ENDWExample
Directiveshighlightedinthisexampleare:
while
endw
ProgramFunctionalDescription
Thisexampleshowstheusefulnessofdirectivewhiletoperformaloopwhileacertainconditionistrue.Thisdirectiveisusedwiththeendwdirective.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.variablei;Definethesymbol'i'asa;variable.reg_hiequ20;Assignvalue20Htolabel;reg_hi.reg_loequ21;Assignvalue21Htolabel;reg_lo.ORG0000;Thefollowingcodewillbe;programmedinresetaddress0.gotostart;Jumptoanaddresswhoselabel;is'start'.shift_rightmacroby_n;Beginningofamacro,which;shiftsregisterdatantimes.;Codelengthgeneratedafter;assembly,variesdependingupon;thevalueofparameter'by_n'.
Page 294
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
i=0;Initializevariablei.whilei<by_n;Following3linesofassembly;codearerepeatedaslongas;i<by_n.bcfSTATUS,C;Clearcarrybit.rrfreg_hi;reg_hiandreg_locontainsrrfreg_lo;16-bitdatawhichisrotated;rightthroughcarry.i+=1;Incrementloopcounteri.endw;Endwhileloop.Theloopwill;breakhereafteri=by_n.endm;Endof'shift_right'macro.org0010;Mymainprogramstartsat10H.start;Thelabel'start'isequalto;10H.shift_right3;Shiftright3timesthe16-bit;datainreg_hiandreg_lo.This;isanexample.Avalue8will;shiftdata8times.goto$end
Page 295
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ListofDataDirectives
Directive Description Syntax
__BADRAM SpecifyinvalidRAMlocations __badram<expr>
CBLOCK DefineaBlockofConstants cblock[<expr>]
CODE_PACK NoPaddingatEndofOddByte code_pack
__CONFIG Setconfigurationfuses __config<expr>OR__config<addr>,<expr>
DA StoreStringsinProgramMemory
[<label>]da<expr>[,<expr2>,...,<exprn>]
DATA CreateNumericandTextData
data<expr>,[,<expr>,...,<expr>]data"<text_string>"[,"<text_string>",...]
DB DeclareDataofOneByte db<expr>[,<expr>,...,<expr>]DE DeclareEEPROMData de<expr>[,<expr>,...,<expr>]DT DefineTable dt<expr>[,<expr>,...,<expr>]
DW DeclareDataofOneWord dw<expr>[,<expr>,...,<expr>]
ENDC EndanAutomaticConstantBlock endc
FILL SpecifyMemoryFillValue fill<expr>,<count>
__IDLOCS SetIDlocations __idlocs<expr>
__MAXRAM SpecifymaximumRAMaddress __maxram<expr>
RES ReserveMemory res<mem_units>
Page 296
CBLOCK/ENDCExample
Directiveshighlightedinthisexampleare:
cblock
endc
ProgramFunctionalDescription
ThisexampleshowstheusageofCBLOCKandENDCdirectivesfordefiningconstantsorvariablersindatamemoryspace.Thesamedirectivescanbeusedforprogrammemoryspacealso.
Theprogramcalculatestheperimeterofarectangle.Lengthandwidthoftherectanglewillbestoredinbuffersaddressedbylength(22H)andwidth(23H).Thecalculatedperimeterwillbestoredinthedouble-precisionbufferaddressedbyperimeter(i.e.20Hand21H).
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.CBLOCK0x20;Startingaddressofprogramor;datamemoryspace.Herethevalue;is20H,whichisindatamemory;space.perimeter:2;Thelabelperimeteris2-byte;wide.Address20Hand21His;assignedtothelabelperimeter.length;Address22Hisassignedtothe;labellength.
Page 297
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
width;Address23Hisassignedtothe;labelwidth.ENDC;Thisdirectivemustbesupplied;attheendofCBLOCKlistto;terminatethelist.clrfperimeter;Clearthebufferaddressedby;'perimeter'i.e.address20H.clrfperimeter+1;Clearaddress21H.movflength,w;Movethedatapresentinthe;registeraddressedby'length';to'w'addwfwidth,w;Adddatain'w'withdatainthe;registeraddressedby'width'.movwfperimeter;Move'w'totheregister;addressedby20H.incfszperimeter+1;Incrementregister21Hifcarry;isgenerated.bcfSTATUS,C;ClearcarrybitinSTATUS;register.rlfperimeter+1rlfperimeterincfszperimeter+1;Highbyteofperimeterisin;21Handlowbyteisin20H.goto$end
Page 298
CONFIGPIC16CXXXExample
DirectiveshighlightedinthisexampleforPIC16CXXXdevicesare:
__config
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthe__configdirective.Thisdirectiveisusedtoprogramconfigurationbitsintheconfigurationregisterduringdeviceprogramming.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.__config_LP_OSC;Configurationregisteris;programmedtoselectlow;poweroscillator.Referto;datasheetfordetailsof;configurationregister.RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0.';Theinstruction'gotostart';isplacedincodesectionRST.gotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRT;isplacedatH'4'.;Theinstruction'goto;service_int'isplacedincode;sectionINTRT.gotoservice_int;Jumpstothelocation
Page 299
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;labelled'service_int'.PGMCODE;Thisisthebeginingofthe;codesectionnamedPGM.Itis;arelocatablecodesection;sincenoabsoluteaddressis;givenalongwithdirectivestart;'CODE'.goto$service_intretfieend
Page 300
CONFIGPIC18CXXXExample
DirectiveshighlightedinthisexampleforPIC18CXXXdevicesare:
__config
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthe__configdirective.Thisdirectiveisusedtoprogramconfigurationbitsintheconfigurationregisterduringdeviceprogramming.
CommentedCodeListing
listp=18c452;Selectthedevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.;codeprotectdisabled.__CONFIG_CONFIG0,_CP_OFF_0;Oscillatorswitchdisabled,RCoscillatorwithOSC2;asI/Opin.__CONFIG_CONFIG1,_OSCS_OFF_1&_RCIO_OSC_1;Brown-OutResetenabled,BORVoltageis2.5v__CONFIG_CONFIG2,_BOR_ON_2&_BORV_25_2;WatchDogTimerenable,WatchDogTimerPostScaler;count-1:128__CONFIG_CONFIG3,_WDT_ON_3&_WDTPS_128_3;CCP2pinMuxenabled__CONFIG_CONFIG5,_CCP2MX_ON_5;Stackover/underflowResetenabled__CONFIG_CONFIG6,_STVR_ON_6RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.;Theinstruction'gotostart'
Page 301
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;isplacedincodesectionRST.gotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'8';ThecodesectionnamedINTRT;isplacedatH'4'.;Theinstruction'gotoservice_int';isplacedincodesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthecode;sectionnamedPGM.Itisa;relocatablecodesection;sincenoabsoluteaddressis;givenalongwithdirectivestart;'CODE'.goto$service_intretfieend
Page 302
DAExample
Directiveshighlightedinthisexampleare:
da
ProgramFunctionalDescription
Thisexampleshowstheusefulnesofdirectivedainstoringacharacterstringintheprogrammemoryof14-bitarchitecturedevices.Thisdirectivegeneratesapacked14-bitnumberrepresentingtwo7-bitASCIIcharacters.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.ORG0000;Thefollowingcodewillbe;programmedinresetaddress0.gotostart;Jumptoanaddresslabelled;'start'.start;Writeyourmainprogramhereto;displaythestringgivenin;'Ch_stng'.goto$ORG1000;Storethestringstartingfrom;1000H.Ch_stngda"PICmicro"Sngl_chda"A";7-bitASCIIequivalentsof'A';andaNULLcharaterwillbepacked;ina14-bitnumber.da0xff55;Places3f55inprogrammemory.;Nopacking.
Page 303
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
end
AdditionalComments
Determining14-BitNumbers
Forthefollowingstatement:
Ch_stngda"PICmicro"
directivedaproducesfour14-bitnumbers:2849,21ED,34E3and396FrepresentingtheASCIIequivalentofPI,Cm,icandro.
Toseehowthe14-bitnumbersaredetermined,let'slookattheASCIIvaluesofPandI,whichare50h(01010000)and49h(01001001)respectively.Eachispresentedin7-bitas(0)1010000and(0)1001001respectively.Thepacked14-bitnumberis10100001001001,whichisstoredas(00)10100001001001or2849.
Page 304
DATAPIC16CXXXExample
DirectiveshighlightedinthisexampleforPIC16CXXXdevicesare:
data
ProgramFunctionalDescription
Thisexampleshowstheusefulnesofdirectivedatainstoringoneormorewordsinprogrammemory.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.ORG0000;Thefollowingcodewillbe;programmedinresetaddress0.gotostart;Jumptoanaddresslabelled;'start'.start;Writeyourmainprogramhereto;displaythestringgivenin;'Ch_stng'.goto$ORG1000;Storethestringstartingfrom;1000H.Ch_stngdata'M','C','U';3programmemorylocations;willbefilledwithASCII;equivalentof'M','C'and;'U'.tb1_dtadata0xffff,0xaa55;Places3fffhand2a55hin;twoconsecutiveprogram;memorylocations.Asprogram;memoryis14-bitwide,
Page 305
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;thelastnibblecanstore;amaximumvalue3.end
Page 306
DATAPIC18CXXXExample
DirectiveshighlightedinthisexampleforPIC18CXXXdevicesare:
data
ProgramFunctionalDescription
Thisexampleshowstheusefulnesofdirectivedatainstoringoneormorewordsinprogrammemory.
CommentedCodeListing
listp=18c452;Selectdevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.ORG0000;Thefollowingcodewillbe;programmedinresetaddress0.gotostart;Jumptoanaddresslabelled;'start'.start;Writeyourmainprogramhereto;displaythestringgivenin;'Ch_stng'.goto$ORG1000;Storethestringstartingfrom;1000H.InPIC18Cxxxdevices,the;firstcharacterisinleast;significantbyte.Ch_stngdata'M','C','U';3programmemorylocations;willbefilledwithASCII;equivalentof'M','C'and;'U'.Ch_stg1data"MCU";2programmemorylocations;willbefilledwithtwo
Page 307
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;words(16-bitnumbers),;eachrepresentingASCI;equivalentoftwo;characters.Thelast;characterwillbetakenas;NULLincaseoddnumberof;charactersarespecified.tb1_dtadata0xffff,0xaa55;Placesffffandaa55in;twoconsecutive;programmemorylocation.end
Page 308
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DBPIC16CXXXExample
DirectiveshighlightedinthisexampleforPIC16CXXXdevicesare:
db
ProgramFunctionalDescription
Thisexampleshowstheusefulnessofdirectivedbinstoringoneormorebyteorcharacterinprogrammemory.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.ORG0000;Thefollowingcodewillbe;programmedinresetaddress0.gotostart;Jumptoanaddresslabelled;'start'.start;Writeyourmainprogramhere.goto$ORG1000;Storethestringstartingfrom;1000H.Ch_stngdb0,'M',0,'C',0,'U'tb1_dtadb0,0xff;Places00ffinprogrammemory;location.end
Page 309
DBPIC18CXXXExample
DirectiveshighlightedinthisexampleforPIC18CXXXdevicesare:
db
ProgramFunctionalDescription
Thisexampleshowstheusefulnesofdirectivedbinstoringoneormorebyteorcharacterinprogrammemory.
CommentedCodeListing
listp=18c452;Selectdevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.ORG0000;Thefollowingcodewillbe;programmedinresetaddress0.gotostart;Jumptoanaddresslabelled;'start'.start;Writeyourmainprogramhereto;displaythestringgivenin;'Ch_stng'.goto$ORG1000;Storethestringstartingfrom;1000H.InPIC18Cxxxdevices,the;firstcharacterisinleast;significantbyte.Ch_stngdb'M','C','U'tb1_dtadb0,0xff;Placesff00inprogrammemory;location.end
Page 310
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 311
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DEPIC16CXXXExample
DirectiveshighlightedinthisexampleforPIC16CXXXdevicesare:
de
ProgramFunctionalDescription
Thisexampleshowstheusageofthededirective.ThisdirectiveisdesignedmainlyforinitializingdataintheEEdatamemoryregionofPICmicrodeviceswithEEdataFLASH.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.org2100;Theabsolueaddress2100his;mappedtothe0000locationof;EEdatamemory.ch_tbl2de"PICmicro";6EEdatamemorylocations;(startingfrom0)willbefilled;with6ASCIIcharacters.end
Page 312
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
DEPIC18CXXXExample
DirectiveshighlightedinthisexampleforPIC18CXXXdevicesare:
de
ProgramFunctionalDescription
Thisexampleshowstheusageofthededirective.ThisdirectiveisdesignedmainlyforinitializingdataintheEEdatamemoryregionofPICmicrodeviceswithEEdataFLASH.
CommentedCodeListing
listp=18c452;Selectdevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.orgF0;TheabsolueaddressF0his;mappedtothe0000locationof;EEdatamemory.ch_tbl2de"PICmicro";6EEdatamemorylocations;(startingfrom0)willbefilled;with6ASCIIcharacters.end
Page 313
FILLPIC16CXXXExample
DirectiveshighlightedinthisexampleforPIC16CXXXdevicesare:
fill
ProgramFunctionalDescription
Thefilldirectiveisusedtoprogramsuccessiveprogrammemorylocationswithaconstantoranassemblyinstruction.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.org0000;Thefollowingcodewillbe;programmedinresetaddress0.gotostart;Jumptoanaddresslabelled;'start'.FILL0,INTRPT-$;Fillwith0uptoaddress3.INTRPTorg0004gotoISRFILL(gotostart),start-$;Filluptoaddress0Fhwith;instruction<gotostart>.ORG0010start;Writeyourmainprogramhere.FILL(nop),5;Fill5locationswithNOPs.goto$ISR;RETFIEEND
Page 314
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
Page 315
FILLPIC18CXXXExample
DirectiveshighlightedinthisexampleforPIC18CXXXdevicesare:
fill
ProgramFunctionalDescription
Thefilldirectiveisusedtoprogramsuccessiveprogrammemorylocationswithaconstantoranassemblyinstruction.ForPIC18CXXXdevices,onlyanevennumberisallowedtobespecifiedasacountoflocationstobefilled.
CommentedCodeListing
listp=18c452;Selectdevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.org0000;Followingcodewillbeprogrammed;inresetaddress0.gotostart;Jumptoanaddresslabelled;'start'.FILL0,HI_INT-$;Fills0in2programmemory;locations:0004and0006.HI_INTorg0008gotoINTR_HFILL(gotostart),6;Fills6locations(eachlocation;is2byteswide)with3numbers;of2wordwideinstructions;<gotostart>LO_INTorg0018gotoINTR_LFILL10a9,start-$;Fillsaddress1Chand1Ehwith;10a9h
Page 316
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ORG0020start;Writeyourmainprogramhere;FILL(nop),4;Fills2locations(4bytes)with;NOPgoto$INTR_H;RETFIEINTR_L;RETFIEEND
Page 317
IDLOCPIC16CXXXExample
DirectiveshighlightedinthisexampleforPIC16CXXXdevicesare:
__idloc
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthe__idlocsdirective.ThisdirectiveisusedtoprogramdeviceIDbitsintheIDLOCregisterduringdeviceprogramming.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.__idlocsH'1234';SetsdeviceIDto1234.RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.;Theinstruction'gotostart'is;placedincodesectionRSTgotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthecode;sectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgivenalong
Page 318
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
start;withdirective'CODE'.goto$service_intretfieend
Page 319
IDLOCPIC18CXXXExample
DirectiveshighlightedinthisexampleforPIC18CXXXdevicesare:
__idloc
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthe__idlocsdirective.ThisdirectiveisusedtoprogramdeviceIDbitsintheIDLOCregisterduringdeviceprogramming.
CommentedCodeListing
listp=18c452;Selectdevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.__IDLOCS_IDLOC0,H'1';IDLOCregister0willbe;programmedto1.__IDLOCS_IDLOC1,H'2';IDLOCregister1willbe;programmedto2.__IDLOCS_IDLOC2,H'3';IDLOCregister2willbe;programmedto3.__IDLOCS_IDLOC3,H'4';IDLOCregister3willbe;programmedto4.__IDLOCS_IDLOC4,H'5';IDLOCregister4willbe;programmedto5.__IDLOCS_IDLOC5,H'6';IDLOCregister5willbe;programmedto6.__IDLOCS_IDLOC6,H'7';IDLOCregister6willbe;programmedto7.__IDLOCS_IDLOC7,H'8';IDLOCregister7willbe;programmedto8.RSTCODEH'0';ThecodesectionnamedRST
Page 320
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;isplacedatH'0'.Theinstruction;'gotostart'isplacedincode;sectionRST.gotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'8';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthecode;sectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgivenalongstart;withdirective'CODE'.goto$service_intretfieend
Page 321
RESExample
Directiveshighlightedinthisexampleare:
res
ProgramFunctionalDescription
Thisexampleshowstheadvantageofresdirectiveindevelopingrelocatablecode.Theprogramcalculatestheperimeterofarectangle.Lengthandwidthoftherectanglewillbestoredinbuffersaddressedbylengthandwidth.Thecalculatedperimeterwillbestoredinthedouble-precisionbufferaddressedbyperimeter.
CommentedCodeListing
listp=18c452;Selectdevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.UDATA;Thisdirectiveallowsthe;followingdatatobeplacedonly;inthedataarea.perimeterres2;Twolocationsofmemoryare;reservedforthelabel;'perimeter'.Addressesofthe;memorylocationswillbe;allocatedbyMPLINK.lengthres1;Onelocationofmemoryis;reservedforthelabel'length'.;Addressofthememorylocation;willbeallocatedbyMPLINK.widthres1;Onelocationofmemoryis;reservedforthelabel'width'.
Page 322
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;Addressofthememorylocation;willbeallocatedbyMPLINK.StartCODE0000;Followingcodewillbeplacedin;address0.gotoPER_CAL;JumptolabelPER_CALCODE;CODEdirectiveheredictatesthat;thefollowinglinesofcodewill;beplacedinprogrammemory,but;thestartingaddresswillbe;decidedbyMPLINK.PER_CALclrfperimeter;Clearthebuffersaddressedbyclrfperimeter+1;'perimeter'.movflength,w;Movethedatapresentinthe;registeraddressedby'length';to'w'.addwfwidth,w;Adddatain'w'withdatainthe;registeraddressedby'width'movwfperimeter;Move'w'totheregister;addressedby'perimeter'.incfszperimeter+1;Increment'perimeter+1'ifcarry;isgenerated.bcfSTATUS,C;ClearcarrybitinSTATUS;register.rlfperimeter+1rlfperimeterincfszperimeter+1goto$end
Page 323
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ListofListingDirectives
Directive Description SyntaxERROR IssueanErrorMessage error"<text_string>"ERRORLEVEL SetMessgeLevel errorlevel0|1|2|<+-><msg>LIST ListingOptions list[<option>[,...,<option>]]MESSG CreateUserDefinedMessage messg"<message_text>"NOLIST TurnoffListingOutput nolistPAGE InsertListingPageEject pageSPACE InsertBlankListingLines space[<expr>]SUBTITLE SpecifyProgramSubtitle subtitl"<sub_text>"TITLE SpecifyProgramTitle title"<title_text>"
Page 324
ERRORExample
Directiveshighlightedinthisexampleare:
error
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityoftheerrorassemblerdirective,whichsetsanerrormessagetobeprintedinthelistingfileanderrorfile.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.variablebaudrate;variableusedtodefine;requiredbaudratebaudratesetD'5600';Entertherequiredvalueof;baudratehere.if(baudrate!=D'1200')&&(baudrate!=D'2400')&&(baudrate!=D'4800')&&(baudrate!=D'9600')&&(baudrate!=D'19200')error"Selectedbaudrateisnotsupported"endifRSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.The;instruction'gotostart'is;placedincodesectionRSTgotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction
Page 325
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthe;codesectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgiven;alongwithdirective'CODE'.startgoto$service_intretfieend
Page 326
ERRORLEVELExample
Directiveshighlightedinthisexampleare:
errorlevel
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityoftheerrorlevelassemblerdirective,whichsetsthetypeofmessagesthatareprintedinthelistingfileanderrorfile.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.errorlevel0;Display/printmessages,;warningsanderrors.messg"CAUTION:Thisprogramhaserrors"errorlevel1;Display/printwarnings;anderrors.messg"CAUTION:Thisprogramhaserrors"group1udata0x20group1_var1res1;Labelofthisdirectiveisnot;atcolumn1.Thiswillgenerate;awarningno.207.errorlevel-207;Thisdisableswarningwhose;msgnumis207.group1_var2res1;labelofthisdirectiveisalso;notatcolumn1,butnowarning;isdisplayed/printed.errorlevel+207;Thisenableswarningwhose;msgnumis207
Page 327
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
group2udataerrorlevel2;Display/printerrorsgroup2_var1res1;labelofthisdirectiveisnot;atcolumn1.Thiswillgenerate;awarningno.207.errorlevel1;Display/printwarnings;anderrors.group2_var2res1;labelofthisdirectiveisnot;atcolumn1.Thiswillgenerate;awarningno.207.RSTCODEH'0';ThecodesectionnamedRSTis;placedatH'0'.Theinstruction;'gotostart'isplacedincode;sectionRST.gotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRTgotoservice_int;Label'service_int'isnot;defined.Hencethisgenerates;error[113].PGMCODE;Thisisthebeginingofthecode;sectionnamed'PGM'.Itisa;relocatablecodesectionsince;noabsoluteaddressisgivenalong;withdirective'CODE'startmovwfgroup1_var1goto$end
Page 328
MESSGExample
Directiveshighlightedinthisexampleare:
messg
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthemessgassemblerdirective,whichsetsamessagetobeprintedinthelistingfileanderrorfile.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.variablebaudrate;variableusedtodefine;requiredbaudratebaudratesetD'5600';Entertherequiredvalueof;baudratehere.if(baudrate!=D'1200')&&(baudrate!=D'2400')&&(baudrate!=D'4800')&&(baudrate!=D'9600')&&(baudrate!=D'19200')error"Selectedbaudrateisnotsupported"messg"onlybaudrates1200,2400,4800,9600&19200Hz"&&"aresupported"endifRSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.The;instruction'gotostart'is;placedincodesectionRSTgotostart;Jumpstothelocationlabelled;'start'.
Page 329
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthe;codesectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgiven;alongwithdirective'CODE'.startgoto$service_intretfieend
Page 330
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ListofMacroDirectives
Directive Description SyntaxENDM EndaMacroDefinition endmEXITM ExitfromaMacro exitmEXPAND ExpandMacroListing expandLOCAL DeclareLocalMacroVariable local<label>[,<label>]MACRO DeclareMacroDefinition <label>macro[<arg>,...,<arg>]NOEXPAND TurnoffMacroExpansion noexpand
Page 331
EXITMExample
Directiveshighlightedinthisexampleare:
exitm
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityoftheexitmassemblerdirective,whichcausesanimmediateexitfromamacro.Itisusedintheexampletoexitfromthemacrowhencertainconditionsaremet.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.resultequ20;Assignvalue20Htolabel;result.ORG0000;Thefollowingcodewillbeplaced;inresetaddress0.gotostart;Jumptoanaddresswhoselabelis;'start'.addMACROnum1,num2;'add'isamacro.Thevaluesof;'num1'and'num2'mustbepassed;tothismacro.ifnum1>0xff;Ifnum1>255decimal,extim;forceimmediatereturnfrom;macroduringassembly.elseifnum2>0xff;Ifnum2>255decimal,extim;forceimmediatereturnfrom;macroduringassembly.
Page 332
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
elsemovlwnum1;LoadWregisterwithaliteral;valueassignedtothelabel;'num1'.movwfresult;LoadWregistertoanaddress;locationassignedtothelabel;'result'.movlwnum2;LoadWregisterwithaliteral;valueassignedtothelabel;'num2'.addwfresult;AddWregisterwiththememory;locationaddressedby'result';andloadtheresultbackto;'result'.endifendifendm;Endof'add'MACROorg0010;Mymainprogramstartsat10H.start;Thelabel'start'isassignedan;address10H.add.100,.256;Call'add'MACROwithdecimal;numbers100and256assignedto;'num1'and'num2'labels,;respactively.EXTIMdirectivein;macrowillforcereturn.end
Page 333
LOCALExample
Directiveshighlightedinthisexampleare:
local
ProgramFunctionalDescription
Thiscodedemonstratestheutilityoflocaldirective,whichdeclaresthatthespecifieddataelementsaretobeconsideredinlocalcontexttothemacro.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.increqu2;Assemblervariableincrisset;equalto2.add_incrmacro;Declarationofmacro'add_incr'.localincr;Localassemblervariable'incr'.incrset3;Local'incr'issetto3,in;contrastto'incr'value;of2inmaincode.clrw;wregisterissettozeroaddlwincr;wregisterisaddedtoincrand;resultplacedbackendm;inwregister.RSTCODEH'0';ThecodesectionnamedRSTis;placedatH'0'.Theinstruction;'gotostart'isplacedincode;sectionRST.gotostart;Jumpstothelocationlabelled;'start'.
Page 334
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthecode;sectionnamed'PGM'.Itisa;relocatablecodesectionsince;noabsoluteaddressisgivenalong;withdirective'CODE'startclrw;Wregistersettozero.addlwincr;Wregisterisaddedwiththe;valueofincrwhichisnowequal;to2.add_incr;Wregisterisaddedwiththe;valueofincrwhichisnowequal;to3(valuesetlocallyinthe;macroadd_incr).clrw;Wregisterissettozeroagain.addlwincr;incrisaddedtoWregisterand;resultplacedinWregister.;incrvalueisagain2,not;affectedbythevaluesetinthe;macro.goto$service_intretfieend
Page 335
MACRO/ENDMExample
Directiveshighlightedinthisexampleare:
macro
endm
ProgramFunctionalDescription
Thiscodedemonstratestheutilityofmacrodirective,whichisusedtodefineamacro.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.resultequ20;Assignvalue20Htolabel;result.ORG0000;Thefollowingcodewillbeplaced;inresetaddress0.gotostart;Jumptoanaddresswhoselabelis;'start'.addMACROnum1,num2;'add'isamacro.Thevaluesof;'num1'and'num2'mustbepassed;tothismacro.movlwnum1;LoadWregisterwithaliteral;valueassignedtothelabel;'num1'.movwfresult;LoadWregistertoanaddress;locationassignedtothelabel;'result'.movlwnum2;LoadWregisterwithaliteral
Page 336
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;valueassignedtothelabel;'num2'.addwfresult;AddWregisterwiththememory;locationaddressedby'result';andloadtheresultbackto;'result'.endm;endof'add'MACROorg0010;Mainprogramstartsat10H.start;Thelabel'start'isassignedan;address10H.add.100,.90;Call'add'MACROwithdecimal;numbers100and90assignedto;'num1'and'num2'labels,;respactively.100and90willbe;addedandtheresultwillbein;'result'.end
Page 337
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
ListofObjectFileDirectives
Directive Description Syntax
BANKISEL GenerateRAMbankselectingcodeforindirectaddressing bankisel<label>
BANKSEL GenerateRAMbankselectingcode banksel<label>CODE Beginsexecutablecodesection [<name>]code[<address>]
EXTERN Declaresanexternallabel extern<label>[,<label>]
GLOBAL Exportsadefinedlabel extern<label>[.<label>]
IDATA Beginsinitializeddatasection [<name>]idata[<address>]
PAGESEL GenerateROMpageselectingcode pagesel<label>
UDATA Beginsuninitializeddatasection [<name>]udata[<address>]
UDATA_ACS Beginsaccessuninitializeddatasection [<name>]udata_acs[<address>]
UDATA_OVR Beginsoverlayeduninitializeddatasection [<name>]udata_ovr[<address>]
UDATA_SHR Beginsshareduninitializeddatasection [<name>]udata_shr[<address>]
Page 338
BANKISELExample
Directiveshighlightedinthisexampleare:
bankisel
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthebankiseldirective.Thisdirectivegeneratestheappropriatecodetoset/cleartheIRPbitoftheSTATUSregisterforanindirectaccess.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.group1udataH'20';group1datastoredatlocations;startingatH'20'(IRPbit0).group1_var1res1;group1_var1locatedatH'20'.group1_var2res1;group1_var2locatedatH'21'.group2udataH'120';group2datastoredatlocations;startingatH'120'(IRPbit1).group2_var1res1;group2_var1locatedatH'120'.group2_var2res1;group2_var2locatedatH'121'.RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.The;instruction'gotostart'is;placedincodesectionRSTgotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin
Page 339
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginningofthe;codesectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgiven;alongwithdirective'CODE'.startmovlwH'20';ThispartofthecodeaddressesmovwfFSR;variablesgroup1_var1&bankiselgroup1_var1;group1_var2indirectly.clrfINDFincfFSR,FclrfINDFmovwfFSRbankiselgroup2_var1clrfINDFincfFSR,FclrfINDFgoto$service_intretfieend
Page 340
BANKSELExample
Directiveshighlightedinthisexampleare:
banksel
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthebankseldirective.Thisdirectivegeneratestheappropriatecodetoset/cleartheRP0andRP1bitsoftheSTATUSregister.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.group1udataH'20';group1datastoredatlocations;startingatH'20'(bank0).group1_var1res1;group1_var1locatedatH'20'.group1_var2res1;group1_var2locatedatH'21'.group2udataH'A0';group2datastoredatlocations;startingatH'A0'(bank1)group2_var1res1group2_var2res1RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.The;instruction'gotostart'is;placedincodesectionRSTgotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin
Page 341
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginningofthe;codesectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgiven;alongwithdirective'CODE'.startbankselgroup1_var1;Thisdirectivegeneratescode;toset/clearbankselectbits;RP0&RP1ofSTATUSregister;dependingupontheaddressof;group1_var1.clrfgroup1_var1clrfgroup1_var2bankselgroup2_var1;Thisdirectivegeneratescode;toset/clearbankselectbits;RP0&RP1ofSTATUSregister;dependingupontheaddressof;group2_var1.clrfgroup2_var1clrfgroup2_var2goto$service_intretfieend
Page 342
CODEExample
Directiveshighlightedinthisexampleare:
code
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthecodedirective,whichdeclaresthebeginningofasectionofprogramcode.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.The;instruction'gotostart'is;placedincodesectionRSTgotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthe;codesectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgiven;alongwithdirective'CODE'.start
Page 343
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
clrwgoto$CODE;Thisisarelocatablecodenop;sectionsincenoaddressis;;specifiedwiththeCODE;;directive.;;service_intretfieend
Page 344
GLOBAL/EXTERNExample
Directiveshighlightedinthisexampleare:
global
extern
ProgramFunctionalDescription
Theprogrammain.asm,alongwithsub.asm,demonstratetheutilityoftheGLOBALandEXTERNdirectives,whichmakeitpossibletousesymbolsinmodulesotherthanwheretheyaredefined.
CommentedCodeListing
;*******************************************************;main.asm;*******************************************************listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.UDATAdelay_valueres1GLOBALdelay_value;Thevariable'delay_value',;declaredGLOBALinthis;module,isincludedinan;EXTERNdirectiveinthemodule;sub.asm.EXTERNdelay;Thevariable'delay',declared;EXTERNinthismodule,is;declaredGLOBALinthemodule;sub.asm.
Page 345
RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.The;instruction'gotostart'is;placedincodesectionRSTgotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthe;codesectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgiven;alongwithdirective'CODE'.startmovlwD'10'movwfdelay_valuexorlwH'80'calldelaygotostartservice_intretfieend;*******************************************************;sub.asm;*******************************************************listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.GLOBALdelay;Thevariable'delay'declared;GLOBALinthismoduleis;includedinanEXTERNdirective;inthemodulemain.asm.EXTERNdelay_value;Thevariable'delay_value';declaredEXTERNinthismodule
Page 346
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;isdeclaredGLOBALinthe;modulemain.asm.PGMCODEdelaydecfszdelay_value,1gotodelayreturnend
Page 347
IDATAExample
Directiveshighlightedinthisexampleare:
idata
ProgramFunctionalDescription
Thedirectiveidataisusedwhengeneratinganobjectfile.ItreservesRAMlocationsforvariablesanddirectsthelinkertogeneratealookuptablethatmaybeusedtoinitializethevariablesspecifiedinthissection.TheStartingAddressofthelookuptablecanbeobtainedfromtheMap(.map)file.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.group1IDATA0x20;Initializeddataatlocation;20h.group1_var1res1;group1_var1locatedat0x20,;initializedwith0.group1_var2res1;group1_var2locatedat0x21,;initializedwith0.group2IDATA;Declarationofgroup2data.The;addressesforvariablesunder;thisdatasectionareallocated;automaticallybythelinker.group2_var1db1,2,3,4;4bytesinRAMarereserved.group2_var2dwH'1234';1wordinRAMisreserved.RSTCODE0x0;ThecodesectionnamedRSTis;placedatH'0'.;Followinginstruction'goto
Page 348
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;start'isplacedincode;sectionRST.gotostart;Jumpstothelocationlabelled;'start'.PGMCODE;CodesectionnamedPGMis;declared.Itisarelocatable;codesectionsincenoabsolute;addressisspecified.start;;end
Page 349
PAGESELExample
Directiveshighlightedinthisexampleare:
pagesel
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityofthepageseldirective,whichgeneratestheappropriatecodetoset/clearPCLATHbits
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.RSTCODEH'0';ThecodesectionnamedRST;isplacedatH'0'.The;instruction'gotostart'is;placedincodesectionRST.gotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGM0CODEH'500';ThecodesectionnamedPGM0is;placedatH'500'.startPAGESELpage1_pgm;addressbits12&11of;page1_pgmarecopiedtoPCLATH;4&3respectively.
Page 350
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
gotopage1_pgmPGM1CODEH'900';ThecodesectionnamedPGM1is;placedatH'900'.Label;page1_pgmislocatedinthispage1_pgm;codesection.goto$service_intretfieend
Page 351
UDATAExample
Directiveshighlightedinthisexampleare:
udata
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityoftheudatadirective,whichdeclaresthebeginningofasectionofuninitializeddata.Thisdirectiveisusedwhengeneratinganobjectfile.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.group1udata0x20;group1datastoredatlocations;startingat0x20.group1_var1res1;group1_var1locatedat0x20.group1_var2res1;group1_var2locatedat0x21.group2udata;Declarationofgroup2data.The;addressesforvariablesundergroup2_var1res1;thisdatasectionareallocatedgroup2_var2res1;automaticallybythelinker.RSTCODEH'0';ThecodesectionnamedRSTis;placedatH'0'.Theinstruction;'gotostart'isplacedincode;sectionRST.gotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin
Page 352
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginningofthecode;sectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgivenalongstart;withdirective'CODE'.bankselgroup1_var1clrfgroup1_var1clrfgroup1_var2bankselgroup2_var1clrfgroup2_var1clrfgroup2_var2goto$service_intretfieend
Page 353
UDATA_ACSExample
DirectiveshighlightedinthisexampleforPIC18CXXXdevicesare:
udata_acs
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityoftheudata_acsdirective,whichisusedwhengeneratinganobjectfile.Thisdirectivedeclaresthebeginningofasectionofuninitializeddata.
CommentedCodeListing
listp=18c452;Selectdevice.#include<p18c452.inc>;Includestandardheaderfile;fortheselecteddevice.group1udata_acs0x20;group1datastoredataccess;RAMlocationsstartingat0x20.group1_var1res1;group1_var1locatedat0x20.group1_var2res1;group1_var2locatedat0x21.group2udata_acs;Declarationofgroup2data.The;addressesfordataunderthis;sectonareallocated;automaticallybythelinker.group2_var1res1;Alladdressesbewillallocatedgroup2_var2res1;inaccessRAMspaceonly.RSTCODEH'0';ThecodesectionnamedRSTis;placedatH'0'.Theinstruction;'gotostart'isplacedincode;sectionRST.gotostart;Jumpstothelocationlabelled;'start'INTRTCODEH'8';ThecodesectionnamedINTRTis
Page 354
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthecode;sectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgivenalong;withdirective'CODE'.startclrfgroup1_var1,A;group1_var1initializedtozeroclrfgroup1_var2,A;group1_var2initializedtozeroclrfgroup2_var1,A;group2_var1initializedtozeroclrfgroup2_var2,A;group2_var2initializedtozerogoto$service_intretfieend
Page 355
UDATA_OVRExample
Directiveshighlightedinthisexampleare:
udata_ovr
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityoftheudata_ovrdirective,whichisusedwhengeneratinganobjectfile.Thisdirectivedeclaresthebeginningofasectionofoverlayeduninitializeddata.
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.same_varudata_ovrH'20';Declaresanoverlayed;uninitializeddatasection;named'same_var'startingatvar1res1;locationH'20'.same_varudata_ovrH'20';Declaresanoverlayed;uninitializeddatasectionvar2res1;withthesamenameastheone;declaredabove.Thusvariables;var1andvar2areallocated;atthesameaddress.RSTCODEH'0';ThecodesectionnamedRSTis;placedatH'0'.Theinstruction;'gotostart'isplacedincode;sectionRST.gotostart;Jumpstothelocationlabelled;'start'.
Page 356
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplacedin;codesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginingofthecode;sectionnamedPGM.Itisa;relocatablecodesection;sincenoabsoluteaddressisgiven;alongwithdirective'CODE'startbankselvar1;Anyoperationonvar1affectsmovlwH'FF';var2alsosincebothvariablesmovwfvar1;areoverlaid.comfvar2goto$service_intretfieend
Page 357
UDATA_SHRExample
DirectiveshighlightedinthisexampleforPIC16FXXXdevicesare:
udata_shr
ProgramFunctionalDescription
Thisprogramdemonstratestheutilityoftheudata_shrdirective,whichisusedwhengeneratinganobjectfile.Thisdirectivedeclaresthebeginningofasectionofshareduninitializeddata.ThisdirectiveisusedtodeclarevariablesthatareallocatedinRAMthatissharedacrossallRAMbanks(i.e.unbankedRAM.)
CommentedCodeListing
listp=16f877;Selectthedevice.#include<p16f877.inc>;Includestandardheaderfile;fortheselecteddevice.shared_dataudata_shr;Declaresthebeginningofadata;sectionnamed'shareddata',varres1;whichissharedbyallbanks.;'var'isthelocationwhichcan;beaccessedirrespectiveof;bankselbits.bank0_varudata0X20;Declaresbeginningofadatavar0res1;sectionnamed'bank0_var',;whichisinbank0.var0is;allocatedtheaddress0x20.bank1_varudata0xa0;Declaresbeginningofadatavar1res1;sectionnamed'bank1_var',;whichisinbank1.var1is;allocatedtheaddess0xa0bank2_varudata0x120;Declaresbeginningofadata
Page 358
var2res1;sectionnamed'bank2_var',;whichisinbank2.var2is;allocatedtheaddess0x120bank3_varudata0x1a0;Declaresbeginningofadatavar3res1;sectionnamed'bank3_var',;whichisinbank3.var3is;allocatedtheaddess0x1a0RSTCODEH'0';ThecodesectionnamedRSTis;placedatH'0'.Theinstruction;'gotostart'isplacedin;codesectionRST.gotostart;Jumpstothelocationlabelled;'start'.INTRTCODEH'4';ThecodesectionnamedINTRTis;placedatH'4'.Theinstruction;'gotoservice_int'isplaced;incodesectionINTRT.gotoservice_int;Jumpstothelocationlabelled;'service_int'.PGMCODE;Thisisthebeginningofthecode;sectionnamedPGM.Itisa;relocatablecodesectionsince;noabsoluteaddressisgivenalongstart;withdirective'CODE'.bankselvar0;Selectbank0.movlwH'00'movwfvar;varisaccessiblefrombank0.bankselvar1;Selectbank1.movlwH'01'movwfvar;varisaccessiblefrombank1;also.bankselvar2;Selectbank2.movlwH'02'movwfvar;varisaccessiblefrombank2;also.bankselvar3;Selectbank3.movlwH'03'
Page 359
MicrochipTechnologyInc.Microchip'sWebSiteVoice:(480)792-7200Fax:(480)899-9210
Microchip'sE-mailAddress
movwfvar;varisaccessiblefrombank3;also.goto$service_intretfieend