Mplab - CXX Compiler User'S Guide: 2000 Microchip Technology Inc. DS51217B
Mplab - CXX Compiler User'S Guide: 2000 Microchip Technology Inc. DS51217B
Mplab - CXX Compiler User'S Guide: 2000 Microchip Technology Inc. DS51217B
Information contained in this publication regarding device applications and the like is intended by way of suggestion
only. No representation or warranty is given and no liability is assumed by Microchip Technology Incorporated with
respect to the accuracy or use of such information. Use of Microchip’s products as critical components in life support
systems is not authorized except with express written approval by Microchip.
2000 Microchip Technology Incorporated. All rights reserved.
The Microchip logo, name, MPLAB, PIC, PICSTART, PRO MATE, and PICmicro are registered trademarks of Microchip
Technology Incorporated in the U.S.A. and other countries.
Microsoft, the Microsoft Internet Explorer, Windows, and MS-DOS are registered trademarks of Microsoft Corporation
in the United States and/or other countries.
Netscape is a registered trademark of Netscape Corporation in the United States and/or other countries.
Microwire is a registered trademark of National Semiconductor Corporation.
I2C is a trademark of Philips Corporation.
SPI is a registered trademark of Motorola Corporation
All product/company trademarks mentioned herein are the property of their respective companies.
Table of Contents
General Information
Introduction .......................................................................................... 1
Highlights ............................................................................................. 1
About This Guide ................................................................................. 1
Warranty Registration .......................................................................... 4
Recommended Reading ...................................................................... 4
Troubleshooting ................................................................................... 5
The Microchip Internet Web Site ......................................................... 6
Development Systems Customer Notification Service ........................ 7
Customer Support ............................................................................... 9
Appendices
Appendix A. ASCII Character Set
A.1 Introduction ...............................................................................155
A.2 ASCII Character Set .................................................................155
Appendix B. PIC17CXXX Instruction Set
B.1 Introduction ...............................................................................157
B.2 Highlights ..................................................................................157
B.3 Key to PICmicro MCU Family Instruction Sets .........................157
B.4 PIC17CXXX Instruction Set ......................................................158
Appendix C. PIC18CXXX Instruction Set
C.1 Introduction ...............................................................................163
C.2 Highlights ..................................................................................163
C.3 Key to Enhanced 16-Bit Core Instruction Set ...........................163
C.4 PIC18CXXX Instruction Set ......................................................164
Appendix D. MPLAB-C17 Errors
D.1 Introduction ...............................................................................169
D.2 Highlights ..................................................................................169
D.3 Errors ........................................................................................169
D.4 Warnings ..................................................................................173
Appendix E. MPLAB-C18 Errors
E.1 Introduction ...............................................................................175
E.2 Highlights ..................................................................................175
E.3 Errors ........................................................................................175
E.4 Warnings ..................................................................................182
Appendix F. References
F.1 Introduction ...............................................................................185
F.2 Highlights ..................................................................................185
F.3 C Standards Information ...........................................................185
F.4 General C Information ..............................................................185
Glossary ..................................................................................................187
Introduction ...................................................................................... 187
Highlights ......................................................................................... 187
Terms .............................................................................................. 187
Index ........................................................................................................203
Worldwide Sales and Service ................................................................210
Information
General
General Information
Introduction
This first chapter contains general information that will be useful to know
before using MPLAB-C17 or MPLAB-C18.
Highlights
The information you will garner from this chapter:
• About this Guide
• Recommended Reading
• Warranty Registration
• Troubleshooting
• The Microchip Internet Web Site
• Development Systems Customer Notification Service
• Customer Support
Information
General
Conventions Used in this Guide
This manual uses the following documentation conventions:
Table: Documentation Conventions
Description Represents Examples
Code (Courier font):
Plain characters Sample code #define START
Filenames and paths c:\autoexec.bat
Angle brackets: < > Variables <label>, <exp>
Square brackets [ ] Optional arguments MPASMWIN
[main.asm]
Curly brackets and Choice of mutually exclusive errorlevel {0|1}
pipe character: { | } arguments
An OR selection
Lower case charac- Type of data “filename”
ters in quotes
Ellipses... Used to imply (but not show) list
additional text that is not rele- [“list_option...
vant to the example , “list_option”]
0xnnn A hexadecimal number where 0xFFFF, 0x007A
n is a hexadecimal digit
Italic characters A variable argument; it can be char isascii
either a type of data (in lower (char, ch);
case characters) or a specific
example (in uppercase charac-
ters).
Interface (Helvetica font):
Underlined, italic A menu selection from the File > Save
text with right arrow menu bar
Bold characters A window or dialog button to OK, Cancel
click
Characters in angle A key on the keyboard <Tab>, <Ctrl-C>
brackets < >
Documents (Helvetica font):
Italic characters Referenced books MPLAB User’s Guide
Updates
All documentation becomes dated, and this user’s guide is no exception.
Since MPLAB IDE, MPLAB-C17, MPLAB-C18 and other Microchip tools are
constantly evolving to meet customer needs, some MPLAB IDE dialogs and/
or tool descriptions may differ from those in this document. Please refer to our
web site to obtain the latest documentation available.
Warranty Registration
Please complete the enclosed Warranty Registration Card and mail it
promptly. Sending in your Warranty Registration Card entitles you to receive
new product updates. Interim software releases are available at the Microchip
web site.
Recommended Reading
This user’s guide describes how to use MPLAB-C17 and MPLAB-C18. For
more information on included libraries and precompiled object files for the
compilers, the operation of MPLAB IDE and the use of other tools, the
following are recommended reading.
MPLAB-CXX Reference Guide – Libraries and Precompiled Object Files
(DS51224)
Reference guide for MPLAB-CXX libraries and precompiled object files. Lists
all library functions with a detailed description of their use.
README.C17, README.C18
For the latest information on using MPLAB-C17 or MPLAB-C18, read the
README.C17 or README.C18 file (ASCII text) included with the software.
These README files contain update information that may not be included in
this document.
README.XXX
For the latest information on other Microchip tools (MPLAB, MPLINK, etc.),
read the associated README files (ASCII text file) included with the MPLAB
IDE software.
MPLAB IDE User’s Guide (DS51025)
Comprehensive guide that describes installation and features of Microchip’s
MPLAB Integrated Development Environment (IDE), as well as the editor and
simulator functions in the MPLAB IDE environment.
MPASM User’s Guide with MPLINK and MPLIB (DS33014)
This user’s guide describes how to use the Microchip PICmicro MCU
assembler (MPASM), the linker (MPLINK) and the librarian (MPLIB).
Technical Library CD-ROM (DS00161)
This CD-ROM contains comprehensive application notes, data sheets, and
technical briefs for all Microchip products. To obtain this CD-ROM, contact the
nearest Microchip Sales and Service location (see back page).
Information
General
Microchip Web Site
Our web site (http://www.microchip.com) contains a wealth of documentation.
Individual data sheets, application notes, tutorials and user’s guides are all
available for easy download. All documentation is in Adobe Acrobat (pdf)
format.
Microsoft® Windows® Manuals
This manual assumes that users are familiar with the Microsoft Windows
operating system. Many excellent references exist for this software program,
and should be consulted for general operation of Windows.
Troubleshooting
See the README files for information on common problems not addressed in
this user’s guide.
Information
General
Development Systems Customer Notification Service
Microchip provides a customer notification service to help our customers keep
current on Microchip products with the least amount of effort. Once you
subscribe to one of our list servers, you will receive email notification
whenever we change, update, revise or have errata related to that product
family or development tool. See the Microchip WWW page for other Microchip
list servers.
The Development Systems list names are:
• Compilers
• Emulators
• Programmers
• MPLAB IDE
• Otools (Other Tools)
Once you have determined the names of the lists that you are interested in,
you can subscribe by sending a message to:
[email protected]
with the following as the body:
subscribe <listname> yourname
Here is an example:
subscribe mplab John Doe
To UNSUBSCRIBE from these lists, send a message to:
[email protected]
with the following as the body:
unsubscribe <listname> yourname
Here is an example:
unsubscribe mplab John Doe
The following sections provide descriptions of the available Development
Systems lists.
Compilers
The latest information on Microchip C compilers, Linkers and Assemblers.
These include MPLAB-C17, MPLAB-C18, MPLINK, MPASM as well as the
Librarian, MPLIB for MPLINK.
To SUBSCRIBE to this list, send a message to:
[email protected]
with the following as the body:
subscribe compilers yourname
Emulators
The latest information on Microchip In-Circuit Emulators. These include
MPLAB-ICE and PICMASTER.
To SUBSCRIBE to this list, send a message to:
[email protected]
with the following as the body:
subscribe emulators yourname
Programmers
The latest information on Microchip PICmicro MCU device programmers.
These include PRO MATE® II and PICSTART® Plus.
To SUBSCRIBE to this list, send a message to:
[email protected]
with the following as the body:
subscribe programmers yourname
MPLAB IDE
The latest information on Microchip MPLAB IDE, the Windows Integrated
Development Environment for development systems tools. This list is focused
on MPLAB IDE, MPLAB-SIM, MPLAB Project Manager and general editing
and debugging features. For specific information on MPLAB IDE compilers,
linkers and assemblers, subscribe to the COMPILERS list. For specific
information on MPLAB IDE emulators, subscribe to the EMULATORS list. For
specific information on MPLAB IDE device programmers, please subscribe to
the PROGRAMMERS list.
To SUBSCRIBE to this list, send a message to:
[email protected]
with the following as the body:
subscribe mplab yourname
Information
General
Customer Support
Users of Microchip products can receive assistance through several channels:
• Distributor or Representative
• Local Sales Office
• Field Application Engineer (FAE)
• Corporate Applications Engineer (CAE)
• Hot line
Customers should call their distributor, representative, or field application
engineer (FAE) for support. Local sales offices are also available to help
customers. See the back cover for a listing of sales offices and locations.
Corporate applications engineers (CAEs) may be contacted at
(480) 786-7627.
In addition, there is a Systems Information and Upgrade Line. This line
provides system users a listing of the latest versions of all of Microchip's
development systems software products. Plus, this line provides information
on how customers can receive any currently available upgrade kits.
The Hot Line Numbers are:
1-800-755-2345 for U.S. and most of Canada, and
1-480-786-7302 for the rest of the world.
NOTES:
with MPLAB-CXX
Getting Started
Chapter 5. Using MPLAB-CXX with MPLAB IDE....................................37
1.1 Introduction
This chapter will give you a preview of MPLAB-C17 and MPLAB-C18.
Part
1.2 Highlights 1
This chapter covers the following topics:
with MPLAB-CXX
• What MPLAB-CXX Is
Getting Started
• What MPLAB-CXX Does
• ANSI Compatibility
• Tool Compatibility
2.1 Introduction
This chapter discusses how to install MPLAB-C17 or MPLAB-C18 on your
PC.
Part
If you are going to use MPLAB-CXX with MPLAB, install MPLAB IDE first. 1
2.2 Highlights
with MPLAB-CXX
Getting Started
This chapter includes:
• Host Computer System Requirements
• Compiler Versions
• Installation
2.5 Installation
If you are going to use MPLAB-CXX with MPLAB, install MPLAB IDE first.
To install MPLAB-CXX, enter Windows, run the file SETUP.EXE on the
CD-ROM, and follow the prompts. For illustration, the setup for MPLAB-C17
v2.30 is described here.
The first dialog you should see is the Welcome dialog. This dialog displays the
version of MPLAB-C17 it will install and give you the opportunity to close any
open programs before installing. When you are ready to proceed, click Next.
The next dialog is a display of the latest README.C17. Check out any new
features and information here. When you are ready to proceed, click Next.
The Choose Destination Location dialog will appear next. The default
destination directory for installing the files is c:\mcc, where c: is your master
hard drive. If you wish to install in a different directory, click Browse... and find
or make another directory for installation. Click OK to return to the Choose
Destination Location dialog. Then click Next to continue.
The next dialog is Select Components. It is recommended that you install all
components. Not doing so may cause certain MPLAB-C17 items not to
function properly. Once you are more familiar with the compiler, you may go
back and re-install it with fewer components, but for people new to
MPLAB-C17, it is best to have all components installed. Click Next to
proceed.
Part
1
with MPLAB-CXX
Getting Started
Figure 2.2: Select Components
The Select Program Manager dialog should now be visible. Choose the
default group of Microchip MPLAB-C17 or pick another group from the list.
Click Next to continue.
The next dialog is the Start Installation dialog. To complete the installation,
click Next. To quit the installation at this point, click Cancel.
The install program will use or create the directory you chose in the Choose
Destination Location dialog. Then it will install MPLAB-C17 components into
seven subdirectories:
• bin – executable versions
• doc – help files
• examples – source code examples, with example-specific header,
linker and batch files
• h – general header files
• lib – library and pre-compiled object files
• lkr – linker script files
• src – source code for files found in lib directory
3.1 Introduction
This chapter presents an overview of the compiler operation.
Part
3.2 Highlights 1
This chapter includes:
with MPLAB-CXX
• Overview of Compilers
Getting Started
• Compiler Input/Output Files
• Compiler Resource Requirements
MAIN.O
UNITS.LIB
MAIN.O
MORE.C
MPLAB-CXX
MORE.O
UNIT1.C MPLIB
MPLAB-CXX
UNIT1.O
MPLIB UNITS.LIB
UNIT2.C
MPLAB-CXX
UNIT2.O
UNIT3.C MPLIB
MPLAB-CXX
UNIT3.O
Extension Purpose
with MPLAB-CXX
Getting Started
.o Output extension from MPLAB-C17/C18 for object files:
<source_name>.o
4.1 Introduction
This chapter discusses how to use MPLAB-CXX from the command line
(without MPLAB IDE).
Part
1
4.2 Highlights
This chapter includes:
with MPLAB-CXX
Getting Started
• MPLAB-CXX – Command Line Overview
• Using MPLAB-C17 on the Command Line
• Using MPLAB-C18 on the Command Line
• Going Forward
MPLAB-CXX Alone
library &
math.lib device.lkr linker script
files
MPLINK LINKER
In this diagram, MPLAB-CXX is used alone to compile the source file main.c
into the object file (main.o). However, this object file may be used for input
into the linker (MPLINK) with other object files to produce a hex file
(prog.hex) for use with programmers.
An assembly source file (prog.asm) is shown also with its associated
assembler (MPASM), producing the object file prog.o for input into MPLINK.
See the MPASM User’s Guide with MPLINK and MPLIB for more information
on using the assembler.
Part
In addition, precompiled object files (precomp.o) may be included. Types of
precompiled object files that are generally required for the successful build of
1
a hex file are listed below.
with MPLAB-CXX
Getting Started
MPLAB-C17: MPLAB-C18:
• Start up code • Standard C libraries
• Initialization code • Processor-specific libraries
• Interrupt service routines (peripheral and SFR defini-
tions)
• Register definitions
Precompiled object files are often device and/or memory model dependent.
For more information on available precompiled object files, see the
MPLAB-CXX Reference Guide.
Some library files are available with the compiler. Others may be built outside
the project using the librarian tool (MPLIB). See the MPASM User’s Guide
with MPLINK and MPLIB for more information on using the librarian. For more
information on available libraries, see the MPLAB-CXX Reference Guide.
The object files, along with library files and a linker script file (device.lkr)
are used by MPLINK to generate output files. See the MPASM User’s Guide
with MPLINK and MPLIB for more information on linker script files and using
the linker.
The main output file generated by MPLINK is the Hex file (prog.hex). The
other output files are:
• COFF file (.out). Intermediate file used by MPLINK to generate Code
file, Hex file, and Listing file.
• Code file (.cod). Debug file used by MPLAB IDE.
• Listing file (.lst). Original source code, side-by-side with final binary
code.
• Map file (.map). Shows the memory layout after linking. Indicates used
and unused memory regions.
The tools shown here are all Microchip development tools. However, many
third party tools are available. Please refer to the Third Party Guide
(DS00104) for more information.
-Or[+|-] Enabled With this optimization on, the compiler will run
an optimization pass to remove extraneous
bank select and MOVLW instructions.
with MPLAB-CXX
Getting Started
m: medium model (near ram, far rom)
c: compact model (far ram, near rom)
l: large model (far ram, far rom)
with MPLAB-CXX
The linker produces the file ex1.hex, as well as several other files used
Getting Started
for debugging. The hex file is used by device programmers such as
PRO MATE II and PICSTART Plus to program a PICmicro MCU device. For
more information on the other debugging files produced by the linker, see
the MPASM User’ Guide with MPLINK and MPLIB.
Summary:
• Create the source code program, ex1.c.
• Compile ex1.c:
mcc17 ex1.c -p=17c756a
• Link to generate ex1.hex:
mplink ex1.o -l c:\mcc\lib c0s17.o p17c756a.o -k
c:\mcc\lkr p17c756s.lkr -m exl.map -o exl.out
3. Then link the resulting object files with the precompiled object files as fol-
lows (This should be entered on one line):
mplink ex1.o add.o -l c:\mcc\lib c0s17.o p17c756a.o -k
c:\mcc\lkr p17c756s.lkr -m exl.map -o exl.out
This will produce a hex file and other output files described in the previous
section.
Part
4.5.1 Command Line Interface 1
The command line interface of MPLAB-C18 is as follows:
with MPLAB-CXX
mcc18 [options] filename
Getting Started
where:
filename is the name of the file being compiled, and
options is zero or more command line options.
For example, if the file test.c exists in the current directory, it can be
compiled with the following command:
mcc18 -p=18c452 test.c
When no command line parameters are specified, or with ‘-?’ or ‘-h’, a help
screen is displayed describing the command line usage and options.
Options to MPLAB-C18 can be specified with either ‘/’ or ‘-’, though the ‘-’ is
shown in the table.
with MPLAB-CXX
Linker directory: c:\mcc\lkr
Getting Started
The linker directory is where device-specific linker script files may be found.
Executable directory:c:\mcc\bin
The executable directory is where the compiler programs are located. Your
PATH variable should include this directory.
The following is a very simple program that adds two numbers.
1. Create the following program with any text editor and save it as ex1.c
in a directory called, for example, c:\proj0.
#include <p18c452.h>
void main(void);
unsigned char Add(unsigned char a, unsigned char b);
unsigned char x, y, z;
void main()
{
x = 2;
y = 5;
z = Add(x,y);
}
unsigned char Add(unsigned char a, unsigned char b)
{ return a+b; }
The first line of the program includes the header file p18c452.h which
provides definitions for all special function registers on that part. For more
information on header files see Chapter 8.
2. Compile the program by typing the following at a DOS prompt:
mcc18 ex1.c -p=18c452
This tells the compiler to compile the program ex1.c for the PIC18C452.
The compiler generates two files by default. The first file is ex1.o, which
is the object file that the linker will use to generate (among other files) the
executable (.hex) file to program your PICmicro MCU. The second file is
ex1.err, which is the error file containing any error messages and/or
warnings that the compiler generates during compilation. These messages
are also displayed on the screen.
3. The C object file now must be linked with other object files and a linker
script to create the final executable file, ex1.hex.
In general, two library files will be necessary. These files are general C
libraries, clib.lib, and the processor-specific libraries, p18c???.lib,
where ‘???’ is the target processor specific number. See the MPLAB-XX
Reference Guide for more information on these precompiled library files.
For MPLAB-C18, these library files are listed in the included linker scripts,
so there is no need to specifically call them out when linking. However, the
path to these files still needs to be specified (c:\mcc\lib) for the linker.
Here is the linker command to produce the executable (Although shown on
multiple lines here, this should be on one line when executed.):
mplink ex1.o -l c:\mcc\lib -k c:\mcc\lkr 18c452.lkr -m
exl.map -o exl.out
The file ex1.o is linked with the library files found in the c:\mcc\lib
directory specified by the -l directive. Specific linker information (including
the names of library files) is provided by the linker script file, 18c452.lkr,
found in the c:\mcc\lkr directory, specified by the -k directive. A map
file called ex1.map is generated with the
-m directive. The -o directive tells the linker to generate a COFF file called
ex1.out, used to generate other output files.
The linker produces the file ex1.hex, as well as several other files used
for debugging. The hex file is used by device programmers such as
PRO MATE and PICSTART Plus to program a PICmicro MCU device. For
more information on the other debugging files produced by the linker, see
the MPASM User’ Guide with MPLINK and MPLIB.
Summary:
• Create the source code program, ex1.c.
• Compile ex1.c:
mcc18 ex1.c -p=18c452
• Link to generate ex1.hex:
mplink ex1.o -l c:\mcc\lib -k c:\mcc\lkr 18c452.lkr -m
exl.map -o exl.out
with MPLAB-CXX
Getting Started
x = 2;
y = 5;
z = Add(x,y);
}
File 2
/* add.c */
#include <p18c452.h>
unsigned char Add(unsigned char a, unsigned char b)
{ return a+b; }
3. Then link the resulting object files with the start-up code as follows (This
should be entered on one line):
mplink ex1.o add.o -l c:\mcc\lib -k c:\mcc\lkr
18c452.lkr -m exl.map -o exl.out
This will produce a hex file and other output files described in the previous
section.
5.1 Introduction
This chapter discusses how to use MPLAB-CXX with MPLAB IDE.
Part
5.2 Highlights 1
This chapter includes:
with MPLAB-CXX
• MPLAB-CXX - MPLAB Projects Overview
Getting Started
• Using MPLAB-C17 with MPLAB – A Tutorial
• Using MPLAB-C18 with MPLAB – A Tutorial
• Going Forward
MPLAB Project
main.c prog.asm
source
files
ASSEMBLER/
MPLAB-CXX MPASM
COMPILER
library &
math.lib device.lkr linker script
files
MPLINK LINKER
SIMULATOR/
MPLAB-SIM MPLAB-ICE PRO MATE II
EMULATORS/
PICMASTER PICSTART Plus
PROGRAMMERS
Figure 5.1: An MPLAB Project with MPLAB-CXX – Files and Associated Tools
In this MPLAB Project, the source file main.c is associated with the
MPLAB-CXX compiler. MPLAB IDE will use this information to generate an
object file (main.o) for input into the linker (MPLINK).
An assembly source file (prog.asm) is shown also with its associated
assembler (MPASM). MPLAB IDE will use this information to generate the
object file prog.o for input into MPLINK. See the MPASM User’s Guide with
MPLINK and MPLIB for more information on using the assembler.
In addition, precompiled object files (precomp.o) may be included in a Part
project, with no associated tool required. Types of precompiled object files
that are generally required in a project are listed below.
1
MPLAB-C17: MPLAB-C18:
with MPLAB-CXX
Getting Started
• Start up code • Standard C libraries
• Initialization code • Processor-specific libraries
• Interrupt service routines (peripheral and SFR defini-
tions)
• Register definitions
Precompiled object files are often device and/or memory model dependent.
For more information on available precompiled object files, see the MPLAB-
CXX Reference Guide.
Some library files are available with the compiler. Others may be built outside
the project using the librarian tool (MPLIB). See the MPASM User’s Guide
with MPLINK and MPLIB for more information on using the librarian. For more
information on available libraries, see the MPLAB-CXX Reference Guide.
The object files, along with library files and a linker script file (device.lkr)
are used to generate the project output files via the linker (MPLINK). See the
MPASM User’s Guide with MPLINK and MPLIB for more information on linker
script files and using the linker.
The main output file generated by MPLINK is the Hex file (prog.hex), used
by simulators (MPLAB-SIM), emulators (MPLAB-ICE and PICMASTER) and
programmers (PRO MATE II and PICSTART Plus). The other output files are:
• COFF file (.out). Intermediate file used by MPLINK to generate Code
file, Hex file, and Listing file.
• Code file (.cod). Debug file used by MPLAB IDE.
• Listing file (.lst). Original source code, side-by-side with final binary
code.
• Map file (.map). Shows the memory layout after linking. Indicates used
and unused memory regions.
The tools shown here are all Microchip development tools. However, many
third party tools are available to work with MPLAB Projects. Please refer to
the Third Party Guide (DS00104) for more information.
5.4.1 Overview
Figure 5.2 gives a graphical overview of the MPLAB Project using MPLAB-
C17. The source file ex1.c is associated with the compiler (MPLAB-C17) to
produce the object file ex1.o. This file and other precompiled object files are
linked via MPLINK according to directions in the linker script file
(p17c756s.lkr) to produce the main output file, ex1.hex.
ex1.c
source
file
object
ex1.o c0s17.o p17c756a.o
files
linker script
p17c756s.lkr
file
MPLINK LINKER
ex1.hex
main output
file
with MPLAB-CXX
y = 5;
Getting Started
z = Add(x,y);
}
unsigned char Add(unsigned char a, unsigned char b)
{ return a+b; }
After setting the project name, click OK and the Edit Project dialog will be
shown.
Part
1
with MPLAB-CXX
Getting Started
Figure 5.5: Edit Project – ex1.pjt
The Node Properties dialog shows the command line switches for the tool, in
this case MPLINK. When you first open this dialog, the checked boxes
represent the default values for the tool. For this tutorial, these do not need to
be changed. Refer to the MPASM with MPLINK and MPLIB User’s Guide
(DS33014) for more information on these command line switches.
Click OK to set these default values to ex1.hex.
Part
1
with MPLAB-CXX
Getting Started
Figure 5.7: Edit Project – Add Node ex1.c
The Edit Project dialog should now look like Figure 5.9. Click on ex1 [.c] in
the Project Files section of the dialog and then click on Node Properties.
In the Node Properties dialog, verify that the language tool is set to
MPLAB-C17.
The default for Memory Model is Small, for optimization reasons. The default
selection will be used for the example. However, while learning how to use the
compiler, it is generally suggested that the large memory model be used, to
ensure proper page and bank selection.
Part
1
with MPLAB-CXX
Getting Started
Figure 5.10: Node Properties - ex1.o
Node Properties can not be set on precompiled object files, as they are
already compiled.
Although there are no library files used in this tutorial project, a library file
(.lib) may be added by following the same procedure as shown above.
For more information on libraries and precompiled object files, please refer to
the MPLAB-CXX Reference Guide – Libraries and Precompiled Object Files.
Part
1
with MPLAB-CXX
Getting Started
Figure 5.12: Add Node – p17c756s.lkr
Part
1
with MPLAB-CXX
Getting Started
Figure 5.14: Build Results – ex1.hex
5.4.13 Troubleshooting
If the build did not complete successfully, check these items:
1. Select Project > Install Language Tool... and check that MPLAB-C17 ref-
erences the mcc17.exe executable (Figure 5.15). Your executable path
may be different from the figure.
When using MPLAB IDE in the Windows 3.x environment, the
mcc17d.exe executable should be used instead.
The Command-line option should be selected.
2. Select Project > Install Language Tool... and check that MPLINK is point-
ing to the mplink.exe executable (Figure 5.16). Your executable path
may be different from the figure.
The Command-line option should be selected.
3. Check the Node Properties for the Project Files ex1.hex and ex1.c.
They should be mapped to the Language Tools MPLINK and
MPLAB-C17 respectively.
4. Check the names of the files added to the project against the ones listed
in Figure 5.13. If any are different, click on them individually, click Delete
Node, and then follow the procedure in the relevant previous section for
adding the correct node.
5. Check each step of this tutorial to see if you completed it correctly.
6. Compile the project in a DOS window. Cut-and-paste commend-line
information into a DOS window to run. Check the autoexec.bat file to
ensure that PATH includes the executable directory (c:\mcc\bin) and
that MCC_INCLUDE is present and represents the include directory
(c:\mcc\h).
Part
1
with MPLAB-CXX
Getting Started
Figure 5.17: Project Window – ex1.pjt
The project window contains a good deal of useful information about the
project. For more information on its contents, see the MPLAB IDE User’s
Guide.
5.5.1 Overview
Figure 5.2 gives a graphical overview of the MPLAB Project using MPLAB-
C18. The source file ex1.c is associated with the compiler (MPLAB-C18) to
produce the object file ex1.o. This file and other precompiled object files are
linked via MPLINK according to directions in the linker script file
(18c452.lkr) to produce the main output file, ex1.hex.
ex1.c
source
file
object
ex1.o clib.lib p18c452.lib
files
linker script
18c452.lkr
file
MPLINK LINKER
ex1.hex
main output
file
with MPLAB-CXX
y = 5;
Getting Started
z = Add(x,y);
}
unsigned char Add(unsigned char a, unsigned char b)
{ return a+b; }
After setting the project name, click OK and the Edit Project dialog will be
shown.
Part
1
with MPLAB-CXX
Getting Started
Figure 5.21: Edit Project – ex1.pjt
The Node Properties dialog shows the command line switches for the tool, in
this case MPLINK. When you first open this dialog, the checked boxes
represent the default values for the tool. For this tutorial, these do not need to
be changed. Refer to the MPASM with MPLINK and MPLIB User’s Guide
(DS33014) for more information on these command line switches.
Click OK to set these default values to ex1.hex.
Part
1
with MPLAB-CXX
Getting Started
Figure 5.23: Edit Project – Add Node ex1.c
The Edit Project dialog should now look like Figure 5.25. Click on ex1 [.c]
in the Project Files section of the dialog and then click on Node Properties.
In the Node Properties dialog, verify that the language tool is set to
MPLAB-C18.
The default for Memory Model is Small, for optimization reasons. The default
selection will be used for the example. However, while learning how to use the
compiler, it is generally suggested that the large memory model be used to
ensure proper bank selection.
Part
1
with MPLAB-CXX
Getting Started
Figure 5.26: Node Properties – ex1.o
In the Project section of the Edit Project window, enter c:\mcc\lib under
Library Path.
Although there are no library files used in this tutorial project, a library file
(.lib) may be added by following this procedure:
• In the Edit Project window, click Add Node.
• In the Add Node dialog, select the Folder c:\mcc\lib.
• Select the desired library from the “File name” list. Make sure ‘List files
of type:’ specifies ‘Libraries (*.lib)’.
• Click OK.
Library files do not have node properties as they are already compiled.
For more information on libraries and precompiled object files, please refer to
the MPLAB-CXX Reference Guide – Libraries and Precompiled Object Files.
Part
1
with MPLAB-CXX
Getting Started
Figure 5.28: Add Node – p18c452.lkr
Part
1
with MPLAB-CXX
Getting Started
Figure 5.30: Build Results – ex1.hex
5.5.13 Troubleshooting
If the build did not complete successfully, check these items:
1. Select Project > Install Language Tool... and check that MPLAB-C18 ref-
erences the mcc18.exe executable (Figure 5.15). Your executable path
may be different from the figure.
The Command-line option should be selected.
2. Select Project > Install Language Tool… and check that MPLINK is
pointing to the mplink.exe executable (Figure 5.32). Your executable
path may be different from the figure.
The Command-line option should be selected.
3. Check the Node Properties for the Project Files ex1.hex and ex1.c.
They should be mapped to the Language Tools MPLINK and MPLAB-
C18 respectively.
4. Check the names of the files added to the project against the ones listed
in Figure 5.29. If any are different, click on them individually, click Delete
Node, and then follow the procedure in the relevant previous section for
adding the correct node.
5. Check each step of this tutorial to see if you completed it correctly.
6. Compile the project in a DOS window. Cut-and-paste commend-line
information into a DOS window to run. Check the autoexec.bat file to
ensure that PATH includes the executable directory (c:\mcc\bin) and
that MCC_INCLUDE is present and represents the include directory
(c:\mcc\h).
Part
1
with MPLAB-CXX
Getting Started
Figure 5.33: Project Window – ex1.pjt
The project window contains a good deal of useful information about the
project. For more information on its contents, see the MPLAB IDE User’s
Guide.
Part
2
MPLAB-CXX
Using
6.1 Introduction
This chapter compares MPLAB-CXX with C programming. A basic
understanding of C programming is assumed. Programmers who are
unfamiliar with the C language can refer to Appendix F for a list of C
programming references.
For those familiar with C but not experienced with programming
microcontrollers, various points are highlighted and deviations from ANSI C
are described. Also, device data sheets describing the operation of various
PICmicro MCU devices are available from any sales office listed on the last
page of this document, or from our web site (http:\\www.microchip.com).
6.2 Highlights
This chapter covers the following topics:
• MPLAB-CXX vs. C
• Components of a Basic MPLAB-CXX Program
• C Keywords Part
2
6.3 C vs. MPLAB-CXX
Most C programmers have gained their experience programming C on
MPLAB-CXX
computers where there was an operating system to handle such things as
Using
memory management, input/output, interdevice communications, etc.
Microcontrollers, by their very nature, do not have the memory overhead for
an operating system. Therefore, it is left up to the programmer to determine
memory allocation, I/O operation through a peripheral, etc. Libraries and
precompiled object files are available with MPLAB-CXX to aid the
programmer in this endeavor.
An MPLAB-CXX program is a collection of declarations, statements,
comments, and preprocessor directives that typically do the following:
• Declare data structures
• Allocate data space
• Evaluate expressions
• Perform program control operations
• Control PICmicro MCU peripherals
The first line is a preprocessor directive (Section 7.3) that includes the
p17cxx.h includes proper
processor definition file. This file defines processor-specific information such
processor-specific header
file based on the processor
as special function registers.
selected on the command The next line is a declaration of a function that will be used in the main routine
line. (function1). Functions are discussed further in Section 7.7. Placing the
function declaration here is called prototyping. The function itself may then be
defined after the main routine. Another option is to place the entire function
definition in the prototype location.
Finally, the main routine is defined, with the appropriate source code between
the braces. Note that the main routine is itself a function.
6.5 C Keywords
The ANSI C standard defines 32 keywords for use in the C language.
Typically, C compilers add keywords that take advantage of the processor’s
architecture. The following table shows the ANSI C and the MPLAB-CXX
keywords, where MPLAB-CXX keywords are shown in bold.
Table 6.1: ANSI C and MPLAB-CXX Keywords
MPLAB-CXX
else Section 7.9.2 struct Section 7.12.2
Using
enum Section 7.6.4 switch Section 7.9.6
NOTES:
7.1 Introduction
MPLAB-CXX Fundamentals describes the C programming language as used
with PICmicro MCU devices.A basic understanding of C programming is
assumed. Programmers who are unfamiliar with the C language can refer to
Appendix F for a list of C programming references.
For those familiar with C but not experienced with programming
microcontrollers, various points are highlighted and deviations from ANSI C
are described. Also, device data sheets describing the operation of various
PICmicro MCU devices are available from any sales office listed on the last
page of this document, or from our website (http:\\www.microchip.com).
7.2 Highlights
This chapter covers the following topics:
• Preprocessor Directives
• Comments
• Constants Part
2
• Variables
• Functions
• Operators
MPLAB-CXX
• Program Control Statements
Using
• Arrays and Strings
• Pointers
• Structures and Unions
7.3.1 #define
7.3.1.1 Description
The #define directive defines string constants that are substituted into a
source line before the source line is evaluated. These can improve source
code readability and maintainability. Common uses are to define constants
that are used in many places and provide short cuts to more complex
expressions.
7.3.1.2 Syntax
define-directive:
#define identifier pp-token-list new-line
#define identifier lparen parameter-list )
pp-token-list new-line
#define identifier lparen ) pp-token-list new-line
lparen:
(1
parameter-list:
identifier
parameter-list , identifier
7.3.1.3 Example
#define MAX_COUNT 100
#define VERSION "v1.0"
#define PERIMETER( x, y ) 2*x + 2*y
7.3.2 #else
7.3.2.1 Description
Refer to #if, #ifdef, and #ifndef for a description of the #else directive.
7.3.3 #elif
7.3.3.1 Description
Refer to #if, #ifdef, and #ifndef for a description of the #elif directive.
MPLAB-CXX
directive.
Using
7.3.5 #error
7.3.5.1 Description
The #error directive generates a user-defined error message at compile
time. One use of #error is to detect cases where the source code generates
constants that are out of range. No code is generated as a result of using this
directive.
7.3.5.2 Syntax
error-directive:
#error pp-token-list new-line
7.3.5.3 Example
#define MAX_COUNT 100
#define ELEMENT_SIZE 3
#if (MAX_COUNT * ELEMENT_SIZE) > 256
#error "Data size too large."
#endif
7.3.6 #if
7.3.6.1 Description
The #if directive is useful for conditionally compiling code based on the
evaluation of an expression. #if must be terminated by #endif. The #elif
is used to test a new expression. The directive #else is also available to
provide an alternative compilation. The defined() operator acts similarly to
#ifdef when combined with #if.
7.3.6.2 Syntax
if-directive:
#if constant-expression new-line
7.3.6.3 Example
#define MAX_COUNT 100
#define ELEMENT_SIZE 3
#if defined(MAX_COUNT) && defined(ELEMENT_SIZE)
#if (MAX_COUNT * ELEMENT_SIZE) > 256
#error "Data size too large."
#else
#define DATA_SIZE MAX_COUNT * ELEMENT_SIZE
#endif
#endif
7.3.7 #ifdef
7.3.7.1 Description
The #ifdef directive is similar to the #if directive, except that instead of
evaluating an expression, it checks to see if the specified symbol has been
defined. Like the #if directive, #ifdef must be terminated by #endif, and
can optionally be used with #else.
7.3.7.2 Syntax
ifdef-directive:
#ifdef identifier new-line
7.3.7.3 Example
#ifdef DEBUG
Count = MAX_COUNT;
#endif
7.3.8 #ifndef
7.3.8.1 Description
The #ifndef directive is similar to the #ifdef directive, except that it checks
to see if the specified symbol has not been defined. Like the #if directive,
#ifndef must be terminated by #endif, and can optionally be used with
#else.
7.3.8.2 Syntax
ifndef-directive:
#ifndef identifier new-line
7.3.8.3 Example
#ifndef DEBUG
#define Debug(x) Part
#else 2
#define Debug(x) x
#endif
MPLAB-CXX
7.3.9 #include
Using
7.3.9.1 Description
#include inserts the full text from another file at this point in the source
code. The inserted file may contain any number of valid C statements.
7.3.9.2 Syntax
include-directive:
#include " filename " new-line
#include < filename > new-line
#include pp-token-list new-line
When “filename” is used, MPLAB-CXX looks for the file in the current
directory and then in the directories specified by the current include search
path, which refers to the environment variable MCC_INCLUDE and command-
line option ‘-i’.
When <filename> is used, MPLAB-CXX looks for the file in the directories
specified by the current include search path.
7.3.9.3 Example
#include <p17cxx.h>
#include "header.h"
7.3.10 #line
7.3.10.1 Description
The line directive causes the compiler to renumber the source text so that the
following line has the specified line number.
7.3.10.2 Syntax
line-directive:
#line digit-sequence new-line
#line digit-sequence " filename " new-line
#line pp-token-list new-line
7.3.10.3 Example
#line 34 /* This line is line 34 */
#line 55 "main.c" /* This line is line 55 of main.c */
7.3.11.2 Syntax
interrupt-directive:
#pragma interrupt function-name [section-name]
save=symbol-list new-line
symbol-list:
symbol-name
symbol-list , symbol-name
MPLAB-CXX
MPLAB-CXX does not automatically place an interrupt function at the
interrupt vector. An absolute code section may be used to locate the interrupt
Using
function. More commonly, a GOTO instruction is placed at the interrupt vector
for transferring control to the interrupt function proper.
7.3.12.2 Syntax
interrupt-directive:
#pragma interrupt function-name [section-name]
save=symbol-list new-line
#pragma interruptlow function-name [section-name]
save=symbol-list new-line
symbol-list:
symbol-name
symbol-list , symbol-name
7.3.12.3 Example
Declare a low-priority interrupt function myInterrupt not located at the interrupt
vector. Save several additional symbols of context.
void myInterrupt (void);
7.3.13.2 Syntax
list-directive:
#pragma list new-line
#pragma nolist new-line
Sections
The section declaration family of pragmas changes the section into which
Logical sections are used MPLAB-CXX will allocate data of the associated type. Optionally, the section
to specify which of the may be allocated at an absolute address.
defined memory regions A section declaration with no name resets the allocation of data of the
should be used for a associated type to the default section for the current module.
portion of source code. For
more on sections, refer to A data section qualified as shared will be located in a SHAREBANK by the
the MPLINK section of the linker. Similarly, a data section qualified as access will be located in an
MPASM User’s Guide with ACCESSBANK by the linker.
MPLINK and MPLIB.
Specifying a section name which has been previously declared causes
MPLAB-CXX to resume allocating data of the associated type into the
specified section. The section qualifiers must match the previous declaration.
For udata and idata sections in MPLAB-C17, the data section type, SFR or
GPR, and a bank number may be optionally specified instead of an absolute
address. This is functionally equivalent to specifying a varlocate pragma
with the same information for each symbol declared in the section. Like
varlocate, this qualifier provides information to the compiler only and is not
enforced by the linker; therefore, care should be exercised in its use.
For pragma optimization tips, see Section 8.5.7.
7.3.14.2 Syntax
section-directive:
#pragma udata [data-qualifier-list] [section-name
[location]] new-line
#pragma idata [data-qualifier-list] [section-name
[location]] new-line
#pragma romdata [overlay] [section-name] new-line
#pragma code [overlay] [section-name] new-line
data-qualifier:
access1
shared2
overlay
location:
= address
gpr bank-number2
sfr bank-number2
MPLAB-CXX
Resume allocation of romdata into the default section.
Using
#pragma romdata
Declare a new udata section which will be located in access memory
(MPLAB-C18 only).
#pragma udata access myAccessDataSection
Declare a new code section at address 0x8000.
#pragma code myExternalCodeSection=0x8000
1. MPLAB-C18 only
2. MPLAB-C17 only
7.3.15.2 Syntax
variable-locate-directive:
#pragma varlocate bank variable-name new-line
#pragma varlocate [bank-reg] variable-name new-line
7.3.16 #undef
7.3.16.1 Description
The #undef directive undefines a string constant. After a string constant has
been undefined, any reference to it generates an error unless the string
constant is redefined.
7.3.16.2 Syntax
undef-directive:
#undef identifier new-line
7.3.16.3 Example
#define MAX_COUNT 10
.
.
.
#undef MAX_COUNT
#define MAX_COUNT 20
7.4 Comments
7.4.1 Description
Comments are used to document the meaning and operation of the source
code. The compiler ignores all comments. A comment can be placed
anywhere in a program where white space can occur. Comments can be
many lines long and may also be used to temporarily remove a line of code.
ANSI C comments cannot be nested.
7.4.2 Syntax
ANSI C comment:
‘/*’ begins and ‘*/’ terminates a block comment.
C++ comment:
‘//’ comments to the end of the line.
7.4.3 Example
/* This is a block comment.
It can have multiple lines
between the comment delimiters. Part
*/ 2
// This is a C++ style one-line comment.
MPLAB-CXX
Using
7.5 Constants
7.5.1 Description
A constant in C is any literal number, single character, or character string.
7.5.2 Syntax
7.5.2.1 Numeric Constants
By default, literal numbers are evaluated in decimal. Hexadecimal values can
be specified by preceding the number by 0x. Octal values can be specified by
preceding the number by 0 (zero). Binary values can be specified by
preceding the number by 0b.
Escape Hex
Description
Character Value
\b Backspace character 08
\\ Backslash 5C
7.5.3 Example
7.5.3.1 Numeric Constants
Each of the following evaluates to a decimal twelve:
• 12 Decimal
• 0x0C Hexadecimal
• 014 Octal
• 0b1100 Binary
MPLAB-CXX
The following is an example of a string constant:
Using
"Hello World"
7.6 Variables
This section examines how C uses variables to store data.
The topics discussed in this section are:
• Basic Data Types
• Variable Declaration
• Enumeration
• typedef
MPLAB-CXX
rom, ram any Locate object in program/data memory.
* Not supported by MPLAB-C17
Using
** Does not imply program memory
7.6.2.2 Syntax
declaration:
declaration-specifiers declarator-list ;
declarator-list:
declarator
declarator-list , declarator
declaration-specifiers:
declaration-specifier
declaration-specifiers declaration-specifier
declaration-specifier:
type-name
extern
static
ram
rom
const
volatile
near
far
type-name:
basic-type-name
tag-type-name
basic-type-name:
int
short
char
unsigned
long
float
double
tag-type-name:
enumerated-type-name
struct-or-union-type-name
Local variables (declared inside a compound statement) can only be used by
statements within the block where they are declared. The value of a local
variable cannot be accessed by functions or statements outside of the
function. The most important thing to remember about local variables is that
they are created upon entry into the block and destroyed when the block is
exited. Local variables must be declared before executable statements.
Global variables can be used by all of the functions in the program. Global
variables must be declared before any functions that use them. Most
importantly, global variables are not destroyed until the execution of the
program is complete.
7.6.2.3 Example
unsigned char GlobalCount;
void f2(void)
{
unsigned char count;
Part
for(count=0;count<10;count++)
GlobalCount++;
2
}
void f1(void)
{
MPLAB-CXX
unsigned char count;
Using
for(count=0;count<10;count++)
{
unsigned char temp;
f2();
temp = count *2;
}
}
void main(void)
{
GlobalCount = 0;
f1();
}
This program increments GlobalCount to 100. The operation of the program is
not affected adversely by the variable named count located in both functions.
The variable temp is allocated inside the for() loop and deallocated once
the loop exits.
7.6.3.2 Example1
In file1.c:
static unsigned char a;
unsigned char b;
void main(void)
{
a = 1;
b = 2;
a = new_function();
return a;
}
In file2.c:
extern int b;
int new_function(void)
{
int c;
c = b; /* this will not produce an error,
because b is extern by default
in file1.c and declared extern
in file2.c */
return a; /* this will produce an undefined
variable error because ’a’ is
only valid within file1.c */
}
7.6.3.3 Example2
unsigned char hello(void)
{
static unsigned char i = 0;
i++;
return i;
}
void main(void)
{
unsigned char count;
for( count = 0; count < 10; count++ )
{
unsigned char a;
a = hello();
}
}
/* For each call of the function hello, i will be incre-
mented. i is static and will maintain its value between
calls to hello. hello is called 10 times, so i will be
’10’ after the last call. */
7.6.3.4 volatile
A volatile variable has a value that can be changed by something other
than user code. A typical example is an input port or a timer register. These
variables must be declared as ‘volatile' so the compiler makes no
assumptions on their values while performing optimizations.
7.6.3.5 Example3
Part
unsigned char x, y; 2
volatile unsigned char TMR0;
x = 0x55; /* Compiler’s temporary registers
contain 0x55 */
y = x; /* and those values can be written to ’y’ since
MPLAB-CXX
x is unchanged. */
Using
TMR0 = 0x00;
y = TMR0; /* The compiler must read TMR0 and cannot use
the 0x00 in its temporary variables since
TMR0 increments with execution. */
7.6.4 Enumeration
7.6.4.1 Description
An enumeration defines a list of named integer constants. The constants
defined by an enumeration can be used in the place of any integral value.
7.6.4.2 Syntax
enumerated-type-name:
enum identifier new-line
enum identifier { enumeration-list } new-line
enum { enumeration-list } new-line
enumeration-list:
enumerated-value
enumeration-list , enumerated-value
enumerated-value:
identifier
identifier = constant-expression
All enumeration identifiers (such as VALUE_1 in the example) must be unique
across all defined enumerations.
Enumerated values can be specified for each enumerated member.
7.6.4.3 Example1
enum tag_1 { VALUE_1, VALUE_2, VALUE_3 } enum_1;
/* VALUE_1 is equal to 0 *
* VALUE_2 is equal to 1 *
* VALUE_3 is equal to 2 */
char char_1;
enum_1 = 42; /* this will not produce an error */
char_1 = VALUE_3;/* this will assign char_1 value to 2 */
7.6.4.4 Example2
enum tag_2 { VALUE_3, VALUE_4, VALUE_5 } enum_2;
/* this definition will cause an error because VALUE_3
already has a value of 2, and cannot also hold a value of
0 */
enum tag_3 { VALUE_6 =2, VALUE_7, VALUE_8=50, VALUE_9 }
enum_3;
/* VALUE_6 is equal to 2 *
* VALUE_7 is equal to 3 *
* VALUE_8 is equal to 50 *
* VALUE_9 is equal to 51 */
enum color_type {red,green,yellow} color;
The entries in the enumeration list are assigned constant integer values,
starting with zero for the first entry. Each entry is one greater than the
previous one. Therefore, in the above example, red is 0, green is 1, and yellow
is 2.
The default integer values assigned to the enumeration list can be overridden
by specifying a value for a constant. The following example illustrates
specifying a value for a constant.
enum color_type {red,green=9,yellow} color;
This statement assigns 0 to red, 9 to green, and 10 to yellow.
Once an enumeration is defined, the name can be used to create additional
variables at other points in the program. For example, the variable mycolor
can be created with the color_type enumeration by:
enum color_type mycolor;
7.6.5 typedef
7.6.5.1 Description
The typedef statement creates a new name for an existing type. The new
name can then be used to declare variables.
7.6.5.3 Example
MPLAB-CXX
Using
typedef char string;
typedef unsigned int uint;
void main(void)
{
string j[10];
uint i;
for(i=0;i<10;i++)
j[i]=i;
}
When using a typedef statement, remember these two key points:
• A typedef does not deactivate the original name or type.
• Several typedef statements can be used to create many new names
for the same original type.
The typedef typically has two purposes:
• Create portable programs
• Document source code
7.7 Functions
Functions are the basic building blocks of the C language. All executable
statements must reside within a function.
The topics discussed in this section are:
• Function Declarations
• Function Prototyping
• Passing Arguments to Functions
• Returning Values from Functions
7.7.1.2 Syntax
function-definition:
function-declarator compound-statement new-line
function-declarator:
declaration-specifiers identifier ( parameter-list )
parameter-list:
parameter
parameter parameter-list
parameter:
type-specifier
declarator
7.7.1.3 Example
unsigned char AddOne(unsigned char x)
{
return(x + 1);
}
7.7.2.2 Syntax
function-prototype:
function-declarator new-line
7.7.2.3 Example
unsigned char AddOne(unsigned char x);
MPLAB-CXX
tions and for returning values from functions. This makes it possible
Using
to support quite complex functions and allows recursive functions,
but there is some overhead in managing the software stack. When
compiling, the compiler will examine the function and only include
the appropriate level of stack support code.
7.7.3.2 Example
The function below calculates the sum of two values that are passed to the
function when it is called. When sum() is called, the value of each argument
is copied into the corresponding parameter variable.
void sum( unsigned char a, unsigned char b )
{
int c;
c = a+b;
}
void main(void)
{
sum(1,10);
sum(15,6);
sum(100,25);
}
Functions pass arguments by value. Any changes made to the formal
parameter do not affect the original value in the calling routine.
7.7.4.2 Syntax
return-statement:
return expression new-line
return new-line
7.7.4.3 Example
unsigned char sum(unsigned char a, unsigned char b)
{
return(a + b);
}
void main(void)
{
unsigned char c;
c = sum(1, 10);
c = sum(15, 6);
c = sum(100, 25);
}
When a return statement is encountered, the function returns immediately to
the calling routine. Any statements after the return are not executed. The
return value of a function is not required to be assigned to a variable or to be
used in an expression; however, if it is not used, then the value is lost.
7.8 Operators
A C expression is a combination of operators and operands. For the most
part, C expressions follow the rules of algebra.
This section discusses many different types of operators including:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional Operator
• sizeof Operator
• Precedence of Operators
7.8.1.2 Syntax
MPLAB-CXX
arithmetic-expression:
Using
postfix-expression
arithmetic-expression arithmetic-operator
postfix-expression
arithmetic-operator:
+ addition
- subtraction
* multiplication
/ division
% modulus
The +, -, *, and / operators may be used with any basic data type.
The modulus operator, %, can only be used with integer data types.
7.8.1.3 Example
-b /* negative b */
count - 163 /* variable count minus 163 */
7.8.2.2 Syntax
relational-expression:
arithmetic-expression
relational-expression relational-operator
arithmetic-expression
relational-operator:
> greater than
>= greater than or equal to
< less than
<= less than or equal to
== equal to
!= not equal to
7.8.2.3 Example
count > 0
value <= MAX
input != BADVAL
7.8.3.2 Syntax
logical-or-expression:
logical-and-expression
logical-or-expression || logical-and-expression
logical-and-expression:
relational-expression
logical-and-expression || relational-expression
logical-not-expression:
! unary-expression
&& Logical AND
|| Logical OR
! Logical NOT
7.8.3.3 Example
NotFound && (i <= MAX)
!(Value <= LIMIT)
((’a’ <= ch) && (ch <= ’z’)) || ((’A’ <= ch) && (ch <=
’Z’))
7.8.4.2 Syntax
bitwise-expression:
postfix-expression
bitwise-expression bitwise-operator
postfix-expression
bitwise-not-expression:
~ unary-expression Part
bitwise-operator: 2
& bitwise AND
| bitwise OR
^ bitwise XOR
MPLAB-CXX
~ 1’s complement
>> right shift
Using
<< left shift
7.8.4.3 Example
Flags & MASK; /* Zero unwanted bits */
Flags ^ 0x07; /* Flip bits 0, 1, and 2 */
Val << 2; /* Multiply Val by 4 */
7.8.5.2 Syntax
assignment-expression:
unary-expression assignment-op expression
assignment-operator:
=
+=
-=
*=
/=
%=
|=
^=
>>=
<<=
7.8.5.3 Example
a += b + c; /* Same as a = a + b + c; */
a *= b + c; /* Same as a = a * (b + c); */
a *= (b + c); /* Same as a = a * (b + c); */
r /= s; /* Same as r = r / s; */
m *= 5; /* Same as m = m * 5; */
Flags |= SETBITS; /* Set bits in Flags */
Div2 >>= 1; /* Divide Div2 by 2 */
7.8.6.2 Syntax
pre-increment-expression:
++ unary-expression
pre-decrement-expression:
-- unary-expression
post-increment-expression:
postfix-expression ++
post-decrement-expression:
postfix-expression --
7.8.6.3 Example
void main(void)
{
unsigned char a = 0, b, c;
a++; /* same as ++a; */
/* a = 1 */
b = 5 + a++; /* b = 6, a = 2 */
c = 6 + --a; /* c = 7, a = 1 */
}
7.8.7.2 Syntax
conditional-expression:
logical-OR-expression ? comma-expression :
conditional-expression
Part
7.8.7.3 Example 2
MPLAB-CXX
Using
7.8.8.2 Syntax
sizeof-expression:
sizeof (type)
sizeof a
7.8.8.3 Example
sizeof (int); /* number of bytes to store an integer
value = 2 */
sizeof (v); /* number of bytes to store variable v
v is int, value = 2 */
sizeof (x); /* number of bytes to store all variables
of array x
x is int, 10 elements, value = 20 */
Precedence Operator
Highest () [] -> .
|
! ~ ++ -- - (type cast) * & sizeof
|
| * / %
|
+ -
|
| << >>
|
< <= > >=
|
| == !=
|
&
|
| ^ Part
|
|
2
|
| &&
|
||
MPLAB-CXX
|
| ?
Using
|
= += -= *= /=
↓
Lowest ,
7.8.9.2 Example
7.9.1 if Statement
7.9.1.1 Description
The if statement is a conditional statement. The statement associated with
the if statement is executed based upon the outcome of a condition. If the
condition evaluates to nonzero, the statement is executed. Otherwise, it is
skipped.
7.9.1.2 Syntax
if-statement:
if ( expression ) statement new-line
7.9.1.3 Example
if(num > 0) Adjust(num);
if(count<0)
{
count=0;
EndFound = TRUE;
}
7.9.2.2 Syntax
if-else-statement:
if ( expression ) statement else statement new-line
7.9.2.3 Example
if(num < 0)
{
num = 0;
Valid = 0;
}
else
Valid = 1;
if(num == 1)
DoCase1(); Part
else if(num == 2) 2
DoCase2();
else if(num == 3)
DoCase3();
MPLAB-CXX
else
DoInvalid();
Using
7.9.3 for Statement
7.9.3.1 Description
One of the three loop statements that C provides is the for loop. The other
two are the if and the do-while statements.
Use a for loop to repeat a statement or set of statements. In general, the first
expression is the initialization expression, the second is the loop condition,
and the third is the loop expression.
7.9.3.2 Syntax
for-statement:
for ( expression ; expression ; expression ) statement
new-line
7.9.3.3 Example
unsigned char i;
for(i=0;i<10;i++)
DoFunc();
for(num=100;num>0;num=num-1)
{ . . . }
for(count=0;count<50;count+=5)
{ . . . }
/* Find Target */
for(i=0; (i<MAX) && (Array[i]<>Target); i++);
7.9.4.2 Syntax
while-statement:
while ( expression ) statement new-line
7.9.4.3 Example
X = GetValue()
while (1); /* Loop Forever */
{
HandleValue(X);
X = GetValue();
}
7.9.5.2 Syntax
if-statement:
do statement while ( expression ) new-line
7.9.5.3 Example
do
{
x = GetValue();
HandleValue(x);
} while (x != 0);
7.9.6.2 Syntax
Part
switch-statement:
2
switch ( expression ) statement new-line
case-statement:
case constant-expression : statement new-line
default-statement:
MPLAB-CXX
default : statement new-line
Using
The switch expression is successively tested against a list of constants.
The use of the default
When a match is found, execution continues at the labeled case statement. If
label is good programming
no match is found, the statements associated with the default case are
practice. It can catch out-
of-range data that is not executed if a default label exists.
expected.
7.9.6.3 Example
switch(i)
{
case 1:
DoCase1();
break;
case 2:
DoCase2();
break;
case 3:
DoCase3();
break;
case 4:
DoCase4();
break;
default:
DoDefault();
break;
}
x = 0;
switch(ch)
{
case ’c’: /* Ignoring case, set x to: */
case ’C’: x++; /* 1 if ch is A */
case ’b’: /* 2 if ch is B */
case ’B’: x++; /* 3 if ch is C */
case ’a’: /* otherwise, ch is invalid */
case ’A’: x++
break;
default :
BadChar(ch);
break;
}
7.9.7.2 Syntax
break-statement:
break new-line
7.9.7.3 Example
/* Get 100 values. Stop immediately if the value is 0. */
unsigned char i;
for(i = 0; i < 100; i++)
{
x = GetValue();
if(x == 0)
break;
HandleValue(x);
}
7.9.8.2 Syntax
continue-statement:
continue new-line
7.9.8.3 Example
/* Get 100 values. If the value is 0,
ignore it and go on. */
unsigned char i;
for (i = 0; i < 100; i++)
{
x = GetValue;
if (x == 0)
continue;
HandleValue(x);
} Part
2
7.9.9 goto Statement
7.9.9.1 Description
MPLAB-CXX
Using
Execution of a goto causes control to be sent directly to the labeled
statement. This statement must be located in the same function as the goto.
Use of goto’s interrupts the normal sequential flow of a program and thus
makes it harder to follow and decipher. For this reason, the use of goto’s is
not considered good programming style, i.e., it is recommended that you do
not use them in your program.
7.9.9.2 Syntax
goto-statement:
goto label new-line
7.9.9.3 Example
/* Branch on error */
goto fatal_error;
:
fatal_error: error_fn ( “fatal error” );
:
Instead of jumping to the error function, call the function where the error
occurred to avoid using a goto.
7.10.1 Arrays
7.10.1.1 Description
An array is a list of elements which are all of the same type and can be
referenced through the same name. When an array is declared, C defines the
first element to be at an index of 0; therefore, if the array has 50 elements, the
last element is at an index of 49.
C stores arrays in contiguous memory locations. The first element is at the
lowest address.
7.10.1.2 Syntax
declarator:
declarator array-declarator
array-declarator:
[ constant-expression ]
array-declarator [ constant-expression ]
7.10.1.3 Example
#define SIZE 10
unsigned char i, num[SIZE];
for(i = 0; i < SIZE; i++)
num[i] = i;
To copy the contents of one array into another, copy each individual element
from the first array into the second array. The following example shows one
method of copying the array a[ ] into b[ ] assuming that each array has 10
elements.
for(i=0;i<10;i++)
b[i] = a[i];
7.10.2 Strings
7.10.2.1 Description
A common one-dimensional array is the string. C does not have a built-in
string data type. Instead, a string is defined as a null (0) terminated character
array. The size of the character array must include the terminating null. All
string constants are automatically null terminated.
7.10.2.2 Example
char String[80];
int i;
.
.
.
for(i = 0; (i < 80) && String[i]; i++)
HandleChar(String[i]);
7.10.3.2 Syntax
MPLAB-CXX
Using
initialized-declarator:
declarator = { value-list }
value-list:
{ value-list }
constant-expression-list
constant-expression-list:
constant-expression
constant-expression-list , constant-expression
7.10.3.3 Example1
The following example shows a 5 element integer array initialization.
int i[5] = {1,2,3,4,5};
The element i[0] has a value of 1 and the element i[4] has a value of 5.
A string (character array) can be initialized in two ways. One method is to
make a list of each individual character:
char str[4]={’a’,’b’,’c’, 0};
7.10.3.4 Example2
Because the PICmicro MCU family of microcontrollers uses separate program
memory and data memory address busses in their design, MPLAB-CXX
requires ANSI extensions to distinguish between data located in ROM and
data located in RAM. The ANSI/ISO C standard allows for code and data to
be in separate address spaces, but this is not sufficient to locate data in the
code space as well. To this purpose, MPLAB-CXX introduces the rom and
ram qualifiers. Syntactically, these qualifiers bind to identifiers just as the
const and volatile qualifiers do in strict ANSI C.
The primary use of ROM data is for static strings. In keeping with this,
MPLAB-CXX automatically places all string literals in ROM. This type of a
string literal is “array of char located in ROM.”
For example, when using MPLAB-C18, a string table in ROM can be declared
as:
rom const char table[][20] = { "string 1",
"string 2", "string 3", "string 4" };
rom const char *rom table2[] = { "string 1",
"string 2", "string 3", "string 4" };
Note: At this time, for MPLAB-C17, you should use manual pointer arith-
matic. See the file README.C17 for more information.
The declaration of table declares an array of four strings that are each 20
characters long, and so takes 40 words of program memory. table2 is
declared as an array of pointers to ROM. The rom qualifier after the * places
the array of pointers in ROM as well. All of the strings in table2 are 9 bytes
long, and the array is four elements long, so table2 takes (9*4+4*2)/2 = 22
words of program memory. Accesses to table2 may be less efficient than
accesses to table, however, because of the additional level of indirection
required by the pointer.
An important consequence of the separate ROM and RAM address spaces
for MPLAB-CXX is that pointers to data in ROM and pointers to data in RAM
are not compatible. That is, two pointer types are not compatible unless they
point to objects of compatible types and the objects they point to are located
in the same address space. For example, a pointer to a string in ROM and a
pointer to a string in RAM are not compatible because they refer to different
address spaces. To copy data from ROM to RAM, an explicit copy is required.
For simple types, this entails only a simple assignment, but for arrays and
other complex data-types it may require more.
For example, a function to copy a string from ROM to RAM could be written as
follows.
void str2ram(static char *dest, static char rom *src)
{
while( (*dest++ = *src++) != ’\0’ )
;
} /* end str2ram */
As an example, the following code will send a ROM string to USART1 on a
PICXXC756 using the PICmicro MCU C libraries. The library function to send
a string to the USART, putsUSART1(const char *str), takes a pointer to
a string as its argument, but that string must be in RAM.
Method 1: Copy the ROM string to a RAM buffer before sending
rom char mystring[] = "Send me to the USART";
void foo( void )
{
char strbuffer[21];
str2ram( strbuffer, mystring );
putsUSART1( strbuffer );
}
Method 2: Modify the library routine to read from a ROM string.
/* The only changes required to the library routine is to
change the name so the new routine does not conflict with Part
the original routine and to add the rom qualifier to the 2
parameter.
*/
void putrsUSART1_rom( static const rom char *data )
MPLAB-CXX
{
do /* Send characters up to the null */
Using
{ /* Write a byte to the UASRT */
while(BusyUSART1());
putcUSART1(*data);
} while(*data++);
} /* end putrsUSART1_rom */
7.11 Pointers
This section covers one of the most important and powerful features of C,
pointers. A pointer is a variable that contains the location of an object.
The topics covered in this section are:
• Introduction to Pointers
• Pointers and Arrays
• Pointer Arithmetic
• Passing Pointers to Functions
7.11.1.2 Syntax
declarator:
* type-qualifier-list declarator
The two special operators that are associated with pointers are the asterisk (*)
and the ampersand (&). The address of a variable can be accessed by
preceding the variable with the & operator. The * operator returns the value
stored at the address pointed to by the variable.
7.11.1.3 Example
void main(void)
{
unsigned char *Var1, Var2, Var3;
Var2 = 6;
Var1 = &Var2;
Var3 = Var2; /* These two do */
Var3 = *Var1; /* the same thing. */
}
The first statement declares three variables: Var1, which is an integer pointer,
and Var2 and Var3, which are integers. The next statement assigns the value
of 6 to Var2. Then the address of Var2 (&Var2) is assigned to the pointer
variable Var1. Finally, the value of Var2 is assigned to Var3 in two ways: first
by accessing Var2 directly, then by accessing Var2 through the pointer Var1.
MPLAB-CXX
.
Using
p = r + 20; /* p points to element 20 of r */
q = p - 5 /* q points to element 15 of r */
p++; /* p points to element 21 of r */
It is possible to increment or decrement either the pointer itself or the object to
which it points. Pointers may also be used in relational operations.
7.11.3.2 Example
void incby10(unsigned char *n)
{
*n += 10;
}
void main(void)
{
unsigned char *p;
unsigned char i = 0;
p=&i;
incby10(p); /* i equals 10 */
incby10(&i); /* i equals 20 */
}
7.12.1 Syntax
struct-or-union-type-name:
struct-or-union identifier
struct-or-union identifier
{ member-declaration-list }
struct-or-union { member-declaration-list }
member-declaration-list:
member-declaration
member-declaration-list member-declaration
member-declaration:
member-declaration-specifiers declarator-list ;
member-declaration-specifiers:
member-declaration-specifier
member-declaration-specifiers member-declaration-
specifier
member-declaration-specifier:
type-name
const
volatile
near
far
7.12.2.2 Example
The following example is for a card catalog in a library.
struct catalog_tag
{
char author[40];
char title[40];
char pub[40];
unsigned int date; Part
unsigned char rev; 2
} card;
In this example, the tag of the structure is catalog. It is not the name of a
variable, only the name of the type of structure. The variable card is declared
MPLAB-CXX
as a structure of type catalog. The following shows what the structure catalog
looks like in memory.
Using
author 40 bytes
title 40 bytes
pub 40 bytes
date 2 bytes
rev 1 byte
To access any member of a structure, specify the name of the variable and
the name of the member separated by a period. For example, to change the
revision member of the structure catalog, use the following:
card.rev=’a’;
To access the third character in the title, use the following:
ThirdChar = card.title[2];
7.12.3.2 Syntax
The <union-name> is the tag of the union, and the <variable-list>
contains the names of the variables that have a data type of <union-name>.
Accessing members of a union is the same as accessing members of a
structure.
7.12.3.3 Example
Because an int is two bytes and a char is one byte, the union below is
stored in memory as shown:
union u_tag
{
int i;
char c[4];
} temp;
where:
<---------- i ---------->
switch( var_or_const.type )
{
case VARIABLE:
variable = var_or_const.value.variable_name;
break;
case CONSTANT:
constant = var_or_const.value.constant_value;
break;
}
}
Based on the type of data stored in struct type_tag, the access of the
data is different. A union allows the data for the two types to share space.
7.12.4.2 Example1
struct Memory Part
{ 2
int RAMSize;
int ROMSize;
};
struct PIC
MPLAB-CXX
{
Using
char Name[12];
struct Memory MemSizes;
};
Members of a structure or union define a separate name space, Meaning that
two different structures can have the same names for their members.
7.12.4.3 Example2
struct struct_tag_1{
int a;
int b;
char c;
} struct_1;
struct struct_tag_2
{
char d;
int a;
int b;
} struct_2;
7.12.5 Bit-fields
7.12.5.1 Description
Bit-fields allow the specification of integer-type members of a struction, which
are the specified number of bits in size. Bit-fields cannot cross byte
boundaries and, therefore, cannot be greater than 8 bits in size.
7.12.5.2 Syntax
struct <struct_name>
{
<int type> <member1> : <bit-width>;
<int type> <member2> : <bit-width>;
:
<int type> <membern> : <bit-width>;
}
7.12.5.3 Example
See Section 8.4.3.
8.1 Introduction
This section discusses specific details for programming PICmicro
microcontrollers (MCUs) when using MPLAB-C17 and MPLAB-C18.
8.2 Highlights
Items discuss in this chapter are:
• PICmicro MCU Programming Specifics
• MPLAB-C17 and PICmicro MCU Programming
• MPLAB-C18 and PICmicro MCU Programming
MPLAB-CXX
• Startup and Initialization
Using
• Interrupt Support
• Internal Assembler
There are certain instructions on PICmicro MCUs that may need to execute
from the C code. They can be included as in-line assembler instructions but
for convenience they are also available as macros in C. They are listed in the
following table:
Note: ‘var’ must be an 8-bit quantity (e.g., char) and not located on the
stack.
Header files are device (processor) specific, i.e., choose the header file
p17c756.h when coding for the PIC17C756. These files are contained in the
c:\mcc\h directory, where c:\mcc is the compiler install directory.
MPLAB-CXX
Using
The usage of the keywords near, far, ram and rom is discussed in Chapter 6.
Macro Action
Part
8.4.3 Register Definitions File 2
The register definitions file is an assembly file that contains declarations for all
the special function registers on the device. Every register definitions file is
associated with a C header file (see previous section) that contains, among
MPLAB-CXX
other things, external declarations for the special function registers.
Using
Example 8.2: PIC17C44 Port A Definition
Here Port A is defined in the register definitions file p17c44.asm as:
BANK0_SFR_SEC DATA H’010’
PORTAbits
PORTA RES 1 ; 010h
TRISB RES 1 ; 011h
.
.
and so on.
The first line specifies the file register bank where Port A is located and the
starting address for that bank. Port A has two labels, PORTAbits and
PORTA, both referring to the same location (in this case 010h in bank 0). So
the above definition reserves 1 byte for PORTA and PORTAbits at location
010h.
In p17c44.h, Port A is declared as:
volatile extern far unsigned char PORTA;
and as:
extern far volatile union
{
struct
{
unsigned RA0:1; /* Bit 0 */
unsigned RA1:1;
unsigned RA2:1;
unsigned RA3:1;
unsigned RA4:1;
unsigned RA5:1;
unsigned :1;
unsigned NOT_RBPU:1;
};
struct
{
unsigned INT:1; /* Alternate name for bit 0 */
unsigned T0CKI:1; /* Alternate name for bit 1 */
unsigned :6; /* pad next 6 locatons */
};
} PORTAbits;
The first declaration specifies that PORTA is a byte (unsigned char), whereas
the second one declares PORTAbits as a union of bit-addressable
structures. Since individual bits in a special function register may have more
than one function (and hence more than one name), there are multiple
structure definitions inside the union all referring to the same register.
Respective bits in all structure definitions refer to the same bit in the register.
Where a bit has only one function for its position, it is simply padded in other
structure definitions. For example, bits 2 through 7 on Port A are simply
padded in the second structure definition using the statement unsigned :6.
When using a special function register such as Port A, write the following
statements:
PORTA = 0x34; /* Assigns the value 0x34 to the */
/* whole port */
PORTAbits.INT = 1; /* Sets the INT pin high */
PORTAbits.RA0 = 1; /* Sets the RA0 pin high, same as */
/* above statement */
The extern modifier is needed since the variables are declared in the
register definitions file. The volatile modifier tells the compile that it cannot
assume that Port A retains values assigned to it. The far modifier specifies
that the port needs a bank switching instruction prior to access.
This reserves 32 bytes in the general purpose RAM area for the software
stack. The size of the software stack required by a program varies with the
Stack Overflow
Avoidance: For MPSIM or
complexity of the program. The following should be kept in mind:
MPLAB-ICE 2000, use a • One RAM location will be reserved by the compiler for use as the Stack
break statement at the Pointer.
last location on the stack. If
the program breaks, then a • When nesting function calls, all arguments and local variables (auto
stack overflow would have variables included) of the calling function will remain on the stack.
occurred in the next byte. Therefore, the stack must be large enough to accommodate the
requirements by all functions in a tree.
MPLAB-CXX
8.4.5.1 _ _STARTUP()
Using
The space shown between
To execute some code immediately after a device reset but before any other
the two underlines code generated by the compiler is executed, optionally create a function by
preceding STARTUP() is the name _ _STARTUP(). This will be the first code executed upon a reset. To
for illustration and should use a _ _STARTUP() function in a program:
not be used in actual code 1. Define a _ _STARTUP() function in a C program as follows:
(i.e., there should be no
space.) void _ _STARTUP(void)
{
// Initialize some registers to 0
TRISB = 0;
TRISC = 0;
}
MPLAB-CXX
Bank 0 Bank 1 Bank 2 Bank 3
Using
0xFB <Available> <Available> <Available> <Available>
The ALUSTA, PCLATH, BSR, and WREG are the registers that absolutely
need to be saved before we branch to the interrupt service function. However,
there are other registers used by the compiler that are worth saving under
certain circumstances. The following is an example that uses the Timer 0
Overflow Interrupt.
#include <p17c44.h>
unsigned char x;
void _ _TMR0()
{
x++;
PORTB = x;
}
void main()
{
x = 1;
// Install interrupt handler for timer 0 interrupt
Install_TMR0(_ _TMR0);
// Set prescale value for TMR0
T0STA = 0b11100110;
// Unmask TMR0 overflow interrupt
INTSTA = 0b00000010;
// Enable all unmasked interrupts
CPUSTA = 0;
// Set Port B in o/p mode
TRISB = 0;
while(1)
{
// Loop and wait for an interrupt to take place!
}
}
Install _TMR0 (_TMR0) sets the function _ _TMR0() as the interrupt handler
for Timer 0 overflow interrupts. Then the appropriate prescale value, interrupt
flag, and global interrupt enable flag are set. The program enters into an
infinite loop when it reaches the while(1) statement. When Timer 0
overflows, program control goes to the _ _TMR0() function where the value
of ‘x’ is sent to PORT B and possibly displayed on LEDs.
In this simple program the PICmicro MCU wasn't doing much at the time the
interrupt occurred. Therefore do not save any more registers in addition to
what the compiler interrupt code saved. However, in a more complex
application, the interrupt may occur at any point in the program. Therefore
other registers may need to be saved. The best way to find out is to look at the
generated code for the interrupt handling function. Find out which registers
are used by the compiler inside the function and make sure to save them at
the beginning and restore them at the end of the function. Looking at the
following example's generated code, determine that registers PRODL and
PRODH are used both inside and outside the interrupt function.
#include <p17c44.h>
#pragma udata intSave = 0xFa
unsigned char save_PRODL; // 0xF9
unsigned char save_1F; // 0xFA
unsigned char save_1E; // 0xFB
#pragma udata anywhere
unsigned char x, y;
void _ _TMR0()
{
_asm
movpf PRODL, save_PRODL
MPLAB-CXX
}
Using
The registers PRODH and PRODL are saved in save_1F, save_1E, and
save_PRODL, respectively. These variables are declared globally and
allocated at locations 0xFa to 0xFB in bank 0 using the #pragma udata
directive. This places them at the end of the bank just before save_B and
guarantees they are in bank 0. Since BSR is cleared in the interrupt support
code, don’t do any bank switching to save those three registers. However,
clear the BSR (using MOVLR 00) before restoring them as the interrupt
function code could have switched banks.
The following are merely guidelines as to what the compiler might be using for
certain tasks. However, the best guarantee that the context is saved and
restored correctly is by looking at generated code.
1. WREG: This is necessary if the program is doing anything other than
looping when an interrupt occurs. It is best to save WREG at all times.
2. FSR0, FSR1: Save FSR0 if the interrupt handling function uses arrays
or pointers.
3. PRODL, PRODH: Save these registers if performing multiplication in the
interrupt function. The compiler potentially uses PRODL and PRODH if
it is evaluating a complex expression.
4. TBLPTRL, TBLPTRH: These two registers are used for table read and
write operations. However, the compiler rarely uses them for temporary
storage. In general, it is not recommended to do table reads or writes in
the interrupt functions if done elsewhere in the program. Table reads and
writes use the 16-bit TBLAT register for latching data transferred from
and to program memory. Since TBLAT is not an addressable register it
cannot be saved or restored during interrupts.
The usage of the keywords near, far, ram and rom is discussed in Chapter 6.
MPLAB-CXX
Using
The register definitions file is an assembly file that contains declarations for all
the special function registers on the device. Every register definitions file is
associated with a C header file (see previous section) that contains, among
other things, external declarations for the special function registers.
There are two startup code files for the PIC18CXXX family. The first is
c018i.c which is used with initialized data (idata). The other is c018.c,
which is used without idata. There is no extra idata file for PIC18CXXX
devices.
MPLAB-CXX
8.5.5.3 Stack Initialization
Using
The stack initialization simply points the compiler stack pointer to the right
location in data memory.
goto loop;
9.1 Introduction
This section describes how to use assembly language and C modules
together. It gives examples of using C variables and functions in assembly
code and examples of using assembly language variables and functions in C.
9.2 Highlights
This chapter covers the following topics:
• Calling Conventions
• Mixing Assembly Language and C Variables and Functions
• Calling an Assembly Function in C – MPLAB-C17
• Using the File Selection Registers (FSR’s)
MPLAB-CXX
• Function declaration may return a value and/or contain parameters.
Using
• Functions are called using standard C function notation.
Calling C Routines from Assembly:
• C functions are inherently global.
• Function name must be declared as extern symbol in assembly file.
• call must be used to make function call; RETURN 0x00 implemented
at end of C function.
ex_asm.asm
; file: ex_asm.asm
LIST P=17C44
EXTERN main ; defined in C module
EXTERN c_variable ; also defined in C module
MYCODE CODE
asm_function
movlw 0xff
movwf c_variable ; put 0xffff in the C declared
; variable
movwf c_variable+1
return
GLOBAL asm_function ; export so linker can see it
MYDATA UDATA
asm_variable RES 2 ; 2 byte variable
GLOBAL asm_variable ; export so linker can see it
END
call_asm.asm
; File call_asm.asm
LIST P=17C756
EXTERN _stack
GLOBAL asm_function Part
MYCODE CODE 2
asm_function
banksel _stack ; Get the stack pointer into 0x00
movfp _stack, 0x01
MPLAB-CXX
decf 0x01, f ; Point FSR1 at the argument
movfp 0x00, 0x0a ; Get the argument
Using
decf 0x0a, f
; The convention is that we return
; with FSR0 pointing at the return value.
; We’ll just reuse the space
; allocated for the argument since we’re already
; pointed there.
global strcpy
STRCPY CODE
; char *strcpy (char *dst, const char *src);
strcpy
; We’ll play loose with the stack and frame pointers in this function.
; As long as the values are restored upon exit and the stack pointer
; always points into unallocated stack space, things will be fine,
; even if an interrupt occurs during our processing here.
;
; Save the current FSR2 value on the stack. We’ll be using it as
; a source index.
movff FSR2L, POSTINC1
movff FSR2H, POSTINC1
; Store the ’src’ pointer into FSR2
movlw -6
movff PLUSW1, FSR2L
movlw -5
movff PLUSW1, FSR2H
; Store the ’dst’ pointer into FSR0
movlw -4
movff PLUSW1, FSR0L
movlw -3
movff PLUSW1, FSR0H
; Perform the copy...
copyloop:
movff POSTINC2, INDF0
; Was that the ’\0’?
tstfsz POSTINC0,0
bra copyloop
; restore FSR2
movf POSTDEC1,1,0
movff POSTDEC1,FSR2H
movff INDF1,FSR2L
; The return value is a pointer to the destination
movlw -4
addwf FSR1L,0,0
movwf FSR0L,0
movlw 0xff
addwfc FSR1H,0,0
movwf FSR0H
return
end
Part
2
MPLAB-CXX
Using
NOTES:
10.1 Introduction
This section describes the behavior of MPLAB-CXX where the ANSI standard
X3.159-1989 describes the behavior as implementation defined. The text
below in italic font is taken directly from the ANSI standard with the
appropriate section in parentheses.
10.2 Highlights
This chapter covers ANSI-implementation issues for the following categories:
• Identifiers
• Characters
• Integers
• Floating Point
• Arrays and Pointers
• Registers
Part
• Structures and Unions
2
• Bit-Fields
• Enumerations
• Switch Statements
MPLAB-CXX
• Preprocessor Directives
Using
10.3 Identifiers
The number of significant initial characters (beyond 31) in
an identifier without external linkage (3.1.2)
The number of significant initial characters (beyond 6) in an
identifier with external linkage (3.1.2)
Whether case distinctions are significant in an identifier
with external linkage (3.1.2)
All MPLAB-CXX identifiers have 31 significant characters. Case distinctions
are significant in an identifier with external linkage.
10.4 Characters
The value of an integer character constant that contains
more than one character or a wide character constant that
contains more than one multibyte character (3.1.3.4)
The value of the integer character constant is the 8-bit value of the first
character. Wide characters are not supported.
Whether a ‘plain’ char has the same range of values as
signed char or unsigned char (3.2.1.1)
A ‘plain' char has the same range of values as a signed char.
For MPLAB-C18, this may be changed to unsigned char via a command
line switch (-k).
10.5 Integers
A ‘char’, a ‘short int’, or and ‘int’ bit-field, or their signed or
unsigned varieties, or an enumeration type, may be used in
an expression wherever an 'int' or 'unsigned int' may be
used. If an ‘int’ can represent all values of the original type,
the value is converted to an ‘int’; otherwise, it is converted
to an ‘unsigned int’. These are called the “integral
promotions.” All other arithmetic types are unchanged by
the integral promotions. The integral promotions preserve
value including sign. (3.2.1.1)
MPLAB-C18 does not enforce this by default. The -oi option can be used to
require the compiler to enforce the ANSI defined behavior.
The result of converting an integer to a shorter signed
integer, or the result of converting an unsigned integer to a
signed integer of equal length, if the value cannot be
represented (3.2.1.2)
When converting from a larger integer type to a smaller integer type, the high
order bits of the value are discarded and the remaining bits are interpreted
according to the type of the smaller integer type. When converting from an
unsigned integer to a signed integer of equal size, the bits of the unsigned
integer are simply reinterpreted according to the rules for a signed integer of
that size.
MPLAB-CXX
the PICmicro format and the IEEE 754 format consists of a rotation of the top
nine bits of the representation, with a left rotate for IEEE to PICmicro, and a
Using
right rotate for PICmicro to IEEE. Conversion to a 24-bit format is obtained by
the rounding to the nearest from IEEE 754 representation. The limiting
absolute values of the floating point formats are: 6.80564693E+38 max and
1.17549435E-38 min.
The rounding to the nearest method is used.
10.8 Registers
The extent to which objects can actually be placed in
registers by use of the register storage class specifier
(3.5.1)
The register storage class specifier is ignored.
10.10 Bit-Fields
Whether a ‘plain' int bit-field is treated as a signed int or as
an unsigned int bit-field (3.5.2.1)
A ‘plain' int bit-field is treated as an unsigned int bit-field (MPLAB-C17)
or a signed int bit-field (MPLAB-C18).
The order of allocation of bit-fields within a unit (3.5.2.1)
Bit-fields are allocated from least significant bit to most significant bit in order
of occurrence.
Whether a bit-field can straddle a storage-unit boundary
(3.5.2.1)
A bit-field cannot straddle a storage unit boundary.
10.11 Enumerations
The integer type chosen to represent the values of an
enumeration type (3.5.2.2)
signed int is used to represent the values of an enumeration type.
Part
10.12 Switch Statement 2
The maximum number of case values in a switch statement
(3.6.4.2)
MPLAB-CXX
The maximum number of values is limited only by target memory.
Using
10.13 Preprocessing Directives
The method for locating includable source files (3.8.2)
Includable source files specified via the #include <filename> mechanism
are searched for in the path specified in the MCC_INCLUDE environment
variable. The MCC_INCLUDE environment variable contains a semi-colon
delimited list of directories to search.
The support for quoted names for includable source files
(3.8.2)
Includable source files specified via the #include “filename” mechanism
are searched for in the current directory and then in the path specified in the
MCC_INCLUDE environment variable. The MCC_INCLUDE environment
variable contains a semi-colon delimited list of directories to search.
The behavior on each recognized #pragma directive (3.8.6)
Each #pragma directive is listed in Chapter 6.
NOTES:
11.1 Introduction
This chapter gives an overview of the example programs included with the
compiler program and support files.
At this time, only MPLAB-C17 has example files.
11.2 Highlights
The contents of this chapter are as following:
• Overview of Example Files
• Example Details
MPLAB-CXX
• Peripheral-Specific Examples
Using
- AD
- INT
- LINK
- PORT
- PWM
- TABLE_R/W
- USART
• Demo
- DEMO
Additions, deletions or other changes to this list may have occurred. Check
the readme.txt in the examples directory for more information on what
examples are available and a brief description of the function of each
example.
Appendices
Part
3
Appendicies
A.1 Introduction
This appendix contains the ASCII character set.
Hex 0 1 2 3 4 5 6 7
1 SOH DC1 ! 1 A Q a q
3 ETX DC3 # 3 C S c s
Least Significant Character
4 EOT DC4 $ 4 D T d t
5 ENQ NAK % 5 E U e u
7 Bell ETB ’ 7 G W g w
8 BS CAN ( 8 H X h x
9 HT EM ) 9 I Y i y
A LF SUB * : J Z j z
B VT ESC + ; K [ k {
C FF FS , < L \ l |
D CR GS - = M ] m } Part
3
E SO RS . > N ^ n ~
F SI US / ? O _ o DEL
Appendicies
NOTES:
B.1 Introduction
This appendix gives the instruction set for the PIC17CXXX device family.
B.2 Highlights
This appendix presents the following reference information:
• Key to PICmicro MCU Family Instruction Sets
• PIC17CXXX Instruction Set
Part
3
Appendicies
Part
3
Appendicies
NOTES:
C.1 Introduction
This appendix gives the instruction set for the PIC18CXXX device family.
C.2 Highlights
This appendix presents the following reference information:
• Key to Enhanced 16-Bit Core Instruction Sets
• PIC18CXXX Instruction Set
NOTES:
D.1 Introduction
This appendix lists errors generated by the MPLAB-C17 compiler.
D.2 Highlights
The following errors apply to MPLAB-C17:
• Errors
• Warnings
D.3 Errors
1000: argument count mismatch in function call
To call a function, the number of arguments passed must match exactly the
number of parameters declared for the function.
1001: type mismatch in argument %d
The type of an argument to a function call must be compatible with the
declared type of the corresponding parameter
1002: arithmetic type expected in expression
The operator requires that its operand be of arithmetic type
1003: arithmetic or pointer to object type required
1004: array must have integral constant size
1005: object of pointer type required for [ ] operator
The array access operator, ‘[ ]’, requires that one operand be a pointer and
the other be an integer, that is, for ‘x[y]’ the expression ‘*(x+y)’ must be
valid. ‘x[y]’ is functionally equivalent to ‘*(x+y)’.
1006: ‘−>’ requires pointer to struct or union
The member access operator ‘−>’ requires operands of pointer to struct/
union. Part
1007: call of non-function
3
The operand of the ‘()’ function call post-fix operator must be of type
‘pointer to function.’ Most commonly, this is a function identifier. Common
Appendicies
D.4 Warnings
2000: no prototype for ‘%s’
2001: shift by zero Part
3
2002: shift by more bits than contained in operand
2003: ‘rom’ and ‘volatile’ in same declaration
2004: unused symbol block
Appendicies
E.1 Introduction
This appendix lists errors generated by the MPLAB-C18 compiler.
E.2 Highlights
The following errors apply to MPLAB-C18:
• Errors
• Warnings
E.3 Errors
1000: unexpected input following ‘%s’
1001: identifier expected following ‘%s’
1002: syntax error, ‘%s’ expected
1003: unknown pre-processor directive ‘%s’
1004: missing ‘)’ in macro on line %d
1005: missing argument %d invoking macro %s
1006: extra argument(s) invoking macro ‘%s’
1007: ‘(’ expected invoking macro ‘%s’
1008: #else without #if detected
1009: #elif without #if detected
1010: #endif without #if detected
1012: identifier expected in macro definition
1013: error in pragma directive
1014: attribute mismatch in resumption of section ‘%s’
1011: missing #endif
Part
1015: missing include path for system header files 3
1050: section address permitted only at definition
1051: section pragma not allowed inside a function
Appendicies
E.4 Warnings
2000: redefinition of macro ‘%s’
2051: storage class mismatch in redeclaration of ‘%s’
2060: shift expression has no effect
2061: shift expression always zero
2052: unexpected return value
A return of a value statement has been detected in a function declared to
return no value. The return value will be ignored.
2053: return value expected
A return with no value has been detected in a function declared to return a
value. The return value will be undefined.
2054: suspicious pointer conversion
A pointer has been used as an integer or an integer has been used as a
pointer without an explicit cast.
2055: expression is always false
The control expression of a conditional statement evaluates to a constant
false value
2056: expression is always true
The control expression of a conditional statement evaluates to a constant
true value
2057: possibly incorrect test of assignment
An implicit test of an assignment expression, e.g., ‘if(x=y)’ is often seen
when a ‘=’ operator has been used when a ‘==’ operator was intended.
2058: call of function without prototype
A function call has been made without an in-scope function prototype for
the function being called. This can be un-safe, as no type-checking for the
function arguments can be performed.
2059: unary minus of unsigned value
The unary minus operator is normally only applied to signed values.
2062: ‘−>’ operator expected, not ‘.’
A struct/union member access via a pointer to struct/union has been per-
formed using the ‘.’ operator.
2063: ‘.’ operator expected, not ‘−>’
A direct struct/union member access has been performed using the ‘−>’
operator.
2064: static function ‘%s’ not defined
The function has been declared as static, but there is no definition for the
function present. Common causes include a misspelled function name in
the function definition.
2065: static function ‘%s’ never referenced
The static function has been defined, but has not been referenced.
Part
3
Appendicies
NOTES:
Appendix F. References
F.1 Introduction
This appendix gives references that may be helpful in programming with
MPLAB-CXX.
F.2 Highlights
This appendix lists the following reference types:
• C Standards Information
• General C Information
NOTES:
Glossary
Introduction
To provide a common frame of reference, this glossary defines the terms for
several Microchip tools.
Highlights
This glossary contains terms and definitions for the following tools:
• MPLAB IDE, MPLAB-SIM, MPLAB Editor
• MPASM, MPLINK, MPLIB
• MPLAB-CXX
• MPLAB-ICE, PICMASTER Emulators
• MPLAB-ICD
• PICSTART Plus, PRO MATE programmer
Terms
Absolute Section
A section with a fixed (absolute) address which can not be changed by the
linker.
Access RAM (PIC18CXXX Devices Only)
Special general purpose registers on PIC18CXXX devices that allow access
regardless of the setting of the bank select bit (BSR).
Alpha Character
Alpha characters are those characters, regardless of case, that are letters of
the alphabet: (a, b, …, z, A, B, …, Z).
Alphanumeric
Alphanumeric characters include alpha characters and numbers: (0,1, …, 9).
Application
A set of software and hardware developed by the user, usually designed to be
a product controlled by a PICmicro microcontroller.
Assemble
What an assembler does. See assembler.
Assembler
A language tool that translates a user’s assembly source code (.asm) into
machine code. MPASM is Microchip’s assembler.
Assembly
A programming language that is once removed from machine language.
Machine languages consist entirely of numbers and are almost impossible for
humans to read and write. Assembly languages have the same structure and
set of commands as machine languages, but they enable a programmer to
use names (mnemonics) instead of numbers.
Assigned Section
A section which has been assigned to a target memory block in the linker
command file. The linker allocates an assigned section into its specified target
memory block.
Break Point – Hardware
An event whose execution will cause a halt.
Break Point – Software
An address where execution of the firmware will halt. Usually achieved by a
special break opcode.
Build
A function that recompiles all the source files for an application.
C
A high level programming language that may be used to generate code for
PICmicro MCUs, especially high-end device families.
Calibration Memory
A special function register or registers used to hold values for calibration of a
PICmicro microcontroller on-board RC oscillator.
COFF
Common Object File Format. An intermediate file format generated by
MPLINK that contains machine code and debugging information.
Command Line Interface
Command line interface refers to executing a program on the DOS command
line with options. Executing MPASM with any command line options or just the
file name will invoke the assembler. In the absence of any command line
options, a prompted input interface (shell) will be executed.
Compile
What a compiler does. See compiler.
Compiler
A language tool that translates a user’s C source code into machine code.
MPLAB-C17 and MPLAB-C18 are Microchip’s C compilers for PIC17CXXX
and PIC18CXXX devices, respectively.
Configuration Bits
Unique bits programmed to set PICmicro microcontroller modes of operation.
A configuration bit may or may not be preprogrammed. These bits are set in
the Options > Development Mode dialog for simulators or emulators and in
the _ _ CONFIG MPASM directive for programmers.
Control Directives
Control directives in MPASM permit sections of conditionally assembled code.
Data Directives
Data directives are those that control MPASM’s allocation of memory and
provide a way to refer to data items symbolically; that is, by meaningful
names.
Data Memory
General purpose file registers (GPRs) from RAM on the PICmicro device
being emulated. The File Register window displays data memory.
Directives
Directives provide control of the assembler’s operation by telling MPASM how
to treat mnemonics, define data, and format the listing file. Directives make
coding easier and provide custom output according to specific needs.
Download
Download is the process of sending data from the PC host to another device,
such as an emulator, programmer or target board.
EEPROM
Electrically Erasable Programmable Read Only Memory. A special type of
PROM that can be erased electrically. Data is written or erased one byte at a
time. EEPROM retains its contents even when power is turned off.
Emulation
The process of executing software loaded into emulation memory as if the
firmware resided on the microcontroller device under development.
Emulation Memory
Program memory contained within the emulator.
Emulator
Hardware that performs emulation.
Emulator System
The MPLAB-ICE emulator system includes the pod, processor module, device
adapter, cables, and MPLAB Software. The PICMASTER emulator system
includes the pod, device-specific probe, cables, and MPLAB Software.
Event
A description of a bus cycle which may include address, data, pass count,
external input, cycle type (fetch, R/W), and time stamp. Events are used to
describe triggers and break points.
Executable Code
See Hex Code.
Export
Send data out of the MPLAB IDE in a standardized format.
Expressions
Expressions are used in the operand field of MPASM’s source line and may
contain constants, symbols, or any combination of constants and symbols
separated by arithmetic operators. Each constant or symbol may be preceded
by a plus or minus to indicate a positive or negative expression.
File Registers
On-chip general purpose and special function registers.
Flash
A type of EEPROM where data is written or erased in blocks instead of bytes.
FNOP
Forced No Operation. A forced NOP cycle is the second cycle of a two-cycle
instruction. Since the PICmicro architecture is pipelined, it prefetches the next
instruction in the physical address space while it is executing the current
instruction. However, if the current instruction changes the program counter,
this prefetched instruction is explicitly ignored, causing a forced NOP cycle.
GPR
See Data Memory.
Halt
A function that stops the emulator. Executing Halt is the same as stopping at a
break point. The program counter stops, and the user can inspect and change
register values, and single step through code.
Hex Code
Executable instructions assembled or compiled from source code into
standard hexadecimal format code. Also called executable or machine code.
Hex code is contained in a hex file.
Hex File
An ASCII file containing hexadecimal addresses and values (hex code)
suitable for programming a device. This format is readable by a device
programmer.
High Level Language
A language for writing programs that is of a higher level of abstraction from
the processor than assembler code. High level languages (such as C) employ
a compiler to translate statements into machine instructions that the target
processor can execute.
ICD
In-Circuit Debugger. MPLAB-ICD is Microchip’s in-circuit debugger for
PIC16F87X devices. MPLAB-ICD works with MPLAB IDE.
ICE
In-Circuit Emulator. MPLAB-ICE is Microchip’s in-circuit emulator that works
with MPLAB IDE.
IDE
Integrated Development Environment. An application that has multiple
functions for firmware development. The MPLAB IDE integrates a compiler,
an assembler, a project manager, an editor, a debugger, a simulator, and an
Local Label
A local label is one that is defined inside a macro with the LOCAL directive.
These labels are particular to a given instance of a macro’s instantiation. In
other words, the symbols and labels that are declared as local are no longer
accessible after the ENDM macro is encountered.
Logic Probes
Up to 14 logic probes connected to the emulator. The logic probes provide
external trace inputs, trigger output signal, +5V, and a common ground.
Machine Code
Either object or executable code.
Macro
A collection of assembler instructions that are included in the assembly code
when the macro name is encountered in the source code. Macros must be
defined before they are used; forward references to macros are not allowed.
All statements following a MACRO directive and prior to an ENDM directive are
part of the macro definition. Labels used within the macro must be local to the
macro so the macro can be called repetitively.
Macro Directives
Directives that control the execution and data allocation within macro body
definitions.
Make Project
A command that rebuilds an application, re-compiling only those source files
that have changed since the last complete compilation.
MCU
Microcontroller Unit. An abbreviation for microcontroller. Also µC.
Memory Models
Versions of libraries and/or precompiled object files based on a device’s
memory (RAM/ROM) size and structure.
Microcontroller
A highly integrated chip that contains all the components comprising a
controller. Typically this includes a CPU, RAM, some form of ROM, I/O ports,
and timers. Unlike a general-purpose computer, which also includes all of
these components, a microcontroller is designed for a very specific task – to
control a particular system. As a result, the parts can be simplified and
reduced, which cuts down on production costs.
Microcontroller Mode (PIC17CXXX and PIC18CXXX Devices Only)
One of the possible program memory configurations of the PIC17CXXX and
PIC18CXXX families of microcontrollers. In microcontroller mode, only
internal execution is allowed. Thus, only the on-chip program memory is
available in microcontroller mode.
MPLINK
MPLINK is a linker for the Microchip relocatable assembler, MPASM, and the
Microchip C compilers, MPLAB-C17 or MPLAB-C18. MPLINK also may be
used with the Microchip librarian, MPLIB. MPLINK is designed to be used with
MPLAB IDE, though it does not have to be.
MPLINK will combine object files and libraries to create a single executable
file.
MPSIM
The DOS version of Microchip’s simulator. MPLAB-SIM is the newest
simulator from Microchip.
MRU
Most Recently Used. Refers to files and windows available to be selected
from MPLAB IDE main pull down menus.
Nesting Depth
The maximum level to which macros can include other macros. Macros can
be nested to 16 levels deep.
Non Real-Time
Refers to the processor at a break point or executing single step instructions
or MPLAB IDE being run in simulator mode.
Node
MPLAB IDE project component.
NOP
No Operation. An instruction that has no effect when executed except to
advance the program counter.
Object Code
The intermediate code that is produced from the source code after it is
processed by an assembler or compiler. Relocatable code is code produced
by MPASM or MPLAB-C17/C18 that can be run through MPLINK to create
executable code. Object code is contained in an object file.
Object File
A module which may contain relocatable code or data and references to
external code or data. Typically, multiple object modules are linked to form a
single executable output. Special directives are required in the source code
when generating an object file. The object file contains object code.
Object File Directives
Directives that are used only when creating an object file.
Power-on-Reset Emulation
A software randomization process that writes random values in data RAM
areas to simulate uninitialized values in RAM upon initial power application.
Precedence
The concept that some elements of an expression are evaluated before
others; i.e., * and / before + and -. In MPASM, operators of the same
precedence are evaluated from left to right. Use parentheses to alter the order
of evaluation.
Program Counter
A register that specifies the current execution address.
Program Memory
The memory area in a PICmicro microcontroller where instructions are stored.
Memory in the emulator or simulator containing the downloaded target
application firmware.
Programmer
A device used to program electrically programmable semiconductor devices
such as microcontrollers.
Project
A set of source files and instructions to build the object and executable code
for an application.
PRO MATE
A device programmer from Microchip. Programs all PICmicro microcontrollers
and most memory and Keeloq devices. Can be used with MPLAB IDE or
stand-alone.
Prototype System
A term referring to a user’s target application, or target board.
PWM Signals
Pulse Width Modulation Signals. Certain PICmicro devices have a PWM
peripheral.
Qualifier
An address or an address range used by the Pass Counter or as an event
before another operation in a complex trigger.
Radix
The number base, hex, or decimal, used in specifying an address and for
entering data in the Window > Modify command.
RAM
Random Access Memory (Data Memory).
Raw Data
The binary representation of code or data associated with a section.
Real-Time
When released from the halt state in the emulator or MPLAB-ICD mode, the
processor runs in real-time mode and behaves exactly as the normal chip
would behave. In real-time mode, the real-time trace buffer of MPLAB-ICE is
enabled and constantly captures all selected cycles, and all break logic is
enabled. In the emulator or MPLAB-ICD, the processor executes in real-time
until a valid break point causes a halt, or until the user halts the emulator.
In the simulator real-time simply means execution of the microcontroller
instructions as fast as they can be simulated by the host CPU.
Recursion
The concept that a function or macro, having been defined, can call itself.
Great care should be taken when writing recursive macros; it is easy to get
caught in an infinite loop where there will be no exit from the recursion.
Relocatable Section
A section whose address is not fixed (absolute). The linker assigns addresses
to relocatable sections through a process called relocation.
Relocation
A process performed by the linker in which absolute addresses are assigned
to relocatable sections and all identifier symbol definitions within the
relocatable sections are updated to their new addresses.
ROM
Read Only Memory (Program Memory).
Run
The command that releases the emulator from halt, allowing it to run the
application code and change or respond to I/O in real time.
Section
An portion of code or data which has a name, size, and address.
SFR
Special Function Registers of a PICmicro.
Shared Section
A section which resides in a shared (non-banked) region of data RAM.
Shell
The MPASM shell is a prompted input interface to the macro assembler.
There are two MPASM shells: one for the DOS version and one for the
Windows version.
Simulator
A software program that models the operation of the PICmicro
microprocessor.
Single Step
This command steps though code, one instruction at a time. After each
instruction, MPLAB IDE updates register windows, watch variables, and
status displays so you can analyze and debug instruction execution.
You can also single step C compiler source code, but instead of executing
single instructions, MPLAB IDE will execute all assembly level instructions
generated by the line of the high level C statement.
Skew
The information associated with the execution of an instruction appears on
the processor bus at different times. For example, the executed opcode
appears on the bus as a fetch during the execution of the previous instruction,
the source data address and value and the destination data address appear
when the opcode is actually executed, and the destination data value appears
when the next instruction is executed. The trace buffer captures the
information that is on the bus at one instance. Therefore, one trace buffer
entry will contain execution information for three instructions. The number of
captured cycles from one piece of information to another for a single
instruction execution is referred to as the skew.
Skid
When a hardware break point is used to halt the processor, one or more
additional instructions may be executed before the processor halts. The
number of extra instructions executed after the intended break point is
referred to as the skid.
Source Code - Assembly
Source code consists of PICmicro instructions and MPASM directives and
macros that will be translated into machine code by an assembler.
Source Code - C
A program written in the high level language called “C” which will be converted
into PICmicro machine code by a compiler. Machine code is suitable for use
by a PICmicro MCU or Microchip development system product like MPLAB
IDE.
Source File - Assembly
The ASCII text file of PICmicro instructions and MPASM directives and
macros (source code) that will be translated into machine code by an
assembler. It is an ASCII file that can be created using any ASCII text editor.
Source File - C
The ASCII text file containing C source code that will be translated into
machine code by a compiler. It is an ASCII file that can be created using any
ASCII text editor.
Special Function Registers
Registers that control I/O processor functions, I/O status, timers, or other
modes or peripherals.
Stack - Hardware
An area in PICmicro MCU memory where function arguments, return values,
local variables, and return addresses are stored; i.e., a “Push-Down” list of
calling routines. Each time a PICmicro MCU executes a CALL or responds to
an interrupt, the software pushes the return address to the stack. A return
command pops the address from the stack and puts it in the program counter.
The PIC18CXXX family also has a hardware stack to store register values for
“fast” interrupts.
Stack - Software
The compiler uses a software stack for storing local variables and for passing
arguments to and returning values from functions.
Static RAM or SRAM
Static Random Access Memory. Program memory you can Read/Write on the
target board that does not need refreshing frequently.
Status Bar
The Status Bar is located on the bottom of the MPLAB IDE window and
indicates such current information as cursor position, development mode and
device, and active tool bar.
Step Into
This command is the same as Single Step. Step Into (as opposed to Step
Over) follows a CALL instruction into a subroutine.
Step Over
Step Over allows you to debug code without stepping into subroutines. When
stepping over a CALL instruction, the next break point will be set at the
instruction after the CALL. If for some reason the subroutine gets into an
endless loop or does not return properly, the next break point will never be
reached.
The Step Over command is the same as Single Step except for its handling of
CALL instructions.
Stimulus
Data generated to exercise the response of simulation to external signals.
Often the data is put into the form of a list of actions in a text file. Stimulus may
be asynchronous, synchronous (pin), clocked and register.
Stopwatch
A counter for measuring execution cycles.
Symbol
A symbol is a general purpose mechanism for describing the various pieces
which comprise a program. These pieces include function names, variable
names, section names, file names, struct/enum/union tag names, etc.
Symbols in MPLAB IDE refer mainly to variable names, function names and
assembly labels.
System Button
The system button is another name for the system window control. Clicking on
the system button pops up the system menu.
System Window Control
The system window control is located in the upper left corner of windows and
some dialogs. Clicking on this control usually pops up a menu that has the
items “Minimize,” “Maximize,” and “Close.” In some MPLAB IDE windows,
additional modes or functions can be found.
system window control
Target
Refers to user hardware.
Target Application
Firmware residing on the target board.
Target Board
The circuitry and programmable device that makes up the target application.
Target Processor
The microcontroller device on the target application board that is being
emulated.
Template
Lines of text that you build for inserting into your files at a later time. The
MPLAB Editor stores templates in template files.
Tool Bar
A row or column of icons that you can click on to execute MPLAB IDE
functions.
Trace
An emulator or simulator function that logs program execution. The emulator
logs program execution into its trace buffer which is uploaded to MPLAB IDE’s
trace window.
Trace Memory
Trace memory contained within the emulator. Trace memory is sometimes
called the trace buffer.
Trigger Output
Trigger output refers to an emulator output signal that can be generated at any
address or address range, and is independent of the trace and break point
settings. Any number of trigger output points can be set.
Unassigned Section
A section which has not been assigned to a specific target memory block in
the linker command file. The linker must find a target memory block in which
to allocate an unassigned section.
Uninitialized Data
Data which is defined without an initial value. In C, int myVar; defines a
variable which will reside in an uninitialized data section.
Upload
The Upload function transfers data from a tool, such as an emulator or
programmer, to the host PC or from the target board to the emulator.
Warning
An alert that is provided to warn you of a situation that would cause physical
damage to a device, software file, or equipment.
WatchDog Timer (WDT)
A timer on a PICmicro microcontroller that resets the processor after a
selectable length of time. The WDT is enabled or disabled and set up using
configuration bits.
Watch Variable
A variable that you may monitor during a debugging session in a watch
window.
Watch Window
Watch windows contain a list of watch variables that are updated at each
break point.
Index
C Listing .....................................................192
C Keywords .................................................... 73 Macro ......................................................193
C Programming ............................................... 75 Object File ..............................................195
C++ Comment ................................................ 85 doc directory ....................................................18
c018.o ........................................................... 137 Document Conventions .....................................3
c018i.o .......................................................... 137 Document Layout ..............................................1
c0l17.asm ..................................................... 129 double .......................................................88, 90
c0s17.asm .................................................... 129 do-while .........................................................108
Calibration Memory ....................................... 188 E
case .............................................................. 109
Edit Project ................................................43, 57
char ........................................................... 88, 89
EEPROM .......................................................189
Characters
else ................................................................107
ANSI C ................................................... 146
Emulator ........................................................189
ClrWdt( ) ....................................................... 124
endasm ( _endasm ) ...............................73, 126
Code
Enumerations ..................................................93
Start Up .......... 25, 28, 39, 47, 125, 129, 136
ANSI C ....................................................149
Code File .................................................. 25, 39
Environment Variable See MCC_INCLUDE
COFF File ..................................... 25, 29, 34, 39
equal to (==) ..................................................100
Command Line
Error File .............................................21, 28, 33
Multiple File Compile, MPLAB-C17 .......... 30
Escape Sequences .........................................86
Multiple File Compile, MPLAB-C18 .......... 35
Example Code ...............................................151
Options, MPLAB-C17 ............................... 26
examples directory ..........................................18
Options, MPLAB-C18 ............................... 31
Executable
Single File Compile, MPLAB-C17 ............ 27
Directory .......................................18, 27, 33
Single File Compile, MPLAB-C18 ............ 33
Files ............................15, 25, 29, 34, 37, 39
Command Line Interface .............................. 188
Executable Code ...........................................190
Comments .............................................. 85, 126
Export ............................................................190
Compiler ....................................................... 188
Expressions ...................................................190
Compiler Overview ......................................... 19
Extended Microcontroller Mode ....................190
Conditional Operator ..................................... 103
extern ..............................................................88
Configuration Bits ......................................... 189
External Declaration ..............123, 124, 127, 135
const ............................................................... 88
External RAM ................................................190
Constants
Character ............................................ 86, 87 F
Numeric .............................................. 86, 87 far ........................73, 88, 90, 118, 126, 128, 135
String .................................................. 84, 87 File
continue ........................................................ 111 Listing .....................................................192
Customer Notification Service .......................... 7 float ...........................................................88, 90
Customer Support ............................................. 9 Floating Point
D ANSI C ....................................................147
for ..................................................................107
Data Memory ................................................ 189
FSR0, PIC17CXXX Hardware .......................133
Data Types ..................................................... 89
FSR1, PIC17CXXX Hardware .......................133
Decrement Operators ................................... 102
FSR1, PIC18CXXX Software ........................136
default ........................................................... 109
FSR2, PIC18CXXX Software ........................136
Development Mode ................................... 41, 55
Functions .........................................................96
Directives ...................................................... 189
Declaration ...............................................96
Control .................................................... 189
Funky ........................................................96
Data ........................................................ 189
Passing Arguments ..................................97
W
Watch Dog Timer .......................................... 202
Watch Window .............................................. 202
Watchdog Timer (WDT) ................................ 124
WDT .............................................................. 202
while ...................................................... 108, 109
WREG ................................................... 131, 133
WWW Address ................................................. 6
X
XOR, Bitwise (^) ............................................ 101
NOTES:
All rights reserved. © 2000 Microchip Technology Incorporated. Printed in the USA. 2/00 Printed on recycled paper.
Information contained in this publication regarding device applications and the like is intended through suggestion only and may be superseded by updates.
It is your responsibility to ensure that your application meets with your specifications. No representation or warranty is given and no liability is assumed by
Microchip Technology Incorporated with respect to the accuracy or use of such information, or infringement of patents or other intellectual property rights
arising from such use or otherwise. Use of Microchip’s products as critical components in life support systems is not authorized except with express written
approval by Microchip. No licenses are conveyed, implicitly or otherwise, except as maybe explicitly expressed herein, under any intellectual property
rights. The Microchip logo and name are registered trademarks of Microchip Technology Inc. in the U.S.A. and other countries. All rights reserved. All other
trademarks mentioned herein are the property of their respective companies.