Home
Dynamic C 32 technical reference
Contents
1. 37 baud rate eS 67 BBR 96 97 98 198 199 200 201 202 213 BCDE 131 135 141 142 BCDE primary register 189 BeginHeader 23 82 83 102 194 195 beginning of file 41 beginning of line 41 BIN files 31 32 50 60 176 210 binary operators 115 BIOS 22 30 31 32 35 76 96 97 98 102 126 199 200 201 210 211 213 Technical Reference library functions 3l symbol library 31 32 BIOS App Lib ClrSEE BIN 32 BIOS App Lib SimEE BIN 31 BIOS App Library BIN 31 BIOS Application BIN 31 210 bitwise AND operator amp complement operator 117 exclusive OR operator 121 inclusive OR operator 122 body module 82 83 195 dungeon 203 files 30 50 176 branching 89 90 break 87 88 90 100 109 222 88 break points 16 35 53 56 104 130 188 208 soe 35 52 53 interrupt status 35 52 53 35 52 53 183 breaking out of a loop 88 breaking out of a switch statement 88 buttons toolbar 67 C files 76 C functions calling assembly code 140 language
2. 122 long 36 104 111 128 205 long integer values 113 longjmp rte 184 lookup function lt CTRL H gt 72 73 74 loops 86 87 102 103 breaking out 88 skipping to next pass 88 M macro multi line assembly code 134 macros 84 85 86 125 132 133 restrictions 86 with parameters 84 main function 51 76 78 79 104 188 212 216 217 65 94 memory allocation 66 dump iuste ded cbe 54 extended 18 22 63 66 96 97 98 100 102 111 124 126 127 139 140 145 169 198 199 200 201 202 203 204 205 206 208 dat eme 127 128 205 strings 128 204 205 flash iet 18 19 logical 63 65 96 97 98 198 199 200 201 202 203 management 96 97 98 100 102 106 145 198 202 211 physical 25 63 64 96 97 98 111 127 128 198 199 200 201 202 203 204 205 206 random access 18 19 22 25 29 37 40 51 64 98 164 168 198 201 211 212 216 234 Index read only 18 19 22 25 29 30 31 32 37 40 50 51 64 98 99 112 164 168 182 198 201 202 208 210 212 213 tetlectiomxzi ineo onenen 211 63 65 root 22 63 66 96 97 98 100 102 106 126 134 135 136
3. 149 150 shared code 159 shared data 160 state 149 150 151 154 156 157 suspended 148 149 151 152 153 154 4 eec 150 unnamed 149 150 154 waitfor esee 151 152 yield iere 153 CRG usual eM 170 Create RTI File for Targetless Compile 29 30 31 32 50 51 172 Create HEX File Also 60 210 creating NEW tiles em eem 42 standalone programs 36 37 CS State 156 CTRL key eee 41 nete 47 10 34 56 CTRE E2 54 CTRL F3 50 51 43 49 CTRL H 37 38 72 73 74 35 52 53 idit 49 CTRL O 34 52 53 ten 49 CTRL U esee 36 54 56 47 CTRL W 35 36 54 55 seduce 46 CTRL Y eee 52 54 CIRE Lies sie Ameis 36 52 curly braces 78 cursor 34 53 54 positioning 2 2222 49 positioning with arrow keys 41 ds 40 74 custom error handler 182 cutting text lt CTRL X gt 46 Technical Reference Index 227 D data in extende
4. 150 Structure user defined 159 189 Code with BIOS 30 32 es 118 COM 67 169 PC nde 29 169 comma operator 123 COMMENT au ehem 81 Multi line 81 simple line 81 226 Index comments essere 78 common base register CBR 140 145 communication RS 232 16 24 65 485 2 2 1 16 24 serial 16 24 67 163 clocked 24 with Dynamic 29 compilation 28 32 40 50 51 60 69 71 126 23 direct to controller 16 A iain 49 speed msi nets 16 17 targetless 29 30 31 32 50 51 COMPILE menu 41 50 51 compile time stamp 60 Compile to File lt gt 32 50 51 60 171 210 Compile to File with RTI File lt ALT CTRL F3 gt 29 30 31 32 50 51 60 172 210 Compile to Target lt F3 gt 29 50 51 compiler directives 124 208 default isse 208 compiler options 30 40 50 58 59 60 61 62 94 171 189 201 210 211 213 222 Application Only BPF 30 211 BIOS App Lib ClIrSEE BIN 32 BIOS 31 BIOS App Library BIN 31 BIOS Application BIN 31 210 Create HEX File Also 60 Download via DLM DLP 32 210 App Lib SimEE BIN
5. string Although this may be sufficient for most purposes the Insert Call button can be clicked to turn the dialog into a function assistant Forte insb cundi e CITRIEG L1B char mtrcpy har dmt cher BESCRIPTION string bo string dmt includizg tha null tarminmtcr BARABETERL Faintar tc tn FARRBETERI Faintar tc lncacion En supply string RETURN Pnirtsr to dat Pointer to location to aCrimq The function assistant will place a call to the function displayed at the insertion point in the source code The function call will be prototypical 1f OK is clicked the call needs to be edited for it to make sense in the context of the code Technical Reference Dynamic C Environment 73 Each parameter can be specified one by one to the function assistant The function assistant will return the name and data type of the parameter When parameter expressions are specified in this dialog the function assistant will use those expressions when placing the function call If the text cursor is placed on a valid C function call and one that is known to the function assistant the function assistant will analyze the function call and will copy the actual parameters to the function lookup dialog Compare the function parameters in the
6. 126 VEC 164 126 ftmakechain 19 126 memmap 22 105 126 208 nodebug 51 101 105 107 109 111 125 188 208 Hmointerleave 126 Znouseix 23 105 127 208 86 126 18 23 77 81 83 127 195 HUSEIX 23 105 127 190 125 125 Yo operator 120 Technical Reference operator 4 44 44 123 amp address operator 94 119 amp amp 122 amp operator 123 parentheses as operators 116 type operator 118 indirection operator 94 118 operator essen 123 Operator rsen Res 118 increment operator 117 operator 0 44004 0 122 gt right arrow operator 116 dot as 116 5 ui ente 60 DLP for Download 172 RII 222 operator 2 119 operator 123 semicolon operator 78 132 lt operator 120 SCODGTator sive 120 lt lt operator 123 lt operator 120 operator eere 122 operator eese
7. Contents 0 Physical address for the segment body ulong 4 SEGLEN length of segment body ulong 8 The segment body SEGLEN 8 CRC for segment and first 8 bytes uint Technical Reference Remote Download 173 174 Remote Download Dynamic C 32 v 6 x 0 10 LocAL UPLOAD Local Upload 175 Technical Reference Z World provides field programmability for its controllers An uploadable to Flash EPROM BIN or to SRAM BPF program file can be created by selecting the appropriate compiler option The Z World Program Loader Utility PLU running on a PC connected via a COM port to the target controller will transfer the program file into the target controller s memory and optionally start it running immediately after upload Local uploading requires a direct serial connection between the host PC and the target controller The uploadable program BIN or BPF should be of the appropriate type for the target controller A BIOS Application BIN type program file is suitable for a Flash EPROM equipped target while an Application Only BPF type program file should only be uploaded to SRAM on a standard non Flash EPROM equipped target controller The PLU determines the target controller EPROM type and defaults to selection of only the appropriate program file type of See Appendix File Formats for more information on these file types It is possible to override the default program type how
8. Help Cancel Select the appropriate COM port from the Port list box Also set the serial Baud Rate and Stop Bits parameters if necessary The Tx Mode group box provides three choices but because the program files are pre compiled by Dynamic C the choices are all equivalent The PLU does not compile programs and so can not overlap compilation and target communication Technical Reference Local Upload 177 Reset the Target Controller The target controller must be reset into program mode in order to communicate with the PLU Often this entails setting a jumper or pressing keys and either cycling power or pressing a reset button Consult the specific controller s hardware manual for details When the target controller is in program mode select the Options gt Reset Target menu item to perform a software reset of the target controller The following message 15 briefly displayed Resetting Target If the target controller is communicating with the PLU then the Resetting Target message will disappear If you see the following message box then the target controller is not communicating with the PLU Target not responding The problem may be that the communication parameters need to be changed either in the PLU or the controller or that the target controller is not running in program mode Click the OK button check the controller s power supply and jumper settings check the PLU s communication parameter
9. 46 47 lt F6 gt replacing text 46 F7 Trace into keywords 19 22 76 98 99 100 101 102 103 104 105 106 107 108 109 110 111 139 150 162 188 201 L language elements 99 112 113 Operators 115 lastlocADDR 156 157 lastlocCBR 156 157 latency interrupts 143 less than operator lt 120 less than or equal operator 120 Lib Entries 37 72 LIB files pinnaga 76 LIB DIR 23 72 83 127 195 libraries 17 23 76 77 102 127 220 function 23 function prototypes 23 lookup dialog 37 modules 82 194 real time programming 17 25 library functions 37 66 72 126 library headers 193 Library Help lookup lt CTRL H gt 72 73 14 194 license agreement 14 line continuation in directives 124 linking iiec 16 local download 176 PRGLOADR EXE 176 locating errors 49 Log File 4 eui 62 Log STDOUT 62 logical AND amp amp 122 Index 233 logical memory 63 65 96 97 98 198 199 200 201 202 203 logical operators 117 122 logical OR
10. ru base Tcp pe 1 1 19 physical address ee Figure D 2 7180 Physical Addresses Technical Reference Extended Memory 199 Figure D 2 shows the address locations Memory Partitions Table D 1 Dynamic C Memory Partitions Description BIOS 8K Basic Input Output System The BIOS is always present and is always mapped to address 0 of ROM or flash The BIOS contains the power up code the communication kernel and important system features ROOT 48K The area between the BIOS and XMEM the bank area The root normal memory tesides in fixed portion of physical memory Root code grows upward in logical space from address 2000 hex and root data static variables stack and heap grow down from E000 Initialized static variables are placed with code whether in ROM flash or RAM XMEM 8K XMEM is essentially an 8K window into extended physical memory XMEM can map to any part of physical memory ROM flash or RAM simply by changing the CBR Table D 1 explains the memory partitions in Dynamic C The XMEM area has many mappings to physical memory The mappings can change by changing the CBR as the program executes Extended memory functions are mapped into XMEM as needed by changing the CBR The mapping is automatic in C functions However code written in assembly l
11. 22 124 164 208 asm 21 83 124 130 131 188 Zclass 24 125 208 debug 101 105 107 109 111 125 188 define 81 84 85 86 125 126 esce 125 126 Zelse 125 126 Zendasm 21 83 124 130 131 132 125 126 125 Hiatal ne estesa 125 funcchain 19 125 f asse etd 125 Vifdef 126 126 Hinterleave 126 EKILE 126 makechain 19 126 memmap 126 208 Znodebug 51 101 105 107 109 111 125 188 208 Znointerleave 126 inouseix 23 105 127 208 Zundef sss 86 126 use 18 23 77 81 83 127 195 23 105 127 190 FWANS ua ette teet 125 Wwarnt 125 default ste 208 Disassemble at Address lt ALT EI02 guai 56 70 Disassemble at Cursor CTRL EIOS se 34 56 70 disassembled code 54 disassembler 34 display Options 58 66 divide assign operator 123 division operator 119 DLC download configuration file 171 Dynamic C 32 v 6 x DLM Download Manager 168 169 170 171 172 173 210 DLM MAX PW LEN 170 MIN PW LEN 170 DLM PASSWORD LVL
12. 170 DLM PASSWORD STR 170 172 TIMEOUT 170 DLM 4Z20 C 169 172 DLP files 50 168 170 171 172 173 210 DMA channels 24 do 87 102 dot operator 93 112 116 download configuration DLC file 171 localis 176 remote 33 168 169 170 171 172 173 210 Download Manager DLM 40 51 168 169 170 171 172 173 210 Download Program 170 Download to RAM 211 Download via DLM DLP 32 171 210 downloadable files ues 51 program 29 30 31 32 170 171 172 173 downloading 29 30 31 32 dummy call 36 Dump at Address 56 Dump to File 57 dump window 57 QW aee centi 132 dynamic memory allocation 65 storage allocation 94 variables 94 Dynamic 14 16 17 23 28 51 126 213 Application Frameworks 160 communication 29 163 debugger 32 33 Technical Reference differences 17 18 19 20 21 22 23 24 25 76 45 68 Help Contents 37 installation 14 28 installation procedure 14 installation requirements 14 license a
13. 47 48 49 ROM 52 53 64 98 164 182 198 201 208 210 212 213 programmable 18 19 22 25 29 30 31 32 37 40 50 51 64 98 99 112 164 168 182 198 201 202 208 210 212 213 66 96 106 126 199 200 201 203 204 211 memory 22 63 66 96 97 98 100 102 106 126 134 135 136 138 139 140 145 169 198 199 200 201 203 204 205 206 208 211 212 FESTVE notes 66 root2xmem esee 205 RS 232 communication 16 24 RS 485 communication 16 24 Dynamic C 32 v 6 x 8 iiec 52 RST 208 212 28 188 RTI remote target information file 29 30 31 32 40 50 51 76 172 RTI files 210 RTK real time kernel 17 25 190 RTK LIB 148 Run F9 sse 34 52 RUN menu 34 35 41 52 53 54 run mode 29 32 49 52 Run w No Polling lt ALT F9 gt 34 52 run time checking 22222 59 errors and standalone programs 182 stack size use entes 65 running a program 52 in polling mode 52 standalone 16 with no polling 52 S sample programs 76 128 169 172 206 basic C constructs 81 SAMPLES subdirectory 76 128 206 SAMPLES AASC subdirectory 169 172 SAVE eee ad 43 save and restore registers 184 Save ds ERRARE 43 Save Enviro
14. init on The costatement 1s initially on and will automatically execute the first time it is encountered in the execution thread The costatement becomes inactive after it completes or aborts If state is absent the costatement is initially off For the costatement to execute it must be triggered by the software Then the costatement will execute once and become inactive again Waitfor Costatements can wait for an event a condition or the passage of a certain amount of time The waitfor statement permitted only inside a costate ment is available for this purpose waitfor expression The waitfor suspends progress of the costatement pending some condition indicated by the expression When a program reaches the waitfor if expression evaluates false that is zero the reentry point for the costatement is set at the waitfor statement and the program jumps out of the costatement Then each time the program reenters the costatement it evalutes the waitfor expression If the expression is false the program jumps out again If the expression is true non zero the program will continue with the statement following the waitfor The diagram on the left side of Figure 7 2 shows the execution thread the first time through a costatement when a waitfor evaluates false The diagram on the right shows the execution thread through a costatement when a waitfor continues to evaluate false MEN cos
15. 8 bit unsigned integer 8 bit characters fit precisely into a char hence the name Range 0 to 255 OxFF 16 bit signed integer Range 32 768 to 432 767 16 bit unsigned integer In this manual the term uint is shorthand for unsigned int Range 0 to 65 535 32 bit signed integer Range 2 147 483 648 to 2 147 483 647 32 bit unsigned integer In this manual the term ulong is shorthand for unsigned long Range 0 to 232 1 32 bit IEEE floating point value The sign bit is 1 for negative values The exponent has 8 bits giving exponents from 127 to 128 The mantissa has 24 bits Only the 23 least significant bits are stored the high bit is implicitly 1 Z180 controllers do not have floating point hardware Range 6 085 x 1038 to 6 085 x 1038 C supports string constants but not a string data type A string in C is really an array of characters Technical Reference The Language 91 The structures of the primitive data types are shown in relative size in Figure 5 3 char S int unsigned int S long int unsigned long int S 127 mantissa 1 0 to 1 99 float Figure 5 3 Structures of Dynamic C Primitive Data Types Aggregate Data Types Simple data types can be grouped into more complex aggregate forms Array A data type whether it is simple or complex can be replicated in an array The declaration int item 10 an a
16. In either case the term name represents the 20 bit physical address of the block Use the following functions to move blocks of data between logical memory and physical memory Pass addresses of extended memory data as long integers containing the 20 bit physical address in the least signifi cant bits Names declared with xdata and xstring are 20 bit extended memory addresses xmem2root long src void dst uint n Copies n bytes from extended memory src to root memory starting at dst root2xmem void src long dst uint n Copies n bytes from root memory src to extended memory starting at dst uint xstrlen long address Returns the length of the string at the address found at address Keep in mind that an xstring declares an array of 20 bit addresses of strings long xgetlong long address Returns the long integer at the extended memory address Technical Reference Extended Memory 205 The following example illustrates the use of extended memory xstring greetings hello there good bye nice to see you how have you been xdata table 1 23 1 45 1 67 1 85 1 93 2 04 5 03 6 78 xdata store 10000 float y long j k int a char my chars 30 get one floating number at j j xmem2root table j 4 x address amp y destination 4 bytes two bytes from store j xmem2root store j amp a 2 root2xmem amp a s
17. 1 to 6 3 Collate Selection Cancel If the Print to File option is selected Dynamic C creates a file it will ask for a path list a format suitable to send to the specified printer if the selected printer is a PostScript printer the file will contain PostScript To choose a printer click the printer name in the drop down list box and then click on one of the names in the displayed list Click the Properties button to adjust or inspect options available on the selected printer The Print range can be All specific Pages or even just a Selection of text if a block of text is currently selected in the active window As many copies of the text as needed may be printed If more than one copy is requested the pages may be collated or uncollated 44 Dynamic C Environment Dynamic C 32 v 6 x Print Setup Allows the printer s page set up to be specified in the following type of dialog box Page Setup HES Paper Size Letter Source Automatically Select m Orientation IB Margins inches Portrait Left 1 Right 1 Landscape Top T Bottom 1 Cancel Printer Depending on the printer selected it may be possible to specify paper size and paper orientation portrait or tall vs landscape or wide Most printers have these options A specific printer may or may not have more than one paper source The page s margins are also
18. 83 header 82 83 102 195 key see 82 194 library 2 82 194 modulus operator 96 120 1006 eig adeptes 40 moving to beginning of file 41 to beginning of line 41 to end of file 41 to end 41 multi line assembly code macro 134 multiplication operator 118 multipy assign operator 123 multitasking 148 149 150 151 152 153 154 155 156 157 158 159 160 21 multithreaded costatements 158 159 160 multithreaded systems 148 N named constants 18 112 costatements 150 enne 112 define 112 42 new libraries GESUPRT LIB 222 SF1000 Z LIB 222 newbbr 213 Technical Reference Next error lt CTRL N gt 46 49 No Background TX 67 nodebug 52 53 56 62 104 124 130 188 189 208 nonmaskable interrupts 163 164 DOISU user aie 104 NOT logical operator 117 not equal operator 121 NOUSEIX 23 105 136 190 NULL 105 NULL device 50 Null Device Bit Bucket 32 numbers 222 112 Object File Option 60 octal integer va
19. Null Device Bit Bucket 32 Program Loader Utility 30 simulated EEPROM 31 32 Zero Time Stamp 60 222 Dynamic C 32 v 6 x compiling 16 28 60 to file 29 30 31 32 40 50 51 210 to flash 51 to RAM 50 51 to ROM 50 51 to target 29 32 40 50 51 compound 112 statements 78 concurrent processes 18 21 148 conditional operation 122 constants 114 named une 112 Content eas 157 contents 71 continue 87 88 101 109 22 88 cooperative multitasking 21 148 149 150 151 152 153 154 155 156 157 158 159 160 CoPause 150 156 copying text 46 47 copyright esses 213 CoReset 150 156 157 150 156 costate 101 150 154 158 costatements 18 21 100 101 110 111 148 149 150 151 152 153 154 155 156 157 158 159 160 abort sse 154 aborted 5a ELS 154 always on 149 151 154 firsttime flag and functions 157 158 initially off 149 151 initially 149 151 multiple threads 158 159 160 named
20. Program comments are written in Courier font plain face Italics Indicates that something should be typed instead of the italicized words e g in place of filename type a file s name Edit Sans serif font bold signifies a menu or menu selection An ellipsis indicates that 1 irrelevant program text is omitted for brevity or that 2 preceding program text may be repeated indefinitely Brackets in a C function s definition or program segment indicate that the enclosed directive is optional lt gt Angle brackets occasionally enclose classes of terms alble Technical Reference A vertical bar indicates that a choice should be made from among the items listed About This Manual xi xii e About This Manual Dynamic C 32 v 6 x 1 1 INSTALLING Dynamic Technical Reference Installing Dynamic 13 Installation Requirements Your PC must meet the following requirements in order to successfully install and use Dynamic C 32 CPU is 386SX or higher Pentium or higher is recommended OS is Windows 95 98 2000 Me or NT CD ROM or compatible drive hard drive with at least 32 megabytes of free space at least 16 megabytes of RAM at least one free COM port Installation Procedure Dynamic C 32 software comes on one CD ROM Insert the CD ROM into the appropriate drive on the After a few moments the installation program should start automatically
21. This feature 1s especially handy to preview code generated for library functions Combined with the scrolling register watch and stack windows the disassembler features let the programmer trace the history of the code and know exactly which machine instruction caused what changes after the fact Break Points At times there may be a need to run a program at full speed and then stop at break points These break points be placed and removed at run time anywhere in the source code The line of code is highlighted where a break point has been inserted in the source code There are hard break points and soft breakpoints Interrupts are disabled at hard break points Interrupts are restored to their former state when execution resumes after a hard break point Soft break points do not affect the interrupt state The interrupt flag may be toggled independently using the Toggle interrupt command on the RUN menu or by using EI and DI in the watch window see below The message bar at the bottom of the Dynamic C window reports the current interrupt state The iff in the watch window may also be used to determine the interrupt state Watch Expressions Watch expressions allow the programmer to obtain the value of a variable to evaluate an arbitrary expression or to invoke a function out of se quence To do this select Add Delete Watch Expressions from the INSPECT menu or press CTRL W This invokes the watch expression dialog box
22. endasm The keyword useix is the only change from the previous sample function Figure 6 4 shows the stack frame for this function L 1 4 4 6 m i 2 J 2 7 ch 2 4 or return address 2 4 x0 prior value of z 2 4 HK amp frame reference point HK SP Figure 6 4 Assembly Language Stack Frame Useing IX Function in Root Memory The arguments will have slightly different offsets because of the additional two bytes for the saved IX register value 1 offset 8 i offset 6 ch offset 4 Now access to stack variables becomes easier Consider for example how to load ch into register A ld a ixtch a lt ch 138 Using Assembly Language Dynamic C 32 v 6 x The IX offset load instruction takes 14 cycles and three bytes If the program needs to load a four byte variable such as 1 the X offset instructions are as follows ld e 1 1 load LSB of 1 ld 1 1 1 ld 1 1 2 ld 1 1 3 load MSB of 1 This takes a total of 56 cycles and 12 bytes Even if IX is the frame reference pointer the SP symbol may still be used ld h1 SP 1 hl lt the offset from SP to the variable add hl sp hl lt the address of the variable ld e hl lt the LSB of 1 inc hl 1 d hl gt inc hl 1 c hl 5 inc hl ld b hl b lt the MSB of 1 This takes 52 cycles and 11 bytes The two a
23. of x 2 4 prior value of z 2 4 SP Figure 6 5 Assembly Language Stack Frame No IX Function in ExtendedMemory Because of the additional 4 bytes for the return address the arguments will have slightly different offsets 1 offset 10 i offset 8 ch 6 Because the compiler maintains the offsets automatically there is no need to worry about the change of offsets The SP approach discussed previously as a means of accessing stack based variables works whether a function is compiled to extended memory or not as long as the C language names of local variables and arguments are used A function compiled to extended memory can use IX as a frame reference pointer as well This adds an additional two bytes to argument offsets because of the saved IX value Again the X offset approach discussed previously can be used because the compiler maintains the offsets auto matically C Functions Calling Assembly Code Dynamic C does not assume that registers are preserved in function calls In other words the function being called need not save and restore registers The exception is the memory management unit register CBR common base register If a function is in root memory and the caller is in extended memory the compiler assumes that the CBR is preserved by the called function 140 Using Assembly Language Dynamic C 32 v 6 x If a C callable assembly function 18 expected to return a result of primi
24. 1 if _sysIsWDTO t statements 1 statements rest of main Functions of the second category have names similar to those in the first category but they do not have initial underbars int sysIsSuperReset int sysIsPwrFail int sysIsWDTO These functions reflect the cause of the last reset They can be called anywhere in the program as often as needed Functions of the first category can only be called at the beginning of main Technical Reference Reset Functions 217 Reset Generation Software can generate two types of system reset Call sysForceReset to turn off interrupts and wait until the watchdog resets This reset will be registered as a watchdog reset when the applica tion restarts Call sysForceSupRst to request a super reset This function turns off interrupts and waits until the watchdog resets This reset will be registered as a super reset when the application restarts The controller must have a hardware watchdog enabled for either of these functions to work 218 Reset Functions Dynamic C 32 v 6 x ArPENDIx H EXISTING FUNCTION CHAINS Technical Reference Existing Function Chains 219 The function chains in Table H 1 exist in the libraries specified Segments may be added to these chains Don t redefine a chain if its library is used noting that SYS LIB is used by default Table H 1 Dynamic C Function Chains Library Function Chain Description Registers AASC hardwar
25. 123 conditional 122 array indices 116 bitwise exclusive OR 121 S assign 123 logical OR 122 bitwise inclusive OR 122 assigns te eti 123 bitwise complement 117 assignment 122 123 associativity 115 124 sesso eer 115 COMMA tere ers 123 conditional 122 117 in assembly language 133 logical 117 122 MINUS 118 precedence 115 124 relational 120 121 119 deterret 115 unary MANUS 118 optimization 22 22 4 188 Optimize For size or speed 62 Options Display 2 2 66 options compiler 58 59 60 61 62 debugger 58 62 58 66 236 Index editota 58 58 63 eet es 58 67 OPTIONS menu 30 40 41 50 51 58 59 60 61 62 63 64 65 66 67 71 94 202 OR assign operator 123 OR logical operator 122 output analog 22 16 digital snide 16 high current 2222 16 Output Generation 60 Create HEX File Also
26. 138 139 140 145 169 198 199 200 201 203 204 205 206 208 211 212 memory management unit MMU 22 96 97 98 140 198 199 200 201 202 211 Memory options 40 51 63 Logical 65 Physical e 63 65 Root Reserve 66 XMem Reserve 66 memory options 58 menu commands 41 42 menus COMPILE 41 50 51 EDIT 36 41 46 47 48 49 FILE 41 42 43 44 45 HELP 37 38 41 71 72 73 74 INSPECT 34 41 54 55 56 69 OPTIONS 30 40 41 50 51 58 59 60 61 62 63 64 65 66 67 71 94 202 RUN 34 35 41 52 53 54 exte ie 41 WINDOW 41 65 68 69 70 71 Message window 69 message window 49 51 68 69 Microsoft Windows Users Guide 40 42 minimized windows 69 minus operator 118 MMU memory management unit 22 96 97 98 140 198 199 200 201 202 211 mod assign operator 123 Dynamic C 32 v 6 x Mode 0 interrupts 164 Mode 2 interrupts 164 modes debug 29 49 52 190 debug same as run mode 32 editi suse 36 40 46 49 54 previews ox eee 43 E 29 32 49 52 modules 77 82 83 102 body 82 83 195 example
27. 24 108 189 190 subfunctions 18 24 108 189 190 subscripts 92 subtract assign operator 122 super reset 21 25 26 216 218 support files 77 suspend te ipe 23 suspended costatements 148 149 151 152 153 154 switch 90 100 101 102 109 203 breaking out 88 switching to edit mode 36 46 49 symbolic constant 125 Sync Bkgnd TX 67 syntax checking 22 32 costatements 150 SYS 220 sysForceReset 26 218 sysForceSupRst 26 218 sysIsPwrFail 217 sysIsSuperReset 217 SysISWDTO sess 217 sysSupRstChain 26 216 220 T table of operator precedence 124 Target Communication 222 targetless compilation 29 30 31 32 50 51 text CUfSOE iir 40 74 Tile Horizontally 69 tiling windows 68 69 met aet ibd 16 programmable 24 watchdog 25 184 185 217 218 Toggle break point F2 52 53 Toggle hard break point lt ALT F2 gt 52 53 Technical Reference Toggle interrupt lt CTRL I gt 35 52 53 Toggle polling lt CTRL O gt 34 52 toolbar 67 print preview 2 2 44 topical help 37
28. 40 41 horizontal tiling 68 69 I register 163 164 212 16 52 67 icons arranged 68 69 IEEE floating point 102 jii efe n E EU 102 103 multichoice 90 simple 2 89 89 eti 35 163 Index 231 immediate evaluation watch 1 36 increment operator 4 4 117 index checking 208 index registers 18 23 131 143 indirect function calls 103 143 indirection operator 94 118 Information Window 65 Information window 71 information window 65 68 69 71 Init Oo ese deese 149 151 initialization global its 20 21 initialized 210 initialized static variables placed in ROM 19 input analog hates es 16 digital 5 dE 16 insertion 47 49 Inspector 69 70 INSPECT menu 34 41 54 55 56 69 installation Dynamic C 14 28 requirements 28 installation procedure 14 installation requirements 14 int 80 81 104 107 110 111 128 205 as default function type 78 integer values 113 Intel extended HEX fo
29. A data structure some additions to the C language and some functions comprise what Z World calls costatements A costatement is a construct a block of code that can suspend its own execution thereby allowing other code to execute A set of costatements presumably in an endless loop executes concurrently seemingly in parallel All of the tasks in the set are in states of partial completion Costatements may execute repeatedly or execute once when triggered and then stop For further detail refer to Chapter 7 Costatements in this manual and to the Dynamic C Application Frameworks manual Interrupt Service Routines Interrupt service routines can be written in Dynamic C using the C language The keyword interrupt designates a function as an interrupt service routine interrupt my handler Embedded Assembly Code There are times when assembly language is necessary or desirable For time critical or machine dependent code it is natural to choose assembly language Dynamic C allows Z180 assembly code to be embedded in a C program Assembly code may be written within a C function or complete assembly code functions may be written C language statements may also be embedded in assembly code For further detail refer to Chapter 6 Using Assembly i Language Technical Reference Introduction to Dynamic 21 Shared and Protected Variables An important feature of Dynamic C is the ability to declare variables as
30. Appendix E Compiler Directives 207 Default Compiler Directives eessssseeeeeee 208 Appendix F File Formats 209 Layout of ROM Files esce poete reet e a De ee ee 210 Layout of Downloadable Files essen 210 Layout of Download to RAM 211 Hex File Information nennen 212 Jumping to Another Program sse 213 Burning ROM teo teniente ad edet 213 Copyright Notice esee eese fec heise eas 213 Technical Reference Table of Contents vii Appendix G Reset Functions 215 Reset Differentiation msio thee teet etre een 216 Reset Generation nee n AL SERV YE Ee een 218 Appendix H Existing Function Chains 219 Appendix I New Features 221 Dynamic 32 IDE 222 Compiler Options Output Generation Group 222 Compiler Options File Type for Compile to File Group 222 Target Communication 222 New Libtaries 222 Program Loader Utility eet TRIS 222 Index 223 viii e Table of Contents Dynamic C 32 v 6 x Tuis MANUAL Z World customers develop software for their programmable controllers using Z World s Dynamic C 32 development system running on an IBM compatible PC The controller is connected to a COM port on the PC usually 2 which by default operates at 19 2
31. How Dynamic C Differs differences in Dynamic C are summarized here and are discussed after the summary Variables that are initialized when declared are considered named constants and are placed in ROM It is an error to try to change such variables default storage class is static not auto There is no include directive are there any include header files Library functions and data are bound to a program by other means There is use directive Dynamic C does not support enumerated types The extern and register keywords have an altered meanings e Function chaining a concept unique to Dynamic C allows special segments of code to be included within one or more functions When a named function chain executes all the segments belonging to that chain execute Function chains allow software to perform initializa tion data recovery or other kinds of tasks on request e Costatements allow concurrent parallel processes to be simulated in a single program Dynamic C allows the programmer to write interrupt service routines in C Dynamic C supports embedded assembly code Dynamic C has shared and protected keywords that help protect data from unexpected loss Dynamic C has a set of features that allow the programmer to make fullest use of extended memory Dynamic C provides two forms of argument passing using the IX index register vs using the stack pointer SP Dyn
32. If not then issue the Windows Run command and type the following command lt disk gt SETUP where dislo is the name of the CD ROM drive If the CD ROM drive is D then type SETUP The installation program will begin to run and guide you through the installation process Note that you will be asked to read and understand the Z World Software End User License Agreement If you decline to accept the terms of the agreement then the installation program will terminate without installing Dynamic C 32 When installation is complete a new Windows program group that includes Dynamic C 32 the Program Loader Utility and an on line help file will have been created In addition desktop shortcut icons for these items have also been created The Dynamic C 32 application may now be run from Windows using any of the standard methods E G double clicking on the icon to launch it Please contact Z World s Technical Support at 530 757 3737 if there are any problems 14 Installing Dynamic C Dynamic C 32 v 6 x 74 2 INTRODUCTION TO Dynamic Technical Reference Introduction to Dynamic 15 Dynamic C is an integrated development system that runs on an IBM compatible PC and is designed for use with Z World controllers and control products Z World s Zilog Z180 microprocessor based controllers include a variety of analog inputs and outputs digital inputs and outputs high current outputs
33. Put your disk in the A drive n embedded newline at end printf MSG print MSG char default empty string a single null byte 114 The Language Dynamic C 32 v 6 x Operators An operator is a symbol such as or 6 that expresses some kind of operation on data Most operators are binary they have two operands 10 two operands with binary operator add Some operators are unary they have a single operand amount single operand with unary minus although like the minus sign some unary operators can also be used for binary operations There are many kinds of operators with operator precedence Precedence governs which operations are performed before other operations when there is a choice For example given the expression 10 will or the be performed first Since has higher precedence than it will be performed first The expression is equivalent to a b c 10 Parentheses can be used to force any order of evaluation The expression b 10 uses parentheses to circumvent the normal order of evaluation Associativity governs the execution order of operators of equal precedence Again parentheses can circumvent the normal associativity of operators For example a b tetd b c performed first a b c d now c d is performed first int a function returning ptr to int int a ptr to function returning int
34. The structure CoData follows typedef struct char CSState uint lastlocADDR char lastlocCBR char ChkSum char firsttime union ulong ul struct 4 uint ul uint u2 us content char ChkSum2 CoData Technical Reference Costatements 155 Costatement State The csState field contains two flags STOPPED and INIT The functions CoBegin CoReset CoPause and CoResume set these two flags The functions isCoDone and isCoRunning report these flags as ind icated in Table 7 1 Table 7 1 Meanings of STOPPED and INIT Flags STOPPED Meaning Yes Yes The costatement either is done or has been initialized to run from the beginning but set to inactive This condition can be set by CoReset Yes No The costatement is paused waiting to resume exe cution from wherever it was paused This condition can be set by CoPause No Yes The costatement has been initialized to run from the beginning and will run when your program execution reaches it This condition can be set by CoBegin No No The costatement is active and running and will resume execution where it left off when the program execution reaches it This is the normal condition of a running costatement CoResume will return the flags to this state The function isCoDone returns true 1 if both the STOPPED and INIT flags are set The function isCoRunning returns true 1 if the STOPPED flag is not set The csstate field applies
35. Unary operators and assignment operators associate from right to left Most other operators associate from left to right Certain operators namely gt dot can be used on the left side of an assignment to construct what is called an value For example float x char amp x L x s LS byte gets value char amp x 3 H x s MS byte gets value Technical Reference The Language 115 When the data types for an operation are mixed the resulting type is the more precise float x y z int i j k char c z i x same as float i x same as k int c By placing a type name in parentheses in front of a variable the program will perform type casting or type conversion In the example above the term float i means the the value of i converted to floating point The operators are summarized in the following pages Grouping Expressions enclosed in parentheses are performed first Parentheses also enclose function arguments In the expression b 10 the term b c is evaluated first Array subscripts or dimension int a 12 array dimension is 12 j a i references the ith element All array subscripts count from 0 The dot operator joins structure or union names and subnames in a reference to a structure or union element struct int x int y coord m coord x gt Rightarrow Used with pointers to
36. control to the labeled statement some statements abc other statements goto abc more statements goto def def more statements Notice the colon at the end of the labels The next simplest form of branching is the if statement The simple form of the if statement tests a condition and executes a statement or com pound statement 1f the condition expression 15 true nonzero The program will ignore the i body when the condition is false zero Recommended form C syntax if expression if expression statement some statements A more complex form of the if statement tests the condition and executes certain statements 1f the expression is true and executes another group of statements when the expression 18 false Recommended form C syntax if expression if expr stmt else stmt some statements if true 1 some statements if false Technical Reference The Language 89 The fullest form of the if statements produces a chain of tests Recommended form C syntax if expr if expr stmt some statements else if expr stmt 15 if expr else if expr stmt some statements else if expr stmt 1 if expr some statements else stmt 1 some statements The program evaluates the first expression expr If that proves false it tries the second expression expr and continues testing until it finds true expression
37. int x char y float z record record array 100 int a b char cc Fourscore and seven char list ABC DEFG HI number of bytes in array define array size sizeof record 100 a sizeof record 7 b array size 700 sizeof 20 d sizeof list Why is sizeof list equal to 6 List is an array of 3 pointers to char and pointers have two bytes Why is sizeof cc equal to 20 and not 19 C strings have a terminating null byte appended by the compiler Divide This is a binary operator Integer division truncates floating point division does not int i 18 j 7 k float x k i j result is 2 x float i 3 result is 2 591 Technical Reference The Language 119 gt gt Modulus This is a binary operator The result is the remainder of the left hand operand divided by the right hand operand int i 13 j i 10 j gets i mod 10 or 3 int k 11 j2 k5 7 j gets k mod 7 or 4 Shift left This is a binary operator The result is the value of the left operand shifted by the number of bits specified by the right operand int i OxFOOF 3 lt lt 4 j gets 0 00 0 The most significant bits of the operand are lost the vacated bits become zero Shift right This is a binary operator The result is the value of the left operand shifted by the number of bits specified by the right operand unsign
38. long arg main lIdentifies the main function All programs start at the beginning of the main function This is actually not a keyword but is a function name nodebug Indicates a function is not compiled in debug mode nodebug int func asm nodebug endasm See also debug and directives debug and nodebug norst Indicates that a function does not use the RST instruction for break points norst void func 104 The Language Dynamic C 32 v 6 x nouseix lIndicates a function does not use the IX register as a stack frame reference pointer nouseix void func Gs See also useix and directives useix and nouseix NULL The null pointer This is actually a macro not a keyword Same as void 0 pop A keyword used in conjunction with certain directives memmap and class These directives can push and pop their states memmap root root functions memmap push xmem xmem functions here memmap pop now back to root functions protected Declares a variable to be protected against system failure This means that a copy of the variable is made before it is modified If a transient effect such as power failure occurs while the variable is being changed the system will restore the variable from the copy main protected int statel state2 state3 push A keyword used in conjunction with certain directives memmap and class These directives can
39. protected Such a variable 1s protected against loss in case of a power failure or other system reset because the compiler generates code that creates a backup copy of a protected variable before the variable is modified If the system resets while the protected variable is being modified the variable s value can be restored when the system restarts A system that shares data among different tasks or among interrupt routines can find its shared data corrupted 1f an interrupt occurs in the middle of a write to a multi byte variable such as type int or float The variable might be only partially written at its next use Declaring a multi byte variable shared means that changes to the variable are atomic that is any change to the variable is a complete change Interrupts are disabled while the variable is being changed Extended Memory Dynamic C supports the 1 MByte address space of the Z180 microproces sor The address space of the 7180 is segmented by a memory manage ment unit Dynamic C allows programs containing up to 512 KBytes in ROM code and constants and 512 KBytes of RAM data Normally Dynamic C takes care of memory management but there are instances where the programmer will want to take control of it Dynamic C has keywords and directives to help put code and data in the proper place The keyword root selects root memory addresses within the 64 K Byte physical address space of the 71180 The keyword xmem selects exten
40. tive type the function must pass the result in the primary register If the result is an int uint char or a pointer return the result in HL register H contains the most significant byte If the result is a long ulong or float return the result in BCDE register B contains the most significant byte A C function containing embedded assembly code may of course use a C return statement to return a value A standalone assembly routine however must load the primary register with the return value before the ret instruction In contrast if a function returns a structure of any size the calling function reserves space on the stack for the return value before pushing the last argument if any A C function containing embedded assembly code may use a C return statement to return a value A standalone assembly routine however must store the return value in the structure return space on the stack before returning An in line assembly code may access the stack area reserved for structure return values by the symbol RETVAL which is an offset from the frame reference point The following code shows how to clear field 1 ofa structure as a returned value of type struct s typedef struct ss int 0 first field char f1 second field xyz xyz my struct my struct func 4 asm xor a Clear register A ld hl1 SP RETVAL ss f1 hl lt the offset from SP to the f1 field of the return
41. 22 107 189 shift left operator lt lt 120 shift right operator gt gt 120 SHIFT F5 sese 49 shift left assign operator lt lt 123 shift right assign operator gt gt 123 oium 107 shortcuts keyboard 72 Index 239 Show Tool Bar 67 single stepping 34 56 130 190 in assembly language 188 with descent lt F7 gt 53 without descent lt F8 gt 53 SIZ ists meu ees 107 SIZeO zs 107 119 skipping to next loop pass 88 soft break points 35 52 53 183 software CMOS saco mto Deis 25 E A 54 software reset Reset Target 178 source 69 SP stack pointer 18 23 127 131 136 141 142 145 184 203 212 special characters 114 special symbols in assembly language 133 Speed scum asta 108 SRIK LIB eines 148 stack 95 100 105 135 136 137 138 140 141 142 143 144 145 184 190 checking 188 189 190 208 frame 135 136 138 140 141 142 143 145 frame reference point 141 frame reference pointer 23 105 139 140 143 190 203 sott 212 pointer SP 18 127 131 136 141 142 145 184 size auxiliary 65 TUN tIME 2 65 snapshots sss 71 verificat
42. 220 function lookup lt CTRL H gt 37 38 72 73 74 function returns 141 142 143 190 functions sss 78 entry and 190 prototypes 23 38 79 80 82 83 G GESUPRT LIB 222 global initialization 20 21 156 157 global variables 94 188 POLO 88 89 103 example sss 88 Goto lt CTRL G gt 46 49 Graphics Engine 222 greater than operator gt 121 greater than or equal operator gt 121 Technical Reference H Hangup Remote Modem 170 HANGUP TIMEOUT 171 hard break points 35 52 53 hardware reset 25 184 185 header BeginHeader 23 EndHeader 23 function 37 38 193 194 library 193 module 82 83 102 195 Heap 65 heap storage 71 94 212 Help contents 37 2 37 topical 37 help online sensns ieir 71 72 HELP menu 37 38 41 71 72 73 74 HEX files 30 60 210 212 information 212 hexadecimal integer values 113 high current output 16 185 HL 131 135 137 141 142 143 HL primary regster 189 Home
43. 655751 start The other form name n defines a block of n bytes in extended memory In either case the term name is represented by an unsigned long integer containing the 20 bit physical address of the block n bytes eu See XDATA C in the SAMPLES subdirectory for more details 128 The Language Dynamic C 32 v 6 x 6 CHAPTER 6 USING ASSEMBLY LANGUAGE Technical Reference Using Assembly Language 129 Dynamic C permits programing in assembly language Assembly language statements may either be embedded in a C function or entire functions may be written in assembly language C statements may also be embedded in assembly code and refer to C language variables in the assembly code A program may be debugged at the assembly language level by opening the assembly window Single stepping and break points are supported in the assembly window When the assembly window is open single stepping occurs instruction by instruction rather than statement by statement Use the asm and endasm directives to place assembly code in programs For example the following function will add two 64 bit numbers together useix int eightadd char ch1 char ch2 asm 1 1 ix ch2 get dest ptr to hl 1 h 1 62 1 1 e ix ch1 get src ptr to de 1 ix ch1 1 1 b 8 number of bytes XOR a clear carry loop 1
44. 88 s a drm 88 for loop 2222 87 cie i ec 88 83 multithreaded costatements 159 92 Union ETE 28 93 Execute Downloaded Program 170 52 55 56 CUISOF 34 53 54 speed 189 Exit lt ALT F4 gt 45 212 Expr in Call 74 extended memory 18 22 63 66 96 97 98 100 102 111 124 126 127 139 140 145 169 198 199 200 201 202 203 208 data 127 128 204 205 206 functions 204 strings 128 204 205 206 extensions teal timeas reni 25 extern 18 22 83 102 195 230 Index F status register 70 BOs dido ertet ee tas 68 BD iret go e e e 52 53 uonacsesc s UM 50 51 us 36 49 Poet satiat teste 47 E 48 Ee en 34 52 53 ES 34 52 53 34 52 E 102 fatal errors 183 184 185 FILE menu 41 42 43 44 45 Find Case sensitive 47 From cursor sss 47 Reverse 47 Find F5 46 47 Find next lt 5 5 gt 46 49 firsttime 102 150 157 flats duis 157 15
45. Compile to File commands generate a BIN Flash EPROM file containing the BIOS code of the target control ler where the BIOS library functions are located the compiled applica tion code the BIOS s symbol library located near the end of a Flash EPROM and the Flash s simulated EEPROM area located at the end of the Flash It is important to note that the Flash s simulated EEPROM area is copied from the attached target controller or RTI file if available otherwise it is cleared into the BIN file Technical Reference Using Dynamic 31 This option is useful only for externally programmed Flash EPROM types it should not be used to generate BIN files intended for loading to the target controller via the Program Loader Utility PLU After installing the externally programmed Flash EPROM into the target controller communi cation with Dynamic C or the PLU is still possible BIOS App Lib CIrSEE BIN When this option is selected the Compile to File commands generate a BIN Flash EPROM file containing the BIOS code of the target control ler where the BIOS library functions are located the compiled applica tion code the BIOS s symbol library located near the end of a Flash EPROM and the Flash s simulated EEPROM area located at the end of the Flash It is important to note that the Flash s simulated EEPROM area is cleared zeroed in the BIN file This option 1s useful only for externally programmed Flash EPROM
46. Download 169 Download Program This menu choice initiates an XMODEM download on the target side The upload must then be initiated on the PC side using the communication program s XMODEM communication facilities The file must be a downloadable program file created with Dynamic C The DLM verifies the correctness of all data transmitted Execute Downloaded Program This menu choice causes the DLM to shut down the interrupts 1t uses but not the serial interrupt used for serial communication because that interrupt vector is shared by the DLP and jump to the startup code of the DLP from which it will not return The DLM stores the CRC check sum for each segment and the number size and locations of downloaded seg ments The DLM verifies the check sum for each segment before the DLP is invoked The DLP will not run unless all CRCs generally 3 or 4 are correct When the DLM is invoked again with another break request it will start up at 0x2200 regardless of what else is running Hangup Remote Modem This menu choice causes the DLM to issue standard modem hang up and reset commands and then jump to the DLP The DLM Code Password security and timeout periods for the DLM can be controlled during compilation by changing the following macro definitions at the beginning of the DLM source code DLM PASSWORD STR defines the default password If set to the null string then just press ENTER after choosing Enter Password to gai
47. Expr in Call box in the dialog with the expected function call arguments Consider for example the following code X strcpy comment Lower tray needs paper If the text cursor is placed on strepy and the Library Help Lookup command is issued the function assistant will show comment as param eter 1 and Lower tray needs paper as parameter 2 The arguments can then be compared with the expected parameters and the arguments in the dialog can then be modified The function help dialog will probably be needed only when the program mer is unfamiliar with or unsure of a function About The Windows standard About item displays the Dynamic C 32 version number and the Z World Inc copyright notice 74 Dynamic C Environment Dynamic C 32 v 6 x 5 THE LANGUAGE Technical Reference The Language 75 This chapter is not intended to be a C language tutorial The reader is expected to know how to program and to know the basic principles of the language The objective of this chapter is to Present the C language features and 2 Review the differences between C and Dynamic C Most punctuation in the examples is literal it is generally required where examples indicate The C language is case sensitive that is upper case capital letters are distinct from lower case letters The term putchar 15 not the same as PutChar All keywords in C are lower case This manual shows syntax by examp
48. The compiler removes surrounding white space comments tabs and spaces and collapses each sequence of white space in the macro definition into one space It places a before any or to preserve their original meaning within the definition Dynamic C implements the and macro operators The operator forces the compiler to interpret the parameter immediately following as a string literal For example if a macro is defined define report value fmt WN printf value fmt value then the macro in report string s will expand to printf string s Wn string and because C always concatenates adjacent strings the final result is printf string s n string The operator concatenates the preceding character sequence with the following character sequence deleting any white space in between Given define set x y z x H y the macro in set AASC FN 6 will expand to 5 6 FN 84 The Language Dynamic C 32 v 6 x For parameters immediately adjacent to the operator the corresponding argument is not expanded before substitution but appears as it does in the macro call Generally speaking Dynamic C expands macro calls recursively until they can expand no more Another way of stating this is that macro definitions can be nested The exceptions to this rule are 1 Arguments to the and operators are not expanded 2 To prevent infinite re
49. To access extended memory data use function calls to exchange data between extended memory and root memory These functions are provided in the Dynamic C libraries GY See XMEM LIB Extended memory addresses are 20 bit physical addresses the lower 20 bits of a long integer Pointers on the other hand are 16 bit machine addresses They are not interchangeable However there are library functions to convert address formats Dynamic C includes two nonstandard keywords to support extended memory data xstring and xdata The declaration xstring name string 1 string n defines a table of 20 bit physical string addresses as unsigned long ints and corresponding strings The term name represents the 20 bit physical address of the table in an unsigned long int name gt table abc start 20 bit gt addresses stop x on gt off 204 Extended Memory Dynamic C 32 v 6 x The xdata statement has two forms The declaration xdata name value 1 value n defines a block of initialized extended memory data The values must be constant expressions of type char int unsigned int long un signed long float or string name 10 5 73 655751 start The other form xdata name n defines a block of n bytes in extended memory name n bytes
50. Trace into lt F7 gt 34 52 53 type casting 116 118 checking 32 61 79 conversion 116 118 definitions sess 80 80 109 types function aniio 78 U unary minus operator 118 Operators 115 plus operator 118 unbalanced stack 145 undoing changes lt ALT Back SDa Ce eden ez ees 46 uninitialized datas 211 94 UNION 78 93 109 116 unpreserved registers 142 143 145 unsigned 110 unsigned int 128 205 unsigned integer values 113 unsigned long 128 204 205 untitled files 43 Update Watch window lt CTRL U gt 36 54 56 init initialize CoData structures 150 23 110 138 190 using assembly language 21 Dynamic 28 Index 241 V variables global 94 152 initialize CoData structures 150 vertical tiling sss 68 VOI iua eee 78 waitfor 102 110 149 150 151 152 154 157 158 warning reports 61 WarhIngs 22 204 watch dialog Res 36 55 expressions 35 55 56 69 line immediate evaluation 36 list zia uen RES
51. a with b Same Bitwise OR assignment b OR a with b Same b Comma operator This operator unique to the C language is a convenience It takes two operands the left operand typically an expression is evaluated producing some effect and then dis carded The right hand expression 1s then evaluated and becomes the result of the operation This example shows somewhat complex initialization and stepping in a for statement for i 0 j strlen s 1 i lt j i j Because of the comma operator the initialization has two parts 1 set ito 0 and 2 get the length of string s The stepping expres sion also has two parts increment i and decrement 3 The comma operator exists to allow multiple expressions in loop or if conditions Technical Reference The Language 123 Table 5 6 shows the operator precedence from highest to lowest operators grouped together have equal precedence Table 5 6 Operator Precedence Operators Associativity O 1 gt dot left to right amp sizeof right to left x left to right left to right lt lt gt gt left to right I I left to right left to right amp left to right left to right left to right amp amp left to right 11 left to right right to left right to left comma left to right Di
52. an else clause or the end of the if statement An else clause is optional Without an else clause an i statement that finds no true condition will execute none of the controlled statements The switch statement the most complex branching statement allows the programmer to phrase a multiple choice branch differently Recommended form switch expression case const statements break case const statements break case const statements 3 break default Statements DEFAULT The switch expression is evaluated It must have an integer value If one of the const expressions matches the switch expression the sequence of statements identified by the const expression is executed If there is no match the sequence of statements identified by the default label is executed The default part is optional 90 The Language Dynamic C 32 v 6 x Unless the break keyword is included at the end of the case s statements the program will fall through and execute the statements for any number of other cases The break keyword causes the program to exit the switch case statement Notice the colons at the end of the cases and after default Data Data variables and constants have type size structure and storage class Primitive Data Types Basic or primitive data types are provided in Table 5 2 Table 5 2 Dynamic C Basic Data Types Type Description unsigned int unsigned long
53. and release blocks of storage Such dynamic variables are neither local nor global The program accesses dynamic variables through pointers Pointers A pointer is a variable that holds the 16 bit logical address of another variable a structure or a function Variables can be declared pointers with the indirection operator int index In this example the variable index is a pointer to an integer The state ment j index references the value of the integer by the use of the asterisk Pointers may point to other pointers int thing ptr to a ptr to an integer j thing j gets the value ref d by thing Conversely a pointer can be set to the address of a variable using the amp address operator int p thing p amp thing Then p and thing have identical values But note that p and thing do not since p Is a pointer and thing is an int 94 The Language Dynamic C 32 v 6 x It is possible to do pointer arithmetic but this is slightly different from ordinary integer arithmetic Here are some examples typedef xyz arbitrary type amp size xyz 10 p an array and some ptrs amp f p array element 0 5 array element 5 qtt gt array element 6 illegal Beware of using uninitialized pointers Uninitialized pointers can reference ANY location in memory Storing data using an uninitialized pointer can overwrite code or cause a fau
54. assembly instruction if the assembly window 1s being used When one of the two single stepping commands is clicked the current statement executes debugging windows are updated and the execution cursor advances to the next statement in the execution sequence To examine code in greater detail the assembly window may be activated to show the compiled code in assembly language format Disassembled Code Bel XI 28 EF rst 28h 28 8 21022C ld 1 2 02 28 E5 push hl 28cc CDET730 call printf 28cf F1 pop af 2840 EF rst 28h 2841 02 call hitwd 2844 EF rst 28h This option may not be needed if the source code is already assembly language Single stepping through assembly code is instruction by instruction The machine state registers and stack can also be displayed independently at any time Disassembler Besides displaying the assembly code at the execution point Dynamic C also allows code to be disassembled independently of the execution point The Disassemble at Cursor option of the INSPECT menu CTRL F10 disassembles the machine code that represents the code at the screen cursor 34 Using Dynamic C Dynamic C 32 v 6 x This feature allows the compiled code of statements to be previewed long before the code is executed Another command on the INSPECT menu Disassemble at Address ALT F10 allows the machine code to be disassembled at any address except at addresses in the BIOS area
55. assembly code may be written in any C function regardless of whether it is compiled to extended memory or root memory However because the bouncer of an extended memory function introduces four more bytes between the last pushed argument and the return address the actual offset of arguments from the stack pointer depends on whether the code is compiled to extended memory or not Therefore it is impor tant to use the symbolic names of stack based variables instead of numeric offsets to access the variables For example if 3 is a stack variable SP j is the actual offset of the variable from the stack pointer Alternatively if IX is the frame reference pointer ix j specifies the address of the stack based variable Technical Reference Extended Memory 203 Dynamic C issues a warning when it finds assembly code embedded in an extended memory function to discourage inline assembly segments that do not use symbolic offsets for stack based variables The warning can be disabled by appending the keyword xmemok after the asm directive Use symbolic names not numeric offsets All static variables even those local to extended memory functions placed in root memory Keep this in mind if functions have many variables or large arrays Root memory can fill up quickly Extended Memory Data Most of the details of calling extended memory functions are handled by the compiler The situation is more complicated for extended data
56. controller present Before compiling programs this way first create a Remote Target Information RTI file for the specific controller the programs will run on It is essential that the RTI file is created with a target controller identical board type BIOS memory size jumper settings etc to the controller on which programs compiled with the RTI file will run Once a suitable RTI file has been created the Compile to File with RTI File command generates output files the same way Compile to File does A dialog box prompts for which RTI file to open All compiler options apply Technical Reference Using Dynamic C 29 Compiler Options The Compiler selection on the Options menu provides many options Compiler Options Ed Run Time Checking Warning Reports 9 All Pointers Serious Only Stack C None Output Generation Type Checking Create HEX File Also Prototype Zero Time Stamp Demotion i Pointer File Type for Compile to File C Application Only Optimize For C BIOS Application BIN Size C BIOS AppsLibrary C Speed C BIOS App Lib SimEE BIOS AppsLib CIrSEE C Download via DLM Nul Device Bit Bucket Help The File Type for Compile to File options specifically affect the Compile to File and the Compile to File
57. de chl source byte adc a hl add ch2 byte 1 1 result to ch2 addr inc hl inc de djnz loop do 8 bytes endasm return The same program could be written in C but it would be many times slower because C does not provide an add with carry operation adc A C statement may be placed within assembly code by placing a C in column 1 The keyword nodebug can be placed on the same line as asm The main reason for the nodebug option is to prevent Dynamic C from running out of debugger table memory which is limited to about 5 000 break points for the entire program not counting libraries If nodebug is specified for entire function then all the blocks of assembly code within the function are assembled in nodebug mode There is no need to place the nodebug directive on each block 130 Using Assembly Language Dynamic C 32 v 6 x Register Summary Figure 6 1 shows the Z180 s basic register set General Alternate Special Registers Registers Registers A F A F R B IX index D E D IY index H b H 12 SP stack pointer PC program counter Figure 6 1 Z180 Basic Register Set Register A is the accumulator Registers B L are general purpose registers and can be coupled in pairs BC DE HL for 16 bit values Registers B C D and E may also be coupled and called BCDE for 32 bit values Register F flags holds status bits Flags S sign bit Z
58. does two things concurrently The code will output the value of i every half second and the for loop increments i and might do other things The process will go on forever since both costatements are in an endless loop Abort A costatement can terminate itself For this purpose there is the abort statement which is permitted only inside a costatement abort The abort statement in effect causes execution to jump to the very end of the costatement where it exits The costatement will then terminate If the costatement is always on it will restart from the top the next time the program reaches it Ifthe costatement is not always on it becomes inactive since the costatement terminates and will not execute again until turned on by some other software Unnamed costatements are always on 154 Costatements Dynamic C 32 v 6 x Y f statement statement abort 7 statement statement Y Figure 7 6 illustartes the executuion of the abort statement costate statement statement abort statement statement a At Time of Abort b Next Time Figure 7 6 Execution of Abort Statement The CoData Structure Each costatement is associated with a structure of type CoData For this discussion assume that each costatement corresponds to a static CoData structure Use the functions provided to operate costatements Do not use the fields of a CoData structure directly
59. greater a minimum of eight bytes and at least eleven bytes if ptr 15 an auto variable Subfunction calls cannot be nested Function Entry and Exit The following events occur when a program enters a function 1 Save IX on the stack and make IX the stack frame reference pointer 1f in useix mode 2 Create stack space for auto variables or to save register variables 3 Set up stack corruption checks if stack checking is on 4 Notify Dynamic C of the entry to the function so that single stepping modes can be resolved if in debug mode Items three and four consume significant execution time and are elimi nated when stack checking is disabled or if the debug mode is off Disable stack checking if speed is needed during debugging In general avoid using auto variables except when a function must be reentrant Using the IX register as a frame reference pointer useix and useix options results in faster and more compact access to arguments and auto variables especially for char variables The useix option is especially valuable when embedding assembly language inside a C program In this case it is easiest to access the variables using the ix register Use nouseix only for functions that can suspend under the real time kernel 190 Efficiency Dynamic C 32 v 6 x ArPENDIX C SOFTWARE LIBRARIES Technical Reference Software Libraries 191 Dynamic C s function libraries provide a way to bring in only those portions of sys
60. i j body executes if i j OK a b true when b Note that the operator is not the same as the assignment operator 7 common mistake is to write if i j body Here i gets the value of 3 and the if condition is true when i is non zero not when i equals 3 Not equal This binary relational operator yields a Boolean value The result is 1 if the left operand z the right operand and 0 otherwise if j body executes if i j OK a b true when a b Bitwise exclusive OR A binary operator this performs the bitwise XOR of two integer 8 bit 16 bit or 32 bit values int i OxFFFO int j Ox0FFF z irj z gets OxFOOF Technical Reference The Language 121 Bitwise inclusive OR A binary operator this performs the bitwise OR of two integer 8 bit 16 bit or 32 bit values int i 0 int j OxOFFO0 zz33 3 z gets OxFFFO amp amp Logical AND This is a binary operator that performs the Bool ean AND of two values If either operand is 0 the result is 0 FALSE Otherwise the result is 1 TRUE E Logical OR This is a binary operator that performs the Boolean OR of two values If either operand is nonzero the result is 1 TRUE Otherwise the result is 0 FALSE Conditional operators This is a three part operation unique to the C language It has three operands and the two operator symbols and If the first
61. in code space 168 Remote Download Dynamic C 32 v 6 x The Download Manager DLM is found in source code for example DIM 20 the SAMPLES AASC subdirectory The DLM may be modified in any way Once the DLM is installed on the target compile it to flash or burn an connect the target to the PC s serial port modem connection is acceptable Start the communication program Then issue a break request ALT B in ProComm The break request will cause the DLM to restart The Download Manager displays the following menu continuously Download Manager Menu 1 Enter Password 2 Set Password 3 Report DLM Parameters 4 Download Program 5 Execute Downloaded Program 6 Hang up Remote Modem Enter Choice Enter Password Choose Enter Password before enabling choices 2 3 or 4 Set Password Choose Set Password press 2 to change the password The DLM will prompt for a new password twice for verification The DLM must allow password changes See below Report DLM Parameters This menu choice causes the DLM to report some memory mapping parameters auch as the following DLM Root Code Top 00 7579 DLM Root Data Bottom 7 7 5 DLM Xmem Code 0000D000 DLM Xmem Data Bottom 0008 000 Dynamic C requires these parameters to compile a downloadable program correctly Dynamic C prompts for these values when a program is compiling to a DLP file Actual values will differ Technical Reference Remote
62. interrupt enable shared long counter shared between different interrupt levels define ticks 2304 9 216MHz 20 005 sec main counter OL initialize counter PRT1 init ticks 5 ms interrupts for if counter gt 5000 break outport ENB485 counter amp 64 IRES TCR TDE1 disable count down IRES TCR TIE1 disable interrupts printf Counter has reached 5000 n this interrupt routine increments the counter PRT1 VEC ccc interrupt reti ccc inport TCR inport TMDRIL clear TIF EI counter counter 4 1 int PRT1 init int tc IRES TCR TDE1 disable count down IRES TCR TIEL disable interrupts outport TMDR1L tc outport TMDR1H tc gt gt 8 set data reg outport RLDR1H tc gt gt 8 set reload counter outport RLDR1L tc set reload counter ISET TCR TDE1 enable count down ISET TCR TIEL enable interrupts EI The interrupt routine ccc increments a counter every 5 milliseconds The program prints a message and stops as soon as the counter reaches 5000 Technical Reference Interrupts 165 166 Interrupts Dynamic C 32 v 6 x 9 9 REMOTE DOWNLOAD Technical Reference Remote Download 167 Z World provides field programmability for its controllers A downloadable program file can be created by selecting the appropria
63. loop A while loop tests at the beginning and may execute zero or more times while expression 110 The Language Dynamic C 32 v 6 x xdata This keyword declares block of data in extended memory There are two forms xdata name value 1 value n xdata name n The name of the block represents the 20 bit physical address of the block The value list of the first form may include constant expressions of type int float uint long ulong char and quoted strings xmem lIndicates that a function is to be placed in extended memory xmem int func memmap xmem xmemok Indicates that assembly language code embedded in a C function can be compiled to extended memory asm xmemok endasm This keyword does not apply to C functions or to memmap xstring This keyword declares a table of strings in extended memory The table entries are 20 bit physical addresses as unsigned long integers The name of the table represents the 20 bit address of the table as an unsigned long integer xstring name string 1 string n yield Used in a costatement this keyword causes the costatement to pause temporarily allowing other costatements to execute The yield statement does not alter program logic but merely postpones it for costate long computation yield Gor See Chapter 7 Costatements Technical Reference The Language 111 Names Names identify varia
64. manual and oY the Dynamic C Application Frameworks manual for more details about the virtual driver and the delay functions 152 Costatements Dynamic C 32 v 6 x Yield costatement can yield to other costatements The yield statement is permitted only inside a costatement yield The yield makes an unconditional exit from a costatement as shown in Figure 7 4 costate statement statement yield Fy ae statement statement v Figure 7 4 Unconditional Yield Exit from Costatement The next time the program executes the costatement it will resume at the statement following the yield as shown in Figure 7 5 Compare this action with the description of the abort statement in the next section costate statement statement yield gt statement statement Figure 7 5 Resumption of Program after Yield Technical Reference Costatements 153 Example is a loop containing two costatements while 1 costate for i 0 i lt 30000 itt some program code yield costate waitfor DelayMs 500 printf i d n i Exactly one iteration of the for loop gets executed on each pass through the endless while loop The second costatement checks whether 500 mil liseconds have passed since the program first entered it It will print the value of i if 500 milliseconds have passed The result is a loop that
65. module known to the application With proper function prototypes and variable declarations a module header ensures proper type checking throughout the entire application program The Body Every line of code after the EndHeader comment belongs to the body of the module until 1 end of file or 2 the BeginHeader comment of another module Dynamic C compiles the entire body of a module if any of the names in the key are referenced used anywhere in the application An Example Module Notice in the following extremely contrived example that the header contains only function and variable declarations not definitions Any function or variable which is actually defined in a header will be compiled into every application that uses the library containing the header whether or not the specific function or variable is ever referenced BeginHeader foo bar foobar struct foo int i int j declaration extern float bar declaration int foobar int b struct foo pf prototype EndHeader float bar variable definition here function definition follows nodebug int foobar int b struct foo pf bar b float pf i float gt 3 return bar b gt 0 5 To minimize waste Z World recommends that a module header contain only macros prototypes extern variable declarations or other declara tions that do not directly generate code or data Define code and data only in the body of a mod
66. name Adds a function or another function chain to a function chain e dif constant expression elif constant expression else endif These directives control conditional compilation Combined they can form a multiple choice if When the condition of one of the choices is met the Dynamic C code selected by the choice is compiled whatever it may be Code belonging to the other choices is ignored entirely main if BOARD TYPE define product Ferrari elif BOARD TYPE define product Maserati Technical Reference The Language 125 elif BOARD TYPE define product Lamborghini else define product Chevy The e1if and else directives are optional Any code between an else and an endif is compiled when all of the expressions are false ifdef name ifndef name Similar to i above these directives enable and disable code compilation respectively based on whether the name has been defined with a define directive interleave nointerleave Controls whether Dynamic C will intersperse library functions with the program s functions during compilation nointerleave forces the user written functions to be compiled first e KILL name To redefine a symbol found in the BIOS of a controller first kill the prior name makechain chain name Creates a function chain When a program executes the function chain named in this directive all o
67. push and pop compilation modes class static static local vars are default class push auto auto local vars are default class pop now back to static register Declares the storage class of a variable The variable has the speed of a static variable yet can be used in reentrant functions int func register float x y register int i Technical Reference The Language 105 ret lIndicates that an interrupt service routine written C uses the ret instruction interrupt ret isr CoS See also interrupt reti Indicates that an interrupt service routine written in C uses the reti instruction interrupt reti isr of See also interrupt retn lIndicates that an interrupt service routine written in C uses the retn instruction interrupt retn isr Go See also interrupt return Explicit return from a function For functions that return values this will return the function result void func if expression return float func int x float temp return temp 10 1 root Indicates a function is to be placed in root memory root int func memmap root asm root endasm 106 The Language Dynamic C 32 v 6 x segchain ldentifies a function chain segment within a function int func int arg int vec 10 segchain GLOBAL INIT for 1 0 1 lt 10 1 vec i 0 This example adds a segmen
68. serial communication channels clocks and timers Z World controllers are programmed using an enhanced form of the well known C programming language Dynamic C Why C Programmable controllers provide the most flexible way to develop a control system And C is the preferred language for embedded systems programming It is widely known and produces efficient and compact code Because C is a high level language code can be developed much faster than with assembly language alone And C allows programming at the machine level when necessary The Nature of Dynamic C Dynamic C integrates the following development functions Editing Compiling Linking Loading Debugging into one program In fact compiling linking and loading are one function Dynamic C has an easy to use built in text editor Programs can be executed and debugged interactively at the source code level Ultimately EPROM files or down loadable files can be created for programs that will run stand alone in the controller Pull down menus and keyboard shortcuts for most commands make Dynamic C efficient Because all the development functions are integrated it 15 possible to switch from one function to another with a simple keystroke Dynamic C also supports assembly language programming It is not necessary to leave C or the development system to write assembly lan guage code C and assembly language may be mixed line by line in a program For debugging Dynamic C provi
69. sysForceSupRst causes a super reset GY Appendix G Reset Functions 26 Introduction to Dynamic C Dynamic C 32 v 6 x 2 3 UsiNG Dynamic Technical Reference Using Dynamic 27 The Dynamic C 32 compiler can generate up to 512 KBytes of code and 512 KBytes of data and fully supports extended memory To run Dynamic C 32 under Windows double click the Dynamic C 1con in the Dynamic C program group or use one of the other standard Windows methods to launch Dynamic C 32 Installation Dynamic C 32 must be installed on a hard disk and requires about 32 MBytes of disk space The PC must be running Windows 95 98 2000 Me or NT on a machine having a 386SX processor or better At least 16 Mbytes of RAM are required to run Dynamic C and there must be one free serial port to communicate with the target controller n Refer to the installation instructions in Chapter 1 Installing Dynamic C Writing Programs A Dynamic C text window is used to enter the program text line by line Fragments of program text may be cut and pasted from one application to another for instance from Microsoft WORD to Dynamic C or from one Dynamic C text window to another Dynamic C allows text to be selected and scrolled and program files can be created and saved using the same techniques as in other Windows programs Compiling Programs Dynamic C provides several ways to compile programs as shown in the Compile men
70. the From cursor checkbox to choose whether to search the entire file or to begin at the cursor location If Case sensitive is selected the search will only find occurrences that match exactly Otherwise the search will find matches having either uppercase or lowercase letters For example switch Switch and SWITCH would all match If Reverse is selected the search will occur in reverse that is the search will proceed toward the beginning of the file rather than toward the end of the file The keyboard shortcut for Find is F5 Technical Reference Dynamic C Environment 47 Replace Replaces specified text The following dialog box appears in response to the Replace command Find Change to From cursor Case sensitive Selection only Reverse No prompt Change at Help Cancel Type the text to be found in the Find drop down text box or click on the down arrow icon to the right of the box and a drop down list of previous Find text is displayed If you click on a previous Find text it will become selected and ready for editing in the Find box Then type the text to substitute in the Change to drop down text box or select and or edit a previous Change to text from the drop down list In this example the Replace command will find an occurrence of the word reg7 and replace it with reg9 Use the From cursor checkbox to choose whether to search the entire
71. the structure In the following structure for example struct s int x int y int z the embedded assembly expression s x evaluates to 0 sty evaluates to 2 and s z evaluates to 4 regardless of where structure s may be 134 Using Assembly Language Dynamic C 32 v 6 x In nested structures offsets can be composite as shown here struct s int x 0 struct a sta 2 int b a b 0 statb 2 int c atc 2 statc 4 Standalone Assembly Code A standalone assembly function is one that is defined outside the context of a C language function It can have no auto variables and no formal parameters Dynamic C always places a standalone assembly function in root memory When a program calls a function from C it puts the first argument into a primary register If the first argument has one or two bytes int uint char pointer the primary register is HL with register H containing the most significant byte If the first argument has four bytes 1ong ulong float the primary register is BCDE with register B containing the most significant byte Assembly language code can use the first argument very efficiently Only the first argument is put into the primary register while a arguments including the first are pushed on the stack C function values return in the primary register if they have four or fewer bytes either in HL or BCDE Assembly language allows assumptions to be mad
72. union body or encloses a function chain segment Extended Memory Data Most of the details of calling extended memory functions are handled by the compiler The situation is more complicated for extended data To access extended memory data use function calls to exchange data between extended memory and root memory These functions are provided in the Dynamic C libraries An extended memory address is represented by an unsigned long integer which contains the 20 bit physical address Pointers on the other hand are 16 bit machine addresses They are not interchangeable However there are library functions to convert between these address formats oY See XMEM LIB Technical Reference The Language 127 Dynamic C includes two nonstandard keywords to support extended memory data xstring and xdata The declaration xstring name string 1 string n defines name as the extended memory address of a table of extended memory addresses as unsigned long ints and corresponding strings name table abc start 20 bit gt addresses stop x on gt off The xdata statement has two forms The declaration xdata name value 1 value n defines a block of initialized extended memory data The values must be constant expressions of type char int unsigned int long un signed long float or string name 10 5 73
73. will however work perfectly well without a mouse although it may be a bit tedious It is also possible to scroll up or down through the text using the arrow keys or the PageUp and PageDown keys or the Home and End keys The left and right arrow keys allow scrolling left and right 40 Dynamic C Environment Dynamic C 32 v 6 x Arrows Use the up down left and right arrow keys to move the cursor in the corresponding direction The CTRL key works in conjunction with the arrow keys this way CTRL Left Move to previous word CTRL Right Move to next word CTRL Up Scroll up one line text moves down CTRL Down Scroll down one line Home Moves the cursor backward in the text Home Move to beginning of line CTRL Home Move to beginning of file SHIFT Home Select to beginning of line SHIFT CTRL Home Select to beginning of file End Moves the cursor forward in the text End Move to end of line CTRL End Move to end of file SHIFT End Select to end of line SHIFT CTRL End Select to end of file Sections of the program text can be cut and pasted add and delete or new text may be typed in directly New text 1s inserted at the present cursor position or replaces the current text selection The Replace command in the Edit menu is used to perform search and replace operations either forwards or backwards Menus Dynamic C has eight command menus File Edit Compile Run Inspect Options Window Help as well as the standard Windows
74. with the target controller The COM port baud rate and number of stop bits may be selected The transmission mode radio buttons also affect communication by controlling the overlap of compilation and downloading In the No Background TX mode Dynamic C will not overlap compila tion and downloading This is the most reliable mode but also the slowest the total compile time is the sum of the processing time and the communication time In the Full Speed Bkgnd TX mode Dynamic C will almost entirely overlap compilation and downloading This mode is the fastest but may result in communication failure The Sync Bkgnd TX mode provides partial overlap of compilation and downloading This is the default mode used by Dynamic C Show Tool Bar The Show Tool Bar command toggles the tool bar on or off alal wg Edit Compite Assemb Regs Stack Dynamic C remembers the toolbar setting on exit Technical Reference Dynamic C Environment 67 Table 4 6 explains what the toolbar buttons mean Table 4 6 Dynamic C Toolbar New file Find Open file Replace Save file Repeat Find or Replace Print Edit Switch to Edit mode Print preview Compile Compile to RAM Cut delete Assemb Toggle assembly window Paste Stack Toggle stack window Copy Regs Toggle register window Show Help contents Save Environment The Save Environment command get
75. zero bit slz H Le H half carry P V parity or overflow 7 6 5 4 3 2 1 9 N negative op C carry The alternate set of registers A L is often used to save and restore register values eo Refer to the Zilog Z180 MPU User s Manual for instruc tions to swap register sets The PC is the program counter SP is the stack pointer The IX and IY registers are index registers The I register is the interrupt vector register The R register may be ignored Dynamic C uses the HL register pair 1 to pass the first 16 bit argument and 2 to return a 16 bit function result Dynamic C uses the BCDE register group 1 to pass the first 32 bit argument and 2 to return a 32 bit function result The Z180 has many other special purpose registers General Concepts Place a body of assembly code between the asm directives asm options 1 endasm The asm directive accepts options GY Directives in Chapter 5 The Language for details Technical Reference Using Assembly Language 131 Comments Comments in embedded assembly code starts with a semicolon The assembler ignores all text from the semicolon to the end of line Labels A label is a name followed by one or two colons A label followed by a single colon is whereas one followed by two colons is g obal local label is not visible to the code out of the current embedded assembly segment that is co
76. 0 remote download 33 168 169 170 171 172 173 210 Remote Target Information 222 remote target information RTI file 29 30 31 32 40 50 51 76 172 210 Replaces 48 Change All 48 From cursor 2 22 2222 48 No 48 48 Selection only 48 Replace lt gt 41 48 replacing text 46 48 49 Report DLM Parameters 169 reserve memory 63 65 238 Index reset 25 26 36 37 216 217 218 hardware 25 power fail eens 25 regular 25 SOfLWATO suse 54 SUPET eret 216 watchdog 22022 25 Reset 26 SysIsPwrFail 26 SysIsSuperReset 26 _SYSISWDTO 26 reset generation 218 Reset program lt CTRL F2 gt 52 54 Reset target lt CTRL Y gt 52 54 resetting program 54 restarting 25 26 program erit teneri 54 target controller 54 ret 105 106 141 144 162 163 105 106 144 162 163 retn 105 106 144 162 163 return 106 109 141 162 return address 136 140 returning to edit mode 36 reverse searching
77. 00 bps Features which were formerly only available in the Deluxe version are now standard Dynamic C 32 supports programs with up to 512K in ROM code and constants and 512K in RAM variable data with full access to extended memory The Three Manuals Dynamic C 32 is documented with three reference manuals Dynamic C 32 Technical Reference Dynamic C 32 Application Frameworks Dynamic C 32 Function Reference This manual describes how to use the Dynamic C development system to write software for a Z World programmable controller The Application Frameworks manual discusses various topics in depth These topics include the use of the Z World real time kernel costatements function chaining and serial communication The Function Reference manual contains descriptions of all the function libraries on the Dynamic C disk and all the functions in those libraries Please read release notes and updates for late breaking oS information about Z World products and Dynamic C Technical Reference About This Manual ix Assumptions Assumptions are made regarding the user s knowledge and experience in the following areas e Understanding of the basics of operating a software program and editing files under Windows on a PC Knowledge of the basics of C programming Dynamic C is not the same as standard C 2 Fora full treatment of C refer to the following texts The C Programming Language by Kernighan and Ritchie C
78. 121 gt ODerator eroe esee 121 gt Operator 121 gt gt 120 gt gt 123 2 122 0 Gn 134 cient 141 SP 136 137 139 140 141 145 203 array indices 116 backslash 132 for character literals 84 OPELALON 121 A 123 Index 223 _aascInitDF 220 GLOBAL INIT 107 150 156 157 220 function chain 20 initializing CoData 150 prot init 185 216 prot recover 185 216 _ 87 _ 220 _ 87 22 2 4 4 220 220 Sys 25msPOstEI 220 SVS BOO tete 220 SSS TOl 220 Sys 781POostElI 220 SysIsPwrFail 26 217 _sysIsSuperReset 26 185 216 217 _SYSISWDTO 26 217 curly 78 Operator 122 123 operator 122 bitwise complement operator 117 DI COLO 213 27629655 a 213 2765 x 213 abort 100 149 150 154 156 About Dy
79. 16 17 18 19 20 21 22 23 24 25 33 35 76 80 91 95 99 113 133 135 C statements embedded in assem bly code 130 C 91 C variables in assembly language 134 cascaded windows 68 69 90 100 101 102 109 case sensitive searching 47 48 49 cast operator type 118 Index 225 CBAR 96 97 98 198 199 200 201 202 213 CBR common base register 56 96 97 98 140 145 162 198 199 200 201 202 203 char 80 101 111 128 190 205 Characters asso esee 114 113 114 constants 114 embedded quotes 114 nonprinting values 114 special values 114 Check sum ius 170 checking array bounds 188 208 pointers 94 188 208 stack 188 189 190 208 iis ed iei rte eere 32 CY PON en emet 32 79 ChES t ree 157 ChkSum2 eese 157 Clear Watch Window 54 55 clipboard 46 47 clocked serial communication 24 16 Close CTRL F4 43 closing a file 42 43 CoBegin 150 156 157 CoData 149 150 155 156 157 158 160 description 156 general usage 158 Initialization
80. 16 bit Z180 addresses to 20 bit memory addresses Three MMU registers CBAR CBR and BBR divide the logical space into three sections and map each section onto physical memory as shown in Figure 5 4 CBAR Common Bank Area Register FFFFF CBR Common Base Register BBR Bank Base Register LE lt CBR CBAR ge Com Bank y XMEM gt 000 d C000 A000 8000 ROOT 6000 4000 M lt BBR 2000 PES 0000 222 9 BIOS 00000 Logical Space Physical Space Figure 5 4 Z180 On Chip Memory Management Unit MMU Registers The logical address space is partitioned on 4 KByte boundaries The upper half of CBAR identifies the boundary between the ROOT memory and XMEM The lower half of CBAR identifies the boundary between the BIOS and the The start of the BIOS is always address 0 The two base registers CBR and BBR map XMEM and ROOT respectively onto physical memory Given a 16 bit address the Z180 uses CBAR to determine whether the address is in XMEM BIOS or ROOT If the address is in XMEM the 7180 uses the CBR as the base to calculate the physical address If the address is in ROOT the Z180 uses the BBR If the address is in the BIOS the 7180 uses a base of 0 96 The Language Dynamic C 32 v 6 x A physical address is essentially base 12 logical address Figure 5 5 shows the address locations 15 121 TT
81. 1s accomplished in software Floating point add subtract and multiply take about 100 microseconds with a 9 216 MHz clock Division is somewhat slower 24 Introduction to Dynamic Dynamic C 32 v 6 x Physical Memory Depending on the product and its jumper wiring Z World controllers can address up to 512 KBytes of ROM and 512 KBytes of RAM It is often not necessary to have memory chips this large on miniature controllers Typical SRAM chips have 32 or 128 KBytes Watchdog Timer Programs sometimes fail or get stuck Z World controllers provide a watchdog timer that will initiate a hardware reset unless the software signals the timer periodically A failed program will generally fail to hit the watchdog timer The watchdog timer can help the controller recover from system hang ups endless loops and hardware upsets resulting from electrical transients The watchdog timer provides a natural way to recover from most fatal software errors Real Time Operations Dynamic C includes two real time function libraries and extensions to the C language to support real time operations Refer to Chapter 7 Costatements and to the Dynamic C GY Application Frameworks manual for more information about the real time kernels Restart Conditions Z World embedded applications need to differentiate the causes of reset and restart Possible hardware resets are listed in Table 2 2 Table 2 2 Hardware Resets Regular Reset The
82. 2 164 168 182 198 201 202 208 210 212 213 programming real time 17 21 promotion serene 116 protected variables 17 18 22 105 185 189 216 prototypes 195 function 23 38 79 80 82 83 in headers 82 194 PSW TIMEOUT 170 punctuation 127 105 125 126 Q quitting Dynamic C lt ALT F4 gt 42 45 R 64 98 164 198 201 211 212 213 static 18 19 22 25 29 37 40 51 64 98 164 168 198 201 211 212 216 Index 237 read only memory 18 19 22 25 29 30 31 32 37 40 50 51 64 98 99 112 164 168 182 198 201 202 208 210 212 213 readireg 22222 163 real time extensions esses 25 kernel RTK 17 25 190 library aoi 25 25 programming 17 21 Syste Scianni nea 148 redoing changes lt ALT SHIFT backspace gt 46 reentrant functions 188 190 Register Window 70 registers 18 105 136 138 139 189 190 SC 131 snapshots sss 70 variables sss 94 window 16 33 68 69 70 regular reset sss 25 relational operators 120 121 Release Notes txt 222 reload 18
83. 56 for repeated evaluation 36 window 16 33 35 36 54 55 68 69 adding items 54 55 clearing 2 2220222 2 55 deleting items 54 55 updating 122222 56 watch expression Add to 55 Del from top 55 Evaluate 2 2 55 WATCH menu 36 Watch window 69 watchdog sss 26 onde ete esent 25 25 26 watchdog timer 25 184 185 217 218 while 78 86 100 101 110 203 WINDOW menu 41 65 68 69 70 71 windows 14 28 40 68 assembly 16 33 34 68 69 70 130 242 Index 68 69 debugging 33 34 information 65 68 69 71 2222 22 68 69 MINIMIZE 69 program group 14 register 16 33 68 69 70 Ruts ce sei 14 stack 16 33 34 68 69 70 STDIO 16 33 62 68 69 182 183 tiled horizontally 68 69 tiled vertically 68 watch 16 33 35 36 54 55 56 68 69 X xdata 22 111 128 204 205 128 206 xgetfloat 22 205 xmem 66 96 97 98 111 126 139 199 200 201 202 203 XMEM reserve 66 XMEM
84. 60 Zero Time Stamp 60 P PageDown 40 PageUp key e 40 parallel processes 18 21 passing arguments 18 23 95 135 136 141 142 143 passwords DLM 170 172 P dsleasn upper oit 47 pasting text lt CTRL V gt 46 47 PC oie 16 52 67 134 COM 29 169 serial 29 PC program counter 184 physical address 97 199 physical memory 25 63 64 96 97 98 111 127 128 198 199 200 201 202 203 204 205 206 PEU aH 180 cautions and disclaimers 176 179 common problems 180 177 Generic upload 179 Help eee 177 Manual software reset 180 OPEN voce irre e 180 program mode 178 Dynamic C 32 v 6 x Reset Target 178 180 Resetting Target 178 Reuse of programming port 180 Run after upload 179 180 TUN mode eee 180 Serial Options 177 software reset 178 180 Upload 179 upload to physical address 179 Uploading 177 use of ZINT VEC 180 use of reload vec 180 PLU Program Loader Utility 176 222 PRGLOADR EXE plus operator 118 pointer c
85. 7 158 functions 157 158 flash 5 sos 98 198 201 flash 29 37 40 51 98 99 112 168 198 201 202 flash memory 18 19 float 36 80 102 111 128 205 113 floating point speed 24 TOES M i eo ME 78 103 character literals 114 87 87 reference point 141 reference pointer 23 105 139 140 143 190 203 ote 94 free 2 222 65 Free 17 nurni nai 65 free Size musste me 65 Dynamic C 32 v 6 x Full Speed Bkgnd TX 67 function calls 34 74 79 86 100 127 135 136 140 141 142 145 190 indirect 2222 143 function chains 18 19 20 107 126 150 156 157 216 220 _aascInitDF 220 GLOBAL INIT 220 _srtk_hightask 220 Srtk lowtask 220 SYS 25MS seen 220 Sys 25msPostBEI 220 288 390 220 eee 220 _sys_781PostE 220 sysSupRstChain 26 220 function headers 193 194 descriptive 38 function headers descriptive 37 function help 194 function libraries 17 23 76 77 82 102 127
86. A Reference Manual by Harbison and Steel Knowledge of basic 780 assembly language and architecture GY For documentation from Zilog refer to the following texts Z180 MPU User s Manual Z180 Serial Communication Controllers Z80 Microprocessor Family User s Manual Acronyms Table 1 lists the acronyms that may be used in this manual Table 1 Acronyms EPROM Erasable Programmable Read Only Memory EEPROM Electronically Erasable Programmable Read Only Memory LCD Liquid Crystal Display LED Light Emitting Diode NMI Non Maskable Interrupt PIO Parallel Input Output Circuit Individually Programmable Input Output PRT Programmable Reload Timer RAM Random Access Memory RTC Real Time Clock SIB Serial Interface Board SRAM Static Random Access Memory UART Universal Asynchronous Receiver Transmitter x About This Manual Dynamic C 32 v 6 x Icons Table 2 displays and defines icons that may be used in this manual Icon d Refer to or see Note Table 2 Icons Meaning Icon Meaning I ease contact T Caution A High Voltage Factory Default Conventions Table 3 lists and defines typographic conventions that may be used in this manual Table 3 Typographical Conventions Example Description while Courier font bold indicates a program a fragment of a program or a Dynamic C keyword or phrase IN O01
87. Application Only BPF Optimize For BIOS Application BIN Size BIOS AppsLibrary BIN C Speed C BlOS App Lib SimEE C BIOS AppsLib CISEE BIN C Download via DLM Nul Device Bit Bucket Help Cancel The Run Time Checking options group control the generation of code for checking the application s run time operation When selected the code generated by each of these options will cause a run time error if a problem is detected These options increase the amount of code and cause slower execution but they can be valuable debugging tools These options are described in Table 4 2 Table 4 2 Run Time Checking Options Array Indices Checks array bounds This feature adds code for every array reference Pointers Check for invalid pointer assignments A pointer assignment is invalid if the code attempts to write to a location marked not writeable Locations marked not writeable include the entire root code segment This feature adds code for every pointer reference Stack Check for stack corruption Stack errors are reported on return from the function Technical Reference Dynamic C Environment 59 The Output Generation options group control miscellaneous aspects of the compiler s code and file output generation Create HEX File Also When this option 15 selected the Compile menu s Compile to File and Compile to File with RTI File commands also create an Intel
88. C 32 v 6 x Dynamic C uses the reti instruction to return from an interrupt created by a Z180 peripheral The reti instruction creates a particular type of bus cycle that the Z180 peripheral recognizes as acknowledging the comple tion of the interrupt service routine The ret type of return can be used for interrupts created by devices not in the Z180 scheme although it would not hurt to use reti The only consideration would be the possibility of affecting devices in the Z180 family that might be part of the system that is accidentally sending the interrupt acknowledge signal to them before servicing the device s interrupt The retn instruction is used to return from a nonmaskable interrupt and it restores the interrupt state to the state prior to the nonmaskable interrupt More information on the Z180 interrupts can be found in the ew gt Zilog manuals If an interrupt routine is short or cannot be interrupted then interrupts can be left disabled throughout its execution However to keep interrupt latency the amount of time that another interrupt request must wait before service at a minimum avoid disabling interrupts for long periods In addition communication with the Dynamic C host system will be disrupted if interrupts are off for long periods although the communication link can tolerate interrupts being off for approximately 0 5 seconds Two functions enable and disable interrupts void EI enable interrupts void D
89. C provides facilities for writing interrupt service routines ISRs in C and for setting up ISRs at compile time Interrupt service routines may be written in assembly language Gu See Chapter 6 Using Assembly Language A function that services interrupts must save and restore registers includ ing the memory management unit s CBR register The keyword interrupt applies to a C function that services interrupts C language ISRs save and restore registers Three additional keywords ret reti or retn can be used to select the return from interrupt instruction that will be performed The following example shows an interrupt service routine in skeletal form interrupt reti iservice reenable interrupts optional body of code return optional at end of code When the above return is executed the final two machine level instruc tions after the registers have been restored are as follows ei enable interrupts reti return from interrupt If the ret keyword were to be used then the final two instructions would be as follows ei enable interrupts ret return from interrupt If the retn keyword were to be used the final instruction would be as follows retn return from interrupt No ei is necessary for retn since this instruction restores the previous state of the interrupts If none of the keywords for the type of return 18 given the default ret is assumed 162 Interrupts Dynamic
90. Dynamic C32 for Zilog Z180 microprocessors Version 6 x Integrated C Development System Technical Reference 019 0083 020330 B Dynamic C 32 v 6 x Technical Reference Part Number 019 0083 020330 B Printed in U S A Copyright O 2002 Z World Inc All rights reserved Z World Inc reserves the right to make changes and improvements to its products without providing notice Trademarks Dynamic C is a registered trademark of Z World Inc PLCBus is a trademark of Z World Inc Windows is a registered trademark of Microsoft Corporation e Modbus is a registered trademark of Modicon Inc Hayes Smart Modem is a registered trademark of Hayes Microcom puter Products Inc Notice to Users When a system failure may cause serious consequences protecting life and property against such consequences with a backup system or safety device is essential The buyer agrees that protection against consequences resulting from system failure is the buyer s responsibility This device is not approved for life support or medical systems Company Address Z World Inc 2900 Spafford Street Z Y VOKLD Davis California 95616 6800 USA Telephone 530 757 3737 Facsimile 530 753 5141 Web Site http www zworld com E Mail zworld zworld com TABLE OF CONTENTS About This Manual ix Chapter 1 Installing Dynamic C 13 Installation Requirements ccscceseesseeseeseceseeceeeseeseeeseeeeeeseeseeeseeae
91. F 30 211 argument passing 18 23 95 135 136 141 142 143 modifying value 95 arguments esee 23 arrange icons command 68 arranged 69 92 93 95 bounds checking 188 characters 113 114 indices sta 116 subscripts 0 222222 92 arrow keys 40 41 for cursor 41 for editing text 41 Dynamic C 32 v 6 x ASCI serial port assembly code multi line macro 134 assembly language 16 21 34 53 83 124 130 131 132 133 140 141 142 143 144 145 188 203 Zasm directive 21 Zendasm directive 21 embedding C statements 130 Assembly window 70 assembly window 16 33 34 68 69 70 130 assign operator 122 assignment operators 122 123 associativity 115 124 auto 18 19 23 24 100 125 134 135 136 138 139 188 189 190 208 Auto Open STDIO Window 62 auxiliary stack 184 212 Qu rS 65 B backslash character literals 114 continuation in directives 124 backup 37 basic unit of a C program 78 battery
92. Global variables are by definition static Local variables are static by default unlike standard C int func 4 int i static by default static float x explicitly static struct lIndicates the beginning of a structure definition struct int x int y abc defines a struct object typedef struct int x int y xyz defines a struct type xyz thing and a thing of type xyz Structure definitions can be nested subfunc Begins the definition of a subfunction subfunction encapsulates a useful code sequence and reduces the amount of storage required by the parent function func int aname subfunc aname k inport x k 4 aname CS See Appendix B Efficiency for details 108 The Language Dynamic C 32 v 6 x switch Indicates the start of a switch statement switch expression case const break case const break case const break default The switch statement may contain any number of cases It com pares a case constant expression with the switch expression If there is a match the statements for that case execute The default case if it is present executes if none of the case constant expres sions match the switch expression If the statements for a case do not include a break return continue or some means of exiting the switch statement the cases following the selected case will execute too regardless of whether their c
93. I disable interrupts The following function returns 1 if interrupts are enabled and 0 otherwise int iff The following functions read and set the 8 bit Z180 I register uint readireg void setireg int value Normally the I register points to a 256 byte vector table defined by the debugger startup code If the location of the table changes copy the interrupt vectors used by the debugger to the new area before modifying the I register Technical Reference Interrupts 163 Interrupt Vectors There are two types of Z180 interrupt vectors The first type which handles modes 0 1 and nonmaskable interrupts requires that a jump instruction be inserted at the vector location because control is actually transferred to that location This type includes the following vectors 08h jP restart service mode 0 int 38h interruptO service mode 1 int 66h jP nmi service nonmaskable Use the following preprocessor directives to set the vectors at 38 and 66 JUMP_VEC RST38 VEC function name JUMP_VEC NMI VEC function name The term RST38_VEC refers to the interrupt at 38 and NMI_VEC refers to the interrupt at 66 Note that jump instructions are not usually stored at these locations because these locations are usually in the library EPROM area and cannot be changed Instead these locations jump to a relay vector in RAM which is actually modified The second type handles the Mode 2 interrupt used by Z180 periphera
94. LLIB 22 127 xmem2root csse 205 xmemok 111 124 139 204 XMODEM 168 170 XOR assign operator 123 xstring 22 111 128 204 205 een 22 205 Y yield 111 149 150 153 154 Z Z180 16 17 21 24 70 96 131 164 188 189 198 199 200 201 Z 80 5 24 163 164 Zero Time Stamp 60 222 Zilog 16 24 163 Dynamic C 32 v 6 x Z WORLD Z World Inc 2900 Spafford Street Davis California 95616 6800 USA Telephone Facsimile Web Site E Mail 530 757 3737 530 753 5141 http www zworld com zworld zworld com Printed in U S A
95. OM or flash ROOT DATA 4 FFFF XMEM E000 ROOT DATA Edo m oe RARE TT gt EPROM LXMEM 2 ROOT CODE gt ROOT CODE 0000 BIOS gt 5 2 00000 Logical Space Physical Space Figure D 4 Memory Layout with Code in ROM or Flash Memory management in Dynamic C is automatic The Dynamic C compiler emits code that will set the mapping registers Control over Memory Mapping The programmer controls how Dynamic C allocates and maps memory AY Refer to the discussion of the OPTIONS menu in Chapter 4 The Dynamic C Environment Extended Memory Functions Physical memory is divided into 4K pages Two consecutive pages are visible in the extended memory window XMEM at any one time Addi tional code is required to handle calls to functions or jumps to locations not currently mapped in the extended memory window A program can use many pages of extended memory Under normal execution code in extended memory maps to the logical address region E000 to F000 the lower half of XMEM As execution approaches F000 the pages are shifted so that the code in the region F000 to FFFF the upper half is moved down to the E000 to F000 region The program automatically calls a function in root memory to accomplish this task The function modifies the CBR to slide the code down one page and then jumps to the new location This transfer of control is made is at the end of the first statement that crosses F000 Hence no si
96. Scorezl Cldemo c Pflash c Relay c Sitk Cldemor c Piodemo c Rtctest c V256x64 E Ctedemo c E Pona c E sbflash c pm gt Fie name Files of type Source Files c lib Cancel To select a file type in the desired file name or select one from the list The file s directory may also be specified A Refer to the Microsoft Windows User Guide for more information 42 Dynamic C Environment Dynamic C 32 v 6 x Save The Save command updates an open file to reflect the latest changes If the file has not been saved before the file is new and untitled the Save As dialog will appear Use the Save command often while editing to protect against loss during power failures or system crashes The keyboard shortcut is CTRL S Save As Allows a new name to be entered for a file and then saves the file under the new name Save in a Samples z e 24 Cd Vwdog Demo Pro asyn c Pk25xx Gazi04 Enoutput c Prtdemo c Plcbus Bdtemp c Laflash c Psflash c Scorezl Cldemo c Pflash c Relay c Sitk Cldemor c Piodemo c Rtctest c V256x64 E Ctedemo c E Pona c E sbflash c gt Fienme Save as type Source Files c lib Cancel Close Closes the active window The active window may also be closed by pressing CTRL F4 or by double clicking on its system menu If there are unsaved changes a dialog prompting to save or discard the changes will be presented The file is saved when
97. TITTTTTTTITTT logical address j 1 1 11 1 4 1I j 1 1 1 1 i 4 base 1 11 1 1 1 19 trir physical address EIL IS E17 LE IJ JI110 11 Figure 5 5 2180 Physical Addresses Memory Partitions Table 5 3 explains the memory partitions in Dynamic C Table 5 3 Dynamic C Memory Partitions Description BIOS 8kbytes Basic Input Output System The BIOS is always present and is always mapped to address 0 of ROM or flash The BIOS contains the power up code the communication kernel and important system features ROOT 48 kbytes The area between the BIOS and XMEM the bank area The root normal memory resides in a fixed portion of physical memory Root code grows upward in logical space from address 2000 hex and root data static variables stack and heap grow down from E000 Initialized static variables are placed with code whether in ROM flash or RAM XMEM 8 kbytes XMEM is essentially an 8 kbyte window into extended physical memory XMEM can map to any part of physical memory ROM flash or RAM simply by changing the CBR Technical Reference The Language 97 The XMEM area has many mappings to physical memory The mappings can change by changing the CBR as the program executes Extended memory functions are mapped into XMEM as needed by changing the CBR The mapping is automatic in C functions However
98. The Debugger command gets Dynamic C to display the following dialog Debugger ptions x Log STDOUT Log file pc our Append Log Help Cance The options on this dialog box may be helpful when debugging programs In particular they allow printf statements and other STDIO output to be logged to a file Check the box labeled Log STDOUT to send a copy of all standard output to the Log File The name of the log file can be specified and the Append Log checkbox selects whether to append or overwrite 1f the log file already exists Normally Dynamic C automati cally opens the STDIO window when a program first attempts to print to it This can be changed with the checkbox labeled Auto Open STDIO Window 62 Dynamic C Environment Dynamic C 32 v 6 x Memory The Memory command gets Dynamic C to display a submenu Click one of the three submenu items to specify memory settings Dynamic 32 Version 6 30 File Edit Compile Run Inspect Window Help Axes simo xje Comite Debugger Memory Physical Display Logical Serial Reserve v Show Tool Bar Save environment The Physical memory options submenu produces the following dialog Physical Memory Options x Start of ROM 0000h EndotRow iron H Start of RAM 800008 EndofRAM 00 M Auto Config Max Root Code B000h CodeDaaGap Oh Help Cance Technical Reference Dynamic C Enviro
99. The Language 87 The continue statement causes the program control to skip uncondition ally to the next pass of the loop Equivalent Code get char get char while EOF while EOF some statements some statements if bad continue if bad goto xxx more statements more statements XXX The break statement causes the program control to jump unconditionally out of a loop Equivalent Code for iz0 i n i t for i 0 i lt n i some statements some statements if cond RED break if cond RED goto yyy more statements more statements YYY more code The break keyword also applies to the switch case statement described in the next section The break statement jumps out of the innermost control structure loop or switch statement only There will be times when break is insufficient The program will need to either jump out more than one level of nesting or there will be a choice of destinations when jumping out Use a goto statement in such cases For example while some statements for 0 lt some statements if cond RED goto yyy some statements if code BLUE goto zzz more statements yyy handle cond_RED 222 handle code BLUE 88 The Language Dynamic C 32 v 6 x Branching The goto statement mentioned previously is the simplest form of branch ing statement Coupled with a statement label it simply transfers program
100. ThisMachine always on Control sequence Applies to any machine Machine i ThisMachine store it back This program is more space efficient than the one before it It uses the same costatement for all the machines However the CoData structure must be copied from and back to the array because the Machine array is the actual storage for the states of each individual machine The following example offers another way to implement the same pro gram CoData Machine an array of codata blocks CoData pMachine ptr to a machine uint i for i 0 i n i for all machines CoBegin amp Machine i enable machine for for i20 i lt n i 11 costate pMachine always on control sequence for all machines Technical Reference Costatements 159 In this approach pMachine is a pointer to CoData structure Using pointers there is no need to copy CoData structures before and after the costatement For further information refer to the Dynamic C Application eo Frameworks manual It is never acceptable to have more than one costatement sharing CoData unless there is a guarantee they will not use the CoData at the same time as in the second example above The fields in CoData can control only one costatement at a time 160 Costatements Dynamic C 32 v 6 x 2 CHAPTER 8 INTERRUPTS Technical Reference Interrupts 161 Dynamic
101. Yes is clicked or is typed If the file is untitled there will be a prompt for a file name in the Save As dialog Any changes to the document will be discarded if No is clicked or is typed Cancel results in a return to Dynamic C with no action taken Print Preview Shows approximately what printed text will look like Dynamic C switches to print preview mode when this command is selected and allows the programmer to navigate through images of the printed pages Technical Reference Dynamic C Environment 43 The following tool bar appears at the top of the print preview window 44 From left to right the icons on the print preview toolbar perform the following functions select the previous or next page select one or two pages displayed at a time show the displayed page number print same as the File gt Print menu command Close exit print preview mode Print Text can be printed from any Dynamic C window There is no restriction to printing only source code For example the contents of the assembly window or the watch window can be printed Dynamic C displays the following type of dialog when the Print command is selected Print Printer Name HP LaserJet 4050 Series PS Properties Status Ready Type HP LaserJet 4050 Series PS Where 10 10 4 160 Comment Print to file Print range Copies C All Number of copies 1 C Pages from
102. ables SP Figure 6 2 General Appearance of assembly Code Stack Frame The return address is always necessary The presence of auto variables and register variables depends on the definition of the function The presence of arguments and structure return space depends on the function call The stack pointer may actually point lower than the indicated mark temporarily because of temporary information pushed on the stack The shaded area in the stack frame is the stack storage allocated for auto and register variables The assembler symbol SP represents the size of this area The meaning of this symbol will become apparent later The following sections describe how to access local variables in various types of functions No IX Function in Root Memory Assume this simple function has been called int gi this is a global variable root nouseix void func char ch int i long 1 auto int x static int y register int z asm some assembly code referencing gi ch i l x y and z endasm 136 Using Assembly Language Dynamic C 32 v 6 x Figure 6 3 shows how the stack frame will look L 1 4 4 6 ar i 2 4 ch 2 4 return address 2 4 of x 2 prior value of z 2 I frame reference point 6 SP Figure 6 3 Assembly Language Stack Frame No IX Function in Root Memory The symbols for gi ch i 1 x y and z will have t
103. addresses in hex Fill in the fields in this dialog to match those reported by the DLM when the DLM parameters menu choice 3 described previously were re quested The fields will be all zeros the first time the DLP 18 compiled Thereafter the field values will be appear with the last values used Buttons in the dialog box allow the download parameters to be saved or retrieved to from a download configuration DLC file This is convenient to create DLPs for more than one type of controller Be careful not to compile a DLP for a configuration different from the one on which it will actually run Technical Reference Remote Download 171 How to Use the DLM Here is a step by step example of how to use the DLM to download and run a program This example also demonstrates the use of an RTI file for targetless compilation 1 With a target controller connected to a PC start Dynamic C and open the file DIM ZO C in the SAMPLES AASC subdirectory Set DLM PASSWORD STR to the desired password or to for no pass word Issue the Create RTI File Targetless Compile command to create an RTI file for later use 3 Compile DIM Z0 C to the target B cor OY Reset the target Start the communication program Enter the pass word when the Download Manager Menu appears Press 3 to display the DLM memory map Jot down the numbers With Dynamic C open open the program that is to be downloaded Select the DLP
104. ake the program report its behavior by including debugging code such as calls to printf in the program This is useful but it is often not sufficient especially if the printf contents scroll off the screen too fast Dynamic C however offers an option to save all the content printed to the STDIO window into a file for later examination This allows the programmer to save a huge file of debug information and then use another program on the PC to analyze the contents 2 Probe and test the program as it runs Unfortunately for debugging programs run faster than humans do Addressing this difference Dynamic C lets the program run at a speed amenable to testing Slow it down here make it run fast there and stop whenever needed to examine its state Dynamic C provides a variety of windows listed in Table 3 1 to monitor a program s state Table 3 1 Dynamic C Monitoring Windows Watch window Evaluates variables expressions and functions STDIO window Calls to printf display in the STDIO window Assembly window Examines or step the compiled code Register window Shows Z180 register values past and present Stack window Shows the top 8 bytes of the processor stack past and present The assembly register stack STDIO and watch windows are all scrolling windows The windows can be scrolled to view the history of contents of registers stack and watch expressions of the last few steps This feature is very u
105. all statements end with a semicolon A C program is treated as a stream of characters where line boundaries are generally not meaningful Any C statement may be written on as many lines as needed Comments the kind may occur almost anywhere even in the middle of a statement as long as they begin with and end with A statement can be many things A declaration of variables is a statement An assignment is a statement A while or for loop is a statement compound statement is a group of statements enclosed in curly brackets and Declarations A variable must be declared before it can be used That means the variable must have a name and a type and perhaps its storage class could be specified If an array is declared its size must be given static integer variable amp static integer array static int thing array 12 auto float array with 2 dimensions auto float matrix 3 3 initialized pointer to char array char message Press any key If an aggregate type struct or union is being declared its internal structure has to be described as shown below struct description of struct char flags struct a nested structure here int x int y 1oc cursor int a a cursor loc x use of struct element here Functions The basic unit of a C language application program is a function Most functions accept parameters or arguments and return results but there are excep
106. amic C provides a subfunc construct to optimize frequently used code Initialized Variables Static variables initialized when they are declared are considered named constants The compiler places them in the same area of memory as program code typically in EPROM or flash memory Uninitialized variables are placed in RAM and must be initialized by the application program int i 100 initialized in declaration here becomes a named constant 18 Introduction to Dynamic C Dynamic C 32 v 6 x int k variable placed in RAM then k 100 initialized by your program When a program is being compiled directly to a controller that has EPROM the compiler places constants and program code in RAM since it cannot modify the controller s EPROM Under these circumstances constants can be modified intentionally or not but it is an error to do so The default storage class for local variables is static not auto so be doubly careful when initializing variables in functions Function Chaining Function chaining a concept unique to Dynamic C allows special segments of code to be distributed in one or more functions When a named function chain executes all the segments belonging to that chain execute Function chains allow the software to perform initialization data recovery or other kinds of tasks on request Dynamic C provides two directives makechain and funcchain and one keyword segchain makechain cha
107. and generates a downloadable DLP program file DLP to be used by the Z World Down Load Manager DLM The Compile to File or Compile to File with RTI File command generates no output The Null Device fast compilation is useful to 1 perform Bit Bucket syntax checking 2 perform type checking or 3 get the sizes of each code and data segment 50 Dynamic C Environment Dynamic C 32 v 6 x The Memory Options command in the Options menu affects the placement and allocation of code and data in the target controller s memory The Serial Options command in the Options menu specifies the speed and mode when the generated code is uploaded from the PC to the target For more details refer to the OPTIONS menu discussion later this chapter The Compile menu commands and their functions are described here Compile to Target Compiles program and loads it in target controller s memory Dynamic C automatically determines whether the target has on target RAM flash EPROM or development board RAM and compiles with the appropriate memory map The controller s reference manual describes which platform is available for the target being used Any compilation errors are listed in the message window that is activated automatically Otherwise the program is ready to run and Dynamic C is in run or debug mode The program will start running without a pause if nodebug precedes the main function Dynamic C will also lose co
108. anguage that calls functions in extended memory may need to do the mapping more specifically 200 Extended Memory Dynamic C 32 v 6 x Functions may be classified as to where Dynamic C may load them The keywords in Table D 2 apply to function definitions Table D 2 Memory Keyword Definitions The function must be placed in root memory It can call functions residing in extended memory The function must be placed in extended memory Calls to extended memory functions are not as efficient as calls to functions in root memory Long or infrequently used functions are appropriate for placement in extended memory This keyword lets the compiler decide where to place the function A function s placement depends on the amount of reserve memory available Refer to the Memory Options command in the OPTIONS menu Depending on which compiler options are selected code segments will be placed in RAM ROM or flash Figure D 3 shows the memory layout with code in RAM Code Placed in RAM gt RAM ROOT DATA FFFF XMEM E009 ROOT CODE ROOT DATA gt EPROM ROOT CODE 0000 BIOS BIOS 00000 Logical Space Physical Space Figure D 3 Memory Layout with Code in RAM Technical Reference Extended Memory 201 Figure D 4 shows the memory layout with code in ROM or flash Code Placed R
109. before every upload When using the PLU to update the program on a series of target controllers it is recommended to select the Options gt Reset Target menu item before each upload This will help to ensure that the PLU is communicating properly with each target controller in turn 180 Local Upload Dynamic C 32 v 6 x A APPENDIX Ruw TivE ERROR PROCESSING Technical Reference Run Time Error Processing 181 Compiled code generated by Dynamic C calls an error handling routine for abnormal situations The error handler supplied with Dynamic C prints any error messages to the STDIO window When software runs stand alone disconnected from Dynamic C such an error message will hang while waiting for a response from the PC being used to development the program or program the controller Be sure to provide for an error handler unless there is a certainty that there will never be any run time errors Your program calls the error handler indirectly through the global function pointer ERROR EXIT The following example shows the use of the standard error handler ERROR EXIT is a pointer ERROR EXIT 50 0 to the standard handler or to your own In this example the standard Dynamic C error handler would send the message Run Time Error 50 to the STDIO window The first argument is the error number The second argument specifies the address at which the error occurred The following example il
110. bles certain constants arrays structures unions functions and abstract data types Names must begin with a letter or an underscore _ and thereafter must be letters digits or an underscore Names may not contain any other symbols especially operators Names are distinct up to 32 characters but may be longer Names may not be the same as any keyword Names are case sensitive Examples my function ok block ok test32 ok jumper not ok uses a minus sign 3270type not ok begins with digit The following two names are not distinct Clean up the data in the arrays now Clean up the data in the arrays later References to structure and union elements require compound names The simple names in a compound name are joined with the dot operator period cursor loc x 10 set structure element to 10 Use the define directive to create names for constants These can be viewed as symbolic constants See Macros previously discussed define READ 010 define WRITE 020 define ABS 0 define REL 1 define READ ABS READ ABS define READ REL READ REL The term READ ABS is the same as 010 0 or 10 and READ REL is the same as 010 1 or 11 Note that Dynamic C does not allow anything to be assigned to a constant expression READ ABS 27 produces compiler error because 010 1 is 10 Numbers Numbers are constant values and are formed from digits possibly a decimal point and possibly the lette
111. brary functions have descriptive headers that are displayed when help regarding the function is requested If a function name a program is selected or clicked on the help com mand CTRL H for short will display the function header If the function name is unknown to Dynamic C a library lookup dialog will appear Click Lib Entries to browse all the library functions known to Dynamic C Library Lookup E3 Types Names in U NVSSXZT80NDC 323DISTRIBSLIBSBL14 15 LIB Z180 DC_32 DISTRIBSLIBSBL14_15 LB 12outin UAWSS Z180 DC_32 DISTRIBALIBSSKEYEXT D LIB Bkey_1dout in U AVSS Z180 DC_32 DISTRIBSLIBSSKEYEXTD LIB Bkey_bank1 dig in U WSS Z180 DC_32 DISTRIBSLIBSSKEYEXTD LI Bkey_bank2dig in U WSS Z180 DC_32 DISTRIBSLIBSSKEYEXTD LI Bkey_boolean U VSS Z180 DC_32 DISTRIBSLIBSSKEY LIB Bkey_dacout in U sVSS Z180 DC_32 DISTRIBSLIBSSKEYEXTD LIB 71 Help Cancel Technical Reference Using Dynamic C 37 Browsing has two benefits 1 Review available functions 2 Quick access to the function header including its prototype This provides a quick reminder how to call the function An additional benefit 1s that a function prototype can be copied from the help window and used to form a function call This saves typing and time Remember that any text in a library help window can be copied and then pasted elsewhere Function Assistance The third form of help is a variant of the function
112. calls in the program will cause execution to pause until polling is resumed Running without polling also prevents debugging until polling is resumed The keyboard shortcut for this command is ALT F9 Trace Into Executes one C statement or one assembly language instruction if the assembly window is displayed with descent into functions Execution will not descend into functions stored in ROM because Dynamic C cannot insert the required break points in the machine code If nodebug is in effect execution continues until code compiled without the nodebug keyword is encountered The keyboard shortcut is F7 Step over Executes one C statement or one assembly language instruction if the assembly window is displayed without descending into functions The keyboard shortcut is F8 Toggle Breakpoint Toggles a regular soft break point at the location of the execution cursor Soft break points do not affect the interrupt state at the time the break point is encountered whereas hard break points do The keyboard shortcut is F2 Toggle Hard Breakpoint Toggles a hard break point at the location of the execution cursor A hard break point differs from a soft breakpoint in that interrupts are disabled when the hard break point is reached The keyboard shortcut is ALT F2 Toggle Interrupt Flag Toggles interrupt state The keyboard shortcut is CTRL b Toggle Polling Toggles polling mode When running in polling m
113. ced when a routine returns In other words the SP must be same on exit as it was on entry From the caller s point of view the SP register must be identical before and after the call instruction Using the 5 approach after pushing temporary information on the stack The SP approach for in line assembly code assumes that SP points to the low boundary of the stack frame This might not be the case if the routine pushes temporary information onto the stack The space taken by temporary information on the stack must be compensated for The following code illustrates the concept SP still points to the low boundary of the call frame push hl save HL SP now two bytes below the stack frame ld h1 SP x 2 Add 2 to compensate for altered SP add hl sp compute as normal ld a hl get the content pop hl restore HL SP again points to the low boundary of the call frame CBR not preserved Dynamic C assumes that root functions preserve the CBR common base register for memory management While most functions have nothing to do with the CBR some functions in extended memory do manipulate the CBR Make sure the CBR is preserved in a function in root memory Registers not preserved In Dynamic C the caller 18 responsible for saving and restoring all registers An assembly routine that calls a C function must assume that all registers will be changed Unpreserved registers in interrupt routines cause unpredictable and unrepea
114. code and then the help command is issued Dynamic C displays help information for that function The keyboard shortcut 15 CTRL H If Dynamic C cannot find a unique description for the function it will display the following dialog box x Library Lookup Types Names TRIBSLIBSBLT4 15 08 5key 12out in 5 555218050 323DISTRIBSLIBNSKEYEXTD LIB 5key 14out in U VSS42180 DC_32 DISTRIBSLIBSSKEYEXTD LIB 5key bankldig in U VSS 52180 DC_32 DISTRIBSLIBSSKEYEXTD LI 5key bank2dig in U VSS 2180 DC_32 DISTRIBSLIB SKEYEXTD LI 5key boolean in U VSS42180 DC_32 DISTRIBSLIBSSKEY LIB 5key dacout in U VSS Z180 DC_32 DISTRIBSLIBSSKEYEXTD LIB Help Cancel Click Lib Entries to display a list of the library functions currently available to the program in the libraries named in the LIB DIR file Then select a function name from the list to receive information about that function Dynamic C displays a dialog like the following one when a function 18 selected for display of help information 72 Dynamic C Environment Dynamic C 32 v 6 x Fires Has ok raa emit Danzzpson Domenica bidim j AIRING LIN BINIAX char zatrcgy chur dst char BESCRIFIION Copies string src bo string dee ineluadizg the null Terminmbm FAPRAPHT RL Folnrer Location bo rebkive STE Ley BARABHTERZ Pointer to Looscion bn supply string EARTHEN FELIE Pnixcer dat
115. code in ROM or flash Code Placed in RAM ROM or flash ROOT DATA Fd FFFF XMEM u E000 2 ROOTDATA lt V reae gt EPROM ucc ROOTCODE ROOTCODE 0000 BIOS BIOS 2 00000 Figure 5 7 Memory Layout with Code in ROM or Flash C Language Elements A Dynamic C program is a set of files each of which is a stream of characters that compose statements in the C language The language has grammar and syntax or rules for making statements Syntactic elements often called tokens form the basic elements of the C language Some of these elements are listed in Table 5 5 Table 5 5 C Language Elements keywords Words used as instructions to Dynamic C Names Words used to name data Numbers Literal numeric values Strings Literal character values enclosed in quotes operators Symbols used to perform arithmetic punctuation Symbols used to mark beginnings and endings directives Words that start with and control compilation Keywords A keyword is a reserved word in C that represents a basic C construct The word while represents the beginning of a while loop It cannot be used for any other purpose There are many keywords and they are summa rized in the following pages Technical Reference The Language 99 abort Jumps out of a costatement for costate if condition abort 22 See Chapter 7 Costatements anymem Allows the compiler
116. code written in assembly language that calls functions in extended memory may need to do the mapping more specifically Functions may be classified as to where Dynamic C may load them The keywords in Table 5 4 apply to function definitions Table 5 4 Memory Keyword Definitions Description The function must be placed in root memory It can call functions residing in extended memory The function must be placed in extended memory Calls to extended memory functions are not as efficient as calls to functions in root memory Long or infrequently used functions are appropriate for placement in extended memory This keyword lets the compiler decide where to place the function A function s placement depends on the amount of reserve memory available Refer to the Memory Options command in the OPTIONS menu Depending on which compiler options are selected code segments will be placed in RAM ROM or flash Figure 5 6 shows the memory layout with code in RAM N Code PlacedinRAM f _ gt RAM ROOT DATA FFFF XMEM Fogo ROOT CODE ROOT DATA J gt EPROM ROOT CODE E 0006 BIOS BIOS 00000 Logical Space Physical Space Figure 5 6 Memory Layout with Code in RAM 98 The Language Dynamic C 32 v 6 x Logical Space Physical Space Figure 5 7 shows the memory layout with
117. cursion a macro does not expand within its own expansion The following complex example illustrates this define B define define uint unsigned int define M x M x define MM x y z x y z define string something define write value fmt printf value fmt value The code uint z M M A A B write string s will expand first to unsigned int z simple expansion MM A A B M M does not expand recursively printf string ss Mn string value gt string fmt gt s then to unsigned int z A AB from A B printf string ss Wn something string something then to unsigned int z B AB gt B printf string s n something concatenation and finally to unsigned int z C AB BC printf string s n something Technical Reference The Language 85 Restrictions number of arguments in a macro call must match the number of parameters in the macro definition An empty parameter list is allowed but the macro call must have an empty argument list Macros are restricted to 32 parameters and 126 nested calls A macro or parameter name must conform to the same requirements as any other C name The C language does not perform macro replacement inside string literals or character constants comments or within a define directive A macro definition remains in ef
118. d Thus a large program say 8 000 lines of code might generate 80 KBytes of machine code and take about 30 seconds to compile and download The application code might only be 400 lines yet it can make calls to several thousand lines of library code all of which are compiled when the program is compiled Dynamic C is Different Dynamic C differs from a traditional C programming system running on a PC or under UNIX The motivation for being different is to be better to help customers write the most reliable embedded control software possible Some of the devices and constructs that C programmers employ on other systems just don t work very well for embedded systems At the very least they must be used with caution In some instances Z World has extended the C language where the value of the extension 18 compelling In an embedded system there is no operating system or supervisor that can halt a program 1f it goes wrong or perform services for the program An embedded program has to do it all and handle its own errors and keep on running embedded program also has to initialize itself In an embedded system a program runs from EPROM or flash and uses a separate RAM for data storage Many Z World controllers have battery backed RAM providing nonvolatile storage Often an embedded program comprises a number of concurrently execut ing tasks rather than a single task Technical Reference Introduction to Dynamic 17
119. d DRE 86 IUUD 86 Continue and Break d e en ertet 87 89 Data en qu FO cni 91 Primitive Data qe dote Va 91 Aggregate Data Types 0 0 2400040 000 iaae a 92 Storage Classes tea ERROR ENNIUS 94 94 Arg ment Passing eie 95 Memory 96 97 C Language Elements nennen 99 99 NAMES i erae tomi dr dq p iis 112 NUMDETS pute cere edi p a eren 112 Strings and Character Data sse 113 SCHUSTER 115 Dip EE 124 P nct ation ghee reg 127 Extended Memory Data sse 127 Chapter 6 Using Assembly Language 129 Register SUMMARY n nire HH EAS 131 General Concepts d Se da 131 Comments PEERS Pe 132 Labels inr ret 132 Defining Constants sess 132 Exptess1Ons oie me eto e qe HT tes 133 Special Symbols een eiim 133 C RE ET RNC 134 Standalone Assembly Code sse 135 Embedded Assembly Code sse 135 No IX Function in Root 136 Us
120. d in a program Never use goto to jump into a loop body or a switch case The results are unpredictable However it is possible to jump out of a loop body or switch case if Indicates the beginning of an if statement if tank full shut off water if expression statements 1 if expression statements else if expression statements else if expression statements 1 statements If one of the expressions is true they are evaluated in order the statements controlled by that expression are executed An if statement can have zero or more else if parts The else part is optional and executes when none of the if expressions is true nonzero Technical Reference The Language 103 int Declares a variable function or array to be an integer If nothing else is specified int implies a 16 bit signed integer int i j k 16 bit signed unsigned int x 16 bit unsigned long int z 32 bit signed unsigned long int w 32 bit unsigned int funct int arg interrupt Indicates that a function is an interrupt service routine interrupt isr An interrupt service routine returns no value and takes no argu ments cuu See also ret reti and retn long Declares a variable function or array to be 32 bit integer If nothing else is specified 1ong implies a signed integer long i j k 32 bit signed unsigned long int w 32 bit unsigned long funct
121. d memory 127 128 204 205 206 data types 92 aggregate sese 92 primitive eee 91 92 dbi ish tet 132 nee temer 208 DCW CEG ette 68 101 124 editor xem tenete an 66 mode 49 52 190 same as run mode 32 debug mode 29 debugger 16 32 212 options 58 62 debugging 16 32 33 36 52 53 55 56 101 104 124 125 163 188 208 212 Append 62 assembly level view 16 Auto Open STDIO Window 62 ur 62 Log STDOUT 62 WIndows 33 34 declarations 78 82 194 decrement operator 117 default 90 102 109 ditectiVes c setas 208 storage class 18 19 24 DEEAUDLDEH e deu 23 Del from Top button 36 55 Delay Functions 152 DelayMS 149 157 DelaySec 149 157 DelayTicks 149 157 deleting watch window items 54 55 demotion nts 60 descriptive function headers 37 38 DL ient 35 163 digital input output 16 direct compilation 16 23 228 Index memory access DMA 24 directives
122. ddresses Three MMU registers CBAR CBR and BBR divide the logical space into three sections and map each section onto physical memory as shown in Figure D 1 CBAR Common Bank Area Register FFFFF CBR Common Base Register BBR Bank Base Register T lt CBR CBAR ff jai XMEM HT dd gt E000 En C000 A000 8000 ROOT 6000 4000 m lt BBR 2000 NM RN 0000 2222 8 BIOS 00000 Logical Space Physical Space Figure D 1 Z180 On Chip Memory Management Unit MMU Registers 198 Extended Memory Dynamic C 32 v 6 x The logical address space is partitioned on 4K boundaries The upper half of the CBAR identifies the boundary between the ROOT memory and XMEM The lower half of CBAR identifies the boundary between the BIOS and the The start of the BIOS is always address 0 The two base registers CBR and BBR map XMEM and ROOT respectively onto physical memory Given a 16 bit address the Z180 uses CBAR to determine whether the address is in XMEM BIOS or ROOT If the address is in XMEM the 7180 uses the CBR as the base to calculate the physical address If the address is in ROOT the Z180 uses the BBR If the address is in the BIOS the Z180 uses a base of 0 A physical address is essentially base lt lt 12 logical address 15 12 11 Oa a logical address
123. de before the asm or after the endasm directive Unless it is followed immediately by the keyword equ the label identifies the current code segment address If the label is followed by equ the label equates to the value of the expression after the keyword equ Because C preprocessor macros are expanded in embedded assembly code Z World recommends that preprocessor macros be used instead of equs whenever possible Defining Constants Constants may be created and defined in assembly code The keyword db define byte places bytes at the current code segment address The keyword db should be followed immediately by numerical values and strings separated by commas as shown here Example Each of the following defines a string in code space db db db 0 41 0 42 0x43 The numerical values and characters strings are used to initialize sequential byte locations The keyword dw defines 16 bit words least significant byte first The keyword dw should be followed immediately by numerical values as shown in this example Example The following defines three constants The first two constants are literals and the third constant is the address of variable xyz dw 0x0123 OxFFFF xyz The numerical values initialize sequential word locations starting at the current code segment address 132 Using Assembly Language Dynamic C 32 v 6 x Expressions The assembler pars
124. ded memory which means anywhere in the 512 KByte code space The directive memmap allows further control Special statements xdata and xstring declare blocks of data in extended memory Certain functions such as xgetfloat and xstrlen help to access data in extended memory Refere to Appendix D Memory Management and to the Gu XMEM LIB library in the Dynamic C Function Reference manual for more details External Functions and Data The keyword static cannot apply to functions The keyword extern is used in module headers those enclosed in BeginHeader and EndHeader comments variable or function may already be declared extern in your a controller s BIOS symbol table Otherwise declare a variable extern if it is to be defined later in the program or in another file 22 Introduction to Dynamic C Dynamic C 32 v 6 x Two files in the Dynamic C directory LIB DIR and DEFAULT H contain lists of libraries that are needed for particular controllers These files are used automatically but they can be modified if necessary Dynamic C has no include directive but does have a use directive Whereas the include directive causes program text to be inserted in place of the directive Z World s use directive does not cause text insertion but identifies a library from which functions and data may be taken The file DEFAULT H contains various sets of use directives one set for each controller Z World offers Dynamic C compiles lin
125. des a standard I O window an assembly window a watch window a register window and a stack window The standard I O window allows the program in a controller to print messages on the development screen The assembly window displays an assembly view of compiled code The watch window allows the programmer to type and evaluate expressions monitor or set variables and call functions Dynamic C s debugger allows breakpoints to be set and cleared on the fly to single step with and without descent into functions and to view execution at the assembly level as well as at the source code level 16 Introduction to Dynamic C Dynamic C 32 v 6 x Dynamic C provides extensions to the C language such as shared and protected variables that support real world system development Interrupt service routines may be written in C Dynamic C supports real time multi tasking with its real time kernel and its costatement extension Dynamic C comes with many function libraries all in source code These libraries support real time programming machine level I O and provide standard string and math functions Please refer to the Dynamic C Application Frameworks and Function Reference manuals Speed Dynamic C compiles directly to Z180 memory Functions and libraries are compiled and linked and downloaded on the fly On a fast PC Dynamic C can compile more than 250 lines of source code per second generating about 2500 bytes of machine code per secon
126. e BABIES m dependent function pointers A chain of code executed by SRTK LIB srtk hightask SRTK every 25 ms in the high priority task A chain of code executed by SRTK LIB srtk lowtask SRTK every 100 ms in the low priority task After sysInitTimerl is called a chain of code executed 8 8 25 every 25 ms in ISR with interrupts disabled After sysInitTimerl is called a chain of code executed SYS LIB _sys_25msPostEI every 25 ms in the PRT1 ISR with interrupts enabled On PK2100 series controllers after sysInitTimerl is SYS LIB _sys_390 called a chain of code executed every 0 390 ms in the PRT1 ISR with interrupts disabled After sysInitTimerl is called a chain of code executed every 0 781 ms in the ISR with interrupts disabled SYS LIB _sys_781 After sysInitTimerl is called a chain of code executed every 0 781 ms in the PRTI ISR with interrupts enabled SYS LIB _sys_781PostEI A chain of tasks to perform when SYS LIB sysSupRstChain super resetting Performs general global initialization tasks Users are encouraged to add segments to this chain VDRIVER LIB GLOBAL_INIT 220 Existing Function Dynamic C 32 v 6 x T ArPENpix NEW FEATURES Technical Reference New Features 221 The reader is encouraged to read the Release Notes txt file in Dynamic C s main installation folder f
127. e The run mode can be also called the debug mode Compilation is in effect the transition between the edit mode and the run mode Developers work with Dynamic C by editing text issuing menu commands or keyboard shortcuts for these commands and viewing various debugging windows Programs can compile directly to a target controller toa file for burning an EPROM toa file meant for downloading to a controller in which the Z World Download Manager resides or toa file meant for downloading to controller RAM In order to compile or run a program a controller must be connected to the PC or a RTI Remote Target Information file for compilation must exist Dynamic C includes editing options compiler options and memory options Most of the options are in the Options menu Details about how to work with Windows have been omitted intentionally Refer to the Microsoft Windows Users Guide for details oY regarding the use of Windows Dynamic C follows Win dows software standards very closely Editing Once a file has been created or has been opened for editing the file is displayed in a text window It is possible to open or create more than one file and one file can have several windows Dynamic C supports normal Windows text editing operations Use the mouse or other pointing device to position the text cursor to select text or to extend a text selection Scroll bars may be used to position text in a window Dynamic C
128. e has the opposite effect Static Variables Static variables are much more efficient on the Z180 than auto vari ables In Dynamic C the default local storage class is static while most C compilers use auto Use auto variables in reentrant or recursive functions Here are some rules concerning declarations that will help to conserve code and save time 1 Use global variables for global communication or constants 188 Efficiency Dynamic C 32 v 6 x 2 Avoid auto variables within functions whenever possible To save code space and execution time while preserving reentrancy use the register storage class for one or two byte items 3 The shared and the protected keywords in data declarations cause slower fetches and stores except for one byte items and some two byte items 4 When there are more than 128 bytes of auto variables declared in a function keep in mind that the first 128 bytes are more easily accessed than later declarations owing to the limited 8 bit range of Z180 IX register addressing Execution Speed Compiler Options can be used to set a switch to optimize for speed or for size The default is size If speed is selected then the program size might increase somewhat Using static variables with nodebug functions will increase program speed greatly Stack checking must be disabled for good speed Subfunctions Subfunctions extensions in Dynamic C allow often used code sequences to be turned into a sub
129. e DLM 0 44 1 2010200 2000 nee 172 DLP File Format eee eese eie 173 Chapter 10 Local Upload 175 The Program Loader Utility essen 176 On line Help 177 Set Communication Parameters sss 177 Reset the Target Controller 178 Select the Program File eese 179 Common Problems essere rennen 180 vi Table of Contents Dynamic C 32 v 6 x Appendix A Run Time Error Processing 181 Long Jumps eee DIG rele m Penes 184 Watchdog Timer ente ae eter Rt e RS 184 Protected Vati bles oe aon 185 Appendix B Efficiency 187 Nodebug Keyword essere 188 Static Variables E eR 188 Execution Speed ea ee eem eb E REIR 189 189 Function Entry and Exit sess 190 Appendix C Software Libraries 191 193 Function Headers ERRARE heo 194 uitae 194 Appendix D Extended Memory 197 Physical Memory epe dde fiendis 198 Memory Management ener 198 Memory Partitions 0 cccceesesccesecseceseeeseeeeneceeenseeeeeseserenseenees 200 Control over Memory Mapping sse 202 Extended Memory Functions essere 202 SUBggeSLIOTIS nece re rtr 203 Extended Memory Data 204
130. e about arguments passed on the stack and auto variables can be defined by reserving locations on the stack for them However the offsets of such implicit arguments and variables must be kept track of If a function expects arguments or needs to use stack based variables Z World recommends using the embedded assembly techniques described in the next section Embedded Assembly Code When embedded in a C function assembly code can access arguments and local variables either auto or static by name Furthermore the assembly code does not need to manipulate the stack because the functions prolog and epilog already do so The concept and structure of a stack frame must be understood before correct embedded assembly code can be written A stack frame is a run time structure on the stack that provides the storage for all auto variables function arguments and the return address Technical Reference Using Assembly Language 135 Figure 6 2 shows the general appearance of a stack frame Stack Frame r Structure return higher addresses optional L space lastargument stack grows down optional F 4 firstargument r return address H 2 6 bytes 4 I i IX optional optiona saved IX register p 9 frame reference point first auto variable optional H last auto variable lower addresses storage for prior optional contents of register i vari
131. e address is expressed in logical address The keyboard shortcut is ALT F10 Dump at Address Allows blocks of raw values in any memory location except the BIOS at 00000h through 01FFFh to be looked at Dump at Address Ed Hex Address 2400 v Dump to File Dec File 71 Root Addr Physical Addr Cancel 56 Dynamic Environment Dynamic C 32 v 6 Values can either be displayed on the screen or written to a file if Dump to File is checked A typical screen display appears below Memory Dump Bl x 2400 OF 07 OF 07 OF 03 03 OF 01 OF OF 07 D9 21 00 aj 2410 00 5B SF DD 08 66 09 E5 21 00 39 2420 DS 01 08 00 ED BO D9 21 00 00 C3 6D SF D9 El 2430 7E 23 4E 23 46 ED 20 38 E5 ED 39 38 21 43 24 5 N 2440 C5 D9 C9 F1 ED 39 38 C9 E9 24 2F 25 07 26 33 26 2450 42 26 EA 28 01 29 D9 21 00 00 CD 07 5F EF F3 EF B amp 2460 CD F8 24 EF 00 32 92 DA EF CD EF 5C EF 21 05 2470 00 5 21 05 00 5 9B 2F F1 F1 EF 21 05 00 5 m 2 dump window be scrolled Scrolling causes the contents of other memory addresses to appear in the window The window always displays 128 bytes and their ASCII equivalent Values in the dump window are updated only when Dynamic C stops or comes to a break point If Dump to File is checked specify the number of bytes and the pathname of the file The file output closely resembles the memo
132. e module When an application uses a library Dynamic C compiles every header and just the headers in the library The purpose of a header is to make certain names defined module known to the application With proper function prototypes and variable declarations a module header ensures proper type checking throughout the application program The Body Every line of code after the EndHeader comment belongs to the body of the module until 1 end of file or 2 the BeginHeader comment of another module Dynamic C compiles the entire body of a module if any of the names in the key are referenced used anywhere in the application 82 The Language Dynamic C 32 v 6 x To minimize waste it is recommended that a module header contain only prototypes and extern declarations Prototypes and extern declara tions do not generate any code by themselves Define code and data only in the body of a module That way the compiler will generate code or allocate data only if the module is used by the application program Programmers who create their own libraries must write modules following the guideline in this section Remember that the library must be included in LIB DIR and a use directive for the library must be placed some where in the code Example BeginHeader ticks extern ulong ticks EndHeader ulong ticks BeginHeader Get Ticks ulong Get Ticks EndHeader ulong Get Ticks Be
133. e program bounds RST 38 The standard error routine reports only fatal errors Technical Reference Run Time Error Processing 183 Long Jumps Error recovery is performed using Dynamic C s setjmp and 1 functions If an error is detected anywhere in a program long jump can be made to a safe location so that the necessary recovery tasks can be performed Typically a jump is made from a deeply nested function back to the main program The setjmp function marks a place in the code and saves the stack pointer and important registers The 1ongjmp function causes a return to the place marked by the setjmp call The processor stack is immediately unwound and a known state is restored This example shows how to do this probably in main jmp_buf savreg you must make a save buffer if setjmp savreg code to recover from the error then somewhere deeper in your code if big error longjmp savreg 1 When long jmp is executed the execution resumes immediately after the call to set jmp and the value returned by the call to setjmp is the same as the second argument passed to longjmp This value can be the error code as long as it is nonzero The return value of setjmp is 0 when it is called directly Call 1 in the same function as the call to setjmp or in a function called directly or indirectly from that function The main function is always a safe place to put s
134. e the assembly window Registers Click the Registers command to activate the Register window L 58 5 68 0000 0000 DE 0000 2480 HL 0630 007 IX 0000 245D PC 245E SP DT7CB 411 The register window displays the 7180 register set Letter codes indicate the bits of the status or flags F register The window also shows the source code line and column at which the register snapshot was taken It is possible to scroll back to see the succession of register snapshots Stack Click the Stack command to activate the Stack window n 58 5 D7CB 224 0630 D7CF 2 8 D7D1 2917 D7D3 4401 D7D5 OOFF D7D7 FFFF 2709 CF01 Fr 70 Dynamic C Environment Dynamic C 32 v 6 x The stack window displays the top 8 bytes of the run time stack It also shows the line and column at which the stack snapshot was taken It is possible to scroll back to see the succession of stack snapshots Information Click the Information command to activate the Information window Base Top Size code 2400 5F87 3888 Total code size 15241 bytes XMEM code 80000 800001 00001 Total data size 812 bytes Watch code 6000 0000 Lines compiled 6512 Stack CFD3 0702 0800 Compile time 7 seconds Root data 0704 DAFF 032C Compile speed 55578 lines minute data 8 000 80000 00001 Bytes generated 15704 Heap DBOO DAFF 0000 Total byte
135. ed for dynamic memory allocation functions such as 11 Heap space must be allocated before using dynamic memory allocation The Free Size option specifies the number of bytes hex that are not allocated for other purposes such as the heap This space is completely under the program s control and is accessed entirely by pointers Use the Information Window under the WINDOW menu to find out where this memory is allocated The Reserve memory options submenu provides the following dialog Memory Reserve Options Ea Root Reserve 2000h Mem Reserve Oh Help Cancel Technical Reference Dynamic C Environment 65 Root Reserve and XMem Reserve specify how the compiler allocates memory When compiling code whose destination is not specified that 1s anymem code Dynamic C first compiles all code to root until the amount of root memory left is less than the size of the Root Reserve Then the compiler places all anymem code in extended memory until the amount of extended memory left is less than the XMem Reserve The compiler then returns to the root until memory 1s exhausted Functions specifically placed in root memory or in XMEM are always compiled in the area specified The reserves guarantee a minimum of space in both the root and extended memory for functions that must go in one of those areas Leave enough space in the Root Reserve for all library functions invoked in the program Display The Display c
136. ed int i OxFOOF int j OxFOOF k i gt gt 4 k gets 0x0F00 k j gt gt 4 k gets 0xFF00 The least significant bits of the left operand are lost the most significant bits are either zeroed if the operation is unsigned or copies of the sign bit if the operation is signed Less than This binary relational operator yields a Boolean value The result is 1 if the left operand lt the right operand and 0 otherwise if i lt j body executes if i j OK a lt b true when a lt b Less than or equal This binary relational operator yields a Boolean value The result is 1 if the left operand x the right operand and 0 otherwise if i lt j body executes if i j OK a lt b true when a lt 120 The Language Dynamic C 32 v 6 x Greater than This binary relational operator yields a Boolean value The result is 1 if the left operand gt the right operand and 0 otherwise if i gt j body executes if i gt j OK a gt b true when a gt b Greater than or equal This binary relational operator yields a Boolean value The result is 1 if the left operand gt the right operand and 0 otherwise if i gt j body executes if i j OK a gt b true when a gt b Equal This binary relational operator yields a Boolean value The result is 1 if the left operand equals the right operand and 0 otherwise if
137. ed structure add hl sp hl now points to fl ld h1 a load a now 0 to f1 endasm It is crucial that SP be added to RETVAL because RETVAL is an offset from the frame reference point not from the current SP Technical Reference Using Assembly Language 141 Assembly Code Calling C Functions A program may call a C function from assembly code To make this happen set up part of the stack frame prior to the call and unwind the stack after the call The procedure to set up the stack frame 15 described here 1 Sy Uo 9a 7 Save all registers that the calling function wants to preserve A called C function may change the value of any register Pushing registers values on the stack is a good way to save their values If the function return is a struct reserve space on the stack for the returned structure Most functions do not return structures Compute and push the last argument if any Compute and push the second to last argument if any Continue to push arguments if there are more Compute and push the first argument if any Also load the first argument into the primary register HL for int uint char and pointers or BCDE for long ulong and float if it is of a primitive type Issue the call instruction The caller must unwind the stack after the function returns 1 Recover the stack storage allocated to arguments With no more than 6 bytes of arguments the program may pop data 2 bytes a
138. eived a byte The interrupt routine would read the byte from the receive buffer If an interrupt has more than one possible cause check for all the causes and remove all the causes at the same time 5 When finished restore registers saved on the stack Naturally this code must match the code that saved the registers Interrupt routines written in C perform this automatically Standalone assembly routines must pop the registers explicitly 6 Reenable interrupts Interrupts are disabled for the entire duration of the interrupt routine unless they are enabled explicitly The interrupt handler must reenable the interrupt so that other interrupts can get the attention of the CPU Interrupt routines written in C reenable interrupts automatically when the function returns Standalone assembly inter rupt routines however must reenable the interrupt using the instruc tion ei explicitly The interrupts should be reenabled immediately before the return instructions ret or reti If the interrupts are enabled earlier the system can stack up the interrupts This may or may not be acceptable because there is the potential to overflow the stack 7 Return The three types of interrupt returns are ret reti and retn wa Refer to Chapter 8 Interrupts and to the Zilog Z180 MPU User s Manual to learn about their differences 144 Using Assembly Language Dynamic C 32 v 6 x Common Problems Unbalanced stack Ensure the stack is balan
139. em costatements will operate independently concurrently and with their own timing The keyword costate identifies a costatement Using costatements presupposes that there will be more than one costate ment It is only when there is more than one task that costatements can be considered cooperative because it is only when there is more than one task that any task can execute in the idle time of another task 148 Costatements Dynamic C 32 v 6 x Nevertheless some single tasks are easier to write using costatements Costatements can be used for example to create delays A typical set of costatements will execute in an endless loop However this 18 not a requirement Costatements are cooperative concurrent tasks because they can suspend their own operation There are three ways they do this 1 They wait for an event a condition or the passage of a certain amount of time waitfor statement is used Special functions are available to cover the passage of time DelaySec DelayMS DelayTicks IntervalSec and IntervalMS 2 They can use a yield statement to yield temporarily to other costatements 3 They can use an abort statement to cancel their own operation Since costatements can suspend their own execution they can also resume their own execution from the point at which they suspended their opera tion In general each costatement in a set of costatements is in a state of partial completion Some are su
140. erand the operand is decremented after use int j a 12 j 12 a jl 3 becomes 11 then gets a 11 a j 3 becomes 10 then r gets 10 s j s 10 then j becomes 9 j becomes 8 If the operator is used with a pointer the value of the pointer decrements by the size of the object bytes to which it points With operands other than pointers the value decrements by 1 Technical Reference The Language 117 Unary plus or binary addition Standard C does not have unary plus Unary plus does not really do anything 10 5 binary addition z ty just for emphasis Unary minus or binary subtraction a b 10 5 binary subtraction y z gets the negative of y Indirection or multiplication As a unary operator it indicates indirection When used in a declaration the indicates that the following item is a pointer When used as an indirection operator in an expression the provides the value at the address specified by a pointer int p p is a pointer to integer int 3 45 683 now points to j k p k gets the value to which p points namely 45 p 25 The integer to which p points gets 25 Same as j 25 since p points to 1 Beware of using uninitialized pointers Also the indirection operator can be used in complex ways int list 10 array of 10 ptrs to int int list 10 pt
141. es can be created using the Compile to File command Generally a program in a Z World controller will run by itself once the controller is disconnected from the PC running Dynamic C and is reset for example by turning power off and then on Check to make sure that the controller in run mode The controller manual provides detailed instructions 36 Using Dynamic C Dynamic C 32 v 6 x Controller with Program in EPROM Once an EPROM has been burned place it in the controller s EPROM socket The program runs when the controller restarts Controller with Program in Flash Memory Dynamic C places the program code in nonvolatile flash memory when compilation is to a flash equipped controller The program runs when the controller restarts in run mode Controller with Program in RAM Dynamic C places the program in RAM when compilation is to a control ler with EPROM As long as the controller s RAM is powered the program runs when the controller restarts in run mode Controllers that have no backup battery will lose the contents of their RAM if they are disconnected from power source Help Dynamic C provides three forms of on line help The first is a standard Windows help system containing descriptions of the available menus keystrokes dialog box options and other information about Dynamic C Function Lookup The second form of on line help provides information about the use of Dynamic C library functions Most li
142. es most C language constant expressions A C language constant expression is one whose value is known at compile time All operators except the following are supported conditional 1 array index dot gt points to dereference sizeof For example consider the following code define FLAG1 1 define FLAG2 4 asm and FLAG1 FLAG2 ld de FLAG1 0x80 endasm The preprocessor expands macros before the assembler parses any text Special Symbols Table 6 1 lists special symbols that can be used in an assembly language expression Table 6 1 Special Assembly Language Symbols The symbol PC evaluates to the current address in the PC program counter register The symbol SP indicates the amount of stack space in bytes used for stack based variables This does not include arguments RETVAL The symbol RETVAL evaluates to the offset from the frame reference point to the stack space reserved for struct function returns See Embedded Assembly Code in Chapter 6 Using Assembly GY Language for details on GSP See C Functions Calling Assembly Code in Chapter 6 Using Assembly Language for details on RETVAL Technical Reference Using Assembly Language 133 The PC symbol is useful when referring to an offset from the current PC address as in the riasmseq assembly code multi line macro definition disable restore interrupts assembly sequences define diasmseq ld a i push af di de
143. es to be written in C declared with the keyword interrupt However the efficiency of one interrupt routine affects the latency of other interrupt routines Assembly routines can be more efficient than the equivalent C functions and therefore more suitable for interrupt service routines Either standalone assembly code or embedded assembly code may be used for interrupt routines The benefit of embedding assembly code in a C language interrupt routine is that there is no need to worry about saving and restoring registers or reenabling interrupts The drawback is that the C interrupt function does save all registers which takes some amount of time A standalone assembly routine needs to save and restore only the registers it uses In general an interrupt routine performs the following actions 1 Turn off interrupts upon entry The Z180 does this automatically 2 Save all registers that will be used on the stack Interrupt routines written in C save all registers on the stack automatically Standalone assembly routines must push the registers explicitly 3 Determine the cause of the interrupt Some devices such as the ASCI serial ports on the Z180 map multiple causes to the same interrupt vector An interrupt handler must determine what actually caused the interrupt Technical Reference Using Assembly Language 143 4 Remove the cause of the interrupt For example an ASCI serial port may cause an interrupt because it has rec
144. escribe libraries Library headers should tell a programmer how to use the library Function Headers Describe functions Function headers form the basis for function lookup help Module Headers Makes functions and global variables in the library known to Dynamic C Users who develop their own libraries are encouraged to include descrip tive headers for the library and all of its functions In particular accurate and correctly formatted headers must be defined for function help to work with functions Library Headers A library has a single header at the beginning that describes the nature of the library The header is a specially formatted comment such as the following example START LIBRARY DESCRIPTION kee e de de de d ke He He ke de k DRIVERS LIB Copyright c 1994 Z World DESCRIPTION Miscellaneous hardware drivers li brary Many of these routines disable inter rupts for short periods Define NODISINT to prevent this SUPPORT LIBRARIES END DESCRIPTION 161111 de ke de e e e e 7 Technical Reference Software Libraries 193 Function Headers Each function in a Z World library has a descriptive header preceding the function to describe the function The header is a specially formatted comment such as the following example START FUNCTION DESCRIPTION Xdx d y de k k k plcport lt DRIVERS LIB gt SYNTAX int plcport int bit KEY WORDS DESCRIPTION Checks the spec
145. escribed above provided that 1 The resulting ROMs are used only with Z World controllers 2 The above copyright notice is placed on the ROM Technical Reference File Formats 213 214 File Formats Dynamic C 32 v 6 x Appenpix RESET FUNCTIONS Technical Reference Reset Functions 215 Z World s embedded applications need to differentiate the cause of resets and restarts Table G 1 lists some possible hardware resets Table G 1 Possible Hardware Resets Regular Reset The system RESET line is pulled low and released Power Failure Power drops below a threshold and the supervisor Reset chip pulls RESET low and causes a reset The watchdog timer was not reset It pulls RESET low and causes a reset Watchdog Reset In addition to these hardware resets an application may cause a super reset A super reset is necessary because important system data should persist over the occurrence of regular resets and power failures Z World s super reset is a mechanism to initialize certain persistent data in battery backed RAM A normal reset does not initialize these data but retains their values A super reset always occurs when a program is first loaded Subsequent resets are normal resets unless the software performs a super reset intentionally Reset Differentiation Dynamic C includes a set of functions to differentiate the various resets These functions are grouped into two main categories 1 The
146. etjmp long jump restores the SP IX and PC registers and also restores the auxiliary stack pointer Watchdog Timer Most Z World controllers have a watchdog timer The watchdog timer is used to ensure that software does not get stuck Even error free software is susceptible to transient problems such as power surges power outages and dropped bits A watchdog timer will reset the system after a certain period typically about 1 6 seconds if the software does not reset the watchdog timer within that period This safety feature helps to ensure that the program continues to function 184 Run Time Error Processing Dynamic C 32 v 6 x The function call hitwd resets the watchdog timer A program must call hitwd at least at the frequency of the watchdog timer about once per second no matter what else it is doing Although the watchdog timer can be disabled on some but not all Z World controllers Z World does not recommend disabling the watchdog timer Protected Variables A program may need to recover protected variables at when it restarts However if the program has never run before it must initialize the protected variables The function prot recover recovers protected variables the function _prot_init initializes them The function sysIsSuperReset calls the appropriate protected variable function GY Appendix G Reset Functions for more information Technical Reference Run Time Error Process
147. ever this is done at the sole discretion of the user The reader is cautioned against such usage unless they have great confidence in their ability as well as complete and detailed knowledge of the target controller s workings In addition such nonstandard uses of the PLU are beyond the scope of this manual The Program Loader Utility The Program Loader Utility PLU is found in the main Dynamic C 32 installation directory as PRGLOADR EXE In addition the Dynamic C 32 installer places a shortcut icon on the Windows desktop as well as a Start bar Program Group entry Start the PLU by any of the standard Windows methods E G double click on its icon I Z W orld Program Loader Utility 2 01 IDE XI File Dump Options Help 176 Local Upload Dynamic C 32 v 6 x On line Help Select the Help Contents menu item to display the following dialog box amp Zworld Upload Help ioj x File Edit Bookmark Options Help Z World Program Loader Utility Help Contents Uploading Uploading a program or data to a target Dump Dumping target memory contents to a file Serial Options Setting serial communication options Click on an Uploading Dump or Serial Options link for information about that Help topic Set Communication Parameters Select the Options gt Serial menu item to display the following dialog box IX Mode Port No background TX Baud Rate 57600 Sync Bkgnd TX Stop Bits 1 Full Speed Bkgnd
148. f the functions or segments belonging to that chain execute memmap push options 1 memmap pop Controls the default memory area for functions The following options are available anymem the compiler decides where to place functions root functions in root memory xmemfunctions in extended memory These options are nestable to 16 levels using the push and pop options undef name Removes undefines a defined macro 126 The Language Dynamic C 32 v 6 x duse libraryname Activates a library named in LIB DIR so modules in the library can be linked with the application program This directive immediately reads in all the headers in the library unless they have already been read useix nouseix Controls whether functions use the IX register as a stack frame reference pointer or the SP stack pointer register Punctuation Punctuation marks serve as boundaries in C programs Table 5 7 lists the punctuation marks Table 5 7 Punctuation Marks Symbols Description Terminates a statement label Terminates simple statement a do loop Required by Separates items a list such as an argument list declaration list initialization list or expression list C Encloses argument or parameter lists Function calls always require parentheses Macros with parameters also require parentheses Begins and ends a compound statement a function body a structure or
149. fect unless removed by an undef directive If an attempt is made to redefine a macro without using fundef a warning will appear and the original definition will remain in effect Program Flow Three terms describe the flow of execution of a C program sequencing branching and looping Sequencing is simply the execution of one statement after another Looping 1s the repetition of a group of statements Branching is the choice of groups of statements Program flow is altered by calling a function that is transferring control to the function Control is passed back to the calling function when the called function returns In the following descriptions the recommended form allows the program mer to enclose any number of statements the body of a control structure simply by adding or deleting lines of code Strictly speaking the C language does not require this regularity Loops A while loop tests a condition at the start of the loop As long as the expression 1s true that is nonzero the loop body statement or compound statement governed by the while expression will execute If the expres sion is initially false zero the program will skip the loop body altogether Recommended form C syntax while expression while expression some statements statement 86 The Language Dynamic C 32 v 6 x A do loop tests a condition at the end of the loop As long as the expres sion is true that is nonzero
150. file or to begin at the cursor location If Case sensitive is selected the search will only find occurrences that match exactly Otherwise the search will find matches having either uppercase or lowercase letters For example reg7 Reg7 and REG7 would all match The Selection only checkbox allows the substitution to be performed only within the currently selected text This box is disabled if no text is selected When used in conjunction with the Change button it limits text replacements to within a selected block of text If Reverse is selected the search will occur in reverse that is the search will proceed toward the beginning of the file rather than toward the end of the file If No prompt is selected then the text replacement s will be made without prompting Otherwise a prompt dialog asks whether or not to make each change This is an important safeguard particularly if the Change button is clicked The keyboard shortcut for Replace is F6 48 Dynamic C Environment Dynamic C 32 v 6 x Find Next Once search text has been specified with the Find or Replace commands the Find Next command xSHIFT F5 for short will find the next occur rence of the same text searching forward or in reverse case sensitive or not as specified with the previous Find or Replace command If the previous command was Replace the operation will be a text replacement Goto Positions the insertion point at the start
151. fine riasmseq pop af jp novf PC 3 ei Notice the symbol in between the several assembly language statements on the multi line assembly macro definition lines Each symbol denotes a new logical line of assembly code When the diasmseq and riasmseq macros are used as matched pairs in assembly code they save the current interrupt enable state disable inter rupts and then later restore the previous interrupt enable state It is impor tant when making any stack references to remember to take into account that these macros use the AF register pair pushed on the stack to preserve and then restore the interrupt enable state The jp novf PC 3 instruc tion permits Dynamic C to make an absolute NB not PC relative or position independent jump a macro definition where the jump address would not be unique I E if a label was included in the macro definition at compile time C Variables C variable names may be used in assembly language What a variable name represents the value associated with the name depends on the variable For a global static local or register local variable the name represents the address of the variable in root memory For an auto variable or formal argument the variable name represents its own offset from the frame reference point See Embedded Assembly Code in Chapter 6 Using Assembly ev Language for details The name of a structure element represents the offset of the element from the beginning of
152. for download compiler option Issue the Compile to File with RTI File command Dynamic C will prompt for the name of the RTI file to use After that the Download Manager Parameters dialog box will appear Enter exactly the numbers from the DLM display in the corresponding fields on the dialog box Click the OK button Assuming successful compilation a download file will be created having the same name as the source file with a DLP extension Press 4 in the DLM menu to initiate the download Then initiate an XMODEM upload in the communication program Use the Page Up and X keys in ProComm 10 When the transfer is complete the DLP is ready to run Press 5 in the DLM menu to run it 11 To terminate the DLP and return to the DLM issue a break request in the communication program ALT B in ProComm The Download Manager menu will reappear 172 Remote Download Dynamic C 32 v 6 x The DLP File Format The DLP file created by Dynamic C has the following format 1 A 128 byte header Contents 0 DLP Root Code Bottom ulong 4 DLP Root Code Top ulong 8 DLP Xmem Code Bottom ulong 12 DLP Xmem Code Top ulong 16 DLP Root Data Bottom ulong 20 DLP Root Data Top ulong 24 DLP Xmem Data Bottom ulong 28 DLP Xmem Data ulong 32 NUMSEG uint 34 125 Reserved 126 CRC for this header uint 2 Following the header there are NUMSEG segments consisting of the following entries
153. form of comment which can be inserted anywhere and can span lines The doubl Slash comment shown below may be placed at end of line Make driver functions available duse drivers lib Define a macro E G a symbolic constant define SIZE 12 int g h Define global integers Declare prototypes for functions defined below float sumSquare int int void init Program starts here float x x is local to main init 10 Call a void function x sumSquare g h x gets sumSquare value printf x f x printf is a stan dard function void functions do things but return no value void init int a Integer argument g a g gets IE 10 h SIZE h gets the symbolic constant defined above Other functions do things and return a value float sumSquare int a int b Integer args float temp Local auto variable temp a a b b Arithmetic return temp Return value and here is the end of the program This program calculates the sum of squares of two numbers g and h which are initialized to 10 and 12 respectively The main function calls the init function to give values to the global variables g and h Then it uses the sumSquare function to perform the calculation and assign the result of the calculation to the variable x It prints the result using the library function printf which includes a formattin
154. function names begin with an underbar have important side effects and may only be called once and only once at the beginning of the main program 2 The function names do not begin with an underbar have no side effects and may be called anywhere in a program e int _sysIsSuperReset This function detects whether a super reset was requested The function returns 1 if a super reset was requested and 0 if not If a super reset was requested this function calls prot initto initialize the protected variable feature In addition it calls the function chain sysSupRstChain Additional code may be added to this function chain If a super reset was not requested this function also calls prot recover recover partially written protected variables 216 Reset Functions Dynamic C 32 v 6 x e int sysIsPwrFail This function determines whether the system had a power failure just before restarting The function return 1 if a power failure occurred and 0 otherwise A custom power failure handler cannot be used with this function e int _sysIsWDTO This function determines whether the system was reset by a watchdog timeout The function returns 1 of a watchdog timeout occurred and 0 otherwise The following is the recommended reset detection sequence It should be done before anything else in the main function main declarations if _sysIsSuperReset 9 statements 1 if _sysIsPwrFail statements
155. g string as the first argument Technical Reference The Language 81 Notice that all functions have and enclosing their contents and all variables are declared before use The functions init and sumSquare were defined before use but there are alternatives to this The Prototypes section earlier in this chapter explained this Modules Modules provide Dynamic C with the ability to know which functions and global variables in a library to use A library file contains a group of modules A module has three parts the key the header and a body of code functions and data A module in a library has a structure like this one BeginHeader func var prototype for func declaration for var EndHeader definition of func var and possibly other functions and data The Key The line a specially formatted comment BeginHeader name name begins the header of a module and contains the module key The key is a list of names of functions and data The key tells the compiler what functions and data in the module are available for reference It is impor tant to format this comment properly Otherwise Dynamic C cannot identify the module correctly If there are many names after BeginHeader the list of names can continue on subsequent lines All names must be separated by commas The Header Every line between the comments containing BeginHeader and EndHeader belongs to the header of th
156. g worked in is displayed in front of the rest Tile Horizontally The Tile Horizontally command gets Dynamic C to display windows in horizontal landscape orientation although the windows are stacked vertically Tile Vertically The Tile Vertically command gets Dynamic C to display windows in vertical portrait orientation Arrange icons When one or more Dynamic C windows have been minimized they are displayed as icons The Arrange icons command arranges them neatly Message Click the Message command to activate the Message window compi lation with errors also activates the message window because the message window displays compilation errors Watch The Watch command activates the Watch window The Add Del Items command on the Inspect menu will do this too The Watch window displays the results whenever Dynamic C evaluates watch expressions Stdio Click the Stdio command to activate the STDIO window The STDIO window displays output from calls to print If the program calls printf Dynamic C will activate the STDIO window automatically unless another request was made by the programmer see Debugger Options Technical Reference Dynamic C Environment 69 Assembly Click the Assembly command to activate the Assembly window The assembly window displays machine code generated by the compiler in assembly language format The Disassemble at Cursor or Disassemble at Address commands on the Inspect menu also activat
157. ginHeader Inc Ticks void Inc Ticks int i EndHeader asm Inc Ticks or a di ei ret endasm There are three modules defined in this code The first one is responsible for the variable ticks the second and third modules define functions Get Ticks and Inc Ticks that access the variable Note that although Inc_Ticks is actually an assembly language routine it has a function prototype in the module header allowing the compiler to check calls to Inc_Ticks If the application program calls Inc_Ticks or Get_Ticks or both the module bodies corresponding to the called routines will be compiled The compilation of these routines further triggers compilation of the module body corresponding to ticks because the functions use the variable ticks Technical Reference The Language 83 Macros Macros can be defined in Dynamic C A macro is a name replacement feature Dynamic C has a text preprocessor that expands macros before the program text is compiled The programmer assigns a name to a fragment of text Subsequently Dynamic C replaces the name with the text fragment wherever the macro name appears in the program this is a macro call In this example define OFFSET 12 define SCALE 72 int i x 1 x SCALE OFFSET the variable i gets the value x 72 12 Macros can have parameters For example define word a b a 8 b char c int i j i word j same as i 3 lt lt 8
158. greement 14 program group 14 28 support files 77 28 EDIT menu 36 41 46 47 48 49 edit mode 36 40 46 49 54 editing 222222 16 40 OPONSE inem 40 EdItoE ecd 16 OPON gen ebuseee 58 35 162 163 144 162 212 else iol 102 embedded assembly code 16 21 135 141 142 143 144 145 embedded quotes 114 End 2 22 2 222 40 41 end of mes 41 end of line sess 41 EndHeader 23 82 83 102 194 195 Enter Password 169 170 enumerated types absence ot conce 24 EPROM 16 18 19 22 25 29 30 31 32 37 40 50 64 98 99 112 164 168 182 198 201 202 208 210 212 213 file generation 60 flash 29 37 40 51 98 99 112 168 198 201 202 132 equal operator 121 ERROR EXIT 103 182 212 Index 229 errors codes 183 CdR isi 66 1 183 184 185 handler 222 22 182 standard 182 locating 49 logging 184 185 184 185 t n time eee 182 Key ete 41 to close 41 Evaluate button 36 55 examples break
159. he call The compiler automatically passes the address of the CoData structure as the first argument if a firsttime function is called from within a costatement Advanced CoData Usage Up to this point the discussion has assumed that CoData structures are static and that there is one for each costatement A costatement is like a script It specifies the sequence of operations to perform The CoData data structure on the other hand is like an actor It is responsible for acting out the script With a static CoData structure for each costatement there one actor for each script However there are instances where multiple actors are needed for the same script For example if a factory has n identical machines and there is a costatement to control the machines a program with static CoData will look like the following program for costate control sequence for machine 1 costate control sequence for machine 2 costate control sequence for machine n 158 Costatements Dynamic C 32 v 6 x Although it is extremely simple the above code is wasteful A second approach is given below CoData Machine n an array of codata blocks CoData ThisMachine one of the machines int i for i20 i n i for all machines CoBegin amp Machine i enable machine for endless loop for 0 lt i ThisMachine Machine i get machine info costate
160. he following values when used in the assembly code 1 offset 6 16 bit address in root memory i offset x offset ch offset 2 2 _16 bit addresses in root memory There is a common method to access the stack based variables 1 i ch and x Consider for example the case of loading variable x into HL The following code using the symbol GSP is one way to do it ld h1 SP x hl lt the offset from SP to the variable add hl sp hl lt the address of the variable ld a hl lt the LSB of x inc hl hl now points to the MSB of x ld h 51 lt the MSB of x ld 1 1 lt the LSB of x at this point hl has the value of x For static variables gi y and z the access is much simpler because the symbol evaluates to the address directly The following code shows for example how to load variable y into HL ld hl load hl with contents of y Technical Reference Using Assembly Language 137 Using IX Function in Root Memory Access to stack based local variables 18 fairly inefficient The efficiency improves if there is a register for a frame pointer Dynamic C can use the register IX as a frame pointer The function in the previous section would then become the following int gi this is a global variable root useix void func char ch int i long 1 auto int x static int y register int z asm some assembly code referencing gi ch i l x y and z
161. he menu title or press ALT C to select the Compile menu amp Dynamic C 32 Version 6 30 File Edit MESE Run Inspect Options Window Help emj Compile to Target F3 LE Compile to File Ctrl F3 Create RTI File for Targetless Compile Alt Ctrl F3 Compile to File with RTI File There are three ways to compile 1 Directly to a target controller connected via COM port to Dynamic C 2 Toa file with a controller connected via COM port to Dynamic C 3 Toa file with no controller connected This requires a Remote Target Information RTI file for the intended controller Use Compile to File to generate a BPF BIN DLP or NULL program file as set by the compiler options selected in the OPTIONS menu Table 4 1 summarizes the file types Table 4 1 Dynamic C Compile to File Types The Compile to File or Compile to File with RTI File command generates a BPF file Application Only This option is included for backward compatibility only and is used for downloading programs via the Program Loader Utility to RAM BIOS Application The Compile to File or Compile to File with BIOS App Library RTI File command generates a BIN BIOS App Lib SimEE EPROM file If the Create HEX File Also BIOS App Lib ClIrSEE compiler option is selected the command also generates an Intel hex format HEX file The Compile to File or Compile to File with Download via DLM RTI File comm
162. hecking 94 188 208 pointers 94 95 114 116 118 119 127 160 uninitialized 94 sme 33 52 53 POP users 105 125 126 ports serial 24 67 positioning text 49 post decrement operator 117 post increment operator 117 power fail 25 26 power failure 43 105 184 216 217 pre decrement operator 117 pre increment operator 117 precedence 115 124 preprocessor 208 preserving registers 142 143 145 preview mode 43 Previous error CTRL P 46 49 PRGLOADR EXE 176 primary register 131 135 141 142 189 primitive data types 91 92 ui edet 44 45 Properties 44 45 Technical Reference Range AT sse tud 44 44 Selection 44 Print Preview 43 44 Print Setup 222224222 45 printf 33 52 53 62 69 81 114 ProCommn 168 169 172 program 22 81 program counter PC 184 program flow 86 87 88 89 90 program group 14 Dynamic 14 28 Program Loader Utility PLU 176 222 PRGLOADR EXE 176 programmable ROM 18 19 22 25 29 30 31 32 37 40 50 51 64 98 99 11
163. hex format file HEX in addition to the BPF or BIN file Zero Time Stamp When this option is selected the compile time stamp and performance information which Dynamic C 32 normally embeds in the application code is forced to zero Thus a given version of Dynamic C 32 can always compile a fixed set of application and library code to exactly the same output file which is useful for code certification It is important to note that when this option is selected an application must not depend on the uniqueness of its compile time stamp to determine when it has been updated with a newer version The File Type for Compile to File option group specifies the file type when Compile to File or Compile to File with RTI File commands are issued The file types appear in Table 4 3 Table 4 3 Dynamic C Compile to File Types The Compile to File or Compile to File with RTI File command generates a BPF file Application Only This option is included for backward compatibility only and is used for downloading programs via the Program Loader Utility to RAM BIOS Application The Compile to File or Compile to File with BIOS App Library RTI File command generates a BIN BIOS App Lib SimEE EPROM file If the Create HEX File Also BIOS App Lib ClIrSEE compiler option is selected the command also BIN generates an Intel hex format HEX file The Compile to File or Compile to File with Download via DLM RTI Fi
164. ified bit of the PLC bus port RETURN VALUE 1 if specified bit is set else zero END DESCRIPTION d ke e e e 7 Function headers are extracted by Dynamic C to provide on line help messages Modules A library file contains a group of modules A module has three parts the key the header and a body of code functions and data A module in a library has a structure like this one BeginHeader func var prototype for func declaration for var EndHeader definition of func var and possibly other functions and data The Key The line a specially formatted comment BeginHeader name name begins the header of a module and contains the key of a module The key Is a list of names of functions and data The key tells the compiler what functions and data in the module are available for reference It is impor tant to format this comment properly Otherwise Dynamic C cannot identify the module correctly If there are many names after BeginHeader the list of names can continue on subsequent lines All names must be separated by commas 194 Software Libraries Dynamic C 32 v 6 x The Header Every line between the comments containing BeginHeader and EndHeader belongs to the header of the module When an application uses a library Dynamic C compiles every header and just the headers in the library The purpose of a header is to make certain names defined in a
165. in name Creates a function chain When a program executes the named function chain all of the functions or chain segments belonging to that chain execute No particular order of execution can be guaranteed funcchain chain name name Adds a function or another function chain to a function chain segchain chain name statements Defines a program segment enclosed in curly braces and attaches it to the named function chain Function chain segments defined with segchain must appear in a function directly after data declarations and before executable statements as shown below my_function data declarations segchain chain x some statements which execute under chain x segchain chain y some statements which execute under chain y function body which executes when my function is called Technical Reference Introduction to Dynamic C 19 A program will call a function chain as it would an ordinary void function that has no parameters For example if the function chain is named recover this is how to call it makechain recover recover Several function chains can be found in Dynamic C libraries These are listed in Appendix X Global Initialization Embedded systems typically have no operating system to perform services such as initialization of data something programmers who are accus tomed to an operating system might take for granted Various hardware devices in a system need to be initia
166. ing 185 186 Run Time Error Processing Dynamic C 32 v 6 x B B EFFICIENCY Technical Reference Efficiency 187 There are a number of methods that can be used to reduce the size ofa program or to increase its speed Nodebug Keyword Dynamic C places an RST 28H instruction in debug code at the beginning of each C statement to provide locations for break points These jumps to the debugger consume one byte and about 25 clocks of execution time for each statement A function will not have RST 28H instructions if the nodebug keyword is used in the function declaration nodebug int myfunc int x int z Once a function is nodebug it is no longer possible to single step into the function or set a break point in the function except when the assembly window is active It is possible to single step through any assembly code The nodebug keyword also reduces entry and exit bookkeeping for the function and turns off all checking for array bounds stack corruption and pointer stores If the nodebug option is used for the main function the program will begin to execute as soon as it finishes compiling as long as the program is not compiling to a file Use the nodebug keyword with the asm directive RY See Chapter 5 Using Assembly Language for more infor mation Use the directive nodebug anywhere within the program to enable nodebug for all statements following the directive The debug directiv
167. ing IX Function in Root Memory sese 138 No IX Function in Extended Memory 139 C Functions Calling Assembly Code sss 140 Assembly Code Calling C Functions esee 142 Indirect Function Calls in Assembly esses 143 Interrupt Routines in Assembly sse 143 Commion Problemis 2 tin d d e Itc 145 Technical Reference Table of Contents v Chapter 7 Costatements 147 148 dre 150 Name aset beer ee ien d 150 Staten OR pe p dee epe PE De eng 151 Malt fog s A 151 153 PLU E M 154 The CoData Structure iscissi siirre 155 The Firsttime Flag and Firsttime Functions ss 157 Advanced CoData Usage 158 Chapter 8 Interrupts 161 Interrupt Vectors i serre re le m Fever aper eee pe Rec 164 Chapter 9 Remote Download 167 The Download Manager sss 169 Enter Password eese ener neenon 169 Set Passwords ode eee i E OE UA 169 Report Parameters essere eene 169 Download Program esto RESO 170 Execute Downloaded 170 Hangup Remote Modem essere 170 guter 170 Downloaded Program 171 How to Use th
168. ion 2222 44 65 window 16 33 69 70 stack pointer SP 203 212 240 Index Stack window 70 standalone assembly code 135 programs 16 standard error handler 182 startup 212 statements voninni nots 78 static RAM 18 19 22 25 29 37 40 51 64 98 164 168 198 201 211 212 216 variables 18 19 22 24 108 125 134 135 136 138 139 188 189 208 212 status register 70 STDIO window 16 33 62 68 69 182 183 Step over F8 34 52 53 Stop lt CTRL Z gt 36 52 stop bits esses 67 stopping a running program 52 storage class 78 100 105 108 125 136 189 pun 94 default 18 19 24 208 register 22 22 94 S atlC saepe 94 aede ree 74 114 SLIDE EO ERE 205 STRING LIB 112 strings 111 113 114 125 128 extended memory 205 functions 113 IO CPI LE 91 in extended memory 128 204 205 206 terminating null byte 113 struct 78 93 95 108 116 134 136 141 142 structures 93 116 134 136 141 142 return space 136 141 142 Dynamic C 32 v 6 x subdirectories SAMPLES 76 128 206 SAMPLES AASC 169 172 subfunc 18
169. ion to Dynamic 23 Subfunctions Subfunctions allow often used code sequences to be turned into an in line subroutine within a C function The subfunction nextbyte in the following example static char nextbyte subfunc nextbyte nextbyte nextbyte can save ten or more bytes of code memory each time it is called Enumerated Types Dynamic C does not have enumerated types Default Storage Class Unlike traditional C compilers the default storage class for local variables is static not auto The default setting may be changed with the directive class Attempts to write recursive or re entrant functions will fail if this default storage class is static Recursive re entrant functions require auto variables Dynamic C and Z World Controllers Z World controllers are based on the Z180 microprocessor which has an instruction set nearly identical to that of a Zilog 780 The Z180 is a well established and popular microprocessor It is a descendent of the original 780 microprocessor but the Z180 also has the following on chip periph eral devices Dual 16 bit programmable timers Dualasynchronous serial communication ports A clocked serial communication port Dual DMA channels for high speed data transfer between memory and I O devices The Z180 has a relatively efficient instruction set At 9 216 MHz many instructions take about 1 microsecond Floating point arithmetic
170. ks and downloads directly to a Z World control ler or to a file Dynamic C functions are not compiled separately and then linked There are no pre compiled software libraries Dynamic C uses source code libraries from which necessary functions are extracted during compilation Since there are no include directives in Dynamic C source libraries make global variables and function prototypes available with special headers such as the following BeginHeader my proc my func my var void my proc int j float my func float arg extern int my var EndHeader These headers are found throughout library source code Such headers must be created to make functions known to the Dynamic C compiler if other libraries are created Function Calling Methods Dynamic C provides a choice of two function calling mechanisms Two keywords and two directives listed in Table 2 1 provide this choice Table 2 1 Function Calling Methods Key Directive Description useix Use the IX register as a frame reference pointer for useix stack based variables and arguments See Chapter 6 Using Assembly Language nouseix Use the stack pointer SP as a frame reference nouseix pointer This is the normal case It is generally more efficient to use the IX register Do not use the IX register as a frame reference pointer for functions that can be suspended under the real time kernel Technical Reference Introduct
171. l devices Z180 internal I O devices and Dynamic C This involves a 256 byte table identified by the I register that can contain addresses of up to 128 interrupt service routines Use the following preprocessor directive to set interrupt vectors in the page specified by the I register const expression function name The constant expression is the offset in bytes of the interrupt vector which is always an even number from 0 to 126 The function name is the name of the interrupt service routine The vector table can be set with assignment expressions during Dynamic C development but these assignments will not work when the code is in flash or burned into ROM Always use the preprocessor directive which is executed at compile time INT_VEC expressions are processed as they are encountered during compilation If a program specifies more than one location for a vector the last one will be used This can happen accidentally if for example an ISR is written for a device and then a library function that includes its own ISR for the same device is invoked The library ISR will be used and the written ISR will be ignored a situation that can be confusing 164 Interrupts Dynamic C 32 v 6 x Example The following program illustrates the use of interrupt service routines written in Dynamic C int PRTl init int tc initialize define TDE1 1 PRT chl down count enable define TIE1 5 PRT chl
172. le command generates a downloadable DLP program file DLP to be used by the Z World Down Load Manager DLM The Compile to File or Compile to File with RTI File command generates no output The Null Device fast compilation is useful to 1 perform Bit Bucket syntax checking 2 perform type checking or 3 get the sizes of each code and data segment 60 Dynamic C Environment Dynamic C 32 v 6 x The Warning Reports option group tells the compiler whether to report all warnings no warnings or serious warnings only It is advisable to let the compiler report all warnings because each is a potential run time bug Demotions such as converting a long to an int considered non serious with regard to warning reports The Type Checking options group tells Dynamic C to perform the appropriate type checking as described in Table 4 4 Table 4 4 Type Checking Options Prototypes Performs strict type checking of arguments of function calls against the function prototype The number of arguments passed must match the number of parameters in the prototype In addition the types of the arguments must match those defined in the prototype Z World recommends prototype checking because it identifies likely run time problems To fully use this feature all functions should have prototypes including functions implemented in assembly Demotion Detects demotion A demotion automatically converts the value of a la
173. le rather than by any formalism For a more formal treatment of the C language refer to the eo many good textbooks available Overview Program Files Programs are built by creating text files containing program code that is source files Then there are libraries files of useful functions There are many library files already in the Dynamic C LIB subdirectory The default library file extension is LIB A controller program requires at least one application file containing the main program and perhaps other functions and global data The default application file extension is C There are many sample programs in the SAMPLES subdirectory Dynamic C links the application program to functions and data in the other files selected for use with the application The compiler will extract the functions and data when needed Code in the BIOS of the target controller or the file is also linked and is very important to the program Thus the overall structure of an application consists of a main program called main zero or more functions and zero or more global data all of which are distributed throughout one or more text files The order in which these are defined 18 not very important The minimum program 18 one file containing only main 76 The Language Dynamic C 32 v 6 x Libraries are linked with the application through the use directive The use directive identifies a file from which functions a
174. ling Alt F9 Trace into Step over F8 Toggle Breakpoint F2 Toggle Hard Breakpoint Alt F2 Toggle Interrupt Flag Toggle Polling Ctrl Reset Program Ctrl F 2 Reset Target Serial Port Run Starts program execution from the current breakpoint Registers are restored including interrupt status before execution begins The keyboard shortcut is F9 Stop The Stop command places a hard break point at the point of current program execution Usually the compiler cannot stop within ROM code or in nodebug code On the other hand the target can be stopped at the rst 028h instruction if rst 028h assembly code is inserted as in line assembly code in nodebug code However the debugger will never be able to find and place the execution cursor in nodebug code The key board shortcut for this command is CTRL 2 Run w No Polling This command is identical to the Run command with an important exception When running in polling mode F9 the development PC polls or interrupts the target system every 100 milliseconds to obtain or send information about target break points watch lines keyboard entered target input and target output from printf statements 52 Dynamic C Environment Dynamic C 32 v 6 x Polling creates interrupt overhead in the target which can be undesirable in programs with tight loops The Run w No Polling command allows the program to run without polling and its overhead Any printf
175. lized not only by setting variables and control registers but often by complex initialization procedures For this purpose Dynamic C provides a specfic function chain GLOBAL INIT Any global initialization may be performed by adding segments to the GLOBAL INIT function chain as shown this example int my func long j int b 100 int 2 segchain GLOBAL INIT 40 Press any key for z 0 z lt c 2 your function code Then have the program call GLOBAL INIT during program startup or when the hardware resets This function chain executes all the global initialization statements indicated by all GLOBAL INIT segments in the program and in Dynamic C libraries as well 20 Introduction to Dynamic C Dynamic C 32 v 6 x Z World supports two levels of initialization A major initialization or super initialization takes place only when there is a need to erase all past history such as when installing a new program EPROM or when a system loses its memory A minor or normal initialization taking place every time the system resets or powers up In a minor initialization exactly which data are re initialized depends on the nature of the system ae For further detail refer to Appendix G Reset Functions and to the Dynamic C Application Frameworks manual Costatements Dynamic C provides a capability whereby the program can execute a set of tasks almost simultaneously
176. lookup Click on the Insert Call button in the lookup dialog box for the function assistant to place the function call in the program The function assistant places a prototypical call in the program when the OK button is clicked However every individual function parameter can be specified in the dialog The function assistant reminds the programmer what types the parameters have and the order of the parameters The function assistant in the following example shows that parameter 1 is named dst a commonly used abbreviation for destination and that it is a char pointer to char The word comment in the example is the expression that replaces parameter 1 in the function call 1 ek gies meem or caca t fm Lm Puncher Dampi Fari Cal CIHTRIEG LIB JINIAX char mtrcpy har dmt cher BESCERIPTION Cnpiam string to string dmt includizg tha null TEBITIZEECI BARABETERL Falntar tc lncacion rarae um PARRBETERI Pointer bo lncacion En supply string RETURN VALUE Pointer to dar iunc Comis Ht Pointer to locatiom to atr img 38 Using Dynamic C Dynamic C 32 v 6 x 4 4 Dynamic ENVIRONMENT Technical Reference Dynamic C Environment 39 Dynamic C can be used to edit source files compile programs and run programs or choose options for these activities There are two modes edit mode and run mod
177. lt common mistake is to declare and use a pointer to char thinking there is a string But an uninitialized pointer is all there 18 char string strcpy string hello invalid printf string Invalid Pointer checking is a run time option of Dynamic C Use the compiler options command in the OPTIONS menu Argument Passing In C function arguments are generally passed by value That is argu ments passed to a C function are generally copies on the program stack of the variables or expressions specified by the caller Changes made to these copies do not affect the original values in the calling program In Dynamic C and most other C compilers however arrays are always passed by address This policy includes strings which are character arrays Dynamic C passes structs by value on the stack Passing a large struct takes a long time and can easily cause a program to run out of memory Pass pointers to large structs if such problems occur For a function to modify the original value of a parameter pass the address of or a pointer to the parameter and then design the function to accept the address of the item Technical Reference The Language 95 Memory Management Z180 instructions can specify 16 bit addresses giving a ogical address space of 64 KBytes 65 536 bytes Dynamic C supports a 1 megabyte physical address space 20 bit addresses An on chip memory management unit MMU translates
178. lues 113 offsets in assembly language 134 137 139 140 online help 37 71 72 194 O Den sane er Aene 42 opening an existing file 42 Operators 115 118 123 logical NOT 117 not 121 84 85 84 85 modulus 120 S a a 123 amp address 119 amp bitwise AND 119 amp amp logical AND 122 amp 123 parentheses 116 type 118 indirection 118 multiplication 118 assign 2 22 2222 123 plus Ee 118 unary plus 118 increment sorn 117 122 Index 235 gt right arrow 116 116 division sss 119 assign sess 123 lt less i 120 lt lt shift left oo ee 120 lt lt assign 2 2222 123 lt less than or equal 120 cea then 122 equal sse 121 gt greater than 121 gt greater than or equal 121 gt gt shift right 120 gt gt 5510
179. lustrates the use of a custom error handling function that can take the place of the standard error handler void my handler uint code uint address error processing code main ERROR EXIT my handler substitute my handler some statements ERROR EXIT code addr call my own handler some statements A built in Dynamic C symbol ROM s set to 1 if the compilation is to an EPROM file Use this variable to conditionally install a custom error handler such as the one below if ROM ERROR EXIT user error handler endif i z 182 Run Time Error Processing Dynamic C 32 v 6 x Table A 1 lists the ranges of Dynamic C error codes Table A 1 Ranges of Dynamic C Error Codes 0 99 User nonfatal For example 49 overflow from pow10 100 127 System nonfatal 128 227 User fatal no return possible 228 255 System fatal no return possible Table A 2 lists the fatal errors generated by Dynamic C Table A 2 Dynamic C Fatal Errors 228 Pointer store out of bounds 229 Array index out of bounds 230 Stack corrupted 231 Stack overflow 232 Aux stack overflow 233 Not used 234 Domain error e g acos 2 235 Range error e g tan pi 2 236 Floating point overflow 237 Long divide by zero 238 Long modulus modulus zero 239 Subtraction overflow 240 Integer divide by zero 241 Unexpected interrupt 242 Execute outsid
180. mposites Composites of structures arrays unions and primitive data may be formed This example shows an array of structures that have arrays as structure elements typedef struct int x int c 32 array in structure node node list 12 array of structures Refer to an element of array c above as shown here z list n c m list 0 c 22 OxFF37 Technical Reference The Language 93 Storage Classes Variable storage can be static auto or register These terms apply to local variables that is variables defined within a function If a variable does not belong to a function it is called a global variable meaning available anywhere but there is no keyword in C to represent this fact Global variables not declared within a function always have static storage The term static means the data occupies a permanent fixed location for the life of the program The term auto refers to variables that are placed on the system stack for the life of a function call The term register describes variables that are allocated as if they were static variables but their values are saved on function entry and restored when the function returns Thus register variables can be used with reentrant functions as can auto variables yet they have the speed of static variables Variables and structures may be created dynamically from free memory space the The standard C functions malloc and free allocate
181. n Clear Watch Window Update Watch Window Ctrl U Disassemble at Cursor Ctrl F10 Disassemble at Address Alt F10 Dump at Address The Inspect menu provides commands to manipulate watch expressions view disassembled code and produce hexadecimal memory dumps The Inspect menu commands and their functions are described here 54 Dynamic C Environment Dynamic C 32 v 6 x Add Del Watch Expression This command provokes Dynamic C to display the following dialog Watch Expressions x intake Add ta top volume Del from top ES Help Close This dialog works in conjunction with the watch window The text box at the top is the current expression An expression may have been typed here or it was selected in the source code This expression may be evaluated immediately by clicking the Evaluate button or it can be added to the expression list by clicking the Add to top button Expressions in this list are evaluated and the results are displayed in the watch window every time the watch window 15 updated Items are deleted from the expression list by clicking the Del from top button An example of the results displayed in the watch window appears below Watch xj L 60 c 5 volume float 1000 lintake unsigned int 0 0 0000 gue The keyboard shortcut is CTRL W A Refer also to Watch Expressions in the Debugging section in Chapter 3 Using Dynamic C Clear Watch Window Rem
182. n entry DLM PASSWORD LVL Setting the password level to 0 enables the Set Password command to change the password at runtime DLM MIN PW LEN Sets the minimum length of a valid password DLM MAX PW LEN Sets the maximum length of a valid password THe password mus be betwen the minimum and the maximum values The program will prompt for a new password twice for verification PSW TIMEOUT Sets the number of milliseconds the DLM should wait for a password before jumping back to the DLP if one is present DLM TIMEOUT Sets the general timeout period for serial communica tions If a serial communication function times out the DLM returns control to the DLP if one is present 170 Remote Download Dynamic C 32 v 6 x HANGUP TIMEOUT Specifies the timeout period the DLM will allow for successful hangup of the modem when transferring control to the DLP If the hangup operation is unsuccessful the DLM still transfers machine control to the DLP The Downloaded Program DLP To create a downloadable program select Download via DLM DLP in the Compiler Options dialog under the OPTIONS menu Then issue the Compile to File command Dynamic C will present the Download Manager Parameters dialog shown below Download Manager Parameters Root Code Top 7579 To 0 Cancel Root Data Bottom E7 A7E5 C ToFlash Help mem Code 0000 000 Save to DLC file HEE mem Data Bottom
183. namic C 74 abstract data 80 active window 2 2 43 adc add with carry 130 Add to Top button 55 add assign operator 122 add with carry adc 130 Add Del Items lt CTRL W gt 36 55 69 Add Del Watch Expression lt CTRL W gt 35 Add Del Watch Expression CTRL 54 55 adding watch window items 54 55 address operator amp 94 119 address space 22 224 Index addresses assembly language 134 137 aggregate data types 92 ALT key ing 41 ALT Backspace 46 50 ALT CTRL F3 50 51 Lettere 41 42 nee 35 56 ALT F2 52 53 ALDEEA 3 inde 42 45 ALTE 34 52 retten 71 ALTCE 54 ALTO i sue fee 58 ren 52 ALT SHIFT backspace 46 ALISW iioii pne 68 always on 149 151 154 156 analog input sss 16 analog output 16 AND assign operator amp 123 logical operator amp amp 122 anymem 66 100 126 208 Append 0 62 application files 76 Application Only BP
184. nd data may be extracted Files identified by use directives are nestable as shown in Figure 5 1 Application X LIB Y LIB fuse x lib duse y lib maini i function bo function duse z lib function duse z lib Figure 5 1 Nesting Files in Dynamic C The Modules section later in this chapter explains how Dynamic C knows which functions and global variables in a library to use Support Files Dynamic C has several support files without which it is not possible to build an application These files are listed in Table 5 1 Table 5 1 Dynamic C Support Files Meaning DCW INI Most Windows applications have INI files This INI file is the one for Dynamic C It contains the display options and other environmental parameters DCW CFG Contains configuration data for the target controller DC HH Contains prototypes basic type definitions defines and default modes for Dynamic C This file can be modified by the programmer LIB DIR Contains pathnames for all libraries that are to be known to Dynamic C The programmer can add to or remove libraries from this list The factory default is for this file to contain all libraries on the Dynamic C distribution disk DEFAULT H Contains a set of use directives for each control product that Z World ships This file can be modified Technical Reference The Language 77 Statements Except for comments everything in a C program is a statement Virtually
185. nded RTI file format Target Communication High resolution inter character gaps have been reintroduced allowing more reliable target communication during debugging especially when combining high bps serial rates with slow controllers New Libraries GESUPRT LIB provides support for interfacing an application to Graphics Engine SF1000 Z LIB provides support for applications requiring the extra nonvolatile storage that is available from Z World s SF1000 series of Serial Flash memory cards Program Loader Utility A new chapter has been added to explain basic operation of the Program Loader Utility which is included with Dynamic C See Chapter 10 Local Upload 222 New Features Dynamic C 32 v 6 x Symbols logical NOT operator 117 operator 121 84 85 operator 84 85 asm 21 83 124 130 131 188 204 1 55 24 105 125 208 debug 101 105 107 109 125 188 define 81 84 85 86 112 125 126 125 126 125 126 endasm 21 83 124 130 131 132 sese 125 126 uetus 125 sss 125 funcchain 19 125 Wo st eds eR edis 125 Hifdef etos 126 22 126 include absence of 18 23 77 VEC 164 180 interleave
186. ngle C expression can be more than 4K long 202 Extended Memory Dynamic C 32 v 6 x However switch or while statements that cause program jumps can be as long as desired If a jump crosses page boundaries the program uses a bouncer to execute the jump While any C function can call any other C function no matter where in memory it is located calling a function located in extended memory is less efficient than calling a function in root memory That is because the program must use a bouncer to modify the CBR before and after the call A bouncer is a 4 byte code in root memory that points at the extended memory function and manipulates the stack and the CBR Because of bouncers calling extended memory functions is no different from calling root memory functions assembly language or otherwise A function entry points are in root memory Suggestions Pure Assembly Routines Pure assembly functions not inline assembly code must reside in root memory C Functions C functions can be placed in root memory or extended memory While access to variables in C statements 1s not affected by the placement of the function there is bouncer overhead to call C functions in extended memory Dynamic C will automatically place C functions in extended memory as root memory fills Short frequently used functions may be declared with the keyword root to force Dynamic C to load them in root memory Inline Assembly in C Functions Inline
187. nment 68 saving a file 42 43 saving and restoring registers 162 saving as a new file 42 Scroll bars sche eee 40 scrolling 40 A1 70 search HELP 72 Technical Reference Search for Help on 72 searching for text 47 48 49 searching in reverse 47 48 49 segchain 19 107 selecting COMPILE menu lt gt 50 EDIT menu ALT E 46 FILE menu lt gt 41 42 HELP menu lt gt 71 INSPECT menu lt gt 54 OPTIONS menu lt ALT O gt 58 RUN menu lt gt 52 WINDOW menu lt gt 68 selecting text to beginning of file 41 to end of file 41 to end of line 41 to start of line 41 serial communication 16 24 67 163 clocked sS 24 serial options 51 58 67 serial 29 67 ASC 143 PC eter ees 169 Set Password 169 170 c oso eren 163 184 setting interrupt vectors 164 jump vectors 164 SF1000 222 SF1000 7 11 222 shared variables 17 18
188. nment 63 The size and boundaries of RAM and ROM can be specified according to the information in Table 4 5 Table 4 5 Physical Memory Options Start of ROM ROM EPROM or Flash always starts at address 0000 End of ROM This option is only used to build an application or to compile to Flash Since the ROM always starts at physical address 00000 this option also specifies the size of EPROM to be built For example if 100004 64K is specified as the end of ROM an EPROM that has 64K bytes is needed for the application Start of RAM RAM starts at 40000 256K 80000 512K or 0000 640K Normally this option is set by the Auto Config feature However if code that is meant for download to RAM is compiled with multiple programs resident this option can be changed so different programs occupy different segments of RAM End of RAM The physical address where RAM ends depends on the RAM chip The difference between end of RAM and start of RAM is equal to the size of the RAM chip Max Root This is the anticipated maximum size of root code This Code parameter is meaningful only when building an application EPROM or compiling to Flash The size of root code in the actual program can be less than or equal to this amount The maximum root code size cannot exceed 44K 000 To get optimum memory allocation compile the program to the Null Device and then use the information in the informa
189. ntact with the target The key board shortcut is F3 Compile to File Compiles program to a file A target controller must be connected because Dynamic C takes configuration information from the target Any compila tion errors are listed in the message window that is activated Otherwise Dynamic C generates a file according to the compiler options that have been selected The keyboard shortcut is CTRL F3 Create RTI File for Targetless Compile It is possible to compile without a target controller present if a Remote Target Information RTI file for the intended controller is created The Compile to File with RTI File command may be used once that has been done A target controller is still needed to create the RTI file The intended target must be identical to the controller used to create the RTI file Compile to File with RTI File Compiles program to a file using RTI file created Any compilation errors are listed in the message window that is activated Otherwise Dynamic C generates a file according to the compiler options that have been selected The keyboard shortcut is ALT CTRL F3 gt Technical Reference Dynamic C Environment 51 Run Menu Click the menu title or press ALT R to select the Run menu The Run menu commands and their functions are described here Dynamic 32 Version 6 30 File Edit Compile 8 inspect Options Window Bun F3 Stop Run w No Pol
190. ode F9 the develop ment PC polls or interrupts the target system every 100 milliseconds to obtain or send information regarding target break points watch lines keyboard entered target input and target output from printf statements Polling creates interrupt overhead in the target which can be undesirable in programs with tight loops This command is useful to switch modes while a program is running The keyboard shortcut is CTRL O Technical Reference Dynamic C Environment 53 Reset Program Resets program to its initial state The execution cursor is positioned at the start of the main function prior to any global initialization and variable initialization Memory locations not covered by normal program initial ization may not be reset The keyboard shortcut for this command is 2 gt The initial state includes only the execution point program counter memory map registers and the stack pointer The Reset Program command will not reload the program if the previous execution overwrites the code segment Reset Target Tells the target system to perform a software reset including system initialization Resetting a target always brings Dynamic C back to edit mode The keyboard shortcut 15 CTRL Y gt Close Serial Port Closes the serial port currently in use by Dynamic C Inspect Menu Click the menu title or press ALT b to select the INSPECT menu Options Window Help Add Del Watch Expressio
191. of the specified line The follow ing dialog is displayed when the Goto command is issued Line Number E Cancel Type the line number or approximate line number to which to jump That line and lines in the vicinity will be displayed in the source window Previous Error Locates the previous compilation error or warning in the source code Any errors or warnings will be displayed in a list in the message window after a program is compiled Dynamic C selects the previous error or warning in the list and positions the offending line of code in the text window when the Previous Error command CTRL P for short is made Use the keyboard shortcuts to locate errors or warnings quickly Next Error Locates the next compilation error or warning in the source code Any errors or warnings will be displayed in a list in the message window after a program is compiled Dynamic C selects the next error or warning in the list and positions the offending line of code in the source window when the Next Error command CTRL N gt for short is made Use the keyboard shortcuts to locate errors or warnings quickly Edit Mode Switches Dynamic C back to edit mode from run mode also called debug mode After a program has been compiled or executed Dynamic C will not allow any modification to the program unless the Edit Mode is selected The keyboard shortcut is F4b Technical Reference Dynamic C Environment 49 Compile Menu Click t
192. ommand gets Dynamic C to display the following dialog Display Options x Window Attribute Error Editor Background Coloi Debug Editor Foreground Color Message Selection Bg Watch Selection Fg Stdio Close Use the Display options dialog box to change the appearance of Dynamic C windows First choose the window from the window list Then select an attribute from the attribute list and click the change button Another dialog box will appear to make the changes Note that Dynamic C allows only fixed pitch fonts and solid colors if a dithered color is selected Dynamic C will use the closest solid color The Editor window attributes affect all text windows except two special cases After an attempt is made to compile a program Dynamic C will either display a list of errors in the message window compilation failed or Dynamic C will switch to run mode compilation succeeded In the case of a failed compile the editor will take on the Error Editor at tributes In the case of a successful compile the editor will take on the Debug Editor attributes 66 Dynamic C Environment Dynamic C 32 v 6 x Serial The Serial command gets Dynamic C to display the following dialog Serial Options Port rw z zg EX Mode No background TX Baud Rate 18200 e x 2 e Stop Bits 1 Full Speed Bkgnd TX Use this dialog to tell Dynamic C how to communicate
193. only if the costatement has a name The CSState flag has no meaning for unnamed costatements Last Location The two fields lastlocADDR and lastlocCBR represent the 24 bit address of the location at which to resume execution of the costatement If lastlocADDR is Zero as it is when initialized the costatement executes from the beginning subject to the CSState flags If lastlocADDR is non zero the costatement resumes at the 24 bit address represented by lastlocADDR and lastlocCBR These fields are zeroed when 1 the CoData structure is initialized by a callto GLOBAL INIT CoBegin or CoReset 2 the costatement is executed to completion or 3 the costatement is aborted 156 Costatements Dynamic C 32 v 6 x Check Sum The ChkSum field is a one byte checksum of the address It is the exclusive or result of the bytes in lastlocADDR and lastlocCBR If ChkSum is not consistent with the address the program will generate a run time error and reset The checksum is maintained automatically It is initialized by GLOBAL INIT CoBegin and CoReset First Time The firsttime field is is a flag that is used by waitfor statements It is set to 1 before the waitfor expression is evaluated the first time This aids in calculating elapsed time for the functions DelayMS DelaySec and DelayTicks Content The content field a union is used by the costatement delay routines to store a delay count Check Sum 2 The ChkSum2 field is currentl
194. onstants match the switch expression typedef lIdentifies a type definition statement Abstract types be defined in C typedef struct int x int y xyz defines a struct type xyz thing and a thing of type xyz typedef uint node meaningful type name node master slavel slave2 union ldentifies the beginning of a union Items in a union have the same address The size of a union is that of its largest member union int x float y abc overlays a float and an int Technical Reference The Language 109 unsigned Declares a variable or array to be unsigned If nothing else is specified a declaration unsigned means 16 bit unsigned integer unsigned i j k 16 bit unsigned unsigned int x 16 bit unsigned unsigned long w 32 bit unsigned unsigned funct unsigned arg Values in a 16 bit unsigned integer range from 0 to 65 535 instead of 32768 to 32767 Values in an unsigned long integer range from 0 to 2 1 useix Indicates that a function uses the IX register as a stack frame pointer useix void func Go See also nouseix and directives useix and nouseix waitfor Used in a costatement this keyword identifies a point of suspension pending the a condition completion of an event or a delay for costate Waitfor input 1 HIGH GS See Chapter 7 Costatements while Identifies the beginning of a while
195. operand evaluates true nonzero then the result of the operation 1s the second operand Otherwise the result is the third operand int i j k i j lt k j k The operator is for convenience The above statement is equivalent to the following if j lt k i j else i k If the second and third operands are of different type the result of this operation is returned at the higher precision Assignment This binary operator causes the value of the right operand to be assigned to the left operand Assignments can be cascaded as shown in this example 10 gets the result of the calculation 0 b gets 0 and a gets 0 Addition assignment a t 5 Add 5 to a Same as 5 Subtraction assignment 5 Subtract 5 from Same 5 122 The Language Dynamic C 32 v 6 x lt lt gt gt Multiplication assignment 5 Multiply 5 Same 5 Division assignment a 2 5 Divide a by 5 Same 5 Modulo assignment a 5 mod 5 Same 5 Left shift assignment lt lt 5 Shift left 5 bits Same as a lt lt 5 Right shift assignment gt gt 5 Shift a right 5 bits Same as gt gt 5 Bitwise AND assignment a amp b AND a with b Same amp b Bitwise XOR assignment b XOR
196. or more comprehensive information on changes Dynamic C 32 IDE Compiler Options Output Generation Group The Zero Time Stamp checkbox has been added to help facilitate code certification When enabled forces to zero the compile time stamp and compiler performance information which is embedded into the compiled code Identical compiler output will always generated given a fixed set of Dynamic C 32 compiler version and options application code and library code Compiler Options File Type for Compile to File Group The compile to BIN EPROM file options have been expanded to include the ability to create BIN files which can communicate with Dynamic C or the Program Loader Utility after being externally programmed into a Flash EPROM chip The simulated EEPROM area options include replacing it copying from the attached controller or new style RTI file clearing zeroing it or excluding it not specifically programming the Flash chip s simulated EEPROM area at all In support of the new BIN file options the Remote Target Information RTI file has been extended to include a Flash equipped source controller s simulated EEPROM area While Dynamic C 32 version 6 30 can use a RTI file created by a previous version of Dynamic C a BIN file created by compiling to file with an older RTI file effectively only gives the choice between clearing or excluding the simulated EEPROM area Previous versions of Dynamic C can not use the exte
197. oves entries from the watch dialog and removes report text from the watch window There is no keyboard shortcut Technical Reference Dynamic C Environment 55 Update Watch Window Forces expressions in the watch expression list to be evaluated and displayed in the watch window Normally the watch window is updated every time the execution cursor is changed that is when a single step a break point or a stop occurs in the program The keyboard shortcut is lt CTRL U gt Disassemble at Cursor Loads disassembles and displays the code at the current editor cursor This command only works in user application code not the libraries that is not declared nodebug This command does not stop the execution on the target either The keyboard shortcut is CTRL F10 Disassemble at Address Loads disassembles and displays the code at the specified address This command produces a dialog box that asks for the address at which disassembling should begin Addresses may be entered in two formats a 4 digit hexadecimal number that specifies any location in the root space the valid range is 2000h to DFFFh or a 2 digit CBR page number followed by a colon followed by a 4 digit logical address the page number ranges from 00h to FFh while the valid range for the logical address is from 000 to FFFFh Note that the disassembler rejects any attempt to disassemble code between address 00000h and 02000h in the physical memory regardless of how th
198. pproaches are competitive Nonetheless the use of X offset is always beneficial when used to access single or double byte variables The offset from IX is a signed 8 bit integer To use X offset the variable must be within 127 or 128 bytes of the frame reference point The SP method is the only method for variables out of this range even if IX is used as a frame reference pointer No IX Function in Extended Memory Functions that are possibly compiled to extended memory are not much different from functions compiled to root memory Examine this extended memory function int gi this is a global variable xmem void func char ch int i long 1 auto int x static int y register int z asm xmemok Some assembly code referencing gi ch i 1 x y and z endasm If the xmem keyword is present Dynamic C compiles the function to extended memory Otherwise Dynamic C can determine where to compile the function On the other hand the xmemok keyword must be present since this function is compiled to extended memory Technical Reference Using Assembly Language 139 This is because functions compiled to extended memory have a 6 byte return address instead of a 2 byte return address In this example the IX register is not used Figure 6 5 shows the stack frame of the function L 1 4 4 10 m iQ 6 ch 2 L return address 6 4 OL _ lt frame reference point
199. r to array of 10 ints float y ptr to a ptr to a float 2 2 gets the value of y typedef char stp stp my stuff my stuff is typed char As a binary operator the indicates multiplication a gets the product of b and c type Cast operator The cast operator converts one data type to another Floating point values are truncated when converted to integer The bit patterns of character and integer data are not changed with the cast operator although high order bits will be lost if the receiving value is not large enough to hold the converted value unsigned i float x 10 5 char c i unsigned x i gets 10 c char amp x c gets the low byte of x typedef typeA typedef typeB 118 The Language Dynamic C 32 v 6 x typeA iteml typeB item2 item2 typeB item1 forces iteml to be treated as a typeB amp Address operator or bitwise AND As a unary operator this provides the address of a variable int x 2 amp X 2 gets the address of x As a binary operator this performs the bitwise AND of two integer char int or long values int i OxFFFO int j OxOFFF z i6 amp j z gets OxOFFO Sizeof The sizeof operator is a unary operator that returns the size in bytes of a variable structure array or union It operates at compile time as 1f it were a built in function taking an object or a type as a parameter typedef struct
200. rectives Directives are special keywords prefixed with the symbol They tell the compiler how to proceed Only one directive per line is allowed but a directive may span more than one line if a backslash is placed at the end of the line s asm options endasm Begins and ends blocks of assembly code The following options are available nodebug disable debug code during assembly debug enable debug code during assembly xmemok OK to compile to extended memory when assembly code is embedded in a C function 124 The Language Dynamic C 32 v 6 x class push options 1 class pop Controls the default storage class for local variables The following options are available auto local variables are placed on the stack static local variables have permanent fixed storage These options are nestable to 16 levels using the push and pop options debug nodebug Enables or disables debug code compilation define name text define name params text Defines a macro with or without parameters A macro without param eters may be considered a symbolic constant But in actuality it is not fatal error 7 warns 7 warnt 7 Instructs the compiler to act as if a fatal error fatal an error error a serious warning warns or a trivial warning warnt was issued The string in quotes following the directive is the message to be printed funcchain chain name
201. rger or more complex type to the value of a smaller or less complex type The increasing order of complexity of Dynamic C s scalar types is char unsigned int int unsigned long long float A demotion deserves a warning because information may be lost in the conversion For example when a long variable whose value is 0x10000 is converted to an int value the resulting value is 0 The high order 16 bits are lost An explicit type casting can eliminate demotion warnings demotion warning reports are considered non serious Pointer Generates warnings if pointers to different types are intermixed without type casting While type casting has no effect in straightforward pointer assignments of different types type casting does affect pointer arithmetic and pointer dereferences All pointer warning reports are considered non serious Technical Reference Dynamic C Environment 61 The Optimize For option group optimizes the program for size or for speed When the compiler knows more than one sequence of instructions that perform the same action it selects either the smallest or the fastest sequence depending on the programmer s choice for optimization The difference made by this option is less obvious in the user application in which most code is not marked nodebug The speed gain by optimiz ing for speed is most obvious for functions that are marked nodebug and have no auto local stack based variables Debugger
202. rite the target controller s BIOS symbol library or simulated EEPROM area located at the end of the Flash However if this type of BIN file is externally programmed into a blank EPROM which is then installed into the target controller communication with Dynamic C or the PLU is no longer possible This is because the BIOS s symbol library is excluded from the BIN file which can be useful in situations where extra code security is desired Also excluded from the BIN file is the simulated EEPROM area located at the end of a Flash BlOS ApptLibrary BIN When this option is selected the Compile to File commands generate a BIN Flash EPROM file containing the BIOS code of the target control ler where the BIOS library functions are located the compiled applica tion code and the BIOS s symbol library located near the end of the Flash It is important to note that the Flash s simulated EEPROM area is excluded from the BIN file This option is useful only for externally programmed Flash types it should not be used to generate BIN files intended for loading to the target controller via the Program Loader Utility PLU After installing the externally programmed Flash into the target controller communication with Dynamic C or the PLU is still possible Note that the Flash s simu lated EEPROM area may or may not have been modified by the external device programmer BIOS App Lib SimEE BIN When this option is selected the
203. rld controller connected to a development system or 2 a copy of the BIOS an RTI file depending on the compile command selected Layout of Downloadable Files Select the Download via DLM DLP compiler option for downloadable files AY Details of the file format are found in Chapter 9 Remote Download 210 File Formats Dynamic C 32 v 6 x Layout of Download to RAM Files Select the Application Only BPF compiler option The following diagram shows the locations of different segments in a RAM file End of File XMEM CODE root data 48K root code RAM start Uninitialized data do not occupy any space in the RAM file The root is always 48 kbytes long The load address for the code in RAM is embed ded in the file output The default load address is 40000 256 kbytes or 80000 512 kbytes but can be changed A RAM file starts with root code and not the BIOS as the BIOS is expected to be in the ROM of the receiving controller memory map for 32 kbyte SRAM is as above but the architecture takes advantage of memory reflection The default code data gap is 8000 32 kbytes This results in the actual layout of the code in the RAM as shown below 64K XMEM 48K 32K memory data reflection root code 32K XMEM 16K 92K real data memory root code Technical Reference File Formats 211 The root data appear to start at 48 kbytes and at 80 kbytes 112 kb
204. rmat 212 HEX fil s n me 60 HEX format 30 60 210 212 interrupt service routines 17 21 104 106 143 144 145 162 163 164 165 162 165 interrupt status and break points 35 52 53 interrupt vectors setting 2 164 232 Index interrupts 21 104 106 107 143 144 145 162 163 164 165 170 218 tete ete 212 disabling ne 163 35 53 latency iic 143 163 Mode 0 164 Model 23 ih 164 2 164 Service routines 21 IntervalMS ssss 149 Interval Seo es maneo 149 isCoDone 150 156 isCoRunning 150 156 ISR interrupt service routines 162 164 IX index register 18 23 105 110 127 131 138 139 140 143 184 189 190 203 208 IY index register 131 143 J jump vectors 164 kernel real time 25 190 key module 82 194 keyboard shortcuts 72 keystrokes esses 72 ALT E gt select EDIT menu 46 ALT R gt select RUN menu 52 lt ALT Backspace gt undoing changes 2 2 2 46 lt ALT C gt select COMPILE ce 50 lt ALT CTRL F3 gt Compile to File with RTI File 51 lt ALT F gt select FILE men
205. routine within the scope of a C function func int aname subfunc aname k inport x k 4 The subfunction is prototyped as if it were a regular function It must be static and may not have any arguments Variables used within the subfunction must be available within the scope of the parent C function The actual code after the sub unc keyword can appear anywhere in the enclosing function The return value if any is indicated by placing an expression followed by a semicolon at the end of the subfunction body This causes the expression value to be loaded into the primary register HL or BCDE Technical Reference Efficiency 189 subfunction calls take three bytes low overhead compared to some simple expressions For example the expression ptr can generate 14 bytes or more Substitute the following code static char nextbyte subfunc nextbyte nextbyte nextbyte This can save ten or more bytes each time nextbyte occurs Subfunctions can also make a program easier to read and understand if descriptive names are used for obscure expressions The advantage of the subfunction over a regular function is that it has access to all the variables within the program and the calling overhead is low Observe that the equivalent C function nextbyte char ptr return can be used for the same purpose However the calling overhead is much
206. rray of 10 integers represents a contiguous group of 10 integers Array elements are refer enced by their subscript j item n the nth element of item Array subscripts count up from 0 Thus item 7 above is the eighth item in the array Notice the and enclosing both array dimensions and array subscripts Arrays can be nested The following doubly dimensioned array or array of arrays int matrix 7 3 is referenced in a similar way scale matrix i j The first dimension of an array does not have to be specified as long as an initialization list is specified int x 2 1 2 3 4 5 6 Y char string abcdefg 92 The Language Dynamic C 32 v 6 x Structure Variables may be grouped together in structures struct in C or in arrays Structures may be nested struct 4 char flags struct 4 int x int y loc cursor Structures can be nested Structure members the variables within a structure are referenced using the dot operator j cursor loc x The size of a structure is the sum of the sizes of its components Union A union overlays simple or complex data That is all the union members have the same address The size of the union is the size of the largest member union int ival long jval float xval u Unions can be nested Union members the variables within a union are referenced like structure elements using the dot operator j u ival Co
207. rs U L X or A F or their lower case equivalents A decimal point or the presence of the letter E or F indicates that a number is real has a floating point representation 112 The Language Dynamic C 32 v 6 x Integers have several forms of representation The normal decimal form is most common 10 327 1000 0 An integer is long 32 bit if its magnitude exceeds the 16 bit range 32768 to 32767 or if it has the letter L appended OL 32L 45000 327671 An integer is unsigned if it has the letter U appended It is long if it also has L appended or if its magnitude exceeds the 16 bit range 09 42949672940 327670 170001 An integer is hexadecimal if preceded by Ox7E 0 000 OxFFFFFFFA It may contain digits and the letters or A F An integer is octal if begins with zero and contains only the digits 0 7 0177 020000 000000630 A real number can be expressed in a variety of ways 4 5 means 4 5 Af means 4 0 0 3125 means 0 3125 456e 31 means 456 x 10 0 3141592e1 means 3 141592 Strings and Character Data A string 15 a group of characters enclosed in double quotes Press any key when ready Strings in C have a terminating null byte appended by the compiler Although the C language does not have a string data type it does have character arrays that serve the purpose Dynamic C does not have string operators such as concatenate but library functions are available Q See STRING LIB in the D
208. ry dump in the window above Technical Reference Dynamic C Environment 57 Options Menu Click the menu title or press ALT O to select the OPTIONS menu The Options menu commands and their functions are described here 32 Version 6 30 File Edit Compile Run Inspect Window Help Sle ded E Debugger Memory Display Serial v Show Tool Bar Save environment Editor The Editor command gets Dynamic C to display the following dialog Editor Options x TabStops E Auto Indent Remove Trailing Whitespace Use this dialog box to change the behavior of the Dynamic C editor By default Tab Stops are set every three characters but may be set to any value greater than zero Auto Indent causes the editor to indent new lines to match the indentation of previous lines Remove Trailing Whitespace causes the editor to remove extra space or tab characters from the end of a line 58 Dynamic C Environment Dynamic C 32 v 6 x Compiler The Compiler command gets Dynamic C to display the following dialog which allows compiler operations to be changed Compiler Options x Warning Reports 25 All Pointers Serious Only Stack C None Output Generation Type Checking Create HEX File Also Prototype Zero Time Stamp Demotion Pointer File Type for Compile to File
209. s and try again 178 Local Upload Dynamic C 32 v 6 x Select the Program File Click on the File gt Upload menu item to display the following dialog box Upload PC to Target Lx File type Upload bin file from 2000h to target Flash Only C Uploadientire lt to Flash Generic upload entire file Physical Address 2000 Run after upload The PLU defaults to the appropriate program file Upload type for the attached target controller Subject to the cautions and disclaimers expressed previously click on Generic upload entire file to override the program file type The Physical Address Hex edit box is enabled allowing unrestricted upload directly to any physical address Select the Run after upload checkbox to optionally start the uploaded program immediately after uploading it Click the OK button to proceed to the file selection dialog Look in a Tech_sup e 691 0157 bin Sprintf3 bin Sprintf9 bin Sprintf4 bin Z180info bin Sprintf bin Sprintf5 bin sprintfQ bin Sprintf amp bin sprintf bin Sprintf bin sprintf2 bin Sprintf8 bin File name Fri 3307 bin Files of type Bin Files BIN Cancel Browse to find and select the uploadable program file which must be located on a local drive or network drive accessible to the PC tha
210. s 14 Installation Procedure essere 14 Chapter 2 Introduction to Dynamic C 15 Why ETE 16 The Nature of Dynamic 16 Nn 17 Dynamic is Different tt 17 How Dynamic C Differs sess 18 Initialized Variables essen 18 Function Chaining ence E HR 19 Global Initialization sess 20 Costatemehlts e ebbe ders 21 Interrupt Service Routines essere 21 Embedded Assembly 21 Shared and Protected Variables esses 22 Extended Memoty ec NAR ORE Be 22 External Functions and Data eese 22 Function Calling Methods seen 23 SubfutiCtlolls ei beo eee 24 Enumerated Types oe tm ete dem ime iret 24 Default Storage 24 Dynamic and Z World Controllers eee 24 Physical Memory essere 25 Watchdog Eimer ie es RE RR 25 Real Time Operations essen 25 Restart Conditions ooo te RR ERRARE 25 Technical Reference Table of Contents iii Chapter 3 Using Dynamic C 27 TristallatiOn oen 28 Writing Programs en e er esee e AREE 28 Compiling Programs essens enese aE RE 28 Compiler Options 30 Debugging Programs cccccsceescesceeseeeeeeseceeeeseesceeseenseeaeeeeeseensee
211. s Dynamic C 32 to update its Windows Registry entries and the DCW CFG configuration file immediately with the current options settings Dynamic C always updates these items on exit Saving them while working provides an extra measure of security Window Menu Click the menu title or press ALT W to select the Window menu amp Dynamic C 32 Version 6 30 File Edit Compile Run Inspect Option elp Ty e s Re Hle Glen oona Tile Vertically Arrange icons Message Watch Stdio Assembly Registers Stack Information v 1 U WSS Z180 DC_32 DISTRIBSSAMPLES DEMO_RT C The first group of items is a set of standard Windows commands that allow application windows to be arranged in an orderly way 68 Dynamic C Environment Dynamic C 32 v 6 x The second group of items presents the various Dynamic C debugging windows Click on one of these to activate or deactivate the particular window It is possible to scroll these windows to view larger portions of data or copy information from these windows and paste the information as text anywhere The contents of these windows can be printed The third group is a list of current windows including source code windows Click on one of these items to bring that window to the front The individual Window menu commands are described here Cascade The Cascade command gets Dynamic C to display windows top of each other but with a small offset The window bein
212. s Dynamic C to choose between root memory and extended memory 3 The nodebug option is enabled when compiling code to ROM if ROM nodebug The nodebug global directive has extensive implications for gener ated code Stack index and pointer checking are disabled debugging features are removed from the code especially RST 28s which are used for break points This generates smaller code that runs efficiently 4 The default for the use of the IX register is nouseix 208 Compiler Directives Dynamic C 32 v 6 x F FORMATS Technical Reference File Formats 209 Use the Compile to File or Compile to File with RTI File command to generate an output file Select the appropriate output file format in the Compiler Options dialog Layout of ROM Files When a program say filename C is compiled for ROM the compiler generates a file named filename BIN Dynamic C can also create an extended Intel HEX file filename HEX Select the BIOS Application BIN compiler option Check the Create HEX File Also box to create an Intex hex file The resulting file contains the three code segments back to back Initial ized data are constants and considered code Unitialized data are not included in the ROM file uide XMEM CODE ROOT CODE BIOS 00000 The BIOS included in the ROM file is either 1 a copy of the first 2000 of ROM of a Z Wo
213. s a function prototype long tick_count char clock_id this is the function s definition long tick_count char clock_id Technical Reference The Language 79 It is not necessary to provide parameter names in a prototype but the parameter type 18 required and all parameters must be included If the function accepts a variable number of arguments as printf does use an ellipsis this prototype is as good as the one above long tick count char this is a prototype that uses ellipsis int startup device id Type Definitions Both types and variables may be defined One virtue of high level languages such as C and Pascal is that abstract data types can be defined Once defined the data types can be used as easily as simple data types like int char and float Consider this example typedef int MILES basic type named MILES typedef struct a structure type float re float im COMPLEX named COMPLEX MILES distance declare variable of type MILES COMPLEX z zp declare complex variable and ptr Use typedef to create a meaningful name for a class of data Consider this example typedef uint node void NodeInit node informative type name void NodeInit uint not very informative 80 The Language Dynamic C 32 v 6 x This example shows many of the basic C constructs Put descriptive information in your program code using this
214. s sent 19575 DCOO DBFF 0000 Re send bytes 0 The information window displays how the memory is partitioned and how well the compilation went In this example no space has been allocated to the heap or free space The base and top of these memory partitions can be changed with commands from the Options menu Help Menu Click the menu title or press ALT H to select the Help menu The Help menu commands and their functions are described here File Edi Compile Run Inspect Options Window T gaius 28 SAS Contents LI Izd e 5 0 Ss pu Keystrokes Search for Help on Library Help Lookup Ctrl H About Contents This standard item displays the contents page of the on line help system Technical Reference Dynamic C Environment 71 Keystrokes Select this item for information on available keystrokes and their func tions Many commands on the Dynamic C menus are also available directly through the keyboard In addition some operations can only be performed through the keyboard certain cursor movement and editing operations Search for Help on Select this standard item to search for help on a particular topic Type in a keyword and press ENTER to see a list of related topics Then select a topic from the list and press ENTER again to view the topic Library Help Lookup Obtains help information for library functions When a function name is clicked or selected in source
215. seenes 32 Poll cte tete tee ee e eei ied 33 Disassembl t ba Da p edits 34 Single Stepping erecto eire erae edes 34 Break PO mts 35 Watch 101 5 secte ete cerei 35 Returning to Edit Mode sese 36 Creating Stand alone Programs sse 36 Controller with Program in EPROM eee 37 Controller with Program in Flash Memory 37 Controller with Program in 37 Help Renee tette torre de 37 Function Lookup odere eei e eee 37 Function Assistance ccc ie etie ea ERRARE e Reed 38 Chapter 4 Dynamic C Environment 39 Editing 40 Mis E 41 File Menu inue e Bue nidi 42 Edit eee tones PD Least 46 Compile Menu ie cease 50 Run Mns nee op Ot s 52 Inspect Menus tee te tete p 54 Options Men hide ee tede ep od ee id 58 Window Menus Ht at 68 Help Mens e ete e a a E EE erg 71 Chapter 5 The Language 75 OVERVIEW PEE 76 Program Files 2 mee tc ere ar era iR 76 Support ai i re Gere tete ie tuti m DN TI Statements aee eet eta e qe ee PS 78 D clarations te kir eu HO ies 78 FUNCIONS esie oe E eer Ee E S GS EE ie 78 lg 79 Type Definitions eR TREE 80 Up er RE 82 iv Table of Contents Dynamic C 32 v 6 x Program FLOW uon nene
216. seful to show how variables registers or the stack change during execution of the program An important aspect of the Dynamic debugger is that it is symbolic This means that the executing program is linked to source code The part of the program that is executing is highlighted in the source code window When expressions variables and functions are evaluated they are evaluated in C using the names in the application and normal integer floating and character representations of constants apply The execution of the program can also be viewed at the machine level Polling Under normal debugging conditions Dynamic C monitors the activity on the target controller The controller is interrupted every 100 milliseconds This is called polling If your the application has very tight timing requirements these interrupts could cause the application to fail Dynamic C allows polling to be enabled or disabled at the programmer s option Technical Reference Using Dynamic C 33 There are three commands on the RUN menu Run with polling Run w No Polling and Toggle Polling allows user to control polling Single Stepping Often there is a need simply to observe the program execute statement by statement There are two commands on the RUN menu for single stepping Trace into with descent into function calls and Step over prevents descent into function calls An execution cursor highlights the current source statement or
217. set up here The Printer button allows you to specify the printer to be used and to set its Properties as has been previously covered in the File Print descrip tion Exit To exit Dynamic C When this is done Windows will either return to the Windows Program Manager or to another application The keyboard shortcut is ALT F4 Technical Reference Dynamic C Environment 45 Edit Menu Click the menu title or press ALT E to select the EDIT menu The Edit menu commands and their functions are described below Dynamic 32 Yersion 6 30 File Compile Inspect Opt Undo Alt Bksp Redo Shift Alt Bksp Cut Ctrl g Copy Ctrl C Paste Etre Find F5 Replace Find Next Shift F5 Goto Ctl G Previous Error Ctrl P Next Error Ctrl N Edit Mode F4 Undo Undoes recent changes in the active edit window This command may be repeated several times to undo multiple changes The amount of editing that may be undone will vary with the type of operations performed but should suffice for a few large cut and paste operations or many lines of typing Dynamic C discards all undo information for an edit window when the file is saved The keyboard shortcut is Redo Redoes modifications recently undone This command only works immediately after one or more Undo operations The keyboard shortcut is lt ALT SHIFT BACKSPACE Cut Removes selected text from
218. spended some are executing With the passage of time other costatements suspend and others resume Placing the costatements in a loop 1s the simplest way to give each costatement a chance to progress in its turn Costatements can be active ON or inactive OFF A costatement may be declared to be always on initially on or initially off A costatement that is initially on will execute once and then become inactive A costatement that is initially off will not execute until it is started by some other part of the program Then it will execute once and become inactive again For each costatement there is a structure of type CoData that supports its operation For example the CoData structure maintains a position pointer that tells the costatement where to resume execution when it has been suspended Costatements may be named or unnamed An unnamed costatement is always on The name of a named costatement can be one of the follow ing Avalid C name not previously used This results in the creation of a structure of type CoData of the same name The name ofa local or global CoData structure that has already been defined A pointer to an existing structure of type CoData Technical Reference Costatements 149 A CoData structure may be declared independently of a costatement Thus many costatements can use a single CoData structure one at a time A single costatement may point to different CoData struc
219. structures and unions instead of the dot operator typedef struct int x int y coord coord p ptr to structure m p gt x ref to structure element 116 The Language Dynamic C 32 v 6 x Logical NOT This is a unary operator Observe that C does not provide a Boolean data type In C logical FALSE is equivalent to 0 Logical TRUE is equivalent to nonzero The NOT operator result is 1 if the operand is 0 The result is 0 otherwise test get_input if test Bitwise complement This is a unary operator Bits in a char int or long value are inverted int switches switches OxFFF0 j switches j becomes 0x000F Pre or post increment This is a unary operator designed primarily for convenience If the precedes an operand the operand is incremented before use If the operator follows an operand the operand is incremented after use int i a 12 i 0 1 gets a 0 then i becomes 1 r r gets a 1 then i becomes 2 S tti i becomes 3 then s itt i becomes 4 If the operator is used with a pointer the value of the pointer increments by the size of the object bytes to which it points With operands other than pointers the value increments by 1 Pre or post decrement This is a unary operator designed for convenience If the precedes an operand the operand is decremented before use If the operator follows an op
220. system RESET line is pulled low and released Power drops below a threshold the supervisor chip pulls RESET low and causes a reset Power Fail Reset Software failed to hit the watchdog timer It pulls RESET low and causes a reset Watchdog Reset In addition to these hardware resets an application may cause a super reset Z World s super reset is a mechanism to initialize certain persistent data in battery backed RAM A normal reset does not initialize these data but retains their values A super reset always occurs when a program is first loaded Subsequent resets are normal resets unless the software performs a super reset intentionally Technical Reference Introduction to Dynamic C 25 Dynamic C includes the functions listed in Table 2 3 to differentiate the various resets Table 2 3 Reset Functions This function detects whether a super reset was requested It also manages protected variables and calls the sysSupRstChain function chain _sysIsSuperReset This function determines whether the system SysIsPwrFail had a power failure just before restarting This function determines whether the system was reset by a watchdog timeout SyslIsWDTO If these reset functions are to be used call them before doing anything else in the main function Dynamic C can generate two types of system reset The function sysForceReset causes a watchdog reset The function
221. system menus An available command can be executed from a menu by clicking the menu and then clicking the command or by 1 pressing the ALT key to activate the menu bar 2 using the left and right arrow keys to select a menu 3 and using the up or down arrow keys to select a command and 4 pressing ENTER It is usually more convenient to type keyboard shortcuts such as lt CTRL H gt for Help once they are known Pressing the ESC key will make any visible menu disappear A menu can be activated by holding the ALT key down while pressing the underlined letter of the menu name use the space bar and minus key to access the system menus For example type ALT F gt to activate the File menu Technical Reference Dynamic C Environment 41 File Menu Click the menu title or press ALT F to select the File menu The File menu commands and their functions are described below a Dynamic C 32 Version Edit Compile Run Save Ctrl S Print Preview Print Print Setup Exit Alt F4 New Creates a new blank untitled program in a new window Open Presents a dialog in which to specify the name of a file to open Unless there is a problem Dynamic C will present the contents of the file in a text window The program can then be edited or compiled Look in a Samples z e 24 C Vwdog EF Demo r c Pro asyn c Pk25xx 22104 Enoutput c Prtdemo c Plcbus Bdtemp c Laflash c Psflash c
222. t is running the PLU Technical Reference Local Upload 179 Click the Open button to start uploading the selected program file A message box similar to this one displays the upload progress 3200 bytes transferred to target When the progress message box disappears the PLU has finished upload ing the program file to the target controller If the Run after upload checkbox was enabled before the upload then the controller should begin to run the newly uploaded application The controller should be returned to run mode in order to assure that the program will resume execution after the next power interruption As mentioned before this often entails setting a jumper or pressing keys and either cycling power or pressing a reset button Consult the specific controller s hardware manual for details Common Problems Reuse of programming port application program intended for upload via the PLU which reuses a serial port that is used by the PLU for communication with the target controller raises special concerns In particular if the PLU communicates with the target controller via Z0 or a PLCBus UART board the application must use the run time reload vec function to set the 70 or INTI respectively interrupt service vector instead of the INT_VEC compile time directive Manual software reset Although the PLU attempts a software reset of the target controller at start up it does not automatically attempt a software reset
223. t time from the stack Otherwise it is more efficient to compute a new SP instead The following code demonstrates how to unwind arguments totaling 36 bytes of stack storage note that HL is changed by this code Use ex de hl to save HL if HL has the return value de hl save HL if required 1 h1 36 want to pop 36 bytes add hl sp compute new SP value 14 sp hl put value back to SP de hl restore HL if required If the function returns struct unload the returned structure Restore registers previously saved Pop them off if they were stored on the stack If the function return was not a struct obtain the returned value from HL or BCDE 142 Using Assembly Language Dynamic C 32 v 6 x Indirect Function Calls in Assembly Indirect function calls are calls made to a function through a pointer to the function The Z180 instruction set does not have an opcode for indirect function calls However they can still be done The following code illustrates how assume HL has the address of the called function ld de retAddr explicitly load the return address push de save the return address jp hl indirect jump to address specified by HL retAddr execution continues here when the function returns If HL is supposed to contain an argument use register IY or IX if IX is not used as a frame reference pointer instead of HL Interrupt Routines in Assembly Dynamic C allows interrupt service routin
224. t to the function chain GLOBAL INIT When this function chain executes this and perhaps other segments elsewhere execute The effect in this example is to re initialize vec shared lIndicates that changes to a multi byte variable such as a float are atomic Interrupts are disabled while the variable is being changed Local variables cannot be shared shared float x y z shared int j main If i is a shared variable expressions of the form i ori 1 1 constitute two atomic references to variable i a read and a write Be careful because i is not an atomic operation short Declares that a variable or array is short integer 16 bits If nothing else is specified short implies a 16 bit signed integer short i j k 16 bit signed unsigned short int w 16 bit unsigned short funct short arg size Declares a function to be optimized for size as opposed to speed size int func sizeof A built in function that returns the size in bytes of a variable array structure union or of a data type j 2 sizeof float int list 10 99 33 2 7 63 217 x sizeof list Technical Reference The Language 107 speed Declares a function to be optimized for speed as opposed to size speed int func static Declares a local variable to have a permanent fixed location in memory as opposed to auto where the variable exists on the system stack
225. table problems In contrast to normal functions interrupt functions are responsible for saving and restoring all registers themselves Technical Reference Using Assembly Language 145 146 Using Assembly Language Dynamic C 32 v 6 x 7 CHAPTER 7 COSTATEMENTS Technical Reference Costatements 147 Dynamic C supports multi threaded real time programming Either the real time kernel LIB or the simplified real time kernel SRTK LIB may be used Costatements are another option Costatements offer cooperative multi tasking within an application There are several advantages to costatements Costatements are a feature built into Dynamic C Costatements are cooperative instead of preemptive Costatements can operate without multiple stacks Using costatements effectively requires a knowledge of their syntax their supporting data structures and the mechanisms by which they may be put to use Overview Costatements are blocks of code that can suspend their own execution at various times for various reasons allowing other costatements or other program code to execute Costatements operate concurrently For example the code shown in Figure 7 1 will operate as shown the diagram main main int x y 2 for y Y Y costate a a b costate b costate c Figure 7 1 Overview of Costatements Blocks a b and c each of th
226. tate costate statement statement statement statement 855 ae N t d waitfor N gt waitfor mem N zz statement statement statement statement 1 I e m Lat a First Time b Subsequent Times Figure 7 2 Execution of waitfor Statement Technical Reference Costatements 151 When the waitfor is encountered in a costatement for the first time a first time flag associated with that the costatement is set This flag 18 used by routines perform timing delays Figure 7 3 diagram shows the execution thread through a costatement when a waitfor finally evaluates true costate statement statement gt waitfor statement statement Figure 7 3 Execution of True waitfor Statement Delay Functions Three special functions others may be created allow the use of delays in the expression evaluated by a waitfor int DelaySec ulong seconds int DelayMs ulong milliseconds int DelayTicks uint ticks int IntervalSec ulong seconds int IntervalMs ulong milliseconds Thus an expression such as the following may be used wait for 30 minutes waitfor DelaySec 30L 60L wait for device or 40 milliseconds waitfor DelayMs 40L device ready The virtual driver must be initialized with a call to VdInit before these delay functions can be used Refer to the Dynamic C Function Reference
227. te compiler option The Z World Download Manager DLM resident in a controller will receive the program place it in memory and start it running Remote downloading requires a communications program such as ProComm that has an XMODEM transfer protocol available The downloaded program DLP and the DLM exist simultaneously as separate programs on the remote controller They occupy different portions of memory It is necessary for Dynamic C to know certain memory mapping parameters about the DLM before it compiles the downloadable file Figure 9 1 shows how the DLM and DLP are arranged in memory The download program can occupy both root and extended memory Target Root Memory BIOS defined DLP downloaded program data to EM DLM Download Manager DLM stack DLM stack can overlap DLP data DLM root ETE data bottoni Target Extended Memory Y DLM data DLM xmem data bottom DLP stack A Aligned at 256 byte DLP code boundaries DLM root DLP code DLM code code top DLM xmem 0x2000 BIOS DLM code 0x0000 Figure 9 1 Arrangement of DLM and DLP in Memory The DLM may run in RAM EPROM or flash The file may be down loaded to flash or RAM The Z World DLM uses memory mapping information contained in the DLP to place the DLP machine code in the correct locations in target memory The DLM does not download uninitialized data for the DLP Initialized data reside
228. tem code that a particular program uses The file LIB DIR contains a list of all libraries known to Dynamic C This list may be modified by the user In particular any library created by a user must be added to this list Libraries are linked with a user s application through the use directive Files identified by use directives are nestable as shown in Figure C 1 Application X LIB Y LIB fuse x lib duse y lib main function yrs function fuse z lib function use z lib Figure C 1 Linking Nestable Files in Dynamic C The file DEFAULT H contains several lists of libraries to use one list for each product that Z World ships Dynamic C usually knows which controller is being used so it selects the libraries appropriate to that controller These lists are the defaults A programmer may find it conve nient or necessary to add or remove libraries from one or more of the lists The default libraries for a Z World controller contain many function names global variable names and in particular many macro names It is likely that a programmer may try to use one of the Z World names for a newly written program Unpredictable problems can arise Z World recommends that DEFAULT H be edited to comment out libraries that are not needed 192 Software Libraries Dynamic C 32 v 6 x Headers Table C 1 describes the three kinds of headers in Dynamic C libraries Table C 1 Dynamic C Library Headers Library Headers D
229. tement The default case which is optional executes only when the switch expression does not match any other case switch expression case const pase condi default do Indicates the beginning of a do loop A do loops tests at the end and executes at least once do while expression The statement must have a semicolon at the end else Indicates a false branch of an i statement if expression statement executes when tru else statement executes when fals extern Indicates that a variable is defined in the BIOS later in a library file or in another library file Its main use is in module headers BeginHeader var extern int var EndHeader int var firsttime Declares a function to be waitfor delay function GU i For details see Chapter 7 Costatements loat Declares a variable function or array as 32 bit IEEE floating point int func float x y p float PI 3 14159265 float func float par 102 The Language Dynamic C 32 v 6 x for Indicates the beginning of a for loop A for loop has an initializ ing expression a limiting expression and a stepping expression Each expression can be empty for an endless loop for i 0 1 lt n itt counting loop goto Causes a program to go to a labeled section of code if condition goto RED RED statements Use goto to jump forward or backwar
230. the active window A copy of the text is saved on the clipboard The contents of the clipboard may be pasted virtually anywhere repeatedly in the same or other source files or even in word processing or graphics program documents The keyboard shortcut is lt CTRL X gt 46 Dynamic C Environment Dynamic C 32 v 6 x Copy Makes a copy of selected text in the active window The copy of the text is saved on the clipboard The contents of the clipboard may be pasted virtually anywhere The keyboard shortcut is CTRL C Paste Pastes text on the clipboard as a result of a copy or cut in Dynamic C or some other Windows application The paste command places the text at the current insertion point Note that nothing can be pasted in a debugging window It is possible to paste the same text repeatedly until something else is copied or cut The keyboard shortcut is CTRL V Find Finds specified text The following dialog box appears in response to the Find command From cursor Case sensitive Reverse Help Cance Type the text to be found the Find drop down text box or click on the down arrow icon to the right of the box and a drop down list of previous Find text is displayed If you click on a previous Find text it will become selected and ready for editing in the Find box In this example the Find command and the Find Next command too will find occurrences of the word switch Use
231. the loop body statement or compound statement governed by the while expression will repeat A do loop executes at least once before its test Unlike other controls the do loop requires a semicolon at the end Recommended form C syntax do do statement while expression some statements while expression The or loop is more complex it sets an initial condition exp evaluates a terminating condition exp and provides a stepping expression exp that is evaluated at the end of each iteration Each of the three expressions is optional Recommended form C syntax for exp expr for exp exp exp statement some statements If the end condition is initially false for loop body will not execute at all A typical use of the for loop is to count times sum 0 for i 0 i lt n i sum sum 1 This loops sets i to 0 initially continues as long as is less than stops when i equals and increments 7 at each pass Another use for the for loop is the infinite loop which is useful in control systems for some statements Here there is no initial condition no end condition and no stepping expression The loop body some statements continues to execute endlessly Continue and Break Two other constructs are available to help in the construction of loops the continue statement and the break statement Technical Reference
232. time in seconds since 1 JAN 1980 on stack as an unsigned long 10 Push program revision as an int on stack 11 Call main 212 File Formats Dynamic C 32 v 6 x Jumping to Another Program Conceivably several programs may be downloaded all in different sections of physical memory There is a function resident in ROM that makes it possible to jump from one program to another void newbbr uint offset uint CBAR BBR This function does not return but jumps to and starts up the program specified by its arguments For example say a program has been downlaoded at address 9C000 Then the BBR is 9C 2 for the size of the BIOS or 9A The CBAR is always E2 for RAM The offset is always 2200 for RAM The following call to newbbr would be made newbbr 0x2200 OxE29A Using the newbbr function requires a fair amount of mastery with Dynamic C and the target controller Burning ROM Z World controllers support several types of EPROM Including the following 27C256 32 kbytes 28 pins 27C512 64 kbytes 28 pins 27 010 128 kbytes 32 pins Copyright Notice The Dynamic C library is copyrighted Place the following copyright notice on any ROM created with Dynamic C O 1990 2002 Z World Inc In addition to this notice a copyright notice may be added to protect other user written code Purchasers of the copyrighted Dynamic C software and a copyrighted Z World ROM are granted permission to copy the ROM as d
233. tion Enter an expression in the watch line and click Add to top The expression will be added to the top of the watch list Watch list entries are deleted using the Delete from top button the entries in the watch list are evaluated every time the program stops at a break point after single stepping and after the stop command 2 watch window update be forced using the Update Watch Window command CTRL U The keyboard shortcut CTRL W allows a variable to be evaluated very quickly Just position the text cursor in the variable type CTRL W and hit ENTER The ability to evaluate expressions and function calls periodically and at will is a very powerful facility Besides providing the ability to monitor the program state this allows the program to be changed The watch dialog can be used to set the value of variables Functions called via the watch dialog can be very effective and possibly dangerous For example the PLCBus may be reset this way or events can be simu lated by changing the values at hardware inputs and outputs A sophisti cated programmer might even write functions meant only to be executed in the watch dialog for debugging purposes Returning to Edit Mode After debugging it is possible to continue editing the source code Click on the Edit mode in the EDIT menu The keyboard shortcut 18 F4 Creating Stand alone Programs As mentioned previously under Compiling EPROM fil
234. tion window to decide this parameter Code Data This option allows the compiler to load programs in RAM Gap using a 32K RAM on the target It is meaningful only when compiling directly to target RAM Set this option to 8000g only if the target RAM size is 32K otherwise set it to 0000H Auto Config This box when checked makes Dynamic C determine the start and end of RAM automatically The code data gap will also be adjusted automatically Auto Config should always be checked for most program mers This allows the physical memory options to be set automatically when Dynamic C connects to the target controller Programmers who wish to create a program that resides in a different part of memory can turn this option off 64 Dynamic C Environment Dynamic C 32 v 6 x The Logical memory options submenu provides the following dialog Logical Memory Options x Stack Size 800h Aux Stack Size 80h Heap Size Free Size 0 Help Cancel The Stack Size option specifies the number of bytes in hex allocated for the run time stack If the function calls nest deeply or if there are large amounts of auto local function data use this option to increase the memory allocated The Aux Stack Size option specifies the number of bytes in hex allocated to an alternate stack used mainly for stack verification bookkeeping The Heap Size option specifies the number of bytes in hex in the heap us
235. tions All C functions have a return type that specifies what kind of result if any it returns A function with a void return type returns no result Ifa function is declared without specifying a return type the compiler assumes that it is to return an int integer value See Fig ure 5 2 78 The Language Dynamic C 32 v 6 x Application Global Data lt Main Function Function 1 Function 2 Function 3 Function n Items accessible by all functions Function type name params t q Items accessible statement 1 statement 2 statement n return expr by this function only Figure 5 2 Functions in C Programming Functions may call other functions A function may even call itself Programmers call such a function a recursive function The main function is called automatically after the program compiles or when the controller powers up The beginning of the main function is the entry point to the entire program Prototypes A function may be declared with a prototype This is so that Functions that have not been compiled may be called 2 Recursive functions may be written 3 The compiler may perform type checking on the parameters to make sure that calls to the function receive arguments of the expected type A function prototype describes how to call the function and is nearly identical to the function s initial code this i
236. to determine in which part of memory function will be placed anymem int func memmap anymem asm anymem endasm auto A local function variable is located on the system stack and exists as long as the function call does int func auto float x break Jumps out of a loop if or case statement while expression if condition break switch expression case 3 break 100 The Language Dynamic C 32 v 6 x case lIdentifies the next case in a switch statement switch expression case const case const case const char Declares a variable or array as a type character This type is also commonly used to declare 8 bit integers and Boolean data char c x string hello int i c char i continue Skip to the next iteration of a loop while expression if nothing to do continue costate Indicates the beginning of a costatement costate name state Name can be absent If name is present state can be always on or init Ifstate is absent the costatement is initially off wa See Chapter 7 Costatements and keywords abort yield and waitfor debug Indicates a function is to be compiled in debug mode debug int func asm debug endasm oY See also nodebug and directives debug and nodebug Technical Reference The Language 101 default Identifies the default case a switch sta
237. tore j 2 other direction copy string to root J 2 if we want nice to see you k xgetlong greetingst j 4 addr of XMEM string xmem2root k my chars destination xstrlen k 1 1 is for null byte Declarations involving xdata and xstring must be made outside the context of a function Bf Refer also to XDATA C in the Dynamic C SAMPLES subdirectory for another example 206 Extended Memory Dynamic C 32 v 6 x E COMPILER DIRECTIVES Technical Reference Compiler Directives 207 Compiler directives are commands that instruct the compiler how to proceed They take the form of preprocessor commands an example of which appears here nouseix These directives are detailed in Chapter 5 The Language oY The nodebug directive automatically disables index checking pointer checking and stack verification Default Compiler Directives Default compilation options are specified in the library header file DC HH The file DC HH is compiled before any other library or user code The following major defaults are set in DC HH 1 The default storage class for variables is static class static This default may be changed but Z World libraries will not work then However static is far more efficient and auto is often not required in embedded programming Reentrant functions require auto vari ables 2 The default memory allocation is anymem memmap anymem This allow
238. tures at different times costatements a program except those that use pointers as their names are initialized whenever the function chain GLOBAL INIT is called The functions VdInit and uplc init also call Gv GLOBAL INIT Refer to the Virtual Driver in the Dynamic Function Reference manual for more information Four functions CoBegin CoResume CoPause and CoReset are available to operate costatements remotely Two functions isCoDone and isCoRunning return the state of a costatement firsttime keyword is available to help create waitfor functions Syntax The general format of a costatement appears below costate name state statement yield abort waitfor expression A costatement can have as many statements including abort statements yield statements and waitfors as needed Name The term name which is optional can be any of the following A valid C name not previously used This results in the creation of a structure of type CoData of the same name The name ofa local or global CoData structure that has already been defined A pointer to an existing structure of type CoData If name is missing then the compiler creates an unnamed structure of type CoData for the costatement 150 Costatements Dynamic C 32 v 6 x State The term state can be one of the following always on The costatement is always active Unnamed costatements are always on
239. types it should not be used to generate BIN files intended for loading to the target controller via the Program Loader Utility PLU After installing the externally programmed Flash EPROM into the target controller communi cation with Dynamic C or the PLU is still possible Download via DLM DLP When this option is selected the Compile to File commands generate a downloadable program file DLP to be used by the Z World download manager DLM When choosing this option be prepared to enter certain parameters generated by the DLM in a dialog box that appears after Compile to File is clicked e A Refer to Chapter 9 Remote Download for details The DLM must be resident in any controller that will receive the downloadable file Null Device Bit Bucket When this option is selected the Compile to File commands generate no output This option allows very fast compilation and is useful just to 1 perform syntax checking 2 perform type checking or 3 get the sizes of each code and data segment The memory mapping scheme is identical to compiling with code with BIOS Debugging Programs Once a program has been compiled successfully with a target controller connected Dynamic C enters run mode also called debug mode Modern symbolic debuggers such as Dynamic C s debugger make debugging relatively easy There are two general methods expect to use a combina tion of the two 32 Using Dynamic C Dynamic C 32 v 6 x 1 M
240. u Dynamic 32 Version 6 30 File Edit MESE Run Inspect Options Window Help ix eni Compile to Target F3 25 08 1 Compile to File Ctrl F3 Create RTI File for Targetless Compile Compile to File with RTI File Alt Ctrl F3 28 Using Dynamic C Dynamic C 32 v 6 x Compile to Target F3 Dynamic C compiles links and downloads machine code directly to a target controller If the controller has flash memory Dynamic C places code in flash memory If the controller has EPROM Dynamic C places code in RAM Dynamic C communicates with the controller through a PC serial port If the compilation is successful Dynamic C enters run AKA debug mode and maintains communication with the target controller Compile to File Ctrl F3 Dynamic C compiles the program to a file whose nature and format can be selected in the compiler options dialog No file is generated if compilation errors occur Note that a controller has to be connected to the PC Com pile to File takes target information from the controller Create RTI File for Targetless Compile When this menu option is selected Dynamic C creates a Remote Target Information RTI file by saving target information taken from the required attached controller A dialog box prompts for the location and file name to save the RTI file Compile to File with RTI File Alt Ctrl F3 Dynamic C allows a program to be compiled to a binary file or a down loadable file without having a target
241. u 41 42 lt ALT F10 gt Disassemble at Address 34 56 Dynamic C 32 v 6 x lt 2 gt Toggle hard break 52 53 lt ALT F4 gt Exit 45 lt ALT F4 gt Quitting Dynamic C 42 lt ALT F9 gt Run w No Polling 52 lt ALT H gt select HELP menu 71 lt ALT I gt select INSPECT menu 54 lt ALT O gt select OPTIONS menu 58 lt ALT SHIFT backspace gt redoing changes 46 lt ALT W gt select WINDOW lt CTRL C gt copying text 46 47 lt CTRL F gt Compile to File 50 lt CTRL F10 gt Disassemble at 34 56 lt CTRL F2 gt Reset Program 52 54 lt CTRL F3 gt Compile to File with RTI File 50 51 lt CTRL F4 gt Close 43 lt CTRL G gt Goto 46 49 lt CTRL H gt Library Help lookup 37 38 41 72 73 74 lt CTRL I gt Toggle interrupt 35 52 53 lt CTRL N gt next error 46 49 lt CTRL O gt Toggle polling 52 53 lt CTRL P gt previous error 46 49 lt CTRL U gt Update Watch window 36 54 56 lt CTRL V gt pasting text 46 47 lt CTRL W gt Add Del Items 35 36 54 55 lt CTRL X gt cutting text 46 lt CTRL Y gt Reset target 52 54 lt CTRL Z gt Stop 36 52 lt 10 gt Assembly window 68 F2 Toggle break point 52 53 F3 Compile to Target 50 51 Technical Reference F4 switching to edit mode 46 F5 finding text
242. ule That way the compiler will generate code or allocate data only if the module body is used by the application program Programmers who create their own libraries must write modules following the guideline in this section Remember that a library must be included in LIB DIR and a use directive for the library has to be placed somewhere in the code Technical Reference Software Libraries 195 196 Software Libraries Dynamic C 32 v 6 x D D EXTENDED MEMORY Technical Reference Extended Memory 197 Physical Memory Depending on PAL coding and board jumper settings Z World controllers can address up to 512K of ROM or 256K of flash memory and 512K of RAM The maximum memory available is 1 megabyte total Usually memory chips installed on Z World controllers have a capacity less than 512K A typical SRAM chip has 32K or 128K If a memory chip has less than 512K addresses outside the memory range map to addresses within the range For example for a 32K chip addresses evaluate modulo 32K If memory is addressed beyond the range of the chip data may seem to be replicated in memory Or worse data may be overwritten Memory Management Z180 instructions can specify 16 bit addresses giving a ogical address space of 64K 65 536 bytes Dynamic C supports a 1 megabyte physical address space 20 bit addresses An on chip memory management unit MMU translates 16 bit Z180 addresses to 20 bit memory a
243. where an expression for evaluation 1s entered If the cursor 18 placed over a variable name or some text in the source file is highlighted this text will appear in the dialog box when the dialog box is opened result of a watch expression will appear in the watch window after the dialog box closes A watch expression may be any valid C expression including assignments function calls and preprocessor macros do not type a semicolon after the expression For example the expression MyVar MyFunc 8 would call the function MyFunc with the value 8 and assign the return value to the variable MyVar assuming MyVar and MyFunc have been defined somewhere in the compiled program A simpler watch expression might include only the name of a variable and return its value Technical Reference Using Dynamic C 35 If a watch expression contains operations on long or float data types the programmer must include a dummy call to the appropriate operator For example if division of long integers is desired in a watch expression a dummy call in the program is required as follows long k 1 variables for dummy operation 1 compile for Watch Expressions There are two basic ways to work with the watch dialog 1 Immediate Evaluation Enter an expression in the dialog box edit line and click Evaluate The expression is evaluated only once with the results displayed immediately in the watch window 2 Repeated Evalua
244. with RTI File commands Application Only BPF When this option is selected the Compile to File commands generate a BPF file containing the compiled application code but without the BIOS code This option is included for backward compatibility only for controllers with standard a EPROM which require the Program Loader Utility to load the application code into SRAM The BIOS BIN Options These options select what type of a BIN EPROM file is generated If the Create HEX File Also compiler option is selected the Compile to File commands also generate an Intel hex format file HEX in addition to the BIN file In most cases either the BIN or the HEX file format will work with external device standard or Flash EPROM programmers 30 Using Dynamic C Dynamic C 32 v 6 x BlOS Application BIN When this option is selected the Compile to File commands generate a BIN standard or Flash EPROM file containing the BIOS code of the target controller where the BIOS library functions are located and the compiled application code It is important to note that the BIOS s symbol library is excluded from the BIN file This option is useful for programming either standard or Flash types When this type of BIN file is loaded via the Program Loader Utility PLU into a Flash equipped target controller communication with Dynamic C or the PLU is still possible This presumes that the BIN file code does not overw
245. y unused The Firsttime Flag and Firsttime Functions A firsttime function is a delay function that can be called from a waitfor statement For example the first time the DelayMs function is called it must set up the countdown variables for the specified amount of delay stored in the field content of a CoData structure All subsequent calls to DelayMs merely check whether the delay has expired The initialization flag must be associated with the CoData structure because several costatements may call DelayMs A firsttime function is declared with the keyword firsttime A proper firsttime function definition would look like the following firsttime int MyDelay CoData ptr delay params some code The first argument of a firsttime function must always be a pointer to a CoData structure A firsttime function will use this pointer to check whether the costatement s firsttime field is 1 If so the function will set up variables required to count the delay The firsttime function should also set the firsttime flag to 0 so subsequent visits to waitfor do not reset the delay counter Technical Reference Costatements 157 Calling a First Time Function From within a costatement use a firsttime function as an argument to a waitfor statement costate waitfor MyDelay 1000 Note that the call to MyDelay above has only one parameter The CoData pointer required in the function definition is not to be included in t
246. ynamic C Function Reference manual Technical Reference The Language 113 Strings are multi byte objects and as such they are always referenced by their starting address and usually by a char variable The following example illustrates typical usage Note that passing a pointer to a string is the same as passing the string char select Select option n char start 32 strcpy start Press any key when ready n printf select pass pointer to string printf start pass string Character constants have a slightly different meaning They are not strings A character constant is enclosed in single quotes andisa representation of an 8 bit integer value Y a Y An M x1B Any character can be represented alternate form whether in character constant or in a string Thus nonprinting characters and charac ters that cannot be typed may be used A character can be written using its numeric value preceded by a backslash x41 the hex value 41 101 the octal value 101 B10000001 the binary value 10000001 There are also several special forms preceded by a backslash bell b backspace formfeed n newline r carriage return t tab v vertical tab O null char backslash the actual character single quote double quote Examples said 11 embedded double quotes char j 77 character constant char MSG
247. ytes since it really starts at 16 kbytes because of the duplication of the memory image Extended memory also appears to start at 48 kbytes In this scheme the sum of root code and data is limited to 16 kbytes and the total extended memory code is limited to 16 kbytes Remember that all static variables even those local to extended memory functions are placed in root memory Hex File Information A HEX file includes an identification flag and other pertinent information This information starts at address 2300 in a ROM file and at 0300 in a RAM file as indicated in Table F 1 Table F 1 HEX File Information 0x 300 OxAA identification byte 0x 301 0x55 identification byte 0x 302 0x81 identification byte 0 2303 0x42 identification byte 0x 304 0x01 for ROM file 0x00 for RAM file 0x 305 6 16 bit cyclic redundancy check 0x 307 BBR register value 0x 308 9 16 bit address of first free byte above root code Startup code for the program appears at 2200 in a ROM file and at 0200 in a RAM file The startup code performs the following functions Load the stack pointer SP Set the I register interrupt base Enable interrupts ei Call library function named startup Call b ree to initialize heap management Set ERROR EXIT to exit as a default Set aux stack checking and debugging and stack limit Reset RST 28 vector to debugger SO 200 Push
Download Pdf Manuals
Related Search
Related Contents
Manual PDF manual do utilizador - DEHAS Medizintechnik & Projektierung GmbH Documents d`accompagnement 「Memoret」取扱説明書ダウンロード(PDF) Kolcraft EQ800 User's Manual User Manual 7" Tablet Android 4.1 Model: S3 Tech air BX411R EN DE Original-Montage- und Betriebsanleitung Original assembly Copyright © All rights reserved.
Failed to retrieve file