Home
C Compiler for the PIC18 Devices User`s Manual
Contents
1. File modulel lkr is generated by the compiler when using option r2 and defines intserv18 and page CODEPAGE NAME idlocs START 0x200000 END 0x200007 PROTECTED CODEPAGE NAME config START 0x300000 END 0x30000D PROTECTED CODEPAGE NAME devid START 0x3FFFFE END 0x3FFFFF PROTECTED CODEPAGE NAME eedata START 0xF00000 END OxF000FF PROTECTED ACCESSBANK NAME accessram START 0x0 END 0x7F DATABANK NAME gpr0 START 0x80 NAME gpr1 START 0x100 END Ox1FF DATABANK NAME gpr2 START 0x200 END 0x2FF DATABANK NAME gpr3 START 0x300 END 0x3FF DATABANK NAME gpr4 START 0x400 END 0x4FF DATABANK NAME gpr5 START 0x500 END 0x5FF ACCESSBANK NAME accesssfr START 0xF80 END OxFFF PROTECTED SECTION NAME STARTUP ROM vectors Reset vector SECTION NAME ISERVER8 ROM intserv8 High priority interrupt SECTION NAME ISERVER18 ROM intservi18 Low priority interrupt SECTION NAME PROG ROM page code space SECTION NAME IDLOCS ROM idlocs ID locations SECTION NAME CONFIG ROM config Configuration bits loc SECTION NAME EEDATA ROM eedata EEPROM data SECTION NAME ACSRAM RAM accessram ACCESS RAM SECTION NAME BANKO RAM gpr0 RAM bank 0 SECTION 1 RAM gpri RAM bank 1 SECTION NAME BANK2 RAM gpr2 RAM bank 2 SECTION NAME BANK3 RAM gpr3 RAM bank 3 SECTION NAME BANK4 RA
2. SECTION NAME CONF IG ROM config Configuration bits location SECTION NAME EEDATA ROM eedata EEPROM data SECTION NAME ACSRAM RAM accessram ACCESS RAM SECTION NAME BANKO RAM gpr0 RAM bank 0 SECTION NAME BANK1 RAM gpri RAM bank 1 SECTION NAME BANK2 RAM gpr2 RAM bank 2 SECTION NAME BANK3 RAM gpr3 RAM bank 3 SECTION NAME BANK4 RAM gpr4 RAM bank 4 SECTION NAME BANK5 RAM gpr5 RAM bank 5 CHANGE 5 modifications when using ICD2 CODEPAGE NAME page START END 0x7DBF CODEPAGE NAME debug START 0x7DCO END 0X7FFF PROTECTED DATABANK NAME gpr5 START 0x500 END 0x5F3 DATABANK NAME dbgspr START 0x5F4 END 0x5FF PROTECTED Logical code blocks STARTUP startvector ISERVER8 logical section for the high priority interrupt ISERVER18 logical section for the low priority interrupt PROG code space CONFIG config word IDLOCS id locations EEDATA EEPROM data Logical RAM blocks ASCRAM Access RAM BANKO bank 0 1 bank 1 2 bank 2 bank 3 BANK4 bank 4 BANK5 bank 5 1 5 bank 15 Command line options Bank naming rbO is the name of the frist RAM bank default rbi is the name of the frist RAM bank Separate interrupt logical section named 8 15 18 r2 use name of current module module lkr r2 file
3. File globdefl h GLOBAL DEFINITIONS TO BE INCLUDED IN ALL C MODULES names assigned to port pins pragma bit in 0 fpragma bit out PORTA 1 modulel c extern bankO char a module2 asm extern bankl char result extern char reverse char W ACKCkCk ckCkck kk ck kCk ck kCck ck kCck ck kk ck kk ck k ck ck kck ck ck ck ck ck ck ck ck ck ck ck ck k ck ck k k k k k kkkkk MODULE2 ASM INCLUDE P18F452 INC 1 UDATA result RES 1 result holder tmp RES 1 temporary location count RES 1 loop counter GLOBAL result PROG CODE reverse GLOBAL reverse movlb 1 movwf tmp movlw 8 movwf count loop rrcf tmp 1 rlcf result 1 decfsz count F 1 goto loop movf result W 1 return END T ACkCkCk ckCkck kCck ck kCck ck kk ck ck ck ck kk ck kk ck kk ck k ck ck k ck ck ck ck ck ck ck k ck ck k k ck k ck k k k kkkkk File 18F452 LKR This example linker script file is for use with the r2 option However it is recommended to instead use th rsc option to let the compiler automatically generate and update the whole script LIBPATH CODEPAGE NAME vectors START 0x0 END 0x7 PROTECTED CODEPAGE NAME intserv8 START 0x8 END 0x17 INCLUDE modulel lkr 81 CC8E Compiler B Knudsen Data
4. Carry DC Zero_ Overflow Negative 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 skipL skipM swap decsnz incsnz addWFC subWFB SubFWB rlnc rrnc negate decadj multiply skipIfEQ skipIfLT SkipIfGT skiplIfZero pushStack popStack softReset tableRead tableReadInc tableReadDec tableReadPreInc tableWrite tableWriteInc tableWriteDec tableWritePreInc Extensions to the standard C keywords bankO 15 bit fixed8 8 fixed24 8 floati16 float24 float32 int8 intl6 int24 int32 interrupt accessBank shrBank Sizel size2 uns8 uns16 uns24 uns32 Standard C keywords used auto break case char const continue default double enum extern do else float for goto if inline int long return short signed sizeof static struct switch typedef union unsigned void while define elif ifdef ifndef include endif error pragma undef The remaining standard C keywords are detected and compiled One is ignored register and the rest cause a warning to be printed volatile line Automatically defined macros and symbols The following symbols are automatically defined when using the CC8E compiler and can be used in preprocessor macros __ 8 Integer version
5. ECFSZ ECE OTO NCF NCFSZ INFSNZ IORLW IORWF LFSR MOVE OVFF MOVLB MOVLW MULLW ULWE N 2 Fh Eh A Aw Eh Eh Fh FH A Fh Fh Fh Ww Eh Eh Fh Fh O TBLWT 5 52 f a XORLW k XORWF f d a destination f destination W B Knudsen Data Skip if Skip if Skip if f W Decimal adjust W Decrement f skip if Decrement f skip if f W f2W not zero zero d 1 Decrement Go to address d f 1 Increment f Increment f skip if Increment f skip if zero not zero k Inclusive OR literal d f Inclusive OR W and f FSRx 12 bits literal d f ove f Move to BSR k W k Move literal to W f W Move to PRODH PRODL Multiply PRODH PRODL W f Multiply 1 Negat No operation Pop value from stack Push PC on stack Reset device Return put Return from Return from interrupt Rotate left f through carry bit Rotate left f Rotate right f through carry bit Rotate right f Relative call OxFF Set f Go into standby mode WDT 0 k W Subtract W from literal W Subtract W from f Subtract with borrow Subtract with borrow Swap halves
6. 9 1 5 SHORT PROGRAM EXAM DE ere n r e rae reae nenne trennen enne 10 1 6 DEFINING THE PICMICRO DEVICE 10 1 7 WHAT TO DO NEXT 11 2 VARTA BLES 12 2 1 INFORMATION ON RAM ALLOCATION ccsscccssscesscecseceseeecacceseeecsaeeeceeceaeceeeeecsaecseeeecsaeceeneesaeeeees 12 2 2 DEFINING V ARIABLES 12 Integer variables ede e A ie 13 eR CREE RUP Rn 13 IEEE754 interoperability creere et tete ORE eI etre ede EI deese 14 Fixed point varidbles eR An RS ERROR noh 15 Assigning variables to RAM addresses eese eene ene eene nennen trennen 16 Supported type modifiets at Re ti e etie te eed ete 18 Local variables sd e n uite eun e 18 Temporary variables RI etico Ri did 19 Arrays structufes and UNIONS uii e tee ede iP eer e eret e eire ce eoe 19 Bitfields 4 et n ADR REGI SB Enn 20 RN 20 23 USING RAM BANKS 20 Th DANK type modifier 4 s nel hee BSE Rae SUNY ns HR eS 21 Dank Sel eC HOM EE RI HEN eren ete Eh 21 Local user Update regions eise eer 21 ZA POINTERS ND 22 Pointer modelss oe be soies ome nm REB 22 2 9 CONST DATA SUPPORT iiid iiie e d c e eee up oe b ie eae psi 23 Data of size 1
7. eese 44 Zpragma SLACK LEVELS hm esee peret tete itte deest utt rentre eet 44 Zpr gma unlockl SR uice RU ORE RU SIRE 44 pragma updateBank entry exit default 0 1 seen 44 Zpragma versionFile lt file gt tt net 45 CC8E Compiler B Knudsen Data 4 2 PICMICRO CONFIGURATION 45 5 COMMAND LINE 46 OPTIONS IN P I PRA IR RR n iets 48 5 2 AUTOMATIC INCREMENTING VERSION NUMBER IN 49 6 PROGRAM CODE 50 6 1 PROGRAM CODE PAGES ER e b ridet teas 50 6 2 SUBROUTINE CALL LEVEL CHECKING 225 ent den 50 Stack level checking when using interrupt eese 50 Recursive functions eet ate de ARE HER te E He eee Mg t eee dip dee 50 OPS INTERRUPTS 50 Custom interrupt save and restore 53 6 4 STARTUP AND TERMINATION CODE 54 Clearing ALL RAM locations o etie site tede ea e dde tete edere retta 54 6 5 LIBRARY SUPPORT 5 eosdebet de mm edere d 54 rins P 54 Integer 55 F
8. NAME intservl8 START 0x18 END 0x31 START 0x32 END 0x7FFF The required change in the main script file is then INCLUDE modulel lkr change to right module script file name CHANGE 2 Interrupt routine in C WITHOUT a separate logical section Example change CODEPAGE NAME vectors 0 0 END 0x7 PROTECTED NEW VALUE CODEPAGE NAME page START 0x8 END 0x7FFF NEW VALUE CHANGE 3 If INTERRUPTS not used then the first code page start at address 4 Example change CODEPAGE NAME vectors START 0x0 END 0x3 PROTECTED NEW VALUE CODEPAGE NAME page START 0x4 END 0x7FFF NEW VALUE CHANGE 4 LOGICAL sections must be added Note that if a logical RAM section is missing then the variables that belongs 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 SECTION NAME STARTUP ROM vectors Reset vector SECTION NAME ISERVER8 ROM intserv8 High priority interrupt SECTION NAME ISERVER18 ROM intservl8 Low priority interrupt SECTION NAME PROG ROM page code space SECTION NAME IDLOCS ROM idlocs ID locations 77 CC8E Compiler B Knudsen Data
9. float32 exp10 float32 10 x range 37 9297794537 38 Input Accuracy ME 1 relative error 1565 2086 ono5 L0s 5 lt 6 10 8 834 words function 531839445 X 1739 basic 24 bit math 648 words function 531839445 55 2335 Timing min aver max Size 323 words 134 floor32 basic 32 bit math Minimum complete program example 840 words CA floa floa t24 sin float24 sine input in radians t24 cos float24 cosine input in radians Input range 512 0 512 0 Accuracy error lt 3 10 5 The relative error can be larger when the output is near 0 for example near sin 2 PI but the absolute error is lower than the stated value Timing min aver max 374 1195 1396 Size 211 words basic 24 bit math library Minimum complete program example 563 words float32 float32 sin float32 sine input in radians cos float32 cosine input in radians Input range 512 0 512 0 Can be used over a much wider range if lower accuracy is accepted degrades gradually to 1 significant decimal digit at input value 10 6 Accuracy error 1 2 10 7 The relative error can be larger when the output is near 0 for example near sin 2 PI but the absolute error is lower than the stated value Timing min aver max 1789 2193 2529 Size 352 words basic 32 bit math library Minimum complete program example 80
10. 3 ADDLW 256 3 b 35 Post and pre incrementing of pointers char Strep St cptt 10 ct d pre incrementing of variables t b 3 sum b 10 t tab 5 Conditions variable lt cond oper gt value amp amp condition condition cond oper gt gt lt lt if x if f amp amp al lt a2 it y gt 44 Carry x z if ees gt 0 if i lt max if 10 1 0 Bit variables bit d char i 3 bit bitfun void bit return type using Carry bit return 0 Clear Carry return return 1 Set Carry return nop return Carry return return b Carry b return return i return b amp PORTA 3 b bitfun2 bitfun 1 if bitfun if bitfun if bitfun 0 b charfun b charfun gt 0 bitfun Carry bitfun b amp bitfun 28 CC8E Compiler B Knudsen Data bitfun b bitfun PORTA 1 b conditional increment conditional decrement k Carry k Carry b Toggle bit b b 0 c assign inverted bit 0 Carry amp PORTA 0 PORTA 1 a PORTA 2 amp a Fh Fh O H H H H H H assign condition using 8 bit char variables b 11 b W b j 0 b k 0 b i gt 0 assig
11. 88 FILES PRODUCED 89 te edi 89 8 2 ASSEMBLY OUTPUT BIB 89 8 33 VARIABEEPILE S eese tee c e 90 SP IST EIEB se ORS SEN nU e C RI uices Lc ed 91 8 5 FUNCTION CALL STRUCTURE 91 9 APPLICATION NOTES eec ce tene to foe ees ioa o Ve sa a 92 COMPUTED GOTO ook eedem Hs 92 Built in skip skipL skipM functions for computed 200000021 92 Originalignment aoi hs en o eer pe ee ege eir edv ase Beste nage 92 Computed goto regions i e d aet e dye ote ede feud epu 93 Examples usc diee tested eaae depo tede etu oie GWA tete a oie eect etd edid 95 9 2 THE SWITCH STATEMENT ee testet eter etie tbe tete epe cea ste e os ite BES 95 APPENDIX C S 96 1 PREDEFINED REGISTER NAMES cccccescsccceseesssssccsccecsesssscescceceessssessseecesssessssseccecsesssesscescesseeseenees 96 A2 ASSEMBLY 5 ri 96 Instruction execution time eese thee 98 CC8E Compiler B Knudsen Data 1 INTRODUCTION Welcome to the CC8E C compiler for the Microchip PIC18 family of microcontrollers The CC8E compiler enables programm
12. TABLAT TBLPTR TABLAT TBLPTRt TABLAT TBLPTR TABLAT TBLPTR TBLPTR TABLAT TBLPTR TABLAT TBLPTR TABLAT TBLPTR TABLAT Skip if f 0 f W literal in W subroutine Exclusive OR literal Exclusive and f 97 8 APPENDIX Knudsen Data QN moe TO PD using BSR to select bank 0 15 using access bank 0x0 Ox7F OxF80 OxFFF file register Zero bit 7 1 if result is 0 Carry bit 1 indicates carry on addition 0 indicates borrow on subtraction Digit Carry bit DC 1 indicates carry on addition DC 0 indicates borrow on subtraction Timeout bit Power down bit Instruction execution time Most instructions execute in instruction cycle 4 clock cycles except branch instructions when PC is modified BC BRA RCALL skip instructions when next instruction is skipped double word instructions MOVFF LFSR GOTO CALL instructions that modify the program counter i e ADDWF PCL 98
13. Timing min aver max 1713 2377 2699 Size 264 words basic 32 bit math library Minimum complete program example 743 words float24 log10 f10at24 10410 function Input range positive number above zero Accuracy ME 1 2 relativ IIrOEr c G L0 5 op Timing min aver max 1293 1794 2067 Size 15 words size of log Minimum complete program example 599 words float32 log10 f10at32 10410 function Input range positive number above zero Accuracy ME 1 2 relativ cx 1 2 10 7 5 Timing min aver max 1840 2502 2793 Size 17 words size of log Minimum complete program example 760 words float24 exp float24 exponential e x function Input range 87 3365447506 88 7228391117 Accuracy ME 1 relative error lt 1 5 10 5 Timing min aver max 903 1539 1725 Size 247 words 95 floor24 basic 24 bit math Minimum complete program example 641 words float32 exp float32 exponential e x function Input range 87 3365447506 88 7228391117 Accuracy ME 1 relative error 6 10 8 Timing min aver max 1920 2073 2301 Size 317 words 134 floor32 basic 32 bit math 58 CC8E Compiler B Knudsen Data Minimum complete program example float24 exp10 float24 10 x Input range 37 9297794537 38 Accuracy ME 1 relative error Timing min aver max 917 1610 Size 254 words 95 floor24 Minimum complete program example
14. 2 2 Defining Variables CC8E supports integer fixed and floating point variables The variable sizes are 1 8 16 24 and 32 bit The default int size is 8 bit and long is 16 bit Char variables are unsigned by default and thus range from 0 to 255 Note that 32 bit integer variables are not supported by all CC8E editions Math libraries may have to be included for math operations Chapter 6 5 Library Support on page 54 CC8E 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 AII 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 in a specific RAM bank or in the access bank Tables and structures greater than 256 byte are allowed Note that variables are assigned to the access bank by default See Chapter 2 3 Using RAM Banks on page 20 on how to use RAM banks 12 CC8E Compiler B Knudsen Data Special purpose registers are either predefined or defined in chip specific header files This applies to WREG INDFO PCL STATUS FSRO Carry etc Integer variables unsigned a8 8 bit unsigned char a8 8 bit unsigned unsigned long 116 16 bit unsigned char varX char counter L byte H byte bit ready 0 or 1 bit flag stop se
15. MULLW 50 SkipIfLT f CPFSLT CPFSGT skipIfZero f pushStack popStack POP softReset RESET tableRead TBLRD tableReadInc TBLRD tableReadDec TBLRD tableReadPreInc TBLRD tableWrite TBLWT tableWriteInc TBLWT tableWriteDec TBLWT tableWritePreInc TBLWT STFSZ f I I N D M M skipIfEQ f CPFSEQ C T PUSH 68 CC8E Compiler B Knudsen Data 6 7 Optimizing the Code The CC8E compiler contains an advanced code generator which is designed to generate compact code For example when comparing a 32 bit unsigned variable with a 32 bit constant this normally requires 12 instructions When comparing a 32 bit variable with 0 this count is reduced to 5 The code generator detects and take advantage of similar situations to enable compact code 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 Testing multiple bits of 16 bit variables or greater 11516 x if x amp OxFO if x amp Ox3C if x amp OxF00 0x300 if x amp 0 7 00 lt 0 4000 Testing single bits using the amp operator if amp 0x10 BTFSC BTFSS a 4 if a amp 0x80 BTFSS BTFSC a 7 if 16 amp
16. pragma assume lt pointer gt in rambank n The Zpragma assume statement tells the compiler that a 8 bit RAM pointer operates in a limited address range Refer to Chapter 2 4 Pointers on page 22 for details pragma assume p in rambank 3 pragma bit name N B or variable B gt Defines the global bit variable name Useful for assigning a bit variable to a certain address Only valid addresses are allowed pragma bit bitxx 0x20 7 pragma bit rx FSROH 1 pragma bit C bit Carry 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 use the variable name from the first assignment instead of the address Zpragma bit var2 9 var1 pragma cdata ADDRESS VXS lt VXS gt The cdata statement can store 16 bit data in program memory at fixed addresses Refer to Chapter 6 9 The cdata Statement on page 82 for details pragma ADDRESS lt VXS gt lt VXS gt pragma cdata lt VXS gt ye 5 33 lt VXS gt pragma cdata IDENTIFIER lt VXS gt lt VXS gt ADDRESS 24 bit byte address VXS lt VALUE EXPRESSION STRING VALUE 0 OxFFFF EXPRESSION any valid C constant expression i e 0 1000 3 1234 STRING Valid String r n 0 x24 x8 xe xFF xff 40 CC8E Compiler B Knudsen Data pragma char lt name
17. Example usage include hexcodes h 1 In DW statements asm DW _ SLEEP Enter sleep mod DW __MOVWF __INDFO 0 Store indirectly DW __ANDLW 0x80 amp 0x80 DW ECF __FSROL __F 0 Decrement FSROL access bank A D DW CLRF OxFF 1 Clear ram banked access DW BCF STATUS 0 Clear Carry bit B B B DW 3 Branch 3 instruction words forward 0 RA DW RA 0 Branch 0 no operation DW _ BRA 1 Branch 1 backward infinite loop DW _ BC 2 Branch on Carry 2 words backwards DW MOVFF INDFO __INDF1 Move byte indirectly DW 5 0 0x130 Load 12 bit constant into FSRO DW __GOTO 0 Goto byte address 0 endasm 2 In cdata statements pragma cdata 1 __GOTO 0x3FF Generating single instructions using C statements 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 show how to generate single instructions from C code nop NOP f W 0 CLRE W f W SUBWF W 1 f f 1 W f amp W ANDWF f W f f amp W ANDWF W f W f W
18. computed goto single word SkipL i void skipL char computed goto double word SkipM i void skipM char computed goto mixed size swap k char swap char SWAPF k d W addWFC k char addWFC char ADDWFC k d 1 subFWB k char subFWB char SUBFWB k d 1 subWFB k char subWFB char SUBWFB k d rlnc i char rlnc char RLNCF i d 1 rrnc i char rrnc char RRNCF i d 1 decsnz i char decsnz char DCFSNZ f d incsnz i char incsnz char INFSNZ f d b negate b char negate char NEGF f decadj W char decadj char DAW multiply i void multiply char MULWF void multiply ij multiply 50 char MULLW literal SkipIfEQ a void skipIfEQ char CPFSEQ f SkipIfLT a void skipIfLT char CPFSLT f SkipIfGT a void skipIfGT char CPFSGT f SkipIfZero a void skipIfZero char TSTFSZ pushStack void pushStack void PUSH popStack void popStack void POP softReset void softReset void RESET tableRead void tableRead void TBLRD tableReadInc void tableReadInc void TBLRD tableReadDec void tableReadDec void TBLRD tableReadPreInc void tableReadPreInc void TBLRD tableWrite void tableWrite void TBLWT tableWriteInc void tableWriteInc void TBLWT tableWriteDec
19. gt the backslash character itself 0x5C gt 0 22 xHH or xH hexadecimal number 1Conflict is better written as 1 Conflict Strings are stored as 8 bit ASCII characters The least significant 8 bits of each code word are filled first Strings are aligned on word addresses for each lt VXS gt 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 pragma cdata ADDRESS set current cdata address fpragma cdata IDENTIFIER get current cdata address Only cdata within the valid code space is counted when calculating the total number of code words Using the cdata statement 1 Defining special startup sequences finclude hexcodes h pragma cdata 0 _ NOP pragma resetVector 2 goto main at byte address 2 2 Storing packed strings and other data 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 define CDATA_START 0x80 pragma cdata CDATA START start of cdata block pragma cdata OxFFFF 0 2000 0x1000 pragma cdata 0 100 10 lt lt 4 3456 10 456 10000 define 18 1 1 1
20. kp vx 0 036 kp vx 1 0 0 036 How to save code Choices that influence code size 1 What libraries to include 24 32 bit float or fixed point 61 CC8E Compiler B Knudsen Data 2 Rounding can be disabled permanently Note that this will reduce the accuracy of the math functions slightly define DISABLE ROUNDING include math32f h 3 Optimization Note that optimize for speed is default Also note that the code saving is small 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 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 or 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 Automatic type conversion integer lt gt float double integer lt gt fixed point float lt gt double fixed point lt gt float double requires additional functions In general using the smallest possible data type will save code and RAM space This must be balanced against
21. pragma accessGPR lt n gt The number of RAM bytes in the access bank can be defined The default setting is 128 0x80 The start address of the SFR regeisters in the access bank at the end of the data space will also change accordingly This statement is normally found in the chip header files pragma accessGPR 0x60 access RAM from 0 to Ox5F pragma alignLsbOrigin lt a gt to lt b gt This pragma statement allows the origin to be aligned The compiler will check if the least significant byte of the origin address is equal to lt a gt or alternatively within the range lt a gt to lt b gt If this is not true 39 CC8E Compiler B Knudsen Data the origin is incremented until the condition becomes true Both lt a gt and lt b gt may range from 254 to 254 and should be even numbers pragma alignLsbOrigin 0 pragma alignLsbOrigin 6 to 100 fpragma alignLsbOrigin 0 to 190 254 254 fpragma alignLsbOrigin 100 to 10 Such alignment is useful to make sure that a computed goto does not cross a 256 byte address boundary More details are found in Section Origin alignment on page 92 in Chapter 9 1 Computed Goto pragma asm2var 1 Enable equ to variable transformation Defined in Chapter 6 6 Inline Assembly page 62 pragma assert lt type gt lt text field gt Assert statements allows messages to be passed to the simulator emulator etc Refer to Chapter 7 3 Assert Statements on page 87 for details
22. binary x 0x1234 256 0 12 MSB x 0x1234 256 0x34 LSB x 33 4 1 x OxF amp OxF3 3 0 2 0 8 10 x 0 2 OXF 051101 x 0510 lt lt 2 8 x err 3 8 2 22 x 3 99 4 67 2 167 x OxF amp OxF3 1 4 16 Please note that parentheses are required in some cases Constant expressions The size of integers is by default 8 bits for this compiler other C compilers use typically 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 10 100 256 an error is printed 101 100 256 error uns16 10 100 256 no error a uns16 10 100 256 error again a 10 200 256 no error 200 is a long int Adding a L means conversion to long 16 bit The command line option cu force 32 bit evaluation of constants so that no significant bits are lost Some new built in types can also be used TYPE SIZE MIN MAX int8 8 bit signed 1 128 127 int16 16 bit signed 2 32768 32767 int24 24 bit signed 3 8388608 8388607 int32 32 bit signed 4 2147483648 2147483647 uns8 8 bit unsigned 1 0 255 11516 16 bit unsigned 2 0 65535 uns24 24 bit unsigned 3 0 16777215 uns32 32 bit unsigned 4 0 4294967295 30 CC8E Compiler B Knud
23. h 256 define D32 0 10000 x 0x10000 pragma cdata 18 10 20 32 10234543 pragma cdata IDO 0 10 200 3000 pragma cdata ID1 Hello world 0 pragma cdata ID2 Another string r n merged H I pragma cdata ID TABLE IDO ID1 1 2 store addresses E ND end of cdata block pragma cdata CDATA pragma origin CDATA END program code follow here void write unsl6 strID 83 CC8E Compiler B Knudsen Data write ID1 write ID2 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 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 Preprocessor statements can be used for checking size during compilation dif CDATA END CDATA START gt 20 derror This is too much endif Storing EEPROM data EEPROM data can be put into the HEX file at addresses OXF00000 an
24. void tableWriteDec void TBLWT tableWritePreInc void tableWritePreInc void TBLWT The internal rotate functions rl rr are also available for the larger variable sizes al6 1 16 16 bit left rotation a32 rr a32 32 bit right rotation Note that skip 1 requires that all instructions in the table are single word single word increments Similarly skipL requires that all instructions in the table are double words GOTO CALL etc and the skipL argument skips double words on each increment The compiler will adapt the optimization to this 32 CC8E Compiler B Knudsen Data need and print an error message if this is not possible The skipM i allows both double and single word instructions in the table but note that the skipM use single word increments when calculating the offset The inline function 20 is implemented by a BRANCH to the next address Thus nop2 can replace two to get more compact code The main use of and 2 is to design exact delays in timing critical parts of the application 3 5 Type Cast Constants and variables of different types can be mixed in expressions The compiler converts them automatically to the same type according to the stated rules For example the expression consists of 2 separate operations The first is the plus operation and the second is the assignment The type conversion rules are first applied t
25. and bank updating Instructions updating the bank 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 default local assembly settings are b o pragma asm default b change default settings asm using default local settings endasm asm b o define local settings pragma asm change setting in assembly mode endasm end current local settings Interpretation o current optimization is performed in assembly mode no optimization in assembly mode b current bank bit updating is performed in assembly mode b no bank bit update in assembly mode Note that b 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 will switch updating off globally The corresponding source code settings are then ignored Direct coded instructions The file hexcodes h contains C macro s that allow direct coding of instructions 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 high level properties are lost The compiler will reset optimization bank updating etc after a DW statement 66 CC8E Compiler B Knudsen Data
26. endasm 0 THIS is the conditional statement Inline assembly supports DW This can be used to insert data or special instructions CC8E 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 asm DW OxFFFF any data or instruction 2 bytes stored DW OxFFFF 0 0 000 multiple words fendasm Assembly instructions are not case sensitive However variables and symbols requires the right lower or upper case on each letter clrwdt Nop NOP The supported operand formats are k EXPR fa VAR EXPR A f d a VAR EXPR D A f b a VAR EXPR EXPR A fs fd VAR EXPR VAR EXPR VAR EXPR EXPR a LABEL or FUNCTION_NAME EXPR EXPR EXPR EXPR EXPR valid constant expression plus assembly extensions Constant formats OVLW 10 decimal radix is default OVLW OxFF hexadecimal MOVLW 0b010001 binary C style MOVLW a character style MOVLW 31 decimal constant OVLW 31 20 1 plus and minus are allowed MOVLW H FF hexadecimal radix 16 MOVLW h OFF MOVLW B 011001 binary radix 2 MOVLW b 1110 1101 OVLW D 200 decimal radix 10 OVLW d 222 MOVLW MAXNUM24EXP defined by EQU or define MOVLW 22h NOT allowed Note that the specifica
27. multiplication and division by a multiple of 2 i e 0 5 b 1024 0 4 0 basic math library basic math library Approx CYCLES min aver max 128 132 139 441 495 580 38 123 193 45 130 200 41 66 110 36 74 137 Approx CYCLES min aver max 78 81 93 270 297 345 32 104 161 39 LEL 168 33 60 95 31 68 112 Approx CYCLES min aver max 46 49 5 121 136 151 26 80 123 33 87 130 37 65 98 26 57 96 57 CC8E Compiler B Knudsen Data Floating point library functions float24 sqrt float24 square root Input range positive number including zero Accuracy ME 1 2 relativ cx Timing min aver max 637 706 782 QR Size 153 words basic 24 bit math library Minimum complete program example 382 words float32 sqrt float32 square root Input range positive number including zero Accuracy ME 1 2 relativ rrore x L 2 190 73 Timing min aver max 1699 1893 2200 Size 168 words basic 32 bit math library Minimum complete program example 580 words float24 log float24 natural log function Input range positive number above zero Accuracy ME 1 relative error 1 5 10 5 Timing min aver max 1210 1714 1985 Size 210 words basic 24 bit math library Minimum complete program example 584 words float32 log float32 natural log function Input range positive number above zero Accuracy ME 1 relative error 6 10 8
28. 0x200 0 55 5 16 1 1 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 command line option The optimization steps are 1 redirect goto to goto 2 remove superfluous gotos 3 replace goto by skip instructions 4 replace INCF and DECF by INCFSZ and DECFSZ 5 remove instructions that affects the zero flag only 6 remove superfluous updating of PAO and 1 7T remove other superfluous instructions 8 remove superfluous loading of the W register 9 to be defined 10 inserts TSTFSZ CPFSEQ 11 inserts branch NOTE Optimization can also be switched on or off in a local region Please refer to the Zpragma optimize statement for more details 6 8 Linker Support CC8E supports the relocatable assembly format defined by Microchip This means that MPLINK can be used to link code modules generated by CC8E 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 external functions and variables ram bank updating call level checking MPLINK script files 69 CC8E Compiler B Knudsen Data e MPLAB integration The command line option or r2 or r makes CC8E generate relocatable assembly This file is then assembled by
29. 99609375 80 00 128 Convention fixed S I D S U unsigned none signed lt I gt number of integer bits D number of decimal bits Thus fixed16 8 uses 16 bits for the integer part plus 8 bits for the decimals 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 Built in fixed point types Type bytes Range Resolution fixed8 8 2 1 1 128 127 996 0 00390625 fixed8 16 3 1 2 128 127 99998 0 000015259 fixed8 24 4 1 3 128 127 99999994 0 000000059605 fixedl16 8 3 Q2 T1 32768 32767 996 0 00390625 fixed16 16 4 2 2 32768 32767 99998 0 000015259 fixed24 8 4 3 1 8388608 8388607 996 0 00390625 fixedU8_8 2 1 1 0 255 996 0 00390625 fixedU8_16 3 1 2 0 255 99998 0 000015259 fixedU8_24 4 1 3 0 255 99999994 0 000000059605 fixedU16_8 3 2 1 0 65535 996 0 00390625 fixedU16_16 4 2 2 0 65535 99998 0 000015259 fixedU24_8 4 3 1 0 16777215 996 0 00390625 additional types with decimals only no integer part fixed_8 1 0 1 0 5 0 496 0 00390625 fixed_16 2 0 2 0 5 0 49998 0 000015259 fixed_24 3 0 3 0 5 0 49999994 0 000000059605 fixed_32 4 0 4 0 5 0 4999999998 0 0000000002328 fixedU_8 1 0 1 0 0 996 0 00390625 fixedU_16 2 0 2 0 0 99998 0 000015259 15 CC8E Compiler B Knudsen Data fixedU_24 3 0
30. 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 Command line options rsc file lkr generate relocatable assembly and use separate logical sections for the interrupt routines Also generate or update the complete linker script file If the linker script file name is not specified then the C module name will be used with the extension lkr The script file will only be generated when compiling the module containing main r2 file lkr generate relocatable assembly with separate logical sections for the interrupt routines A partial linker script file containing dynamic definitions of page and intserv8 or intserv18 is generated and should be included in the main linker script file If the partial linker script file name is not specified then the C module name will be used with the extension lkr r generate relocatable assembly without separate logical sections for the interrupt routines NO linker script file is generated rx make variables static by default External assembler options x file assembler executable xC progra 1 m
31. The compiler will print a warning when detecting more than one inline math integer operation of the same type Including a math library will save code but execute slightly slower Note that assembly code inspection and type casts are sometimes needed to reduce the number of library functions inserted The warning can be disabled by the wi command line option 60 CC8E Compiler B Knudsen Data Fixed point example pragma chip PIC18C242 include math24x h 11516 data fixed16_8 tx av mg a vx prev kp void main void vx 3 127 tx data automatic type cast data kp assign integer part if tx lt 0 tx tx make positive av tx 20 0 mg av 1 25 0 98 0 980469 error 0 000478 prev vx 5 0 prev kp vx 0 036 0 03515626 error 0 024 kp vx 1 0 0 036 27 7773437 CODE 266 code words including library 129 Floating point example CODE 596 code words including library 424 The statements are identical to the above fixed point example to enable code size comparison pragma chip PIC18C242 include math24f h unsi6 data float tx av mg a vx prev kp void main void InitFpFlags enable rounding as default vx 3 127 tx data automatic type cast data kp assign integer part lf C lt 10 tx tx make positive av tx 20 0 mg av 1 25 0 98 prev vx vx 5 0 prev
32. be adjusted r only variables which are referenced in the code n sort variables by name u keep the variables unsorted D use decimal numbers Variable file contents X B Address Size Name X gt L local variable G global variable P assigned to certain address E extern variable R overlapping directly assigned 2 const variable Biz we access RAM O0 bank 0 1 bank 1 etc Address gt 0 00 file address Ox00C 0 bit address file bit number Size gt size in bytes 0 for bit gt 12 number of direct accesses to the variable Examples X B Address Size AC Name 0 00 1 10 alfa 0x00B 1 12 5 fixc L 0 00 1 15 lok L 0 0 012 0 0 6 bl 0 0 012 1 0 16 bx 0 0x015 1 23 b 90 CC8E Compiler B Knudsen Data When a function is not called unused all its parameters and local variables are truncated to the same location Example L 0 00 1 16 lt gt pm_2_ 8 4 List File The compiler can also produce a list file The command line option is L or L lt col gt lt lin gt The maximum number of columns per line lt col gt and lines per page lt lin gt can be altered The default setting is L200 60 The contents of the list file can be changed by using the A option 8 5 Function Call Structure The function call structure can be written to file lt src gt fcs This is useful for codepage optimization and function
33. 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 updateBank 3 command line option u 4 command ine option bu 5 command line option b ALW AYS remember to report instances of compiler bugs to B Knudsen Data 7 1 Compilation Errors The compiler prints error messages when errors are detected The error message is proceeded by 2 lines of source code and a marker line indicating where the compiler has located the error The printing of source and marker lines can be switched off by the e command
34. gt lt constant or variable gt Defines the global variable lt name gt Useful for assigning a variable to a certain address Only valid addresses are allowed pragma char i 0x20 pragma char PORTX PORTC 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 use the variable name from the first assignment instead of the address Zpragma char var2 varl pragma chip device Defines the chip type This allows the compiler to select the right boundaries for code and memory size variable names etc Note that the chip type can also be defined as a command line option fpragma chip PIC18C242 This statement have to proceed any normal C statements but some preprocessor statements like if and define can be compiled first The supported devices are defined in a PICmicro header file i e 18C242 h It is also possible to make new header files Refer to file chip txt for details computedGoto 0 1 This statement can be used when constructing complicated computed goto s Refer to Chapter 9 7 Computed Goto on page 92 for details fpragma computedGoto 1 start region pragma computedGoto 0 end of region pragma config lt offset gt expression This statement allow PICmicro configuration information to be put in the generated hex and assembly file ID locations can al
35. line option The maximum number of errors printed can also be altered Setting the maximum to 12 lines is done by the command line option E12 The format of the error messages is Error filename line number error message 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 macro s 85 CC8E 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 Error and warning details The compiler prints a short description of the error message to the output screen and to the occ file but not to the err file Note that the description will not be visible when enabling the error file in MPLAB The occ file can then be opened and inspected do not print error details disable do not print warning details disable eL list error and warning details at the end Some common compilation problems e not enough variable space Solution Some redesign is required The scope of local variables can be made more narrow A better overlapping strategy fo
36. of the interrupt service routine is as follows include int18XxXx h void _highPrioritylInt void pragma origin 0x8 interrupt highPriorityIntServer void W STATUS and BSR are saved to shadow registers handle the interrupt 8 code words available including call and RETFIE highPriorityInt restore W STATUS and BSR from shadow registers pragma fastMode pragma origin 0 18 interrupt lowPriorityIntServer void STATUS and BSR are saved by the next macro int_save_registers NOTE shadow registers are updated but will be overwritten in case of a high priority interrupt Therefore pragma fastMode should not be used on low priority interrupts save remaining registers on demand error warning uns16 sv FSRO FSRO uns16 sv 1 5 1 uns16 sv FSR2 FSR2 uns8 PCLATH PCLATH uns8 PCLATU PCLATU uns8 PRODL PRODL uns8 PRODH PRODH uns24 sv TBLPTR TBLPTR uns8 sv TABLAT TABLAT handle the interrupt restore registers that are saved FSRO sv FSRO FSR1L sv FSR1 FSR2 FSR2 PCLATH PCLATH PCLATU PCLATU PRODL PRODI PRODH sv PRODH TBLPTR sv TBLPTR TABLAT sv TABLAT int restore registers W STATUS and BSR 51 CC8E Compiler B Knudsen Data IMPORTANT GIEH GIE or GIEL shoul
37. pins and then define the input output configuration This avoids spikes at the output pins PORTA 05 0010 out 1 TRISA 0b 1111 0001 xxxx 0001 9 value assigned to global variable do if in 0 stop if in is low break sub while a gt 0 9 iterations if some condition goto WARM_RESET main is terminated by a SLEEP instruction 1 6 Defining the PICmicro Device CC8E offers 3 ways to select the PICmicro device in an application 10 CC8E Compiler B Knudsen Data 1 By a command line option MPLAB will generate this option automatically p18F242 2 By a pragma statement in the source code Note that the command line option will override the selection done by pragma chip pragma chip PIC18F242 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 finclude 18F242 n NOTE 1 When using a pragma statement or include file remember to use this the beginning of the C program so that it is compiled first However some preprocessor statements like Zdefine and may proceed the Zinclude Zpragma statement NOTE 2 CC8E will use automatic include of the right header file when using the p lt device gt or pragma chip statement NOTE 3 If the header file does not reside in the default project folder then the path name is required
38. pointer to program memory This pointer can access more than 256 byte data e 16 bit pointer to RAM or program memory Bit 15 is used to detect RAM or program memory access 2 5 Const Data Support CC8E supports constant data stored in program memory The C keyword const tells the compiler that these data do not change Examples const char ps Hello world const float ftx 1 0 33 34 1 3e 10 y t ps ps mans fx ftx i The compiler will normally insert const data at the end of the user code high address The following pragma statement will allow the const data to be inserted between two user functions or at a specific address if using ffpragma origin first pragma insertConst The implementation of constant data supports the following features e both 8 and 16 bit pointers to const data in the same application size of single const pointers can be chosen automatically e const pointers can access both RAM and program memory compiler will not put all constant data in a single table but rather make smaller tables if this saves code space e duplicate strings and other data are automatically merged to save space 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 bit or more
39. restructuring in case of call level problems Note that two different formats are produced the first is a list of functions the second is a recursive expansion of the function call structure The command line option is Q for both formats Format sample functionl 1 func2 5 delay 2 func3 3 The meaning of the symbols is 1 func2 delay and func3 are called from function 1 2 1 function is called once 3 3 func3 is called 3 times once from function 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 LO main 11 functionl L2 func2 L2 delay L2 func3 11 functionl Explanation of symbols used e LI stack level 1 max 31 levels This is the REAL stack level compensated when CALL s have been replaced by GOTO e only the first call is fully expanded if more that one call to the same function occur inside the same function body e CALL gt GOTO CALL replaced by GOTO in order to get more call levels e T GOTO CALL RETURN is replaced by GOTO to save a call level e RECURSIVE recursive funct
40. skip format I lt directory gt include files directory folder Up to 5 library directories can be supplied by using separate I dir options 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 lt dir gt The current directory is skipped when using include lt test h gt L lt col gt lt lin gt produce list file src lst The maximun number of columns per line col and lines per page lin can be changed The default setting is L80 60 LFSR do not use the LFSR instruction LFSR use the LFSR instruction mc1 default const pointer size is 1 byte 8 bits mc2 default const pointer size is 2 bytes 16 bits mr1 default RAM pointer size is 1 byte mr2 default RAM pointer size is 2 bytes mml default pointer size is 1 byte all pointer types mm2 default pointer size is 2 bytes all pointer types lt gt write hex file to name O lt directory gt output files directory Files generated by the compiler are put on this directory except when a full path name is supplied p lt device gt defines the chip type i e pPIC18C242 or p18C242 The device have to supported by a header file 1 18C242 H No default device is available q lt N gt assume disabled interrupt at the lt N gt deepest call levels For exa
41. skipL table if a branch is out of reach The skip functions use 8 bit parameters only Note however that the range of skipL is 128 double word instructions Carry is automatically generated if the table cross a 256 byte address boundary Options available GD dynamic selected skip format default GW dynamic selected skip format warning on long format GS always short skip format error if boundary is crossed GL always long skip format When using the GS option CC8E will generate an error if the table cross a 256 byte 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 256 byte 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 Relocatable assembly requires another approach to fix the address This is found in Section Using code sections on page 74 in Chapter 6 8 Linker Support Example A function contain a computed goto After inspecting the generated list file there are 15 instructions words between the function start and the address latch update instruction MOVF PCL W 0 updates PCLAT
42. the APPSEC section while the last origin says somewhere in the APPSEC section Locating code from a specific address is sometimes useful but note that MPLINK does not allow the above origin statements to be mixed for code belonging to the same section If the sections starting at address 0x200000 and 0x300000 are not defined then the compiler will automatically use section names IDLOCS and CONFIG However it is recommended to use the above definitions in the C file especially when using the rsc option The compiler estimate the current hex address and use this to detect when to insert the ISERVERS and ISERVER18 sections when using the rsc or r2 options Sometimes these sections should not be inserted This problem will occur infrequently and is easily detected because MPLINK will report the conflict This problem can be solved by inserting the following statements at the right place pragma sectionDef PROG pragma origin SECTION PROG Interrupts CC8E requires that the interrupt functions are located at address 8 and 0x18 Writing the interrupt service routine in C using MPLINK will require some care The best method is to use SEPARATE logical sections in the linker script file for the interrupt service routines This is a robust solution CC8E will generate a full or partial script file to avoid manual address calculation Node that pragma origin 0x8 and 0x18 must be used for the interrupt routines It is also possible
43. to design an assembly module containing the interrupt service routines Information on how to do this should be found in the MPASM MPLINK documentation Call level checking CC8E will normally check that the call level is not exceeded This is only partially possible when using MPLINK CC8E can ONLY check the current module NOT the whole linked application When calling an external function from the C code CC8E 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 74 CC8E Compiler B Knudsen Data code modules are called from well known stack levels Calling C function from assembly will require manual analysis of the call level Therefore careful verification of the call structure is required to avoid program crash when using too deep calls max 31 levels 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 CC8E will always use the long format when generating code for skip It is not possible to use the GS option in combination with relocatable assembly Recommendations when using MPLINK 1 Use as few C modules as possible because of a inefficient bank bit updating between modules b local variable space can not be reused between modules c only single 8 bit parameter in calls betw
44. to the standard C syntax 1 The bit variable type 2 The interrupt function type 3 style comments are allowed a comment valid to the end of the line 4 Local variables can be declared between statements as in Standard C requires local variables to be defined in the beginning of a block 5 Binary constants Obxxxxxx or bin xxxxxx The individual bits can be separated by the 050100 05 0 000 1 01 00000 bin 0100 bin 0001 0100 6 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 0 if 0 amp amp BBB 0 0 endif 7 Several of the type modifiers are not standard in C 0 15 accessBank size1 size2 More C extensions are allowed by the pragma statement 3 8 Predefined Symbols The basic PICmicro registers are predefined header files defines the rest 35 CC8E Compiler B Knudsen Data TOSU TOSH TOSL STKPTR PCLATU PCLATH PCL TBLPTRU TBLPTRH TBLPTRL TBLPTR TABLAT PRODH PRODL INTCON INTCON2 INTCON3 I POSTINCO POSTDECO P W WREG I B A EINCO PLUSWO FSROH FSROL FSRO NDF1 5 POSTDEC1 P SR BSRL INDF2 POSTINC2 POSTDEC2 PREINC2 PLUSW2 FSR2H FSR2L FSR2 EINC1 PLUSW1 5 FSR1L
45. unique 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 The general format is A scHDftumiJN N N s symbolic arguments are replaced by numbers c no C source code is printed H hexadecimal numbers only D decimal numbers only f no object format directive is printed t no tabulators normal spaces only u no extra info at the end of the assembly file m single source line only i no source indentation straight left margin J put source after instructions to achieve a compact assembly file R detailed macro expansion N N N label mnemonic and argument spacing Default is 8 6 10 89 CC8E Compiler B Knudsen Data Note that the options are CASE sensitive Some examples Default i xtt mO01 INCF x AsDJ m001 INCF 10 xtt AG 3 001 7648411 001 INCF 1 1 6 10 001 10514646 m001 INCF OAh PX 8 3 Variable File The variable list file contains information on the variables declared Variables are sorted by address by default but this can be changed The compiler needs the command line option V to produce this file The file name is lt src gt var The general format is V rnuD The additional letters allows the file contents to
46. 3 0 0 99999994 0 000000059605 fixedU_32 4 0 4 0 0 9999999998 0 0000000002328 1 All types ending on _8 have 2 correct digits after decimal point 2 types ending on _16 have 4 correct digits after decimal point 3 types ending on 24 have 7 correct digits after decimal point 4 types ending 32 have 9 correct digits after decimal point Fixed point constants The 32 bit floating point format is used during compilation and calculation fixed8_8 a 10 24 16 8 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 Constant rounding error example Constant 0 036 Variable type fixedl16 8 1 byte for decimals Error calculation 0 036 256 9 216 The byte values assigned to the variable are simply 0 0 9 The error is 9 256 0 036 0 036 0 023 The compiler prints this normalized error as a warning Type conversion The fixed point types are handled as subtypes of float Type casts are therefore infrequently required Fixed point interoperability It is recommended to stick to one fixed point format in a program The main problem when using mixed types is the enormous number of combinations which makes library support a challenge However many mixed operations are allowed when CC8E can map the types to the built in integer code generator fixed8 16 a b fixed 16 c OK code is generated dir
47. 4 are available math32f h before sending a floating point value float32ToIEEE754 floatVar change to IEEE754 3 instr I I before using a floating point value received IEEE754ToFloat32 floatVar change from 754 3 instr I I math24f h float24ToIEEE754 floatVar change to IEEE754 3 instr jER754ToFloat24 floatVar change from 754 3 instr I H I 14 CC8E Compiler B Knudsen Data Fixed point variables Fixed point can be used instead of floating point mainly to save program space Fixed point math use formats where the decimal point is permanently set at byte boundaries For example fixed8_8 use one byte for the integer part and one byte for the decimal part Fixed point operations maps nicely to integer operations except for multiplication and division which are supported by library functions Information on fixed point libraries is found in Chapter 6 5 Library Support on page 54 fixed8_8 fx fx low8 Least significant byte decimal part fx high8 Most significant byte integer part MSB LSB 1 256 0 00390625 07 01 7 0x01 0 00390625 7 0039625 07 80 7 0 80 0 00390625 65 07 FF 7 OxFF 0 00390625 7 99609375 00 00 0 FF 00 1 FF FF 1 OxFF 0 00390625 0 0039625 00 127 FF 127 OxFF 0 00390625 127
48. 50 1 1 2 bit ttl 50 1 1 2 1 3 bit tt2 8 50 1 1 2 1 BX1 enum BXL 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 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 use the variable name from the first assignment instead of the address Zpragma char var2 varl An alternative is to use the define statement define PORTX PORTC define ready Priority when allocating variables 1 Variables permanently assigned to a location 2 Local variables allocated by the compiler 3 Global variables allocated by the compiler 17 CC8E Compiler B Knudsen Data Supported type modifiers static char a a global variable known in the current module only or having the same name scope as local variables when used ina local block extern char a global variable in another module auto char a local variable auto is normally not used register char a ignored type modifier const char 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 CC8E use the address to automatically decide that most of the special purp
49. 50 124 130 134 248 24 8 24 8 123 112 112 112 5 24 8 24 8 24 8 64 1014 1060 1311 24 8 24 8 24 8 43 1045 1081 1365 56 CC8E Compiler B Knudsen Data 153 135 1275 1303 168 150 1491 1524 157 135 1559 1629 172 150 1807 1893 point basic math 5 16 16 16 16 16 16 135 147 16 16 16 16 16 16 108 135 5 16 16 16 16 16 16 64 1206 16 16 16 16 16 16 43 1245 5 8 24 8 24 8 24 150 162 8_24 8 24 8 24 123 150 5 8 24 8_24 8 24 64 1398 8_24 8_24 8_24 43 1445 Floating point libraries mathl6f h 16 bit floating math24f h 24 bit floating point math24lb h 24 bit floating point math32f h 32 bit floating point math321b h 32 bit floating point NOTE The timing values includes parameter transfer call and return and also assignment of the return value Basic 32 bit math Size b multiplication 131 b division 104 b addition 154 a subtraction add 5 int32 gt float32 67 float32 gt int32 80 Basic 24 bit math Size a b multiplication 82 b division 87 addition 132 subtraction 5 int24 gt float24 52 float24 gt int24 70 Basic 16 bit math Size b multiplication 51 a b division 73 addition 104 a b subtraction add 5 int16 gt float16 58 float16 gt int16 53 The following operations are handled by inline code assignment comparing with constants
50. 554 632 24 24 24 37 435 442 531 A wm 32 32 32 34 706 718 898 ABC 5 8 16 8 26 184 185 187 5 8 24 5 8 28 291 291 295 No 8 32 8 30 413 413 418 5 16 16 16 40 239 245 278 Bis 25 16 24 16 42 369 381 424 16 32 16 44 515 534 587 29 24 24 24 50 446 458 550 A 5 32 32 32 60 717 736 919 Fixed point libraries math16x h 16 bit fixed point 8 8 signed and unsigned math24x h 24 bit fixed point 8 16 16 8 signed and unsigned math32x h 32 bit fixed point 8 24 16 16 24 8 signed and unsigned The libraries can be used separately or combined The timing stated is measured in instruction cycles 4 clock and includes parameter transfer call return and assignment of the return value The timing values are found by executing a large number of iterations using selected argument values Sign unsigned S signed Sign Res argl op arg2 Program Approx CYCLES mathl6x h Code min aver max 5 88 8_8 88 44 50 52 56 88 88 88 23 38 38 38 5 88 88 88 46 422 440 507 88 88 88 29 437 453 533 math24x h Code min aver max S 168 168 16 8 74 83 87 91 16_8 16_8 16 8 50 Tal 71 rx S 16_8 16 8 16 8 59 686 718 861 16 8 16 8 168 36 709 734 901 5 8 16 8 16 8 16 89 98 102 106 8 16 8 16 8 16 65 86 86 86 5 8 16 8 16 8 16 55 846 895 1061 8 16 816 8 16 36 877 918 1117 math32x h Code min aver max 5 248 24 8 24 8 1
51. 6 bit OF more e icio err HO er nre ERR eredi 23 Merging s ieri aer reti P ER ESO E ORO er pede ee een 24 Examples uer oed aper ERR 24 25 SUP bete e epa dese IER EE STEP 25 25 WHILE SLQLEINENE 25 7 s iie tet RE 25 do statement ine stet nei dtes ec et ec ie tuus 26 Switch statement 26 break statement i ss nee e eee 26 27 return statement cete d t ese 27 BOLO SLGL ETON TEE 27 3 2 ASSIGNMENT AND CONDITIONS Kross Knp esete teap e a A Er E E in NR EEEE ER e Ea 27 Special synt x examples oe eoi tp ito dence ena anser 2 uui ni eet te ec ee dete rene 28 Bit Variables x ei 28 Multiplication division and modulo eese eese enne enne entente entree nenne 29 CC8E Compiler B Knudsen Data Precedence of C operators sc 29 Mixed variable sizes are allowed ettet tritt trn tried 30 319 CONSTANTS ee Pork iod teat 30 Const rit CXPTESSTONS wos sese ette Tee Ye ER eese er tap 30 JUI M 31 JA BUNCTIONS estie
52. 7 words 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 for 24 bit floating point and 6 10 for 32 bit floating point Only a small fraction of the calculations may the stated error The min and max timing stated have been found by simulating many thousands calculations However the min and max limits are approximate only All timing is measured in instruction cycles When using a 4 MHz oscillator one instruction cycle is 1 microsecond Fast and compact inline operations The compiler will use inline code for efficiency at some important operations Integer converting to left and right shifts a 8 2 59 CC8E Compiler B Knudsen Data selecting high low bytes words 256 a 256 b 0x10000 replacing remainder by AND operation a 64 a 0x80 Fixed Point converting to left and right shifts a 8 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 0 0 comparing with constants gt 0 lt 10 0 inverting the sign bit b Combining inline integer math and library calls It is possible to force the compiler to generate inline integer math code after a math library is included T
53. CC8E C Compiler for the PICIS Devices Version 1 1 User s Manual D Knudsen Data Trondheim Norway CC8E Compiler B Knudsen Data This manual and the CC8E compiler is protected by Norwegian copyright laws and thus by corresponding copyright laws agreed internationally by mutual consent The manual and the compiler may not be copied partially or as a whole without the 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 CC8E compiler you agree to be bound by this agreement Only one person may use a licensed CC8E compiler at the same time If more than one person want to use the compiler for each license then this have to be done by some manual handshaking procedure not electronic automated for instance by exchanging this manual as a permission key 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 this manual or in the compiler This also applies to problems caused by such errors Copyright B Knudsen Data Trondheim Norway 2001 2004 This manual covers CC8E version 1 1 and related topics New versions may contain changes without prior notice Microchip and PI
54. Cmicro are trademarks of Microchip Technology Inc Chandler U S A COMPILER BUG REPORTS 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 support bknd com or by fax to 47 73 96 51 84 Document version B CC8E Compiler B Knudsen Data CONTENTS 1 INTRODUCTION 7 1 1 SUPPORTED DEVICES 7 1 2 INSTALLATION AND SYSTEM REQUIREMENTS 8 Support for long file names ssiri ette tne reir ert E Here ER pentes 8 User interface iro e P eer Re HERE RE REPRE 8 1 3 MP AE SUPPORT 8 1 4 SUMMARY OF DELIVERED FILES
55. H and PCLATU The last computed goto destination address offset 10 resides further 2 10 instructions words below the address latch update instruction A fast a compact computed goto requires that these addresses resides the same byte page i e address amp OxFFFFO00 are identical for the two addresses This is achieved with the statement 92 CC8E Compiler B Knudsen Data pragma alignLsbOrigin 15 1 2 to 254 2 10 2 15 1 2 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 pragma alignLsbOrigin 0 align on LSB 0 pragma alignLsbOrigin 0 to 190 254 254 pragma alignLsbOrigin 100 to 10 Computed goto regions The compiler enters a goto region when skip skipL or skipM is detected In this region optimization is slightly changed and some address checks are made The goto region normally ends where the function ends A goto region can also be started by a pragma statement pragma computedGoto 1 start c goto region useful if PCL is written directly A goto region can also be stopped by a pragma statement pragma computedGoto 0 end of c goto region recommended if the function contains code below the goto region for instance when the table consis
56. LAB suite The CC8E files can be deleted without any un installation procedure Support for long file names CC8E supports long file names It is also possible to use spaces in file names and include directory names Equivalent include directory option formats I C Program Files cc8e IC progra l1l cc8e Equivalent include file formats include C Program Files cc8e C file finclude C progra l cc8e Cfile i 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 MPLAB version 5 uses and displays the short format only User interface The CC8E compiler is a command line program It requires a list of command line options to compile a C source file and produce the required files Starting CC8E from Windows can be done from the Start gt Run menu Then type the full path name including cc8e exe or use Browse The list of compiler command line options are then written to the screen The normal way of using CC8E is to use it as a tool from an integrate environment like MPLAB Compiling a program requires a file name and command line options 8 samplel c lt enter gt 1 3 MPLAB Support CC8E can be selected as tool in MPLAB which offers an integrated environment including e
57. M gpr4 RAM bank 4 SECTION NAME BANK5 RAM gpr5 RAM bank 5 6 9 The cdata Statement The cdata statement stores 16 bit data in program memory 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 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 except config ID and EEPROM data The data is added at the end of the assembly and hex file in the same order as it is defined SYNTAX pragma cdata ADDRESS lt VXS gt lt VXS gt pragma cdata lt VXS gt lt VXS gt fpragma IDENTIFIER lt VXS gt lt VXS gt ADDRESS 24 bit byte address VXS lt VALUE EXPRESSION STRING VALUE 0 OxFFFF EXPRESSION constant expr i e 0 1000 3 1234 STRING Valid String r n 0 x24 x8 xe xFF xff 82 CC8E Compiler B Knudsen Data String translation or xH hexadecimal number 0 gt 0 NI gt 1 2 gt 2 3 gt 3 4 gt 4 5 gt 5 6 gt 6 7 gt 7 gt 7 b gt 8 t gt 9 n gt 10 Nf gt 12 v gt 11 Nr gt 13
58. PONES De 73 Bank bit updating ue eie e e PR 73 Ia eu MEE 73 Using code sections ie ep redi RCRUM rei e e redes 74 74 Call level checking 74 Computed 010 s etr EE REPRE M ERRORES eR ER bi 75 Recommendations when using 75 MPLAB and MPASM Support etre tre 76 The MPLINK script file toe tet terr ER pe HR EPA ERES RR da 76 Example With 2 modules uio e re HEP EE RUE REUS pe Ibi Pr erede 78 6 9 THE CHATA STATEMENT intret eer de PD Y 82 Using the cdat statement 63 Storing EEPROM Gata eire greed 64 T DEBUGGING erp 85 7 1 COMPILATION ERRORS 85 Error and warning detdils s ee di are 86 CC8E Compiler B Knudsen Data Some common compilation 86 7 2 MPLAB DEBUGGING nn n nnn nnn n n a a 86 ICD2 debugging etes te o are tu are 67 7 3 ASSERT 5 87 7 4 DEBUGGING IN ANOTHER ENVIRONMENT
59. SH TOSL char STKPTR uns24 TBLPTR char TBLPTRU TBLPTRH TBLPTRL TABLAT char PCLATU PCLATH PCL char PRODH PRODL char INTCON INTCON2 INTCON3 char W WREG char BSR BSRL 11516 char INDFO POSTINCO POSTDECO PREINCO PLUSWO FSROH FSROL 11516 char INDF1 POSTINC1 POSTDEC1 PREINC1 PLUSW1 FSR1H FSRII 11516 FSR2 char INDF2 5 2 POSTDEC2 PREINC2 PLUSW2 FSR2H FSR2L char STATUS bit Carry DC Zero Overflow Negative A2 Assembly Instructions Assembly Status Operation ADDLW C DC Z N OV W Add literal and W ADDWF frd a C DC Z N OV W ADDWFC f d a C DC Z N OV d Add with Carry ANDLW 2 amp AND literal W ANDWF f d a 2 d f amp W AND W and f BC 1 Branch if Carry BN I Branch if Negative BNC 1 Branch if No Carry BNN 1 Branch if Not Negative BNOV 1 Branch if Not Overflow BNZ 1 Branch if Not Zero BOV I Branch if Overflow BRA 1 Branch always BZ 1 Branch if Zero BCF f b a f b 0 Bit clear f BSF f b 1 Bit set BTG f b a f b f b Bit toggle BTFSC f b a Bit test skip if clear 55 f b a Bit test skip if set CALL k Call subroutine CLRF f a Z f 0 Clear CLRWDT TO PD WDT 0 Clear watchdog timer COMF Ep dja 2 d f 7255 Complement f 96 CC8E APPENDIX CPFSEO CPFSGT CPFSLT DAW C DCFSNZ D D G T I Fh Fh Fh
60. This can be supplied by a command line option as an include folder directory I lt path gt NOTE 4 New header files can be defined according to file chip txt NOTE 5 ICD2 debugging requires defining a symbol before the header file is compiled to avoid that the application use reserved resources a By a command line option DICD2 DEBUG b By using define in combination with pragma chip or include define ICD2 DEBUG pragma chip PIC18F452 or include 18F452 H 1 7 What to do next It is important to know the PICmicro family and the tools well The easiest way to start is to read the available documentation and experiment with the examples Then move on to a simple project Some suggestions e study the supplied program samples e compile code fragments and check out what the compiler accepts e study the optional assembly file produced by the compiler Typical steps when developing programs is as follows e describe the system make requirements suggest solutions that satisfy these requirements write detailed code in the C language compile the program using the CC8E compiler test the program on a prototype or a simulator 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 controller 11 CC8E Compiler B Knudsen Data 2 VARIABLES The compiler prints in
61. a to lt gt 39 EE ER 40 pragma assert type text field esee eene nennen trennen rennen ene 40 pragma assume pointer in rambank n esses eerte ene nere trennen rennen ene 40 pragma bit lt name gt 9 N B or variable B eese nennen eene 40 Zpragma cdatalADDRESS VXS lt gt 40 pragma char name 9 constant or variable eese teen eene 41 Zpragma chip devices asi eet eg levees e rta e Sv ere ere 41 Hpragma computedGoto 0 12 eese 41 pragma config offset lt gt eene nennen rennen ene 41 Zpragma inlineMath lt 0 T gt 42 pragma Insert Consi MEE 42 pragma interruptSaveCheck n w e 42 Zpraema library lt O L gt ase etie e a e e Te 42 Zpragma optimize IN 0 12 ie eee 42 origin expression sac tete rt ie e ree eee epe e db re eX eoe 43 Zpragma rambank 5 0 1 2 152 4e diete tt eee ade She eaae ee 43 Zpraegma ramb se n iei ue eth 43 Zpr gmar setVectOr T t SURE PEG HRS 43 pragma return lt n gt strings or constants eene enne 43 pragma sectionDef name lt id gt start end PROTECTED
62. agma rambank 20 CC8E Compiler B Knudsen Data The bank type modifier It is also possible to use the bank type modifier to select the RAM bank bankO bank15 shrBank accessBank can replace pragma rambank shrBank and accessBank is the access bank 1 char tx 3 tx is located in bank 1 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 have 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 least code to update the bank selection bits Some advise when locating variables All local variables and f
63. ank is to instruct the bank update algorithm to do certain selections These statements can only be used inside the functions pragma updateBank entry 0 The entry bank force the bank bits to be set to a certain value when calling this function pragma updateBank exit 1 The exit bank force the bank bits to be set 44 CC8E Compiler B Knudsen Data to a certain value at return from this function pragma updateBank default 0 The default bank is used by the compiler at loops and labels when the algorithm give up finding the optimal choice pragma versionFile lt file gt Allows a version number at the and of the include file to be incremented for each compilation The use of this statement is defined in Chapter 5 2 Automatic incrementing version number in a file on page 49 4 2 PlCmicro Configuration PICmicro configuration information can be put in the generated hex and assembly file ID locations can also be programmed The configuration information is generated IF AND ONLY IF the Zpragma config statement is included Note that some PICmicro programming devices may reject this information Syntax pragma config lt offset gt expression pragma config lt offset gt expression pragma config offset amp expression pragma config ID lt offset gt expression Examples pragma config 0 0b 1 000 0101 byte at address 0x300000 pragma co
64. at merged or overlapping strings are handled fully automatically Note that the string termination 0 also have to be equal otherwise merging is not possible For example the string world can not 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 const char al 10 20 30 const char a2 Wail const char a3 5 10 20 30 tan 0 Examples A table of pointers to strings const struct const char s 3 Hello world Monday world automatically merged with first string tb i s const char char i char t pIx char x Note that const struct is required to put the pointer array in program memory Using const char tx means that the strings resides in program memory but the table tx resides in RAM String parameters myfunc Hello void myfunc const char str myfunc amp tab i char tab 20 string in RAM myfunc ctab const char ctab A string 24 CC8E Compiler B Knudsen Data 3 SYNTAX 3 1 Statements C statements are separated by semicolons and surrounded by block delimiters lt statement gt lt statement gt The typical statements are if while for do switch break continue return goto assignment function call w
65. ata MPLAB and MPASM support Please refer to linker txt for details on how to set up a project with several modules in MPLAB Note that MPASM will generate its own warnings and messages These should normally be ignored MPASM 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 CC8E 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 CC8E so that no extra command is required only the right command line options Case Sensitivity option in MPASM is by default On and should remain On because C use case dependent identifiers Options to start MPASM and generate relocatable object code xC progra 1 mplab mpasm exe X o X q Options when assembling and linking a single file xC progra 1 mplab mpasm exe X q If CC8E error file option F is missing CC8E 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 CC8E error file option F
66. ave to be specified This statement is normally NOT required because the compiler normally use the default location which is the first location pragma resetVector 0 at byte address 0 pragma resetVector 10 at byte address 10 pragma resetVector NO reset vector at all pragma return lt n gt lt strings or constants gt Allows multiple return statements to be inserted This statement should be proceeded by the skip statement The compiler may otherwise remove most returns The constant lt n gt is optional but it allows the compiler to print a warning when the number of constants is not equal to n Refer to Chapter 9 7 Computed Goto on page 92 for more details Note that const data types should normally be used for constant data skip W define NoH 11 pragma return NoH Hello world 43 CC8E Compiler B Knudsen Data pragma return 5 1 4 5 6 7 pragma return 01 2 3 44 H Hello 2 3 4 0x44 pragma return H e 1 1 o pragma return 3 0b010110 Ob111 0 10 pragma return 9 a r n o pragma return 10 10 2 0 80 nd pragma return 10000 16 16 bit constant 0x123456 24 24 bit constant 10000 10000 32 32 bit constant pragma sectionDef lt name gt lt id gt lt start gt lt end gt PROTECTED pragma sectionDef allows code sections to be defined and used in the application when generati
67. bally which means that all settings in the source code are ignored pragma origin lt expression gt Valid byte address region 0x0000 upper device byte code address gt Defines the byte address of the following code The current active location can not be moved backwards even if there is no code in that area Origin can not be changed inside a function pragma origin 8 high priority interrupt start address pragma origin 0x700 2 pragma origin SECTION APPSEC relocatable asm option rsc pragma rambank lt 0 1 2 15 gt gt access bank 0x000 0 07 0 gt bank 0 0 080 OxOFF T gt bank 1 0x100 1 2 gt bank 2 0x200 Ox2FF 15 gt bank 15 0 00 OxF7F pragma rambank defines the region 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 controllers Non existing banks for the other controllers are mapped into bank 0 pragma rambase lt n gt Defines the start address when declaring global variables The use of rambank and rambase are very similar The address have to be within the RAM space of the chip used NOTE that the start address is not valid for local variables but rambase can be used to select a specific RAM bank pragma resetVector lt n gt Some chips have an unusual startup vector location The reset vector then h
68. cur at the N deepest call levels of the main program The application writer must then ensure that interrupt will not occur when executing functions at the deepest lt N gt call levels normally by using the global interrupt enable bit CC8E will generate a warning for the critical functions The normal error message is always generated when the application contains more than 31 call levels For example the q1 option generates a warning for functions calls that will put the return address at stack level 31 no free stack entry for interrupt Using q2 means an additional warning at stack level 30 if the interrupt routine requires 2 levels i e contains function calls Itis NOT recommended to use the q N as a default option Recursive functions Recursive functions are possible Please note that the termination condition have to be defined in the application code and therefore the call level checking can not 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 a function which call itself directly or through another function This warning can be switched off with the wr command line option 6 3 Interrupts The PIC18 devices allows both low priority and high priority interrupts 50 CC8E Compiler B Knudsen Data The structure
69. d 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 The file int18xxx h contains recommended program sequences for saving and restoring registers Other registers must be saved manually The interrupt routine can also contain local variables Storage for local variables is allocated separately because interrupts can occur anytime IMPORTANT CC8E will AUTOMATICALLY check that vital registers are saved and restored during interrupt This applies to Group 1 W WREG STATUS BSR most frequent used Group 2 FSRO FSR1 FSR2 indirect access Group 3 TBLPTR TABLAT reading const data Group 4 PRODL PRODH multiplication instructions Group 5 PCLATH PCLATU computed goto NOTE that it is not required to save registers before starting to service the interrupt Section Custom interrupt save and restore on page 53 shows a list of instructions that that will not disturb the main registers It is possible to limit the save and restore of a specific register to a small region inside the interrupt service routine if this register is modified only inside this region 52 CC8E Compiler B Knudsen Data CC8E 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 The compiler will detect if the in
70. d automatically to ensure that there are no overlapping e When a variable is located at a fixed address the compiler will automatically EXCLUDE this address from the default bank definition in the script file The largest free region in the bank will be defined and made available for allocation by MPLINK It is important that the main C module knows all fixed RAM definitions Otherwise it is required to make a manual definition in the script file to exclude unknown locations from normal allocation It is also possible to make the linker script file manually although this should normally not be preferred MICROCHIP supplies sample linker script files for each device with the file extension Ikr look in the MPLAB directory When making a linker script file for a specific project this file can be copied and edited to suit the needs of CC8E The sample MPLINK script files must be changed slightly if the interrupt function is written in C The reason is that the interrupt functions must start at addresses 8 and 0x18 when using CC8E It could be possible to use a vector at address 8 0x18 but this slows down interrupt response CHANGE 1 Interrupt routine in WITH a separate logical section CC8E generates a partial script file when using the r2 command line option or r2 lt file lkr gt This file is written if and only if CC8E compiles a module with an interrupt service routine The generated script file may look like
71. d forward for transfer to the internal EEPROM during programming of a device Note that each cdata item is 16 bit wide and will thus define 2 EEPROM locations The low 8 bit will be stored first even addresses then the high 8 bit odd addresses The compiler does not know how much EEPROM space a device has define EEPROM START OxF00000 fpragma cdata EEPROM START start of cdata block pragma cdata OxFFFF 1000 4 bytes EEPROM data define D8 1 h 1 h 256 pragma cdata D8 10 20 D8 0 2 5 4 bytes Strings will be stored as a number of 2 8 bits when using cdata pragma cdata Hello world 0 84 CC8E 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
72. d normally NOT be set or cleared in the interrupt routine GIEH GIEL are AUTOMATICALLY cleared on interrupt entry by the CPU and set to 1 on exit by RETFIE Setting GIEH GIEL to 1 inside the interrupt service routine will cause nested interrupts if an interrupt is pending Too deep nesting may crash the program void highPriorityInt void save registers on demand restore registers on demand 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 have 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 However if the program contains recursive functions then the call level can not be checked by the compiler The interrupt vector is permanently set to address 0 8 and 0x18 The interrupt service routines can only be located at these addresses The pragma origin statement have 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 0 8 0 18 to the interrupt routine pragma unlockISR Vital registers such as STATUS BSR an
73. ddle of the switch statement switch token case 2 2 break case 9 case 1 default if PORTA 0x22 break case P pint 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 26 CC8E 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 for i 0 i lt 10 itt if i 7 continue return statement return lt expression gt exits the current function return no return value return 1 1 return value goto statement goto lt label gt Jumps to a location forward or backward goto XYZ XYZ 3 2 Assignment and Conditions Basic assignment examples varli x y 100 yey URS 0x10 W 0x10 1 multiple assignment operations lt lt gt gt flag 1 set bit variable itt or i or i i 1 fone Porky sol d Nontf FS ao 19 Special syntax examples define mx a if mx 27 CC8E Compiler B Knudsen Data
74. ded to use conditional compilation to manage several editions of the same program 49 CC8E Compiler B Knudsen Data 6 PROGRAM CODE 6 1 Program Code Pages The PIC18 devices does not use code pages The pragma codepage location and page type modifiers offered by CC5X to select code pages are ignored 6 2 Subroutine Call Level Checking Subroutine calls are limited to 31 levels for the PIC18 devices The compiler automatically checks that this limit is not exceeded 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 gotos Call is NOT replaced by goto when a The program counter PCL is manipulated in the user code computed goto in a function of type char b The number of return literal exceeds 10 c The function is called from another codepage and the number of returns exceeds 10 2 Call followed by return is replaced by a single goto Stack level checking when using interrupt CC8E will normally assume that an interrupt can occur anywhere in the main program also at the deepest call level An error message is printed if stack overflow may occur This is not always true because the interrupt enable bits controls when interrupts are allowed Sometimes the main program need all 31 stack levels for making calls The q lt N gt option force CC8E to assume that interrupt will NOT oc
75. ditional test code use of printf use of powerful debuggers etc The disadvantage is that some program rewriting is required 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 else low level PICmicro code fendif The following can be compiled and debugged without modifications General purpose RAM access Bit operations overlapping variables requires care Use of FSRx and INDFx with some precautions Use of rr swapO and nop2 Carry can be used together with rl and rr Direct use of Zero should be avoided 5 Use of the W register re Sure The recommended sequence is to 1 Write the program for the actual PICmicro device 2 Continue working until it can be compiled successfully 3 Debug low level modules separately by writing small test programs i e for keyboard handling displays IIC bus IO RT clocks 4 the necessary SIM code and definitions to the code Debug parts of the program in another environment Writing alternative code for the low level modules is possible 5 Return to the PICmicro environment and compile with SIM switched off and continue debugging using the actual chip 88 CC8E Compiler B Knudsen Data 8 FILES PRODUCED The compiler produces a com
76. ditor and tool support compilers assemblers simulators emulators device programmers Compilation errors are easily handled MPLAB supports point and click to go directly to the source line that needs correction CC8E supports the COD file format used by MPLAB for program debugging CC8E offers two modes of source file debugging is available C or assembly mode Thus tracing programs in MPLAB can be done using assembly instructions or C statements MPLAB is free and can be downloaded from the Microchip Internet site Please refer to the supplied file install txt for a description on how to install and use CC8E in the MPLAB environment CC8E Compiler B Knudsen Data 1 4 Summary of Delivered Files CC8E EXE compiler INSTALL TXT installation guide and MPLAB setup INLINE TXT information on inline assembly syntax CHIP TXT how to make new chip definitions CDATA TXT info on the pragma cdata statement CONFIG TXT the PICmicro configuration bits LINKER TXT using MPLINK to link several modules C or asm MATH TXT math library support ERRATA TXT silicon errata issues INT18XXX H interrupt header file HEXCODES H direct coded instructions CC8E MTC MPLAB tool configuration file MPLAB tool configuration file command line options file RELOC INC options for generating object
77. e register save checking should NOT be disabled btss 6 1 BTFSS 0 70 6 1 access RAM SFR only bx2 1 BSF 0x70 bx2 access RAM SFR only 6 1 0 0 70 6 1 access RAM SFR only bx3 bx3 BIG 0x70 bx3 access RAM SFR only 6 1 BTFSC 0x70 bxl access RAM SFR only vs swap vs SWAPF vs 1 access RAM SFR only vs incsz vs INCFSZ vs 1 access RAM SFR only decsz vs DECFSZ vs 1 access RAM SFR only clrwdt CLRWDT MOVFF a b all RAM SFR CALL GOTO BRA RCALL C It is possible to enable interrupt only in special regions wait loops in such a way that main registers can be modified during interrupt without disturbing the main program The register save can then be omitted and the save checking must be switched off to avoid the error messages pragma interruptSaveCheck no warning or error INTERRUPTS CAN BE VERY DIFFICULT THE PITFALLS ARE MANY 53 CC8E Compiler B Knudsen Data 6 4 Startup and Termination Code The startup code consists of a jump to main No variables are initiated All initialization has to be done by user code This simplifies design when using the watchdog timer or MCLR pin for wakeup purposes The SLEEP instruction is executed when the processor exit main This stops program execution and the chip enters the low power mode Program execution may be restarted by a
78. e 54 Floating point exception flags The floating point flags are accessible in the application program At program startup the flags should be initialized FpFlags 0 reset all flags disable rounding FpRounding 1 enable rounding 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 char FpFlags contains the floating point flags bit FpOverflow bit FpUnderFlow FpFlags bit FpDivO FpFlags fp overflow bit FpDomainError FpFlags t u fp underflow fp divide by zero domain error fp rounding FpFlags oN gt bit FpRounding FpFlags FpRounding 0 truncation FpRounding 1 unbiased rounding to nearest LSB 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 IEEE75
79. e by adding extern in front of a variable definition extern char a All global variables that are not static are made available for other modules automatically CC8E inserts GLOBAL statements in the generated assembly file CC8E will generate a MOVLW LOW var name offset when using the address operators amp var 71 CC8E Compiler B Knudsen Data Global bit variables is a challenge It is recommended to first define a char variable and then use bit bx ch 0 Otherwise CC8E will defines a global char variable with random name This name have the format Gbit X X where X is more or less random selected letters This variable is reserved by a RES statement and used in the assembly file when generating relocatable assembly bat bik 20 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 extern char definition only no allocation of space char px space is allocated for the pointer IMPORTANT const data can not be extern because MPLINK does not s
80. e computed in advance CC8E detects this and generates an error message The name 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 1 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 72 CC8E Compiler B Knudsen Data 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 contains global definitions that are included in all C modules Such files can contain definitions define IO variable names etc Using RAM banks RAM bank definitions only applies to devices with RAM located in more than one bank Note that the RAM bank of ALL variables have 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 mod
81. e inserted anywhere but they should surround a smallest possible region Please check the generated assembly code to ensure that the desired results 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 44 in Chapter 4 1 The pragma Statement 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 2 4 Pointers Single level pointers is implemented char t 10 p amp 1 100 p 2 The compiler allows using a 8 bit RAM pointer when all accesses using this pointer is limited to the same bank The bank is automatically detected and used In some cases it may be needed to define this bank directly For example when using a 8 bit pointer from several modules through relocatable assembly An error message is printed if a restricted pointer is loaded with an address from the wrong RAM bank bankl char t 10 bank3 char pi pragma assume pi in rambank 1 pi amp t 2 Pointer models Using 8 bit pointers when possible saves both code and RAM space CC8E allows the size of all single pointers to be decided automaticall
82. e transferred using the W register moviw 10 call fl equivalent to f1 10 rcall f1 equivalent to f1 10 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 64 CC8E Compiler B Knudsen Data 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 fasm BO equ 0 B7 equ 7 MAXNUM24EXP equ OxFF endasm Equ can also be used to define variable addresses However the compiler do not know the 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 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 enable equ to variable transformat
83. ectly a b 10 22 OK library function is supplied a b new user library function is required a type cast can select an existing library function fixed8_16 c Assigning variables to RAM addresses All variables including structures and arrays can be assigned to fixed address locations This is useful for assigning names to port pins It is also possible to define overlapping variables similar to union Variables can overlap parts of another variable table or structure Multiple levels of overlapping is allowed The syntax is lt variable_definition gt lt address constant_expression gt variable definition variable element 16 CC8E Compiler B Knudsen Data Examples char th 0x25 bit thl 0x25 1 overlap warning bit thl th 1 no warning char tty bit 50 char io tty bit b0 bit bx2b tty 7 char tui b0 size exceeded long tty size exceeded char tab 5 long tr Q8 tab struct long tiM long uu ham tab char aa ttb 2 char ttb 10 bit aa 7 a second level of overlapping bit bb 8 ttb 1 1 Size2 char cc da a da is a struct char dd 3 8 da sloi 1 pi ncup uns16 ee fx midl6 float32 fx TypeX ii tab is a typedef struct An expression can define the address of a variable This makes it easier to move a collection of variables char tty
84. een modules d only 1 bit return values between modules 2 Use definition header files that are shared between modules Include the shared definition in all C modules to enable consistency checking a variables add bank information modulel c extern shrBank char b define ARRAY_SIZE 10 extern bank0 char array ARRAY SIZE module3 asm extern bankl char mulcnd mulplr byte L byte b constants definitions enumerations and type information define MyGlobalDef 1 enum 51 10 52 53 54 55 names assigned to port pins pragma bit in 06 0 fpragma bit out PORTB 1 3 Define bit variables to overlap with a char variable extern char myBits bit bl myBits 0 bit b2 myBits 1 use extern char myBits for global bits and put the definitions in a shared header file Move definition char myBits to one of the modules 4 It is recommended to use the rsc option to enable the compiler to AUTOMATICALLY generate and later update the linker script 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 6 Do the final call level checking manually 7 Update conventions in assembly functions called from C modules The bank selection bits should be updated in the beginning of assembly functions that are called from C 75 CC8E Compiler B Knudsen D
85. emoved 2 Using V means a single quote in an option I C MProgram Files cc8e gt IC Program Files cc8e 48 CC8E Compiler B Knudsen Data IC Program Files cc8 gt IC Program Files cc8e DMyString Hello n gt DMyString Hello n DQuotes NN gt DQuote 5 2 Automatic incrementing version number in a file The compiler is able to automatically increment one or more version numbers for each compilation Three different syntax alternatives are available 1 Option verfverfile c include verfile c or lt verfile c gt 2 Option ver pragma versionFile next include is version file include verfile c or lt verfile c gt 3 Option ver pragma versionFile verfile c or lt verfile c gt 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 allows more than one version file It is recommen
86. ert e text passed to the debugger pragma assert e text passed to the debugger pragma assert this assert command is ignored 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 NO IO WI N2 Xo mm NE gt 6 gt TQ Nboc 8 AE gt 9 d0y 42 USE MACRO S Macro s can be used inside assert statements with some limitations The macro should cover the whole text field AND the lt type gt identifier or none of them Macro s limited to a part 87 CC8E Compiler B Knudsen Data of the text field are not translated Macro s can be used to switch on and off a group of assert statements or to define similar assert statements define COMMON ASSERT a text field define AA pragma assert COMMON ASSERT pragma assert AA a text field Macro AA can also disable a group of assert statements if writing define AA define XX a this will NOT work pragma assert XX causes an error message 7 4 Debugging in Another Environment Testing a program larger than 500 1000 instructions can be difficult It is possible to debug parts of the program in the Windows MSDOS environment Another C compiler have to be used for this purpose Using another environment has many advantages like faster debugging ad
87. f W XORWF f W f W ADDWF f W f f W ADDWF W f MOVE W Wo 5 255 ff Sif 0 W f 1 INCF W f f 1 INCF decsz i DECFSZ W decsz i DECFSZ rr f W rr f rl f RLCF W f rl f RLCF W swap SWAPF W swap f SWAPF 67 CC8E Compiler B Knudsen Data incsz i INCFSZ W incsz i INCFSZ bi O b buscas BSF b Bom 16 BIG btsc b BTFSC b btss b BTFSS f b sleep SLEEP clrwdt CLRWDT return 5 RETLW 5 51 CALL sl goto X GOTO X 45 MOVLW 45 W W 23 IORLW 23 W W amp 53 ANDLW 53 W W 12 XORLW 12 W 33 W ADDLW 33 W 33 W SUBLW 33 return RETURN retint W addWFC f ADDWFC addWFC f ADDWFC subWFB f SUBWFB f W subWFB f SUBWFB subFWB f SUBFWB W subFWB f SUBFWB rrnc f rrnc f rlnc f RLNCF rlnc f RLNCF decsnz i DCFSNZ decsnz i DCFSNZ incsnz i INFSNZ W incsnz i INFSNZ negate f NEGF W decadj W DAW multiply MULWF f multiply 50
88. formation 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 CC8E Version 1 1 Copyright c B Knudsen Data Norway 2001 2004 gt EXTENDED edition 8 32 bit int 16 32 bit float 32k code words 18 demo c Chip 18C242 aOR KKK KK KKKKKKKK KKKKKKKK KKKKKKKK 40h KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK ko k ck ck ck ck kk o KKKKKKKK KKKKKKKK 80h KKKKKK KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK COh KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK ko ok ck ck kk k ko KKKKKKKK Bank 0 220 1 254 bytes free RAM usage 38 bytes 31 local 474 bytes free File demo fcs Optimizing removed 27 code words 16 File demo var File demo asm File demo lst File demo cod File demo occ File demo hex Total of 175 code words 2 2 1 Information on RAM allocation The compiler prints information on RAM allocation A full map is printed for the access bank and bank 0 which is useful to check out which RAM locations are still free Detailed information on memory allocation is written to file lt src gt var when using the V command line option Symbols free location predefined or pragma variable local variable s global variable 7 7 free bits in this location
89. hen 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 16 uns16 b8 c8 1 Adding parenthesis just isolate 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 16 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 33 CC8E Compiler B Knudsen Data 16 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 al6 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
90. hile 1 3 1 0 for i 0 i lt 10 i 1 0 do a sample rr a 8 while 5 lt 200 reg 1 if PORTA return 5 else if count 3 goto X if PORTB 3 break if statement if condition statement else if condition statement else statement The else if and else parts are optional while statement while condition statement while 1 infinite loop for statement for initialization condition lt increment gt statement initialization legal assignment or empty 25 CC8E Compiler B Knudsen Data condition legal condition or empty increment legal increment or assignment or empty for 0 v lt 10 v for P x x T0 22 3 for v 0 v for i20 i 5 a b x 2 do statement do statement while condition switch statement The switch statement supports variables up to 32 bit The generated code is more compact and executes faster than the equivalent if else if chain switch variable case constantl statement statement break case constant2 statement statement break default statement statement break lt variable gt all 8 32 bit integer variables including W break optional default optional can be put in the mi
91. his may be useful when speed is critical or in the interrupt service routine Functions with parameters or local variables are not reentrant because local variables are mapped to global addresses and therefore the compiler will not allow calls from both main and the interrupt service routine to the same function 0 516 b c b inline code is generated include mathl h a math library function is called pragma inlineMath 1 a cb inline code is generated pragma inlineMath 0 math library function is called Inline type modifier on math operations It is possible to combine inline integer math and math library functions without making a special purpose math library This is done by stating that the selected operations are inline BEFORE the standard math library is included It is optimal to use inline code when there is only one operation of a certain type inline uns24 operator uns24 argl uns24 arg2 include math24 h 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 Detection of multiple inline math integer operations
92. ibrary 0 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 54 CC8E Compiler B Knudsen Data 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 straight forward to get correct results when using floating point However floating point functions requires 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 efficient handled inline The following command line options are available we no warning when fixed point constants are rounded wO warning on operator library calls wi no warning on multiple inline math integer operations wm no warning on single call to math integer function Integer libraries The math integer libraries allows selection between different optimizations speed or size The lib
93. ifier bankO bank3 shrBank pragma rambank 0 char a b pragma rambank 1 extern char arrayl 10 pragma rambank extern char ex access RAM Bank bit updating use an advanced algorithm to update the bank selection bits However it is not possible to trace calls to external functions Therefore calling an external function or allowing incoming calls makes CC8E assume that the bank bits are undefined This often means that more code compared to the optimal bank bit update strategy 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 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 needs 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 extern void funcl void defined in another module extern void func2 void can be called from another module NOTE that extern functions can only have a single 8 bit parameter which is transferred in W not const pointer bit This is because local storage information is not shared between modules The return value can n
94. igned variables and variables larger than 8 bits also use temporary variables on the computed stack A function can return any value type The W register is used for 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 Parameters in function calls There are no fixed limit on the number of parameters allowed in function calls Space for parameters are allocated in the same way as local variables which allows efficient reuse The bit type is also allowed Note that if W is used this has to be the LAST parameter char func char unsi16 b bit ob char W 31 CC8E Compiler B Knudsen Data Internal functions The internal functions provides 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 1 decsz i char decsz char DECFSZ f d incsz i char incsz char INCFSZ f d nop void nop void NOP nop2 0 void nop2 void branch 2 cycles retint void retint void RETFIE rl i char rl char RLF i d rr i char rr char RRF i d sleep void sleep void SLEEP Skip i void skip char
95. in program memory const 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 Extended call level by using GOTO instead of CALL when possible Access to most assembly instructions through corresponding C statements Inline assembly Integrated interrupt support Chip configuration information in source code Size in bits of the variables supported by the different compiler editions STANDARD EXTENDED integer 8 16 24 8 16 24 32 fixed 8 16 24 8 16 24 32 float 24 32 16 24 32 1 1 Supported devices 16 bit PIC18 core e up to 16 RAM banks of 256 byte plus access bank CC8E Compiler B Knudsen Data 1 2 Installation and System Requirements The CC8E compiler uses 32 bit processing console application and runs on IBM PC compatible machines using Windows NT 95 98 me 2000 XP Installing CC8E is done by first creating a directory folder on the hard disk where the compiler files should be located Most application programs are found in the Program Files folder on the C drive Create for example folder CC8E here The compiler is normally supplied as a ZIP file A tool like PKUNZIP or WINZIP is required to extract the files into the compiler folder CC8E 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 MP
96. in structures with more than 256 byte data must be aligned Data of size 16 bit or more The compiler allows access of 8 16 24 and 32 bits data including fixed and floating point formats When using arrays or structures with more than 256 byte data single data items have to be aligned Alignment means that there should not be any remainder when dividing the offset with the size of the data item This is only a problem when defining structures containing data of different sizes const uns24 th 1000000 OxFFFFFF 9000000 const int32 ti 1000000000 Ox7FFFFFFF 900000000 const long 1 5 10000 10000 0 30000 1 23 CC8E Compiler B Knudsen Data const fixed8 8 tf 1 1 200 25 100 25 Y const float tp 1 1 200 25 23e20 const double td 1 1 200 25 23e 30 const floati16 ts 1 1 200 25 23 30 l1 tl i reading a long integer d td x reading a double float constant 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 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 th
97. ine NBR Ox NBR CONCAT3 0 gt OxOf define CONCAT4 TKN TKN CONCAT4 gt define mrg s _msg s define xmrg s mrg s define foo alt mrg foo gt foo msg alt xmrg foo gt alt_msg alt define ILLEGALI _command define ILLEGAL2 _command Macro stringification The stringification operator allows a macro argument to be converted into a string constant Examples define STRINGI1 ARG ARG STRINGI1 help gt help STRINGII gt 37 CC8E Compiler B Knudsen Data define STRINGI2 A1 A2 1 A2 STRINGI2 gt x y equivalent to x y define str s 5 define xstr s str s define foo 4 str foo gt foo xstr foo gt A define WARN IF EXP do if EXP warn Warning EXP n while 0 WARN_IF x 0 gt do if x 0 warn Warning x 0 n while 0 include include test h include lt test h gt Zinclude 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 lt dir gt The current directory is skipped when using include lt test h gt undef define MAX 145 undef MAX removes definition of MAX undef does the opposite of define The undef state
98. ing 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 C enables the following advantages compared to assembly e Source code standardization Faster program development Improved source code readability Easier documentation Simplified maintenance Portable code The CC8E 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 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 CCSE 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 bank selection bits Enhanced and compact support of bit operations including bit functions Floating and fixed point math up to 32 bit Math libraries including functions like sin 1050 sqrt etc Supports standard C constant data and strings
99. ion pragma asm2var 1 Al equ 0x20 CLRF Al Al is changed from an equ constant to a char variable Comments types allowed in assembly mode NOP a comment NOP C style comments are also valid CLRWDT 2 nested style comments are also valid Conditional assembly is allowed However the C style syntax have to be used ifdef SYMBOLA nop else clrwdt endif Most preprocessor statements can be used in assembly mode pragma return Hello 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 N clrwdt movlw a if a 10 nop fendif 65 CC8E Compiler B Knudsen Data clrf UUA 10 ax UUA 9 PORTA Note that labels inside a makro often need to be supplied as a parameter if the makro is used more than once Also note that there should always be a backslash after endasm in a macro to avoid error messages when this macro is expanded in the C code This applies to all preprocessor statements inside macro s define waitX uSec LBM asm LBM NOP NOP DECFSZ uSec 1 GOTO LBM endasm X waitX i LL1 waitX i LL2 The compiler can optimize and perform bank 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
100. ion call 91 CC8E Compiler B Knudsen Data 9 APPLICATION NOTES 9 1 Computed Goto Computed goto is a compact and elegant way of implementing a multiselection It can also be used for storing a table of constants However the const type modifier is normally the best way to store constant data in program memory 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 Note that PCLATU and PCLATH in most cases have to be updated before writing to PCL The compiler can do ALL updating and checking automatically Built in skip skipL skipM functions for computed goto The different skip functions allows both single and double word instructions to be used in the table 1 skip all instructions in the table must be single word using single word increments 2 skipL all instructions in the table must be double words using double word increments 3 skipM both double and single word instructions in the table using single word increments Note that the compiler will check the table contents when using skip and skipL and generate en error message if the single double word conditions are not met Also note that goto LABEL statements inside the table will not be changed to a branch if skipL is used This makes it easy to change a skip table to a
101. iply 2 skip 5 execute 4 instructions at each selection Case0 nop nop return Casel nop nop nop return Case2 nop nop nop return Case3 nop nop nop return Case4 nop nop nop return Case5 nop nop nop goto END Case6 nop nop nop goto END Case7 nop nop nop goto END Case8 nop nop nop goto END Case9 nop nop goto END pragma computedGoto 0 end of region END 94 CC8E Compiler B Knudsen Data More statements 9 2 The switch statement char select char W switch W case 1 XORLW 1 LE RS 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 lt const gt 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 95 CC8E APPENDIX APPENDIX 1 Predefined Register Names B Knudsen Data All register names including the predefined ones are found in the header files The predefined register names are char TOSU TO
102. is present CC8E 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 Note that MPLAB will automatically show the contents of the error file if it is non empty Otherwise the screen output is displayed in Build Results window The MPLINK script file The compiler is able to generate the FULL linker script file This is done when using command line option rsc lt file lkr gt The compiler will automatically do the following when the C module contains interrupt routine s a Generate or update a complete script If the file exists initially then it should preferably contain an empty line The script file will only be generated when compiling the module containing main b Add remove and adjust definitions that are maintained by the compiler c Forward code section definitions to the script file and allow the definitions to be used in pragma origin statements etc pragma sectionDef lt secID gt lt secDef gt start last PROTECTED pragma sectionDef IDLOC idlocs 0x200000 0x200007 PROTECTE pragma sectionDef CONFIGS config 0x300000 0x30000D PROTECTED pragma sectionDef EEPROM eedata OxF00000 OxFOOOFF PROTECTED pragma sectionDef APPSEC appdefl 0 1000 0 102 76 CC8E Compiler B Knudsen Data pragma sectionDef PROG d Code definition will be adjuste
103. 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 16 int16 18 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 OxFFFF have the same 16 bit representation 16 uns16 uns8 i8 uns8 j8 1 To get an 8 8 bit unsigned multiplication it is required 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 al6 now have the same type for the assignment and no type conversion is needed al6 uns16 b8 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 al6 now have the same type for the assignment and no type conversion is needed 3 6 Accessing Parts of a Variable Each bit in a variable ca
104. itially mentioned registers are modified during interrupt processing without being saved and restored The supplied macros for saving and restoring registers will only save W STATUS and BSR The other registers have to be saved and restored by user code when needed For example if FSRO is modified by a table or pointer access or by direct writing the compiler will check that FSRO is saved and restored also in nested function calls Note that the FSRO 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 the Group 2 5 registers mentioned above are saved but not changed The error and warning messages printed can be removed pragma interruptSaveCheck no warning or error pragma interruptSaveCheck warning only pragma interruptSaveCheck error and warning default Note that the above pragma also change the checking done on all registers Custom interrupt save and restore It is not required to use the above save and restore macros CC8E also supports custom interrupt structures A You may want to use your own save and restore sequence This can be done by inline assembly If CC8E does not accept your code just insert on your own risk pragma interruptSaveCheck n no warning or error B No registers need to be saved when using the following instructions in the interrupt routine Th
105. ixed point motae ng e ipe E pace 56 Floating point libraries i socle od se idee RR CREER FC ont 57 Floating point library FUNCTIONS s aile Ge teri e cene o Ten ie e tee eere pos 58 Fast and compact inline operations bere eere t 59 Combining inline integer math and library calls eese 60 Fixed point example id oe be dtt ote e 61 Floating pointexample saei OR eiie ie evo eee oed et ets eges 61 SAVE 61 6 0 INLINE ASSEMBLY ihi OI Ie irem 62 Direct coded instructlonsus asus aate ye reris as iine eia orn desse t pente ge epos 66 Generating single instructions using C 5 eerte eene enne rennen 67 6 7 OPTIMIZING THE CODE nieder ted UD E RUE IO re debe Pr d at br oe 69 Optimized Syntdx s et UU SIDE ER dre haeo d Ree ae 69 Peepholeoptimization etr DRE Reed qp qon dedi 69 6 8 LINKER SUPPORT eR AIR EU I n de re Ie e eh Pe re e Pene hes 69 Using MPLINK or a single module eese eene enne nennen rennen enne 70 Restrictions on the demo edition i e a E eese eben ee redire teer een ands ve edere een 71 Variables and pointers diea e 71 Tocalvariables s dte RED IR RU se E 72 Header files Use eie 73 Using RAM banks eder
106. lkr use defined file nam Example with 2 modules This example demonstrates the syntax only KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK MODULE1 C pragma chip PIC18F452 include globdefl h 78 CC8E Compiler B Knudsen Data include int18xxx H void _highPrioritylInt vo pragma origin 0x8 id interrupt highPriorityIntServer void STATUS and BSR are saved to shadow registers handle the interrupt 8 code words available including call and RETFIE highPriorityInt restore W STATUS and BSR from shadow registers pragma fastMode pragma origin 0x18 interrupt lowPriorityIntServer void STATUS and BSR are saved by the next macro int_save_registers NOTE shadow registers are updated but will be overwritten in case of a high priority interrupt Therefore pragma fastMode should not be used on low priority interrupts save remaining registers on demand error warning uns16 sv FSRO FSRO uns16 sv 1 5 1 uns16 sv FSR2 FSR2 uns8 PCLATH PCLATH uns8 PCLATU PCLATU uns8 sv PRODL PRODL uns8 PRODH PRODH uns24 sv TBLPTR TBLPTR uns8 sv TABLAT TABLAT handle the interrupt restore registers that are saved FSRO 1 sv FSR1 FSR2 FSR2 PCLATH
107. mafor int i 8 bit signed signed char sc 8 bit signed long i16 16 bit signed uns8 u8 8 bit unsigned unsl6 ul6 16 bit unsigned uns24 u24 24 bit unsigned uns32 u32 32 bit unsigned int8 58 8 bit signed int16 16 16 bit signed int24 s24 24 bit signed int32 s32 32 bit signed The bitfield syntax can also be used unsigned x 24 24 bit unsigned int y 16 16 bit signed The value range of the variables are TYPE SIZE MIN MAX int8 1 128 127 16 2 32768 32767 int24 3 8388608 8388607 int32 4 2147483648 2147483647 uns8 1 0 255 11516 2 0 65535 11524 3 0 16777215 01532 4 0 4294967295 Floating point The compiler supports 16 24 and 32 bit floating point The 32 bit floating point can be converted to and from IEEE754 by 3 instructions macro in math32f h Supported floating point types floati16 16 bit floating point float float24 24 bit floating point double float32 32 bit floating point 13 CC8E Compiler B Knudsen Data Format Resolution Range 16 bit 2 4 digits t 3 4 38 1 1e 38 24 bit 4 8 digits t 3 4 38 1 1e 38 32 bit 7 2 digits t 3 4 38 1 1e 38 Note that 16 bit floating point is intended for special use where accuracy is less important More details on the floating point formats is found in math txt Information on floating point libraries is found in Chapter 6 5 Library Support on pag
108. mbler option X q all options must be separate ZZ optimize inline multiplication for size ZD optimize inline multiplication for speed default Doublequotes allows spaces in the option I C Program Files Ncc8e A path name can be written using if this is supported by the file system example c compiler lib file h Default compiler settings hex file output to file lt name gt hex e optimizing on e extended call level is allowed e update bank selection bits Permanent assigned settings e nested comments is allowed e charis unsigned 5 1 Options in a file Options can be put in a file The syntax is cc8e lt filename gt Many option files can be included and up to 5 levels of nested include files are allowed Options in a file allows 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 the rest of the line is a comment Spaces can be added to each option if a space is added behind the starting the option This syntax disables using more than one option on each line Examples D 1 p 18C242 comment p 18C242 this will not work p 186242 a not this either Note that the file path is required if the file does not reside on the current directory String translation rules for options in a file 1 Doublequotes allows spaces in the option quotes are r
109. ment will not produce any error message if the symbol is not defined Tif dif defined ALFA amp amp ALFA statements compiled if ALFA is equal to 1 conditional compilation may be nested endif 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 1 macro s are automatically expanded 2 defined SYMBOL and defined SYMBOL are replaced by 1 if the symbol is defined otherwise 0 3 legal constants 1234 1 4 legal operations gt gt lt lt lt lt gt gt amp amp bake d 38 CC8E Compiler B Knudsen Data 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 endif endif ifdef SYMBOL endif error error This is a custom defined error message The compiler generates an error message using the text found behind error 4 1 The pragma Statement The pragma statement is used for processor specific implementations
110. modules for linking DEMO C syntax demo file DEMO VAR C defining RAM variables DEMO MAT C integer math DEMO FPM C floating point math DEMO FXM C fixed point math DEMO ROM C const data and DW DEMO PTR C tables and pointers DEMO INS C generating single instructions MATH16 H 8 16 bit math library MATH24 H 8 24 bit math library ATH32 H 1 8 32 bit math library ATH16X H 16 bit fixed point library MATH24X H 24 bit fixed point library MATH32X H 1 32 bit fixed point library 16 1 16 bit floating point library ATH24F H 24 bit floating point library MATH32F H 32 bit floating point library MATH24LB H 24 bit floating point functions Logysdrty cosSs ATH32LB H 32 bit floating point functions log sqrt cos 18C242 H 18F452 H PICmicro header files NEWS TXT recent added features README TXT 1 Not available on the DEMO and STANDARD edition CC8E Compiler B Knudsen Data 1 5 Short Program Example global variables char a bit bl b2 assign names to port pins pragma bit in 0 pragma bit out PORTB 1 void sub void char i a local variable generate 20 pulses for i 0 i lt 20 i out 1 nop out 0 void main void if 1 amp amp PD 1 power up WARM_RESET clearRAM clear all RAM first decide the initial output level on the output port
111. mple 41 allows the main program to use all stack levels for function calls Disabling interrupt at the deepest call level MUST then be properly ensured in the user application program Q write the call tree to lt gt r generate relocatable assembly no hex file rsc lt filename Ikr gt generate relocatable asm and update the linker script file r2 filename Ikr generate relocatable asm use separate logical section for interrupt routine rb lt N gt name bank 0 is BANK lt N gt default BANKO ro lt N gt add offset lt N gt when generating local variable block name rx make variables static by default S silent operation of the compiler u no optimizing V rnuD generate variable file lt src gt var sorted by address as default r only variables which are referenced in the code n sort by name u unsorted D decimal numbers we no warning when fixed point constants are rounded 47 CC8E Compiler B Knudsen Data wi no warning on multiple inline math integer operations wm no warning on single call to math integer function wO warning on operator library calls wr no warning on recursive calls wS warning no error when constant expression loses significant bits wU warning on uncalled functions W wait until key pressed after compilation lt gt assembler executable xC progra 1 mplab mpasm exe X lt option gt asse
112. n be accessed directly uns32 a 1 set bit 7 of variable to 1 if test bit 31 of variable a 10 bit 4 of the i th element CRG Bit 0 least significant bit Bit 7 most significant bit of a 8 bit variable Bit 15 most significant bit of a 16 bit variable Bit 23 most significant bit of a 24 bit variable Bit 31 most significant bit of a 32 bit variable ct ct Ct Also parts of a variable can be accessed directly unsi6 a uns32 b a low8 100 set the least significant 8 bits b highl6 load the most significant 16 bits low8 least significant byte high8 most significant byte mid8 second byte midL8 second byte midH8 third byte lowl6 least significant 16 bit 01916 middle 16 bit highl6 most significant 16 bit low24 least significant 24 bit high24 most significant 24 bit 34 CC8E Compiler B Knudsen Data 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 Ke OS 0 7 x OF 61908 0 7 BSS 16 23 24 31 mids 0 7 8 15 8 25 8 15 midL8 0 7 8 15 8 15 ANB midH8 0 7 8 15 16 23 16 23 lowl6 0 7 0 15 0 15 e midl6 0 7 0 15 8 23 8 23 highl6 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 adds some extensions
113. n bit conditions b c amp d also amp amp tye Ha SE conditions using bit variables if b also gt lt gt lt initialized local bit variables bit bx cx bit by fx OxFF Multiplication division and modulo multiplication 16 b16 c16 16 16 bit A general multiplication algorithm is implemented allowing most combinations of variable sizes Including a math library allows library calls to be generated instead of inline code The algorithm makes shortcuts when possible for instance when multiplying by 2 This is treated as a left shift division al6 b16 c8 16 8 bit modulo a32 b32 16 32 16 bit 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 C Lowest H Cy 29 CC8E Compiler B Knudsen Data Mixed variable sizes are allowed a32 uns32 b24 c8 24 8 bit result 32 bit 16 16 b8 16 8 bit result 16 bit Most combinations of variables are allowed the compiler performs sign extension is 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 ASCII x 05010101
114. nfig 1 3 set bit 0 1 addr 0x300001 pragma config 2 amp 0 0x80 clear bit 4 7 set bit 7 pragma config 2 1 OxF 0x80 pragma config 0 0x99 byte at address 0x200000 pragma config ID 1 0x88 byte at address 0x200001 pragma config ID 2 0x03 The CONFIG and ID are specified in BYTES CC8E will join 2 bytes into a 16 bit WORD in the generated hex asm and list files If only one byte is defined for a word then the default value is used for the undefined byte The default setting of config attributes are 1 ID locations have 0 as default value It is also possible to define the CONFIG and ID locations by using pragma cdata statements Then 16 bits words is defined directly CONFIG word start address PIC18 0x300000 ID word start address PIC18 0x200000 45 CC8E Compiler B Knudsen Data 5 COMMAND LINE OPTIONS The compiler needs a C source file name to start compiling Other arguments can be added if required The syntax is CC8E options src c options a lt asmfile gt produce assembly file The default file name is lt src gt asm A scHDftumiJRN N N assembly file options s symbolic arguments are replaced by numbers source code is printed H hexadecimal numbers only D decimal numbers only f no object format directive is printed t no tabulators normal spaces only u no extra info at the end of the assembly file m single source line o
115. ng relocatable assembly option rsc Predefined code sections are STARTUP ISERVER8 ISERVER18 and PROG These definitions will also automatically appear in the script file pragma sectionDef IDLOC idlocs 0x200000 0x200007 PROTECTED pragma sectionDef CONFIGS config 0x300000 0x30000D PROTECTED pragma sectionDef EEPROM eedata OxF00000 OxFOOOFF PROTECTED pragma sectionDef APPSEC appdefl 0 1000 0x102F pragma sectionDef PROG Further details are found in Section Using code sections on page 74 in Chapter 6 8 Linker Support pragma stackLevels lt n gt The number of call levels can be defined normally not required PIC18 uses by default 31 levels pragma stackLevels 30 max 64 pragma unlockISR The interrupt routines normally have to reside on address 0 8 and 0x18 The following pragma statement will allow the interrupt routine to be placed anywhere Note that the compiler will NOT generate the link from address 0x8 0x18 to the interrupt routine pragma unlockISR pragma updateBank entry exit default lt 0 1 gt The main usage of pragma updateBank is to allow the automatic updating of the bank selection register to be switched on and off locally These statements can also be inserted outside the functions but they should surround a region as small as possible pragma updateBank 0 OFF pragma updateBank 1 ON Another use of pragma updateB
116. nly i no source indentation straight left margin J put source after instructions to achieve a compact assembly file R detailed macro expansion N N N label mnemonic and argument spacing Default is 8 6 10 b do not update bank selection bits BSR register bu non optimized updating of the bank selection bits CC lt file gt produce COD file C mode CA lt file gt produce COD file ASM mode allow cdata outside program space warning only cu use 32 bit evaluation of constant expressions do not search current directory for include files dc do not write compiler output file lt src gt occ D lt name gt xxx define macro Equivalent to define name xxx e single line error messages no source lines are printed ed do not print error details ew do not print warning details eL list error and warning details at the end lt gt stop after N errors default is 4 f lt hex file format gt i e INHX8M INHX8S INHX16 INHX32 Default is INHX32 Note that INHXSS use output files lt gt and file HXL F produce error file lt src gt err FM MPLAB compatible error format g do not replace call by goto 46 CC8E Compiler B Knudsen Data GW dynamic selected skip format warning on long format GD dynamic selected skip format default GS always short skip format error if 256 byte boundary is crossed GL always long
117. nterrupts on page 50 for details or file int18xxx h The error and warning messages can be removed pragma interruptSaveCheck no warning or error pragma interruptSaveCheck warning only pragma interruptSaveCheck error and warning default pragma library lt 0 1 gt CC8E will automatically delete unused library functions pragma library 1 functions that are deleted if unused applies to prototypes and function definitions pragma library 0 pragma optimize N lt 0 1 gt This statement enables optimization to be switched ON or OFF in a local region A specific type of optimization can also be switched on or off The default setting is on redirect goto to goto remove superfluous gotos replace goto by skip instructions remove instructions that affects the zero flag only replace INCF and DECF by INCFSZ and DECFSZ remove superfluous updating of PAO and PAI remove other superfluous instructions remove superfluous loading of W to be defined 0 inserts TSTFSZ CPFSEQ 1 inserts branch d OO DO Examples pragma optimize pragma optimize pragma optimize pragma optimize ALL off ALL on fy type 2 om 10 type lo off combinations are also possible 42 CC8E Compiler B Knudsen Data pragma optimize 3 0 0 res Sob pragma optimize 1 1 0 0 2052370 NOTE The command line option will switch optimization off glo
118. number 1000 means version 1 0 CoreSet 1800 PIC18 3 9 Upward Compatibility The aim is to provide best possible upward compatibility from version to version Sometimes the generated code is improved If the application programs contain timing critical parts depends on an exact instruction count then these parts should be verified again for example by using the MSDOS program fc file compare on the generated assembly files 36 CC8E Compiler B Knudsen Data 4 PREPROCESSOR DIRECTIVES The preprocessor recognizes the following keywords define undef include if ifdef ifndef elif else endif error pragma A preprocessor line can be extended by putting a V at the end of the line This requires that there are space characters behind the V define define counter v1 define MAX 145 define echo v2 x define mix echo 1 nested macro Note that all define s are global even if they are put inside a function Preprocessor directives can be put into the define statement Macro concatenation The concatenation operator allows tokens to be merged while expanding macros Examples define CONCAT NAME NAME _command CONCAT quit gt quit_command gt _command CONCAT dummy help gt dummy help command define 2 N1 N2 _comm N2 CONCAT2 help and gt help_comm_and def
119. o b c The result of the plus operation and a are treated last The CC8E compiler use 8 bit int size and contains significantly 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 use 16 or 32 bit int size The type conversion rules implemented are if one operand is double gt the other is converted to double if one operand is float gt the other is converted to float if one operand is 32 bit gt the other is converted to 32 bit if one operand is 24 bit gt the other is converted to 24 bit if one operand is long gt the other is converted to long if one operand is unsigned gt the other is converted to unsigned De NOTES The sign is extended before the operand is converted to unsigned Assignment is also operation 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 11516 16 1158 b8 int8 18 18 al6 b8 c8 12 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 t
120. ose registers are volatile 0 void fx void IGNORED by CC8 pagel page2 page3 bankO char a variable a resides in RAM bank 0 bank0 bankl bank2 bankl15 shrBank accessBank access bank unbanked size2 char px pointer px is 16 bit wide sizel size2 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 in 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 9 inner block is added char a for a 0 a lt 10 att i 0 sub 1 another inner block to enable better reus char b s 1 int il 1 i2 0 more code 18 CC8E Compiler B Knudsen Data Local variables may have the same name However the compiler adds an extension to produce an unique name in the assembly list and COD files When a func
121. ot be larger than 8 bit for the same reason bit values are returned in Carry Supported extern function parameter types char uns8 int8 Supported extern function return types char uns8 bit 73 CC8E Compiler B Knudsen Data CC8E inserts a GLOBAL lt function gt in the generated assembly code for all external available functions EXTERN lt function gt is inserted for functions defined in other modules If the C module contains main then a goto main is inserted in the STARTUP section Using code sections It is possible to use pragma origin and pragma cdata when the compiler know the section the following code should be placed in The compiler automatically knows the STARTUP ISERVER8 ISERVER18 and PROG sections In addition it is possible to define sections manually in the C file These definitions will also automatically appear in the script file when using the rsc option pragma sectionDef IDLOC idlocs 0x200000 0x200007 PROTECTED pragma sectionDef CONFIGS config 0 300000 0 30000 PROTECTED pragma sectionDef EEPROM eedata OxF00000 OxFOOOFF PROTECTED pragma sectionDef APPSEC appdefl 0x1000 0x102F pragma sectionDef PROG Note the difference between using pragma origin 0 1000 gt generates APPSEC CODE 0x1000 and pragma origin SECTION APPSEC gt generates APPSEC CODE The first origin says from the start of
122. piler output file and a hex file that may be used for programming the PICmicro chips directly 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 e assembly variable list function outline COD and error files 8 1 Hex File The default hex file format is INHX32 The format is changed by the f command line option The INHX8M INHXSS and INHX32 formats 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 00000001 11 8 bits data word checksum the sum of all bytes is zero The 16 bit format used by INHX16 is defined by 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 CE checksum the sum of all bytes is zero 8 2 Assembly Output File The compiler produces a complete assembly file This file can be used as input to an assembler Text from the source file is merged into the assembly file This improves readability Variable names are used throughout A hex format directive is put into the assembly file This can be switched off if needed Local variables may have the same name The compiler will add an extension to ensure that all variable names are
123. plab mpasm exe X option assembler option X q all options must be separate Assembly file options normally not used rb N name on RAM bank 0 is BANK lt N gt default BANKO ro N add offset lt N gt when generating local variable block name Using MPLINK or a single module Currently it is best to use a single C module for several reasons MPLINK support was mainly offered to enable asm modules to be added Limitations when using MPLINK 1 Asm mode debugging only C source code appear as comments 2 Multiple C modules does not allow the static local variable stack to be calculated for the whole program meaning that much more RAM space will be used for local variables 3 Calllevel checking must be done manually 4 Computed goto will be slower because the compiler can not check 256 byte address boundary crossing 5 Inefficient RAM bank updating meaning mode code The main reasons for using multiple modules is probably 1 Faster build However CC5X is increadible fast MPASM doing much simpler tasks is 3 times slower 2 Module separation However sufficient module separation can be achieved by using multiple C files 3 Asm modules Inline ASM is supported by CC5X 70 CC8E 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 1 Include the sepa
124. r global variables can be tried e compiler is unable to generate code Solution Some of the C statements have to be rewritten possibly using simpler statements too much code generated Solution rewrite parts of the code By checking the assembly file it may be possible to detect inefficient code fragments Rewriting by using the W register directly may sometimes reduce the code size Experience has shown that around 10 of the hex code can be removed by hand optimizing the C code Optimal usage of RAM banks is important deep call level Solution rewrite the code Remember that the compiler handles most cases where functions are called once only 7 2 MPLAB Debugging Support The CC8E compiler can be used inside the MPLAB environment The COD file format for debugging purposes is supported Two modes of source file debugging is available a Using the C source file s b Using the generated assembly file as the source file The format of the assembly file in order to suit the debugging tool Take a look at the assembly file options Some suggestions 1 6 10 AmiJ Simulator I 1 6 6 AmiJs Simulator II A6 8 12Jt compact I Am6 8 412Jt compact II Enabling the COD file is done by a command line option CC filename generate debug file using C source file s filename is optional The asm file option is also switched on CA filename generate debug file using generated assembly as sou
125. raries contains operations for multiplication division and division remainder mathl6 h basic library up to 16 bit math24 h basic library up to 24 bit math32 h basic library up to 32 bit The min and max timing cycles are approximate only Sign unsigned S signed Sign Res argl op arg2 Program Approx CYCLES A math32 h B math24 h C mathl6 h Code min aver max 38 24 16 16 31 47 47 49 5 32 16 16 41 55 56 61 A 32 16 16 27 49 49 49 24 24 24 33 54 54 54 5 32 32 16 49 70 70 73 32 32 16 43 67 67 67 5 32 32 32 57 87 87 87 ABC 16 16 8 19 252 232 232 24 24 8 20 365 365 365 32 32 8 21 514 514 514 16 16 16 22 235 239 283 24 24 16 2 5 392 407 488 32 32 16 26 549 SNS 677 24 24 24 29 443 452 563 32 32 32 36 715 729 939 5 16 16 8 33 193 197 206 5 24 24 8 35 302 306 317 A S 32 32 8 37 427 432 444 5 16 16 16 43 244 252 305 SES a9 24 24 16 45 377 398 464 5 32 32 16 47 526 557 639 SBu 9 24 24 24 52 452 470 587 55 CC8E Compiler B Knudsen Data 58 32 32 32 61 724 750 965 8 16 8 18 222 222 222 8 24 5 8 19 352 352 352 E 8 32 8 20 498 498 498 16 16 16 20 228 231 260 SBa gt 16 24 16 23 374 393 454 16 32 16 24 520
126. rate modules into the main module include modulel c include module2 c include moduleN c If void main void 2 Each module should include the required header files in the beginning of the module This can be private or common header files include headerl c include header2 c include headerN c 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 fifndef _HEADER_N_Symbol the first header file lin define _HEADER_N_Symbol compile this line once only header definitions as required endif the last header file lin Restrictions on the demo edition There are some restrictions when using relocatable assembly on the CC8E DEMO 1 single demo C module is possible plus many assembly modules The demo C module can call EXTERN functions and use extern variables defined in assembly modules 3 The demo C module is NOT allowed to export extern functions or variables 4 main must be defined in the demo C module The interrupt routines should preferably also be defined in the demo C module 5 The demo C module can maximum contain 1024 instructions Variables and pointers Variables defined in other module can be accessed CC8E needs to know the type and this is don
127. rce filename is optional The asm file option is also switched on Arrays Arrays and structures represent a slight challenge because all variables passed in the COD file are currently either char or bit types 86 CC8E Compiler B Knudsen Data This is solved by adding new variables which appears during debugging char table 3 gt table offset 0 table 1 offset 1 table e2 offset 2 struct char a char b st st offset 0 element a st el offset 1 element b This means that the name of a structure element is not visible when inspecting variables in a debugger ICD2 debugging ICD2 debugging requires defining a symbol before the header file is compiled to avoid that the application use reserved resources a By a command line option DICD2 DEBUG b By using define in combination with pragma chip or include define ICD2 DEBUG pragma chip PIC18F452 or include 18F452 H 7 3 Assert Statements Assert statements allows messages to be passed to the simulator emulator etc Syntax pragma assert type text field optional character type user defined assert user defined emulator command user defined printf 1 user defined log command text field undefined syntax valid to the end of the line The line can be extended by a character like other preprocessor statements pragma ass
128. sen Data The constant type is by default the shortest signed integer Adding an U behind a constant means that it is treated as unsigned Note that constants above 7 are unsigned by default with or without an 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 Al A2 A3 A4 typedef enum alfa 8 beta zeta 4 eps 1 nn enum con Read A Read B enum con mm mm Read A nn eps 3 4 Functions Function definitions can look as follows void subroutine2 char p C statements bit functionl void long function2 char void main void Function calls subroutinel subroutine2 24 bitX function1 x function2 W xl fx3 x The compiler need to know the definition of a function before it is called to enable type checking 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 subroutinel void Function return values Functions can return values up to 4 bytes wide Return values can be assigned to a variable or discarded Handling and using return values is automated by the compiler The least significant byte is always placed in W S
129. so be programmed pragma config lt offset gt expression pragma config lt offset gt expression pragma config lt offset gt amp expression pragma config ID lt offset gt expression Examples pragma config 0 0b 1 000 0101 byte at address 0x300000 pragma config 1 3 set bit 0 1 addr 0x300001 pragma config 2 amp 0 0x80 clear bit 4 7 set bit 7 pragma config 2 1 OxF 0x80 pragma config ID 0 0x99 byte at address 0x200000 pragma config ID 1 0x88 byte at address 0x200001 pragma config ID 2 0x03 The CONFIG and ID are specified in BYTES Refer to Chapter 4 2 PICmicro Configuration on page 45 for more details 41 CC8E Compiler B Knudsen Data pragma inlineMath lt 0 1 gt The compiler can be instructed to generate inline integer math code after a math library is included pragma inlineMath 1 a b inline integer code is always generated pragma inlineMath 0 pragma insertConst The compiler will normally insert const data at the end of the user code high address The following pragma statement will allow the const data to be inserted between two user functions or at a specific address if using pragma origin first fpragma insertConst pragma interruptSaveCheck lt n w e gt The compiler will automatically check that vital registers are saved and restored during interrupt Please refer to Chapter 6 3 I
130. struct bitfield unsigned a 1 bat Cs unsigned d 32 char aa 27 The CC8E compiler also allows the bitfield syntax to be used outside structures as a general way of defining variable size int x 24 a 24 bit signed variable Typedef Typedef allows defining new type identifiers consisting of structures or other data types typedef struct hh HH HH varl typedef unsigned ux 16 equal to 16 Ux PE c be 2 3 Using RAM Banks The RAM bank definitions are access bank 0x000 0x07F and OxF80 OxFFF bank 0 0x080 OxOFF bank 1 0x100 0 1 bank 2 0 200 Ox2FF bank 15 OxFO0 OxF7F Using more than one RAM bank is done by setting the active rambank variables proceeding the first rambank statement are placed in the access bank This is also valid for local variables and parameters pragma rambank 1 char a b c a b and c are located in bank 1 parameters and local variables in functions placed here are also located in bank 1 pragma rambank 0 char d located in bank 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 the access bank The access bank is selected by pr
131. sv PCLATH PCLATU PCLATU PRODL sv PRODI PRODH sv PRODH TBLPTR sv TBLPTR TABLAT sv TABLAT int restore register IMPORTANT GIEH GIE r S W STATUS and BSR or GII EL should normally NOT be 79 CC8E Compiler B Knudsen Data set or cleared in the interrupt routine GIEH GIEL are AUTOMATICALLY cleared on interrupt entry by the CPU and set to 1 on exit by RETFIE Setting GIEH GIEL to 1 inside the interrupt service routine will cause nested interrupts if an interrupt is pending Too deep nesting may crash the program void highPriorityInt void save registers on demand restore registers on demand bankO char bit bl b2 static char ppm shrBank char sr void sub bankl char ax bankl char i a local variable generate pulses for i 0 i lt 1 i out 1 2 out 0 increment global variable void main void PORTA 0b0010 TRISA 000001 if 1 66 PD 1 power up clearRAM set all to 0 5 b1 1 ppm 0 sr reverse sr call assembly routine b2 b1 do if in 1 break sub amp 3 while a lt 200 80 CC8E Compiler B Knudsen Data
132. the extra work to analyze the program to prevent overflow and too large accumulated errors If there is plenty of code space in the controller 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 CC8E can print a warning for each operator function that is called option wO 6 6 Inline Assembly The CC8E compiler supports inline assembly located inside a C function There are some restrictions compared to general assembly First it is only possible to CALL other functions Second GOTO is restricted to labels inside the function asm assembly instructions fendasm Features e many assembly formats e equ statements can be converted to variable definitions e macro and conditional assembly capabilities e call C functions and access C variables e C style comments is possible e optional optimization e optional automatic bank updating Inline assembly is NOT C statements but are executed in between the C statements It is not recommended to write the code like this 62 CC8E Compiler B Knudsen Data if a b asm this is not statement by definition
133. tion is not called defined but not in use then all parameters and local variables are truncated to the same unused location 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 Arrays structures and unions One dimensional arrays is implemented char t 10 i index x temp unsl6 tx 3 tx i 10000 EDL Senay 20 AY ook t i t x 20 not allowed temp t x 20 t i temp Normal C structures can be defined also nested types Unions are allowed struct hh f long a char b vx1 union struct char a inelo ai pp char x 4 uns32 1 uni accessing structure elements vxl a 10000 uni x 3 vxl b 10 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 19 CC8E Compiler B Knudsen Data Bitfields Bitfields in structures are allowed The size have to be 1 8 16 24 or 32 bit
134. tion of access bank 0 or banked access 1 is OPTIONAL and automatically decided by the variable accessed If this information is added then the compiler checks that it is equal to the access required by the variable Variables residing at address 0 7 and OxF80 OxFFF must use the access bank other accesses must be banked 63 CC8E Compiler B Knudsen Data ax W 0 load result into W in access bank ax W 1 load result into ax in bank 0 15 ax W load result into W implicit banked accessbank Formats when loading then result into the W register implicit banked accessbank 0 load result into W iorwf ax w load result into iorwf ax W Formats when writing the result back to the RAM register implicit banked accessbank decf ax decf 1 iorwf ax f iorwf ax F Bit variables are accessed by the following formats implicit banked accessbank bcf Carry bsf Zero bcf ax B2 B2 defined by EQU or define bef 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 Labels can start anywhere on the line goto LABEL4 LABEL1 LABEL2 LABEL3 LABEL4 nop nop goto LABEL2 Functions are called directly A single 8 bit parameter can b
135. top idt Po tsb iden 3l Function ret rn vales RE 31 Param ters in funetion calls eis ettet 31 TAa TRU 32 JO C LYPEGCASTS oen ONES Rege tote Neo 33 3 6 ACCESSING PARTS OF A VARIABLE sese ee een e nennen eene nennen nennen rere 34 344 JC EXTENSIONS ty duc scien cadena Caden RAURU IN RUPEE 35 3 8 PREDEFINED S YMBOLS 35 Automatically defined macros and symbols 36 3 9 UPWARD COMPATIBILITY 2 nee 36 4 PREPROCESSOR 2 1 2 1 1 ons 37 e T DER 37 Macro concatenatioh se e 37 Macro stringtfiCatiOn eee 37 38 Fundef 38 Vif ii a et PRU x Re 38 HU 39 39 39 dlc UE 39 seo sri wae e EGER DS EEUU Pete e EU tee oe ay tet ee t eee He tee pei ed deb vet 39 e YII E be 39 4 1 THEPRAGMA STATEMENT item ie eet bee bebe rie eder eee 39 Zpr gma dccessGPR ENS annn 39 Zpragma alignLsbOrigin
136. ts of an array of goto statements examples follow later Computed Goto Regions affects 1 Optimization 2 Register bank bit updating 3 256 byte boundary checks Examples char subO char i skip i jumps i code words forward pragma return Hello world pragma return 10 more text 0 1 2 3 OxFF This is a safe and position independent method of coding return arrays or lookup constant tables It works for all PICmicro devices The compiler handles all checking and code generation issues It is possible to use return arrays like above or any C statements return 110 return Ox2F 93 CC8E Compiler B Knudsen Data 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 gt 3 goto Default skip 5 goto Case0 goto Casel goto LastCase pragma computedGoto 0 end of c goto region Case0 user statements return Casel LastCase user statements return Default user statements return void sub4 char this solution can be used if very fast execution is important and a fixed number of instructions 2 4 8 is executed at each selection Please note that extra statements have to be inserted to fill up empty space between each case if s gt 10 goto END S rlnc s multiply by 2 S rlnc s mult
137. unction parameters should preferably be put in the access bank The most frequently used variables except arrays should be placed in the access bank It is efficient to put the most frequent used arrays in bank 0 Try to locate variables which are close related to each other in the same bank Try to locate all variables accessed in the same function in the same bank See RAM bank selection RAM and special purpose registers can be located in up to 16 banks A special bank instruction is used to select the right bank The bank selection bits are automatically checked and updated by the compiler and attempts to update the bank in the source code may be 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 REMOVE attempts to use the bank instruction MOVLB in user source code However it is possible to switch to manual updating by the b command line option or locally by a pragma statement Local user update regions The automatic updating can be switched off locally This is done by pragma statements pragma updateBank 0 OFF pragma updateBank 1 ON 21 CC8E Compiler B Knudsen Data These statements can b
138. upport the const access functions generated by CC8E 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 CC8E can not 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 sizel size2 will be 16 bit wide An extern visible pointer with the sizel 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 a specific bank by a pragma statement extern sizel char px pragma assume px in rambank 2 Note that 8 bit pointers in a struct can only access addresses from 0 255 even if the struct is static or local Local variables uses a different naming strategy on local variables when generating relocatable assembly CC8E reserves a continuous block in each ram bank or access 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 can not contain local variables or parameters because address sharing can not b
139. watchdog timer timeout or a low state on the MCLR pin PIC18 also allows restart by interrupt A RESET instruction is therefore inserted if main is allowed to terminate SLEEP This ensures repeated execution of the main program Clearing ALL RAM locations The internal function clearRAM will set all RAM locations to zero The generated code use the FSRO register The recommended usage is void main void if 1 66 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 Typically 4 or 5 instruction cycles is required for each RAM location At 4 MHz each instruction cycle is 1 microsecond PIC18C452 device contains 1536 RAM locations which means 1536 5 7680 instruction cycles or 7 68 milliseconds at 4 MHz 6 5 Library Support The library support includes standard math and support for user defined libraries The library files should be included in the beginning of the application but after the interrupt routines interrupt routines finclude math16 h 16 bit integer math include math24f h 24 bit floating point finclude math241b h 24 bit math functions CC8E 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 l
140. y 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 That 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 Automatic chosen pointer size single pointers 3 Pointer size chosen according to the default model Command line options mc1 default const pointer size is 1 byte 8 bits mc2 default const pointer size is 2 bytes 16 bits mr1 default RAM pointer size is 1 byte mr2 default RAM pointer size is 2 bytes mm1 default pointer size is 1 byte all pointer types mm2 default pointer size is 2 bytes all pointer types Pointer size type modifiers sizel pointer size is 1 byte 8 bits e size2 pointer size is 2 bytes 16 bits 22 CC8E Compiler B Knudsen Data bankl size2 float pf The supported pointer types are a 8 bit pointer to RAM The compiler will automatically update the MSB bits FSROH b 16 bit pointer to RAM This format is required only when the same pointer have to access locations in different 256 byte RAM segments 8 bit pointer to program memory This pointer can access up to 256 byte data d 16 bit
Download Pdf Manuals
Related Search
Related Contents
SBS TE0SCL85K mobile phone case DSLR-A100 Case Logic ULM-116 SUIVIE DES E P D70 Dm PRAMAC - Scalemates Les Intelligences Multiples en pratique BULLETIN DLABONNEMENT 5. FUNCIONALIDAD DE VOZ: REPRODUCCIÓN, GRABACIÓN Samsung YP-T8Q Инструкция по использованию Copyright © All rights reserved.
Failed to retrieve file