Home

C Compiler V3 user's Guide

image

Contents

1. 4 4 Operator Operators C compiler V1 C compiler V2 C compiler V3 ANSI C Arithmetic operators e D D e Relation operators gt lt gt lt e e e e Logical operators amp amp D D D D Bitwise operators lt lt gt gt amp D D D D Assignment operators t gt gt lt lt 8 4 e e e H Condition operators D D D D Comma operators D D D e Pointeroperators and amp D D D e Byte evaluation operators sizeof D D D e Type conversion operators type D D D D Structure memberoperators gt D D D e Suffix operator D D D D Function adjustment operators D D D D Increment operators D D D D Decrement operators D D D D Minus sign operators D D D e Plus sign operators t D D D e RAM address assignment operators D D 4 5 Preprocessor Instructions ege C compiler V1 C compiler V2 C compiler V3 ANSI C asm Y Y NO N define Y Y Y Y elif Y Y Y Y else Y Y Y endif Y Y Y Y error Y Y N N if Y Y Y Y ifdef Y Y Y Y ifndef Y Y Y Y include Y Y Y Y pragma Y h N N undef Y Y Y Y Note D Indicates error information error size too big ee 2 C compiler V3 inline assembly code use asm format please refer to 2 4 Rev 1 00 53 December 26 2014 4 6 Preprocessor directive pragma The Format pragma ke
2. Compiler Settings Linker Options Compiler Flags Preprocessor Categories lt All Categories zj IDo not warn if an unexpected timize generated code fo Use the syntax of Holtek V2 inlini attribute is used Wno attributes e assembly Compile error if a function parameter is declared as implicit int type Using table read access the const variable Must be set if the const qualifier variables with spe d en gt v lt Generate listing file If no nested interrupts occur in the program which means the program will not enter another interrupt during the execution of the current interrupt then selecting the Optimize data memory option can save RAM space The interrupt program should be written as briefly as possible otherwise it will take up too much RAM space Rev 1 00 70 December 26 2014 e Compiler Settings Linker Options Categories All Categories M Optimize data memory if not nesting interrupts occur 4 Remove unused function only for C Uninitialized global static variables are automatically set to 0 Warn if the address of alias variable is overlap Arrange the ROM space by address order For the MCU whose ROM is 16 bits wide and
3. iaiaaaaaaaaaaaaaaaasaanaaaaananaannunauaaaannanauananaaannannananua 22 1 4 1 Using Structure Union and Enumeration 2 212 21122222222222usdasinasdsslkassa sgdanassanssunanfsals 22 1 4 2 Differences between Structure and Union 23 1 5 Differences between Preprocessor Macro definition and Inline function 23 TE FlOW COMMON M 25 1 6 1 Three Execution EloW gas rer EE eves pi re tere Oe E na 25 16 2 Using of if arid SW a eee ad ad ia nes 25 1 6 3 LOOP and nested loopitng E 26 1 6 4 break and COntUnUG E 26 1 6 5 9oto statement rd 27 A REOS 28 Chapter 2 C compiler V3 Expansion and Limitation 29 2 1 Holtek C compiler V3 settings in the HT IDE3000 22 222224222kissssss sn ssnn snsn stansskansnnnn 29 2 1 1 Operation environment reine Dee ra 29 2 1 2 Building a new project use Holtek C V3 compiler err 29 2 1 3 After opening the project how to use the Holtek C V3 compiler 30 2 1 4 Project Compiler Option settings 2 1 Linker options actes 2 2 C compiler V3 Extended syntax and f nction 11 2issssanvssanvisasv andinassnnas na saan danan siiani 34 2 2 1 Interrupt Service Roultlnes irte l tu eie tiran e REESEN 34 2 2 2 Absolute variable ici ire ret p Hasa P valda vata f ii VBa LI TER EN TRU ERE cita 35 Rev 1 00 3 December 26
4. eee 60 6 1 Header Files L 60 enee Ee EE 60 6 3 Calling a function from other original les 60 6 4 Using el TE 61 Chapter 7 Mixed LAN nnmn 62 TA REI Re SNS E a ddr 62 7 2 Nanable and function naming f les cierre certe die 62 7 3 Calling an assembly function from the C program 62 7 4 Calling a C function from the assembly program sse 64 Chapter 8 Common Error Solutions esses 66 9 1 Internal TEE 66 8 2 RAM bank overflow sue nde dienes bi eoe LA SERE Ge ER BR da Dae n SERA dina 66 8 3 ROM RAM space overflow 66 8 4 Variable Overlap Warning eiii cac n EE ie ee Ced coke SEE coa eheu ES a 66 9 5 Variable Rede ici iri eterne netu essei reset uen ps na be penes 67 Chapter 9 Programming Examples 5 eene ran n rdar 68 9 1 LED flashing using the interrupt eerte enin etre ine ket cene cn 68 9 2 7 segment LED display number using ole 68 Chapter 10 Program Optimization ecce 70 10 1 Optimization OP EE 70 10 2 Variable Declaration ii Free BER A OR NA d b Ra deet 73 10 2 1 unsigned sighed iint oto d ma a a a Entente erit a El a pa dee kg oes 73 10 2 2 Date type tei eh cta re e aa aa ates 73 10 2 3 Floating Be 73 10 24 CONSTA iuri it tente eiae aee 74 10 3 Arithmetic Operation sain d amti EES eie te dent aaa eden Ene il dae ehe 74 10 3 1 Bitwise AND 8 replaces Remainder
5. nor The main difference between structure and union is the configuration of the memory space A structure assigns memory space for every member while a union provides a way to manipulate different kinds of data in a single storage area The union size is the largest data type size For example in the example 8 if using sizeof pa type to operate the structure size then the result is 1 if pa5 is set to 1 then the 5th member of pa type is set to as well 1 5 Differences between Preprocessor Macro definition and Inline function Rev 1 00 There are three preprocessors in the C language macro define define include file include conditional compiler if etc If preprocessing was executed before compiling such as in macro expansion then it is performed when precompiling 1 Macro definition note that when using macro definition the macro name is simply replaced by the macro defined content and does not execute any operations For example define S r 3 1415926 r r if using S 6 6 then the result is 3 1415926 6 6 6 6 but it is not the desired result Then by using define S r 3 1415926 r r the desired result can be obtained 2 Include file using include to include the files using file h is different from using lt file h gt to include files file h is used for user defined files while lt gt is used for library files in order to reduce the time spent in searching pat
6. PCL For table read 43 December 26 2014 Chapter 3 C compiler V3 optimization function 3 1 Optimization Contents Introduction The C Compiler V3 is an optimized complier whose main objective in optimisation is to simplify the code and reduce the quantity of code required By default enable Os will execute all the optimization functions The following table shows each function as executed by the compiler including whether each optimized function can affect debugging whether SE save ROM save RAM save Stack the debugging Algebraic Transformations y e copy propagation value propagation y e Unreachable code Elimination y e Dead code Elimination y e Constant Folding e constant propagation e Inline Procedure y e Strength Reduction y e Tail Recursive Call e subexpression elimination e Tail merging y e BP optimization e Dead section elimination y e 3 2 Algebraic Transformations Algebraic transformations mean that the compiler will replace some expressions with simpler operations which have the same functions For example a gt a if la amp amp b gt if a b This kind of replacement will not affect debugging 3 3 Copy Propagation Value Propagation Rev 1 00 Copy propagation is a kind of transformation for the variables x and y when y was assigned to x If the values of x and y are not changed in
7. 10 10 char array 10 10 void fun void void init array void int i j int i j for i 0 i lt 9 i for i 0 i lt 9 i for j 0 j lt 9 j for j 0 j lt 9 j array i 3 0 array i 3 0 void main void void fun void int i j init_array for i 0 i lt 9 i for j 0 j lt 9 j void main void array i j 0 fun init array fun Code size 119 Code size 64 10 5 3 If the function can only be called in the current file it can be defined as static float s float s unsigned char func unsigned char dx static unsigned char func unsigned char dx unsigned char sum sum dx 0 dx 1 dx 2 unsigned char sum return sum sum dx 0 dx 1 dx 2 return sum unsigned char sum unsigned char array 4 unsigned char sum void main unsigned char array 4 void main sum func array s sum float 3 14 sum func array s sum float 3 14 Code size 222 Code size 184 Rev 1 00 77 December 26 2014 10 6 Global Variable Assignment For non long instruction architecture MCUs banks other than Bank0 in RAM must be addressed indirectly As shown in the following example the number of instructions for indirect addressing is 5 more than direct addressing So when RAM Bank overflows users can define the infrequently used variables to other banks and the more frequently used variables to bank0 Direct addressing Bank 0 Indirect
8. 2 Input the library name as follows math lib mull lib separated by Project Option Debug Option Directories Document Production Micro Controller pa with BootLoader Language Tool Holtek C Compiler V3 Assembler MA Project s Build Option Assembler Compiler Options Define Symbol DS CS v Generate listing file V Generate Project listing file list Linker Options Libraries math lib mull lib Section address V Generate Map File 2 1 5 2 Set the function address format fun name addr fun2 name addr2 here fun name is _ function name addr is the address it is hexadecimal if there are multiple functions then the address is separated by Note This feature is not recommended because it will affect compiler optimization 2 1 5 3 Generate Map File when checked a map file will be generated 2 1 5 4 Linker options Optimize data memory If not nesting interrupts occur in the project select the option can save data memory Remove unused function If a function is not called then the system will not assign space for it this option is enabled by default Uninitialized global static varibles are automatically set to 0 If a global has no initial value the default initial value is 0 this value will be cleared when the program starts running Warn if the address of the alias variable is overlap Check whether the address of the alias variable is
9. 2014 2 2 3 MCU header file introduction in einen sens caerse 36 2 2 4 Naflablellitlall lati 222 sis iku skata iiec rr Fecha eea na blaa SR ar RE NK 38 2 2 5 Inline Assembly EE 39 2 2 6 Specify Function Allee ai arie lak a 40 2 2 7 Specify const address is aa ae ca en naa E ee eee 40 2 2 8 Variable assignment a a dieti tee oen bk den acens Ed 41 2 2 9 altribule SYNI EE 41 23 C compiler V3 limitation send 42 231 FUNCION POM ie 42 2 3 2 Rec rsive FUNCTION EE 42 2 3 9 T bit MP Memory Pointer ssi sansa snasa slarasravkal astar ska aaa e 42 2 4 Compiler managed fESOUrGES 1 eerie nennen nnn nrbt alan Baada ka al sa cantes 43 Chapter 3 C compiler V3 optimization function suus 44 3 1 Optimization Contents Introduction emen nenne 44 3 2 Algebraic Transformations cernunt recente tt te tke A Lena n nandi 44 3 3 Copy Propagation Value Propagation seen eme emen 44 3 4 Unreachable Code Elimination iiie errore re eee er ecco Re c FASI 45 3 5 Dead code Elimination icons ttt tette et att bach Ba prime shed reme Re E Roe agna eet 45 3 0 Constant Folding EE 45 3 7 Constant Propagation e ierit a da ETUR ERA o 45 3 9 Inline Proce d n s s Faces O aa a e a aa eR 46 3 9 Strength Ee 47 3 10 Tall Recursive Calls aman slanga reet aa a een ce ions t EE eL oPn eI 48 3 11 Subexpression Eliminat curan
10. 32 bit field now allowed neitheris Union allowed neitheris Se max max DP the definition for over the definition for 9 bit field over 9 bit field Recursion Recursion Recursion function Recursion function not E Function hetallhbaltes Subpored function not function pp PP supported supported Cannot be applied to Cannot beapplieg constant and bit to constant and A e variables For pointer Function pointer Pointer bit variables Se Y function it must be full not supported Function pointer domain and all function not supported without parameters Initial value cannot be set when the The initial value cannot global variable is be set when the global T being declared variable is being Wies While declaring declared declaring the d the const the initial const the initial value value must be set must be set first first Stack Layers limited D Layers limited D Layers limited D Layers not limited Rev 1 00 56 December 26 2014 Note There are limited numbers of stack levels for every MCU When calling functions the stack levels required should be taken into account The numbers of layers occupied by operators or functions during the calling process are shown in the table below Operator Function Stack Needed Operator Function Stack Needed main 0 _ri int char 0 _clrwdt 0 _ric int 0 _clrwat1 0 _Iri
11. 48 30 0 80 50 P 112 70 p 17 11 DC1 49 31 1 81 51 Q 113 71 q 18 12 DC2 50 32 2 82 52 R 114 72 r 19 13 DC3 51 33 3 83 53 S 115 73 S 20 14 DC4 52 34 4 84 54 T 116 74 t 21 15 NAK 53 35 5 85 55 U 117 75 u 22 16 SYN 54 36 6 86 56 V 118 76 V 23 17 ETB 55 37 7 87 57 W 119 77 w 24 18 CAN 56 38 8 88 58 X 120 78 X 25 19 EM 57 39 9 89 59 Y 121 79 y 26 1A SUB 58 3A 90 5A Z 122 TA Z 27 1B ESC 59 3B h 91 5B 123 7B 28 1C FS 60 3C lt 92 5C 124 7C 29 1D GS 61 3D 93 5D 125 7D 30 1E RS 62 3E gt 94 5E S 126 7E 31 1F US 63 3F 95 5F 127 7F Rev 1 00 79 December 26 2014 HOLTER S Appendix B Operator Priority C Compiler V3 user s Guide Priority Operators Description operation type Associativity parenthesis subscription 1 unary left to right gt structure pointer structure member Deny Take one s complement tt increment decrement 2 type key word type coercions i ar right to left unary plus unary minus li pointer amp address sizeof size of type 3 1 Multiplication Division Remainder binary left to right 4 unary plus unary minus binary left to right lt lt shift left A 5 binary left to right gt gt shift right e on eran Oeae an oroia oppent lefttorighi 7 l Equal Unequal relational left to righ
12. N Y 4 9 Main Functions Main Function Rule C compiler V1 C compiler V2 C COMPILER V3 ANSI C Number piece 1 1 1 1 Data return type void void void int Parameter piece None None None 2 one pointerarray 4 10 Interrupt Functions Interrupt Function Rule C compiler V1 C compiler V2 C COMPILER V3 ANSIC Setup interrupt Y Y Y vectorvalue Number piece Plurality acceptable Plurality acceptable Plurality acceptable Data return type void void void Parameter None None None g No interupt Re enterinterrupt N YO YO functions Interrupt called in the N N N program Interrupt calling assembly Y Y Y function Interrupt calling C function N YO YG Note Although different interrupts can be nested at the same time the same interrupt cannot be generated twice at the same time until the previous interrupt ISR has completed For those controllers without interrupt nesting feature the interrupt function cannot be enabled in the service routine 2 It is necessary to define the called function as pragma nolocal otherwise RAM overuse will occur which is not recommended 3 The function called by interrupt can not call the same function with the main function otherwise RAM overuse will occur The different interrupt can not call the same function For instance isr1 funl fun3 main fun2 fun1 isr2 fun3 then the ter and main
13. a void main a max 10 20 function calling att int max int a int b return value type function name parameters list returna gt b a b Operation result a 21 1 2 2 Parameter list and return value Parameters are written in parentheses after the function name and will be called into a function Formal and actual parameters Actual parameters can be constants variables or expressions but they must be definite values which will be passed to the formal parameters of the function when the function is called When the function is defined the formal parameter must be specified as a data type The formal and actual parameters must be compatible The most important characteristic of formal parameters is one way passing This means that any changes to the formal parameters will not affect the actual parameter values in the calling routine In the C compiler V3 the naming rules of function Local variables and parameters is _ funname 2 n For example variables of fun function are named as fun 2 n indicates the variables number If the return value size is one byte then the value is stored in the ACC if it is two bytes then its low byte is stored in ra the high byte is stored in rb if it is four bytes then the four bytes are stored in ra rb rc rd from low byte to high byte Due to the MCU limitations no stack the parameters and internal variables will take up RAM space The function variables which do not
14. addressing not Bank 0 Rambank 0 ds Rambank 1 ds ds section data ds section data _var0 db _varl db MOV A 40H OV A BANK varl MOV var A OR A ROM BANK FUNC OV BP A OV A OFFSET varl OV MP1 A OV A 40H OV IAR1 A Code size 2 words Code size 7 words 10 7 Interrupt Service Routines Generally if two functions do not have a call relationship with each other their local variables can share the same address but interrupt service routines can not share the local variable address with the main function So in order to reduce the use of RAM the interrupt program should be written as briefly as possible and not be too complicated Rev 1 00 78 December 26 2014 Appendix A ASCII CODE TABLE DEC HEX Symbol DEC HEX Symbol DEC HEX Symbol DEC HEX Symbol 0 0 NUL 32 20 space 64 40 a 96 60 1 1 SOH 33 21 65 41 A 97 61 a 2 2 STX 34 22 66 42 B 98 62 b 3 3 ETX 35 23 67 43 C 99 63 C 4 4 EOT 36 24 68 44 D 100 64 d 5 5 ENQ 37 25 96 69 45 E 101 65 e 6 6 ACK 38 26 amp 70 46 F 102 66 f 7 7 BEL 39 27 i 71 47 G 103 67 g 8 8 BS 40 28 12 48 H 104 68 h 9 9 HT 41 29 73 49 105 69 i 10 OA LF 42 2A 74 4A J 106 6A j 11 0B VT 43 2B 75 4B K 107 6B k 12 0C FF 44 2C 76 4C L 108 GC 13 0D CR 45 2D 77 4D M 109 6D m 14 OE so 46 2E 78 4E N 110 6E n 15 OF SI 47 2F 79 4F O 111 6F o 16 10 DLE
15. bank then the code will be call fun2 If funl is assigned to bank0 fun2 is assigned to bank1 then the code will be set BP 5 call fun2 clr BP 5 49 December 26 2014 3 14 Dead section Elimination Rev 1 00 If a function was not called during the programs then the linker will not assign space for this function this character can be selected by the following option A special condition is that when the compiler optimizes the function call to an inline expanded function then the subfunction may be removed without being called B z eg Projects Buld Opna rs A Compiler Settings Linker Options Categories lt All Categories S Optimize data memory if not nesting interrupts occur Uninitialized global static variables are automatically set to 0 Warn if the address of alias variable is overlap Arrange the ROM space by address order lt OK Cancel 50 December 26 2014 Chapter 4 Contrast of Holtek C V1 Holtek C V2 Holtek C V3 ANSI C 4 1 Data Type Data type Size bit C Size bit Cc Size bit C Size bit compiler V1 compiler V2 COMPILER V3 ANSI C bit 1 1 N N char 8 8 8 8 signed char 8 8 8 8 unsigned char 8 8 8 8 short 8 16 16 16 unsigned sholt 8 16 16 16 Int 8 16 16 16 unsigned int 8 16 16 12 Long 16 32 32 32 unsigned long 16 32 32 32 long long N N 32 64 unsigned
16. both call funl while the isrl and isr2 both call fun3 Rev 1 00 55 December 26 2014 HOLTER S 4 11 Built in Functions C Compiler V3 user s Guide C compiler V1 C compiler V2 Function Paremeter Type Paremeter Type C compiler V3 ANSIC _clrwdt Y Y GCC_CLRWDT N _clrwdt1 Y Y GCC_CLRWDT1 N _clrwdt2 Y Y GCC_CLRWDT2 N _halt Y Y GCC_HALT N _nop Y Y GCC_NOP N _rr int8 Y int Y char GCC_RR int 8 N _rre int8 Y int Y char GCC_RRC int 8 N _Irr int16 Y long Y int N N _Irre int16 Y long Y int N N _rl int8 Y int Y char GCC_RL int 8 N _ric int8 Y int Y char GCC_RLC int 8 N _Irl int16 Y long Y int N N _Iric int16 Y long Y int N N _swap int8 Y int Y char GCC_SWAP int 8 N _delay unsigned long tick Y tick lt 65535 Y tick lt 263690 GCC_DELAY tick N 4 12 Other Functions Function C compiler V1 C compiler V2 C COMPILER V3 ANSI C Inline assembly Y Y Y N Static variables 1 Static variable and functions not Sialic variables and Y Y functions not supported supported Constant Bit constant Biteohstantsl bporle Bit constant Bit constant not supported PP supported supported bit field placed in ee me gaunt wo et placed i e Bai Structure and 8 bit units are now PES Up to 32 bit field Up to
17. can directly jump to a statement label to execute programs It is generally not recommended to use goto statements Example 10 using goto correctly to optimizes code code list 1 20 typedef unsigned char u8 define BOOL u8 define TRUE 1 define FALSE 0 u8 result BOOL fun1 BOOL fun2 BOOL fun3 Original version goto version void main void main BOOL b result FALSE BOOL b result FALSE u8 b 3 a 3 u8 b 3 a 3 u8 p a u8 p a b result funl b result funl if b result if b result goto error result 0x55 b result fun2 p b if b_result goto error b result fun3 b result fun2 if b_result goto error if b_result error result 0x55 result 0x55 p b p b b result fun3 if b result result 0x55 p b Rev 1 00 27 December 26 2014 example 11 using do while 0 instead of goto do while O version void main char b result 0 u8 b 3 a 3 u8 p a do b result funl if b result break b result fun2 if b result break b result fun3 if b result break while 0 result 0x55 p b 1 7 Scope Both the variable and the function has its scope Global variable function can be used in the whole project after being configured as extern If a global variable is defined as static then this variable can only be used in this file In order to
18. character and floating types The structure data types contain structure arrays union and enumeration Using these structure data types will be able to construct the required data structures The basic data types C compiler V3 are shown in the following table 1 1 1 Data Type Size bit Scope Bool 1 8 0 1 char 2 8 128 127 unsigned char 8 0 255 short 16 32 768 32 767 unsigned short 16 0 65535 int 16 32 768 32 767 unsigned int 16 0 65535 long 32 2147483648 2147483647 unsigned long 32 0 4294967295 long long 32 2147483648 2147483647 unsigned long long 32 0 4294967295 float 3 24 3 4E 038 3 4E 038 double 4 32 3 4E 038 3 4E 038 long double 4 32 3 4E 038 3 4E 038 Table 1 1 1 Basic Data Types C compiler V3 Note 1 Bool type when the value is not 0 then the result is 1 when the value is 0 then the result is 0 For example Bool a 4 then a 1 21 If no signed or unsigned is marked in front of the basic data type it will be regarded as signed It is the same for below Rev 1 00 8 December 26 2014 3 The floating type is 24 bit supported by C compiler V3 and only 4 5 digit precision is supported by V3 20 or above sign exponent e mantissa m 23 22 15 14 8 7 0 4 Double and long double data types have IEEE 754 32 bit format and 6 7 digit precision supported by V3 20 or abo
19. have a call relationship with each other can share the same RAM space Example 3 The value a is changeable Code list1 4 int a void change int b b void main a 15 change a Operation result a 15 A function can return a value to the calling routine the return type can be void but it is important to not write any statements after the return statement 15 December 26 2014 1 2 3 Function Call 1 2 3 1 Function Call method and Process There are three methods to call the function 1 Function statements the function call can be used as a statement to achieve a function such as change a 2 Function expressions for example int a 3 max 10 20 3 Function parameters for example int a max max 20 30 20 Function Call Process The function call process and the function parameters passing direction of the different compilers are different In the C language the formal parameter passing direction is from right to left The following example describes the process of calling a function in the C compiler V3 take Example 2 as an example Process 1 store return value int a max 10 20 Return the address back from q the stack to the PC Push the next instruction address o ntothe stack End of the function call Pass 20 to the formal parameter b Call max jump to max address pass 10 to the formal parameter a to execute the instructions 1 2 3 2 Nest Call The function nest call
20. num1 gt num2 numl num2 u8 getMax u8 numl u8 num2 return Max numl num2 endif EY H ifndef KEY H define KEY H include FUNCTION H u8 GetKey u8 numl u8 num2 u8 key getMax numl num2 return LeftShift key 2 endif AIN C include FUNCTION H include KEY H define DEBUG 1 using when debugging u8 debugval Rev 1 00 24 December 26 2014 void main u8 ch const u8 Led String YOU while Led String if DEBUG if changing 1 to 0 then this statement can not be compiled _debugval Led String endif ch Led String ch LeftShift ch 1 GetKey ch 0 Led Stringtt If passing ch to numl passing 0 to num2 of macro definition Max num1 num2 then ch gt 0 ch 0 but the value of ch is not the expected value Therefore the macro definition should be noted 1 6 Flow Control 1 6 1 Three Execution Flow The execution flow of the C language is sequential execution optional execution and loop execution 1 6 2 Using of if and switch If and switch are conditional expressions When many conditions exist the if statement can be replaced with the switch statement The switch variable must be enumerated and a basic data type except for float The case statement variable must be a constant value not including the constant with const the break statement will be used after the case statement was executed If no break statement exists
21. save ROM space static is not recommend The local variable can be used in the statements of the function after being declared If the variable is declared in the if and switch of the loop then the variable can not be used in the following statements after executing the if and switch statements As seen with the j variable of code list 1 19 the external statements of the while loop can not be used Rev 1 00 28 December 26 2014 Chapter 2 C compiler V3 Expansion and Limitation 2 1 Holtek C compiler V3 settings in the HT IDE3000 2 1 1 Operation environment This chapter is written based on the HT IDE3000 7 85 version Note The Holtek C V3 must operate in the HT IDE3000 7 71 or later version 2 1 2 Building a new project use Holtek C V3 compiler In the HT IDE3000 development environment build a new project using the following method Move the mouse cursor to the Project menu and click the left button Move the mouse cursor to the New command and click the left button In the following window select Holtek C Compiler V3 10 Assembler default in the Choose Language Tool Project Name Project Location C Users Documents HTK Project Project MCU Y Create directory for project BS83B08 3 MCU Information with Boot Loader RAM Size 1 Bank s Choose Language Tool ROM Size 800H WT EX EDT Stack Size 4 Holtek C Compiler V1 HCC Assembler BootLoader Size 0H Holtek C C ler V2 EHCCY Assembler Holtek C C
22. should not exceed 32K If it is a general array the length should not exceed one rambank Rev 1 00 51 December 26 2014 4 3 Identifier Reserved Words Rev 1 00 Reserved Word C compiler V1 C compiler V2 C COMPILER V3 ANSI C auto D D e e break e e e e bit e e case e e e e char e D e e const D D D D constant e continue e D D e default e e e e do e e e e double D e else e D e e enum e e e e extern D D D D float D e for e e e e goto D D e e if e e e e int e e e e long e D D e register D D e return e D D D short D D e e signed e D D e sizeof e e e e static e e e e struct D D e e Switch e e e e typedef e D D e union e D e e unsigned e D D e void e D e e volatile e e e e while e e e e vector D e attribute e at e 2 interrupt e 3 entry e 4 Note 1 The D and are used to define absolute address variable for example unsigned char sfr attribute at 0x40 it means the definition of sfr variable in the 0x40 address 2 The and 9 are used to define interrupt variable for example void attribute interrupt 0x04 isr name void it means the definition of interrupt isr name in the 0x04 address 3 The 4 is for entry function please refer to 2 2 9 52 December 26 2014
23. the array a while b is a pointer it points to the first address of the array that the data type is char and length is 5 If using sizeof to operate we can know that the length of a is 10 the length of b is 2 4 Index overflow Code List 1 11 unsigned char a8 5 0 1 2 3 4 unsigned char p a8 p 5 8 Operation results if a8 is stored in the start address 0x0085 of memory then the value of address 0x008a is 8 If an important value is stored in 0x008a it will affect the operation results of the entire programs Rev 1 00 20 December 26 2014 5 Operation constant pointer and pointer constant constant pointer means that the contents of the pointer pointed to is constant defined as the follows const char c pl The pointer constant means that the value of the pointer itself cannot be changed but the pointed contents can be changed defined as follows char const p2 c code list 1 12 void main char a 5 0 1 2 3 4 b 5 const char p Hello Word char const q a p 1 o try to modify the contents of the string constants error p Hello Word the pointer pointed to the constant can be changed p b can also point to the variable address q 1 2 modify the contents of the pointer constant pointed to q b try to modify the value of constant pointer error 6 Pointer operation The Pointer can execute add subtract increment decrement a
24. the following code then the value y can replace the value x This kind of optimization can not reduce the number of instructions but it can eliminate any dead code Refer to the section 3 5 Dead code Elimination for more information For example 00 char c 01 void foo char a 02 03 char b 04 b a 05 c b 06 Description Line 05 can be changed to c a then the code in line 04 has no purpose therefore it can be deleted Variable b also can be deleted Copy propagation will affect the debugging because of the elimination of line 04 and variable b The user can not set a breakpoint in line 04 and there will be no variable b in the watch window 44 December 26 2014 3 4 Unreachable Code Elimination The Unreachable Code Elimination function is used to delete the code that will not be executed in normal programs For example if 1 x 5 else x 6 In the above codes the else part will never be executed After optimizing the code using this function the new assembly code generated will not contain the else part The Unreachable Code Elimination function will affect the breakpoint setting in some lines of the C source code 3 5 Dead code Elimination In the function calculation if the values are not used in the whole function then these values are called dead values The instructions which only calculate the dead values are called dead instructions The values outside the function are used values
25. then the next statement will continue to be executed Multiple case expressions can execute the same statements The default statement shows the default cases and can execute without a break Code List 1 17 unsigned char f break default 3 Rev 1 00 25 December 26 2014 HOLTER S 1 6 3 Loop and nested looping C Compiler V3 user s Guide 1 while expression statement 2 do while expression Differences do while expression the statement executes at least once code list 1 18 int sum 0 void main int i 11 while i lt 11 sum i itt int sum 0 void main int i 11 do sum i itt while i lt 11 result sum 0 sum 11 3 nested looping In loop statements the loop can be executed more than once 1 6 4 break and continue Break is used for loop or switch case statement while continue is only used for the loop statement the differences between them are that the continue statement orders the program to skip to the end of the loop and begins the next iteration of the loop while the break statement is to jump out from a loop and execute other statements outside this loop code list 1 19 while 1 int j 0 while 1 Jtt if j 5 continue execute the next iteration of the loop if j 10 break jump out from the loop Rev 1 00 26 December 26 2014 1 6 5 goto statement The goto statement
26. thus saving the b c operation once int a b c d g a b octg d b c d gt tmp b c a tmp tg d tmp d Subexpression Elimination will not affect debugging 48 December 26 2014 3 12 Tail Merging The same instruction sequences can be merged into one instruction sequence this operation is called Tail Merging The following C source codes show how to use it 00 if user value PORTB 0x55 user value 0 else PORTB 0x80 user value 0 0 On Cn BF WN rn S y d ox cc Lo Ln03 and Ln08 are the same code The compiler will compile the Ln 08 code only and the Ln03 code will be deleted If executing the if branch then after executing the Ln02 the program will jump to Ln08 and not to the else branch which may create some misunderstanding Because the multiple source codes may have the same assembly code sequence this will make it difficult for the debugger to determine which code line is executing 3 13 ROM BP Optimization Rev 1 00 For the microcontroller with multiple ROM banks it is important to set the BP to choose the bank before using Jmp and call If the current BP is the BP after using Jmp and call the linker will delete the following instruction mov BP a If the ROM BP instruction can not be deleted then using the set clr BP 5 6 7 instruction will save using the ACC For example void funl fun2 If funl and fun2 are assigned to the same
27. 14 C Compiler V3 user s Guide 4 Inline function definition HOLTEK j 7 Built in Function Description GCC RL varname 1 varname rotates left without carry GCC RLC varname 1 varname rotates left with carry GCC RR varname 1 varname rotates right without carry GCC RRC varname 1 varname rotates right with carry GCC NOP nop execute a dummy instruction NOP GCC SWAP varname 1 exchange the first four bits and the last four bits of varname GCC HALT halt execute a HALT instruction GCC CLRWDT clrwdt clear the watchdog timer CLRWDT GCC CLRWDT2 clrwdt2 clear the watchdog timer CLRWDT2 GCC CLRWDT1 clrwdt clear the watchdog timer CLRWDT1 GCC DELAY n 2 Delay n instructions Note 1 varname must be a 8 bit variable 2 0 lt n lt 263690 5 If MCU contains EEPROM then define EEPROM DATA a b c d e f g h Using this statement to write a value to EEPROM define mkstr x asm asm asm asm asm asm asm asm ix define _ EEPROM DATA a b c d e f g h eeprom data section eeprom V dblt mkstr a N db t mkstr b do t mkstr c N db t mkstr d do t mkstr e N db t mkstr f dblt mkstr g db t mkstr h asm 8 values can be written in order at once such as EEPRO
28. 2 3 4 Inline Function Using the keyword inline to qualify functions then the function is named inline function Using inline function body statments instead of calling functions to achieve the function purpose will reduce time and stack overheads when calling functions However the inline function of multiple calls may add much additional code Code List 1 7 unsigned char max inline void getmax unsigned char varl unsigned char var2 max var2 gt varl var2 varl void main getmax 23 32 Here using the codes max var2 gt varl var2 varl in place of getmax 23 32 function 1 2 4 Main Function The Main function is a special function which is the start of a program execution After initializing the MCU environment the Main function is executed Every project must include a main function however the main function does not require parameters and return values 1 2 5 Standard Library The C Compiler V3 v3 20 or above supports math h string h and other standard librarys For a more complete description refer to the IDE doc lt standard library user s guide gt 1 3 Pointer and Array Rev 1 00 An array is composed of elements of the same data type using the array name and index to distinguish each element of the array Every byte has one number called address in memery while the pointer itself is a variable that stores the address numbers 1 3 1 Array Definition Initialization and Usage Array d
29. 3 This is the highest optimization level Using this option the code compilation time will become longer and the generated code may be different from the original codes For this reason it is not generally used Os This level is used to optimize the code size Using O2 the code stored space will not increase This is extremely useful for small storage capacity devices For a more detailed parameter description refer to the GCC user s guide 59 December 26 2014 Chapter 6 Multiple file programming Multiple files may be used in a project Here similar functions and definitions are written into one file in order to manage them more easily This chapter describes the related contents of multiple file programming The main contents are as follows Header file Common variables Function call from other original files Using libraries 6 1 Header File Head file used to declare variables and functions define macros specify the address variables and types and Can t define generic variables and functions ifndef XXX H define XXX H endif 6 2 Common Variables If multiple original files access a common variable then the variable needs to be defined as a global variable without static Using extern to declare the variable as an external variable after which the variable can be used In the same way the variable can be used in the header file The extern can be either in the function body or outside the function 6
30. 3 Calling a function from other original files Using the header file and extern allows external functions to be referenced The external functions may modify the global variables of the original files when calling the external functions Example 12 Using external functions to modify external variables Code list 5 1 FUNCTION H tifndef FUNCTION H define FUNCTION H typedef unsigned charu8 typedef unsigned int ul6 typedef unsigned longu32 define BOOL u8 define TRUE 1 define FALSE 0 u8 getMax u8 numi u8 num2 tendif FUN C tinclude FUNCTION Dn u8 g var Rev 1 00 60 December 26 2014 u8 getMax u8 numl u8 num2 if num2 0 g var 0x55 Jelse if numl 0 g var Oxaa return numl gt num2 numl num2 MAIN C u8 sk getMax 28 0 void main i while 1 GCC NOP Operation result sk 28 g var 0x55 6 4 Using libraries Refer to section 2 1 5 Rev 1 00 61 December 26 2014 Chapter 7 Mixed Language In order to improve the efficiency of programs and ROM utilization it is necessary to write programs using mixed languages This chapter describes how to program with mixed languages The following subjects are discussed Data format Calling assembly function from a C program Calling a C function from an assembly program 7 1 Data format The data format is Little Endian where the low byte occupies the lower address and the high byte occupies the h
31. 30 December 26 2014 Project Option Debug Option Directories Document Production Micro Controller HI with BootLoader E Project s Build Option Language Tool Assembler Compiler Options Define Symbol Y Generate listing file V Generate Project listing file list Linker Options Libraries Section address V Generate Map File 2 Compile parameter When using Holtek C V3 choose the compiler option the optimizing parameter Os is selected by default in the HT IDE3000 click Project s Build Option in the project settings and a dialog box as follows will appear Compiler Settings Linker Options Compiler Flags Preprocessor Categories lt All Categories H Warn if the compiler detects that code will never be executed Wunreachable code Do not warn if an unexpected _ attribute is used Wno attributes Optimize generated code f Use the syntax of Holtek V2 inline assembly Compile error if a function parameter is declared as implicit int type lt Generate listing file Rev 1 00 31 December 26 2014 Case sensitive for assembly For mixed language projects If a project includes either a c file or an asm file then this option can be enabled Words in C are Case sensitive words in assembly language are Case in
32. 96 operation s 74 E Meel EE 75 10 4 1 Replace the if else statement with the switch statement 000 75 10 4 2 Replace repeated operations with a loop 10 4 3 Using preprocessors to maintain source Code 10 5 Function Call rri io t iere n er ote Ee RE TER eid in 10 5 1 Avoid unnecessary function calls ecciesie eene innen nn 10 5 2 Encapsulate frequently used codes as a function 10 5 3 If the function can only be called in the current file it can be defined as static 77 10 6 Global Variable Assignment sisri sa a tcn tnter wil salsa dak a deae ana a E Ba 78 10 7 Intemupt Service ROUTInes uere nter ttai tette Elena ti keen oe ERR Ir uasa dba 78 Appendix A ASCII CODE TABLE conta 79 Appendix B Operator Priority aaaaaaaaaasv ns nnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn 80 Appendix C Command line mode command parameters and functions 81 Rev 1 00 5 December 26 2014 Reference books 83 HT IDE3000 User s Guide n 83 C standard library user s guide 00 00 nn IRI 83 Holtek C Compiler V3 FAQ 0 000 0 83 GCC MANUAl MESSER TT 83 Rev 1 00 6 December 26 2014 C Compiler V3 user s Guide Introduction Version Rev 1 00 HOLTEK j S This document describes the C programming language basic functions and the C compiler V3 syntax structure and its optimization helping the users devel
33. EES Deor Ana cet re E Xue co geen 48 3 12 Tall MERGING 49 3 13 ROM BP OptimizallOni EE 49 3 14 Dead section Ellmiriatioh iiieiooc A ice aa saka bala cere esso VAR PA RA GL BEAR aaa d EPOR ed 50 Chapter 4 Contrast of Holtek C V1 Holtek C V2 Holtek C V3 ANSI C 51 41 Data Ty Pe sasssa T 51 Eech SE Eege Ee EE geg 51 4 3 Identifier Reserved Words aaaaaaaaaaaaaaiaaaanannnnnnananannnannsaananunannnnnnnsanananuaaanananaaaaaanaaana 52 O EE 53 4 5 Preprocessor Instructions enne nc cnn nn cnn cnn annn cnn nnne nnns 53 4 6 Preprocessor directive Zpragma ince cene cineri NEEN 54 ee 54 4 8 Pre defined Head Files niea id 55 4 9 Main FONS C I 55 4 10 Intemupt FUNCIONS sasssa a ED DRE e 55 4 41 Bulltzin F nctlons E uei eui eh kg and La Lea Diada baki SALA LL AR LO SECURA ce ede A ai 56 2 12 Other ee 56 Chapter 5 Command Line Mode eese 58 5 1 Setting Environment Variable 1 o etuer aj nan GR tenen e esrb reed e eiae eran 58 Rev 1 00 4 December 26 2014 5 2 Using the Command Mode to compile the original file a aaaasaaisaassaaassaasssaasasaasaaaaa 58 5 3 Command line parameter err drede iiei ennt nne nennt ene n na tenens tenes sre 58 Chapter 6 Multiple file programming
34. M DATA 1 2 3 4 5 6 7 8 Note EEPROM DATA can not be written into the function body Rev 1 00 37 December 26 2014 2 2 4 Variable Initialization The C Compiler V3 supports variable initialization by calling a startup program at the beginning The startup program is composed of startup0 and startupl E Project test ong MCU HT66F60 GO Startup Code startupi asm b CJ OBJ Files 1 When establishing a new project startupl will be added to the project automatically If users need to change the variable value to 0 after resetting the followwing option need to be selected This function is implemented in the 7 72 or above version of the HT IDE3000 Project s Build Option Compiler Settings Linker Options Categories lt All Categories v Optimize data memory f not nesting interrupts occur 4 Remove unused function only for C Warn if the address of alias variable is overlap Arrange the ROM space by address order Cancel 2 Startup program code is opened this function is implemented in the version of HT IDE3000 7 72 or above 3 If the the IDE version is updated the startup file under the project folder must be deleted and the IDE3000 will reload it Rev 1 00 38 December 26 2014 Rev 1 00 2 2 5 Inline Assembly code If simplified program code compilation and higher execution
35. Storage Class The storage class has two kinds of types Static Storage and Dynamic Storage including auto static register and extern 1 auto Local variable if not declared as static it defaults to auto writing auto char a or char a has the same effectiveness 2 static Can be divided into global static storage and local static storage If static is added to the global variable then the variable can only be referenced in this document The local static storage is that the variable will retain its value after the whole program ends When the function is called next time the variable will already have a value 3 register The above two kinds of variables are stored in the memory while this variable is stored in a register As there are special case MCUS the details will not be described here 10 December 26 2014 C Compiler V3 user s Guide HOLTEK j S 4 extern This type of variable is defined in another document which indicates that the variable has been defined externally Therefor add an extern when using the variable Details are described in the following sections 5 volatile A type specifier Designed to qualify the variables which are accessed or modified by different operators Variables defined using volatile cannot be omitted because of compiler optimization Variables recommended to be defined with volatile special register variables used in the interrupt functions variables defined
36. ar pal 1 unsigned char pal 1 unsigned char pa2 1 unsigned char pa3 1 unsigned char pa4 1 unsigned char pa5 1 unsigned char pa6 1 unsigned char pa 7 1 pa bits typedef union define union _ pa bits bits using of structure Sfr byte byte pa type DEFINE SFR pa type pa Oxla define register PA define pa __pa byte using of union members define pa5 __pa bits pad using of structure members The first enumeration constant has the last specified value if no explicit value is specified If all the enumeration constants are not specified then the first enumeration constant has the value 0 Subsequent enumeration constants without explicit associations receive an integer value one greater than the value associated with the previous enumeration constant code list 1 15 enum weekday sun 6 mon 0 tue wed thu fri sat const unsigned char dayLine const unsigned char printDay 7 HI Monday I am Tuesday Today is Wednesday Today is Thursday Happy Friday Today is Saturday Today is Sunday l const unsigned char getDay enum weekday today return printDay today 22 December 26 2014 C Compiler V3 user s Guide void main enum weekday today sat dayLine getDay today dayLine Today is Saturday unsigned char ch while dayLine ch dayLine dayLine 1 4 2 Differences between Structure and Union
37. aring in this Data Sheet is believed to be accurate at the time of publication However Holtek assumes no responsibility arising from the use of the specifications described The applications mentioned herein are used solely for the purpose of illustration and Holtek makes no warranty or representation that such applications will be suitable without further modification nor recommends the use of its products for application that may present a risk to human life due to malfunction or otherwise Holtek s products are not authorized for use as critical components in life support devices or systems Holtek reserves the right to alter its products without prior notification For the most up to date information please visit our web site at http www holtek com tw Rev 1 00 84 December 26 2014
38. c o file2 asm The asm file will then be generated by the above instructions 5 3 Command line parameter Parameter Description g Generate a debug message 00 01 02 03 Os D lt macro gt lt val gt Optimization parameter Macro definition I lt path gt Set the header file path msingle ram bank Single RAM mmulti ram bank Multiple RAM default msingle rom bank Single ROM mmulti rom bank Multiple ROM default fno builtin Does not use gcc built in function mno tbhp Without TBHP mtbhp addr Specify the TBHP address addr 09H is default mlong instruction Long instruction MCU 58 December 26 2014 Rev 1 00 There are five kinds of optimization parameters O0 O1 O2 O3 and Os The compiler can only set one of them to compile Optimization level O0 This level will disable all the optimization options The default level is the level before setting O The codes can not be optimized O1 This is the basic optimization level The compiler will try to generate faster and smaller code with limited time overheads These optimizations are very basic and can be completed successfully O2 Advanced optimization for O1 it is the optimized level O2 enables more signs than Ol After setting O2 the compiler will try to increase the code performance while not increase code size but will consume much more compilation time O
39. c void 2 attribute at addr Specify the address of function variable Syntax For function attribute at addr return type function name parameters for variable _ attribute at addr type variable name Noted a addr is the address of function variable can not missing b The variable with _ attribute at addr must be described as static c For the MCU whose ROM is 16 bits and contains the TBHP register the C Compiler V3 20 or above supports specification of the address of constant d The main isr function can be specified with address Example attribute at 0x400 void func void 41 December 26 2014 _ attribute at 0x180 int a attribute at 0x100 const int array 4 1 2 3 4 3 attribute interrupt addr Define an Interrupt Service Runtine Syntax _ attribute interrupt addr void isr name void Noted a addr is the address of function variable can not missing and must be 4 times number Example _ attribute interrupt 0x04 void isr timer void A function can be specified with a variety of attribute a attribute entry at addr b attribute interrupt addr at addr 2 3 C compiler V3 limitation 2 3 1 Function Pointer The C Compiler V3 does not support the function pointer so the following instruction will display an error C Users test Text1 c 14 10 error Holtek gcc does not yet support
40. contains the TBHP register and without long instructions the Compiler supports table look up instructions to access constant variables as shown by the following option which is checked by default If the number of the const variables is large checking it will save code otherwise it will waste Users can choose whether to check it according to the actual program r P D Compiler Settings Linker Options Compiler Flags Preprocessor Categories lt All Categories Do not warn if an unexpected _ attribute is used Wno attributes V Optimize generated code for size Os Use the syntax of Holtek V2 inline assembly Compile error if a function parameter is declared as implicit int type Using table read access the const variable Must be set if the const qualifier variables with spe 4 ul Tm gt lt Generate listing file Rev 1 00 71 December 26 2014 Rev 1 00 Select the following parameter optimize allocation of global variables For the MCU with long instruction architecture it is not necessary to specify a variable address The linker can automatically assign all variable addresses including banks other than bank0 in RAM It can assign according to the using frequency of the variables and give priority to the more frequently used variables Compiler Se
41. d parameter col set the high byte of the second parameter to 0 save the value to the first parameter row call C function DISPLAY get return value from ra rb and store in the local variable code loc the low byte is stored in ra the high byte is stored in rb RET Operation result Variable code loc 0x0050 Note that if the following errors in fig 6 3 1 are shown Error L2001 Unresolved external symbol RA Error L2001 Unresolved external symbol RB Rev 1 00 fig 6 3 1 64 December 26 2014 Then the option Case sensitive for assembly in the compiler flags option needs to be checked Compiler Settings Linker Options Compiler Flags Preprocessor Categories Stop compiling after first error Wfatal errors E String alignment eg DW string1 Two chars will be aligned in one program ROM word if c v Enable all compiler warnings override many other settings Wall Enable extra compiler warnings Wextra Warn if the compiler detects that code will never be executed Wunreachable code Generate listing file Cancel fig 6_3_2 Rev 1 00 65 December 26 2014 HOLTER S C Compiler V3 user s Guide Chapter 8 Common Error Solutions 8 1 Internal Error If error information includes an internal compiler error then it is a compiler internal error Contact Holtek in t
42. ddress The compiler will translate it into an EQU instruction with assembly language as follows bp EQU 4h In the head file for ht48c70 1 h define it define DEFINE SFR sfr type sfr addr static volatile sfr type sfr _ attribute at addr Description Modify with a volatile keyword to prevent optimization So if the program appears include MCU h it also be written as follows DEFINE SFR unsigned char bp 0x04 Array pointer structure variables can also be defined as absolute variables which defined ways are the same with general variable except one additional address for example static volatile unsigned char arr 10 attribute at 0x140 array static unsigned int volatile p attribute at 0x040 pointer typedef struct int a int b my type static volatile my type ab attribute at 0x040 struct Rev 1 00 35 December 26 2014 2 2 3 MCU header file introduction Rev 1 00 The HT IDE3000 has MCU header files these header files contain the definitions of some registers and flags In the project it is only necessary to write include MCU h such as include ht66f60 h which will include the header file automatically The main contents of header files are 1 Absolute addresses and interrupt syntax abbreviations define DEFINE ISR isr name vector V void _ attribute interrupt vector isr name void here isr name is the interrupt service routine name vector is the interr
43. different conditions Using a hard coded manner may consume a large amount of ROM however if using the conditional compilation it can be achieved easily unsigned char LETTER 1 unsigned char c int i unsigned char c int i void main void main unsigned char str 20 C Language unsigned char str 20 C Language while i 19 while i lt 19 c str i c strlil if LETTER 1 if LETTER if c gt a ggc lt z c c 32 if c a amp amp c z c c 32 else else if c A amp amp c 2 if c A amp amp c 2 c ct32 c ct32 endif i c itt str i c it define LETTER 1 Code size 108 Code size 94 10 5 Function Call 10 5 1 Avoid unnecessary function calls If a function is called many times but there is no difference in its return value it is recommended to define a variable to receive the return value and use it instead int fun int i return i int i void main void if fun i 0 i 0 else if fun i 1 i 6 else if fun i 2 i Ae int fun int i return i int i void main void int temp fun i if temp 0 i 0 else if temp 1 1 6 else if temp 2 i de Rev 1 00 76 December 26 2014 10 5 2 Encapsulate frequently used codes as a function If a piece of code is frequently used in the program when possible encapsulate the code as a function to reduce the number of instructions char array
44. e Type Conversion Example int a 20000 int b 20000 void main void Result C 25536 long c atb Description a and b are all int type so should use int type to calculate the result is 40000 but the result is beyond the range of int therefore the result is 25536 Solution long c long atb Result 40000 1 1 3 2 Logical Operation HOLTER j S char a 100 char b 100 void main void Result 200 Description a and b are all smaller than int therefore using int type to calculate the result is 200 int c atb The results of both the Logical Operation and Relational Operation only have two values TRUE or FALSE The numeric value of a relational or logical expression is 1 if the relation is true and 0 otherwise Logical operations are AND OR and NOT and expressions are connected by amp amp or Code List 1 2 char a b c d e f g hj void main a 0x41 b 0x31 e f C Oxaa d 0x55 g 0x5a h Oxad if c a b d a e 0x18 else e 0x81 if g a lt b amp amp h a f 0x18 else f 0x81 logic OR short circuiting logic AND short circuiting Operation Result a 0x41 b 0x31 c both d and h are not given any value 0x01 d 0x55 e 0x18 f 0x81 g 0x00 h 0xa5 NOT operation special application 0xXX when OxXX is not 0 then
45. efficiency is required then assembly language instructions can be added into a C language program The syntax is 1 asm opcode operands Compiler outputs the instruction opcode operands directly e g extern void FUN asm extern FUN PAR1 byte extern function parameter declaration void main asm mov a 1 asm mov FUN PARl a asm call FUN function call 2 asm opcode 0 m varname m varname asm opcode 0 r varname m varname While varname is a variable name m is an output variable r is an output to ACC m is 66499 D an input variable r is an input from ACC r can be omitted e g include ht46ru25 h char i void main char c asm rl 0 m pd m pd sfr asm mov a 0 er c m c Local variable can read a value asm mov 0 a m i Global variable can write a value while 1 3 asm endasm When choose the option Use the syntax of Holtek V2 inline assembly the following syntax can be use to edit a assembly segment e g void main asm MOV A 1 MOV FUN PAR1 A CALL FUN tendasm Note Every statement only writes one instruction it needs to use quotation marks The second embedded assembly format can only occur within the function Its variable size should not exceed 1byte The first embedded assembl
46. efined as volatile Note MP TBLP will be saved when they are used in the interrupt function The following rules should be noted when using the interrupt service routine The Holtek C V3 supports an interrupt internal call function The different interrupts and the main function can not call the same function otherwise it will cause a RAM overlap The linker will detect this phenomenon and issue a warning If the called function is not declared and uses any local variables this warning can be ignored For example 34 December 26 2014 void funl void fun2 fun1 void main funl void attribute interrupt 0x04 isrl void funl void attribute interrupt 0x08 isr2 void fun2 The main and isr1 both call funl This is a common call Although isr2 does not call funl directly but it calls fun2 and fun2 calls funl so it is also a common call The call diagram will be found in the map file nthe same way the different ISRs can not call the same function unless it can be guaranteed not to enter interrupt 2 during the execution of interrupt 1 2 2 2 Absolute variable A variable is designated to the fixed address for example bp in the address 04H can be described as follows static volatile unsigned char bp attribute at 0x04 At compile time the compiler will change the program which contains the absolute variable to the address The Linker will not distribute the other variable to the a
47. efinition data type array name argument number argument number must be a literal constant or a symbolic constant Ex unsigned char led table 5 Array Initialization 1 Define an array Ex unsigned char led table 5 then give values to the elements one by one 2 Initialization when define an array Ex unsigned char led table 5 0 1 2 3 4 3 Initialization without argument number Ex unsigned char led table 0 1 2 3 4 it shows the argument number is 5 4 Partial initialization Ex unsigned char led table 5 2 1 Note 1 The array index is a positive integer starting from zero up to the total number of elements minus one 2 when giving values to the array the array index should not exceed the elements number for example when the elements number is 10 then the maximum index is 9 3 led table 0 2 led table 1 1 the values of the others which are not given any values are 0 An array can be used in the following form array name index Ex led table 2 Because the C language doesn t check the array boundaries it is important to prevent situations of array index overflow 18 December 26 2014 1 3 2 Multidimensional Array An array which has a multiple index is not required to define the highest dimension Ex led table 4 1 2 35 0 005 The second dimension is 3 in the above example Each dimension must be specified when it is used 1 3 3 String and End Flag 99 e S
48. ents can be converted as a Switch statement then tries to replace them with the switch statement to save ROM unsigned char i test void main void if test 0 i 0 se if test 1 se if test 2 se if test 3 se if test 4 se if test 5 se if test 6 i se if test 7 i se if test 8 i 00000000 unsigned char i test void main void switch test case i 0 break case 1 break case 3 break case 5 break case 2 break case 9 break case 7 break case 4 break case 8 break CO O On FWNHE O H H H H H peo peo to to Code size 64 Code size 62 10 4 2 Replace repeated operations with a loop When there are repeated and regular operations in the program then try to replace them with a loop unsigned char show data 6 unsigned long hex void main show data 5 hex 10 show data 4 hex 10 10 show data 3 hex 100 10 show data 2 hex 1000 10 show data 1 hex 10000 10 show data 0 hex 100000 10 unsigned char show data 6 unsigned long hex void main unsigned long temp hex unsigned char i for 1 6 1 gt 0 177 show data i temp 10 temp 10 Code size 378 Code size 156 Rev 1 00 December 26 2014 HOLTER S 10 4 3 Using preprocessors to maintain source code C Compiler V3 user s Guide Sometimes for maintenance convenience of users may desire that the same source code can meet the requirements of
49. er of 15 and 8 which is equated to 15 amp 7 Here 7 is shown that 8 1 7 the result is 8 Other Multiplication Simplification such as 0x08 7 0x08 8 1 0x08 lt lt 3 0x08 8 9 Rotate rotate a 16 bit value left for n bits OxXX gt gt 16 n 0xXX lt lt n Rotate rotate a 16 bit value right for n bits 0xXX lt lt 16 n OxXXX gt gt n 1 2 Functions The function is the same as a subprogram where each function can implement one special function During the application program development frequently used function modules can be written as a single function so as to reduce the repetitive work In fact a function is an address calling the program to jump to this address to excute the instructions 1 2 1 Function declaration and definition Rev 1 00 It is not necessary to define the function before being declared The declared function must be an existent function If using a library function then directly add the header file If it is a user defined function then the function must be declared behind the document Functions cannot be nested Function definitions include the return value type function name parameter list and the function body form return type function name argl arg2 statements function body 14 December 26 2014 Rev 1 00 Example 2 Find the larger one of two numbers code list 1 3 int max int int function declaration int
50. ernal functions 2 Declare the call function with proc endp 3 If the function includes parameters declare all the corresponding variables to be external variables The parameter assembly names may refer to the assembly files which the C function compiles Note that each compile result may be different so try not to take parameters 4 After calling the C function read the return value if the return value is 1 byte then it will be placed into ACC If the return value is 2 bytes the low byte will be placed into ra and the high byte into rb If the return value is 4 bytes the return value will be placed into ra rb rc and rd from low byte to high byte Note that ra rd are already defined they just need to be declared before being used Code list 6 3 FUN C int DISPLAY char row int col define function the function name must be uppercase d int retval retval int row lt lt 1 col return retval CODE ASM 7 code asm call function DISPLAY extern DISPLAY near H extern DISPLAY 2 byte H extern ra byte H extern rb byte CODE section code code proc local code loc db 2 dup H OV A 10h OV DISPLAY 2 A H CLR DISPLAY 2 1 H OV A 20h OV DISPLAY 2 2 A H CALL DISPLAY H OV A ra OV code loc A OV A rb OV code loc 1 A H code endp declare function name as external name declare parameter variable name declare return value define local variable save the value to the secon
51. for some certain function codes such as a delay function With regard to other variables it is not recommended that they are defined using volatile as this will reduce the compiler optimization code list 1 1 Filel c int cpv File2 c extern Cpv int c int statictest cpv 5 static int k 26 auto int p 0 k ptt cpvtt return k p cpv void main c statictest C 7 statictest The result is 34 35 Rev 1 00 quotes the variable cpv in Filel c static variable auto may be omitted IP c c 34 35 11 December 26 2014 HOLTER S 1 1 3 C Language Operation Introduction C language has many kinds of operations including arithmetic operation logical operation bitwise operation assignment operation conditional operation comma operation etc The operation priority is listed in Appendix B C Compiler V3 user s Guide 1 1 3 1 Type conversion Type conversion rules Mix Data type Arithmetic Operation if the conversion type is smaller than the integer the result is integer convert small type to large type The conversion process is shown in fig 2 1 1 assignment between different data types the conversion type is the type to the left assignment statement Function Arguments Passing Return values the conversion type is the type of the parameter returned value fig 2 1 1 Rev 1 00 12 December 26 2014 C Compiler V3 user s Guid
52. function pointer void FileFunc void EditFunc void foo typedef void funcp void funcp pfun FileFunc pfun pfun EditFunc pfun 2 3 2 Recursive Function Holtek MCUS do not support recursive calls but the compiler can optimize a special recursive call called Tail Recursive Call and change it to a non recursive function Details are described in chapter 3 10 2 3 3 7 bit MP Memory Pointer The MPs in some of the older Holtek MCU structures only have 7 bits In order to achieve higher optimization efficiency the C Compiler V3 does not support this kind of MCU Refer to the file lt Holtek C Compiler V3 FAQ gt for the MCU types Rev 1 00 42 December 26 2014 C Compiler V3 user s Guide 2 4 Compiler managed resources Rev 1 00 HOLTEK j S Some special function registers in the Holtek MCUs are used by the C Compiler V3 so users should be careful when using them These registers and the main functions to the complier are listed in the following table When entering into interrupt service routines the used registers will be saved automatically special registers used by complier Main functions MP IR Access the value of RAM space used with RAM BP BP RAM BP is used to access the value of RAM space ROM BP is used to access ROM space STATUS For expression calculation TBLP For table read or storing RAM BP TBHP For table read TBLH For table read acc pog
53. g value _tm2ah Oxf4 9 2 7 segment LED display number using table To display numbers using a 7 segment LED from the assembly table using mixed language code list 7 2 Table ASM INCLUDE HT66F50 INC public code code SECTION CODE code proc Rev 1 00 68 December 26 2014 TAB 7 SEG DC OF9COH DC OBOA4H DC 09299H DC 0F882H DC 09580H DC 08388H DC 0A1A7H DC 08E86H code endp END Main c include HT66F50 h void delay unsigned char times volatile unsigned char tl t2 t3 tl times while t1 2 35 while t2 t3 110 while t3 asm extern CODE near void maint unsigned char k acerl 0x00 _cp0c 0x08 _pac 0x00 pa Oxff asm mov a low CODE asm mov 0 a m tblp asm mov a asm mov while 1 high CODE a m tbhp os for k 0 k lt 8 k asm tabrdc 0 m pa asm inc 0 m tblp _delay 50 asm mov a 0 m tblh asm mov 0 a m pa _delay 50 asm mov a Offh asm mov 0 a n pa all SEG off _delay 50 Rev 1 00 69 December 26 2014 HOLTER S Chapter 10 Program Optimization 10 1 Optimization Options C Compiler V3 user s Guide Select Optimize generated code i e Os as shown below For more detailed optimization contents description refer to chapter 3 M Project s Build Option m
54. g values to the address where the uninitialized pointer are pointed to unpredictable errors will be created There are two pointer operators amp obtain the memory address and obtain the content 1 Operation of the pointer pointed to variables Example 6 Is the value changeable Code List 1 8 char a void change char b h pb void main a a change amp a operation result a b because the passed parameter is the address of a changing the value of the address is equal to changing the argument 19 December 26 2014 2 Operation of the pointer pointed to pointers Example 7 Is the value changeable Code List 1 9 char a void change char b b char 0x81 modify the pointer itself void main a char 0x80 change a Operation Result a 0x80 Since the parameter passing is unidirectional if it is desired to change the value a the code is as follows Code List 1 10 char a void change char b b char 0x81 modify pointer content void maint a char 0x80 change ta Operation Result a 0x81 3 Operation of an array pointer and pointer array An array pointer is the pointer which is pointed to in an array defined as char b 5 The pointer array is the array which stores the data type of pointer defined as char a 5 What is the difference Here a is the first address of the array 5 pointer values are stored in
55. h when compiling Pay attention to avoid duplication of header file including 3 Conditional compiler Compilation choose one of the source codes to compile as there is no need to compile all the codes This is used for debugging and code transplants between the different machines There are 3 types the else directive is alternative 1 ifdef symbol source Code else source code2 endif 2 ifndef symbol source codel else source code2 endif 3 if symbol source Code else source code2 endif 23 December 26 2014 4 Differences between macro definition and inline function 1 Macro definition only does simple replacement without any operations 2 Macro is defined when precompiling while the inline function is used when function calls occur 3 Macro definition parameters can not be specified with any data types while the inline function must specify the data types 4 The compiler does not check the macro definition contents if using define error 8 there is no error to be found while the inline function is different Example 9 preprocessor comprehensive example code list 1 16 FUNCTION H ifndef FUNCTION H if removing ifndef then the redefinition error occurs define _FUNCTION H typedef unsigned char u8 typedef unsigned int ul6 typedef unsigned long u32 define BOOL u8 define TRUE 1 define FALSE 0 define LeftShift val times val lt lt times define Max numl num2
56. his case For example tingXROM Bank Setting c In function main tingXROM Bank Setting c 72 22 internal compiler error in emit library call value 1 at calls c 3929 8 2 RAM bank overflow For the short instruction architecture MCU the C Compiler will assign the variables to RAM bank0 long instruction MCU can assign the variables to any bank automatically by default When bank0 is full RAM bank 0 overflows and the following massage will be shown Linking Error L1838 RAM bank 8 overflow memory allocation fails for section Total 1 error s Total 8 Warning s ROM Bank Setting Total 1 error s 8 varning s fund When the above message is shown you should take the following measures Check the data type is correct or not especially the programs from V1 C Compiler fitis multi RAM bank MCU you can put the global variables to other banks manually please refer to the section 2 2 2 8 3 ROM RAM space overflow When ROM or RAM space is not enough the following message will be shown Error L1838 ROM bank si overflow memory allocation fails for sec Total 1 error s Total 43 Warning s eUriterProLCD 888813 Total 1 error s 45 warning s When the above message is shown the following measures should be taken Check the optimize parameter Os is open or not refer to the section2 1 4 Check the map file to understand the RAM ROM assignment and delete unnecessary programs 8 4 Variable Overlap Wa
57. igher address For example static long ldata attribute at 0x180 ldata OxAABBCCDD In the memory the data format is as follow Address 0x180 0x181 0x182 0x183 Content OxDD OxCC OxBB OxAA 7 2 Variable and function naming rules When Holtek C V3 compiler is compiling global variable and function it will add a underscore character in front of the old name For example The global variable count is compiled into count The function GetTotalSize is compiled into GetTotalSize Local variables static variables and function parameters are named quite irregularly so please refer to the debug information in the assembly files compiled But it is noted that the compiled name may be different each time After the assembler compiled the assembly program it will change the names of variable and function for the upper case letters For example The variable count is compiled into COUNT The function GetTotalSize is compiled into GETTOTALSIZE 7 3 Calling an assembly function from the C program Assembly Language Program function definition rules 1 Add an underscore character prior to the function name and declare it as a public variable 2 If the function includes parameters declare the function parameters as public variables 3 Define the variables as local if there are local variables 4 Define functions with proc endp Calling Rules for C 1 Uses capital letters to define and declare the called fu
58. ile Iz Generate a debug message Ih Display help Source Asm file that will be compiled object Specify the name of the generated obj files listing Specify the name of the generated list files Rev 1 00 December 26 2014 HOLTER S Rev 1 00 3 Linker parameter C Compiler V3 user s Guide Command HIDE xxx MCU xxx NOLOGO novectornest OptimizeParam 2 OptimizeLInst 1 Startup0 EEPROM xx TBHP 1 ERRORLOG xxx option objectfile taskfile mapfile dbgfile libraryfiles HIDE xxx MCU xxx NOLOGO novectornest OptimizeParam 2 OptimizeLInst 0 Startup0 EEPROM xx TBHP 0 ERRORLOG xxx option batchfile Note These parameters must be set in accordance with the above order otherwise an error message will be generated by the linker The parameters are case sensitive The environment variable LIB is the searching path of the lib file Parameters Description HIDE IDE control code 8 hexadecimal numbers MCU MCU project name NOLOGO Hidden LOGO Inovectornest This parameter requests no ISR nesting which can save RAM space for C Compiler V3 only OptimizeParam x bitO bit3 means BP optimization parameter bit4 means Dead Section optimization for C Compiler V3 only OptimizeLInst x Expresses the long instruction optimization O means no optimization 1 means optimization Without opt
59. imization by default for C Compiler V3 only Initialize the global variables without initial values to 0 SE for C Compiler V3 only EEPROM xx Specify EEPROM DATA SIZE for C Compiler V3 only ERRORLOG Save the error log path MAP Generate MAP file ADDR section_name addr Lsection name addr Specify that some section assignment addresses are started from the specified addresses Note addr is hexadecimal IHELP Display the command line format help information Note To set the environment variable CFG before calling the assembler and linker CFG set HTCFG IDE path MCU 82 December 26 2014 Reference books HT IDE3000 User s Guide The User s Guide introduces how to use the tools including the HT IDE assembler and linker It can be obtained from the HT IDE3000 installment file DOC C standard library user s guide This user s guide introduces the standard function library and their use supported by Holtek C This can be obtained from the HT IDE3000 installment file DOC Holtek C Compiler V3 FAQ C Compiler V3 FAQ common problems These FAQs are continuously updated and can be downloaded from http www holtek com chinese tech tool MCU Tools Users Guide htm gcc manual GCC manual can be downloaded from http gcc gnu org onlinedocs gcc 4 8 1 gcc pdf Rev 1 00 83 December 26 2014 Copyright 2014 by HOLTER SEMICONDUCTOR INC The information appe
60. ion can not be a recursive function 3 Function statements in the function body cannot be more than 30 lines 4 The subfunction and the generating function must be in the same C file Example loat square float a return a a loat parabola float x return square x 1 0f inline function float parabola float x return x x 1 0 Disadvantages of inline functions The program size will increase along with the expansion of the function To avoid using the inline function subfunction and generating function can use the different files to program Advantages of the inline function 1 After the function was expanded it may have additional optimization 2 Reduced stack usage 3 After the subfunction was expanded if not called by other functions then the code will be as the dead section and deleted by the Linker refer to 2 3 14 The inline function will create a situation where the expanded subfunction can not set breakpoints 46 December 26 2014 3 9 Strength Reduction Rev 1 00 Strength reduction means that some simple loops can be changed to some general statements For example for i 0 i 10 itt Isi k jti can be changed to for i 0 i 10 i ji k jti even j i 10 k 20 Strength reduction will create a situation where simplified code will not be able to set breakpoints Note The compiler only cares about the operation results therefore the special purpose codes ex im
61. lic symbol ar in the file C Documents and Settings ydwang My Documents HTK_Project t T1 0BJ Solution Do not define the variables in the header file If t c and t1 c both need to use a then define a in a file and declare a with extern int in the header file t C t h tl c include t h extern int a include t h int a void fun void main a 3 a 2 67 December 26 2014 Chapter 9 Programming Examples This chapter shows how to use the C compiler V3 to compile MCU programs The main contents are as follows Using the interrupt function Using a mixed language program 9 1 LED flashing using the interrupt This example uses the timer to control LED flashing The time interval is 1s which means the LED light is on for 1s and off for 1s Code list 7 1 include HT66F50 h void main _acerl 0x00 cp0c 0x08 pac 0x00 set PAC as output _pa Oxff All SEG off _m 0e 0x01 enable Multi function 0 interrupt _t2ae 0x01 enable T2A interrupt _tm2c0 0x30 set clk sys 64 tm2cl Oxcl set Compared with CCRA _t2af 0x00 clear T2A interrupt flag _mf0f 0x00 clear Multi function 0 flag _emi 1 enable interrupt _tm2al 0x03 Matching value _tm2ah 0x00 _t2on 1 start counting while 1 DEFINE ISR ISR ADC 0x14 definition ISR _t2af 0x00 clear T2A interrupt flag _pa pa _tm2al 0x24 Matchin
62. long int 0 _clrwdt2 0 _Irlc long 0 _halt 0 _delay unsigned long 1 nop 0 1 _rr int char 0 1 _rre int 0 1 _Irr long int 0 Constant array 1 _Irrc long 0 Integer and floating conversion 1 2 refer to 2 3 3 Rev 1 00 57 December 26 2014 HOLTER S Chapter 5 Command Line Mode C Compiler V3 user s Guide This chapter describes the C compiler V3 command line mode and guides programmers on how to use the command mode to compile an original file The main contents are as follows entering into the command line environment using the command mode to generate an object file command line parameters 5 1 Setting Environment Variable To setup the environment variable before using the command line environment Using the set command in the command line to add a bin file in the HT IDE3000 installation path For example set PATH PATH XXX bin Here XXX bin is the bin file in the HT IDE3000 installation path The HT IDE3000 tools of the bin file can be used in the present CMD window 5 2 Using the Command Mode to compile the original file After setting the environment variables then being to write the code Taking example 5 as an example compile filel c and file2 c in example 5 to the corresponding assembly files command hgcc32 options cfile o asmfile compile filel c hgcc32 g Os filel c o filel asm compile file2 c hgcc32 g Os filel
63. long long N N 32 64 float N 32 24 32 double N 32 32 64 long double N N N 128 Holtek C V2 float double all use IEEE754 32 bit format The floating type is 24 bit supported by C compiler V3 and only 4 5 digit precision is supported by V3 20 or above sign exponent e mantissa m 23 22 15 14 8 7 0 Double and long double data types have IEEE 754 32 bit format and 6 7 digit precision supported by V3 20 or above sign exponent e mantissa m 31 30 23 22 16 15 8 7 0 The bit variable for V1 V2 compilers cannot be used for pointer data type or defined as const only one bit is occupied Holtek C V3 doesn t support bit data type and it can be replaced by structure domain 4 2 Array Dimension C compiler V1 C compiler V2 C COMPILER V3 ANSI C the the Longest Array the Longest Array the Longest Array Longest Array One dimension array 256 O No limits Two dimension array N O No limits e dimension N N No limits Pointer array N O No limits Function array N Functional limitation N No limits String array Not supported Not supported a No limits Note If it is a const array it may apear bug when the total length is over 1 page so is no recommended to use If it is a general array the length should not exceed one rambank 2 If it is a const array the length
64. means that the function can be called in another function The function call can be nested but the function definition can not be nested The recursive call is a special nest call It means that the function can be called directly or indirectly in this function itself 1 2 3 3 External Function There are two methods to use external functions one is using the header files and include the other is using the keyword extern 1 Header file include method Example 4 Call the external addition and subtraction function Code List 1 5 Filel h tifndef Filel H define Filel H Rev 1 00 16 December 26 2014 typedef unsigned char u8 u8 add u8 a u8 b u8 sub u8 a u8 b endif Filel c include FILE1 H u8 add u8 a u8 b return a b u8 sub u8 a u8 b return a b File2 c include FILE1 H u8 c d void main u8 a 10 u8 b 10 c add a b d sub c b Operation Result a 10 b 10 c 20 d 10 2 extern method Example 5 call the external multiplication and division function Code List 1 6 Filel c typedef unsigned char u8 u8 mul u8 a u8 b return a b u8 div u8 a u8 b return a b File2 c typedef unsigned char u8 extern u8 mul u8 a u8 b extern u8 div u8 a u8 b u8 c d void main u8 a 10 b 10 c mul a b d div a b Operation Result a 10 b 10 c 100 d 1 Rev 1 00 17 December 26 2014 1
65. nction name 2 If the function includes parameters declare the function parameters externally 3 Call the function Rev 1 00 62 December 26 2014 C Compiler V3 user s Guide HOLTEK A 7 Example 13 Assembly language subtraction function Code list 6 2 CODE ASM public opera public opera varl public opera var2 Opera section page code Opera proc local opera varl db local opera var2 db local result local db mov a Opera varl sub a opera var mov result local a ret opera MAIN C endp extern unsigned char OPERA asm extern OPERA VARl byte asm extern OPERA VAR2 byte void main volatile asm asm asm asm H mov mov H H mov mov H unsigned char result a 20h OPERA VARI a a 10h OPERA VAR2 a result OPERA whi e 1 asm nop Operation result result 0x10 Rev 1 00 define the function and parameters as public define function with proc endp define parameters define local variables define the function namewith uppercase function call 63 December 26 2014 HOLTER S C Compiler V3 user s Guide 7 4 Calling a C function from the assembly program Calling Rule for C Uses capital letters to define and declare the called function name Mixed lauguage program function definition rules 1 Declare the function name starting with underscored letters to be ext
66. nd other operations code list 1 13 unsigned int a 5 1 2 3 4 5 assume a 0x84 unsigned int p a p 0x84 void main p ptl p 0x86 unsigned int occupies 2 bytes ttp 10 p 0x88 operation result p 0x88 a 2 10 1 3 7 Differences between array name and pointer The array name is the first address of the array in memory it is similar to the pointer but there are also a few differences between them 1 The array name is a constant so is not allowed to be modified and is equal to a pointer constant 2 The operation result is different when using sizeof to operate the result of the array name shows the occupied space while the result of the pointer is fixed 2 3 The array name cannot be incremented and decremented Rev 1 00 21 December 26 2014 1 4 Structure Union and Enumeration A structure is a collection of data unlike an array the elements of the array must be same types while the structure can be different data types A union is similar to the structure The enumeration limits the value of variables in a scope of a specified range 1 4 1 Using Structure Union and Enumeration Rev 1 00 Example 8 The definition of register PA and bit PAS using Structure and Union code list 1 14 define DEFINE SFR sfr type sfr addr static volatile sfr type sfr attribute at addr typedef unsigned char sfr byte typedef struct define structure unsigned ch
67. not dead values because these values can not be sure of being used Refer to the example in the copy propagation value propagation section 3 3 3 Dead code Elimination will affect any breakpoint settings and variable monitoring in some lines of the C source codes 3 6 Constant Folding Constant Folding means that the compiler will calculate the expression internal values directly but will not generate the assembly codes Example double a b a b 2 0 3 0 compiler will output the following assembly statements a b 0 666667 Constant Folding will not affect debugging 3 7 Constant Propagation The variables of some expressions are not constants but the compiler can operate on their values through simple computation For example float a 5 0f b b a 1 0f Here the compiler will output the following assembly statements float a 5 0f b b 6 0 Constant Propagation will not affect debugging Rev 1 00 45 December 26 2014 3 8 Inline Procedure Rev 1 00 When a subfunction is a simple function as in the following conditions the subfunction code will be directly written to the function which call the subfunction Thus it can reduce the use of the stack The following rules should be obeyed when using an inline function 1 The function can not contain complex statements The complex statements include switch statements for statements while and do while statements goto statements 2 The funct
68. o floating constants the result can be first calculated define HALF float 0 5 define HALF float 0 5 define QUARTER float 0 25 define QUARTER float 0 25 float 1 r float l r void main void maint r 1 HALF HALF r 1 QUARTER Code size 171 Code size 152 Rev 1 00 73 December 26 2014 EE Ff c compller va users Cuide 10 2 4 Const Array A const array defined as a global variable can save more RAM space than one which is defined as a local variable unsigned char sum const unsigned char tx 7 unsigned char dx 7 1 3 5 15 5 3 1 void main unsigned char sum unsigned char dx 7 const unsigned char tx 7 void main 1 3 5 15 5 3 Ek unsigned char i unsigned char i for i 0 1 lt 7 i for i 0 i lt T itt sum dx i tx i sum dx i tx i 10 3 Arithmetic Operation 10 3 1 Bitwise AND amp replaces Remainder operation Generally the amp operation is simpler than the operation so in some special conditions perhaps users can use the amp operation instead of the operation to reduce the number of used instructions char i j char i j void main void void main void j ist Rev 1 00 74 December 26 2014 C Compiler V3 user s Guide 10 4 Program structure HOLTEK j 7 10 4 1 Replace the if else statement with the switch statement When there are multi level nested if else statements in the program and the multiple judgm
69. ompiler V3 10 mbler Rev 1 00 29 December 26 2014 2 1 3 After opening the project how to use the Holtek C V3 compiler After opening the project click Project Setting command in Option menu and click Holtek C Compiler V3 10 Assembler in the Language Tool to set Holtek C V3 compiler Project setting Project Option Debug Option Directories Document Production Micro Controller HTS6R688 with BootLoader Language Tool Project s Build Option Holtek C Compiler Assembler Holtek der V2 Assembler Y Generate listing file v Generate Project listing file list Linker Options Libraries Section address Y Generate Map File Cancel 2 1 4 Project Compiler Option settings Rev 1 00 1 Define Symbol The setting is shown as the following red box The HT IDE3000 will pass the parameter to the compiler DGCC COMPILER DCOUNT 5 Be equivalent to macro definition define GCC COMPILER define COUNT 5 Its effective scope is the whole project the multiple macro definitions are separated by The example of using D command line option is conditional compilation Ex if GCC COMPILER typedef unsigned int uintl6 else typedef unsigned int uint8 endif if COUNT 5 x25 elif COUNT 2 x 26 else x 7 endif Note When using the C Compiler V3 HT IDE3000 7 72 or above version the macro definition is V3 by default
70. op application programs quickly by using the C compiler V3 The C compiler V3 is based on the GCC 4 6 2 version or above Refer to the GCC user s guide except for the machine related chapters It is assumed that the reader already has the following basic qualities Knows how to write C programs Has already read and understood the target MCU datasheet Release date Compiler version IDE version 2012 12 1 V3 10 HT IDE30007 7 2013 10 V3 20 HT IDE30007 8 2014 3 V3 30 HT IDE30007 82 2014 9 V3 31 HT IDE3000 7 85 December 26 2014 Chapter 1 C language This chapter introduces the C language syntax and structure from the simplest to the more complex providing a basic knowledge for learning the C compiler V3 Due to the architecture of the Holtek microcontroller the contents described in this chapter are all based on the C language ANSI C99 protocol compatible with the C compiler V3 syntax This chapter covers the following topics Data types operators and expressions Functions Arrays and Pointers Structures unions and enumeration Preprocessor directives Flow control Scope 1 1 Data types operators and expressions 1 1 1 C Data types Due to the necessity of using ROM or RAM before using the variables the data type must be defined The data types consist of basic data types Structure data types Pointer and void The basic data types contain integer
71. overlapping or not If the address is overlapping then a warning will be generated Arrange the ROM space by address order linker will arrange the function in a small space priority if not select this option 33 December 26 2014 Project s Build Opti Compiler Settings Linker Options Categories lt All Categories Optimize data memory f not nesting interrupts occur V Remove unused function only for C Uninitialized global static variables are automatically set to 0 Warn if the address of alias variable is overlap Arrange the ROM space by address order 2 2 C compiler V3 Extended syntax and function 2 2 1 Interrupt Service Routines Rev 1 00 If the MCU peripheral devices contain interrupt functions the programs also need the interrupt functions to finish the task then the interrupt service routine ISR should be defined in the following Way void attribute interrupt 0x0c ISR tmr0 void ticktt The interrupt service routine must obey the following rules gt The type of the return value must be void No parameters included Must use attribute interrupt 0x0c to setup the interrupt vector The registers ACC BP STATUS MP TBLP will be saved automatically when the system is outside the interrupt entrance The variables that can be accessed by both the interrupt service routine and other functions are d
72. plement delay function by loops will have no meaning In such cases it is recommended to use inline assembly instead of loops or define the variables as volatile For example Example 1 for i 0 i 10 i asm nop Example 2 volatile unsigned char count for i 0 i lt 10 i counttt 47 December 26 2014 3 10 Tail Recursive Call Holtek MCU does not support recursive calls but there is a special recursive call that can be implemented by the compiler Here the compiler will change a recursive call to a non recursive call This s called the Tail Recursive Call for example int primes int a int b if a 0 return b 1 if b 0 return a 1 return primes b a b For the above code the last lines of code which are calling the function itself is called a Tail Recursive Call Here the compiler will change the recursive call to a loop int primes int a int b Ll if a 0 return b 1 if b 0 return a 1 a b b a b goto Ll A Tail Recursive Call will not affect debugging 3 11 Subexpression Elimination Rev 1 00 If there are the same subexpressions in the expressions then the compiler will calculate these subexpressions first and store them into a temporary variable The variable can be operated directly This is called subexpression elimination For example the following expression b c is a public subexpression and can be stored in the variable tmp first
73. por CFE C Compiler V3 user s Guide Revision V1 00 Date December 26 2014 wwii hoitekK com Notice This document may be not be the latest version As Holtek s tools and documents will continue to be updated some dialog boxes and tool descriptions in actual use may differ from the contents of this document For the most up to date information visit the Holtek website at http www holtek com chinese tech tool MCU Tools Users Guide htm Rev 1 00 2 December 26 2014 Table of Contents INTOUCHON saka a in aaa fa cidcid 7 VEFSION ERN 7 Chapter 1 C language 8 1 1 Data types operators and expressions 8 L NT Data EE 8 1 1 2 Constant and VA eio re ek tente shite aut eerta eir Ene Rte Aa annar ecu 9 1 1 3 C Language Operation Introduction eem 12 1 2 inl ce 14 1 2 1 Function declaration and d efinItion 2 1220 2120 bla snsn i asla sgaii einir iiad mem 14 1 2 3 Function Call sci ni ii aa EENS Var cand couse v t RD BA i s mr a l a NEE 16 1 24 Main FUNGUO EE 18 1225 Standard Le EE 18 NS Eeer 18 1 3 1 Array Definition Initialization and Usage 18 1 3 2 Multidimensional Array ran nn aaa a 19 1 3 3 string and End FAG EE 19 1 34 PONG EE 19 1 3 5 Pointer Data Type tenen secant tec Pe tiet eee DEN BE a a eee aie 19 13 6 Pointer Operation ai a 19 1 3 7 Differences between array name and pointer 21 1 4 Structure Union and Enumeration
74. ptions Compiler Flags Preprocessor Categories Al Categories v EIDo not warn if an unexpected _ attribute is used Wno attributes Optimize generated code for size Os 1 Use the syntax of Holtek V2 inline assembly Compile error if a function parameter is declared as implicit int type E v Using table read access the const variable Must be set if the const qualifier variables wr d v Lal Tm Generate listing file Cancel The statements are as follows const type _ attribute at addr var 1 2 3 4 5 for example const char attribute at 0x123 ci 5 1 2 3 4 5 then the results in ROM are as follows address 0x123 0x124 0x125 content 0x0201 0x0403 0x0500 1 1 2 2 Variable Definition During program execution the variable values will change Every variable must have a name defined before it is used This name is case sensitive The variable must be declared in advance When making variable declarations the data type must be designated so as to inform the compiler of the required memory size such as int a Identifiers are used to identify variables constants functions types and a number of characters Identifiers must consist of letters digits and underscores and begin with letters and underscores 1 1 2 3 Variable Storage Class Each variable has two properties in C language they are Data Type and
75. rning Rev 1 00 When absolute address variable positions overlap the following messages will be generated Linking Varning L3818 Absolute Adress 88H Length 8 is overlay with Adress 86H length 8 Varning L3818 Absolute fdress 88H length 6 is overlay with Adress 88H length 6 Warning L3616 Absolute Adress 8eH length 13 is overlay with Adress 8eH length 13 There are two conditions which may cause the above warnings The same absolute variables are defined many times in different files such as the variable var is defined in a h static volatile unsigned char var attribute at 0x180 When tl c and t2 c both include a h then the warning message will be popped up in this case this warning message can be ignored or set the option to avoid the warning message refer to section 2 1 5 The defined addresses of different variables overlap shown as the follows the addresses of b and aoverlap b needs to be defined in the address 0x0142 DEFINE SFR unsigned int a 0x0140 DEFINE SFR unsigned char b 0x0141 error 66 December 26 2014 8 5 Variable Redefinition Rev 1 00 If a variable not absolute address variable is defined in the header file while the header file is quoted by multiple c files then variable redefinition will occur Linking Error L1631 Public symbols are duplicated Public symbol ar in the file C Documents and Settings ydwang My Documents HTK_Project t T OBJ Pub
76. sensitive by default String alignment eg DW string1 Two chars will be aligned in one program ROM word For an asm file when the selected MCU is 16 bits such as HT66F50 this option can be enabled then every two characters in the string will take one word If disabled then one character takes one word by default If the selected MCU is 14 or 15 bits such as the HT46R4AB then this option can not be enabled Enable extra compiler warnings such as lack of function return value unsigned value comparing with zero Optimize generated code for size Os Optimization option Use the syntax of Holtek V2 inline assembly You can use the asm endasm completed inline assembler syntax function when select this option Using table read access the const variable MCU no long instructions with TBHP register and the PROM width is 16 bits has this option The size of table will be halved when this option is selected The option must be set if the const qualifier variables with specified address exist 2 1 5 Linker options Rev 1 00 2 1 5 1 Include The Library 1 Add the library paths to the directories y Project setting Project Option Debug Option Directories Document Production i Output files path Cs Users ydwang Desktop 3 holtektest2 Show directories for Library paths Y Directories D Program D Holteklib Cancel 32 December 26 2014
77. t 8 amp bitwise AND bit operation left to right 9 A bitwise XOR bit operation left to right 10 bitwise OR bit operation left to right 11 amp amp logical AND bit operation left to right 12 ll logical OR bit operation left to right 13 Ke conditional expression ternary right to left H assignment binary right to left 15 comma sequential left to right Rev 1 00 80 December 26 2014 C Compiler V3 user s Guide HOLTEK j 7 Appendix C Command line mode command parameters and functions 1 Compiler parameter Command hgcc32 options cfile o asmfile Parameter Description g Generate an debug message 00 01 02 03 Os Optimization parameter D lt macro gt lt val gt Macro definition I path Set the header file path msingle ram bank Single RAM mmulti ram bank Multiple RAM default msingle rom bank Single ROM mmulti rom bank Multiple ROM default fno builtin Without using gcc build in function mno tbhp Without TBHP mtbhp addr Specify TBHP address addr 1fH is default mlong instruction Long instruction MCU 2 Assembler parameter Command hasmgcc32 options source object listing Parameter Description chip chip name Specify MCU type case Case sensitive d lt macro gt Macro definition i lt include path gt Set the search path of the header f
78. the operation result is 1 Rev 1 00 13 December 26 2014 1 1 3 3 Bitwise operation There are two very attractive points in the C lauguage one is the pointer and the other is the bitwise operation There are six operators for manipulating bit by bit operations they are bitwise AND amp bitwise OR bitwise XOR bit complement left shift lt lt and right shift gt gt The operation time will be reduced significantly by using the bitwise operation skillfully The following are common applications and operations 1 2 3 Change lower case to upper case clear bit a amp OxDF the result is A Change upper case to lower case set bit A 0x20 the result is a Take one s complement in other words Exclusive OR to the bit and 1 the first bit complement OxFF 0x01 the result is OXFE Partial multiplication simplification multiply with the n th power of 2 which is equated to a variable left shift for n bits such as 0x02 multiplies 4 0x02 lt lt 2 here 2 is shown that 4 the twice power of 2 the result is 8 Partial division simplification divide with the n th power of 2 which is equated to moving the variable with a right shift for n bits such as 0x08 divided by 4 0x08 2 here 2 is shown that 4 twice the power of 2 the result is 2 Partial remainder simplification remainder with the n th power of 2 which is equated to 2n AND 2n 1 such as the remaind
79. timize generated code for size Os Use the syntax of Holtek V2 inline assembly Compile error if a function parameter is declared as implicit int type Using table read access the const variable Must be set if the const qualifier variables wi 3 e m I gt Generate listing file Rev 1 00 40 December 26 2014 Rev 1 00 2 2 8 Variable assignment Holtek MCUs have two memory areas ROM and RAM The variable assignment rules are as follows 1 The general variables will take up RAM space the initial values are stored in the ROM space 2 Const variables take up ROM space but if using a volatile qualifier no specify address then this will take up RAM space 3 If the static variable value is not changed in the program and passes the optimized parameter then the compiler will regard this as a const and take up ROM space 2 2 9 attribute Syntax This section describes the syntax with which attribute may be used and the constructs to which attribute specifiers bind for the C language 1 attribute entry support above IDE V7 82 Specify a entry function Syntax _ attribute entry void entry function name void Noted a entry has no parameters b return type should be void c parameters type should be void d The main isr function can be set to entry but is not valid Example _ attribute entry void fun
80. tring constants are saved in ROM ended with 0 For example String char c chip chip takes 5 characters If the last element of a character array is VO then it also can be used as string An array name is the array starting address in the memory such as led table 5 Then led table is the address of led table 0 1 3 4 Pointer Variables defined in programs will be assigned to the memory unit while the memory unit has a number which is called address the pointer content stores the address of the variables 1 3 5 Pointer Data Type The pointer points to the address of the different types of variables RAM address such as int char and so on Therefore the data type of variables which is pointed to by the pointer must be indicated when defining the pointer There are some special pointer data types such as the data types of the pointer which points to functions points to pointers and points to multidimensional arrays Pointer size is not relevant to the pointer data types regardless of what the data type is the pointer size is fixed and only depends on the microcontroller architecture Ex char p long q When using sizeof p and sizeof q the value is always 2 C compiler V3 1 3 6 Pointer Operation Rev 1 00 There are three steps to operate a pointer pointer definition pointer initialization and using a pointer It is important to be careful that the pointer is initialized when being used If writin
81. ttings Linker Options Categories lt All Categories v Remove unused function only for C Uninitialized global static variables are automatically set to 0 Warn if the address of alias variable is overlap Arrange the ROM space by address order Check stack overflow 72 December 26 2014 10 2 Variable Declaration 10 2 1 unsigned signed Generally when using the signed type the compiler will take into account positive or negative conditions So if there are no negative conditions using unsigned will omit the negative to save ROM space char a 10 char a 10 void main void void main void char i unsigned char i for i 0 i lt 9 itt for i 0 i lt 9 i ali 1 ali 1 Code size 34 Code size 31 10 2 2 Date type Select the data types with the appropriate scope to make the instruction more simple long i unsigned int i void main void void main void if 1 gt 456 if i gt 456 i 2 i 2 10 2 3 Floating Constant The floating constant defaults to the double type If the required precision in the calculation is not high it can be forced to change to float For example float 3 14 float s r float s r void main void maint Ev 314 r xr float 3 14 Code size 343 Code size 177 The compiler will not carry out constant folding in floating operations So if it is required to calculate tw
82. upt address for example DEFINE ISR isr timer 0x0c define DEFINE SFR sfr type sfr addr static volatile sfr type sfr attribute _ at addr Here static shows that the special register is static Each C file may include a MCU header file therefore the special register must be defined as static sfr type is the data type and sfr is the special register name addr is the address for example DEFINE SFR unsigned bp 0x03 2 Special register definition define acc acc here acc is the variable that has been defined by DEFINE SFR Users can use it in their programs directly 3 Flag definition define c Status bits c here status is the defined variable if users want to define the flag the follwing ways can be used as a reference a Frst define a struct Collection of all the status register flags and union using status to operate on complete bytes or a single bit typedef struct unsigned char c 1 unsigned char ac 1 unsigned char z 1 unsigned char _ ov 1 unsigned char pdf 1 unsigned char to 1 unsigned char cz 1 unsigned char sc 1 _ status bits typedef union status bits bits unsigned char byte status type b Specify status to the address Ox0a If it is a general bit variable then there is no need to specify the address DEFINE SFR status type status 0x0a c Define pa0 macro as a bit field for easy reference define c Status bits c 36 December 26 20
83. ve sign exponent e mantissa m 31 30 23 22 16 15 8 7 0 1 1 2 Constant and Variable A constant value remains unchanged during program execution A variable is a storage unit with specific attributes in memory which is used to store data depending upon the required data type for the defined variables 1 1 2 1 Numeric Constant String Constant Constant e Numeric Constant C Compiler V3 supports the specified Hexadecimal 0x and Octal 0 prefix The binary value begins with 0b For example the number 237 is represented in binary as 0b11101101 String Constant Included within double quotation marks ex abc Constant C Compiler V3 supports up to 64 pages of const constants and also supports const array the pointer pointed to const and so on Example const unsigned char TABLE 8 1 2 3 4 5 6 7 8 unsigned char Test 10 void TEST Const unsigned char data unsigned char counter unsigned char i T counter T counter counter for i 0 i T counter itt Test i datatt void main TEST Const TABLE 8 Regarding the long instruction MCUs such as the HT66F70A the ROM width is 16 bits and with TBHP register such as the HT66F60 need to selete the following option V3 Compiler V3 20 or above supports the const constants which are designated address Rev 1 00 9 December 26 2014 Rev 1 00 Project s Build Opt kl Compiler Settings Linker O
84. y format can occur outside the function and can be used to define variables such as section etc It will output the string between the quotes The compiler will not deal with this 39 December 26 2014 2 2 6 Specify Function Address C Compiler V3 20 or above version offers support to specify the function address syntax unsigned char attribute at addr fun char parm key word _ attribute at addr specifies the function address to addr such as unsigned char _ attribute at 0x373 foo char parm This shows a defined address at 0x373 The function specified address supports parameter and return values 2 2 7 Specify const address For the MCU whose ROM is 16 bits and contains the TBHP register the C Compiler V3 20 or above supports specification of the address syntax const char attribute at addr cvarl 3 1 2 3 key word attribute at addr specifies the function address to addr such as const int attribute at 0x123 a 3 1 2 3 int b int c 9 int fun int pa int a at pa retrun a void main b fun a c attribute at 0x123 means that the defined address of 0x123 The option shown below must be set to use this function Project s Build Optior Compiler Settings Linker Options Compiler Flags Preprocessor Categories lt All Categories Y Do not warn if an unexpected attribute is used Wno attributes V Op
85. yword option Some keywords may have options Keyword C compiler V1 C compiler V2 C COMPILER V3 ANSI C bp free D bp nofree function nobp nolocal nompO nomp1 rambank0 norambank e rombank0 norombank rombank vector D novectornest e inline e 2 Note C compiler V3 supports inline function and its format is the same as the standard C language 4 7 Const Variable Const Variable C compiler V1 C compiler V2 C COMPILER V3 ANSI C Data Type bit excepted bit excepted any any Y Y Used directly by N N when quoting when quoting otherdocuments add qualifier extern add qualifier extern before const before const Should to be declared as globle h S N Initialization setting Y Y Y Y at announcement Constant array size Y Y Y Y assignment Addressing operating bit NO NO Y Rev 1 00 54 December 26 2014 4 8 Pre defined Head Files Pre defined Head File C compiler V1 C compiler V2 C compiler V3 ANSI C HTxxxxx H Y Y N assert h N N N Y ctype h N Y N Y errno h N N N Y float h N N N Y limits h N N N Y locale h N N N Y math h N Y N Y setjmp h N N N Y signal h N N N Y stdarg h N N N Y stddef h N N N h stdio h N N N Y stdlib h N Y N Y string h N Y N Y time h N Y

Download Pdf Manuals

image

Related Search

Related Contents

Capteur de flux SCHMIDT SS 20.260 Mode d`emploi  印刷・ダウンロードが必要な方は賛助会員専用へ。  箱の中身は無限の時空  Targus Stow-N-Go Media Remote Control Card  

Copyright © All rights reserved.
Failed to retrieve file