C Compiler For The Picmicro Devices: User'S Manual
C Compiler For The Picmicro Devices: User'S Manual
C Compiler For The Picmicro Devices: User'S Manual
Version 3.8
User's Manual
B Knudsen Data
Trondheim - Norway
CC5X C Compiler B Knudsen Data
This manual and the CC5X compiler is protected by Norwegian copyright laws and thus by
corresponding copyright laws agreed to internationally by mutual consent. The manual and the compiler
may not be copied, partially or as a whole without written consent from the author. The PDF-edition of
the manual can be printed to paper for private or local use, but not for distribution. Modification of the
manual or the compiler is strongly prohibited. All rights reserved.
LICENSE AGREEMENT:
By using the CC5X compiler, you agree to be bound by this agreement.
Only one person may use a licensed edition of the CC5X compiler at the same time for each user license.
If more than one person wants to use the compiler for each user license, then this has to be done by some
manual handshaking procedure (not electronic automated), for example by exchanging a printed copy of
the CC5X User's Manual as a permission key. A site license allows an unlimited number of users within
the same administration unit.
You may make backup copies of the software, and copy it to multiple computers. You may not distribute
copies of the compiler to others. B Knudsen Data assumes no responsibility for errors or defects in the
documentation or in the compiler. This also applies to problems caused by such errors.
This manual covers CC5X version 3.8 and related topics. New versions may contain changes without
prior notice.
Microchip and PICmicro are trademarks of Microchip Technology Inc., Chandler, AZ, U.S.A.
The compiler has been carefully tested and debugged. It is, however, not possible to guarantee a 100 %
error free product.
If the compiler generates application code bugs, it is almost always possible to rewrite the program
slightly in order to avoid the bug. #pragma optimize can be used to avoid optimization bugs. Other
#pragma statements are also useful.
Please report cases of bad generated code and other serious program errors.
1) Investigate and describe the problem. If possible, please provide a complete C example program that
demonstrates the problem. A fragment from the generated assembly file is sometimes enough.
2) This service is intended for difficult compiler problems (not application problems).
3) Language: English
4) State the compiler version.
5) Send your report to [email protected].
Document version: M
2
CC5X C Compiler B Knudsen Data
CONTENTS
1 INTRODUCTION ..................................................................................................................................8
1.1 SUPPORTED DEVICES ..........................................................................................................................9
1.2 INSTALLATION AND SYSTEM REQUIREMENTS ....................................................................................9
Support for long file names ..................................................................................................................9
User interface .......................................................................................................................................9
1.3 MPLAB SUPPORT ............................................................................................................................10
1.4 THE SETCC UTILITY .......................................................................................................................10
1.5 SUMMARY OF DELIVERED FILES ......................................................................................................10
1.6 SHORT PROGRAM EXAMPLE .............................................................................................................12
1.7 DEFINING THE PICMICRO DEVICE ....................................................................................................13
1.8 WHAT TO DO NEXT ...........................................................................................................................14
2 VARIABLES.........................................................................................................................................15
2.1 INFORMATION ON RAM ALLOCATION ..............................................................................................15
2.2 DEFINING VARIABLES ......................................................................................................................16
Integer variables.................................................................................................................................16
Floating point .....................................................................................................................................17
IEEE754 interoperability ...................................................................................................................17
Fixed point variables..........................................................................................................................18
Assigning variables to RAM addresses...............................................................................................20
Supported type modifiers....................................................................................................................21
Local variables ...................................................................................................................................22
Temporary variables ..........................................................................................................................23
Arrays, structures and unions.............................................................................................................23
Large arrays on the Enhanced 14 bit core .........................................................................................24
Bitfields...............................................................................................................................................24
Typedef ...............................................................................................................................................24
2.3 USING RAM BANKS.........................................................................................................................25
The bank type modifier .......................................................................................................................25
RAM bank selection bits .....................................................................................................................26
Manual bank bit update regions.........................................................................................................26
2.4 POINTERS .........................................................................................................................................27
Pointer models....................................................................................................................................27
The 12 bit Core...................................................................................................................................28
The 14 bit core: the IRP bit ................................................................................................................29
2.5 CONST DATA SUPPORT.....................................................................................................................30
Storing 14 bit data ..............................................................................................................................31
Data of size 16 bits or more ...............................................................................................................31
Code pages .........................................................................................................................................31
Locating Const Data ..........................................................................................................................32
Merging data ......................................................................................................................................32
Examples ............................................................................................................................................32
Const data stored in dedicated functions............................................................................................33
3 SYNTAX................................................................................................................................................34
3.1 STATEMENTS ....................................................................................................................................34
if statement .........................................................................................................................................34
while statement ...................................................................................................................................34
for statement .......................................................................................................................................34
do statement........................................................................................................................................35
switch statement..................................................................................................................................35
break statement...................................................................................................................................35
3
CC5X C Compiler B Knudsen Data
continue statement..............................................................................................................................36
return statement..................................................................................................................................36
goto statement.....................................................................................................................................36
3.2 ASSIGNMENT AND CONDITIONS .......................................................................................................36
Special syntax examples .....................................................................................................................36
Conditions ..........................................................................................................................................37
Bit variables .......................................................................................................................................37
Multiplication, division and modulo...................................................................................................38
Precedence of C operators .................................................................................................................38
Mixed variable sizes are allowed .......................................................................................................39
3.3 CONSTANTS ......................................................................................................................................39
Constant expressions ..........................................................................................................................39
Enumeration .......................................................................................................................................40
3.4 FUNCTIONS .......................................................................................................................................40
Function return values .......................................................................................................................40
Parameters in function calls...............................................................................................................40
Internal functions ...............................................................................................................................41
3.5 TYPE CAST .......................................................................................................................................41
3.6 ACCESSING PARTS OF A VARIABLE ..................................................................................................43
3.7 C EXTENSIONS .................................................................................................................................43
3.8 PREDEFINED SYMBOLS .....................................................................................................................44
Extensions to the standard C keywords ..............................................................................................44
Standard C keywords used .................................................................................................................44
The sizeof operator .............................................................................................................................45
Function offsetof( struct_type, struct_member)..................................................................................45
Automatically defined macros and symbols .......................................................................................45
Macros __FILE__ and __LINE__......................................................................................................46
Macros __DATE__ and __TIME__....................................................................................................46
3.9 UPWARD COMPATIBILITY.................................................................................................................46
4 PREPROCESSOR DIRECTIVES ......................................................................................................47
#define ................................................................................................................................................47
Macro concatenation..........................................................................................................................47
Macro stringification..........................................................................................................................47
#include ..............................................................................................................................................48
#undef .................................................................................................................................................48
#if........................................................................................................................................................48
#ifdef...................................................................................................................................................49
#ifndef.................................................................................................................................................49
#elif.....................................................................................................................................................49
#else....................................................................................................................................................49
#endif..................................................................................................................................................49
#error .................................................................................................................................................49
#warning.............................................................................................................................................50
#message ............................................................................................................................................50
4.1 THE PRAGMA STATEMENT ................................................................................................................50
#pragma alignLsbOrigin <a> [ to <b>] ...........................................................................................50
#pragma asm2var 1............................................................................................................................50
#pragma assert [/] <type> <text field>.............................................................................................50
#pragma assume *<pointer> in rambank <n> .................................................................................50
#pragma bit <name> @ <N.B or variable[.B]> ...............................................................................50
#pragma cdata[ADDRESS] = <VXS>, .., <VXS>...........................................................................51
#pragma char <name> @ <constant or variable> ...........................................................................51
#pragma chip [=] <device> ..............................................................................................................51
#pragma codepage [=] <0,1,2,3, ..15> .............................................................................................51
#pragma computedGoto [=] <0,1,2> ................................................................................................52
4
CC5X C Compiler B Knudsen Data
5
CC5X C Compiler B Knudsen Data
6
CC5X C Compiler B Knudsen Data
7
CC5X C Compiler B Knudsen Data
1 INTRODUCTION
Welcome to the CC5X C compiler for the Microchip PICmicro family of microcontrollers. The CC5X
compiler enables programming using a subset of the C language. Assembly is no longer required. The
reason for moving to C is clear. Assembly language is generally hard to read and errors are easily
produced.
The CC5X compiler was designed to generate tight and optimized code. The optimizer automatically
squeezes the code to a minimum. It is possible to write code that compiles into single instructions, but
with C syntax. This means that the C source code can be optimized by rewriting inefficient expressions.
The design priority was not to provide full ANSI C support, but to enable the best possible usage of the
limited code and RAM resources. If the compiler generated less optimal code, this would force assembly
to be used for parts of the code.
CC5X features
• Local and global variables of 8, 16, 24 and 32 bits, plus bit variables
• Efficient reuse of local variable space
• Generates tight and optimized code
• Produces binary, assembly, list, COD, error, function outline and variable files
• Automatic updating of the page selection bits
• Automatic updating of the bank selection bits
• Enhanced and compact support of bit operations, including bit functions
• Floating and fixed point math up to 32 bits
• Math libraries including functions like sin(), log(), exp(), sqrt(), etc.
• Supports standard C constant data and strings in program memory (const)
• Automatic storing of compressed 2*7 bit data in each code word if possible
• Pointer models of 8 and 16 bits, mixed sizes in same application allowed
• RAM and/or ROM pointers
• The size of single pointers can be automatically chosen by the compiler
• Linker support (MPLINK), interfaces with assembly (MPASM) modules
• Extended call level by using GOTO instead of CALL when possible
• Inserts links to "hidden" subroutines
• Access to all assembly instructions through corresponding C statements
• Inline assembly
• Lookup tables: #pragma return[] = "Hello world"
• Integrated interrupt support
• Device configuration information in source code
Size (in bits) of the variables supported by the different compiler editions:
FREE STANDARD+EXTENDED
integer 8+16 8+16+24+32
fixed - 8+16+24+32
float 24 16+24+32
8
CC5X C Compiler B Knudsen Data
Installing CC5X is normally done by running the installation program for the latest version. Multiple
versions can be installed.
CC5X is now ready to compile C files. Header and C source files have to be created and edited by a
separate editor (not included), for instance in the MPLAB suite.
The UTF-8 representation of the Byte Order Mark is the byte sequence 0xEF,0xBB,0xBF. This sequence
is allowed in the start of a source file.
The same installation program can be used to un-install the compiler. Alternatively the CC5X files can be
deleted without any un-installation procedure.
-I"C:\Program Files\cc5x"
-IC:\progra~1\cc5x
The alternative to long names is the truncated short format. The truncated form is decided by the file
system. The best guess consists of the 6 first characters of the long name plus ~1. The last number may be
different (~2) if the first 6 characters are equal to another name in the same directory.
User interface
The CC5X compiler is a command-line program that can be run in a console window in the Windows
environment. It requires a list of command line options to compile a C source file and generate the
required files.
Starting CC5X from Windows can be done by clicking on the executable file. The list of compiler
command line options is then written to a console window. The normal way of using CC5X is to use it as
a tool from an integrate environment like MPLAB X.
9
CC5X C Compiler B Knudsen Data
The device header files supplied with the compiler can alternatively be used instead of generating new
header files for each project.
CC5X.EXE : compiler
10
CC5X C Compiler B Knudsen Data
11
CC5X C Compiler B Knudsen Data
/* global variables */
char a;
bit b1, b2;
/* generate 20 pulses */
for ( i = 0; i < 20; i++) {
out = 1;
nop();
out = 0;
}
}
do {
if (in == 0) /* stop if 'in' is low */
break;
sub();
12
CC5X C Compiler B Knudsen Data
// if (some condition)
// goto WARM_RESET;
-p16F883
2) By a pragma statement in the source code. Note that the –p command line option will override the
selection done by #pragma chip. This pragma should not be used in combination with MPLAB.
3) By using include to directly select a header file. This is not recommended because there will be an
error if the command line option is also used.
#include "16f883.h"
NOTE 1: When using a pragma statement or include file, remember to use it in the beginning of the C
program so that it is compiled first. However, some preprocessor statements like #define and #if may
precede the #include/#pragma statement.
NOTE 2: When using the command line option or the pragma statement, CC5X will use the internal
definitions for some devices. If the device is not known internally, automatic include of a header file is
started. The internal known devices are: 16C54,55,56,57,58, 61,64,65, 71,73,74, 84, 620,621,622.
NOTE 3: If the header file does not reside in the default project folder, then the path name is required.
This can be supplied by a command line option as an include folder/directory (-I<path>).
NOTE 4: Debugging means that the debugger may use certain device resources. These resources should
not be used by the application during debugging. The debugger and device documentation should be
consulted. Reservations for some devices are supplied in the device header files. The device header file
should also be inspected. Activating the reservations is done by defining a symbol before the header file
is compiled:
13
CC5X C Compiler B Knudsen Data
Note that using more than one ram bank or code page requires pragma instructions.
Writing programs for the PICmicro microcontroller family requires careful planning. Program and RAM
space are limited, and the key question is often: Will the application code fit into the selected device?
14
CC5X C Compiler B Knudsen Data
2 VARIABLES
The compiler prints information on the screen when compiling. Most important are error messages, and
how much RAM and PROGRAM space the program requires. The compiler output information is also
written to file *.occ. Example:
delay.c:
Chip = 16C74
RAM: 00h : -------- -------- -------- --------
RAM: 20h : ==.***** ******** ******** ********
RAM: 40h : ******** ******** ******** ********
RAM: 60h : ******** ******** ******** ********
RAM: 80h : -------- -------- -------- --------
RAM: A0h : ******** ******** ******** ********
RAM: C0h : ******** ******** ******** ********
RAM: E0h : ******** ******** ******** ********
Optimizing - removed 11 instructions (-14 %)
File 'delay.asm'
Codepage 0 has 68 word(s) : 3 %
Codepage 1 has 0 word(s) : 0 %
File 'delay.hex'
Total of 68 instructions (1 %)
The compiler prints information on RAM allocation. This map is useful to check out which RAM
locations are still free. The map for the 16C57 chip may look like this:
Symbols:
* : free location
- : predefined or pragma variable
= : local variable(s)
. : global variable
7 : 7 free bits in this location
Detailed information on memory allocation is written to file <src>.var when using the –V command line
option.
15
CC5X C Compiler B Knudsen Data
Math libraries may have to be included for math operations (Chapter 6.5 Library Support on page 70).
CC5X uses LOW ORDER FIRST (or little-endian) on variables. This means that the least significant byte
of a variable is assigned to the lowest address. All variables are allocated from low RAM addresses and
upwards. Each RAM location can contain 8 bit variables. Address regions used for special purpose
registers are not available for normal allocation. An error message is produced when there is no space
left.
Special purpose registers are either predefined or defined in chip-specific header files. This applies to W,
INDF, TMR0, PCL, STATUS, FSR, Carry, PD, TO, etc.
Integer variables
unsigned a8; // 8 bit unsigned
char a8; // 8 bit unsigned
unsigned long i16; // 16 bit unsigned
char varX;
char counter, L_byte, H_byte;
bit ready; // 0 or 1
bit flag, stop, semaphore;
16
CC5X C Compiler B Knudsen Data
uns8 1 0 255
uns16 2 0 65535
uns24 3 0 16777215
uns32 4 0 4294967295
Floating point
The compiler supports 16, 24 and 32 bit floating point. The supported 32 bit floating point format can be
converted to and from the IEEE754 format by 3 instructions (macro in math32f.h).
Note that 16 bit floating point is intended for special use where accuracy is less important. More details
on the floating point formats are found in ‘math.txt’. Information on floating point libraries is found in
Chapter 6.5 Library Support on page 70.
Also, after an exception is detected and handled in the application, the exception bit should be cleared so
that new exceptions can be detected. Exceptions can be ignored if this is most convenient. New
operations are not affected by old exceptions. This also enables delayed handling of exceptions. Only the
application program can clear exception flags.
IEEE754 interoperability
The floating point format used is not equivalent to the IEEE754 standard, but the difference is very small.
The reason for using a different format is code efficiency. IEEE compatibility is needed when floating
point values are exchanged with the outside world. It may also happen that inspecting variables during
debugging requires the IEEE754 format on some emulators/debuggers. Macros for converting to and
from IEEE754 are available:
17
CC5X C Compiler B Knudsen Data
math32f.h:
// before sending a floating point value:
float32ToIEEE754(floatVar);
// change to IEEE754 (3 instr.)
math24f.h:
float24ToIEEE754(floatVar);
// change to IEEE754 (3 instr.)
IEEE754ToFloat24(floatVar);
// change from IEEE754 (3 instr.)
fixed8_8 fx;
Convention: fixed<S><I>_<D> :
<S> : 'U' : unsigned
<none>: signed
<I> : number of integer bits
<D> : number of decimal bits
Thus, fixed16_8 uses 16 bits for the integer part plus 8 bits for the decimal, for a total of 24 bits. The
resolution for fixed16_8 is 1/256=0.0039, which is the lowest possible increment. This is equivalent to 2
decimal digits (actually 2.4 decimal digits).
18
CC5X C Compiler B Knudsen Data
To sum up:
1. All types ending on _8 have 2 correct digits after the decimal point
2. All types ending on _16 have 4 correct digits after the decimal point
3. All types ending on _24 have 7 correct digits after the decimal point
4. All types ending on _32 have 9 correct digits after the decimal point
fixed8_8 a = 10.24;
fixed16_8 a = 8 * 1.23;
fixed8_16 x = 2.3e-3;
fixed8_16 x = 23.45e1;
fixed8_16 x = 23.45e-2;
fixed8_16 x = 0.;
fixed8_16 x = -1.23;
Type conversion
The fixed point types are handled as subtypes of float. Type casts are therefore infrequently required.
fixed8_16 a, b;
fixed_16 c;
a = b + c; // OK, code is generated directly
a = b * 10.22; // OK: library function is supplied
19
CC5X C Compiler B Knudsen Data
Examples:
char th @ 0x25;
//bit th1 @ 0x25.1; // overlap warning
bit th1 @ th.1; // no warning
char tty;
bit b0;
char io @ tty;
bit bx0 @ b0;
bit bx2b @ tty.7;
//char tui @ b0; // size exceeded
//long r @ tty; // size exceeded
char tab[5];
long tr @ tab;
struct {
long tiM;
long uu;
} ham @ tab;
An expression can define the address of a variable. This makes it easier to move a collection of variables.
Pragma statements can also be used (limited to bit and char types):
#pragma char port @ PORTC
#pragma char varX @ 0x23
#pragma bit IOpin @ PORTA.1
#pragma bit ready @ 0x20.2
#pragma bit ready @ PA2
20
CC5X C Compiler B Knudsen Data
If the compiler detects double assignments to the same RAM location, this will cause a warning to be
printed. The warning can be avoided if the second assignment uses the variable name from the first
assignment instead of the address (#pragma char var2 @ var1).
The shadowDef type modifier allows local and global variables and function parameters to be assigned to
specific addresses without affecting normal variable allocation. The compiler will ignore the presence of
these variables when allocating global and local variable space.
The above definition allows location 0x70 to be inspected and modified through variable 'gx70'.
Function parameters can be assigned to addresses. No other variables will be assigned by the compiler to
these locations. Such manual allocation can be useful when reusing RAM locations manually.
Parameter transfer can be omitted for functions sharing overlapping parameters. This also applies to bit
parameters:
bit sharedBitPar;
bit func2( bit par @ sharedBitPar ) { /*..*/ return Carry; }
bit func1( bit par @ sharedBitPar ) { /*..*/ return func2( par ); }
const char a; /* ‘const’ tells that compiler that the data is not
modified. This allows global data to be put in program memory. */
volatile char a; /* ignored type modifier. Note that CC5X uses the
address to automatically decide that most of the special purpose
registers are volatile */
21
CC5X C Compiler B Knudsen Data
Local variables
Local variables are supported. The compiler performs a safe compression by checking the scope of the
variables and reusing the locations when possible. The limited RAM space is therefore used efficiently.
This feature is very useful, because deciding which variables can safely overlap is time consuming,
especially during program redesign. Function parameters are located together with local variables.
Variables should be defined in the innermost block, because this allows best reuse of RAM locations. It is
also possible to add inner blocks just to reduce the scope of the variables as shown in the following
example:
void main(void)
{
char i; /* no reuse is possible at the
outermost level of 'main' */
i = 9;
Local variables may have the same name. However, the compiler adds an extension to produce a unique
name in the assembly, list and COD files. When a function is not called (defined but not in use), then all
parameters and local variables are truncated to the same (unused) location.
Local variables will reside in a single block not crossing any bank boundaries. This is a requirement
because of the overlapping/reuse performed within the local block allocated.
The following pragma will define a single main stack. The main stack is not an additional stack, but tells
the compiler where the main stack is located (which bank).
22
CC5X C Compiler B Knudsen Data
Using this pragma means that local variables, parameters and temporary variables of size 3 bytes and
larger (including tables and structures) will be stored in a single stack allocated no lower than address
0x20. Smaller variables and variables with a bank modifier will be stored according to the default/other
rules. Using size 0 means all variables including bit variables.
Note that the bank defined by #pragma rambank is ignored for variables stored in the main stack.
Addresses ranging from 0x20 to 0x6F/0x7F are equivalent to the bank0 type modifier.
In some cases it will be efficient to use shared RAM or a specific bank for local variables up to a certain
size. This is possible by using the following pragma:
In this case, local variables, parameters and temporary variables up to 2 bytes will be put in shared RAM
from address 0x70 and upward. Larger variables and variables with a bank modifier will be stored
according to the default/other rules. Using size 0 means bit variables only. This pragma can be used in
combination with the main stack. The variable size defined by the minor stack has priority over the main
stack.
The most efficient RAM usage is to use a single stack. Separation into different stacks increases total
RAM usage, and should be avoided if possible.
Temporary variables
Operations like multiplication, division, modulo division and shifts often require temporary variables.
However, the compiler needs NO PERMANENT SPACE for temporary variables.
The temporary variables are allocated the same way as local variables, but with a narrow scope. This
means that the RAM locations can be reused in other parts of the program. This is an efficient strategy
and often no extra space is required in application programs.
tx[i] = 10000;
Normal C structures can be defined, as can nested types. Unions are allowed.
struct hh {
long a;
char b;
} vx1;
union {
23
CC5X C Compiler B Knudsen Data
struct {
char a;
int16 i;
} pp;
char x[4];
uns32 l;
} uni;
The equivalent of a (small) multidimensional array can be constructed by using a structure. However,
only one index can be a variable.
struct {
char e[4];
char i;
} multi[5];
multi[x].e[3] = 4;
multi[2].e[i+1] += temp;
Arrays greater than 80 bytes are allocated to multiple banks by the compiler. Such a large array does not
belong to a specific bank. The compiler will automatically handle the required mapping. Data items up to
80 bytes are allocated first. Then the large data items are allocated. A data item up to 80 bytes can only
cross a bank boundary if it is assigned a specific address (type variable @ address;). Large data items can
also be assigned to specific addresses.
Bitfields
Bitfields in structures are allowed. The size has to be 1, 8, 16, 24 or 32 bits.
struct bitfield {
unsigned a : 1;
bit c;
unsigned d : 32;
char aa;
} zz;
The CC5X compiler also allows the bitfield syntax to be used outside structures as a general way of
defining variable size:
Typedef
Typedef allows defining new type identifiers consisting of structures or other data types:
24
CC5X C Compiler B Knudsen Data
#pragma rambank 1
#pragma rambank 0
The compiler automatically finds the first free location in the selected bank.
NOTE: Local variables and function parameters also have to be located. It may be necessary to use
#pragma rambank between some of the functions and even INSIDE a function. The recommended
strategy is to locate local variables and function parameters in mapped RAM or bank 0.
Mapped/unbanked RAM is selected by:
#pragma rambank –
The bank type modifier defines the RAM bank to locate the variable. It can locate global variables,
function parameters and local variables. The bank type modifier applies to the variable itself, but not to
the data accessed. This difference is important for pointers.
NOTE 1: The bank type modifier has higher priority than #pragma rambank.
NOTE 2: Using 'extern' makes it possible to state the variable definition several times. However, the first
definition defines the rambank, and later definitions must use the same bank.
NOTE 3: When defining a function prototype, this will normally not locate the function parameters.
However, when adding a bank type modifier to a function parameter in a prototype, this will define the
bank to be used for this variable.
If variables are located in non-existing RAM banks for a device, these variables are mapped into existing
RAM banks (bank 0). This applies to the bank type modifiers and the #pragma rambank statement.
Using RAM banks requires some planning. The optimal placement requires the least code to update the
bank selection bits. Some advice when locating variables:
1. Try to locate variables which are close related to each other in the same bank.
2. Try to locate all variables accessed in the same function in the same bank.
25
CC5X C Compiler B Knudsen Data
3. Switching between bank 0 and 3, or bank 1 and 2 require more instructions than the other
combinations. Note that this does not apply to the Enhanced 14 bit core.
4. Use as few banks as possible. Fill bank 0 first, then bank 1, etc.
5. Remember that local variables and function parameters also may require updating of the bank
selection bits.
The bank selection bits are automatically checked and updated by the compiler, and attempts to set or
clear these bits in the source code are removed by the compiler. This feature can be switched off, which
means that correct updating has to be done in the source code.
The compiler uses global optimizing techniques to minimize the extra code needed to update the bank
selection bits. Removing all unnecessary updating is difficult. However, there should be few redundant
instructions.
NOTE: The compiler REMOVES all bank updating done by the user. However, it is possible to switch to
manual updating with the -b command line option, or locally by a pragma statement.
These statements can be inserted anywhere, but they should surround the smallest possible region. Please
check the generated assembly code to ensure that the desired result is achieved. Another use of #pragma
updateBank is to instruct the bank update algorithm to do certain selections. Refer to Section #pragma
updateBank on page 57 for more details.
NOTE: The safest coding is to not assume any specific contents of the bank selection bits when a local
update region is started. The compiler uses complex rules to update the bank selection bits outside the
local regions. Also, all updating inside a local update region is traced to enable optimal updating when the
local update region ends.
26
CC5X C Compiler B Knudsen Data
2.4 Pointers
Single level pointers are implemented. Note that pointer arithmetic is limited to 8 bit. Assignment is
allowed for 8, 16, 24 and 32 bit.
p = &t[1];
*p = 100;
p[2] ++;
Pointer models
Using 8 bit pointers when possible saves both code and RAM space. CC5X allows the size of all single
pointers to be decided automatically. However, pointers in structures and arrays have to be decided in
advance, by using the memory model command line options or a size type modifier. Note that the
operator ‘sizeof(pointer)’ will lock the size according to the chosen default model. Using sizeof(pointer)
is normally not required and should be avoided.
Default pointer sizes are used only when the pointer size is not chosen dynamically. The priority when
deciding the pointer size is:
1) Pointer size type modifiers
2) Automatically chosen pointer size (single pointers)
3) Pointer size chosen according to the default model
Certain pointer operation will generate warnings. The warnings can be removed by adding a proper type
cast. The first warning can be disabled by command line option -wx. The other two warnings be disabled
by command line option -wz.
27
CC5X C Compiler B Knudsen Data
f) 16 bit pointer to RAM or program memory. Bit 15 is used to detect RAM or program memory
access.
a = t[i];
s[i] = e;
s[i+3] = e;
The last three statements requires that variable e is located in mapped RAM (below 0x10) or in the same
bank as array s[]. Otherwise an error message is printed to indicate that the compiler cannot update the
bank selection bits.
#pragma rambank 3
char *px, r;
#define LTAB 5
char tab[LTAB];
#pragma assume *px in rambank 3
px = &tab[0];
*px = r;
if (++px == &tab[LTAB])
px = &tab[0];
A pointer may access more than one bank. The #pragma assume statement should NOT be used in such
cases. The only difference is that the compiler will know the contents of the FSR.5,6 when a variable in a
specific bank is accessed. Therefore, a statement like:
*pointer_to_any_rambank = e;
Note that the #pragma assume statement works for single pointers (and pointers in arrays), but not for
pointers located in structures.
i = 0;
// ..
tab[i] = r;
if (++i == LTAB)
i = 0;
28
CC5X C Compiler B Knudsen Data
FSR = px;
INDF = i;
Variable i have to reside in mapped RAM. The compiler performs the checking when INDF is accessed.
The compiler does not try to trace the contents of FSR when it is loaded directly. Therefore, a statement
like *px = r; is normally preferred.
Using #pragma assume *px in rambank 3 also makes loading of px more restrictive. An error message is
printed if px is loaded with an address in another bank. The following cases are checked:
A statement like px = &tab[i]; may fool the compiler if the value of i is too large.
If the above syntax is too restrictive, then a local update region is the solution. All bank updating then
have to be done with C statements. Normally, local update regions require inspection of the generated
assembly file to avoid problems.
i = LTAB;
do
tab[i-1] = 0;
while (--i > 0);
In this example, the local update region only has a speed advantage. The same amount of instructions is
generated. Note that although no bank updating is required inside the above local region, the compiler
does not know the contents of FSR.5,6 at the end of the region, and will therefore update these bits
afterwards.
#pragma rambank 2
char array[50];
char x;
29
CC5X C Compiler B Knudsen Data
NOTE: IRP is not updated by the compiler if INDF is used directly in the user code. Using array[x]
instead of INDF enables automatic updating of the IRP bit.
The compiler will trace all loading of pointers to decide how the IRP bit should be updated. This applies
to both 8 and 16 bit pointers.
An error message is printed if a pointer is loaded with an address from the wrong RAM half. Note that
bank 0 and 1 are grouped together (the lower RAM half, 0 - 0xFF). Bank 2 and 3 are the upper RAM half
(0x100 - 0x1FF).
Updating of IRP can be switched off locally. The compiler does not remove superfluous updating of the
IRP register. This means that IRP is updated for each pointer or table access.
An efficient strategy may be to locate (most of) the tables in upper or lower RAM (above or below
address 0x100), and do all updating of IRP in the user code. Few updates are sometimes sufficient.
30
CC5X C Compiler B Knudsen Data
Recommendations:
It is recommended to use small data tables and structures. This allows the compiler to merge equal data
items and build optimal blocks of constant data.
Limitations:
1) The compiler will not initialize RAM variables on startup
2) Data items of 16 bits or more in structures with more than 256 bytes of data must be aligned
When a constant table contains less than 256 byte of data, there will be a tradeoff between speed and size.
Using a return table executes faster but requires more code when the table contains more than 40-50 bytes
of data. If speed is required, the following pragma statement defines a new limit for size optimization.
Code pages
When using devices with more than one codepage, the compiler will automatically calculate the optimal
codepage for the data. The disadvantage is that the compiler will not know when a codepage is full, so the
functions still have to be moved manually between codepages to find allowed and optimal combinations.
Also, const data can be located on a specific codepage by using a page type modifier.
The compiler will group the const data (including strings) into "storage classes" depending on data types,
optimization and how they are accessed.
31
CC5X C Compiler B Knudsen Data
Data belonging to the same storage class are accessed by the same _constX access function generated by
the compiler.
The general rule is that all const data accessed by the same pointer belongs to the same storage class.
It is sufficient to use a page type modifier on one of the const data items in a storage class, then all data
belonging to that storage class will be stored on that codepage. This can be used to split large amount of
const data into separate codepages.
Strings are sometimes harder to force into specific codepages. However, since equal strings are merged
together by the compiler it is possible to define an unused data item with a known string used somewhere
else to force a specific group of strings to a specific codepage. The unused string will not consume any
code space. Example:
#pragma insertConst
Merging data
The compiler will automatically merge equal strings and sub-strings, and also other data items. Using
small tables will increase the chance of finding data items that can be merged. Note that data containing
initialized addresses (ROM and RAM) are not merged. Examples:
1. The string "world!" is identical to the last part of the string "Hello world!". It is therefore not required
to use additional storage for the first string. The compiler handles the address calculations so that
merged (or overlapping) strings are handled fully automatically. Note that the string termination '\0'
also has to be equal, otherwise merging is not possible. For example, the string "world" cannot be
merged with the above strings.
2. Merging applies to all kinds of data. Data is compared byte by byte. This allows the first two of the
following tables to be merged with the last one.
Examples
A table of pointers to strings:
const struct {
const char *s;
} tb[] = {
"Hello world",
"Monday",
"",
"world" // automatically merged with first string
};
32
CC5X C Compiler B Knudsen Data
t = *p++; // char t;
t = p[x]; // char x;
Note that 'const struct' is required to put the pointer array in program memory. Using 'const char *tx[];'
means that the strings reside in program memory, but the table 'tx[]' resides in RAM.
String parameters:
It is possible to read and assign the address of the const table, but without any operations. All access of
data within this type of tables must be done by an application access function. It is not possible to use a
table index read (dataTable[i]), fixed offset (dataTable[5]) or pointers.
33
CC5X C Compiler B Knudsen Data
3 SYNTAX
3.1 Statements
C statements are separated by semicolons and surrounded by block delimiters:
{ <statement>; .. <statement>; }
if statement
if (<condition>)
<statement>;
else if (<condition>)
<statement>;
else
<statement>;
while statement
while (<condition>)
<statement>;
for statement
for (<initialization>; <condition>; <increment>)
<statement>;
34
CC5X C Compiler B Knudsen Data
do statement
do
<statement>;
while (<condition>);
switch statement
The switch statement supports variables up to 32 bits. The generated code is more compact and executes
faster than the equivalent 'if - else if' chain.
switch (<variable>) {
case <constant1>:
<statement>; .. <statement>;
break;
case <constant2>:
<statement>; .. <statement>;
break;
..
default:
<statement>; .. <statement>;
break;
}
switch (token) {
case 2:
i += 2;
break;
case 9:
case 1:
default:
if (PORTA == 0x22)
break;
case 'P':
pin1 = 0; i -= 2;
break;
}
break statement
The ‘break;’ statement is used inside loop statements (for, while, do) to terminate the loop. It is also used
in switch statements.
35
CC5X C Compiler B Knudsen Data
while (1) {
..
if (var == 5)
break;
..
}
continue statement
The ‘continue;’ statement is used inside loop statements (for, while, do) to force the next iteration of the
loop to be executed, skipping any code in between. In while and do-while loops, the loop condition is
executed next. In for loops, the increment is processed before the loop condition.
return statement
return <expression>; /* exits the current function */
goto statement
goto <label>;
goto XYZ;
..
XYZ:
..
var1 = x + y;
i = x - 100;
y ^= 'A'; // y = y ^ 'A';
W |= 0x10; // W = W | 0x10;
a = b = c + 1; // multiple assignment
36
CC5X C Compiler B Knudsen Data
W = W - 3; // ADDLW 256-3
b = fx() - 3;
// pre-incrementing of variables
t = ++b | 3;
sum( --b, 10);
t = tab[ --b];
Conditions
[ ++ | -- ] <variable> <cond-oper> <value>
[ && condition ]
[ || condition ]
if (x == 7) ..
if (Carry == 1 && a1 < a2) ..
if (y > 44 || Carry || x != z) ..
if (--index > 0) ..
if (bx == 1 || ++i < max) ..
if (sub_1() != 0) ..
Bit variables
bit a, b, c, d;
char i, j, k;
b = !charfun();
b = charfun() > 0;
b = !bitfun();
Carry = bitfun();
b &= bitfun();
37
CC5X C Compiler B Knudsen Data
if (bitfun() == b) ..
if (bitfun() == PORTA.1) ..
i += b; // conditional increment
i -= b; // conditional decrement
i = k+Carry;
i = k-Carry;
b = !b; // Toggle bit (or b=b==0;)
b = !c; // assign inverted bit
PORTA.0 = !Carry;
a &= PORTA.0;
PORTA.1 |= a;
PORTA.2 &= a;
The division algorithm also allows most combinations of variable sizes. Shortcuts are made when
dividing by 2 (or 2*2*..). These are treated as right shifts.
Precedence of C operators
Highest: ( )
++ --
* / %
+ -
<< >>
< <= > >=
== !=
&
^
|
&&
||
Lowest: = += -= *= /= etc.
38
CC5X C Compiler B Knudsen Data
Most combinations of variables are allowed; the compiler performs sign extension as required. Multiple
operations in the same expression are allowed when using 8 bit variables.
a8 = b8 + c8 + d8 + 10;
3.3 Constants
x = 34; /* decimal */
x = 0x22; /* hexadecimal */
x = 'A'; /* ASCII */
x = 0b010101; /* binary */
Constant expressions
The size of integers is by default 8 bits for this compiler (other C compilers typically use 16 or 32 bits
depending on the CPU capabilities). An error is printed if the constant expression loses significant bits
because of value range limitations.
char a;
a = (10 * 100) / 256; // an error is printed
a = (10L * 100) / 256; // no error
a = ((uns16) 10 * 100) / 256; // no error
a = (uns16) (10 * 100) / 256; // error again
a = (10 * 200) / 256; // no error, 200 is a long int
The command line option -cu forces 32 bit evaluation of constants so that no significant bits are lost.
39
CC5X C Compiler B Knudsen Data
The constant type is by default the shortest signed integer. Adding a U behind a constant means that it is
treated as unsigned. Note that constants above 0x7FFFFFFF are unsigned by default (with or without a U
behind).
Enumeration
An enumeration is a set of named integer constants. It can often replace a number of #define statements.
The numbering starts with 0, but this can be changed:
enum { A1, A2, A3, A4 };
typedef enum { alfa = 8, beta, zeta = -4, eps, } EN1;
EN1 nn;
enum con { Read_A, Read_B };
enum con mm;
mm = Read_A;
nn = eps;
3.4 Functions
Function definitions can appear as follows:
void subroutine2(char p) { /* C statements */}
bit function1(void) { }
long function2(char W) { }
void main(void) { }
Function calls:
subroutine1();
subroutine2(24);
bitX = function1();
x = function2(W);
y = fx1(fx3(x));
The compiler needs to know the definition of a function before it is called to enable type checking. A
prototype is a function definition without statements. Prototypes are useful when the function is called
before it is defined. The parameter name is optional in prototypes:
char function3(char);
void subroutine1(void);
The least significant byte is always placed in W when using 14 bit core devices. Signed variables and
variables larger than 8 bits also use temporary variables on the computed stack. The 12 bit core use the W
register when returning 8 bit constants. All other return values are placed in return variables on the
computed stack.
A function can return any value type. The W register is used for an 8 bit return value if possible. The
Carry flag is used for bit return values. The compiler will automatically allocate a temporary variable for
other return types. A function with no return value is of type void.
40
CC5X C Compiler B Knudsen Data
Internal functions
The internal functions provide direct access to certain inline code:
btsc(Carry); // void btsc(char); - BTFSC f,b
btss(bit2); // void btss(char); - BTFSS f,b
clrwdt(); // void clrwdt(void); - CLRWDT
clearRAM(); // void clearRAM(void); clears all RAM
f = decsz(f); // char decsz(char); - DECFSZ f,d
W = incsz(f); // char incsz(char); - INCFSZ f,d
nop(); // void nop(void); - NOP
nop2(); // void nop2(void); - GOTO next address
retint(); // void retint(void); - RETFIE
W = rl(f); // char rl(char); - RLF f,d
f = rr(f); // char rr(char); - RRF f,d
sleep(); // void sleep(void); - SLEEP
skip(i); // void skip(char); - computed goto
f = swap(f); // char swap(char); - SWAPF f,d
Additional internal functions are available for the enhanced core 14:
The internal rotate functions are also available for the larger variable sizes:
The inline function nop2() is implemented by a GOTO to the next address. Thus, nop2() can replace two
nop() to get more compact code. The main use of nop() and nop2() is to design exact delays in timing
critical parts of the application.
a = b + c;
consists of 2 separate operations. The first is the plus operation and the second is the assignment. The
type conversion rules are first applied to b+c. The result of the plus operation and a are treated last.
The CC5X compiler uses 8 bit int size and contains many data types (integers, fixed and floating point).
The type cast rules have been set up to provide best possible compatibility with standard C compilers
(which typically uses 16 or 32 bit int size).
41
CC5X C Compiler B Knudsen Data
NOTES:
• The sign is extended before the operand is converted to unsigned.
• Assignment is also an operation.
• The char type is unsigned
• Constants are SIGNED, except if U is added.
• The bit type is converted to unsigned char.
• The fixed point types are handled as subtypes of float.
Type conversion in C is difficult. The compiler may generate a warning if a type cast is required to make
the intention clear. Remember that assignment (=) is a separate operation. The separate operations are
marked (1:), (2:) and (3:) in the following examples.
uns16 a16;
uns8 b8, c8;
int8 i8, j8;
a16 = b8 * c8; /* (1:) In this case both b8 and c8 are 8 bit unsigned, so the type of the multiplication is 8
bit unsigned. (2:) The result is then assigned to a 16 bit unsigned variable, a16. Converting the 8 bit
unsigned result to 16 bit unsigned means clearing the most significant bits of a16. The compiler generates
a warning because significant bits of the multiplication are lost due to the type conversion rules. */
a16 = (uns16) (b8 * c8); /* (1:) Adding parentheses just isolates the multiplication and the multiplication
result is still 8 bit unsigned. (2:) The (uns16) type cast is not needed because this type cast is done
automatically before the assignment. The compiler generates a warning because significant bits of the
multiplication are lost due to the type conversion rules. */
a16 = (uns16) b8 * c8; /* (1:) Converting one of the arguments to 16 bit unsigned BEFORE the
multiplication is the right syntax to get a 16 bit result. (2:) The result and the destination a16 now have
the same type for the assignment and no type conversion is needed. */
a16 = (uns8) (b8 * c8); /* (1:) The multiplication result is 8 bit unsigned. (2:) The (uns8) type cast tells
the compiler that the result should be 8 bit unsigned, and no warning is generated even though it looks
like significant bits of the multiplication are lost. */
a16 = b8 * 200; /* (1:) Constant 200 is a 16 bit signed constant (note that 200U is an 8 bit unsigned
constant, and that 127 is the largest 8 bit signed constant). Argument b8 is therefore automatically
converted to 16 bit. The constant is then converted to unsigned and the result is 16 bit unsigned. (2:) The
result and the destination a16 now have the same type for the assignment and no type conversion is
needed. */
a16 = (int16) i8 * j8; /* (1:) Both arguments are converted to 16 bit signed and the result is 16 bit signed.
(2:) The result is converted to unsigned before the assignment, but this does not mean any real change
when the size is the same (example: -1 and 0xFFFF have the same 16 bit representation). */
a16 = (uns16) (uns8)i8 * (uns8)j8; /* (1:) To get an 8*8 bit unsigned multiplication it is necessary to cast
both arguments to unsigned before extending the size to 16 bit unsigned. Otherwise the sign bit will be
extended and the multiplication will need more code and cycles to execute. (2:) The result and the
destination a16 now have the same type for the assignment and no type conversion is needed. */
a16 = ((uns16) b8 * c8) / 3; /* (1:) Converting one of the arguments to 16 bit unsigned before the
multiplication gives a 16 bit result. (2:) Division is the next operation and is using the 16 bit unsigned
multiplication result. Constant 3 is 8 bit signed, and is then automatically converted to 16 bit signed and
further to 16 bit unsigned. The result of the division is 16 bit unsigned. (3:) The division result and the
destination a16 now have the same type for the assignment and no type conversion is needed. */
42
CC5X C Compiler B Knudsen Data
uns32 a;
a.7 = 1; // set bit 7 of variable a to 1
if (a.31 == 0) // test bit 31 of variable a
t[i].4 = 0; // bit 4 of the i'th element
uns16 a;
uns32 b;
a.low8 = 100; // set the least significant 8 bits
a = b.high16; // load the most significant 16 bits
The table shows which bits are accessed depending on the variable size in bytes (1,2,3,4) and the sub-
index used. The * indicates normal use of the sub-index:
1 2 3 4
------ ------ ------- -------
low8 0-7 * 0-7 * 0-7 * 0-7
high8 0-7 * 8-15 * 16-23 * 24-31
mid8 0-7 8-15 * 8-15 8-15
midL8 0-7 8-15 8-15 * 8-15
midH8 0-7 8-15 16-23 * 16-23
low16 0-7 0-15 * 0-15 * 0-15
mid16 0-7 0-15 8-23 * 8-23
high16 0-7 0-15 * 8-23 * 16-31
low24 0-7 0-15 0-23 * 0-23
high24 0-7 0-15 0-23 * 8-31
3.7 C Extensions
CC5X adds some extensions to the standard C syntax:
43
CC5X C Compiler B Knudsen Data
3. Local variables can be declared between statements as in C++. Standard C requires local variables to
be defined in the beginning of a block.
5. Preprocessor statements can be put into macros. Such preprocessor statements are not extended to
multiple lines. The inserted preprocessor statements are evaluated when the macro is expanded, and not
when it is defined.
#define MAX \
{ \
a = 0; \
#if AAA == 0 && BBB == 0 \
b = 0; \
#endif \
}
6. Several of the type modifiers are not standard in C (page0..page3, bank0..bank3, shrBank, size1,size2)
The following names are defined as internal functions, and are translated into special instructions or
instruction sequences.
btsc, btss, clearRAM, clrwdt, decsz, incsz, nop, nop2, retint, rl,
rr, sleep, skip, swap, addWFC, subWFB, lsl, lsr, asr, softReset
The remaining standard C keywords are detected and compiled. One is ignored (register), and the rest
cause a warning to be printed (volatile, line).
44
CC5X C Compiler B Knudsen Data
45
CC5X C Compiler B Knudsen Data
Evaluation of constant expression is slightly changed from version 2.x in order to adapt to standard C. An
error message is printed if significant bits are lost. The cure is to use type conversion.
a = (uns16) 10 * 100;
Alternatively will the command line option -cu force 32 bit evaluation of constant expressions. The
option -wS changes the error message to a warning.
46
CC5X C Compiler B Knudsen Data
4 PREPROCESSOR DIRECTIVES
The preprocessor recognizes the following keywords:
A preprocessor line can be extended by putting a '\' at the end of the line. This requires that there are no
space characters after the '\'.
#define
#define counter v1
#define MAX 145
#define echo(x) v2 = x
#define mix() echo(1) /* nested macro */
Note that all #define's are global, even if they are put inside a function.
Macro concatenation
The concatenation operator ## allows tokens to be merged while expanding macros. Examples:
Macro stringification
The stringification operator # allows a macro argument to be converted into a string constant. Examples:
47
CC5X C Compiler B Knudsen Data
#define str(s) #s
#define xstr(s) str(s)
#define foo 4
#define WARN_IF(EXP) \
do { if (EXP) \
warn("Warning: " #EXP "\n"); } \
while (0)
#include
#include "test.h"
#include <test.h>
#include's can be nested. When using #include "test.h" the current directory is first searched. If the file is
not found there, then the library directories are searched, in the same order as supplied in the command
line option list (-I<dir>). The current directory is skipped when using #include <test.h>.
Macros can be used in #include files. The following examples show the possibilities. Note that this is not
standard C.
#undef
#define MAX 145
..
#undef MAX /* removes definition of MAX */
#undef does the opposite of #define. The #undef statement will not produce any error message if the
symbol is not defined.
#if
#if defined ALFA && ALFA == 1
..
48
CC5X C Compiler B Knudsen Data
An arbitrary complex constant expression can be supplied. The expression is evaluated the same way as a
normal C conditional statement is processed. However, every constant is converted to a 32 bit signed
constant first.
#ifdef
#ifdef SYMBOL
..
/* Statements compiled if SYMBOL is defined.
Conditional compilation can be nested. SYMBOL
should not be a variable or a function name. */
#endif
#ifndef
#ifndef SYMBOL
/* statements compiled if SYMBOL is not defined */
#endif
#elif
#ifdef AX
..
#elif defined BX || defined CX
/* statements compiled if AX is not
defined, and BX or CX is defined */
#endif
#else
#ifdef SYMBOL
..
#else
/* statements compiled if SYMBOL is not defined */
#endif
#endif
#ifdef SYMBOL
..
#endif /* end of conditional statements */
#error
#error This is a custom defined error message
The compiler generates an error message using the text found behind #error.
49
CC5X C Compiler B Knudsen Data
#warning
#warning This is a warning
The following output is produced. Note that this directive is not standard C.
Warning test.c 7: This is a warning
#message
#message This is message 1
The following output is produced. Note that this directive is not standard C.
Message: This is message 1
#pragma alignLsbOrigin 0
#pragma alignLsbOrigin 2 to 100
#pragma alignLsbOrigin 0 to 190 // [-255 .. 255]
#pragma alignLsbOrigin -100 to 10
Such alignment is useful to make sure that a computed goto does not cross a 256 word address boundary.
More details are found in Section Origin alignment on page 114 in Chapter 9.2 Computed Goto. This type
of alignment does not apply to the 12 bit core.
#pragma asm2var 1
Enable equ to variable transformation. This is defined in Chapter 6.6 Inline Assembly on page 79.
NOTE: If the compiler detects double assignments to the same RAM location, this will cause a warning
to be printed. The warning can be avoided if the second assignment uses the variable name from the first
assignment instead of the address (#pragma bit var2 @ var1).
50
CC5X C Compiler B Knudsen Data
ADDRESS: 0 .. 0x7FFE
VXS : < VALUE | EXPRESSION | STRING>
VALUE: 0 .. 0x3FFF
EXPRESSION: any valid C constant expression,
i.e. 0x1000 | (3*1234)
STRING: "Valid C String\r\n\0\x24\x8\xe\xFF\xff\\\""
NOTE: If the compiler detects double assignments to the same RAM location, this will cause a warning
to be printed. The warning can be avoided if the second assignment uses the variable name from the first
assignment instead of the address (#pragma char var2 @ var1).
This statement has to precede any normal C statements, but some preprocessor statements, like #if and
#define, can be compiled first.
The supported devices are either known internally (16C54,55,56,57,58, 61,64,65, 71,73,74, 84,
620,621,622) or defined in a PICmicro header file (e.g.16F877.h). It is also possible to make new header
files. Refer to file ‘chip.txt’ for details.
Defines the codepage to be used. Code is located at the start of the active codepage, or from the current
active location on that page. The codepage cannot be changed inside a function. Non-existing pages for a
specific device are mapped into existing ones.
#pragma codepage 3
/* following functions are located on codepage 3 */
51
CC5X C Compiler B Knudsen Data
In order to use symbolic config register setting there must be a symbolic config definition. This is
normally found in the device header file:
For the first config register it is also possible use the '&=' and the '|=' operators. The default setting of the
config bits are 0 when using these operators:
52
CC5X C Compiler B Knudsen Data
Some devices use a different physical address of the configuration word compared to the default logical
address established. The chip programming software will normally map the configuration word in these
cases.
#pragma inlineMath 1
a = b * c; // inline integer code is always generated
#pragma inlineMath 0
#pragma insertConst
The compiler will normally insert 'const' data at the start of each codepage (after the interrupt routine).
The #pragma insertConst statement will allow 'const' data for the current codepage to be inserted between
user functions, or at a specific address when using #pragma origin first. The current codepage can also be
set by using #pragma codepage.
#pragma library 1
// functions defined here are deleted if unused
// applies to prototypes and function definitions
#pragma library 0
53
CC5X C Compiler B Knudsen Data
Using this pragma means that local variables, parameters and temporary variables of size 3 bytes and
larger (including tables and structures) will be stored in a single stack allocated no lower than address
0x20. Smaller variables and variables with a bank modifier will be stored according to the default/other
rules. Size 0 means all variables including bit variables.
Note that #pragma rambank is ignored for variables stored in the main stack. Addresses ranging from
0x20 to 0x6F/0x7F are equivalent to the bank0 type modifier.
In this case, local variables, parameters and temporary variables up to 2 bytes will be put in shared RAM
from address 0x70 and upward. Larger variables and variables with a bank modifier will be stored
according to the default/other rules. Size 0 means bit variables only. This pragma can be used in
combination with the main stack. The variable size defined by the minor stack has priority over the main
stack.
N Function
1. redirect goto to goto.
2. remove superfluous gotos.
3. replace goto by skip instructions.
4. remove instructions that affect the zero-flag only.
5. replace INCF and DECF by INCFSZ and DECFSZ.
6. remove superfluous updating of page selection bits.
7. remove other superfluous instructions.
8. remove superfluous loading of W.
Examples:
#pragma optimize 0 /* ALL off */
#pragma optimize 1 /* ALL on */
#pragma optimize 2:1 /* type 2 on */
#pragma optimize 1:0 /* type 1 off */
54
CC5X C Compiler B Knudsen Data
NOTE: The command line option -u will switch optimization off globally, which means that all settings
in the source code are ignored.
Examples:
#pragma origin 4 // interrupt start address
#pragma origin 0x700 + 2
#pragma rambank defines the region(s) where the compiler will allocate variable space. The compiler
gives an error message when all locations in the current bank are allocated.
RAM banks are only valid for some of the devices. Non-existing banks for the other devices are mapped
into defined RAM space.
12 bit core note: The locations from address 0 to 31 are treated as a unit. Using start address 7 means that
locations in the mapped register space and bank 0 are allocated. Using start address 32 implies that
locations in the mapped register space are allocated.
NOTE: The start address is not valid for local variables, but rambase can be used to select a specific
RAM-bank.
55
CC5X C Compiler B Knudsen Data
skip(W);
#define NoH 11
#pragma return[NoH] = "Hello world"
#pragma return[5] = 1, 4, 5, 6, 7
#pragma return[] = 0 1 2 3 44 'H' \
"Hello" 2 3 4 0x44
#pragma return[]= 'H' 'e' 'l' 'l' 'o'
#pragma return[3] = 0b010110 \
0b111 0x10
#pragma return[9] = "a \" \r\n\0"
#pragma return[] = (10+10*2), (0x80+'E') "nd"
#pragma return[] = 10000 : 16 /* 16 bit constant */ \
0x123456 : 24 /* 24 bit constant */ \
(10000 * 10000) : 32 /* 32 bit constant */
#pragma sharedAllocation
This pragma allows functions containing local variables and parameters to be shared between
independent call trees (interrupt and the main program). However, when doing this there will be a risk of
overwriting these shared variables unless special care is taken. Further description is found in Section
“Functions shared between independent call trees” in Chapter 6.2 Subroutine Call Level Checking.
#pragma unlockISR
The interrupt routine normally has to reside at address 4. The following pragma statement will allow the
interrupt routine to be placed anywhere. Note that the compiler will NOT generate the link from address 4
to the interrupt routine.
#pragma unlockISR
56
CC5X C Compiler B Knudsen Data
Another use of #pragma updateBank is to instruct the bank update algorithm to do certain selections.
These statements can only be used inside functions:
These statements can be inserted anywhere, but they should surround a region as small as possible.
57
CC5X C Compiler B Knudsen Data
These statements can be inserted anywhere, but they should surround a region as small as possible.
Option -VG or -Vg will list the available symbolic config settings at the end of the *.var file generated for
the project. This list can be copied to a project C source file and modified to desired settings.
The config symbols are found at at the end of the device header file. Example definitions:
58
CC5X C Compiler B Knudsen Data
It is possible to disable the symbolic config definitions found in the header files for backward
compatibility with the fixed config symbols in compiler versions older than version 3.6.
For the first config register it is also possible use the '&=' and the '|=' operators. The default setting of the
config bits are 0 when using these operators.
It is possible to use the STANDARD MPASM identifiers for defining to configuration bits. See example
in file 'config.txt'.
Programming of ID-locations:
#pragma config ID=0x1234 // all 4 locations, 4*4 bit
#pragma config ID[0] = 0xF // location 0
#pragma config ID[1] = 0x1 // location 1
#pragma config ID[2]=1, ID[3]=0x2
59
CC5X C Compiler B Knudsen Data
60
CC5X C Compiler B Knudsen Data
-f<hex-file-format> : i.e. INHX8M, INHX8S, INHX16, INHX32. Default is INHX32 for enhanced 14
bit devices, otherwise INHX8M. Note that INHX8S uses two output files: <file>.HXH and <file>.HXL
-O<folder> : output files folder. Files generated by the compiler are put on this folder, except when a full
path name is supplied.
61
CC5X C Compiler B Knudsen Data
-p<device> : defines the chip type. The device has to be known internally: 16C54,55,56,57,58, 61,64,65,
71,73,74, 84 or supported by a header file (e.g., 16F877.H). Default device is 16C54.
-q<N> : assume disabled interrupt at the <N> deepest call levels. For example, –q1 allows the main
program to use all stack levels for function calls. Disabling interrupts at the deepest call level MUST then
be properly ensured in the user application program.
-u : no optimizing
A path name can be written using '/' if this is supported by the file system, for example:
c:/compiler/lib/file.h
62
CC5X C Compiler B Knudsen Data
Many option files can be included, and up to 5 levels of nested include files are allowed. Options in a file
allow an unlimited number of options to be stated. Linefeed, space and TAB separates each option.
Comments can be added in the option file using the syntax:
Spaces can be added to each option if a space is added after the '-' starting the option. This syntax disables
using more than one option on each line. Examples:
- D MAC = 1 + OP
- p 16C54 // comment
-p 16C54 // this will not work
- p 15C64 -a // not this either
Note that the file path is required if the file does not reside on the current directory.
1. Option : -ver#verfile.c
#include "verfile.c" // or <verfile.c>
2. Option : -ver
#pragma versionFile // next include is version file
63
CC5X C Compiler B Knudsen Data
3. Option : -ver
#pragma versionFile "verfile.c" // or <verfile.c>
Note that the command line option is required to make this increment happen. It is the decimal number
found at end of the included file that is incremented. The updated file is written back before the file is
compiled. No special syntax is assumed in the version file. Suggestions:
#define MY_VERSION 20
#define VER_STRING "1.02.0005"
/* VERSION : 01110 */
If the decimal number is 99, then the new number will be 100 and the file length increases by 1. If the
number is 099, then the file length remains the same. A version file should not be too large (up to 20k),
otherwise an error is printed.
Formats 2 and 3 above allow more than one version file. It is recommended to use conditional
compilation to manage several editions of the same program.
The variable CCINC is an alternative to the -I<path> option. The compiler will only read this variable (or
specified variable) when using the following command line option:
Variable CCHOME can be used to define the primary folder during compilation. The compiler will only
read this variable (or specified variable) when using the following command line option:
64
CC5X C Compiler B Knudsen Data
6 PROGRAM CODE
#pragma codepage 2
char fx(void) { .. }
/* this function is placed on codepage 2 */
#pragma codepage 1
/* following functions are placed on codepage 1 */
When switching between codepages, the compiler will keep track on the next free location on each
codepage. Use of codepages is just a matter of optimization, as long as the compiler accepts the selection.
The optimal combination requires least code (or has a speed advantage). The optimizer removes
unnecessary setting and clearing of the page selection bits.
Some of the PICmicro devices have 4 code pages. Note that calls which requires switching between page
0 and 3, or page 1 and 2 requires more instructions than the other combinations. The enhanced 14 bit core
requires only one instruction for all code page switching.
The compiler produces an error message when page limits are exceeded. Invalid code pages are mapped
to valid ones.
1. A function prototype will locate the function on the desired codepage, even if the current active
codepage is different when the function definition is compiled.
2. #pragma location has higher priority than #pragma codepage.
3. '#pragma location -' restores the active codepage defined by the last #pragma codepage (or #pragma
origin).
65
CC5X C Compiler B Knudsen Data
Notes:
1. The location statements have to be compiled before the function definition
2. Functions not located are placed on the current active codepage
3. A warning is printed in case of conflicts
The #pragma location statement should only be used if required. An example is when functions inside a
module (file) have to be placed on different codepages, or if much tuning is required to find the optimal
combination. The #pragma codepage statement is normally sufficient.
The page type modifier defines the codepage to locate the function in, both for function prototypes and
function definitions.
NOTE 1: The page type modifier has higher priority than both #pragma codepage and #pragma location.
NOTE 2: When the codepage have been defined using the page type modifier or #pragma location, then
the location is fixed and cannot be changed in the function definition or by using a second prototype.
Core 12 note: assigning a value to the status register (f3) may cause the automatic updating to fail.
The compiler can replace CALL by GOTO to seemingly achieve deeper call levels.
1. When a function is called once only, the CALL can be replaced by a GOTO. All corresponding
returns are replaced by GOTO. Note that the call will only be replaced by GOTO when the call level
must be reduced. Also, the CALL is NOT replaced by GOTO when:
a) The program counter (PCL) is manipulated (computed goto) in a function of type char.
b) The number of return literals exceeds 10
c) The function is called from another codepage and the number of returns exceeds 10
When subroutines are located in the second half of a codepage, it cannot be called directly when using 12
bit core devices. The compiler automatically inserts links to such "hidden" subroutines.
66
CC5X C Compiler B Knudsen Data
The -q<N> option forces CC5X to assume that an interrupt will NOT occur at the <N> deepest call levels
of the main program.
The application writer must then ensure that interrupts will not occur when executing functions at the
deepest <N> call levels, normally by using the global interrupt enable bit. CC5X will generate a warning
for the critical functions. (The normal error message is always generated when the application contains
more than 8 call levels.)
For example, the -q1 option generates a warning for functions calls that will put the return address at
stack level 8 (no free stack entry for interrupt). Using -q2 means an additional warning at stack level 7
will be generated if the interrupt routine requires 2 levels, i.e. contains function calls.
The error message will be changed to a warning by the following pragma statement. Note that this means
that local variable and parameter overwriting must be avoided by careful code writing.
#pragma sharedAllocation
Recursive functions
Recursive functions are possible. Please note that the termination condition has to be defined in the
application code, and therefore the call level checking cannot be done by the compiler. Also note that the
compiler does not allow any local variables in recursive functions. Function parameters and local
variables can be handled by writing code that emulates a stack.
A warning is printed when the compiler detects that a function calls itself directly or through another
function. This warning can be switched off with the -wr command line option.
6.3 Interrupts
The 14 bit core allows interrupts. The structure of the interrupt service routine is as follows:
#include "int16CXX.h"
#pragma origin 4
interrupt serverX(void)
{
/* W and STATUS are saved by the next macro. PCLATH is also
saved if necessary. The code produced is CPU-dependent. */
67
CC5X C Compiler B Knudsen Data
The keyword interrupt allows the routine to be terminated by a RETFIE instruction. It is possible to call a
function from the interrupt routine (it has to be defined by a prototype function definition first).
The interrupt routine requires at least one free stack location because the return address is pushed on the
stack. This is automatically checked by the compiler. Even function calls from the interrupt routine are
checked. However, if the program contains recursive functions, then the call level cannot be checked by
the compiler.
The interrupt vector is permanently set to address 4. The interrupt service routine can only be located at
this address. The #pragma origin statement has to be used in order to skip unused program locations.
The following pragma statement will allow the interrupt routine to be placed anywhere. Note that the
compiler will NOT generate the link from address 4 to the interrupt routine.
#pragma unlockISR
Vital registers such as STATUS and W should be saved and restored by the interrupt routine. However,
registers that are not modified by the interrupt routine do not have to be saved. Saving and restoring
registers is device dependent. The file int16CXX.H contains recommended program sequences for saving
and restoring registers. The interrupt routine can also contain local variables. Storage for local variables is
allocated separately because interrupts can occur anytime.
CC5X also supports CUSTOM save and restore sequences. If you want to use your own register save and
restore during interrupt, please read the following Section Custom interrupt save and restore.
IMPORTANT: CC5X will AUTOMATICALLY check that the registers W, STATUS, PCLATH and
FSR are saved and restored during interrupt.
Note that register save checking does not apply to the enhanced 14 bit core.
The compiler will detect if the FSR register is modified during interrupt processing without being saved
and restored. The supplied macros for saving and restoring registers will not save FSR. This has to be
done by user code when needed. If FSR is modified by a table or pointer access, or by direct writing, the
compiler will check that FSR is saved and restored, also in nested function calls. Note that the FSR
saving and restoring can be done in a local region surrounding the indexed access, and does not need to
be done in the beginning and end of the interrupt routine.
A warning is printed if FSR is saved but not changed. The error and warning messages printed can be
removed:
68
CC5X C Compiler B Knudsen Data
Note that the above pragma changes the checking done on all registers.
A) You might want to use your own save and restore sequence. This can be done by inline assembly. If
CC5X does not accept your code, just insert (at your own risk):
B) No registers need to be saved when using the following instructions in the interrupt routine. The
register save checking should NOT be disabled.
C) It is possible to enable interrupt only in special regions (wait loops) in such a way that W, STATUS,
PCLATH and FSR can be modified during interrupt without disturbing the main program. Note that
interrupt must ONLY be enabled in codepage 0 when PCLATH is not saved. The register save can then
be omitted and the save checking must be switched off to avoid error messages:
The SLEEP instruction is executed when the processor exits main(). This stops program execution and
the chip enters low power mode. Program execution may be restarted by a watchdog timer timeout or a
low state on the MCLR pin.
The 14 bit core also allows restart by interrupt. An extra GOTO is therefore inserted if main is allowed to
terminate (SLEEP). This ensures repeated execution of the main program. No extra GOTO is added when
a sleep() command is inserted anywhere else in the application program.
69
CC5X C Compiler B Knudsen Data
void main(void)
{
if (TO == 1 && PD == 1 /* power up */) {
WARM_RESET:
clearRAM(); // set all RAM to 0
}
..
if (condition)
goto WARM_RESET;
}
The code size and timing depends on the actual chip. The following table describes the basic types. Chip
devices not found here maps to one of the described types.
// ..interrupt routine
#include “math16.h” // 16 bit integer math
#include “math24f.h” // 24 bit floating point
#include “math24lb.h” // 24 bit math functions
CC5X will automatically delete unused library functions. This feature can also be used to delete unused
application functions:
#pragma library 1
// library functions that are deleted if unused
#pragma library 0
70
CC5X C Compiler B Knudsen Data
Math libraries
Integer: 8, 16, 24 and 32 bit, signed and unsigned
Fixed point: 20 formats, signed and unsigned
Floating point: 16, 24 and 32 bit
All libraries are optimized to get compact code. All variables (except for the floating point flags) are
allocated on the generated stack to enable efficient RAM reuse with other local variables. A new concept
of transparent sharing of parameters in a library is introduced to save code.
Note that fixed point requires manual worst case analysis to get correct results. This must include
calculation of accumulated error and avoiding truncation and loss of significant bits. It is often
straightforward to get correct results when using floating point. However, floating point functions require
significantly more code. In general, floating point and fixed point are both slow to execute. Floating point
is FASTER than fixed point on multiplication and division, but slower on most other operations.
Operations not found in the libraries are handled by the built in code generator. Also, the compiler will
use inline code for operations that are most efficiently handled inline.
Integer libraries
The math integer libraries allow selection between different optimizations, speed or size. The libraries
contain operations for multiplication, division and division remainder.
The min and max timing cycles are approximate only. The enhanced 14
bit core will use fewer cycles and less code.
A:math32.h
B:math24.h
C:math16.h Code min aver max
ABC - 16 = 8 * 8 13 83 83 83
ABC S 16 = 8 * 8 21 85 85 85
ABC S/- 16 = 16 * 16 18 197 222 277
.B. S 24 = 16 * 16 35 220 261 334
71
CC5X C Compiler B Knudsen Data
A:math32m.h
B:math24m.h
C:math16m.h Code min aver max
ABC - 16 = 8 * 8 37 50 50 50
ABC S/- 16 = 16 * 16 23+37 74 147 158
.B. - 24 = 24 * 8 32+37 124 162 166
A.. - 32 = 32 * 8 43+37 178 212 222
72
CC5X C Compiler B Knudsen Data
The timing stated is measured in instruction cycles (4*clock) and includes parameter transfer, call, return
and assignment of the return value. The min and max timing cycles are approximate only. The enhanced
14 bit core will use fewer cycles and less code.
73
CC5X C Compiler B Knudsen Data
NOTE: The timing values include parameter transfer, call and return and also assignment of the return
value. The min and max timing cycles are approximate only. The enhanced 14 bit core will use fewer
cycles and less code.
The following operations are handled by inline code: assignment, comparison with constants,
multiplication and division by a multiple of 2 (e.g., a*0.5, b * 1024.0, c/4.0).
74
CC5X C Compiler B Knudsen Data
75
CC5X C Compiler B Knudsen Data
(*) The accuracy of the math functions have been checked using many thousands of calculations. ME=1
means that the mantissa value can be wrong by +/- 1 (i.e. 1 bit). The relative error is then 1.5*10-5 for 24
bit floating point, and 6*10-8 for 32 bit floating point. Only a small fraction of the calculations may have
the stated error.
(**) The min and max timing cycles are approximate only. The enhanced 14 bit core will use fewer
cycles and less code. All timing is measured in instruction cycles. When using a 4 MHz oscillator, one
instruction cycle is 1 microsecond.
Integer:
- converting to left and right shifts: a * 8, a / 2
- selecting high/low bytes/words: a / 256, a % 256, b % 0x10000
- replacing remainder by AND operation: a % 64, a % 0x80
Fixed Point:
- converting to left and right shifts: a * 8, a / 2
- all operations except multiplication and division are implemented inline
Floating point:
- add/sub (incr/decr) of exponent: a * 128.0, a / 2
- operations == and != : a == b, a != 0.0
- comparing with constants: a > 0, a <= 10.0
- inverting the sign bit: a = -a, b = -a
uns16 a, b, c;
..
a = b * c; // inline code is generated
76
CC5X C Compiler B Knudsen Data
..
#include "math16.h"
..
a = b * c; // math library function is called
..
#pragma inlineMath 1
a = b * c; // inline code is generated
#pragma inlineMath 0
..
a = b * c; // math library function is called
The math prototypes are found in the beginning of the standard math libraries. Just remember to remove
the operator name before adding the inline type modifier.
A warning is printed when there is ONE call to a unsigned integer math library function. The warning can
be disabled by the -wm command line option.
NOTE that the inline type modifier is currently IGNORED, except for the math operations.
#pragma codepage 1
#include "math24f.h"
#pragma codepage 0
Prototypes can be used when functions are called before they are defined. Note that operator functions
need a function name to be defined as prototypes.
Also note that the compiler use a linear search from the beginning of the operator table until a match for
the current operation is found. The operator definition/prototype sequence may therefore influence the
operator selected.
It is not recommended to modify the libraries by adding 'pragma codepage' between the functions.
Instead, prototypes and 'pragma location' or the page type modifier makes function placement easier to set
up and tune. For example, placing the division function on codepage 1 and the other on the default
codepage can be done by:
77
CC5X C Compiler B Knudsen Data
..
#include "my_math.h"
..
#include "math24f.h"
..
void main(void)
{
vx = 3.127;
tx += data; // automatic type cast
data = kp; // assign integer part
if ( tx < 0)
tx = -tx; // make positive
av = tx/20.0;
mg = av * 1.25;
a = mg * 0.98; // 0.980469, error: 0.000478
prev = vx;
vx = a/5.0 + prev;
kp = vx * 0.036; // 0.03515626, error: 0.024
kp = vx / (1.0/0.036); // 27.7773437
}
void main(void)
{
InitFpFlags(); // enable rounding as default
vx = 3.127;
tx += data; // automatic type cast
data = kp; // assign integer part
78
CC5X C Compiler B Knudsen Data
if ( tx < 0)
tx = -tx; // make positive
av = tx/20.0;
mg = av * 1.25;
a = mg * 0.98;
prev = vx;
vx = a/5.0 + prev;
kp = vx * 0.036;
kp = vx / (1.0/0.036);
}
3. Optimization, currently available on division only. Note that “optimize for speed” is default. Also note
that the saving is only 5 - 7 instructions. Timing difference is up to 15-20 percent.
#define FP_OPTIM_SIZE // optimize for SIZE
#define FP_OPTIM_SPEED // optimize for SPEED: default
The recommended strategy is to select a main library for the demanding math operations. Different
floating and fixed point operations should only be mixed if there is a good reason for it.
Mixing different data types is possible to save code and RAM space. For example by using a small type
in an array and a larger type for the math operations.
So, first decide what math library to include. For floating point the main decision is between the 24 bit
and the 32 bit library. If you use 32 bit operations, this can be combined with 24 (and 16) bit floating
point types to save RAM.
In general, using the smallest possible data type will save code and RAM space. This must be balanced
against the extra work to analyze the program to prevent overflow and too large accumulated errors. If
there is plenty of code space in the device, and timing is no problem, then large types can be used.
Otherwise analysis is required to get optimal selections.
It is recommended to keep the number of called library functions as low as possible. Although function
selection is done automatically by the compiler, it is possible to use type casts or even make a custom
library by copying the required functions from existing libraries. All libraries are written in C. CC5X can
print a warning for each operator function that is called (option -wO).
79
CC5X C Compiler B Knudsen Data
restricted to labels inside the function. If these restrictions make program design too difficult, consider
using the linker support and link C and assembly modules using MPLINK.
#asm
.. assembly instructions
#endasm
Features:
• many assembly formats
• equ statements can be converted to variable definitions
• macro and conditional assembly capabilities
• call C functions and access C variables
• C style comments is possible
• optional optimization
• optional automatic bank and page updating
Note that the file inline.h is for emulating inline assembly, and should NOT be included when using real
inline assembly. The compiler does not optimize inline assembly or update the bank or page bits unless it
is instructed to do so.
Inline assembly is NOT C statements, but are executed in between the C statements. It is not
recommended to write the code like this:
if (a==b)
#asm
nop // this is not a C statement (by definition)
#endasm
a = 0; // THIS is the conditional statement!!!
Inline assembly supports DW. This can be used to insert data or special instructions. CC5X will assume
that the data inserted are instructions, but will not interpret or know the action performed. Bank selection
bits are assumed to be undefined when finishing executing DW instructions. PCLATH bit 3 (and 4) must
remain unchanged or restored to correct value if more than one code page is available on the device.
Example use is found in file ‘startup.txt’.
#asm
DW 0x3FFF ; any data or instruction
DW /*CALL*/ 0x2000 + ADDRESS
#endasm
Assembly instructions are not case sensitive. However, variables and symbols require the right lower or
upper case on each letter.
clrw
Nop
NOP
80
CC5X C Compiler B Knudsen Data
Constant formats:
MOVLW 10 ; decimal radix is default
MOVLW 0xFF ; hexadecimal
MOVLW 0b010001 ; binary (C style)
MOVLW 'A' ; a character (C style)
MOVLW .31 ; decimal constant
MOVLW .31 + 20 - 1 ; plus and minus are allowed
MOVLW H'FF' ; hexadecimal (radix 16)
MOVLW h'0FF'
MOVLW B'011001' ; binary (radix 2)
MOVLW b'1110.1101'
MOVLW D'200' ; decimal (radix 10)
MOVLW d'222'
MOVLW MAXNUM24EXP ; defined by EQU or #define
;MOVLW 22h ; NOT allowed
decf ax,0
iorwf ax,w
iorwf ax,W
bcf Carry
bsf Zero_
bcf ax,B2 ; B2 defined by EQU or #define
bcf ax,1
bcf STATUS,Carry ; Carry is a bit variable
Arrays, structures and variables larger than 1 byte can be accessed by using an offset.
clrf a32 ; uns32 a32; // 4 bytes
clrf a32+0
clrf a32+3
clrf tab+9 ; char tab[10];
; clrf tab-1 ; not allowed
goto LABEL4
LABEL1
:LABEL2
LABEL3:
LABEL4 nop
nop
goto LABEL2
Functions are called directly. A single unsigned 8 bit parameter can be transferred using the W register.
movlw 10
call f1 ; equivalent to f1( 10);
81
CC5X C Compiler B Knudsen Data
The ONLY way to transfer multiple parameters (and parameters different from 8 bit) is to end assembly
mode, use C syntax and restart assembly mode again.
#endasm
func( a, 10, e);
#asm
The enhanced 14 bit core allows more instructions and new formats:
ADDWFC i,W
SUBWFB i,1
LSLF i,0
LSRF i
ASRF i,W
MOVLB 1
MOVLP 1
RESET
ADDFSR INDF0,31
ADDFSR INDF1,-1
MOVWI ++INDF0
MOVIW INDF0--
MOVIW 1[INDF0]
MOVIW -2[INDF1]
The EQU statement can be used for defining constants. Assembly blocks containing EQU's only can be
put outside the functions. Note that Equ constants can only be accessed in assembly mode. Constants
defined by #define can be used both in C and assembly mode.
#asm
B0 equ 0
B7 equ 7
MAXNUM24EXP equ 0xFF
#endasm
Equ can also be used to define variable addresses. However, the compiler does not know the difference
between an Equ address and an Equ constant until it is used by an instruction. When an Equ symbol is
used as a variable, that location is disabled for use by other variables. The symbol then changes from an
Equ symbol to a variable symbol and is made available in C mode also. There is a slight danger in this
logic. DO NOT USE a series of Equ's to define an array. If one of the locations are not read or written
directly, the compiler will not know that it is a part of an array and may use it for other purposes. Reading
and writing through FSR and INDF is not used to transform equ definitions. Therefore, define arrays by
using C syntax (or #pragma char).
82
CC5X C Compiler B Knudsen Data
The following address operations are possible when the variable (structure/array) is set to a fixed address:
NOP ; a comment
NOP // C style comments are also valid
/*
CLRW ;
NOP /* nested C style comments are also valid */
*/
#ifdef SYMBOLA
nop
#else
clrw
#endif
C style macros can contain assembly instructions, and also conditional statements. Note that the compiler
does not check the contents of a macro when it is defined.
#define UUA(a,b)\
clrw\
movlw a \
#if a == 10 \
nop \
#endif \
clrf b
UUA(10,ax)
UUA(9,PORTA)
Note that labels inside a macro often need to be supplied as a parameter if the macro is used more than
once. Also note that there should always be a backslash '\' after a #endasm in a macro to avoid
83
CC5X C Compiler B Knudsen Data
error messages when this macro is expanded in the C code. This applies to all preprocessor statements
inside a macro.
waitX(i, LL1);
waitX(i, LL2);
The compiler can optimize and perform bank and page updating in assembly mode. This does not happen
automatically, but has to be switched on in the source code. It is normally safe to switch on optimization
and bank/page updating. Instructions updating the bank and page register are removed before the
compiler insert new instructions. If the assembly contains critical timing, then the settings should be left
off, at least in local regions.
Interpretation:
o+ : current optimization is performed in assembly mode
o- : no optimization in assembly mode
b+ : current bank bit updating is performed in assembly mode
b- : no bank bit update in assembly mode
p+ : current page bit updating is performed in assembly mode
p- : no page bit update in assembly mode
Note that b+ o+ p+ means that updating is performed if the current setting in C mode is on. Updating is
NOT performed if it is switched off in the C code when assembly mode starts. The command line options
-b, -u, -j will switch updating off globally. The corresponding source code settings are then ignored.
Note that direct coded instructions are different from inline assembly seen from the compiler. The
compiler will view the instruction codes as values only and not as instructions. All high level properties
are lost. The compiler will reset optimization, bank updating, etc. after a DW statement.
Example usage:
#include "hexcodes.h"
..
84
CC5X C Compiler B Knudsen Data
// 1. In DW statements:
#asm
DW __SLEEP // Enter sleep mode
DW __CLRF(__INDF) // Clear indirectly
DW __ANDLW(0x80) // W = W & 0x80;
DW __DECF(__FSR,__F) // Decrement FSR
DW __BCF(__STATUS,__Carry) // Clear Carry bit
DW __GOTO(0) // Goto address 0
#endasm
..
// 2. In cdata statements:
#pragma cdata[1] = __GOTO(0x3FF)
The compiler will normally generate single instructions if the C statements are simple. Remember to
inspect the generated assembly file if the application algorithm depends upon a precisely defined
instruction sequence. The following example shows how to generate single instructions from C code.
nop(); // NOP
f = W; // MOVWF f
W = 0; // CLRW
f = 0; // CLRF f
W = f - W; // SUBWF f,W
f = f - W; // SUBWF f
W = f - 1; // DECF f,W
f = f - 1; // DECF f
W = f | W; // IORWF f,W
f = f | W; // IORWF f
W = f & W; // ANDWF f,W
f = f & W; // ANDWF f
W = f ^ W; // XORWF f,W
f = f ^ W; // XORWF f
W = f + W; // ADDWF f,W
f = f + W; // ADDWF f
W = f; // MOVF f,W
W = f ^ 255; // COMF f,W
f = f ^ 255; // COMF f
W = f + 1; // INCF f,W
f = f + 1; // INCF f
W = decsz(i); // DECFSZ f,W
f = decsz(i); // DECFSZ f
W = rr(f); // RRF f,W
f = rr(f); // RRF f
W = rl(f); // RLF f,W
f = rl(f); // RLF f
W = swap(f); // SWAPF f,W
f = swap(f); // SWAPF f
W = incsz(i); // INCFSZ f,W
f = incsz(i); // INCFSZ f
b = 0; // BCF f,b
b = 1; // BSF f,b
btsc(b); // BTFSC f,b
btss(b); // BTFSS f,b
85
CC5X C Compiler B Knudsen Data
Most of the code is generated inline, even multiplication and division. However, if many similar and
demanding math operations have to be performed, then it is recommended to include a math library.
Optimized syntax
Bit toggle uses the W register to get compact code:
86
CC5X C Compiler B Knudsen Data
bit b;
b = !b; // MOVLW K, XORWF var
uns16 x;
if (x & 0xF0)
if (!(x & 0x3C))
if ((x & 0xF00) == 0x300)
if ((x & 0x7F00) < 0x4000)
Peephole optimization
Peephole optimizing is done in a separate compiler pass which removes superfluous instructions or
rewrite the code by using other instructions. This optimization can be switched off by the -u command
line option. The optimization steps are:
NOTE: Optimization can also be switched on or off in a local region. Please refer to the #pragma
optimize statement for more details.
; while (1) {
; if (Carry == 0) {
m001 BTFSC status,Carry
GOTO m004 ; REDIRECTED TO m001 (1)
; i++;
INCF i ; REPLACED BY INCFSZ (4)
; if (i != 0)
MOVF i ; REMOVED (5)
BTFSS status,Zero_ ; REMOVED (4)
GOTO m002 ; REMOVED (3)
; var++;
INCF var
; test += 2;
m002 MOVLW .2
ADDWF test
; if (test == 0)
MOVF test ; REMOVED (5)
BTFSS status,Zero_ ; REPLACED BY BTFSC (3)
GOTO m003 ; REMOVED (3)
; break;
GOTO m005
87
CC5X C Compiler B Knudsen Data
; W = var;
m003 MOVF var,W
; if (W == 0)
XORLW .0 ; REMOVED (5)
BTFSS status,Zero_
GOTO m004 ; REDIRECTED TO m001 (1)
; break;
GOTO m005 ; REMOVED (7)
m004 GOTO m001 ; REMOVED (2)
; sub1();
m005 BSF status,PA0
CALL sub1
BCF status,PA0 ; REMOVED (6)
; sub2();
BSF status,PA0 ; REMOVED (6)
BSF status,PA1
CALL sub2
BCF status,PA0
BCF status,PA1
CC5X supports the relocatable assembly format defined by Microchip. This means that MPLINK can be
used to link code modules generated by CC5X, including MPASM assembly modules. There are many
details to be aware of. It is therefore recommended to read this file carefully. The important issues are
related to:
The command line option '-r' (or ‘-r2’) makes CC5X generate relocatable assembly. This file is then
assembled by MPASM and linked together with other C and assembly modules by MPLINK. This can
automated by using 'make' to build the whole application in several stages.
NOTE that if you need the application program to be as compact as possible, then it is recommended to
use only ONE C module. Source code modularity is obtained by using many C files and include these in
the main C module by using #include.
88
CC5X C Compiler B Knudsen Data
C modules can be merged into a single module and still be viewed as single modules. Such C
modules can be used in several projects without modification. The procedure is as follows:
#include "module1.c"
#include "module2.c"
// ..
#include "moduleN.c"
// ..
void main( void) { .. }
2. Each merged “module” includes the required header files. This can be header files specific for the
“module” or common header files:
#include "header1.h"
#include "header2.h"
// ..
#include "headerN.h"
// ..
// module functions
3. If the same header file is included in more than one “module”, it will be required to prevent compiling
the same header file definitions more than once. This is done by using the following header file framing:
89
CC5X C Compiler B Knudsen Data
extern char a;
All global variables that are not 'static' are made available for other modules automatically. CC5X inserts
'GLOBAL' statements in the generated assembly file.
CC5X will generate a 'MOVLW LOW (var_name+<offset>)' when using the address operators
'&var_name'.
Global bit variables are a challenge. It is recommended to first define a char variable and then use 'bit bx
@ ch.0;'. Otherwise CC5X will define a global char variable with random name. This name have the
format '_Gbit<X><X>' where <X> is a (more or less) random selected letter. This variable is reserved by
a RES statement and used in the assembly file when generating relocatable assembly.
bit b1;
b1 = 0; // BCF _GbitQB+0,0
The variable file (*.var) is slightly modified when generating relocatable assembly. Note that most
addresses stated in the variable file are reallocated by MPLINK.
Option -rx will make variables static by default. This means that variables will not be visible outside the
module unless 'extern' is added in front of the type definition. Note that option -rx requires that an extern
pointer definition need to be stated before the allocation of the pointer.
IMPORTANT: 'const' data cannot be 'extern' because MPLINK does not support the const access
functions generated by CC5X. Identifiers with the 'const' modifier will not be made visible outside the
module. This also applies to struct objects with const pointers.
IMPORTANT: Allocation of pointers is slightly different when using relocatable assembly. The main
reason for this is that CC5X cannot trace how addresses are assigned to pointers between different
modules. There is no change on local and static pointers. An extern visible pointer without a size modifier
(size1/size2) will be:
a) 16 bit if RAM alone use more than 8 bit addresses regardless of the default memory model used.
b) 16 bit if special registers need more than 8 bit addresses when the default RAM memory model is 16
bit (option -mm2 or -mr2).
c) 8 bit otherwise.
An extern visible pointer with the size1 modifier will access addresses from 0 - 255. An error is printed if
the pointer is assigned higher addresses. However, it is possible to force an extern 8 bit pointer to access
addresses 256 - 511 by a pragma statement:
Note that 8 bit pointers in a struct can only access addresses from 0 - 255, even if the struct is static or
local.
90
CC5X C Compiler B Knudsen Data
Local variables
CC5X uses a different naming strategy on local variables when generating relocatable assembly. CC5X
reserves a continuous block in each ram bank (or shared bank) and use this name when accessing local
variables.
IMPORTANT RESTRICTION: The main() routine, interrupt service routines and all extern functions are
defined as independent call trees or paths. A function called from two independent call paths cannot
contain local variables or parameters because address sharing cannot be computed in advance. CC5X
detects this and generates an error message.
The names of the local RAM blocks are _LcRA, _LcRB, etc. The last letter is related to the RAM bank
and the second last to the module name. Adding option -ro1 will for example change name _LcAA to
_LcBA. This can be used if there is a collision between local variable block defined in separate C
modules. MPLINK detects such collisions.
-ro<N> : add offset <N> when generating local variable block name
Local variables for external available functions are allocated separately, one block for each extern
function. This often means inefficiently use of RAM. It is therefore recommended to use 'extern' only on
those functions that have to be extern, and use few local variables in the extern functions. Also consider
using global variables.
Header files
It is recommended to make common header files that contain global definitions that are included in all C
modules. Such files can contain definitions (#define), IO variable names, etc.
Note that the RAM bank of ALL variables has to be known (defined) during compilation. Otherwise the
bank bit updating will not be correct. The bank is defined by using '#pragma rambank' between the
variable definition statements, also for 'extern' variables. An alternative is to use the bank type modifier
(bank0..bank3, shrBank).
#pragma rambank 0
char a,b;
#pragma rambank 1
extern char array1[10];
#pragma rambank -
extern char ex; // shared/common RAM
It is therefore recommended to only use 'extern' on those functions that have to be extern, and keep the
number of calls between modules to a minimum.
91
CC5X C Compiler B Knudsen Data
Functions
Functions residing in other modules can be called. Functions defined can be called from other modules
(also from assembly modules).
NOTE that ALL functions that are called from another module need an 'extern' first. This is an extra
requirement that is optional in C. The reason is that the compiler needs to decide the strategy on bank bit
updating and local variables allocation. It is most efficient to use FEW extern functions.
NOTE that extern functions can only have a single unsigned 8 bit parameter which is transferred in W.
This is because local storage information is not shared between modules. The return value cannot be
larger than 8 bit for the same reason (bit values are returned in Carry).
CC5X inserts a 'GLOBAL <function>' in the generated assembly code for all external available functions.
'EXTERN <function>' is inserted for functions defined in other modules.
If the C module contains main(), then a 'goto main' is inserted in the STARTUP section.
The code page of all function calls have to be known (defined) during compilation. Otherwise the page
bit updating will not be correct. The page is defined by using '#pragma location' or the page type modifier
for functions defined in another module. For functions defined in the current module, '#pragma codepage'
can also be used.
It is recommended to define the function heading (prototypes) for all extern functions in a header file
including page information. This file should be included in all C modules.
IMPORTANT: When a module contains functions located on more than one codepage, all function
belonging to the same page must be put in sequence in the source file. This because MPASM/MPLINK
requires all object code sections to be continuous and CC5X is unable to change the definition order of
the functions.
Interrupts
CC5X requires that the interrupt function is located at address 4. Writing the interrupt service routine in C
using MPLINK will require some care. The main issue is to set up the linker script file as described later
in this file. Two options are possible:
ALTERNATIVE 1: Use the linking sequence to locate the interrupt service routine. This is done by
listing the module with the interrupt service routine FIRST in the module list used by MPLINK. This is
the important point which makes MPLINK put the interrupt service routine in the beginning of the
PROG/PROG1 logical code section (address 4). The list file generated by MPLINK should be inspected
to ensure that the interrupt routine starts at address 4. Another important point is to remove the #pragma
origin 4 when using MPLINK. This is the only difference in the C source compared to using the built in
CC5X linker (single C module).
92
CC5X C Compiler B Knudsen Data
ALTERNATIVE 2: Set up a SEPARATE logical section in the linker script file for the interrupt service
routine. This is a more robust solution. CC5X will generate a partial script file to avoid manual address
calculation. The partial script file must be included in the main script file. The setup is described in
Section The MPLINK script file on page 95.
It is also possible to design an assembly module containing the interrupt service routine. Information on
how to do this should be found in the MPASM/MPLINK documentation.
When calling an external function from the C code, CC5X will assume that the external call is one level
deep. This checking is sometimes enough, especially if all C code is put in one module, and the assembly
code modules are called from well known stack levels. Calling C function from assembly will require
manual analysis.
Therefore, careful verification of the call structure is required to avoid program crash when overwriting a
return value on the hardware stack (which is 2 or 8 levels deep). The compiler generated *.fcs files can
provide information for this checking.
Calls to external functions is written in the *.fcs file. External function calls are marked [EXTERN].
Computed goto
14 bit core: CC5X will always use the long format when generating code for skip(). It is not possible to
use the -GS option. The long format is 3 instructions longer than the short format.
12 bits core: All destination addresses must be located in the first 256 word half of the codepage.
Unfortunately CC5X cannot check the layout done by MPLINK. It is therefore strongly recommended to
apply some manual design rules that will prevent destination addresses to be moved into the invisible
(high) code page half. This can be done by ensuring a linking sequence that will put all modules
containing computed goto at the beginning (offset 0) of the codepage. Inspection of the generated list file
is recommended.
2. Use definition header files that are shared between modules. Include the shared definition in all C
modules to enable consistency checking.
a) function headings (prototypes). Add page information when using more than one code page:
// module1.c
extern page0 void sub(char ax);
// module2.c
extern page1 void mpy(void);
// Do not add extern to functions that are not called
// from other modules.
char localFunctionA(void); // local function
// Note that it is required to use extern in the
// function definition when an extern prototype
93
CC5X C Compiler B Knudsen Data
// is not defined.
4. Make a linker script file according to the description stated later. Follow the guidelines when using
interrupts.
5. Set up a 'makefile' to enable automatic (re)compilation and linking. Follow the guidelines when using
MPLAB. Edit and use the option '+reloc.inc' when compiling C modules.
MPASM
The linker script file must be made (or adapted) according to the description stated.
Note that MPASM will generate its own warnings and messages. These should normally be ignored.
MPASM do not know about the automatic bank bit updating and will display messages about this.
MPASM have generated the message if the asm file extension is used in the message.
Program execution tracing will always use the assembly file as source when using MPLINK. MPASM
can generate object code from assembly modules. There are some restrictions and additions when using
relocatable modules compared to using a single assembly module.
CC5X does not support the object code directly, but generates relocatable assembly that MPASM use to
generate the object file. MPASM is started from within the CC5X so that no extra command is required
(only the right command line options).
94
CC5X C Compiler B Knudsen Data
Case Sensitivity option in MPASM is by default On, and should remain On because C use case dependent
identifiers.
If the CC5X error file option (-F) is missing, CC5X will read the error file generated by MPASM and
write the error and warnings found there to the screen and the output file (*.occ). The error file is then
deleted.
If the CC5X error file option (-F) is present, CC5X will write error and warnings to the error file (*.err)
and append the error and warnings generated by MPASM at the end of this file.
The sample MPLINK script files must be changed slightly if the interrupt function is written in C. The
reason is that the interrupt function must start at address 4 when using CC5X. It could be possible to use a
vector at address 4, but this slows down interrupt response. Anyway, using a goto vector directly is not
possible when the device contains more than 2048 words of code. This is because PCLATH needs to be
saved before it can be updated.
CHANGE 1: Interrupt routine in C WITH a separate logical section. CC5X generates a partial script file
when using the -r2 (or -r2[=]<file.lkr>) command line option. This file is written if (and only if) CC5X
compiles a module with an interrupt service routine. The generated script file may look like:
CHANGE 3: If INTERRUPTS are not used, then the first code page can start at address 1. Example
change:
95
CC5X C Compiler B Knudsen Data
CHANGE 4: The 12 bit core devices need a logic section for the startup vector. Example change for the
16C57:
CHANGE 5: Certain devices require a special interrupt save sequence that needs to use certain RAM
locations (0x20 and 0xA0). These addresses must be made unavailable for allocation in the linker script
file. This applies to 14000, 16C63, 16C63A, 16C65, 16C65A, 16C65B, 16C73, 16C73A, 16C73B,
16C74, 16C74A, 16C74B, 16F873, 16F874 and similar devices. CC5X generates a warning when
variables are assigned to fixed addresses. Example change:
CHANGE 6: LOGICAL RAM sections must be added, one for each DATABANK that contains RAM
locations (not special function registers). Note that if a logical RAM section is missing, then the variables
that belong to this section will be put in the "default" section. MPLINK gives no error on missing logical
sections in the script file and the program will fail.
96
CC5X C Compiler B Knudsen Data
Page naming:
-rp0 : PROG0 is the name of the first codepage
-rp1 : PROG1 is the name of the first codepage
Bank naming:
-rb0 : BANK0 is the name of the first RAM bank
-rb1 : BANK1 is the name of the first RAM bank
//***************************************************
// MODULE1.C
#include "globdef1.h"
#include "int16CXX.H"
#pragma origin 4
interrupt int_server(void)
{
int_save_registers // W, STATUS (and PCLATH)
if (T0IF) {
/* TMR0 overflow interrupt */
TMR0 = -45;
T0IF = 0; /* reset flag */
}
if (INTF) {
/* INT interrupt */
INTF = 0; /* reset flag */
}
int_restore_registers // W, STATUS (and PCLATH)
}
char a;
bit b1, b2;
void main(void)
{
PORTA = 0b0010;
TRISA = 0b0001;
97
CC5X C Compiler B Knudsen Data
b2 = !b1;
do {
if (in == 1)
break;
sub(a&3);
} while (a < 200);
}
//****************************************************
// MODULE2.C
#include "globdef1.h"
/* generate pulses */
for (i = 0; i <= ax+1; i++) {
out = 1;
nop2();
out = 0;
a ++; // increment global variable
}
}
;****************************************************
; GLOBDEF1.H
// names assigned to port pins
#pragma bit in @ PORTA.0
#pragma bit out @ PORTA.1
// module1.c
extern bank0 char a;
// module3.asm
extern bank1 char mulcnd, mulplr, H_byte, L_byte;
// module2.c
extern page0 void sub(char ax);
// module3.asm
extern page0 void mpy(void);
; ***************************************************
; MODULE3.ASM
#INCLUDE "P16F877.INC"
BANK1 UDATA
mulcnd RES 1 ; 8 bit multiplicand
mulplr RES 1 ; 8 bit multiplier
H_byte RES 1 ; High byte of the 16 bit result
L_byte RES 1 ; Low byte of the 16 bit result
count RES 1 ; loop counter
98
CC5X C Compiler B Knudsen Data
END
//**************************************************
// File: 16f877.lkr
LIBPATH .
99
CC5X C Compiler B Knudsen Data
//**************************************************
// File: module1.lkr : generated by CC5X when using the -r2 option
// Note that -r2 must be used instead of -r (file 'reloc.inc')
NOTE 1: cdata[] can currently not be used with relocatable assembly. When using MPLINK, such data
statements can be put in an assembly module.
NOTE 2: Constant data should normally be stored using the 'const' type modifier. However, cdata[] is
useful for storing EEPROM data, or data and instructions at fixed addresses.
NOTE 3: There is no check on validity of the inserted data or address. However, it is NOT possible to
overwrite program code and other cdata sections. The data is added at the end of the assembly and hex
file in the same order as it is defined.
NOTE 4: cdata outside legal program and EEPROM space is disabled. The error message can be changed
to a warning by using the -cd command line option. EEPROM address range is 0x2100 - 0x21FF for
legacy 14 bit core devices and 0xF000 - 0xF0FF for enhanced 14 bit core devices.
SYNTAX:
100
CC5X C Compiler B Knudsen Data
Strings are stored as 7 bit ASCII characters (14 bit core devices). The least significant 7 bits of each code
word are filled first. Strings are aligned on word addresses for each <VXS>. However, alignment does
not occur when writing "abc" "def".
IDENTIFIER: any undefined identifier. It is converted to a macro identifier and set to the current cdata
word address. The purpose is to provide an automatic way to find the address of stored items.
Empty cdata statements can be used to set or read the current cdata address.
Only cdata within the valid code space is counted when calculating the total number of code words.
#include "hexcodes.h"
#pragma cdata[0] = __NOP
#pragma resetVector 1 // goto main at address 1
#include "hexcodes.h"
#define ResetAddress 0x3FF // 16C509(A)
#pragma cdata[ResetAddress]= __MOVLW(CalValue)
The cdata definitions should be put in a separate file and included in the beginning of the program. This
enables identifiers to be used in the program and checking to be performed.
101
CC5X C Compiler B Knudsen Data
write(ID1);
write(ID2);
All cdata start addresses have to be decided manually. The setup could be as follows:
.. cdata definitions
.. C functions at addresses lower than CDATA_START
// #pragma origin CDATA_START // optional
#pragma origin CDATA_END
.. C functions at addresses higher than CDATA_END
The #pragma origin CDATA_START is not required, because data overlapping is detected automatically.
However, the compiler tells how many instructions are skipped for each origin statement. The cdata
words are not counted at this printout.
Statement #pragma origin CDATA_END allows functions to be stored right after the cdata area. This
origin statement is not required if all cdata are located at the end of the code space.
#if __EnhancedCore14__
#define EEPROM_START 0xF000 // Enhanced 14 bit core devices
#else
#define EEPROM_START 0x2100 // Legacy 14 bit core devices
#endif
#pragma cdata[EEPROM_START] // start of cdata block
#pragma cdata[] = 0x3F, 10, 'a' // 3 bytes EEPROM data
Note that strings will normally be packed into 2*7 bits when using cdata. This will not work for the
EEPROM area. It is possible to add '\0' in the strings ("a\0b\0c\0"), but it is better to use a pragma to
specify unpacked strings:
#pragma packedCdataStrings 0
// Store following strings unpacked
#pragma cdata[] = "Hello world!\0"
#pragma packedCdataStrings 1
// Store remaining strings packed
LINKER NOTE: EEPROM data must be put in an assembly module when using MPLINK.
102
CC5X C Compiler B Knudsen Data
7 DEBUGGING
Removing compilation errors is a simple task. The real challenge is to reveal the many application bugs.
ALWAYS remember to check the assembly file if the application program does not behave as expected.
Using a compiler does not remove the need for understanding assembly code.
Debugging methods
There are several ways of debugging the program:
1. Test (parts of) the program on a simulator. This allows full control of the input signals and thus exact
repetition of program execution. It is also possible to speed up testing to inspect long term behavior
and check out rare situations. How to do this is application dependent.
2. Use a hardware emulator. An emulator allows inspection and tracing of the internal program state
during execution in the normal application environment, including digital and analog electronics.
3. Insert application specific test-code and run the program on a prototype board. Then gradually
remove the extra code from the verified program parts. The key is to take small steps and restore the
program to a working state before doing the next change. The extra test code can consist of:
1) Code that produces patterns (square waves) on the output pins. This can be checked by an
oscilloscope.
2) Repetition of output sequences.
3) Extra delays or extra code to handle special situations.
The different debugging methods have their advantages and disadvantages. It can be efficient to switch
between several methods.
Compiler bugs
Compiler bugs are hard to detect, because they are not checked out until most other tests have failed.
(Silicon bugs can be even harder). Compiler bugs can often be removed by rewriting the code slightly, or,
depending on the type of bug, try:
1) #pragma optimize
2) #pragma update_FSR
3) #pragma update_RP
4) command line option: -u
5) command line option: -bu
6) command line option: -b
Some errors are fatal, and cause the compiler to stop immediately. Otherwise the compiling process
continues, but no output files are produced.
If there is a syntax error in a defined macro, then it may be difficult to decide what the problem actually
is. This is improved by printing extra error messages which points to the macro definition, and doing this
recursively when expanding nested macros.
103
CC5X C Compiler B Knudsen Data
NOTE: When an error is detected, the compiler deletes existing hex and assembly files produced by the
last successful compilation of the same source file.
void sel(char i) {
Carry = 0;
W = rl(i); /* multiply by 2 */
skip(W);
#pragma computedGoto 1
W = '0'; goto ENDS;
W = '1'; goto ENDS;
W = '4';
#pragma computedGoto 0
ENDS:
/* processing continues here */
}
104
CC5X C Compiler B Knudsen Data
b) Using the generated assembly file as the source file (COD only). COFF file debugging in this mode
can be supported by generating an assembly file and send it to MPASM in order to generate the
COFF debugging file. The format of the assembly file can be changed in order to suit the debugging
tool. Take a look at the assembly file options. Some suggestions:
Arrays:
COD FILE PROBLEM ONLY: Arrays and structures represent a slight challenge, because all variables
passed in the COD file are currently either char or bit types.
This means that the name of a structure element is not visible when inspecting variables in a debugger.
105
CC5X C Compiler B Knudsen Data
NOTE 1: comments in the <text field> will not be removed, but passed to the debugger.
NOTE 2: Only ASCII characters are allowed in the assert text field. However, a backslash allows some
translation:
\0 => 0, \1 => 1, \2 => 2, \3 => 3, \4 => 4
\5 => 5, \6 => 6, \7 => 7, \a => 7, \b => 8
\t => 9, \n => 10, \v => 11, \f => 12, \r => 13
USE OF MACROS: Macros can be used inside assert statements with some limitations. The macro
should cover the whole text field AND the <type> identifier (or none of them). Macros limited to a part
of the text field are not translated. Macros can be used to switch on and off a group of assert statements or
to define similar assert statements.
All low level activity, like IO read and write, have to be handled different. Conditional compilation is
recommended. This also allows additional test code to be easily included.
#ifdef SIM
// simulated sequence
// or test code (printf statements, etc.)
106
CC5X C Compiler B Knudsen Data
#else
// low-level PICmicro code
#endif
107
CC5X C Compiler B Knudsen Data
8 FILES PRODUCED
The compiler generates a hex file that can be used for programming the PICmicro devices directly. The
hex file normally contains code, data and optionally device configuration information. However, it is
possible to successfully compile a source file that contains data only. In this case the source code
typically will contain #pragma cdata statements with FLASH or EEPROM data.
The hex file is produced only there are no errors during compilation. The compiler may also produce
other files by setting some command line options:
• assembly, variable, list, function outline, debugging, preprocessor output and error files
:BBaaaaTT112233...CC
BB - number of data words of 8 bits, max 16
aaaa - hexadecimal address (byte-address)
TT - type :
00 : normal objects
01 : end-of-file (:00000001FF)
11 - 8 bits data word
CC - checksum - the sum of all bytes is zero.
:BBaaaaTT111122223333...CC
BB - number of data words of 16 bits, max 8
aaaa - hexadecimal address (of 16 bit words)
TT - type :
00 : normal objects
01 : end-of-file (:00000001FF)
1111 - 16 bits data word
CC - checksum - the sum of all bytes is zero.
The records in the HEX file are sorted according to the address. Option -chu will disable this sorting for
backward compatibility with older compiler versions (version 3.2R and earlier).
The compiler will use __config and __idlocs in the generated assembly file when #pragma config is used
in the source. The old assembly format is still available by using the command line option -cfc.
Command line option -Ma will truncate all automatic generated labels in the assembly and list files. This
option is sometimes useful when comparing assembly files generated by different compiler versions.
There are many command line options which change the assembly file produced. Please note the
difference between the -a and the -A options. The -a option is needed to produce an assembly file, while
the -A option changes the contents of the assembly and list files.
108
CC5X C Compiler B Knudsen Data
Some examples:
Default : ; x++;
m001 INCF x
-AsDJ : m001 INCF 10 ; x++;
-Ac : m001 INCF x
-AJ6+8+11 : m001 INCF x ; x++;
-AiJ1+6+10 : m001
INCF x ;x++;
-AiJs1+6+6 : m001
INCF 0Ah ;x++;
The general format is -V[rnuDGg]. The additional letters allows the file contents to be adjusted:
109
CC5X C Compiler B Knudsen Data
C : const variable
Examples:
X B Address Size #AC Name
P [-] 0x000 1 : 0: INDF
R [-] 0x006.0 0 : 1: in
R [-] 0x00B 1 : 10: alfa
P [-] 0x00B 1 : 12: fixc
L [-] 0x00D 1 : 1: lok
L [0] 0x012.0 0 : 6: b1
G [0] 0x012.1 0 : 16: bx
G [0] 0x015 1 : 23: b
When a function is not called (unused), all its parameters and local variables are truncated to the same
location. Example:
L [-] 0x00F 1 : 16<> pm_2_
Options -VG and -Vg will list the available device configuration bit symbols (config as found in the
device header file) at the end of the variable list file. Note that option -VG will list the default settings
enabled and not the actual settings for the project. The intension of the list is to provide an easy way to
copy-and-paste the config symbols into a C source file where the actual settings can be decided by simple
editing of the list. Example listing for option -VG:
110
CC5X C Compiler B Knudsen Data
Format sample:
F: function1 :#1 : p0 <- p1
func2 : #5 : p0 -> p3 **
delay : #2 : p0 -> p2 *
func3 : #3 : p0 -> p0
The call structure is expanded recursively. The indentation show the nesting of the function calls in the
source. The true call level is printed at the beginning of the line. The true call level is different from the
indentation level when CALL's have been replaced by GOTO's. A mark is then printed at the end of the
line in such cases. The interrupt call level is handled automatically and checked. There is a separate
expansion for the interrupt service routine.
L0 main
L1 function1
L2 func2
L2 delay
L2 func3
L1 function1 ..
The option format is -B[pims] where the additional letters allow some alternatives:
p : partial preprocessing
i : no include files
m: modify symbols
s : modify strings
Compilation will stop after preprocessing when using any of the additional letters.
111
CC5X C Compiler B Knudsen Data
9 APPLICATION NOTES
9.1 Delays
Delays are frequently used. There are various methods of generating them:
void delay10(char n)
/*Delays a multiple of 10 millisec.
Clock : 4 MHz => period T = 0.25 microsec.
DEFINITION: 1 is = 1 instruction cycle
error: 0.16 percent
*/
{
char i;
OPTION = 7;
do {
clrwdt(); /* only if necessary */
i = TMR0 + 39; /* 256 us * 39 = 10 ms */
while (i != TMR0)
;
} while (--n > 0);
}
void _delay10(char x)
/*
Delays a multiple of 10 millisec.
Clock : 32768 Hz => period T = 30.518 microsec.
DEFINITION: 1 is = 1 instruction cycle
= 4 * T = 122 microsec
10 ms = 82 is (81.92) => error: 0.1 percent
*/
{
char i;
do {
i = 26; /* 2 is */
do
i = i - 1;
while (i > 0); /* 26 * 3 - 1 = 77 is */
112
CC5X C Compiler B Knudsen Data
char counter;
void main(void)
{
if (TO == 1) {
/* power up or MCLR */
PORTA = 0; /* write output latch first */
TRISA = 0; /* all outputs */
TRISB = 0xFF; /* all inputs */
}
else {
/* watchdog wakeup */
counter -= 1;
if (counter > 0) {
OPTION = 0x0B; /* WDT divide by 16 */
sleep(); /* waiting 16 * 18 ms =
288 ms = 0.288 seconds */
}
}
delay(100); /* 100 millisec */
/* .. */
delay10(100); /* 1 second */
/* .. */
counter = 7; /* 7*0.288ms = 2000 ms */
OPTION = 0x0B; /* 0 1011 : WDT divide by 16 */
/* sleep(); waiting 16*18 ms = 0.288 seconds */
} /* total of 2 seconds, low power consumption */
WARNING: Designing computed goto's of types not described in this section may fail. The generated
assembly file will then have to be studied carefully because optimization and updating of the bank
selection bits can be wrong.
The 12 bit core requires that all destinations of the computed goto are within the first half code page. The
14 bit core requires that PCLATH is correctly updated before loading PCL. The compiler can do ALL
updating and checking automatically. Study the following code samples.
char sub0(char i)
{
skip(i); // jumps 'i' instructions forward
#pragma return[] = "Hello world"
#pragma return[] = 10 "more text" 0 1 2 3 0xFF
113
CC5X C Compiler B Knudsen Data
return 110;
return 0x2F;
}
char sub01(char W)
{
skip(W); // using W saves one instruction
#pragma return[] = "Simple, isn't it" 0
/* skip(W) is allowed on the 12 bit core and for
the first 256 addresses of the 14 bit core */
}
When using the -GS option, CC5X will generate an error if the table cross a 256 word code address
boundary. The short format enables most compact code, but requires manually moving the table in the
source code if the error is produced.
Origin alignment
It is possible to use #pragma origin to ensure that a computed goto inside a function does not cross a 256
word address boundary. However, this may require many changes during program development. An
alternative is to use #pragma alignLsbOrigin to automatically align the least significant byte of the origin
address. Note that this alignment is not possible when using relocatable assembly, and also that it does
not apply to the 12 bit core.
Example: A function contains a computed goto. After inspecting the generated list file, there are 16
instructions between the function start and the first destination address (offset 0) right after the ADDWF
PCL,0 instruction that perform the computed goto. The last destination address (offset 10) resides 10
instructions after the first destination. A fast a compact computed goto requires that the first and last
destination resides on the same “byte page” (i.e. (address & 0xFF00) are identical for the two addresses).
This is achieved with the statement:
The alignment pragma statement is not critical. The compiler will generate an error (option -GS) or a
warning (-GW) if the computed goto cross a boundary because of a wrong alignment. An easier approach
is to align the LSB to a certain value (as long as program size is not critical).
114
CC5X C Compiler B Knudsen Data
Examples
char sub01(char W)
{
/* The computed goto region can be constructed
just as in assembly language. However, '#pragma
computedGoto' should be inserted around such a
region. Otherwise unexpected results may
occur. */
#pragma computedGoto 1
PCLATH = 0; // 14 bit core only
PCL += W;
/* 14 bit core: REMEMBER to make sure that the
function is located within the first 256
addresses. (There is no warning on this when
'skip(W)' is NOT used) */
return 'H';
return 'e';
return 'l';
return 'l';
return 'o';
#pragma computedGoto 0
}
char sub02(void)
{
/* H_dst,L_dst : index to the desired element,
starting from 0 */
#define CGSTART 0x100
PCLATH = CGSTART/256 + H_dst; // MSB offset
PCL = L_dst; // GLOBAL JUMP AT THIS POINT
return W; // dummy return, never executed
115
CC5X C Compiler B Knudsen Data
char sub02r(void)
{
#pragma computedGoto 2 // start of large table
#pragma return[] = "ALFA"
#pragma return[] = 0x10 0x11
..
}
#pragma origin 0x0320
/* using an origin statement after a large return
table is useful to check the number of return
instructions generated. In this case, there
should be 0x320-0x100=0x250=544 instructions.
If not, any differences will be reported by
the compiler, either as an error, or as a
message. */
void sub3(char s)
{
/* the next statements could also be written as
a switch statement, but this solution is
fastest and most compact. */
if (s >= 3)
goto Default;
skip(s);
goto Case0;
goto Case1;
goto LastCase;
#pragma computedGoto 0 // end of c-goto region
Case0:
/* user statements */
return;
Case1:
LastCase:
/* user statements */
return;
Default:
/* user statements */
return;
}
void sub4(char s)
{
/* this solution can be used if very fast execution is important
and a fixed number of instructions (2/4/8/..) is executed at
116
CC5X C Compiler B Knudsen Data
if (s >= 10)
goto END;
Carry = 0;
s = rl(s); /* multiply by 2 */
s = rl(s); /* multiply by 2 */
skip(s);
/*
NOTE: "goto END" is necessary for ALL cases if the function is
called from another codepage. NOTE: '#pragma optimize ..' can
be useful in this situation. If the call level is too deep, note
that the compiler can only replace CALL by GOTO if there are few
'return constant' inside the function.
*/
}
char select(char W)
{
switch(W) {
case 1: /* XORLW 1 */
/* .. */
break;
case 2: /* XORLW 3 */
break;
case 3: /* XORLW 1 */
case 4: /* XORLW 7 */
return 4;
case 5: /* XORLW 1 */
return 5;
}
return 0; /* default */
}
The compiler performs a sequence of XORLW <const>. These constants are NOT the same as the
constants written in the C code. However, the produced code is correct! If more compact code is required,
then consider rewriting the switch statement as a computed goto. This is very efficient if the cases are
close to each other (i.e. 2, 3, 4, 5, ..).
117
CC5X - APPENDIX B Knudsen Data
APPENDIX
A1 Using Interrupts
#include "int16CXX.H"
#pragma origin 4
interrupt int_server(void)
{
int_save_registers // W, STATUS (and PCLATH)
/* It is recommended to use int_save_registers and
int_restore_registers on all devices for compatibility */
/* Note 1: The Enhanced 14 bit core has hardware register
save and restore of W, STATUS, BSR, FSRx and PCLATH */
/* Note 2: The Enhanced 12 bit core has hardware register
save and restore of W, STATUS, BSR and FSR */
if (T0IF) {
/* TMR0 overflow interrupt */
TMR0 = -45;
if (pin1 == 1)
pin1 = 0;
else
pin1 = 1;
T0IF = 0; /* reset flag */
}
if (INTF) {
/* INT interrupt */
INTF = 0; /* reset flag */
}
if (RBIF) {
/* RB port change interrupt */
W = PORTB; /* clear mismatch */
RBIF = 0; /* reset flag */
}
/*
NOTE: GIE is AUTOMATICALLY cleared on interrupt entry and set
to 1 on exit (by RETFIE). Setting GIE to 1 inside the
interrupt service routine will cause nested interrupts
if an interrupt is pending. Too deep nesting may crash
the program !
*/
int_restore_registers // W, STATUS (and PCLATH)
}
void main(void)
{
118
CC5X - APPENDIX B Knudsen Data
#ifdef _16C71
ADCON1 = bin(11); /* port A = digital */
#endif
#if defined _16F873 || defined _16F874 || defined _16F876 || \
defined _16F877
ADCON1 = 0b0110; // PORT A is digital
#endif
PORTA = 0; /* 76543210 */
TRISA = 0b11111001;
Core 12:
char W;
char INDF, TMR0, PCL, STATUS, FSR, PORTA, PORTB;
char INDF0, RTCC, PC; // alternative names
char OPTION, TRISA, TRISB;
char PORTC, TRISC;
bit Carry, DC, Zero_, PD, TO, PA0, PA1, PA2;
bit FSR_5, FSR_6;
Core 14:
char W;
char INDF, TMR0, PCL, STATUS, FSR, PORTA, PORTB;
char INDF0, RTCC, PC, OPTION; // alternative names
char OPTION_REG, TRISA, TRISB;
char PCLATH, INTCON;
bit PS0, PS1, PS2, PSA, T0SE, T0CS, INTEDG, RBPU_;
bit RTE, RTS; // alternative names
bit Carry, DC, Zero_, PD, TO, RP0, RP1, IRP;
bit RBIF, INTF, T0IF, RBIE, INTE, T0IE, GIE;
bit RTIF, RTIE; // alternative names
bit PA0, PA1; // PCLATH
119
CC5X - APPENDIX B Knudsen Data
A3 Assembly Instructions
Assembly: Status: Function:
NOP - - No operation
MOVWF f - f = W; Move W to f
CLRW - Z W = 0; Clear W
CLRF f Z f = 0; Clear f
SUBWF f,d C,DC,Z d = f - W; Subtract W from f
DECF f,d Z d = f - 1; Decrement f
IORWF f,d Z d = f | W; Inclusive OR W and f
ANDWF f,d Z d = f & W; AND W and f
XORWF f,d Z d = f ^ W; Exclusive OR W and f
ADDWF f,d C,DC,Z d = f + W; Add W and f
MOVF f,d Z d = f; Move f
COMF f,d Z d = f ^ 255; Complement f
INCF f,d Z d = f + 1; Increment f
DECFSZ f,d - Decrement f, skip if zero
RRF f,d C Rotate right f through carry bit
RLF f,d C Rotate left f through carry bit
SWAPF f,d - Swap halves f
INCFSZ f,d - Increment f, skip if zero
120
CC5X - APPENDIX B Knudsen Data
Note:
d = 1 : destination f: DECF f : f = f - 1
d = 0 : destination W: DECF f,W : W = f - 1
f : file register 0 – 31, 0 – 127
mm : increment ++, or decrement --
Z : Zero bit : Z = 1 if result is 0
C : Carry bit :
ADDWF : C = 1 indicates overflow
SUBWF : C = 0 indicates overflow
RRF : C = bit 0 of file register f
RLF : C = bit 7 of file register f
DC : Digit Carry bit :
ADDWF : DC = 1 indicates digit overflow
SUBWF : DC = 0 indicates digit overflow
TO : Timeout bit
PD : Power down bit
121