Home

User`s Manual - Digi International

image

Contents

1. Operators Associativity Function gt left to right member er a E STEDT right to left unary x left to right multiplicative left to right additive lt lt gt gt left to right bitwise lt lt gt gt left to right relational left to right equality amp left to right bitwise A left to right bitwise l left to right bitwise amp amp left to right logical 11 left to right logical right to left conditional 2 Soe fe He fe right to left assignment comma left to right series Chapter 13 Operators 177 178 Dynamic C User s Manual 14 Graphical User Interface Dynamic C can be used to edit source files compile and run programs and choose options for these activities using pull down menus or keyboard shortcuts There are two modes edit mode and run mode which is also known as debug mode Various debugging windows can be viewed in run mode Programs can compile directly to a target controller for debugging in RAM or flash Pro grams can also be compiled to a bin file with or without a controller connected to the PC To debug a program a controller must be connected to the PC either directly via a programming cable or indirectly via an Ethernet connection and a RabbitLink board Multiple instances of Dynamic C can be run simultaneously This means multiple debugging sessions are possible over different serial ports This is useful for
2. 148 Dynamic C User s Manual Identifies the main function All programs start at the beginning of the main function main is actually not a keyword but is a function name Indicates a function is not compiled in debug mode This is the default for assembly blocks nodebug int func asm nodebug endasm See also debug and directives debug nodebug Indicates that a function does not use the RST instruction for breakpoints norst void func Indicates a function does not use the IX register as a stack frame reference pointer This is the default case nouseix void func The null pointer This is actually a macro not a keyword Same as void 0 Chapter 12 Keywords 149 An important feature of Dynamic C is the ability to declare variables as protected Such a vari able is protected against loss in case of a power failure or other system reset because the com piler 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 val ue can be restored when the system restarts Battery backed RAM is required for this operation A system that shares data among different tasks or among interrupt routines can find its shared data corrupted if an interrupt occurs in the middle of a write to a multibyte variable such as type int or float The variable might be
3. 169 real time programming 3 modules eeeseeseeseees 36 37 39 XOR assign 5 170 writing your OWN 37 body ea A NA 37 38 39 associativity eee eeeeeeee 165 Library Help lookup 40 206 custom PDAS sagami 37 pian dated Vetere tes 165 207 example osisssa 39 bitwise operators linking tiara tense 3 DEAE errs Ss aB yA Et address 8 sesssssssseses 170 locating errors sssssssssseseee 184 KEY ssesssesrsssessrsoseeeserevesensne 37 bitwise AND amp esses 170 long WDEALY 50 8 h tok codecs aus 37 bitwise exclusive OR integer vaise joy MOUSE oeiia ieina 172 171 keyword assssssssnseecseeee 148 Multitasking bitwise inclusive OR I 171 lookup function 206 207 Coop erative ee G complement 171 JOODS spern iirin ii 30 31 REPCID DUNC sienai Eit itin 59 pointers oe 170 breaking out of 0 eee 31 N shift left lt lt we 170 dG sition ithe anit 143 shift right gt gt seese 170 TOL a o oeeo ees 145 NAMES oros ireira eniT 16 COMMA oo eee eeeeeseeeees 177 skipping to next pass 31 define cssectsssseetskeesetsseestss 16 conditional operators 175 Next error lt CTRL N gt 184 equality operators 172 M nodebug 115 149 187 190 equal secesii 172 et ee 17 118 119 160 196 231 232 not equal seess 172 274 Dynamic C User s Manual in assembly eee 117 logical operators 173 lo
4. if condition goto RED RED Use goto to jump forward or backward 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 Indicates the beginning of an if statement if tank_full shut_off_water if expression statements else if expression statements else if expression statements else if expression statements else 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 e1se is optional and executes only when none of the if or else if expressions are true non zero 146 Dynamic C User s Manual The costatement is 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 Declares variables function return values or array elements to be 16 bit integers 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 Indicates that a function is an interrupt service routine All registers including alternates are saved when an interrupt f
5. td Available starting with Dynamic C v 7 10 Description Disable type demotion checking Default Type demotion checking is performed GUI Equivalent Uncheck the Options Compiler Demotion menu dialog box option tp Description Disable type checking of pointers This switch is available only in Dynamic C v 7 05 and 7 06 Default Type checking of pointers is performed GUI Equivalent Uncheck the Options Compiler Pointer menu dialog box option tp Available starting with Dynamic C v 7 10 Description Enable type checking of pointers Default Type checking of pointers is performed GUI Equivalent Check the Options Compiler Pointer menu dialog box option 216 Dynamic C User s Manual tp Available starting with Dynamic C v 7 10 Description Disable type checking of pointers Default Type checking of pointers is performed GUI Equivalent Uncheck the Options Compiler Pointer menu dialog box option tt Description Disable type checking of prototypes This switch is available only in Dynamic C v 7 05 and 7 06 Default Type checking of prototypes is performed GUI Equivalent Uncheck the Options Compiler Prototype menu dialog box option tt Available starting with Dynamic C v 7 10 Description Enable type checking of prototypes Default Type checking of prototypes is performed GUI Equivalent Check the Options Compiler Prototype menu dialog box option tt Availabl
6. 248 Custom Configuration 0 249 Examples niire rs 250 18 5 Compatibility with TCP IP 253 Socket Locks 200 eeeeceeeeeeeeee 253 18 6 Debugging Tips eee 254 Macros and Global Variables 257 Compiler Defined Macros 257 Global Variables 00 0 0 eee 259 Exception Types ceceeeeeeeeeeeees 260 Rabbit 2000 3000 Internal registers 260 Map File Generation 0 cece 261 Grammars eid reesei cesses sess 261 Utility Programs 0 eeeeeeeeeeeeees 263 Font and Bitmap Converter Utility 263 Library File Encryption Utility 263 Rabbit Field Utility eee 264 Tode kee eE erence ee 271 vi Dynamic C User s Manual 1 Installing Dynamic C Insert the installation disk or CD in the appropriate disk drive on your PC The installation should begin automatically If it doesn t issue the Windows Run command and type the following command COILS gt 3 N ORUE The installation program will begin and guide you through the installation process 1 1 Requirements Your IBM compatible PC should have at least one free COM port and be running one of the fol lowing e Windows 95 e Windows 98 e Windows 2000 e Windows Me e Windows NT 1 2 Assumptions It is assumed that the reader has a working knowledge of e the basics of operating a software program and editing files under Windows on a PC e programming in a high level language e a
7. 56 Dynamic C User s Manual 5 5 8 Solving the Real Time Problem with Cofunctions for costate task 1 wid emergencystop for i 0 i lt MAX_DEVICES i wre turnoffdevice i costate task 2 wid x buttonpushed wfd turnondevice x waitfor DelaySec 60L wfd turnoffdevice x COSIEAEST soo taskn Cofunctions with their ability to receive arguments and return values provide more flexibility and specificity than our previous solutions Using cofunctions new machines can be added with only trivial code changes Making but tonpushed acofunction allows more specificity because the value returned can indicate a particular button in an array of buttons Then that value can be passed as an argument to the cofunctions turnondevice and turnoffdevice 5 6 Patterns of Cooperative Multitasking Sometimes a task may be something that has a beginning and an end For example a cofunction to transmit a string of characters via the serial port begins when the cofunction is first called and continues during successive calls as control cycles around the big loop The end occurs after the last character has been sent and the wait fordone condition is satisified This type of a call to a cofunctions might look like this waitfordone SendSerial string of characters next statement The next statement will execute after the last character is sent Cha
8. ERRLOG_USE_REG_DUMP Default 1 Include a register dump in log entries Changing this to zero in the BIOS excludes the register dump in log entries ERRLOG_STACKDUMP_SIZE Default 16 Include a stack dump of size ERRLOG_STACKDUMP_SIZE in log entries Changing this to zero in the BIOS excludes the stack dump in log entries ERRLOG_NUM_ENTRIES Default 78 This is the number of entries allowed in the log buffer ERRLOG_USE_MESSAGE Default 0 Exclude error messages from log entries Changing this to one in the BIOS includes error messages in log entries The default error handler makes no use of this feature Chapter 8 Run Time Errors 95 8 3 4 Error Logging Functions The run time error logging API c errlogGetHeaderInfo errlogGetNthEntry errlogGetMessage errlogFormatEntry errlogFormatRegDump errlogFormatStackDump errlogReadHeader ResetErrorLog onsists of the following functions Reads error log header and formats output Loads errLogEntry structure with the Nth entry from the error log buffer errLogEnt ry is a pre allo cated global structure Returns a NULL terminated string containing the 8 byte error message in errLogEntry Returns a NULL terminated string containing basic information in errLogEntry Returns a NULL terminated string containing the regis ter dump in errLogEntry Returns a NULL terminated string containing the stack dump in errLogEntry Reads error log header into the struc
9. 151 curly braces eee 21 A ADOTT cise eatin acta ad 137 about Dynamic C oe 208 abstract data types 23 24 adc add with carry 115 address space eee 4 97 addresses in assembly 119 aggregate data types 25 AIST ces scevssd Me E eeehdsetonys 138 ALT key See keystrokes ALWAYS_ON oo eeeeeeeecseeceneeeees 138 ANYVMEM eriein egete 138 argument passing 29 122 128 129 modifying value 29 blocks in xmem assignment operators 119 120 122 139 231 storage of variables Auto Open STDIO Window 197 character literals continuation in directives 159 basic unit of a C program binary operators calling premain command line compiler 210 compilation environments 227 compile option configuration macros 95 103 include in bin file macro definitions memory location memory settings redefine a symbol in reserving memory root memory usage variable defined in out of a switch statement 31 breakpoints 125 149 187 190 interrupt status 187 188 SOLE EESE 187 188 buttons toolbar 00 202 C C language 3 4 5 13 20 23 29 34 117 120 Dynamic C User s Manual calling assembly 127 embedded in assembly 116 variables in assembly 119 cascaded windows 202 CASE eneee 33 140 143 Char osais 23 140 157 characters ALL AYS 25 fe a a a E
10. 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 abasic type named MILES typedef struct astructure type float re Eloart lime idle Been COMPLEX mamed COMPLEX MILES distance declare variable of type MILES COMMENT XGS 24 R ZO declare variable of amp pointer to type COMPLEX Chapter 4 Language 23 Use typedef to create a meaningful name for a class of data Consider this example typedef unsigned int node WOuLel Wevcleiliaalic iavevcle 4 void NodeInit unsigned int This example shows many of the basic C constructs type name is informative not very informative Put descriptive information in your program code using this form of comment which can be inserted anywhere and can span lines The double slash comment shown below may be placed at the end of a line define SIZE 12 ime Gj lag Float SumScqmarS Lat Lat J vorge imit main float x wia 2 xX sumSgquare g fh Ie AiM Ie Mx Bie R WO Le tmit g 107 h SIZE float sumSquare int a int b float temp temp a a b b return temp and here is the end of the program Vat A symboli
11. Changing port from default of 1 to 2 dccl_cmp myProgram c s 2 115200 1 0 224 Dynamic C User s Manual Sto SerialResponseTimeout Available starting with Dynamic C v 7 10 Description Default GUI Equivalent Example Time in milliseconds Dynamic C waits for a response from the target on any retry while trying to establish serial communication 300 ms None dccl_cmp myProgram c sto 400 t NetAddress TcpName TcpPort Description Default GUI Equivalent Example Use TCP with parameters defined in a contiguous colon separated format of NetAddress TcpName TcpPort Include all parameters even if only one is being changed netAddress n n n n tcpName Text name of TCP port tcpPort decimal number of TCP port None Select the Options Communications Use TCP IP Connection dialog box options dccl_cmp myProgram c t 10 10 6 138 TCPName 4244 Chapter 15 Command Line Interface 225 15 5 Examples The following examples illustrate using multiple command line switches at the same time If the switches on the command line are contradictory such as mr and mf the last switch read left to right will be used 15 5 1 Example 1 In this example all current settings of default dcp are used for the compile dccl_cmp samples timerb timerb c 15 5 2 Example 2 In this example all settings of mypro ject dcp are used except t imer_b c is compiled to timer_b bin instead of to the targ
12. EndHeader int var 144 Dynamic C User s Manual firsttime in front of a function body declares the function to have an implicit CoData parameter as the first parameter This parameter should not be specified in the call or the proto type but only in the function body parameter list The compiler generates the code to automat ically pass the pointer to the CoData structure associated with the costatement from which the call is made A firstime function can only be called from inside of a costatement cofunc tion or slice statement The De layTick function from COSTATE LIB below is an example of a firsttime function firsttime nodebug int DelayTicks CoData pfb unsigned int ticks if ticks 0 return 1 if pfb gt firsttime fb gt firsttime 0 save current ticker fb gt content ul unsigned long TICK_TIMER else if TICK_TIMER pfb gt content ul gt ticks return 1 return 0 Declares variables function return values or arrays as 32 bit IEEE floating point int func float x Yr p float PI 3 14159265 float func float par Indicates the beginning of a for loop A for loop has an initializing expression a limiting ex pression and a stepping expression Each expression can be empty for Fy an endless loop for i 0 i lt n i counting loop Chapter 12 Keywords 145 Causes a program to go to a labeled section of code
13. LIBRARY SP_STREAM LIB Chapter 7 The Slave Port Driver 87 int SPSwrite SPSream stream void data int length DESCRIPTION This function transmits length bytes to slave port output buffer If the slave port is in poll ing mode this function will call SPt ick while waiting for the output buffer to empty This function is non reentrant PARAMETERS stream Pointer to the stream state structure data Bytes to write to stream length Size of write buffer RETURN VALUE Number of bytes written into the data buffer LIBRARY SP_STREAM LIB int SPSwrFree DESCRIPTION Returns number of free bytes in the stream write buffer RETURN VALUE Space available in the stream write buffer LIBRARY SP_STREAM LIB 88 Dynamic C User s Manual int SPSrdFree DESCRIPTION Returns the number of free bytes in the stream read buffer RETURN VALUE Space available in the stream read buffer LIBRARY SP_STREAM LIB int SPSwrUsed DESCRIPTION Returns the number of bytes currently in the stream write buffer RETURN VALUE Number of bytes currently in the stream write buffer LIBRARY SP_STREAM LIB int SPSrdUsed DESCRIPTION Returns the number of bytes currently in the stream read buffer RETURN VALUE Number of bytes currently in the stream read buffer LIBRARY SP_STREAM LIB Chapter 7 The Slave Port Driver 89 7 3 3 2 Byte Stream Sample Program This program S
14. The exceptions to this rule are 1 Arguments to the and operators are not expanded 2 To prevent infinite recursion a macro does not expand within its own expansion The following defin defin defin defin defin defin defin printet The code urA Z M M write complex example illustrates this e AB e B e uint unsigned int e M x M x e MM x y Z x y z e string something e write value fmt value fmt n value r A A B Sinieiimg 8 will expand first to unsign MM A OIEI IME IE then to unsign A AB jOue IL TONE iE then to unsign B AB r printet and finally to unsign C AB ma primet ed int zp simple expansion A B M M does not expand recursively Wisi 1 aLioney n WW ee Ul TATOU string ee value gt string fmt 3s Gel iinet Zp from A A B Weeresting Y Wall Wesel WN sonneielastiae 2 string something ecl inte 2 i H A gt E string s n something concatenation ecl ine 27 i ff B C String S540 something 18 Dynamic C User s Manual 4 5 1 Restrictions The number of arguments in a macro call must match the number of parameters in the macro defi nition 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
15. body executesif i lt j OK a lt b truewhen a lt b Less than or equal This binary relational operator yields a boolean value The result is 1 if the left operand is less than or equal to the right operand and 0 otherwise if i lt j body executesif i lt j OK a lt b truewhen a lt b Chapter 13 Operators 171 Greater than This binary relational operator yields a Boolean value The result is 1 if the left operand is greater than the right operand and 0 otherwise if i gt gj body executesif i gt j OK a gt b truewhen a gt b Greater than or equal This binary relational operator yields a Boolean value The result is 1 if the left operand is greater than or equal to the right operand and 0 otherwise if i gt j body executesif i gt j OK a gt b truewhen a gt b 13 5 Equality Operators Equal This binary relational operator yields a Boolean value The result is 1 if the left operand equals the right operand and 0 otherwise At ae body executesif i j OK a b truewhen a b Note that the operator is not the same as the assignment operator A common mistake is to write a es ee d body Here i gets the value of j and the if condition is true when i is non zero not when i equals j Not equal This binary relational operator yields a Boolean value The result is 1 if the left oper and is not equal to
16. 18 2 Tasking Aware Interrupt Service Routines TA ISR Special care must be taken when writing an interrupt service routine ISR that will be used in con junction with wC OS II so that uC OS II scheduling will be performed at the proper time 18 2 1 Interrupt Priority Levels uC OS II for the Rabbit reserves interrupt priority levels 2 and 3 for interrupts outside of the ker nel Since the kernel is unaware of interrupts above priority level 1 interrupt service routines for interrupts that occur at interrupt priority levels 2 and 3 should not be written to be tasking aware Also a uC OS II application should only disable interrupts by setting the interrupt priority level to 1 and should never raise the interrupt priority level above 1 Chapter 18 uC OS II 241 18 2 2 Possible ISR Scenarios There are several different scenarios that must be considered when writing an ISR for use with uC OS II Depending on the use of the ISR it may or may not have to be written so that it is task ing aware Consider the scenario in the Figure below In this situation the ISR for Interrupt X does not have to be tasking aware since it does not re enable interrupts before completion and it does not post to a semaphore mailbox or queue Task 1 Interrupt X Interrupt X ISR ipres i Task 1 S Figure 6 Type 1 ISR If however an ISR needs to signal a task to the ready state then the ISR must be tasking aware In the examp
17. k wadtirorcdome ywCotmme2z p BZ CoruMmes sca Pp The keyword wait fordone can be abbreviated to the keyword wfd must be inside a costate ment or cofunction Since a cofunction must be called from inside a wfd statement ultimately a wfd statement must be inside a costatement If only one cofunction is being called by wfd_ the curly braces are not needed The wfd statement executes cofunctions and firsttime functions When all the cofunctions and firsttime functions listed in the wfd statement are complete or one of them aborts exe cution proceeds to the statement following wfd Otherwise a jump is made to the ending brace of the costatement or cofunction where the wfd statement appears and when the execution thread comes around again control is given back to wfd In the example above x y and z must be set by return statements inside the called cofunc tions Executing a return statement in a cofunction has the same effect as executing the end brace In the example above the variable k is a status variable that is set according to the following scheme If no abort has taken place in any cofunction k is set to 1 2 n to indicate which cofunction inside the braces finished executing last If an abort takes place k is set to 1 2 n to indicate which cofunction caused the abort 5 5 2 1 Using the IX Register Functions called from within a cofunction may use the IX register if they restore it before the cofun
18. point q to array element 5 qt point q to array element 6 D 19 w GIF illegal Because the float is a 4 byte storage element the statement q pt5 sets the actual value of q to p 20 The statement q adds 4 to the actual value of q If were an array of 1 byte charac ters the statement q adds 1 to q Chapter 4 Language 27 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 crash A common mistake is to declare and use a pointer to char thinking there is a string But an unini tialized pointer is all there is Clmeie STELE Sicmcoy string Vaello Jp Invalid PEIRCE ONN Invalid Pointer checking is a run time option in Dynamic C Use the compiler options command in the Options menu Pointer checking will catch attempts to dereference a pointer to un allocated mem ory However if an uninitialized pointer happens to contain the address of a memory location that the compiler has already allocated pointer checking will not catch this logic error Because pointer checking is a run time option pointer checking adds instructions to code when pointer checking is used 4 16 Pointers to Functions Indirect Calls Pointers to functions may be declared When a function is called using a pointer to it instead of directly we call this an indirect call The syntax for declaring a pointer
19. 102 keyword 0 eee 4 151 memory MAP eee 97 static variables 00 98 variable address 119 RST 28H eee 187 231 run MENU cei A Aaa 186 mode saon 184 186 no polling wo ee 186 S sample programs basic C constructs 24 save environment 202 saving a file eee 181 Search text cccsecccccesesseeees 183 segchain oo eee 34 151 SEGSIZE osc he iis 97 separate I amp D space 117 190 195 serial communication 199 OPTIONS esinaise 200 shadow registers 260 shared orlare en 151 shared variables 3 150 232 SOLE sis ccciivel cee eee 152 show tool bar cceeeeeeeeee 202 single stepping 125 190 231 with descent cccceeee 187 without descent 187 SIZ EEEE E E 152 196 SIZEOK m aan e a a 152 skipping to next loop pass 31 Slave port oe eee ee eeeeeeeeee 69 slice statements c008 59 soft breakpoints 187 188 software libraries ccccceeeeeee 36 37 TESCE it eee 188 source Window ccceeeeeeees 202 SP stack pointer 122 128 129 136 163 special characters ee 21 special symbols Dynamic C User s Manual 275 in assembly oe 119 Speed niyin 152 196 232 stack 29 126 128 129 130 136 139 149 231 checking oe 231 232 frame 122 128 129 136 frame reference point 128 frame reference po
20. Compile to a bin file using parameters defined in a colon separated for mat of BoardID CpuID CrystalSpeed RAMSize FlashSize The resulting compiled file will have the same pathname as the source c file being compiled but with a bin extension BoardID Hex integer CpuID Decimal integer CrystalSpeed Decimal floating point in MHz RAMSize Decimal in KBytes FlashSize Decimal in KBytes None For Dynamic C v 7 05 and 7 06 select the Compile Compile to bin file Define target information Specify Board Parameters menu option For Dynamic C v 7 10 and later select the Options Define target configuration Specify Board Parameters menu option dccl_cmp myProgram c rti 0x0101 2000 29 4912 128 256 s Port Baud Stopbits BackgroundTx Description Default GUI Equivalent Example Use serial transmission with parameters defined in a colon separated format of Port Baud Stopbits BackgroundTx Port 1 2 3 4 5 6 7 8 Baud 110 150 300 600 1200 2400 4800 9600 12800 14400 19200 28800 38400 57600 115200 128000 230400 256000 Stopbits 1 2 BackgroundTx 0 None 1 Sync 2 Full Speed Include all serial parameters in the prescribed format even if only one is being changed Starting with Dynamic C v 7 10 the last parameter is ignored and therefore may be dropped from the command line without consequence 1 115200 1 0 Select the Options Communications Serial dialog box options
21. One tick 1 1024 second Chapter 5 Multitasking with Dynamic C 59 name When defining a named slice statement you supply a context buffer as the first argument When you define an unnamed slice statement this structure is allocated by the compiler statement yield abort waitfor expression The body of a slice statement may contain e Regular C statements e yield statements to make an unconditional exit e abort statements to make an execution jump to the very end of the statement e waitfor statements to suspend progress of the slice statement pending some condition indicated by the expression 5 9 2 Usage The slice statement can run both cooperatively and preemptively all in the same framework A slice statements like costatements and cofunctions can suspend its execution with an abort yield or wait for as with costatements and cofunctions or with an implicit yield deter mined by the t ime_slice parameter that was passed to it A routine called from the periodic interrupt forms the basis for scheduling slice statements It counts down the ticks and changes the slice statement s context 5 9 3 Restrictions Since a slice statement has its own stack local auto variables and parameters cannot be accessed while in the context of a slice statement Any functions called from the slice statement function normally Only one slice statement can be active at any time which eliminates the possibility of nesting
22. The Virtual Driver 65 6 3 Global Timer Variables SEC_TIMER MS_TIMER and TICK_TIMER are global variables defined as shared unsigned long These variables should never be changed by an application program Among other things the TCP IP stack depends on the validity of the timer variables On initialization SEC_TIMER is synchronized with the real time clock The date and time can be accessed more quickly by reading SEC_TIMER than by reading the real time clock The periodic interrupt updates SEC_TIMER every second MS_TIMER every millisecond and TICK_TIMER 1024 times per second the frequency of the periodic interrupt These variables are used by the DelaySec DelayMS and DelayTicks functions but are also convenient for application programs to use for timing purposes The following sample shows the use of MS_TIMER to measure the execution time in microseconds of a Dynamic C integer add The work is done in a nodebug function so that debugging does not affect timing For more informa tion on the nodebug keyword please see nodebug on page 149 define N 10000 maini emesis e nodebug timeit unsigned long int TO cloew WZ Wils HiME Xp We WINE LE TO MS_TIMER tor SOP ixe ade 4 T1 gives empty loop time T1 MS_TIMER TO TO MS_TIMER or SOP a lt INp aiarr Seay Ht T2 gives test code execution time T2 MS_TIMER TO subtract empty loop time and convert to time for single pass
23. The syntax expected is a semi colon separated list of defined constants with optional values given with an equal sign This is the same as the command line compiler d option except that the CLC expects a single defined expression to follow each d dccl_cmp mysourcefile c d DEF1 d MAXN 10 d DEF2 while the GUI window expects a semi colon separated list DEF 1 MAXN 10 DEF2 The end result is the same as if every file compiled and run were prepended with define DEF1 define MAXN 10 define DEF2 196 Dynamic C User s Manual 14 2 6 3 Debugger Choosing the Debugger menu item from the Options dialog box displays the following Debugger Options x V Auto Open STDIO Window T Log STDOUT Log file DC OUT Append Log MV Enable breakpoints Max breakpoints 32 IV Enable watch expressions Max watch expressions E IV Enable instruction level single stepping The options in the Debugger dialog box may be helpful when debugging programs In particular they allow printf statements and other STDIO output to be logged to a file Starting with Dynamic C version 7 25 the macro STDIO_DEBUG_SERIAL may be defined to redirect STDIO output to a designated serial port A B C or D For more information please see the sample pro gram Samples STDIO_SERIAL C Check the box labeled Log STDOUT to send a copy of all standard output to the named log file For a file that already exists check Append Log unless y
24. This function disables the slave port driver and unloads the ISR if one was used LIBRARY SLAVE_PORT LIB 7 3 Examples The rest of the chapter describes some useful handlers 7 3 1 Status Handler SPstatusHandler available in Slave_port 1ib is an example of a simple handler to report the status of the slave To set up the function as a handler on slave port address 12 do the following SPsetHandler 12 SPstatusHandler amp status_char Sending any command to this handler will cause it to respond with a 1 in the response register and the current value of status_char in the data return register 74 Dynamic C User s Manual 7 3 2 Serial Port Handler Slave_port 1ib contains handlers for all four serial ports on the slave Master_serial 1lib contains code for a master using the slave s serial port handler This library illustrates the general case of implementing the master side of the master slave protocol 7 3 2 1 Commands to the Slave Table 7 10 Commands that the master can send to the slave Command Command Description Transmit byte Byte value is in data register Slave responds with 1 if the f byte was processed or 0 if it was not 2 Receive byte Slave responds with 2 if has put a new received byte into the data return register or 0 if there were no bytes to receive Combined transmit receive a combination of the transmit and receive 3 commands The response will also be a logical O
25. User defined timerb_intvec User defined name User defined inputcap_intvec User defined name quad_intvec qd_isr extO_intvec User defined name extl_intvec User defined name DevMateSerialISR _ Fast and nonmodifiable sera_intvec spa_isr User defined serb_intvec spb_isr serc_intvec spc_isr serd_intvec spd_isr sere_intvec spe_isr serf_intvec spf_isr User defined a Please note that this ISR shares the same interrupt vector as DevMateSeriallISR Using spa_isr precludes Dynamic C from communicating with the target Chapter 11 Using Assembly Language 135 11 8 Common Problems Unbalanced stack Ensure the stack is balanced 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 SP approach after pushing temporary information on the stack The SP approach for inline 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 hl SP x 2 Add 2 to compe
26. and then recreated with fcreate For a more robust program more error checking should be included 112 Dynamic C User s Manual 10 7 Skeleton Program Using FS2 The following program uses some of the FS2 API It writes several strings into a file reads the file back and prints the contents to the STDIO window Fuse MSD HUSN OSI Lis Wai ila il main iLike iI stratie Char ourien 256 p iSite 0 Q if fcreate amp file TESTFILE amp amp fopen_wr amp file TESTFILE printr Terror opening TESTETLE Zann Cicwia 9 ecwien ip fseek amp file 0 SEEK_END terce ELS Anello 5 IEWAeILES Giz Ihe VLAZSAa 6 p iWwieileS erile YGHIIGO Y ONP Seek Gis O ESE EKES ES while fread amp file buffer 6 gt 0 prineri Se a lowit tei 2 fclose amp file For a more robust program more error checking should be included See the sample programs in the SAMPLES FILESYSTEM folder for more complex examples which include error checking formatting partitioning and other new features FS2 returns more information in the case of errors than FS1 The library ERRNO LIB contains a list of all possible error codes returnable by the FS2 API These error codes mostly conform to POSIX standards If the return value of an FS2 API indicates an error then the errno variable may be examined to determin
27. cycles and can only change locations via recompilation The file system can be configured to use RAM also While there may applications where storing persistent in RAM is acceptable for exam ple a data logger where the data gets retrieved and the battery checked periodically keep in mind that a programming error such as an uninitialized pointer could cause RAM data to be corrupted xalloc will allocate blocks of RAM in extended memory It will allocate the blocks consis tently from the same physical address if done at the beginning of the program and the program is not recompiled Chapter 17 Hints and Tips 233 17 3 Root Memory Reduction Tips Customers with programs that are near the limits of root code and or root data space usage will be interested in these tips for saving root space The usage of root code and data by the BIOS in Dynamic C 7 20 increased from previous versions A follow on release will reduce BIOS root space usage but probably not to the level of usage in previous versions 17 3 1 Increasing Root Code Space Increasing the available amount of root code space may be done in the following ways e Use memmap xmem This will cause C functions that are not explicitly declared as root to be placed in xmem Note that the only reason to locate a C function in root is because it modifies the XPC register in embedded assembly code or it is an ISR The only performance dif ference in running code in xmem is in g
28. directive nouseix will not break the code But if SP has been changed by user code e g a push it won t work ld hl spt SP lgt2 ld b h ld c L ld hl sp SP 1g ex de hl endasm 124 Dynamic C User s Manual 11 4 2 1 The Disassembled Code Window A program may be debugged at the assembly level by clicking the Assemb radio button on Dynamic C s toolbar to open the Disassembled Code window Single stepping and breakpoints are supported in this window When the Disassembled Code window is open single stepping occurs instruction by instruction rather than statement by statement The figure below shows the Regis ters Stack and Disassembled Code windows for the example code asm1 c just before the func tion call Dynamic C Dist 7 05P File Edt Compile Run Inspect Options Window Help ilese ale Keele Disassembled Code 15c6 22Fici ld iciFi j hl 13 15c9 EF rst 28h 15ca 117766 ld de 6677 6 15ed 015544 ld be 4455 6 15d0 EDS3EDC1 ld C1ED de 15 15d4 ED43EFC1 ld C1EF be 15 15d8 EF rst 28h 8 15d9 EDSBEDC1 ld de C1ED 13 15dd ED4BEFC1 ld be C1EF 13 15e1 c5 push he 10 15e2 DS push de 10 15e3 2AF1ic1 ld hl C1F1 11 15e6 ES push hl 10 15e7 ZAF3C1 ld hl C1F3 11 l5ea 2600 ld h 00 4 15ec ES push hl 10 15ed CDFC15 call fune gt 15f0 00 nop 2 15f1 2708 add sp 08 4 15f3 EF rst 28h 8 15f4 D9 exx 2 15f5 210000 ld hl 0000 6 15f8 CD341
29. fixed storage The default storage class is static Enables or disables debug code compilation debug is the default condition These direc tives override the debug and nodebug keywords used on function declarations or assembly blocks nodebug prevents RST 28h instructions from being inserted between C statements and assembly instructions Chapter 12 Keywords 159 Syntax define name textor define name parameters text Defines a macro with or without parameters according to ANSI standard A macro without pa rameters may be considered a symbolic constant Supports the and macro operators Mac ros can have up to 32 parameters and can be nested to 126 levels Ends a block of assembly code Syntax fatal 7 Instructs the compiler to act as if a fatal error The string in quotes following the directive is the message to be printed Syntax GLOBAL_INIT variables GLOBAL_INIT sections are blocks of code that are run once before main is called They should appear in functions after variable declarations and before the first executable code If a local static variable must be initialized once only before the program runs it should be done in a GLOBAL_INIT section but other inititialization may also be done For example This function outputs and returns the number of times it has been called slime COo Che GOME GLOBAL INIT initialize count count 1 make port A output WrPortI
30. given the limited room in the first flash that can be over written with the macro define FS_BLOCK_SIZE 512 See the sample program 1st flash c for an example of using the first flash with FS1 10 2 3 FS2 Requirements The file system library must be compiled with the application use FS2 LIB For the simplest applications this is all that is necessary for configuration For more complex applications there are several other macro definitions that may be used before the inclusion of FS2 LIB These are define FS_MAX_ DEVICES 3 define FS_MAX_LX 4 define FS_MAX_FILES 10 These specify certain static array sizes that allow control over the amount of root data space taken by FS2 If you are using only one flash device and possibly battery backed RAM and are not using partitions then there is no need to set FS_MAX_DEVICES or FS_MAX_LX For more information on partitioning please see section 10 4 Setting up and Partitioning the File System on page 107 102 Dynamic C User s Manual 10 2 4 FS2 Configuration Macros FS_MAX DEVICES This macro defines the maximum physical media If it is not defined in the program code FS_MAX_DEVICES will default to 1 2 or 3 depending on the values of FS2_USE_PROGRAM_FLASH XMEM_RESERVE_SI2ZE and FS2_RAM_RESERVE FS_MAX LX This macro defines the maximum logical extents You must increase this value by 1 for each new partition your application creates It this
31. the first half of the flash and LX 3 would be 128K the other half LX 2 is untouched Having partitioned once fs_setup may be called again to perform further subdivision This may be done on any of the original or new extents Each call to s_setup in partitioning mode increases the total number of logical extents You will need to make sure that FS_MAX_LX is defined to a high enough value that the LX array size is not exceeded While developing an application you might need to adjust partitioning parameters If any parame ter is changed FS2 will probably not recognize data written using the previous parameters This problem is common to most operating systems The solution is to save any desired files to out side the file system before changing its organization then after the change force a format of the file system Note that in particular files written by FS1 are not readable by FS2 since the two file systems are incompatible at the device level 10 4 3 Logical Sector Size fs_setup can also be used to specify non default logical sector LS sizes and other parame ters FS1 uses fixed logical sectors i e blocks of 4096 bytes FS2 allows any LS size between 64 and 8192 bytes providing the LS size is an exact power of 2 Each LX including sub parti tions can have a different LS size This allows some performance optimization Small LSs are bet ter fora RAM LX since it minimizes wasted space without incur
32. 155 E a e a E e e i 169 WAOE iiaiai ea aai 155 aae aa a ie REE EEAS 169 waitfordone e E E S 169 Wid anane 156 SPS EEE 169 While rari n eae reai ieee 156 T A EAA e a hat 170 ROALD a ae a 157 INS vss Sede ban e i E aT Ea ENEKE ER Rapai 170 MIMO OEE EEEE 157 AA E EE E T 170 XSH Senenin s 157 13 3 Bitwise Operators 0 eee 170 yield iernare eae ees 158 LA E nhs aie e ae oei 170 12 1 Compiler Directives 159 DD E E EEA STT 170 Hasman SAME Rhea thtis 159 ea E R ae ela ey eette Deeveee es 170 FCIASS ious cscs eaten E 159 IN E 171 debug et AR RASA E 171 hodebug issis 159 E ats obese EEES ET 171 defhe decap 160 13 4 Relational Operators 0 0 ee 171 HENCASM aanne ennei 160 L E ee nash teens E Or ETE EER 171 Dynamic C User s Manual v 13 9 Conditional Operators Test REE S R E 13 10 Other Operators 0 eee 14 Graphical User Interface TA V Editin t snee a 14 2 MENUS ccccceeeeeeeessseeeececeeseseseeevens Inspect Menu eeeeeseeeseeeeeeees Options Menu eee eee cree ECU OP re eie E aN Compiler s sseseseeseeseeereerersseeeees DeODUS SOE e n hee Display vecgviesssesivensereveteecees Communications eee Define Target Configuration Other Menu Choices Window Menu ceseessceneeeees Help Menu isin cinncateerennits 15 Command Line Interface 000000 15 1 Default States cece ececeeeneee 15 2 User Input is
33. 199 TEXT CULSOT syntiin 207 text editing wee 182 text search isiin 183 tiling windows oe 202 toggle breakpoint 187 188 interrupt flag oe 188 polling wee 188 toggle polling ow 188 100 0 sinni a 202 trace Into ssc scesssecestsesesstescees 187 type CASUDE s sissies estes eeieets 166 checking oe 23 195 definitions 0 00 23 24 typedef oe 23 24 154 U unary operators 165 unbalanced stack 136 undoing changes 182 uninitialized pointers eee 28 UNION iiA 22 26 155 unpreserved registers 129 136 Unsigned eee 155 unsigned integer oe 19 untitled files oo ee 181 USB nann eo 200 USE_2NDFLASH_CODE 99 232 USEI seiorn 126 155 231 Utility Programs Font Bitmap Converter 263 Library File Encryption 263 Rabbit Field Utility 264 V variables UO senina 139 global aoe esere enese sns 26 StalIC aa ies 153 vertical tiling woe 202 Ww Wal tlOr orinni 155 waitfordone ou eeeeeeeee 156 warning reports oo 195 watch expressions add or delete 189 evaluate button 189 watch menu option 203 watch window 006 190 WINdOW essenin niit 202 AO 6 re 156 while eeeee eee 21 30 156 Window menu ccce 202 windows assembly 125 202 203 Cascaded modien ersen 202 information 202 205 IMESSABE sieis Ai K 202 TeGiSter oe 202 204
34. Branching The goto statement is the simplest form of a branching statement Coupled with a statement label it simply transfers program control to the labeled statement some statements abc other statements goto abc more statements GoTo der den more statements The colon at the end of the labels is required In general the use of the goto statement is discour aged in structured programming 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 compound statement if the condition expression is true non zero The program will ignore the if body when the condition is false zero if expression some statement s 32 Dynamic C User s Manual A more complex form of the if statement tests the condition and executes certain statements if the expression is true and executes another group of statements when the expression is false if expression some statement s iftrue else some statement s if false The fullest form of the if statements produces a succession of tests LEC OSPE 4 SOMES GCATEMEMES Jelse 1r exer i SOMERS EE ECNE Jelse irl expr 1 some statements else some statements The program evaluates the first expression expr If that proves false it tries the second expres sion expr gt and continues testing until it finds a true expression an e1 se clause or the end
35. Chapter 14 Graphical User Interface 205 Function Lookup Insert Displays descriptions for library functions The function is chosen in the Library Lookup dia log box by clicking on its name and then clicking OK Library Lookup Lib Entries stremp in E DYNC 7 25 LIB STRING LIB streat in E D YNC 7 25 LIB STRING LIB strchr in E D YNC 7 25 LIBSSTRING LIB stremp in E DYNC 7 25 LIBSSTRING LIB strempi in E D YNC 7 25 LIBSSTRING LIB strepy in E DYNC 7 25 LIBSSTRING LIB strespn in E DYNC 7 25 LIBSSTRING LIB strlen in E SDYNC 7 25 LIB STRING LIB This dialog box is also displayed when the keyboard shortcut lt Ctrl H gt is used anywhere in the source code If a Dynamic C function is selected at the time lt Ct r1 H gt is pressed then the dialog box is skipped and the Function Lookup Insert screen displays the function description stecmp lt STRING LIBS SYUTAX int atremp char atel char ake DESCRIPTION Pecform unsigned charecter by character comparison of tem nall terminated strings Pointer to skering 1 Pointer to sbring Z if stri as less than str char in stri is less than coreeaponding char in atril is aborter than but otherwise identical ta if stcl ig equal to stra stri is identical to atr if stri is greater than stri char in stri is greater than corresponding char in str atr is aborter than but otherwise identical ta atel FEYWORDS string compace 206 Dynamic C User s M
36. 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 A compound statement is a group of statements enclosed in braces and Chapter 4 Language 21 4 9 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 Root data arrays are limited to a total of 32 767 elements statio Ini thing array lizi static integer variable amp static integer array auto Float matciciss 3 Lsi auto float array with 2 dimensions char message Press any key initialized pointer to char array If an aggregate type struct or union is being declared its internal structure has to be described as shown below Struct 1 description of structure Charl tlagsy Sie ruca a nested structure here LNE X Lae We OC k CilieSore 3 TAT aF a eursor OO use of structure element here 4 10 Functions The basic unit of a C application program is a function Most functions accept parameters or arguments and return results but there are exceptions All C functions have a return type that specifies what kind of result if any it returns A functio
37. E Samples E mem gt Pong c Seeparam c File name Files of type Source Files c lib Cancel The subfolders contain sample programs that illustrate the use of the various Dynamic C librar ies The subfolder named Cofunc for example contains sample programs illustrating the use of COFUNC LIB The sample program Pong c demonstrates output to the STDIO window Each sample program has comments that describe its 3 1 Run DEMO1 C purpose and function This sample program will be used to illustrate some of the functions of Dynamic C Open the file Samples DEMO1 C The program will appear in a window as shown in Figure 1 below minus some comments Use the mouse to place the cursor on the function name print f in the program and press lt Ctrl H gt This brings up a documentation box for the function print f You can do this with all functions in the Dynamic C libraries including libraries you write yourself Chapter 3 Quick Tutorial Pee C programs begin with main main Initialize a counter Start an endless loop Increment counter for G07 7 lt 20000 G Delay by counting to 20 000 princi Val Bel ia Y al 2 Bi ag se Print out counter end of while Re Fae ee Nets Crean End of the endless loop Figure 1 Sample Program DEMO1 C To run the program DEMO1 C open it with the File menu compile it using the Compile menu and then run it by selectin
38. II uC OS ID library and sample code and the Point to Point Protocol PPP library are not included in this amendment 1 1 3 Excluding the exceptions in 1 1 2 library and sample code provided with the Software may be modified for use with the Softools WinIDE program in Qualified Systems as defined in 1 2 All other Restrictions specified by this license agreement remain in force 1 2 Qualified Systems means a microprocessor based computer system which is either i manufactured by for or under license from Z WORLD or ii based on the Rabbit 2000 microprocessor or the Rabbit 3000 microprocessor Qualified Systems may not be a designed or intended to be re programmable by your customer using the Software or b competitive with Z WORLD products except as otherwise stated in a written agreement between Z World and the system manufacturer Such written agreement may require an end user to pay run time royalties to Z World Dynamic C User s Manual 267 2 License Z WORLD grants to You a nonexclusive nontransferable license to i use and repro duce the Software solely for internal purposes and only for the number of users for which You have purchased licenses for the Users and not for redistribution or resale ii use and repro duce the Software solely to develop the Qualified Applications and iii use reproduce and distribute the Qualified Applications in object code only to end users solely for use on Quali fied Systems
39. K K 2K K K 2 K K K K FKK K K K K K 2K K K K 2s FKK K 2s K K K K 4 5 01 2 47 16 PM dccl_cmp exe Version 7 10P English samples demo1 c Options h o myoutputs txt Program outputs Note Version information refers to dcwd exe with the same compiler core h Available starting with Dynamic C v 7 10 Description Disable printing of program header information Factory Default No header information will be printed GUI Equivalent None id Available starting with Dynamic C v 7 30 Description Enable separate instruction and data space Factory Default Separate I amp D space is disabled GUI Equivalent Check Separate I amp D Space in the Options Compiler dialog box id Available starting with Dynamic C v 7 30 Description Disable separate instruction and data space Factory Default Separate I amp D space is disabled GUI Equivalent Uncheck Separate I amp D Space in the Options Compiler dialog box Chapter 15 Command Line Interface 211 If Available starting with Dynamic C v 7 10 Description Factory Default GUI Equivalent mf Description Default GUI Equivalent mfr Description Default GUI Equivalent mr Description Default GUI Equivalent Undo Library Directory file specification No Library Directory file is specified Uncheck the Options Compiler User Defined Libraries File Use menu dialog box option Memory BIOS setting Flash Memory BIOS settin
40. This is not an exhaustive list of the macros and global variables that are available A 1 Compiler Defined Macros The macros in the following table are defined internally Where applicable default values are given as well as directions for changing values Table A 3 Macros Defined by the Compiler Macro Name Definition and Default _BIOSBAUD_ This macro was introduced in Dynamic C 7 25 It is the debug baud rate The baud rate can be changed in the Options Communications menu _BOARD_TYPE_ This is read from the System ID block or defaulted to 0x100 the BL1810 JackRabbit board if no System ID block is present This can be used for conditional compilation based on board type Board types are listed in boardtypes lib _CPU_ID_ This macro identifies the CPU type e g R3000 is the Rabbit 3000 microprocessor CC_VER Gives the Dynamic C version in hex i e version 7 05 is 0x0705 DC_CRC_PTR Reserved __DATE__ The compiler substitutes this macro with the date that the file was compiled either the BIOS or the c file The character string literal is of the form Mmm dd yyyy The days of the month are as follows Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec There is a space as the first character of dd if the value is less than 10 DEBUG_RST In the Compile pull down menu check Include Debug Code RST 28 Instructions to set DEBUG_RST
41. VALUE gt endasm VALUE can have any positive integer expression or the special operands even and odd The operand even aligns the instruction on an even address and odd on an odd address Integer expressions align on multiples of the value of the expression Some examples align odd This aligns on the next odd address align 2 Aligns on a 16 bit 2 byte boundary align 4 Aligns on a 32 bit 4 byte boundary align 100h Aligns the code to the next address that is evenly divisible by 0x100 align sizeof int 4 Complex expression involving sizeof and integer constant Note that integer expressions are treated the same way as operand expressions for other asm oper ators so variable labels are resolved to their addresses not their values The costatement is always active Unnamed costatements are always on Allows the compiler to determine in which part of memory a function will be placed anymem int func memmap anymem asm anymem endasm 138 Dynamic C User s Manual Use in Dynamic C code to insert one assembly language instruction If more than one assembly instruction is desired use the compiler directive asm instead int func int X y Z asm ld hl 0x3333 A functions s local variable is located on the system stack and exists as long as the function call does int func auto float x Identifies a variable to be placed into a second data area reserved for battery back
42. a Ie lax lt is I Coala Gy aime a IF i word Jy J sameasi j lt lt 8 c The compiler removes the 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 it as a string literal For example if a macro is defined define report value fmt printf value fmt n value then the macro in report string s will expand to pLiInte string Ss n String Ny and because C always concatenates adjacent strings the final result of expansion will be printf string s n string The operator concatenates the preceding character sequence with the following character sequence deleting any white space in between For example given the macro define set x y z x z _ y the macro in set AASC FN 6 will expand to AASC6_FN For parameters immediately adjacent to the operator the corresponding argument is not expanded before substitution but appears as it does in the macro call Chapter 4 Language 17 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
43. a few extra machine cycles Code placement in mem ory can be changed by the keywords xmem and root depending on the type of code Pure Assembly Routines Pure assembly functions may be placed in root memory or extended memory Prior to Dynamic C v 7 10 pure assembly routines had to be in root memory C Functions C functions may be placed in root memory or extended memory Access to variables in C state ments is not affected by the placement of the function Dynamic C will automatically place C functions in extended memory as root memory fills Short frequently used functions may be declared with the root keyword to force Dynamic C to load them in root memory Inline Assembly in C Functions Inline assembly code may be written in any C function regardless of whether it is compiled to extended memory or root memory All static variables even those local to extended memory functions are placed in root memory Keep this in mind if the functions have many variables or large arrays Root memory can fill up quickly 98 Dynamic C User s Manual 10 The Flash File System Dynamic C 7 0 introduced a simple file system that can be used with a second flash memory or in SRAM Dynamic C 7 05 introduced an improved file system with more features e The ability to overwrite parts of a file e The simultaneous use of multiple device types e The ability to partition devices e Efficient support for byte writable devices e Better perfor
44. after the In each of the following examples if const was missing the compiler would generate a trivial warning Warnings for const can be turned off by changing the compiler options to report se rious warnings only Note that const is not currently permitted with return types automatic locals or parameters and does not change the default storage class for cofunctions Example 1 ptr_to_x is a constant pointer to an integer aioe 38 lnt COMSIE CEG COo lt Cx Example 2 cptr_to_i isa constant pointer to a constant integer const ime a SP GCOS Ime COMMS Goer IcO_i i Example 3 ax isa constant 2 dimensional integer array const imc axi Ill 42 3 1 2 he Example 4 Struct wee ine a Echar blll zed isa constant struct Const Siwucc reekzameni Example 5 cptr is a constant pointer to an integer typedef int PEE TCO LNA const per tO lnt COLE ip this declaration is equivalent to the previous one lace CONSE Goti ap Chapter 12 Keywords 141 Skip to the next iteration of a loop while expression if nothing to do continue Indicates the beginning of a costatement costate name state Name can be absent If name is present state can be always_onorinit_on If state is absent the costatement is initially off Indicates a function is to be compiled in debug mode This is the default case for Dynamic C functions with the exceptio
45. assembly code is to add a C statement before the desired assembly instruction Note that the assembly code must be contained in a debug C function in order to enable C code debugging Below is an example debug dummyfunction asm function label omer add line of C code to permit a breakpoint before jump relative jr nc label ret endasm NOTE Single stepping through assembly code is always allowed if the assembly window is open 116 Dynamic C User s Manual 11 2 Assembler and Preprocessor The assembler parses 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 Table 11 18 Operators Not Supported By The Assembler Operator Symbol Operator Description conditional array index dot gt points to dereference 11 2 1 Comments C style comments are allowed in embedded assembly code The assembler will ignore comments beginning with text from the semicolon to the end of line is ignored text from the double forward slashes to the end of line is ignored text between slash asterisk and asterisk slash is ignored 11 2 2 Defining Constants Constants may be created and defined in assembly code with the assembly language keyword db define byte db should be followed immediately by numerical values and strings separated by commas For
46. at address 190 disassembled code 190 CCIOL ice ila eas 198 Keyword ceeeeeeeeneeeeeee 142 memory dump 4 190 MNOS seien 231 prevention wee 186 run time errors eee eee 91 SIED OVET oo eeeeeeeeeeeeeeee 187 switching modes 184 trace into oo eeeeeeeeeeeeeeeee 187 update watch expressions 190 watchdog timers neeese 67 declarations cc000 22 37 default 0 ee 33 143 demotion 20 0 eeeeeeeeeeneceeeees 195 disassemble at address 06 190 203 at CUFSOF ccceeeeeees 190 203 display OPTIONS oo issii 198 dO LOOP ririn 30 dot operator oo 16 25 downloading eee 3 dump window ee 191 CW EE theese cesta sci 118 Dynamic Cow eeeeeeeee 3 differences 06 4 5 34 OX monon ient 182 202 Installation eects 6 support files we 40 dynamic storage allocation 26 E Edit menu ccceeeeeeeeeeeee 182 edit mode 179 184 188 COILON eieren ET 3 OPTIONS siisii sesers 192 EEPROM aeieea E 5 elses Sit eas ew eh sks 143 embedded assembly 3 122 127 128 embedded quotes 0 21 End Key series iisisti 179 EndHeadet 0006 37 38 CMUM MEERE EE ET 144 EPROM sce eene 4 QU sis s sks obs sigh setiet Spassbsvadectasy 119 errors editor rr 198 error code ranges 91 JOC ALINE sisri 184 run time eee cece 91 193 ESC key to close menu 006 180 exa
47. be print ing out regularly in the STDIO window You can set breakpoints while the program is running by positioning the cursor to a statement and using the F2 key If the execution thread hits the breakpoint a breakpoint will take place You can toggle the breakpoint with the F2 key and continue execution with the F9 key 3 1 4 Editing the Program Click on the Edit box on the task bar This will put Dynamic C into edit mode so that you can change the program Use the Save as choice on the File menu to save the file with a new name so as not to change the demo program Save the file as MYTEST C Now change the number 20000 inthe for statement to 10000 Then use the F9 key to recompile and run the program The counter displays twice as quickly as before because you reduced the value in the delay loop Chapter 3 Quick Tutorial 9 3 2 Run DEMO2 C Go back to edit mode and load the program DEMO2 C using the File menu Open command This program is the same as the first program except that a variable k has been added along with a statement to increment k by the value of i each time around the endless loop The statement runwatch has been added as well This is a debugging statement to view variables while the program is run ning Use the F9 key to compile and run DEMO2 C 3 2 1 Watching Variables Dynamically Press lt Ctrl W gt to open the watch window and add the watch expression k to the top of the list of watch expressio
48. bit unsigned integer range from 0 to 65 535 instead of 32768 to 32767 Values in an unsigned long integer range from 0 to 232 1 Indicates that a function uses the IX register as a stack frame pointer useix void func See also nouseix and directives useix nouseix Used in a costatement this keyword identifies a point of suspension pending the outcome of a condition completion of an event or some other delay for costate waitfor input 1 HIGH Chapter 12 Keywords 155 The wait fordone keyword can be abbreviated as wf d It is part of Dynamic C s cooperative multitasking constructs Used inside a costatement or a cofunction it executes cofunctions and firsttime functions When all the cofunctions and firsttime functions in the wfd state ment are complete or one of them aborts execution proceeds to the statement following wfd Otherwise a jump is made to the ending brace of the costatement or cofunction where the wfd statement appears when the execution thread comes around again control is given back to the wfd statement The wfd statements below are from Samples cofunc cofterm c x wfd login wd with one cofunction wfd wd with several cofunctions clrscr putat 5 5 name putat 5 6 password echoon As shown wfd may return an argument Identifies the beginning of a while loop A while loop tests at the beginning and may ex ecute ze
49. calling OSInit E g to change the tick rate to 32 ticks per second define OS_TICKS_PER_SEC 32 OSInit OSStart Chapter 18 wC OS II 239 18 1 2 Task Creation In a uC OS II application stacks are declared as static arrays and the address of either the top or bottom depending on the CPU of the stack is passed to OSTaskCreate Ina Rabbit based system the Dynamic C development environment provides a superior stack allocation mechanism that uC OS II incorporates Rather than declaring stacks as static arrays the number of stacks of particular sizes are declared and when a task is created using either OSTaskCreate or OSTaskCreateExt only the size of the stack is passed not the memory address This mecha nism allows a large number of stacks to be defined without using up root RAM There are five macros located in ucos2 lib that define the number of stacks needed of five different sizes In order to have three 256 byte stacks one 512 byte stack two 1024 byte stacks one 2048 byte stack and no 4096 byte stacks the following macro definitions would be used define STACK_CNT_256 3 number of 256 byte stacks define STACK_CNT_512 1 number of 512 byte stacks define STACK _CNT_1K 2 number of 1K stacks define STACK _CNT_2K 1 number of 2K stacks define STACK _CNT_4K 0 number of 4K stacks These macros can be placed into each uC OS I application so that the number of each size stack can be customized ba
50. clRFU myProgram bin t 10 10 1 100 4244 V Description Causes the RFU version number and additional status information to be dis played Default Only error messages are displayed RFU GUI Status information is displayed by default and there is no option to turn it Equivalent off Example clRFU myProgram bin v 264 Dynamic C User s Manual cl ColdLoaderPathName Description Default RFU GUI Equivalent Example Select a new initial loader bios coldload bin From the Setup Boot Strap Loaders dialog box type in a pathname or click on the ellipses radio button to browse for a file c1RFU myProgram bin cl myInitialLoader c pb PilotBiosPathName Description Default RFU GUI Equivalent Example Description RFU GUI Equivalent Example Select a new secondary loader bios pilot bin From the Setup Boot Strap Loaders dialog box type in a pathname or click on the ellipses radio button to browse for a file c1RFU myProgram bin pb mySecondaryLoader c Run Ethernet discovery Don t load the bin file This option is for infor mation gathering and must appear by itself with no other options and no binary image file name From the Setup Communications dialog box click on the Use TCP IP Connection radio button then on the Discover button c1RFU d Dynamic C User s Manual 265 266 Dynamic C User s Manual Z WORLD SOFTWARE END USER LICENSE AGR
51. consti break case const2 break case const3 break default The switch statement may contain any number of cases The constants of the case statements are compared with expression If there is a match the statements for that case execute The default case if it is present executes if none of the constants of the case statements match 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 also execute regard less of whether their constants match the switch expression This keyword provides a way to create new names for existing data types typedef struct int xi 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 154 Dynamic C User s Manual Identifies a variable that can contain objects of different types and sizes at different times Items in a union have the same address The size of a union is that of its largest member union int x3 float y abe overlays a float and an int Declares a variable or array to be unsigned If nothing else is specified in a declaration unsigned means 16 bit unsigned integer unsigned i Jy k 16 bit unsigned unsigned int x 16 bit unsigned unsigned long w 32 bit unsigned unsigned funct unsigned arg Values in a 16
52. converter to their bitmaps Double click on the fmbcnvtr exe file in the Dynamic C directory Select and convert existing fonts or bitmaps Complete instructions are available by clicking on the Help button within the utility When complete the converted file is displayed in the editing window Editing may be done but probably won t be necessary Save the file as whatever 1ib the name of your choice Add the file to applications with the statement use whatever lib remember to add this filename to Lib dir or by cut and pasting from whatever 1ib directly into the application file C 2 Library File Encryption Utility The Library File Encryption Utility allows distribution of sensitive runtime library files Encrypt exe may be obtained by calling technical support at Z World Complete instructions are available by clicking on the Help button within the utility Context sensitive help is accessed by positioning the cursor over the desired subject and hitting lt F1 gt The encrypted library files compile normally but cannot be read with an editor The files will be automatically decrypted during Dynamic C compilation but users of Dynamic C will not be able to see any of the decrypted contents except for function descriptions for which a public interface is given An optional user defined copyright notice is put at the beginning of an encrypted file Dynamic C User s Manual 263 C 3 Rabbit Field Utility The Rabbit Field Utili
53. de increment ch2 pointer djnz loop do 8 bytes ch1 now points to 64 bit result endasm The keywords debug and nodebug can be placed on the same line as asm Assembly code blocks are nodebug by default This saves space and unnecessary calls to the debugger kernel All blocks of assembly code within a C function are assembled in nodebug mode The only excep tion to this is when a block of assembly code is explicitly marked with debug Any blocks marked debug will be assembled in debug mode even if the enclosing C function is marked nodebug Chapter 11 Using Assembly Language 115 11 1 2 Embedded C Syntax A C statement may be placed within assembly code by placing a c in column 1 Note that which ever registers are used in the embedded C statement will be changed fasm IMLEWALUES s s e start_time 0 Couimeeic 256s ret endasm 11 1 3 Setting Breakpoints in Assembly Starting with Dynamic C version 7 20 there are two ways to enable breakpoint support in a block of assembly code One way is to explicitly mark the assembly block as debug the default condition is nodebug This causes the insertion of rst 0x28 instructions between each assembly instruction These rst 0x28 instructions may cause jump relative i e jr instructions to go out of range but this prob lem can be solved by changing the relative jump jr to an absolute jump jp The other way to enable breakpoint support in a block of
54. debugging boards that are communicating among them selves 14 1 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 select text or extend a text selection Scroll bars may be used to position text in a window Dynamic C 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 14 1 0 1 Arrow Keys 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 14 1 0 2 Home Moves the cursor backward in the text to the start of the line 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 Chapter 14 Graphical User Interface 179 14 1 0 3 End Moves the cursor forward in the text End Move to end of line
55. endif 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 Syntax KILL name To redefine a symbol found in the BIOS of a controller first KILL the prior name Syntax makechain chainname Creates a function chain When a program executes the function chain named in this directive all of the functions or segments belonging to the function chain execute Syntax memmap options Controls the default memory area for functions The following options are available e anymem NNNN When code comes within NNNN bytes of the end of root code space start putting it in xmem Default memory usage is memmap anymem 0x2000 e root All functions not declared as xmem go to root memory e xmem All C functions not declared as root go to extended memory Assembly blocks not marked as xmem go to root memory 62 Dynamic C User s Manual Allows library functions in a comma separated list to be compiled immediately after the BIOS The precompile directive is useful for decreasing the download time when developing your program Precompiled functions will be compiled and downloaded with the BIOS instead of each time you compile and download your program The following limitations exist e Precompile functions must be defined nodebug e Any functions to be precompiled must be in a library and that lib
56. for Replace is lt F6 gt Chapter 14 Graphical User Interface 183 Find Next Once search text has been specified with the Find or Replace commands the Find Next com mand F3 for short will find the next occurrence 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 replace Goto Positions the insertion point at the start of the specified line Type the line number or approximate line number to go to That line and lines in the vicin ity will be displayed in the source window Previous Error Locates the previous compilation error in the source code Any errors will be displayed in a list in the message window after a program is compiled Dynamic C selects the previous error in the list and positions the offending line of code in the text window when the Previous Error command lt Ctrl P gt for short is made Use the keyboard shortcuts to locate errors quickly Next Error Locates the next compilation error in the source code Any errors will be displayed in a list in the message window after a program is compiled Dynamic C selects the next error in the list and positions the offending line of code in the source window when the Next Error command lt Ctrl N gt for short is made Use the keyboard shortcuts to locate errors quickly Edit Mode Switches Dynamic C back to edit mode fro
57. for the desired time to elapse but instead return 0 to indicate that the desired time has not yet elapsed DelayMs IntervalMs DelaySec IntervalSec DelayTicks IntervalTick User defined firsttime functions are allowed 5 4 6 Shared Global Variables The variables SEC_TIMER MS_ TIMER and TICK_TIMER are shared making them atomic when being updated They are defined and initialized in VDRIVER LIB They are updated by the periodic interrupt and are used by firsttime functions They should not be modified by an application program Costatements and cofunctions depend on these timer variables being valid for use in wait for statements that call functions that read them E g the following statement will access SEC_TIMER waitfor DelaySec 3 Chapter 5 Multitasking with Dynamic C 51 5 5 Cofunctions Cofunctions like costatements are used to implement cooperative multitasking But unlike cos tatements they have a form similar to functions in that arguments can be passed to them and a value can be returned but not a structure The default storage class for a cofunction s variables is Instance An instance variable behaves like a st atic variable i e its value persists between function calls Each instance of an Indexed Cofunction has its own set of instance variables The compiler directive class does not change the default storage class for a cofunction s variables All cofunctions in the program are in
58. handling Example echoes characters main IME E serXopen 19200 oprite while 1 loophead wid c cof_serAgetc wid cof_serAputc c serAclose 5 5 6 Types of Cofunction Calls A wfd statement makes one of three types of calls to a cofunction 5 5 6 1 First Time Call A first time call happens when a wfd statement calls a cofunction for the first time in that state ment After the first time only the original wfd statement can give this cofunction instance con tinuation calls until either the instance is complete or until the instance is given another first time call from a different statement 5 5 6 2 Continuation Call A continuation call is when a cofunction that has previously yielded is given another chance to run by the enclosing wf d statement These statements can only call the cofunction if it was the last statement to give the cofunction a first time call or a continuation call 5 5 6 3 Terminal Call A terminal call ends with a cofunction returning to its wfd statement without yielding to another cofunction This can happen when it reaches the end of the cofunction and does an implicit return when the cofunction does an explicit return or when the cofunction aborts Chapter 5 Multitasking with Dynamic C 55 5 5 6 4 Lifetime of a Cofunction Instance This stretches from a first time call until its terminal call or until its next first time call 5 5 7 Special Code Blocks The fo
59. instructions and checks nodebug int myfunc int x int z If programs are executing on the target controller with the debugging instructions present but without Dynamic C attached the function that handles RST 2 8H instructions will be replaced by a simple ret instruction The target controller will work but its performance will not be as good as when the nodebug keyword is used 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 Chapter 17 Hints and Tips 231 Use the directive nodebug anywhere within the program to enable nodebug for all statements following the directive The debug directive has the opposite effect Assembly code blocks are nodebug by default even when they occur inside C functions that are marked debug therefore using the nodebug keyword with the asm directive is usually unnec essary 17 1 2 Static Variables Using static variables with nodebug functions will greatly increase the program speed Stack checking is disabled by default When there are more than 128 bytes of auto variables declared in a function the first 128 bytes are more easily accessed than later declarations because of the limited 8 bit range of IX and SP regis ter addressing This makes performance slower for bytes above 128 The shared and the protected keywords in data declarations cause slower fetches and
60. int x char y float z record record array 100 ANE ar Dy Gr dy char cc Fourscore and seven char list ABC DEFG HI define array_size sizeof record 100 number of bytes in array a sizeof record FET b array_size 700 Cc sizeof cc 20 d sizeof list 6 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 176 Dynamic C User s Manual 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 is 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 1l i lt j i j Because of the comma operator the initialization has two parts 1 set i to 0 and 2 get the length of string s The stepping expression also has two parts increment i and decrement j The comma operator exists to allow multiple expressions in loop or if conditions The table below shows the operator precedence from highest to lowest All operators grouped together have equal precedence Table 13 1 Operator Precedence
61. is the baud rate used for target communi cations after the program has been downloaded Max Download Baud Rate When baud negotiation is enabled the compiler will start out at the selected baud rate and work downwards until it reaches one both the compiler and target can handle Prior to Dynamic C 7 26 this value was accessible in the registry instead of the GUI Stop Bits The number of stop bits used by the serial drivers Defaults to 1 Enable Processor Verification Processor detection is enabled by default The connection is normally checked with a test using the Data Set Ready DSR line of the PC serial connection If the DSR line is not used as expected a false error message will be generated in response to the connection check To bypass the connection check uncheck the Enable Processor Verification checkbox This allows custom designed systems to not connect the STATUS pin to the programming port Also disabling the connection check allows non standard PC ports or USB converters which might not implement the DSR line to work Use USB to Serial Converter Check this checkbox if a USB to serial converter cable is being used Dynamic C will then attempt to compensate for abnormalities in USB converter drivers This mode makes the communications more USB RS232 converter friendly by allow ing higher download baud rates and introducing short delays at key points in the loading pro cess Checking this box may also help non standard
62. its only parameter int isCoDone CoData p This function returns true if the costatement pointed to by p has completed int isCoRunning CoData p This function returns true if the costatement pointed to by p will run if given a continua tion call void CoBegin CoData p This function initializes a costatement s CoData structure so that the costatement will be executed next time it is encountered 50 Dynamic C User s Manual void CoPause CoData p This function will change CoData so that the associated costatement is paused When a costatement is called in this state it does an implicit yield until it is released by a call from CoResume or CoBegin void CoReset CoData p This function initializes a costatement s CoData structure so that the costatement will not be executed the next time it is encountered unless the costatement is declared always_on void CoResume CoData p This function unpauses a paused costatement The costatement will resume the next time it is called 5 4 5 Firsttime Functions In a function definition the keyword firsttime causes the function to have an implicit first parameter a pointer to the CoData structure of the costatement that calls it The following firsttime functions are defined in COSTATE LIB For more information see the Dynamic C Function Reference Manual These functions should be called inside a wait for statement because they do not yield while waiting
63. lastlocCBR If ChkSum is not consistent with the address the program will generate a run time error and reset The check sum is maintained automatically It is initialized by _GLOBAL_INIT CoBegin and CoReset First Time The firsttime field is a flag that is used by a wait for or wait fordone statement It is set to 1 before the statement is evaluated the first time This aids in calculating elapsed time for the functions De layMs DelaySec DelayTicks IntervalTick IntervalMs and IntervalSec Chapter 5 Multitasking with Dynamic C 49 Content The content field a union is used by the costatement or cofunction delay routines to store a delay count Check Sum 2 The ChkSum2 field is currently unused 5 4 3 Pointer to CoData Structure To obtain a pointer to a named costatement s CoData structure do the following CoData core allocate memory for a CoData struct CoData lt OCOsit lp pcostl amp costl get pointer to the CoData struct Copecqumm oeosielly i initialize CoData struct costate pcostl pcost1 is the costatement name and also a ff pointer to its CoData structure 5 4 4 Functions for Use With Named Costatements For detailed function descriptions please see the Dynamic C Function Reference Manual or select Function Lookup Insert from Dynamic C s Help menu keyboard shortcut is lt Ctrl H gt All of these functions are in COSTATE LIB Each one takes a pointer to a CoDat a struct as
64. only partially written at its next use Declaring a multibyte variable shared means that changes to the variable are atomic i e inter rupts are disabled while the variable is being changed Declaring a variable to be protected guards 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 when the variable is being changed the system will restore the variable from the copy main procectedhine statemi state States _sys IsSoftReset On restore any protected variables The call to_sysIsSoftReset checks to see if the previous board reset was due to the com piler restarting the program i e a soft reset If so then it initializes the protected variable flags and calls sysReset Chain a function chain that can be used to initialize any protect ed variables or do other initialization If the reset was due to a power failure or watchdog time out then any protected variables that were being written when the reset occurred are restored Explicit return from a function For functions that return values this will return the function re sult void func if expression return float func int x f float temp return temp 10 1 150 Dynamic C User s Manual Indicates a function is to be placed in root memory This keyword is semantically meaningful in function prototypes and produces mor
65. other operating systems It represents a contiguous area of the device set aside for file system operations An LX contains sectors that are all the same size and all contiguously addressable within the one device Thus a flash device with three different sector sizes would necessitate at least three logical extents and more if the same sized sectors were not adjacent FS1 does not allow mixing of devices it supports only one LX as defined in this document Files stored by the file system are comprised of two parts one part contains the actual application data and the other is a fixed size area used to contain data controlled by the file system in order to track the file status This second area called metadata is analogous to a directory entry of other operating systems The metadata consumes one sector per file The data and metadata for a file are usually stored in the same LX however they may be separated for performance reasons Since the metadata needs to be updated for each write operation it is often advantageous to store the metadata in battery backed SRAM with the bulk of the data on a flash device 10 4 2 1 Specifying Logical Extents When a file is created the logical extent s to use for the file are defined This association remains until the file is deleted The default LX for both data and metadata is the flash device LX 1 if it exists otherwise the RAM LX If both flash and RAM are available LX 1 is the flash de
66. param eters to the function lookup dialog Compare the function parameters in the 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 st rcpy and the Function Lookup Insert command is issued the function assistant will show the comment as parameter 1 and Lower tray needs paper as parameter 2 The arguments can then be compared with the expected parameters and the argu ments in the dialog can then be modified Chapter 14 Graphical User Interface 207 Instruction Set Reference Invokes an on line help system and displays the alphabetical list of instructions for the Rabbit 2000 microprocessor and the Rabbit 3000 microprocessor Keystrokes Invokes an on line help system and displays the keystrokes page Although a mouse or other pointing device may be convenient Dynamic C also supports operation entirely from the key board Contents Invokes an on line help system and displays the contents page From here view explanations of various features of Dynamic C Tech Support Bulletin Board Opens a browser window to a Z World Rabbit Semiconductor forum for products based on the Rabbit 2000 and the Rabbit 3000 Tip of the Day Brings up a window displaying some useful information about Dynamic C There is an option to scroll to another screen of Dynamic C information and an option to disa
67. permanently locked out of use Formatting is also required if any of the logical extent parameters are changed such as changing the logical sector size or re partitioning This would normally happen only during application development Chapter 10 The Flash File System 107 The question for application developers is how to code the application so that it formats the file system only the first time it is run There are several approaches that may be taken e A special program that is loaded and run once in the factory before the application is loaded The special program prepares the filesystem and formats it The application never formats it expects the filesystem to be in a proper state e The application can perform some sort of consistency check If it determines an inconsis tency it calls format The consistency check could include testing for a file that should exist or by checking some sort of signature that would be unlikely to occur by chance e Have the application prompt the end user if some form of interaction is possible e A combination of one or more of the above e Rely ona flash device being erased This would be OK for a production run but not suit able if battery backed SRAM was being used for part of the filesystem 10 4 2 Logical Extents LX In FS2 the presence of both devices causes an initial default configuration of two logical extents to be set up An LX is analogous to disk partitions used in
68. portaddr register address of the port PARAMETER2 value data to be written to the port RETURN VALUE None KE aa OLD Simo chachlMlcHiey Ss Oras SEE ALSO RdIOport END DESCRIPTION HK KK KK KK KK KK KKK KK If this format is followed user created library functions will show up in the Function Lookup Insert facility Note that these sections are scanned in only when Dynamic C starts 4 24 Support Files Dynamic C has several support files that are necessary in building an application These files are listed below Table 4 5 Dynamic C Support Files File Name Purpose of File DCW CFG Contains configuration data for the target controller Contains prototypes basic type definitions de fine and default modes eee for Dynamic C This file can be modified by the programmer Contains a set of use directives for each control product that Z World De UE ships This file can be modified 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 the libraries on the Dynamic C distribu tion disk Any library that is to be used in a Dynamic C program must be listed in the file LIB DIR or another DIR file specified by the user Starting with version Dynamic C 7 05 a different DIR file may be specified by the user in the Compiler Options dialog to facilitate working on multi
69. slice statements or using a slice statement inside a function that is either directly or indi rectly called from a slice statement The only methods supported for leaving a slice state ment are completely executing the last statement in the slice or executing an abort yield or wait for statement The return continue break and goto statements are not supported Slice statements cannot be used with uC OS II or DCRTCP LIB 60 Dynamic C User s Manual 5 9 4 Slice Data Structure Internally the slice statement uses two structures to operate When defining a named slice statement you supply a context buffer as the first argument When you define an unnamed slice statement this structure is allocated by the compiler Internally the context buffer is represented by the SliceBuffer structure below struct SliceData ioc CMe OVC VOLE im _Sior Monidi Callie sige CoData codata Stiuet SlieesBuitier SlieceData Slice _caitar char stack fills rest of the slice buffer 5 9 5 Slice Internals When a slice statement is given control it saves the current context and switches to a context associated with the slice statement After that the driving force behind the slice statement is the timer interrupt Each time the timer interrupt is called it checks to see if a slice statement is active Ifa slice statement is active the timer interrupt decrements the t ime_out field in the slice s SliceData When
70. 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 func tions and data The key tells the compiler what functions and data in the module are available for reference It is important 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 A key can have no names in it and it s associated header will still be parsed by the precompiler and compiler Chapter 4 Language 37 4 23 2 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 module known to the application With proper function prototypes and variable declarations a module header ensures proper type checking throughout the application program Prototypes vari ables structures typedefs and macros declared in a header section will always be parsed by the compiler if the library is used and will have global scope It is even permissible to put function bodies in header sections but this is not recommended Variables declared in a header section will be allocated memory space unl
71. the field is decremented to zero the timer interrupt saves the slice statement s context into the SliceBuffer and restores the previous context Once the timer interrupt completes the flow of control is passed to the statement directly following the slice statement A similar set of events takes place when the slice statement does an explicit yield abort wait for Chapter 5 Multitasking with Dynamic C 61 5 9 5 1 Example 1 Two slice statements and a costatement will appear to run in parallel Each block will run inde pendently but the slice statement blocks will suspend their operation after 20 ticks for slice_a and 40 ticks for slice_b Costate a will not release control until it either explicitly yields aborts or completes In contrast s1ice_a will run for at most 20 ticks then slice_b will begin running Costate a will get its next opportunity to run about 60 ticks after it relinquishes control main Iie XK Wp Be fOr 28 4 SO Siecie cmc slice S500 20 4 i slice a SLICE SOO AO q Ji alice 5 9 5 2 Example 2 This code guarantees that the first slice starts on TICK_TIMER evenly divisible by 80 and the second starts on TICK_TIMER evenly divisible by 105 main oe e2 costate slice 500 20 fi slice a waitfor IntervalTick 80 Slice 500 50 4 fi slice o WelILIE 1c Ne ALimeEeiaye Ee 62 Dynamic C User s Manual 5 9 5 3 Example 3 This approach is
72. the named files in the flash file system Chapter 10 The Flash File System 111 10 6 Skeleton Program Using FS1 The following program uses many of the file system commands It writes several strings into a file reads the file back and prints the contents to the STDIO window The macro RESERVE should be 0 when the file system is in SRAM When the file system is in flash memory you can adjust where it starts by defining RESERVE to be 0 or a multiple of the block size define FS FLASH use FILESYSTEM LIB define FORMAT define RESERVE OL define BLOCKS 64 define TESTFILE 1 main Pilkey Gea Lee GEAELe Claeae louseireie 256 p ifdef FORMAT fs_format RESERVE BLOCKS 1 iLit GHE ISASIES SIE ILS MESNE 4 printi cerror cresting WHS Ww iis Via 2 moct f else fs_init RESERVE BLOCKS if fopen_wr amp file TESTFILE print Terror CSSinaine Wa Sw Wis ia p TOLLED il g endif Eune CS aE ILS WaS lo G A IEWHeILES ena lian WI 2A 6 p Eweneens OT DO 6 p wails fread amp file buffer 6 gt 0 jOw sia st Ses Vin Oe eS y fclose amp file After running this program at least once comment out define FORMAT You will see that it runs in a similar fashion but now the file is appended using fopen_wr instead of being erased by fs_format
73. the priority of the interrupt before the ISR is called This effec tively turns off interrupts that are of the same or lower priority Generally the ISR performs the following actions 1 Save all registers that will be used i e push them on the stack Interrupt routines written in C save all registers automatically Stand alone assembly routines must push the registers explic itly 2 Determine the cause of the interrupt Some devices map multiple causes to the same interrupt vector An interrupt handler must determine what actually caused the interrupt 3 Remove the cause of the interrupt 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 Stand alone assembly routines must pop the registers explicitly 6 Restore the interrupt priority level so that other interrupts can get the attention of the CPU ISRs written in C restore the interrupt priority level automatically when the function returns However stand alone assembly ISRs must restore the interrupt priority level explicitly by call ing ipres The interrupt priority level must be restored immediately before the return instructions ret or reti Ifthe interrupts are enabled earlier the system can stack up the interrupts This may or
74. the right operand and 0 otherwise ae ae t 5J J4 body executesif i j OK a b truewhen a b 172 Dynamic C User s Manual 13 6 Logical Operators Logical AND This is a binary operator that performs the Boolean AND of two values If either operand is 0 the result is 0 FALSE Otherwise the result is 1 TRUE Logical OR This is a binary operator that performs the Boolean OR of two values If either oper and is non zero the result is 1 TRUE Otherwise the result is 0 FALSE 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 non zero The NOT operator result is 1 if the operand is 0 The result is 0 otherwise test get_input if test 13 7 Postfix Expressions Grouping Expressions enclosed in parentheses are performed first Parentheses also enclose func tion arguments In the expression a b c 10 the term b cis evaluated first Array subscripts or dimension All array subscripts count from 0 int a 12 array dimension is 12 j a i references the ith element Chapter 13 Operators 173 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 Right arrow Used with pointers to structures and unions instead of the dot operator typed
75. the stream as though it came from a serial port on the slave 7 3 3 1 Slave Side of Stream Channel To set up the function SPShandler as the byte stream handler do the following SPsetHandler 10 SPShandler stream_ptr This sets up the stream to use channel 10 on the slave A sample program in Section 7 3 3 2 shows how to set up and initialize the circular buffers An internal data structure SPSt ream keeps track of the buffers and a pointer to it is passed to SPsetHandler and some of the auxiliary functions that supports the byte stream handler This is also shown in the sample program 7 3 3 1 1 Functions These are the auxiliary functions that support the stream handler function SPShandler void cbuf_init char circularBuffer int dataSize DESCRIPTION This function initializes a circular buffer PARAMETERS circularBuffer The circular buffer to initialize dataSize Size available to data The size must be 9 bytes more than the number of bytes needed for data This is for internal book keeping LIBRARY RS232 LIB Chapter 7 The Slave Port Driver 85 int cof_SPSread SPStream stream void data int length unsigned long tmout DESCRIPTION Reads length bytes from the slave port input buffer or until tmout milliseconds tran spires between bytes after the first byte is read It will yield to other tasks while waiting for data This function is non reentrant PARAMETERS stream Pointer to the stream s
76. 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 KB physical address space The keyword xmem selects extended memory which means anywhere in the 1024 KB or 1 MB code space root and xmem are semantically meaningful in function prototypes and more effi cient code is generated when they are used Their use must match between the prototype and the function definition The directive memmap allows further control See Memory Manage ment on page 97 for further details on memory Dynamic C User s Manual 2 2 2 Dynamic C Differences The main differences in Dynamic C are summarized here and discussed in detail in chapters Lan guage on page 13 and Keywords on page 137 If a variable is explicitly initialized in a declaration e g int x 0 itis stored in Flash Memory EEPROM and cannot be changed by an assignment statement Starting with Dynamic C 7 x such declaration will generate a warning that may be suppressed using the const keyword const int x 0 To initialize static variables in Static RAM SRAM use GLOBAL_INIT sections Note that other C compilers will automatically initialize all static variables to zero that are not explicitly initialized before entering the main function Dynamic C programs do not do this because in an embedded system you may wish to preserve t
77. with Dynamic C 7 10 the polling is done every 3 seconds instead of every 100 ms 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 key board shortcut is lt Ctrl O gt Poll Target Starting with DC 7 30 This menu option used to be named Toggle Polling see above A check mark indicates that Dynamic C will poll the target The absence of a check mark indicates that Dynamic C will not poll the target This differs from Toggle Polling in that Dynamic C will not restart polling without the user explicitly requesting it The keyboard shortcut is lt Ctrl O gt Reset Target Tells the target system to perform a software reset including system initializations Resetting a target always brings Dynamic C back to edit mode The keyboard shortcut is lt Ctrl Y gt Close Serial Port Disconnects the programming serial port between PC and target so that the target serial port is accessible to other applications 188 Dynamic C User s Manual 14 2 5 Inspect Menu Click the menu title or press lt Alt I gt to select the INSPECT menu n Options Window Help Sh Add Del Watch Expression Ctrl W 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 pro
78. 0 Dynamic C User s Manual 4 7 2 Character Constants Character constants have a slightly different meaning They are not strings A character constant is enclosed in single quotes and is a representation of an 8 bit integer value a Nin x1B Any character can be represented by an alternate form whether in a character constant or in a string Thus nonprinting characters and characters 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 a leading zero is optional B10000001 the binary value 10000001 There are also several special forms preceded by a backslash a bell b backspace f formfeed n newline r carriage return t tab v vertical tab O null character backslash c the actual character c single quote double quote Examples wie gare V elle y Y embedded double quotes canst char j VA s character constant const Chai MSE Pmie wour S im Ele A Cleave ia l embedded new line at end printf MSG print MSG chars sdetault Ua empty string a single Nul1 byte 4 8 Statements Except for comments everything in a C program is a statement Almost 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
79. 0000 then this option should be unchecked When compiling to a bin file choose Use attached target to use the parameters of the con troller connected to your system Some versions of Dynamic C do not support this menu option If there is no connected controller or if there is but you want to use a different config uration choose Compile with defined target configuration To define a target configuration access the Configure Targetless Compilation dialog box It has been relocated to Options Define target configuration and the Compile Compile to a bin file menu selection now compiles with those parameters upon acceptance of a confirmation prompt Reset Target Compile BIOS This option reloads the BIOS to RAM or flash depending on the BIOS memory setting cho sen in Options Compiler dialog box The default option is flash The following box will appear upon successful compilation and loading of BIOS code BIOS Successfully Compiled Ready to Compile User Programs Chapter 14 Graphical User Interface 185 Include Debug Code RST 28 Instructions If this is checked debug code will be included in the program even if nodebug precedes the main function in the program Debug code consists mainly of RST 28h instructions inserted after every C statement Atan RST 28h instruction program execution is trans ferred to the debug kernel where communication between Dynamic C and the target is tended to before returning to the user progr
80. 0k This limitation holds true even on boards with a512k RAM chip The limitation involves the placement of BIOS con trol blocks in the upper part of the lower 256k portion of RAM To obtain more RAM memory xalloc may be used If xalloc is called first thing in the program the same memory addresses will always be returned This can be used to store non vola tile data is so desired if the RAM is battery backed however it is not possible to manage this area using the file system When using FS1 since only one device type is allowed at a time the entire file system would have to be in SRAM This is recommended for debugging purposes only Using FS2 increases flexibil ity with its capacity to use multiple device types simultaneously Since RAM is usually a scarce resource it can be used together with flash memory devices to obtain the best balance of speed performance and capacity 10 1 3 Wear Leveling The current code has a rudimentary form of wear leveling When you write into an existing block it selects a free block with the least number of writes The file system routines copy the old block into the new block adding in the users new data This has the effect of evening the wear if there is a reasonable turnover in the flash files 10 1 4 Low Level Implementation For information on the low level implementation of the flash file system refer to the beginning of the library files FS2 LIB and FS_DEV LIB if using FS2 or library
81. 1 Failure LIBRARY MASTER_SERIAL LIB int cof_MSwrite char address char data int length DESCRIPTION Transmits an array of bytes from the serial port on the slave Yields to other tasks while waiting for write buffer to clear PARAMETERS address Slave channel address of serial handler data Array to be transmitted length Size of array RETURN VALUE Number of bytes actually written or 1 if error LIBRARY MASTER_SERIAL LIB Chapter 7 The Slave Port Driver 77 int MSclose char address DESCRIPTION Closes a serial port on the slave PARAMETERS address Slave channel address of serial handler RETURN VALUE 0 Success 1 Failure LIBRARY MASTER_SERIAL LIB int MSgetc char address DESCRIPTION Receives a character from the serial port PARAMETERS address Slave channel address of serial handler RETURN VALUE Value of received character 1 No character available LIBRARY MASTER_SERIAL LIB 78 Dynamic C User s Manual int MSgetError char address DESCRIPTION Gets bitfield with any current error from the specified serial port on the slave Error codes are SER_PARITY_ERROR 0x01 SER_OVERRUN_ERROR 0x02 PARAMETERS address Slave channel address of serial handler RETURN VALUE Number of bytes free Success 1 Failure LIBRARY MASTER_SERIAL LIB int MSinit int io_bank DESCRIPTION Sets up the connection to the slave PARAMET
82. 1 3 Stand Alone Assembly Code 120 Stand Alone Assembly Code in Extended Memoty 00 121 Example of Stand Alone Assembly Codes snes ache A a ieee 121 11 4 Embedded Assembly Code 122 The Stack Frame eee 122 Embedded Assembly Example 124 Local Variable Access 4 126 11 5 C Calling Assembly 127 Passing Parameters cee 127 Location of Return Resullts 127 11 6 Assembly Calling Co ee 129 11 7 Interrupt Routines in Assembly 130 Steps Followed by an ISR 130 Modifying Interrupt Vectors 131 11 8 Common Problems eee 136 12 Keywords eeceeesseecsestesseeeeseseeneeeees 137 abandonis mnie 137 ADOT side a Ase 137 ALIGN seve ste svecdtessvessesdovavevsey ee 138 always Oninin 138 ADYVMEM esrin ee es 138 asmina a ene eee a 139 AANO E A EEEE REE E 139 DbLaM esse ke Ee 139 Break asnes 139 C wand nieahd haan E 140 CASE esccsivccsntcssugecetesccegshesecesddcensess 140 Chak site bie 140 CODSLe sees raS a E betes EE 141 Dynamic C User s Manual CONNUE seieiccsne etic Bei eaae 142 FAA seek ccsesceseoces ie ae 160 COSTAE inea E 142 GLOBAL_INIT o e 160 debti a EE 142 HeiTOT 0 3065 vices e ne e a a 161 defaults ni aeai 143 funcchain 00 eeeeeseceeeeceeeeeneeeeees 161 dO e a ee Bi aie Ss 143 if EE ai EE E 143 elif enU er aa a eek et 144 else A n EE AEE 144 endif ooreen eee a 161 F
83. 1 means 456 x 107 0 3141592e1 means 3 141592 Chapter 4 Language 19 4 7 Strings and Character Data A string is 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 C does not have a string data type it does have character arrays that serve the purpose C does not have string opera tors such as concatenate but library functions strcat and strncat are available Strings are multibyte objects and as such they are always referenced by their starting address and usually by a char variable More precisely arrays are always passed by address Passing a pointer to a string is the same as passing the string Refer to Section 4 15 for more information on pointers The following example illustrates typical use of strings const char select Select option n Elagie start SZ p strepy start Press any key when ready n OmuMer select Jy pass pointer to string princi start 5 pass string 4 7 1 String Concatenation Two or more string literals are concatenated when placed next to each other For example Rabbits like carrots becomes Rabbits like carrots during compilation If the strings are on multiple lines the macro continuation character must be used For example Rabbits don t like line dancing becomes Rabbits don t like line dancing during compilation 2
84. 2 Dynamic C User s Manual 14 2 6 2 Compiler The Compiler command gets Dynamic C to display the following dialog which allows compiler operations to be changed Compiler Options M Run Time Checking These options if checked can allow a fatal error at run time They also increase the amount of code and cause slower execution but they can be valuable debugging tools e Array Indices Check array bounds This feature adds code for every array reference e Pointers Check for invalid pointer assignments A pointer assignment is invalid if the code attempts to write to a location marked as not writable Locations marked not writable include the entire root code segment This feature adds code for every pointer reference Chapter 14 Graphical User Interface 193 BIOS Memory Setting A single default BIOS source file that is defined in the system registry when installing Dynamic C is used for both compiling to RAM and compiling to flash Dynamic C defines a preprocessor macro FLASH_ _RAM_or_FAST_RAM_ depending on which of the fol lowing options is selected This macro is used to determine the relevant sections of code to compile for the corresponding memory type e Code and BIOS in Flash If you select this option the compiler will load the BIOS to flash when cold booting and will compile the user program to flash where it will nor mally reside e Code and BIOS in RAM TIf you select this option the compile
85. 20 embedded quotes 21 nonprinting values 21 special values cesses 21 clipboard snieni 183 closing a file woe 181 CoData Structure oe 48 pointer tO wee 50 COFUNCTIONS 00 eee eee eeeeee 52 57 abandon rr 56 calling restrictions 53 everytime ooo eee 56 PITSUHME psani 145 INGEX EDs oniinn aaa 54 Single User eee eee 54 SYNTAR seier ieie 52 cold loader oo eee eeeeeeeeeeee 185 COM pott o0 eee eee eeeeee 199 communication SEM al ee atievsntahaeseed ves 199 TCP IP hitia 199 compile sirince wes 185 BIOS ennen 185 command line 209 226 CLLOTS opikseen nirre iiis ai 184 MEDU ginoes 185 OPTIONS isinisisi 193 Sp ed enini e 3 SATUS 5s csssss05 ees scivessseescsea s 205 targetless wee 185 TOILE ritiri 179 185 tofas hench 185 to RAM sisisi 185 to target we 179 185 compiler directives 4 159 ASM oo eects 115 159 232 OPTIONS oe 159 Helas S neneiia 159 Options oe 159 debug 149 159 232 271 define ceeeeeeee 17 160 ci P SEAE LAE A 161 Ea TE EAEE E ERA 161 endasm 115 119 160 H endif esenee 161 FEOT re a 161 Ffata loa ossad ro n RnS 160 funcchain 06 34 161 GLOBAL_INIT 160 ALL te estes esate eceenaeeaes 161 Hifdef aside sic eirs 162 ifndef 0 ececeeeeeeee 162 Hinterleave o ccceceeeees 162 AKM iran 162 makechain 34 162 MEMMAP neseser 162 Op
86. 6 call rspixffn_ 12 15fb c9 ret 8 15fce D9 exx 2 15fd 21Fcrr ld hl FFFC 6 1600 CD2A16 call sspixffn_ 12 1603 EF rst 28h 1604 218888 ld h1 8888 6 1607 D402 ld sp 2 hl 11 J Pc l zZ BC DE HL IX PC 2233 6677 4455 16D0 OSFF 21D2 Ope4 Sed 11 4455 6677 0011 0000 15ED Edit Compile Assemb Regs zec bo AF 0000 BC 0000 DE 0000 HL D3FD IY 15B SP D3F5 Figure 5 Registers Stack and Disassembled Code Windows a Chapter 11 Using Assembly Language 125 11 4 2 2 Instruction Cycle Time The Disassembled Code window shows the memory address on the far left followed by the code bytes for the instruction at the address followed by the mnemonics for the instruction The last column shows the number of cycles for the instruction assuming no wait states The total cycle time for a block of instructions will be shown at the lowest row in the block in the cycle time col umn if that block is selected and highlighted with the mouse The total assumes one execution per instruction so the user must take looping and branching into consideration when evaluating exe cution times 11 4 3 Local Variable Access Accessing static local variables is simple because the symbol evaluates to the address directly The following code shows for example how to load static variable y into HL tachi 37 load hl with contents of y 11 4 3 1 Using the IX Register Access to stack based l
87. 9 2 Extended Memory Functions 98 Code Placement in Memory 98 10 The Flash File System oe 99 10 1 General Usage 0 eee ee eeeeeeee 99 Maximum File Size wo 100 Using SRAM oseere 100 Wear Leveling 100 Low Level Implementation 100 Multitasking and the File System 100 10 2 Application Requirements 101 FS1 Requirements cee 101 FS1 and Use of the First Flash 101 FS2 Requirements eee 102 FS2 Configuration Macros 103 FS2 and Use of the First Flash 104 10 3 Functions 20 0 eeseeeeceeeeeeeeeeee 105 ES LAPD isc 2th ciara 105 FESZ API 08 8 cn ea en 106 10 4 Setting up and Partitioning the File SYSCOM eiia tai ra 107 Initial Formatting 107 Logical Extents LX 108 Logical Sector Size 109 10 5 File Identifiers 0 eee 110 File Numbers sssr 110 Fil Names vic s cscsessesccecseeteastsscoests 110 10 6 Skeleton Program Using FS1 112 10 7 Skeleton Program Using FS2 113 11 Using Assembly Language 115 11 1 Mixing Assembly and C 115 Embedded Assembly Syntax 115 Embedded C Syntax 116 Setting Breakpoints in Assembly 116 11 2 Assembler and Preprocessor 117 Comments eee eseeseeeseceeeeees 117 Defining Constants 0 0 117 Multiline Macros oo eee 118 Labels er an ea 119 Special Symbols 0 eee 119 C Variables renren i 119 1
88. 92 auto 139 lt ALT SHIFT backspace gt ee meee eee reece eres eeseeeeseses ol Eereeerererereers 120 126 127 129 bbram 139 redoing changes ge ys 182 ee meee reece eee ee ees esse eseses Home key asiera anes 179 break 139 Sii lt ALT W gt Pee eee eee eee eee eee eee eee eee ees horizontal tiling 202 e 140 select Window menu 202 esesesesosososososososoosososesosososooo l lt CTRL F10 gt CASCE 25 E E 140 Disassemble at Cursor 190 char ER EE 140 icons lt CTRL F2 gt COntInue osesesesiseeeseseseeerereee 142 arranged nuses 202 Reset Program s 187 COSIALE aprii 142 IEEE floating point 145 lt CTRL G gt debug scorri cera 142 UE E E E 143 Goto notes 184 defali issii eieae 143 multichoice eeeeeeee ee ee 33 lt CTRL H gt dO A ieee ects es 143 simple adi cad ALLIRI IIR ONEEN 32 Library Help lookup a 206 CISC E EEE 143 with else sssoneessoensesseeessee 33 lt CTRL I gt CRUD cc EE EER ET 144 information window 202 205 Toggle Interrupt Flag 188 Exter moer innii 144 INDE LOM r dies weieerteaeeasesnce 147 lt CTRL N gt firsttime oo eee 145 insertion point 183 184 ERE EAB EET 184 float ve nanie 145 Inspect menu 189 203 lt CTRL O gt fOf shee aS 145 installation Poll Target u nan 188 BOLO ssc soevesstessdeesastessees otentcs 146 Dynamic Ceea eee Cree nee 6 Toggle polling Jaen ATL 188 if PERIE eiieis dinje e Hoje viele A NEAAF 146 Instruction Set Refe
89. Address of Register Internal Register From g Address of g Register Use Name z Master s Register i Perspective SPDOR 0x20 0 Command and response register SPD1R 0x21 1 Address register SPD2R 0x22 2 Optional data register SPSR 0x23 3 Slave port status register In this protocol the only bit used is for checking the command response register Bit 3 is set if the slave has written to SPDOR It is cleared when the master writes to SPSR which also deasserts the SLAVEATTN line Chapter 7 The Slave Port Driver 69 Accessing the same address 0 1 or 2 uses two different registers depending on whether the access was a read or a write In other words when writing to address 0 the master accesses a dif ferent location than when the it reads address 0 Table 7 8 What happens when the master accesses a slave register Register Address Read Write 0 Gets command response from Sends command to slave triggers slave slave response 1 Not used Sets channel address to send command to 2 Gets returned data from slave Sets data byte to send to slave 3 Gets slave port status see Clears slave response bit see below below The status port is a bit field showing which slave port registers have been updated For the pur poses of this protocol Only bit 3 needs to be examined After sending a command the master can check bit 3 which is set when the slave writes to the response register At this poin
90. C version 7 20 introduced more control when single stepping through a uC OS II pro gram Prior to 7 20 single stepping occurred in whichever task was currently running It was not possible to limit the single stepping to one task Starting with Dynamic C 7 20 single stepping may be limited to the currently running task by using F8 Step over If the task is suspended single stepping will also be suspended When the task is put back in a running state single stepping will continue at the statement following the statement that suspended execution of the task Hitting F7 Trace into at a statement that suspends execution of the current task will cause the program to step into the next active task that has debug information It may be useful to put a watch on the global variable OSPrioCur to see which task is currently running For example if the current task is going to call OSSemPend on a semaphore that is not in the signaled state the task will be suspended and other tasks will run If F8 is pressed at the statement that calls OSSemPend the debugger will not single step in the other running tasks that have debug information single stepping will continue at the statement following the call to OSSemPend If F7 is pressed at the statement that calls OSSemPend instead of F8 the debugger will single step in the next task with debug information that is put into the running state 254 Dynamic C User s Manual Dynamic C User s
91. Conditional Operators Conditional operators are a three part operation unique to the C language The operation has three operands and the two operator symbols and If the first operand evaluates true non zero then the result of the operation is the second operand Otherwise the result is the third operand int i j k i sj 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 Chapter 13 Operators 175 13 10 Other Operators The cast operator converts one data type to another A floating point value is 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 typeA iteml typeB item2 item2 typeB iteml forces item1 to be treated as a typeB 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 if it were a built in function taking an object or a type as a parameter typedef struct
92. Creates a file with an unused file number fopen_rd FS2 Opens a file for reading fopen_wr FS2 Opens a file for writing and reading fshift Removes specified number of bytes from file fwrite FS2 Writes to a file starting at current position fread FS2 Reads from the current file pointer fseek FS2 Moves the read write pointer ftell FS2 Returns the current offset of the file pointer fs_syne FS2 Flushes any buffers retained in RAM to the underlying hardware device fflush FS2 Flushes buffers retained in RAM and associated with the specified file to the underlying hardware device Paget siden ae Heo etn ie ane of the preferred flash device the fs_get_lx_size FS2 Returns the number of bytes of the specified LX fe get other le so a LX of the non preferred flash usually the first fs_get_ram_lx FS2 Return the LX number of the RAM file system device fclose Closes a file fdelete FS2 Deletes a file 106 Dynamic C User s Manual 10 3 2 1 FS2 API Details The functions fs_init and fs_format are used in a slightly different manner than in FS1 fs_init does not use its two parameters reserveblocks and numblocks since it computes appropriate values internally s_format should only be called after fs_init if necessary This function s first parameter reserveblocks must be 0 any thing else returns an error This is one of the few cases of incompatibility between FS1
93. 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 or new text may be typed in directly New text is 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 14 2 Menus Dynamic C Joj x File Edit Compile Run Inspect Options Window Help Dynamic C has eight command menus as well as the standard Windows system menus An avail able 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 acti vated by holding the Alt key down while pressing the underlined letter of the menu name For example press lt Alt F gt to activate the FILE menu 14 2 1 File Menu Click the menu title or press lt Alt F gt to select the FILE menu Prior to Dynamic C 8 x there is a 10 000 line limit on the size of a single source file If your source code is that big split up some of it into libraries ed factory Dynami
94. EEMENT IMPORTANT READ CAREFULLY BY INSTALLING COPYING OR OTHERWISE USING THE ENCLOSED Z WORLD INC Z WORLD DYNAMIC C SOFTWARE WHICH INCLUDES COMPUTER SOFTWARE SOFTWARE AND MAY INCLUDE ASSOCIATED MEDIA PRINTED MATERIALS AND ONLINE OR ELECTRONIC DOCUMENTATION DOCUMENTATION YOU ON BEHALF OF YOURSELF OR AS AN AUTHORIZED REPRESENTATIVE ON BEHALF OF AN ENTITY AGREE TO ALL THE TERMS OF THIS END USER LICENSE AGREEMENT LICENSE REGARDING YOUR USE OF THE SOFTWARE IF YOU DO NOT AGREE WITH ALL OF THE TERMS OF THIS LICENSE DO NOT INSTALL COPY OR OTHERWISE USE THE SOFTWARE AND IMMEDIATELY CON TACT Z WORLD FOR RETURN OF THE SOFTWARE AND A REFUND OF THE PUR CHASE PRICE FOR THE SOFTWARE We are sorry about the formality of the language below which our lawyers tell us we need to include to protect our legal rights If You have any questions write or call Z World at 530 757 4616 2900 Spafford Street Davis California 95616 1 Definitions In addition to the definitions stated in the first paragraph of this document capital ized words used in this License shall have the following meanings 1 1 Qualified Applications means an application program developed using the Software and that links with the development libraries of the Software 1 1 1 Qualified Applications is amended to include application programs developed using the Softools WinIDE program for Rabbit processors available from Softools Inc 1 1 2 The MicroC OS
95. ERS io_bank The IO bank and chip select pin number for the slave device This is a number from 0 to 7 inclusive RETURN VALUE 1 Success LIBRARY MASTER_SERIAL LIB Chapter 7 The Slave Port Driver 79 int MSopen char address unsigned long baud DESCRIPTION Opens a serial port on the slave given that there is a serial handler at the specified ad dress on the slave PARAMETERS address Slave channel address of serial handler baud Baud rate for the serial port on the slave RETURN VALUE 1 Baud rate used matches the argument 0 Different baud rate is being used 1 Slave port comm error occurred LIBRARY MASTER_SERIAL LIB int MSputc char address char ch DESCRIPTION Transmits a single character through the serial port PARAMETERS address Slave channel address of serial handler ch Character to send RETURN VALUE 1 Character sent 0 Transmit buffer is full or locked LIBRARY MASTER_SERIAL LIB 80 Dynamic C User s Manual int MSrdFree char address DESCRIPTION Gets the number of bytes available in the specified serial port read buffer on the slave PARAMETERS address Slave channel address of serial handler RETURN VALUE Number of bytes free Success 1 Failure LIBRARY MASTER_SERIAL LIB int MSsendCommand char address char command char data char data_returned unsigned long timeout DESCRIPTION Sends a single command to the sl
96. ESENTATIVES SHALL CREATE A WARRANTY OR IN ANY WAY INCREASE THE SCOPE OF THIS WARRANTY SOME JURISDIC TIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES SO THE ABOVE EXCLUSION MAY NOT APPLY TO YOU 7 Limitation of Liability YOU AGREE THAT UNDER NO CIRCUMSTANCES INCLUD ING NEGLIGENCE SHALL Z WORLD BE LIABLE FOR ANY INCIDENTAL SPECIAL OR CONSEQUENTIAL DAMAGES INCLUDING DAMAGES FOR LOSS OF BUSINESS PROFITS BUSINESS INTERRUPTION LOSS OF BUSINESS INFORMATION AND THE LIKE ARISING OUT OF THE USE AND OR INABILITY TO USE THE SOFTWARE EVEN IF Z WORLD OR ITS AUTHORIZED REPRESENTATIVE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OR EXCLUSION OF LIABILITY FOR INCIDENTAL OR CONSE QUENTIAL DAMAGES SO THE ABOVE LIMITATION OR EXCLUSION MAY NOT APPLY TO YOU IN NO EVENT SHALL Z WORLDS TOTAL LIABILITY TO YOU FOR ALL DAMAGES LOSSES AND CAUSES OF ACTION WHETHER IN CONTRACT TORT INCLUDING NEGLIGENCE OR OTHERWISE EXCEED THE AMOUNT PAID BY YOU FOR THE SOFTWARE 8 Termination This License is effective for the duration of the copyright in the Software unless terminated You may terminate this License at any time by destroying all copies of the Software and its documentation This License will terminate immediately without notice from Z WORLD if You fail to comply with any provision of this License Upon termination You must destroy all copies of the Software and its documentation Except for Sec
97. FilePathname Bios RabbitBios c GUI Equivalent Select the Options Compiler User Defined BIOS File Use menu Example dialog box option dccl_cmp myProgram c bf MyPath MyBIOS 1lib d MacroDefinition Description Default Define macros and optionally equate to values The following rules apply and are shown here with examples and equiva lent define form Separate macros with semicolons dccl_cmp myProgram c d DEF1 DEF2 define DEF1 define DEF2 A defined macro may be equated to text by separating the defined macro from the text with an equal sign dccl_cmp myProgram c d DEF1 20 DEF2 define DEF1 20 define DEF2 Macro definitions enclosed in quotation marks will be interpreted as a sin gle command line parameter dccl_cmp myProgram c d DEF1l text with spaces DEF2 define DEF1 text with spaces define DEF2 A backslash proceeding a character will be kept except for semicolon quote and backslash which keep only the character following the backslash An escaped semicolon will not be interpreted as a macro separator and an escaped quote will not be interpreted as the quote defining the end of a command line parameter of text dccl_cmp myProgram c d DEF1l statement ESCQUOTE define DEF1 statement define ESCQUOTE dccl_cmp myProg c d FSTR Temp 6 2F DEGREES C n define FSTR Temp 6 2f degrees C n None GUI Equivalent Select the Op
98. ITS ME oe i n aei 145 raO E E E 162 floaten nn ameoa a 145 HINGE Les netre ienen e 162 IO EE E E Geechee 145 interleave POO ena a Ra aer a E ES 146 nointerleave eee 162 Poe acl ish abies eesti Bieta 146 PRU E o i a rates 162 init_on a ou alt hea EAA 147 Hmakechain a 162 int Lien aS E ceva cebtep cate a ae e 147 HMEMMA evsesesessseseeseeeeseveeeeeeeveee 162 Interript aeina nea aai 147 Hprecompile sssssseessesseeeeeeeeeeeeeee 163 INCELTUPt_VECLOL eosessssssssssseseeenees 148 HINGE Fata ns enna 163 TONG a 148 HUSE oaase 163 MAINS 3 3 52 nA Read ie Ea 149 A aceite NOGEDUG risiini eisenii 149 ENT E 163 norst a a O E RN 149 aae e aA oe Aa ts an 164 MOSI seep E ER E er 142 WAM nnnnnnnnnnn 164 NUL Een rn ata nie ean 149 XUMPOTt nnn 164 protected issi irikiera 150 TE i aiie 150 13 Operators oo eeeceeeeeeeeeeeeeeeteeeeteeeees 165 TOOT e T 151 13 1 Arithmetic Operators 0 0 0 166 SePChAaIM olka 151 o E Gi disens dh E EE 166 Sh r d sisa aaeeio BLO 2 eA ths heal aeaa a aa 166 SHOL shes och nish ee ET 152 es celta beet E a igi AE 167 SIZ EE A EEE 152 Lasagne EE EA 167 sizeof enea E NTE 152 PoE oo See Seek eE SE 168 Speed iiss nasa irse aiis 152 E E 168 StA a eae ari 153 Tse So E EE AE 168 SUC tiina e ni a rT 153 13 2 Assignment Operators 0 0 169 SWiteh nA wana heen aia 154 St Ate an deh iain at 169 typedef 154 T a E 169 LEa TTO a EEE E AEE 155 E E teenechueyeaes 169 USI ENEJ iiinn 155 E E 169 ETE D E E E
99. Manual Part Number 019 0071 020813 R Printed in U S A 2001 Z World Inc All rights reserved Z World reserves the right to make changes and improvements to its products without providing notice Notice to Users Z WORLD PRODUCTS ARE NOT AUTHORIZED FOR USE AS CRITICAL COMPONENTS IN LIFE SUPPORT DEVICES OR SYS TEMS UNLESS A SPECIFIC WRITTEN AGREEMENT REGARD ING SUCH INTENDED USE IS ENTERED INTO BETWEEN THE CUSTOMER AND Z WORLD PRIOR TO USE Life support devices or systems are devices or systems intended for surgical implantation into the body or to sustain life and whose failure to perform when properly used in accordance with instructions for use provided in the labeling and user s manual can be reasonably expected to result in significant injury No complex software or hardware system is perfect Bugs are always present in a system of any size In order to prevent danger to life or prop erty it is the responsibility of the system designer to incorporate redun dant protective mechanisms appropriate to the risk involved Trademarks Dynamic C isa registered trademark of Z World Inc Windows is a registered trademark of Microsoft Corporation Z World Inc 2900 Spafford Street Davis California 95616 6800 USA Telephone 530 757 3737 Fax 530 757 3792 www zworld com 256 Appendix A Macros and Global Variables This appendix contains many macros and global variables that may be of interest
100. PC ports to work properly with Dynamic C Disable Baud Negotiation Since Dynamic C version 7 25 the compiler negotiates a baud rate for program download This helps with USB or anyone who happens to have a high speed serial port This default behavior may be disabled by checking the Disable Baud Negotiation checkbox When baud negotiation is disabled the program will download at 115k baud or 56k baud only When enabled it will download at speeds up to 460k baud as specified by Max Download Baud Rate 200 Dynamic C User s Manual 14 2 6 6 Define Target Configuration The Define target configuration menu option displays the following dialog box Configure Targetless Compilation 22MH2z RCM2300 128K SRAM 256k Flash fd pawo OOOO O O OE mee E ee Be es There are three options available in this dialog box for choosing the board parameters that will be used in the compile Select Board Type is the default choice and activates the Board ID pull down menu a list of all known board configurations Specify Board Parameters when checked brings up a dialog box to enter data for a new board configuration The name specified in the dia log box for the new board configuration will be automatically included in the Board ID pull down menu Use Target Information File when checked will prompt for a Remote Target Information RTD file Any target configuration can be saved as a rt i file by clicking the Save as RTI but ton a
101. Pores kndHeader 7 unsigned long ticks BeginHeader Get_Ticks unsigned long Get_Ticks Poors WiaClleackeie 7 7 unsigned long Get_Ticks Pre B ginieader Line Ticks vorei Ime TLekS diate a Jy fs machieader asm TACAPICKS i OP a losec il ipres 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 Although Inc_Ticks is an assembly language routine it has a function prototype in the module header allowing the compiler to check calls to it 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 Chapter 4 Language 39 4 23 4 Function Description Headers Each user callable function in a Z World library has a descriptive header preceding the function to describe the function Function headers are extracted by Dynamic C to provide on line help mes sages The header is a specially formatted comment such as the following example START FUNCTION DESCRIPTION AAAA AAAA SS ERRAR WrlOport TONBE SYNTAX VON Tr Oporne Gne porcadadr inti yale IDI SICIRILEME ION 8 Writes data to the specified I O port PARAMETER1
102. R of the two command responses Set baud factor byte 1 LSB The actual baud rate is the baud factor 4 as multiplied by 300 Set baud factor byte 2 MSB The actual baud rate is the baud factor 5 Me multiplied by 300 6 Set port configuration bits 7 Open port 8 Close port Get errors Slave responds with 1 if the port is open and can return an error 9 bitfield The error bits are the same as for the function serAgetErrors and are put in the data return register by the slave Returns count of free bytes in the serial port write buffer The two 10 11 commands return the LSB and the MSB of the count respectively The LSB 10 should be read first to latch the count Returns count of free bytes in the serial port read buffer The two 12 13 commands return the LSB and the MSB of the count respectively The LSB 12 should be read first to latch the count Returns count of bytes currently in the serial port write buffer The two 14 15 commands return the LSB and the MSB of the count respectively The LSB 14 should be read first to latch the count Returns count of bytes currently in the serial port write buffer The two 16 17 commands return the LSB and the MSB of the count respectively The LSB 16 should be read first to latch the count Chapter 7 The Slave Port Driver 7 3 2 2 Slave Side of Protocol To set up the serial port handler to connect serial port A to channel 5 do the followi
103. SPCR SPCRShadow 0x84 output count WrPortI PADR NULL count increment and return count return aPpiiCOwiaie 160 Dynamic C User s Manual Syntax error Instructs the compiler to act as if an error was issued The string in quotes following the direc tive is the message to be printed Syntax funcchain chainname name Adds a function or another function chain to a function chain Syntax if constant_expression elif constant_expression felse fendif These directives control conditional compilation Combined they 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 Code belonging to the other choices is ignored main if BOARD TYPE 1 define product Ferrari elif BOARD TYPE 2 define product Maserati elif BOARD_TYPE define produce hemloorelaiim else define product Chevy renci f The elif and e1se directives are optional Any code between an else and an endif is compiled if all values for constant_expression are false Chapter 12 Keywords 161 Syntax ifdef name This directive enables code compilation if name has been defined with a de fine directive This directive must have a matching endif Syntax ifndef name This directive enables code compilation if name has not been defined with a def ine direc tive This directive must have a matching
104. ST28_OFS SERE_OFS RST38_OFS SERF_OFS SLAVE_OF S QUAD_OF S TIMERA_OFS INPUTCAP_OF S TIMERB_OFS Table 11 21 External Interrupts and their offset from XINTVEC_BASE EXTO_OFS EXT1_OFS Chapter 11 Using Assembly Language 131 The following example from RS232 LIB illustrates the new I amp D space compatible way of mod ifying interrupt vectors The following code fragment to set up the interrupt service routine for the periodic interrupt from Dynamic C 7 25 is not compatible with separate I amp D space asm xmem Old method ld a iir get the offset of interrupt table ld h a ld 1 0x00 ld iy hl ld iy 0c3h jp instruction entry inc iy ld hl periodic_isr set service routine ld iy hl endasm The following code fragment shows an I amp D space compatible method for setting up the ISR for the periodic interrupt in Dynamic C 7 30 asm xmem New method ld a 0xc3 Jp instruction entry ld hl periodic_isr set service routine ld INTVEC_BASE PERIODIC_OFS a write to the interrupt table ld INTVEC_BASE PERIODIC_OFS 1 hl endasm When separate I amp D space is enabled INTVEC_BASE points to a proxy interrupt vector table in RAM that is modifiable The code above assumes that the actual interrupt vector table pointed to by the IIR is set up to point to the proxy vector When separate I amp D space is disabled INTVEC_BASE an
105. Staken ee 202 204 Stdio we 197 202 203 tiled horizontally 0 0 0 0 202 tiled vertically 0 202 watch 190 202 203 X datas an 157 XMEM ooeesseseersrsrsrsrsessrse 127 157 asm blocks ceceeeeeeee 121 Dd u ET EEEE E E dee 97 234 XSIDE eeann had ei 157 Y yield ennnen 158 276 Dynamic C User s Manual
106. T2 T2 T1 float NA multiply by 1000 to convert ms to us jOmiiane MEM EO execute test Code Sir usya 12710000 66 Dynamic C User s Manual 6 4 Watchdog Timers Watchdog timers limit the amount of time your system will be in an unknown state 6 4 1 Hardware Watchdog The Rabbit CPU has one built in hardware watchdog timer WDT The Virtual Driver hits this watchdog periodically The following code fragment could be used to disable this WDT asm Lda a 0x51 ioi ld WDTTR a ld a 0x54 ioi ld WDTTR a endasm However it is recommended that the watchdog not be disabled This prevents the target from entering an endless loop in software due to coding errors or hardware problems If the Virtual Driver is not used the user code should periodically call hitwd When debugging a program if the program is stopped at a breakpoint because the breakpoint was explicitly set or because the user is single stepping then the debug kernel hits the hardware watchdog periodically 6 4 2 Virtual Watchdogs There are 10 virtual WDTs available they are maintained by the Virtual Driver Virtual watch dogs like the hardware watchdog limit the amount of time a system is in an unknown state They also narrow down the problem area to assist in debugging The function VdGetFreeW count allocates and initializes a virtual watchdog The return value of this function is the ID of the virtual watchdog I
107. To obtain the logical extent number for a one flash board fs_get_flash_1x must be called instead of fs_get_other_1x 104 Dynamic C User s Manual 10 3 Functions For backwards compatibility FS2 uses the same function names as FS1 Some functions have enhanced semantics when using FS2 For example fwrite will allow writing over existing parts of the file rather than just appending 10 3 1 FS1 API These functions are the file system API for FS1 They are defined in FILESYSTEM LIB Fora complete description of these functions please see the Dynamic C Function Reference Manual Table 10 15 FS1 API Command Description fs_init FS1 Initialize the internal data structures for the file system fs_format FS1 Initialize the flash memory and the internal data structures Ee eee Teen Reserves blocks for privileged files FS1 fsck FS1 Verifies data integrity of files fcreate FS1 Creates a file and open it for writing fcreate_unused F RE Creates a file with an unused file number FS1 fopen_rd FS1 Opens a file for reading fopen_wr FS1 Opens a file for writing also opens it for reading fshift Removes specified number of bytes from file fwrite FS1 Writes to the end of a file fread FS1 Reads from the current file pointer fseek FS1 Moves the read pointer ftell FS1 Returns the current offset of the file pointer fclose Closes a file fdel
108. VAL is an offset from the frame refer ence point not from the current SP 128 Dynamic C User s Manual 11 6 Assembly Calling C 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 is described here 1 ON Oy n aa 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 val ues 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 reg ister HL for int unsigned int char and pointers or BCDE for long unsigned long and float ifit is of a primitive type Issue the call instruction The caller must unwind the stack after the function returns 1 2 3 Recover the stack storage allocated to arguments With no more than 6 bytes of arguments the program may pop data 2 bytes at time from the stack Otherwise it is more efficient to com pute a new SP instead The following code demonstrates how to unwind arguments tot
109. X board is that Dynamic C expects no BIOS kernel to be present on the target when it starts up Dynamic C stores the BIOS kernel as a C source file Dynamic C compiles and loads it to the Rabbit target when it starts This is accomplished using the Rabbit CPU s bootstrap mode and a special programming cable provided in all Rabbit product development kits This method has numerous advantages e A socketed flash is no longer needed BIOS updates can be made without a flash EPROM burner since Dynamic C can communicate with a target that has a blank flash EPROM Blank flash EPROM can be surface mounted onto boards reducing manufacturing costs for both Z World and other board developers BIOS updates can then be made available on the Web e Advanced users can see and modify the BIOS kernel directly e Board Developers can design Dynamic C compatible boards around the Rabbit CPU by simply following a few simple design guidelines and using a skeleton BIOS provided by Z World e A major new feature introduced in Dynamic C 7 x is the ability to program and debug over the Internet or local Ethernet This requires the use of a RabbitLink board available alone or as an option with Rabbit based development kits 6 Dynamic C User s Manual 3 Quick Tutorial Sample programs are provided in the Dynamic C Samples folder similar to the one shown below Open 2 Serial Slice E Sysclock E Tcpip Timerb E Vdriver Look in
110. _GLOBAL_INTIT for this purpose Your program can initialize variables and take initialization action with global initialization This is done by adding segments to the _GLOBAL_INIT function chain as shown in the example below Lome wy _itumMe Cina 3 main my_func 100 long my_func char j imne Lg iongmanrray 2 56 The GLOBAL_INTT section is automatically run once when the program starts up GLOBAL_INIT mene a OP a lt 100s ate Jy aiccay aj aap return array j only this code runs when the function is called The special directive GLOBAL_INIT _ tells the compiler to add the code in the block enclosed in braces to the GLOBAL INIT function chain The GLOBAL INIT function chain is always called when your program starts up so there is nothing special to do to invoke it It may be called at anytime in an application program but do this with caution When it is called all cos tatements and cofunctions will be initialized See Calling GLOBAL_INIT on page 65 for more information Any number of GLOBAL_INIT sections may be used in your code The order in which the GLOBAL_INIT sections are called is indeterminate since it depends on the order in which they were compiled Chapter 4 Language 35 4 21 Libraries Dynamic C includes many libraries files of useful functions in source code form They are located in the LIB subdirectory where Dynamic C was ins
111. acros _FLASH_or _RAM_ These two macros are defined by the compiler based on the currently selected radio button in the BIOS Memory Setting group box User Defined Lib Directory File The Library Lookup information retrieved with lt Ctrl H gt is parsed from the libraries found in the 1ib dir file which is part of the Dynamic C installation Checking the Use box for User Defined Libraries File allows the parsing of a user defined replacement for lib dir when Dynamic C starts Library files must be listed in 1ib dir or its replacement to be available to a program If the function description headers are formatted correctly See Function Description Head ers on page 40 the functions in the libraries listed in the user defined replacement for lib dir will be available with lt Ctrl H gt just like the user callable functions that come with Dynamic C This is the same as the command line compiler 1 f option 194 Dynamic C User s Manual Watch Expressions Allow any expressions in watch expressions This option causes any compilation of a user program to pull in all the utility functions used for expression evaluation Restricting watch expressions may save root code space Choosing this option means only utility code already used in the application program will be compiled Separate 1 amp D Space When checked this option enables separate instruction and data space doubling the amount of root code and root data space avai
112. aling 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 Sp ces ele Dl save HL if required el ail 3E want to pop 36 bytes add hl sp compute new SP value le soal put value back to SP Be e der IniL restore HL if required If the function returns a st ruct unload the returned structure Restore registers previously saved Pop them off if they were stored on the stack 4 Ifthe function return was not a st ruct obtain the returned value from HL or BCDE Chapter 11 Using Assembly Language 129 11 7 Interrupt Routines in Assembly Interrupt Service Routines ISRs may be written in Dynamic C declared with the keyword interrupt But since an assembly routine may be more efficient than the equivalent C func tion assembly is more suitable for an ISR Even if the execution time of an ISR is not critical the latency of one ISR may affect the latency of other ISRs Either stand alone assembly code or embedded assembly code may be used for ISRs The benefit of embedding assembly code in a C language ISR 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 stand alone assembly routine needs to save and restore only the registers it uses 11 7 1 Steps Followed by an ISR The CPU loads the IP register with
113. am There are certain loop optimizations that are not gen erated when code is compiled as debug This option also controls the definition of a compiler defined macro symbol DEBUG_RST If the menu item is checked then DEBUG_RST is set to 1 otherwise it is 0 If the option is not checked the compiler marks all code as nodebug and debugging is not possible The only reason to check this option if debugging is finished and the program is ready to be deployed is to allow some current or planned diagnostic capability of the Rabbit Field Utility RFU to work in a deployed system This option effects both code compiled to bin files and code compiled to the target In order to run the program after compiling to the target with this option disconnect the target from the programming port and reset the target CPU 14 2 4 Run Menu Click the menu title or press lt Alt R gt to select the RUN menu Inspect Options Window H Bun F9 Stop Etrit Run w No Polling Alt F9 Trace into F7 Step over F8 Source Trace into Alt F Source Step over Alt F8 Toggle Breakpoint F2 Toggle Hard Breakpoint Alt F2 Clear All Breakpoints Ctrl A4 Toggle Interrupt Flag Ctrl 1 v Pall Target Ctr 0 Reset Program Ctrl F2 Close Serial Port Run Starts program execution from the current breakpoint Registers are restored including inter rupt status before execution begins The keyboard shortcut is F9 Run w No Polling This command is identi
114. amples SlavePort Slave_Demo c runs ona slave and implements a byte stream over the slave port class auto use Slave_port lib use sp_stream lib define STREAM BUFFER_SIZE 31 main char buffer 10 int bytes_read SPStream stream Circular buffers need 9 bytes for bookkeeping char stream_inbuf STREAM _BUFFER_SIZE 9 char stream_outbuf STREAM _BUFFER_SIZE 9 SPStream stream_ptr setup buffers cbhuf_init stream_inbuf STREAM _BUFFER_SIZE stream inbuf stream_inbuf cbuf_init stream_outbuf STREAM_BUFFER_SIZE stream outbuf stream_outbuf stream_ptr amp stream SPinit 1 SPsetHandler 0x42 SPShandler stream_ptr while l1 bytes_read SPSread stream_ptr buffer 10 10 if bytes_read SPSwrite stream_ptr buffer bytes_read 90 Dynamic C User s Manual 8 Run Time Errors Compiled code generated by Dynamic C calls an exception handling routine for run time errors The exception handler supplied with Dynamic C prints internally defined error messages to a Win dows message box when run time errors are detected during a debugging session When software runs stand alone disconnected from Dynamic C such a run time error will cause a watchdog timeout and reset Starting with Dynamic C 7 05 run time error logging is available for Rabbit based target systems with battery backed RAM 8 1 Run Time Error Handling When a run time
115. an one statement in the loop body while expression some statement s A do loop tests a condition at the end of the loop As long as expression is true non zero the loop body some statement s will execute A do loop executes at least once before its test Unlike other controls the do loop requires a semicolon at the end do some statements while expression The for loop is more complex it sets an initial condition exp evaluates a terminating condi tion exp2 and provides a stepping expression exp3 that is evaluated at the end of each iteration Each of the three expressions is optional for expl exp2 exp3 some statements If the end condition is initially false a for loop body will not execute at all A typical use of the for loop is to count n times sum 0 ror r Of r lt mp ade 4 sum sum array ii This loop initially sets i to 0 continues as long as i is less than n stops when i equals n and increments i at each pass Another use for the for loop is the infinite loop which is useful in control systems for some statement s 30 Dynamic C User s Manual Here there is no initial condition no end condition and no stepping expression The loop body some statement s continues to execute endlessly An endless loop can also be achieved with a while loop This method is slightly less efficient than the for loop while 1 some statement s 4 18 2 C
116. and FS2 The third parameter wearlevel should be 1 for a new flash memory otherwise it should be 0 to use the current wear leveling The fsck function is not available and is not needed in FS2 fs_init always completely checks for internal consistency Refer to Samples FileSystem FS2DEMO1 C for more details 10 3 2 2 FS2 API Error Codes When an API function returns an error it may also return an error code in the global variable errno The error codes are defined in the library file ERRNO LIB 10 4 Setting up and Partitioning the File System FS2 can be more complex to initialize than FS1 This is because multiple device types can be used in the same application For example if the target board contains both battery backed SRAM and a second flash chip then both types of storage may be used for their respective advantages The SRAM might be used for a small application configuration file that changes frequently and the flash used for a large log file FS2 automatically detects the second flash device if any and will also use any SRAM set aside for the file system if FS2_RAM_RESERVE is set 10 4 1 Initial Formatting The filesystem must be formatted when it is first used The only exception is when a flash memory device is known to be completely erased which is the normal condition on receipt from the fac tory If the device contains random data then formatting is required to avoid the possibility of some sectors being
117. and any other proprietary legends that appear on or in the original copy of the Software Except for the limited license granted above Z WORLD retains all right title and interest in and to all intellectual property rights embodied in the Software including but not limited to patents copyrights and trade secrets 4 Export Law Assurances You agree and certify that neither the Software nor any other techni cal data received from Z WORLD nor the direct product thereof will be exported outside the United States or re exported except as authorized and as permitted by the laws and regulations of the United States and or the laws and regulations of the jurisdiction if other than the United States in which You rightfully obtained the Software The Software may not be exported to any of the following countries Cuba Iran Iraq Libya North Korea Sudan or Syria 5 Government End Users If You are acquiring the Software on behalf of any unit or agency of the United States Government the following provisions apply The Government agrees i if the Software is supplied to the Department of Defense DOD the Software is classified as Commercial Computer Software and the Government is acquiring only restricted rights in the Software and its documentation as that term is defined in Clause 252 227 7013 c 1 of the DFARS and ii if the Software is supplied to any unit or agency of the United States Govern ment other than DOD the Government s
118. andomNumberTask void pdata Declare semaphore global so all tasks have access OS_EVENT RandomSem void main ab ghee Initialize OS internals OSInit for i 0 i lt OS_MAX TASKS itt Create each of the system tasks OSTaskCreate RandomNumberTask NULL 1024 i semaphore to control access to random number generator RandomSem OSSemCreate 1 4 Set number of system ticks per second OSSetTicksPerSec OS_TICKS_PER_SEC Begin multi tasking OSStart 252 Dynamic C User s Manual void RandomNumberTask void pdata Declare as auto to ensure reentrancy auto OS_TCB data auto INT8U err auto INT16U RNum OSTaskQuery OS_PRIO_SELF amp data j while 1 Rand is not reentrant so access must be controlled via a semaphore OSSemPend RandomSem 0 amp err RNum int rand 100 OSSemPost RandomSem printf Task 02d s random d n data OSTCBPrio RNum Wait 3 seconds in order to view output from each task OSTimeDlySec 3 18 5 Compatibility with TCP IP The TCP IP stack is reentrant and may be used with the uC OS real time kernel The line use ucos2 lib must appear before the line use dcrtcp lib A call to OSInit must be made before calling sock_init 18 5 1 Socket Locks Each socket used in a uC OS II application program has an associated socket lock Each socket lock uses one semaphore of type OS_EVENT Therefore th
119. ans of accessing stack based variables works whether a function is compiled to extended memory or not as long as the C lan guage 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 off set approach discussed previously can be used because the compiler maintains the offsets automat ically 11 5 C Calling Assembly Dynamic C does not assume that registers are preserved in function calls In other words the func tion being called need not save and restore registers 11 5 1 Passing Parameters When a program calls a function from C it puts the first argument into HL if it has one or two bytes with register H containing the most significant byte If the first argument has four bytes it goes in BC DE with register B containing the most significant byte Only the first argument is put into the primary register while all arguments including the first pushed last are pushed on the stack 11 5 2 Location of Return Results If a C callable assembly function is expected to return a result of primitive type the function must pass the result in the primary register If the result is an int unsigned int char or a pointer return the result in HL register H contains the most significant byte If the result is a long unsigned long or float return th
120. anual Although this may be sufficient for most purposes the Insert Call button can be clicked to invoke a function assistant This is only useful if the Function Lookup Insert dialog box was displayed in response to selecting a function in source code Otherwise the function assistant will only restate the function description information Function Lookap Ainge Bronse OK Cancel Helo ine OV nw Function Danera inant Cal atecmp STRING LIBS SYNTAX int stecrgjchasr atel char ste2 DESCRIPTION Pecform unsigned charecter by character comparison of ten nall terminated strings TARAHETEFLI Pointer ta string 1 PARAMETER 3 Pointer Eo ering 2 RETURN VALUE lt 0 if stri as less than str Pointer bo string 1 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 if OK is clicked the call needs to be edited for it to make sense in the context of the code 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
121. asic handlers are available in the library Slave_Port 1ib These handlers will be discussed later in this chapter When the slave port driver is initialized a callback table of handler functions is set up Handler functions are added to the callback table by SPsetHandler 7 2 Functions Slave_port 1ib provides the following functions int SPinit int mode DESCRIPTION This function initializes the slave port driver It sets up the callback tables for the different channels The slave port driver can be run in either polling mode where SPt ick must be called periodically or in interrupt mode where an ISR is triggered every time the mas ter sends a command There are two version of interrupt mode In the first interrupts are reenabled while the handler function is executing In the other the handler function will execute at the same interrupt priority as the driver ISR PARAMETERS mode 0 For polling 1 For interrupt driven interruptible handler functions 2 For interrupt driven non interruptible handler functions RETURN VALUE 1 Success 0 Failure LIBRARY SLAVE_PORT LIB Chapter 7 The Slave Port Driver 71 int SPsetHandler char address int handler void handler_params DESCRIPTION This function sets up a handler function to process incoming commands from the master for a particular slave port address PARAMETERS address The 8 bit slave port address of the channel that corresponds to the
122. ata structure corrupted 244 Virtual watchdog timeout 245 XMEM allocation failed xalloc call 246 Stack allocation failed 247 Stack deallocation failed 248 not used 249 Xmem allocation initialization failed 250 No virtual watchdog timers available 251 No valid MAC address for board 252 Invalid cofunction instance 253 Socket passed as auto variable while running wC OS I 254 not used 255 92 Dynamic C User s Manual 8 2 User Defined Error Handler Dynamic C allows replacement of the default error handler with a custom error handler This is needed to add run time error handling that would require treatment not supported by the default handler A custom error handler can also be used to change how existing run time errors are handled For example the floating point math libraries included with Dynamic C are written to allow for execu tion to continue after a domain or range error but the default error handler halts with a run time error if that state occurs If continued execution is desired the function in question would return a value of INF or whatever value is appropriate then a simple error handler could be written to pass execution back to the program when a domain or range error occurs and pass any other run time errors to Dynamic C 8 2 1 Replacing the Default Handler To tell the BIOS to use a custom error handler call this function void defineErrorHandler void errfcn This function sets the BIOS function p
123. ated automatically in the Dynamic C exe path The factory project can be opened at any time and the environment changed and saved to another project name but factory dcp will not be changed by Dynamic C 16 1 2 Default dcp This default project file is originally a copy of factory dcp and will be automatically recre ated as such in the exe path if it cannot be found when Dynamic C opens The default project will automatically become the active project with File Project Close The default project is special in that the command line compiler will use it for default values unless another project file is specified with the pf switch in which case the settings from the indi cated project will be used Please see chapter 15 Command Line Interface starting on page 209 for more details on using the command line compiler 16 1 3 Active Project Whenever a project is selected the current project related data is saved to the closing project file the new project settings become active and the possibly new BIOS will automatically be recom piled prior to compiling a source file in the new environment The active project can be factory dcp default dcp or any project you create with File Project Save As When Dynamic C opens it retrieves the last used project or the default project if being opened for the first time or if the last used project cannot be found If a project is closed with the File Projects Close men
124. atenation ssseseeeseeeeee 20 aN SOR ONE E Firsttime Functions ccccee 53 Character Constants ceecee 21 Types of Cofunctions e 54 4 8 Statements eneeeeeeseeesseeeeseeseeeessseessee 21 Types of Cofunction Calls 55 4 9 Declarations ccccccecessecesseeeeeteeees 22 i Special Code Blocks eee 56 4 10 FUNCtiONS cccecceceeseceeeeecesteeeesseeees 22 Solving the Real Time Problem 4 11 Prototypes cece ceeeeeceeeeeeeeeeeee 23 es with Cofunctions ccceeeeeees 57 4 12 Type Definitions eeeeeeeeeeees 23 5 6 Patterns of Cooperative Multitasking 57 4 13 Aggregate Data Types 25 oe 5 7 Timing Considerations 0 0 0 ce 58 Aray octave e ar E R o a 25 gots Strictirie 25 waitfor Accuracy Limits 59 UCTUTE ssssssssststt steret tst arststt eteten aete Bg Overview of Precmptive Multitasking59 UMOM ge eeen e e e 26 5 9 Slice Statement ccc cceeeeeeeteees 59 Composites ee eeeeeeeeeeeeeeeeeees 26 Snes 59 4 14 Storage Classes eee ceeeseeeseeeeees 26 ni T A a E LOE ra E tants eee seantgeveee ets 60 4 15 POInters oinin i ea 27 Restrictions 60 4 16 Pointers to Functions Indirect Calls 28 E ing amet EAN E OG EA Slice Data Structure cceee 6l 4 17 Argument Passing 0 0 eee eee 29 Slice Internals 61 4 18 Program FLOW 00 eee eee eeeeteeeeeees 30 BTN Spre
125. atency Just like a standard ISR the first thing a TA ISR does is to save the registers that it is going to use 1 Once the registers are saved the interrupt source is cleared 2 and the nesting counter is incremented 3 Note that bios_intnesting is a global interrupt nesting counter provided in the Dynamic C libraries specifically for tracking the interrupt nesting level If an ipres instruc tion is executed 4 other interrupts can occur before this ISR is completed making it necessary for this ISR to be a TA ISR If it is possible for the ISR to execute before uC OS II has been fully initialized and started multi tasking a check should be made 5 to insure that uC OS II is in a known state especially if the TA ISR signals a task to the ready state 6 After the TA ISR has done its necessary work which may include making a higher priority task than is currently run ning ready to run OSIntExit must be called 7 This wC OS II function determines the high est priority task ready to run sets it as the currently running task and sets the global flag bios_swpend if a context switch needs to take place Interrupts are disabled since a context switch is treated as a critical section 8 If the TA ISR decrements the nesting counter and the count does not go to zero then the nesting level is saved in bios_intnesting 9 the regis ters used by the TA ISR are restored interrupts are re enabled if not already done in 4 and the TA ISR ret
126. ave and gets a response This function also serves as a general example of how to implement the master side of the slave protocol PARAMETERS address Slave channel address to send command to command Command to be sent to the slave see Section 7 3 2 1 data Data byte to be sent to the slave data_returned Address of variable to place data returned by the slave timeout Time to wait before giving up on slave response RETURN VALUE 20 Response code 1 Timeout occured before response 2 Nothing at that address response Oxff LIBRARY MASTER_SERIAL LIB Chapter 7 The Slave Port Driver 81 int MSread char address char buffer int size unsigned long timeout DESCRIPTION Receives bytes from the serial port on the slave PARAMETERS address Slave channel address of serial handler buffer Array to put received data into size Size of array max bytes to be read timeout Time to wait between characters before giving up on receiving any more RETURN VALUE The number of bytes read into the buffer behaves like serXread LIBRARY MASTER_SERIAL LIB int MSwrFree char address DESCRIPTION Gets the number of bytes available in the specified serial port write buffer on the slave PARAMETERS address Slave channel address of serial handler RETURN VALUE Number of bytes free Success 1 Failure LIBRARY MASTER_SERIAL LIB 82 Dynamic C User s Manual int MSwrite char address cha
127. bbit version of uC OS II includes the new features and API changes available in version 2 51 of uC OS II The documentation for these changes is included with Dynamic C in Samples UCos IlI The file Newv251 pdf contains all of the features added since version 2 00 and Relv251 pdf contains release notes for version 2 51 18 1 Changes to pC OS II To take full advantage of services provided by Dynamic C minor changes have been made to uC OS II 18 1 1 Ticks per Second In most implementations of uC OS II OS_TICKS_PER_SEC informs the operating system of the rate at which OSTimeTick is called this macro is used as a constant to match the rate of the periodic interrupt In uC OS II for the Rabbit however changing this macro will change the tick rate of the operating system set up during OSInit Usually a real time operating system has a tick rate of 10 Hz to 100 Hz or 10 100 ticks per second Since the periodic interrupt on the Rabbit occurs at a rate of 2 kHz it is recommended that the tick rate be a power of 2 e g 16 32 or 64 Keep in mind that the higher the tick rate the more overhead the system will incur In the Rabbit version of uC OS II the number of ticks per second defaults to 64 The actual num ber of ticks per second may be slightly different than the desired ticks per second if TicksPerSec does not evenly divide 2048 Changing the default tick rate is done by simply defining OS_TICKS_PER_SEC to the desired tick rate before
128. ble the feature This is the same window that is displayed when Dynamic C initializes About The About command displays the Dynamic C version number and the copyright notice 208 Dynamic C User s Manual 15 Command Line Interface The Dynamic C command line compiler dccl_cmp exe performs the same compilation and program execution as its GUI counterpart dcrabxx exe but is invoked as a console applica tion from a DOS window It is called with a single source file program pathname as the first parameter followed by optional case insensitive switches that alter the default conditions under which the program is run The results of the compilation and execution all errors warnings and program output are directed to the console window and are optionally written or appended to a text file 15 1 Default States With versions of Dynamic C prior to 7 10 the default states of Dynamic C environment variables are used each time dccl_cmp is called If a sequence of calls is written into a batch file varia tions from the defaults must be repeated for each call For instance if a change is made to the serial parameters dccl_cmp myProgram c s 2 115200 1 0 the next call will revert to the default settings of 1 115200 1 0 unless the switch is used with that next call as well Starting with Dynamic C v 7 10 the command line compiler uses the values of the environment variables that are in the project file indicated by the pf switch or i
129. c C 7 i0D5 Edit Compile Run Inspect Options New Open Saye Ctl S Save As Close Open Saye Save As Close Print Preview Print Print Setup Exit Alt F4 180 Dynamic C User s Manual 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 To select a file type in the desired file name or select one from the list The file s directory may also be specified Save The Save command updates an open file to reflect the latest changes If the file has not been saved before that is the file is a new untitled file the Save As dialog will appear Use the Save command often while editing to protect against loss during power failures or system crashes Save As Allows a new name to be entered for a file and saves the file under the new name Close Closes the active window The active window may also be closed by pressing lt Ctrl F4 gt or by double clicking on its system menu If there is an attempt to close a file before it has been saved Dynamic C will present a dialog similar to one of these two dialogs The file is saved when Yes or type y is clicked If the file is untitled there will be a prompt for a file name in the Save As dialog Any changes to the docum
130. c constant defined Declare global integers Prototypes for functions below Program starts here x islocaltomain Calla void function x gets sumSquare value printf isa standard function Noid functions do things but a they return no value Here it uses the symbolic constant defined above Integer arguments Local variables Arithmetic statement Return value The program above 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 formatting string as the first argument 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 explained this 24 Dynamic C User s Manual 4 13 Aggregate Data Types Simple data types can be grouped into more complex aggregate forms 4 13 1 Array A data type whether it is simple or complex can be replicated in an array The declaration ine Ween 10 An array of 10 integers represents a contiguous group of 10 intege
131. cal 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 ms to obtain or send information about target breakpoints watch lines keyboard entered target input and target output from printf statements Polling creates interrupt overhead in the 186 Dynamic C User s Manual target which can be undesirable in programs with tight loops The Run w No Polling com mand allows the program to run without polling and its overhead Any printf 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 lt Alt F9 gt Stop The Stop command places a hard breakpoint at the point of current program execution Usu ally 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 inline assembly code in nodebug code However the debugger will never be able to find and place the execution cursor in nodebug code The keyboard shortcut is lt Ctrl Z gt 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 initialization may not be reset Th
132. ces of a few milliseconds each and by the uC OS II real time kernel 5 1 Cooperative Multitasking In the absence of a preemptive multitasking kernel or operating system a programmer given a real time programming problem that involves running separate tasks on different time scales will often come up with a solution that can be described as a big loop driving state machines y Top of loop y State machine State machine State machine Figure 1 Big Loop Chapter 5 Multitasking with Dynamic C 43 This means that the program consists of a large endless loop a big loop Within the loop tasks are accomplished by small fragments of a program that cycle through a series of states The state is typically encoded as numerical values in C variables State machines can become quite complicated involving a large number of state variables and a large number of states The advantage of the state machine is that it avoids busy waiting which is waiting in a loop until a condition is satisfied In this way one big loop can service a large number of state machines each performing its own task and no one is busy waiting The cooperative multitasking language extensions added to Dynamic C use the big loop and state machine concept but C code is used to implement the state machine rather than C variables The state of a task is remembered by a statement pointer that reco
133. cicttart nates 15 3 Saving Output to a File 15 4 Command Line Switches 15 5 Examplesine oc ose nt iat head Example T yccsdccvectisscseveceteceecegevessess Example 2 ccccsssssssssseseeesssvees Example rraren onenn aA 175 16 Project Files oo ceeeeeeeeeeeeeee 227 16 1 Project File Names eee 227 Active Project ceeceeeeeeseceeeeeeeee 227 16 2 Updating a Project File 228 16 3 Menu Selections 0 0 0 228 16 4 Command Line Usage 229 17 Hints and Tips ee eeeeeeeseeeeeeeees 231 17 1 EM Clency o nn ei cee testes 231 Nodebug Keyword ee 231 Static Variables eee 232 17 2 Run time Storage of Data 0 232 User Block ienesis 233 Flash File System 233 WriteFlash2 oe eee certs 233 Battery Backed RAM 233 17 3 Root Memory Reduction Tips 234 Increasing Root Code Space 234 Increasing Root Data Space 236 Bu E E E esac ta 239 18 1 Changes to UC OS IL ee 239 Ticks per Second eee 239 Task Creation eee eeeeeeeeeees 240 ReStrictiOns eee eees ieoi 241 18 2 Tasking Aware Interrupt Service Routines TA ISR eeseeeeseeeees 241 Interrupt Priority Levels 241 Possible ISR Scenarios 242 General Layout of a TA ISR 243 18 3 Library Reentrancy eee 247 18 4 How to Get a uwC OS II Application RUNNING speres penis 248 Default Configuration
134. cond The costatement executes each pass through the while loop When a wait for condition is encountered the first time the cur rent value of MS_ TIMER is saved and then on each subsequent pass the saved value is compared to the current value If a wait for condition is not encountered then a jump is made to the end of the costatement 4 and on the next pass of the loop when the execution thread reaches the begin ning of the costatement execution passes directly to the wait for statement Once 1000 ms has passed the statement after the wait for is executed A costatement can wait for a long period of time but not use a lot of execution time Each costatement is a little program with its own state ment pointer that advances in response to conditions On each pass through the while loop as few as one statement in the costatement executes starting at the current position of the costate ment s statement pointer Consult Chapter 5 Multitasking with Dynamic C for more details The second costatement in the program checks to see if a key has been pressed and if one has prints out that key The abort statement is illustrated at 5 If the abort statement is exe cuted the internal statement pointer is set back to the first statement in the costatement and a jump is made to the closing brace of the costatement To illustrate the use of snooping use the watch window to observe secs while the program is running Add the variable secs to t
135. 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 de fine direc tive A macro definition remains in effect unless removed by an undef directive If an attempt is made to redefine a macro without using undef a warning will appear and the original defini tion will remain in effect 4 6 Numbers Numbers are constant values and are formed from digits possibly a decimal point and possibly the letters 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 Integers have several forms of representation The normal decimal form is the 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 32 15 45000 32767L 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 0U 4294967294U 32767U 1700UL An integer is hexadecimal if preceded by 0x Ox7E 0xE000 OxFFFFFFFA It may contain digits and the letters a f 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 4f means 4 0 0 3125 means 0 3125 456e 3
136. 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 st ruct 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 Chapter 4 Language 29 4 18 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 is 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 4 18 1 Loops A while loop tests a condition at the start of the loop As long as expression is true non zero the loop body some statement s will execute If expression is initially false zero the loop body will not execute The curly braces are necessary if there is more th
137. ction e The function saves IX on the stack and makes IX the stack frame reference pointer if the program is in the useix mode e The function creates stack space for auto variables e The function sets up stack corruption checks if stack checking is enabled on e The program notifies Dynamic C of the entry to the function so that single stepping modes can be resolved if in debug mode The last two consume significant execution time and are eliminated when stack checking is dis abled or if the debug mode is off 17 1 1 Nodebug Keyword When the PC is connected to a target controller with Dynamic C running the normal code and debugging features are enabled Dynamic C places an RST 28H instruction at the beginning of each C statement to provide locations for breakpoints This allows the programmer to single step through the program or to set breakpoints It is possible to single step through assembly code at any time During debugging there is additional overhead for entry and exit bookkeeping and for checking array bounds stack corruption and pointer stores These jumps to the debugger con sume one byte of code space and also require execution time for each statement At some point the Dynamic C program will be debugged and can run on the target controller without the Dynamic C debugger This saves on overhead when the program is executing The nodebug keyword is used in the function declaration to remove the extra debugging
138. ction is exited which includes an exit via an incomplete wait fordone statement In the case of an application that uses the useix directive the IX register will be corrupted when any stack variable using function is called from within a cofunction or if a stack variable using function contains a call to a cofunction 5 5 3 CoData Structure The CoData structure discussed in Section 5 4 1 applies to cofunctions each cofunction has an associated CoData structure 5 5 4 Firsttime Functions The firsttime functions discussed in Firsttime Functions on page 51 can also be used inside cofunctions They should be called inside a wait for statement If you call these functions from inside a wfd statement no compiler error is generated but since these delay functions do not yield while waiting for the desired time to elapse but instead return 0 to indicate that the desired time has not yet elapsed the wfd statement will consider a return value to be completion of the firsttime function and control will pass to the statement following the wfd Chapter 5 Multitasking with Dynamic C 53 5 5 5 Types of Cofunctions There are three types of cofunctions simple indexed and single user Which one to use depends on the problem that is being solved A single user indexed cofunction is not valid 5 5 5 1 Simple Cofunction A simple cofunction has only one instance and is similar to a regular function with a costate taking up most of the functi
139. d GUI Equivalent Uncheck the Options Compiler Array Indices menu option ri Available starting with Dynamic C v 7 10 Description Enable runtime checking of array indices Default Runtime checking of array indices is performed GUI Equivalent Check the Options Compiler Array Indices menu option ri Available starting with Dynamic C v 7 10 Description Disable runtime checking of array indices Default Runtime checking of array indices is performed GUI Equivalent Uncheck the Options Compiler Array Indices menu option rp Description Disable runtime checking of pointers This switch is available only in Dynamic C v 7 05 and 7 06 Default Runtime checking of pointers is performed GUI Equivalent Uncheck the Options Compiler Pointers menu option 214 Dynamic C User s Manual rp Available starting with Dynamic C v 7 10 Description Enable runtime checking of pointers Default Runtime checking of pointers is performed GUI Equivalent Uncheck the Options Compiler Pointers menu option rp Available starting with Dynamic C v 7 10 Description Disable runtime checking of pointers Default Runtime checking of pointers is performed GUI Equivalent Uncheck the Options Compiler Pointers menu option rW Description Restrict watch expressions may save root code space This switch is available only in Dynamic C v 7 05 and 7 06 Default Allow any expressions in watch exp
140. d or unnamed If name is absent the compiler creates an unnamed structure of type CoData for the costatement state can be one of the following e always_on The costatement is always active This means the costatement will execute every time it is encountered in the execution thread unless it is made inactive by CoPause It may be made active again by CoResume e init_on The costatement is initially active and will automatically execute the first time it is encountered in the execution thread The costatement becomes inactive after it completes or aborts The costatement can be made inactive by CoPause If state is absent a named costatement is initialized in a paused init_on condition This means that the costatement will not execute until CoBegin or CoResume is executed It will then execute once and become inactive again Unnamed costatements are always_on You cannot specify init_on without specifying name Chapter 5 Multitasking with Dynamic C 47 5 3 3 Control Statements waitfor expression The keyword wait for indicates a special wait for statement and not a function call The expression is computed each time wait for is executed If true non zero execution pro ceeds to the next statement otherwise a jump is made to the closing brace of the costatement or cofunction with the statement pointer continuing to point to the wait for statement Any valid C function that returns a value can be used
141. d the IIR point to the same location The code above is an example only the default configration for the periodic interrupt is not modifiable 132 Dynamic C User s Manual The following example from RS232 LIB illustrates the new I amp D space compatible way of mod ifying interrupt vectors The following function serAclose from Dynamic C 7 25 is not compatible with separate I amp D space asm xmem serAclose ld a iir ld h a ld 1 0xcO ld a 0xc9 ipset 1 ld hl a ld a 0x00 ld SACRShadow a ioi ld SACR a ipres lret endasm hl spaisr_start de iir Oxe0 vet in first byte disable interrupts for port This version of serAclose in Dynamic C 7 30 is compatible with separate I amp D space asm xmem serAclose ld a Oxc9 ipset 1 ld a 0x00 ld SACRShadow a ioi ld SACR a ipres lret endasm ld INTVEC_BASE SERA_OFS a ret in first byte of spaisr_start disable interrupts for port Chapter 11 Using Assembly Language 133 If separate I amp D space is enabled using the modifiable interrupt vector proxy in RAM adds about 80 clock cycles of overhead to the execution time of the ISR To avoid that the preferred way to set up interrupt vectors is to use the new keyword interrupt_vector to set up the vector location at compile time When compiling with separate amp D space modify applications that use Set Vect Intern SetVectExtern2000 o
142. debugging 16 3 Menu Selections The menu selections for project files are available in the File menu The choices are the familiar ones Open Save Save As and Close Choosing File Project Open will bring up a dialog box to select an existing project filename to become the active project The environment of the previous project is saved to its project file before it is replaced unless the previous project is factory dcp The BIOS will automatically be recompiled prior to the compilation of a source file within the new environment which may have a different library directory file and or a different BIOS file Choosing File Project Save will save the state of the environment to the active project file including the state of the recently used filelist and any files open in edit windows This selection is greyed out if the active project is factory dcp This option is of limited use since any project changes will be updated immediately to the file and the state of the recently used filelist and open edit windows will be updated when the project is closed for any reason Choosing File Project Save as will bring up a dialog box to select a project file name The file will be created or if it exists it will be overwritten with the current environment settings This environment will also be saved to the active project file before it is closed and its copy the newly created or overwritten project file will become activ
143. duce hexadecimal memory dumps The INSPECT menu commands and their func tions are described here Add Del Watch Expression This command provokes Dynamic C to display the following dialog Watch Expressions EI p Add to top Del fom top Close ELE 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 eval uated and the results are displayed in the Watch window every time the Watch window is updated Items are deleted from the expression list by clicking the Del from top button Chapter 14 Graphical User Interface 189 An example of the results displayed in the Watch window appears below Watch iof x PC 1a12 dy int 52243 6xCC13 x1 int 1 6x6661 xh int 6265 6x183D L 23 C 4 dy int 52243 0xCC13 x1 int 1 6x66601 Bh int 6265 6x183D Clear Watch Window Removes entries from the Watch dialog and removes report text from the Watch window There is no keyboard shortcut Update Watch Window Forces expressions in the Watch Expression list to be evaluated and displayed in the Watch window only when the function runwatch is called from the application program run watch monitors f
144. e Choosing File Project Close first saves the environment to the active project file unless the active project is factory dcp and then loads the Dynamic C default project default dcp as the active project As with Open the BIOS will automatically be recompiled prior to the compilation of a source file within the new environment The new environment may have a differ ent library directory file and or a different BIOS file 228 Dynamic C User s Manual 16 4 Command Line Usage When using the command line compiler dccl_cmp exe a project file is always read The default project default dcp is used automatically unless the project file switch pf specifies another project file to use The project settings are read by the command line compiler first even if a pf switch comes after the use of other switches and then all other switches used in the com mand line are read which may modify any of the settings specified by the project file The default behavior given for each switch in the command line documentation is with reference to the factory dcp settings so the user must be aware of the default state the command line compiler will actually use The settings of default dcp can be shown by entering dccl_cmp alone on the command line The defaults for any other project file can be shown by following dccl_cmp by a the project file switch without a source file dccl_cmp shows the current state of all default dcp setti
145. e 20 bit physical addresses The name of the table represents the 20 bit physical address of the table this address is assigned to name by the compiler xstring name string_1 a a string_n j Chapter 12 Keywords 157 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 post pones it for costate yield 158 Dynamic C User s Manual 12 1 Compiler Directives Compiler 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 Syntax asm options Begins a block of assembly code The available options are e debug Enables debug code during assembly e nodebug Disables debug code during assembly This is the default condition It is still possible to single step through assembly code as long as the assembly win dow is open e xmem Places a block of code in extended memory overriding any previous mem ory directives The block is limited to 4KB If the asm block is unmarked it will be compiled to root Syntax class options Controls the storage class for local variables The available options are e auto Place local variables on the stack e static Place local variables in permanent
146. e Sl 9 turnoffdevice2 break other tasks or state machines Chapter 5 Multitasking with Dynamic C 45 If there are other tasks to be run this control problem can be solved better by creating a loop that processes a number of tasks Now each task can relinquish control when it is waiting thereby allowing other tasks to proceed Each task then does its work in the idle time of the other tasks 5 3 Costatements Costatements are Dynamic C extensions to the C language which simplify implementation of state machines Costatements are cooperative because their execution can be voluntarily suspended and later resumed The body of a costatement is an ordered list of operations to perform a task Each costatement has its own statement pointer to keep track of which item on the list will be performed when the costatement is given a chance to run As part of the startup initialization the pointer is set to point to the first statement of the costatement The statement pointer is effectively a state variable for the costatement or cofunction It specifies the statement where execution is to begin when the program execution thread hits the start of the costatement All costatements in the program except those that use pointers as their names are initialized when the function chain __GLOBAL_INIT is called _GLOBAL_INIT is called automatically by pre main before main is called Calling _GLOBAL_INIT from an applicat
147. e a more specific reason for the failure The possible errno codes returned from each function are documented with the function Chapter 10 The Flash File System 113 114 Dynamic C User s Manual 11 Using Assembly Language This chapter gives the rules for mixing assembly language with Dynamic C code A reference guide to the Rabbit Instruction Set is available from the Help menu of Dynamic C and is also doc umented in the Rabbit 2000 3000 Microprocessor Instruction Reference Manual 11 1 Mixing Assembly and C Dynamic C permits assembly language statements to be embedded in C functions and or entire functions to be written in assembly language C statements may also be embedded in assembly code C language variables may be accessed by the assembly code 11 1 1 Embedded Assembly Syntax Use the asm and endasm directives to place assembly code in Dynamic C programs For example the following function will add two 64 bit numbers together 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 WoOicl EGieincackl Cee cli Claakw Celaz asm ld AL Sfosrela 2 get source pointer ex de hl Save in register DE ld heo peny get destination pointer ld D6 number of bytes xor a clear carry HOODS ld a de ch2 source byte ace i Gal add ch1 byte ld Ual pe store result to ch1 address Sar eanl increment ch1 pointer inc
148. e aby ecisee hss aera esse tet 63 EGOpS s Ae E cies E 30 i E Rice cee Continue and Break cse 31 Dynamic C User s Manual iii 6 The Virtual Driver eee 65 6 1 Default Operation ee 65 6 2 Calling GLOBAL_INITO 0 00 65 6 3 Global Timer Variables 000 0 66 6 4 Watchdog Timers 00 eens 67 Hardware Watchdog cee 67 Virtual Watchdogs 0 0 eee 67 6 5 Preemptive Multitasking Drivers 67 7 The Slave Port Driver eee 69 7 1 Slave Port Driver Protocol 69 OVEIVIEW piesei edict eseencsiesiens 69 Registers on the Slave 0 0 69 Polling and Interrupts 0 71 Communication Channels 71 7 2 FUNCIONS ishon siete cots hisieclancs 71 T3 EXamMples ss isisclatiunch ieee 74 Status Handler eee 74 Serial Port Handler 75 Byte Stream Handler ee 85 8 Run Time Errors eeeeeeeeeeeeees 91 8 1 Run Time Error Handling 52 91 Error Code Ranges n se 91 Fatal Error Codes cece 92 8 2 User Defined Error Handlert 93 Replacing the Default Handler 93 8 3 Run Time Error Logging 94 Error Log Buffer eee 94 Initialization and Defaults 95 Configuration Macros 95 Error Logging Functions 96 Examples of Error Log Use 96 9 Memory Management 97 9 1 Memory Map eee ceeceseeeeeeeees 97 Memory Mapping Control 98
149. e address of a variable LIE JOE Ie AES ALP HIE aL per tonm gi set pointer equal to the address of i i 10 assign a value to i Soci Ac _alp this sets j equaltothe value in i In this example the variable pt r_to_i is a pointer to an integer The statement j ptr_to_i references the value of the integer by the use of the asterisk Using correct pointer terminology the statement dereferences the pointer pt r_to_i Then ptr_to_i and i have identical values Note that pt r_to_i and i do not have the same values because pt r_t o_i is a pointer and i is an int Note also that has two meanings not counting its use as a multiplier in others contexts in a variable declaration such as int ptr_to_ij the means that the variable will be a pointer type and in an executable statement j ptr_to_i means the value stored at the address contained in pt r_to_i Pointers may point to other pointers ILE JOLIE LO TA LIME OIE IS IO joie iO is int i je pern ICO iF Set pointer equal to the address of i ptr_to_ptr_to_i amp ptr_to_i Seta pointer to the pointer tothe address of i iL 10g Assign a value to i NMOS IE IFO foe ie _IEO_a 7 This sets j equal tothe value in i It is possible to do pointer arithmetic but this is slightly different from ordinary integer arithmetic Here are some examples tloac TOn BP SR anarray and some ptrs Boa by point p to array element 0 G boy
150. e and structure of a stack frame should be understood before writing embedded assem bly code 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 for a particular function If the IX register is used for a frame reference pointer the previous value of IX is also kept in the stack frame The fol lowing figure shows the general appearance of a stack frame Stack Frame Last Auto Variable Optional Frame Reference Point Optional Return Address First Parameter pushed last Optional Lower Addresses o o Last Parameter stack grows down j Structure Ret Optional A e a Higher Addresses Figure 4 General Appearance of Assembly Code Stack Frame The return address is always necessary The presence of auto variables depends on the function definition 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 tem porary information pushed on the stack The shaded area in the stack frame is the stack storage allocated for auto variables The assem bler symbol SP represents the size of this area 122 Dynamic C User s Manual 11 4 1 1 The Frame Reference Point The frame reference point is a location in the stack frame that immediately follows the function s return address The IX register ma
151. e clock RTC If the RTC is set correctly this is the number of seconds that have elapsed since the reference date of January 1 1980 The periodic interrupt updates SEC_TIMER every second This variable is initialized by the Virtual Driver when a program starts MS_TIMER This unsigned long variable is initialized to zero The periodic interrupt updates MS_TIMER every millisecond This variable is initialized by the Virtual Driver when a program starts TICK_TIMER This unsigned long variable is initialized to zero The periodic interrupt updates TICK_TIMER 1024 times per second This variable is initialized by the Virtual Driver when a program starts Dynamic C User s Manual 259 A 3 Exception Types These macros are defined in errors lib define define define define define define define define define define define define define define define define define define define A 4 Rabbit 2000 3000 Internal registers ERR_BADPOINTER ERR_BADARRAYINDEX ERR_DOMAIN ERR_RANGE ERR_FLOATOVERF LOW ERR_LONGDIVBYZERO ERR_LONGZEROMODULUS ERR_BADPARAMETER ERR_INTDIVBYZERO ERR_UNEXPECTEDINTRPT ERR_CORRUPTEDCODATA ERR_VIRTWDOGTIMEOUT ERR_BADXALLOC ERR_BADSTACKALLOC ERR_BADSTACKDEALLOC ERR_BADXALLOCINIT ERR_NOVIRTWDOGAVAIL ERR_INVALIDMACADDR ERR_INVALIDCOFUNC 228 229 234 235 236 237 238 239 240 241 243 244 245 246 247 249 250 251 252 Macros are defined for all of the Rabbit s I O regi
152. e efficient code when used Its use must be consistent between the prototype and the function definition root int func memmap root asm root endasm Identifies a function chain segment within a function int func int arg int vec 10 segchain _GLOBAL_INIT for i 0 i lt 10 i vec i 0 This example adds a segment to the function chain _GLOBAL_INIT Using segchain is equivalent to using the GLOBAL_INTIT directive When this function chain executes this and perhaps other segments elsewhere execute The effect in this example is to re initialize vec Indicates that changes to a multi byte variable such as a float are atomic Interrupts are dis abled when 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 i 1 constitute two atomic references to variable i a read and a write Be careful because i is not an atomic operation Chapter 12 Keywords 151 Declares that a variable or array is short integer 16 bits If nothing else is specified short im plies a 16 bit signed integer short i j k 16 bit signed unsigned short int w 16 bit unsigned short funct short arg Declares a function to be optimized for size as opposed to speed size int func A built in function that returns the size in bytes of a va
153. e keyboard shortcut is lt Ctrl F2 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 previ ous execution overwrites the code segment That is if your code is corrupted the reset will not be enough you will have to reload the program to the target 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 breakpoints in the machine code If nodebug is in effect execution continues until code compiled without the nodebug key word 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 Source Trace into Executes one C statement with descent into functions when the assembly window is open Execution will not descend into functions stored in ROM because Dynamic C cannot insert the required breakpoints in the machine code If nodebug is in effect execution continues until code compiled without the nodebug keyword is encountered The keyboard shortcut is lt Alt F7 gt Source Step over Executes one C statement without descending into functions when the assembly window is op
154. e macro MAX_OS_EVENTS must take into account each of the socket locks plus any events that the application program may be using semaphores queues mailboxes event flags or mutexes Determining OS_MAX_EVENTS may get a little tricky but it isn t too bad if you know what your program is doing Since MAX_SOCKET_LOCKS is defined as define MAX _SOCKET_LOCKS MAX_TCP_SOCKET_BUFFERS MAX_UDP_SOCKET_BUFFERS OS_MAX_EVENTS may be defined as define OS_MAX_EVENTS MAX_TCP_SOCKET_BUFFERS MAX_UDP_SOCKET_BUFFERS 2 z The constant 2 is included for the two global locks used by TCP IP and z is the number of OS_EVENTS semaphores queues mailboxes event flags or mutexes required by the program Chapter 18 uC OS II 253 If either MAX_TCP_SOCKET_BUFFERS or MAX_UDP_SOCKET_BUFFERS is not defined by the application program prior to the use statements for ucos 1ib and dcrtcp 1ib default values will be assigned If MAX_TCP_SOCKET_BUFFERS is not defined in the application program it will be defined as MAX_SOCKETS If however MAX_SOCKETS is not defined in the application program MAX_TCP_SOCKET_BUFFERS will be 4 If MAX_UDP_SOCKET_BUFFERS is not defined in the application program it will be defined as 1 if USE_DHCP is defined or 0 otherwise For more information regarding TCP IP please see the Dynamic C TCP IP User s Manual avail able online at zworld com or rabbitsemiconductor com 18 6 Debugging Tips Dynamic
155. e reserved for the struct function returns See Section 11 4 1 1 on page 123 for more information Determines the next reference address of a variable plus it LENGTH size 11 2 6 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 or static 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 The name of a structure element represents the offset of the element from the beginning of the structure In the following structure for example SGtmuer S LNE KE ae WP imic Ae the embedded assembly expression s x evaluates to 0 st y evaluates to 2 and s z evaluates to 4 regardless of where structure s may be The following list of processor register names are reserved and may not be used as C variable names in assembly A B C D E F H L AF HL DE BC IX IY SP PC XPC IP IIR and EIR Both upper and lower case instances are reserved Chapter 11 Using Assembly Language 119 In nested structures offsets can be composite as shown here Struct s LE skp S x 0 struct al M SaS inte 97 a b Ost at b 2 LIME at C Schrat ac 4 E Kr 11 3 Stand Alone Assembly Code A stand alone assembly function is one that is defined outside
156. e 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 stand alone assembly routine however must load the pri mary register with the return value before the ret instruction Chapter 11 Using Assembly Language 127 11 5 2 1 Returning a Structure 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 Dynamic C functions contain ing embedded assembly code may use a C return statement to return a value A stand alone assembly routine however must store the return value in the structure return space on the stack before returning Inline 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 of a structure as a returned value of type SELUGE S typedef struct ss aime i0 8 first field Gaam iig second field xyz KVA iW SHE IEUICIE p thy Scere CWAC xyz func asm xor a clear register A ld hl SP QRETVAL ss f1 hl lt the offset from SP to the fI field of the returned structure add hl sp hl now points to fl le Ual ai load a now 0 to fl endasm It is crucial that SP be added to RETVAL because RET
157. e same pathname as the source file but witha bin extension This switch is available only in Dynamic C v 7 05 and 7 06 Compilation is written only to the target and not to a file Select the Compile Compile to bin file Use attached target menu option bf Available starting with Dynamic C v 7 10 Description Factory Default GUI Equivalent Description Default GUI Equivalent Example Undo user defined BIOS file specification None Uncheck the Options Compiler User defined BIOS file Use dialog box option Print program header information This switch is available only in Dynamic C v 7 05 and 7 06 No header information will be printed None dccl_cmp samples demol c h o myoutputs txt Header text preceding output of program PES FAS FAS K K K K K K K K K K K K K KK K 2K K K K K K K K K 2K KK 2K K K K K FKK K K K K K K K ie K K FKK K K K K ok K 4 5 01 2 47 16 PM dccl_cmp exe Version 7 05P English samples demol c Options h o myoutputs txt Program outputs Note Version information refers to dcwd exe with the same compiler core 210 Dynamic C User s Manual h Available starting with Dynamic C v 7 10 Description Print program header information Factory Default No header information will be printed GUI Equivalent None Example dccl_cmp samples demol c h o myoutputs txt Header text preceding output of program KKK K K K K K K K K K K K K K K KK K K K K K K K
158. e starting with Dynamic C v 7 10 Description Disable type checking of prototypes Default Type checking of prototypes is performed GUI Equivalent Uncheck the Options Compiler Prototype menu dialog box option VP Available starting with Dynamic C v 7 20 Description Verify the processor by enabling a DSR check This should be disabled if a check of the DSR line is incompatible on your system for any reason Default Processor verification is enabled GUI Equivalent Check the Options Communications Enable DSR verification box vp Available starting with Dynamic C v 7 20 Description Assume a valid processor is connected Default Processor verification is enabled GUI Equivalent Uncheck the Options Communications Enable DSR verification box Chapter 15 Command Line Interface 217 wa Description Report all warnings Default All warnings reported GUI Equivalent Select the Options Compiler All menu dialog box option wn Description Report no warnings Default All warnings reported GUI Equivalent Select the Options Compiler None menu dialog box option WS Description Report only serious warnings Default All warnings reported GUI Equivalent Select the Options Compiler Serious menu dialog box option 218 Dynamic C User s Manual 15 4 2 Switches Requiring a Parameter bf BIOSFilePathname Description Default Compile using a BIOS file found in BIOS
159. e two directives makechain and funcchain and one keyword seg chain that create and control function chains makechain chain_name Creates a function chain When a program executes the named function chain all of the func tions 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 iscalled A program will call a function chain as it would an ordinary void function that has no parameters The following example shows how to call a function chain that is named recover makechain recover recover 34 Dynamic C User s Manual 4 20 Global Initialization Various hardware devices in a system need to be initialized not only by setting variables and con trol registers but often by complex initialization procedures Dynamic C provides a specific func tion chain
160. ed RAM Gen erally the battery backed RAM is attached to CS1 due to the low power requirements In the case of a reset or power failure the value of a boboram variable is preserved but not atomically like with protected variables No software check is possible to ensure that the RAM is bat tery backed This requirement must be enforced by the user If interested please see the Rabbit 3000 Microprocessor Designer s Handbook for information on how the second data area is reserved Jumps out of a loop if or case statement while expression if condition break switch expression case 3 break Chapter 12 Keywords 139 Use in assembly block to insert one Dynamic C instruction asm InitValues c start_time 0 c counter 256 ld hl 0xa0 ret endasm Identifies the next case in a switch statement Switch expression case const case const case const Declares a variable or array element as an unsigned 8 bit character char c x string hello int ae c char i type casting operator 140 Dynamic C User s Manual This keyword declares that a value will be stored in flash thus making it unavailable for mod ification const is a type qualifier and may be used with any static or global type specifier char int struct etc The const qualifier appears before the type unless it is modify ing a pointer When modifying a pointer the const keyword appears
161. ed very precise delay timing Suppose the application requires a 60 second delay with only 100 ms of delay accuracy that is an actual delay of 60 1 seconds is considered acceptable Then if the processor guarantees to check the delay every 50 ms the delay would be at most 60 05 seconds and the accuracy requirement is satisfied 5 8 Overview of Preemptive Multitasking In a preemptive multitasking environment tasks do not voluntarily relinquish control Tasks are scheduled to run by priority level and or by being given a certain amount of time There are two ways to accomplish preemptive multitasking using Dynamic C The first way is uC OS II a real time preemptive kernel that runs on the Rabbit microprocessor and is fully sup ported by Dynamic C For more information see Chapter 18 uC OS II The other way is to use slice statements 5 9 Slice Statements The slice statement based on the costatement language construct allows the programmer to run a block of code for a specific amount of time 5 9 1 Syntax slice context_buffer context_buffer_size time_slice name statement yield abort waitfor expression context buffer size This value must evaluate to a constant integer The value specifies the number of bytes for the buffer context_buffer It needs to be large enough for worst case stack usage by the user program and interrupt routines time slice The amount of time in ticks for the slice to run
162. ef struct int x int y coord coord p pisa pointer to structure m p gt x reference to structure element 13 8 Reference Dereference Operators Address operator or bitwise AND As a unary operator this provides the address of a variable ATE X Zz amp xX z gets the address of x As a binary operator this performs the bitwise AND of two integer char int or long val ues int i OxFFFO int j Ox0OFFF zZz i6 amp j z gets OxOFFO 174 Dynamic C User s Manual Indirection or multiplication As a unary operator it indicates indirection When used in a declara tion indicates that the following item is a pointer When used as an indirection operator in an expression provides the value at the address specified by a pointer int p p isa pointer to an integer int j 45 p amp j p 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 Sameas j 25 since p pointsto j 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 ptr to array of 10 ints float y ptrtoaptrtoa float z y z gets the value of y typedef char stp stp my_stuff my_stuff istyped char As a binary operator the indicates multiplication a b c a gets the product of b and c 13 9
163. en The keyboard shortcut is lt Alt F8 gt Toggle Breakpoint Toggles a regular soft breakpoint at the location of the execution cursor Soft breakpoints do not affect the interrupt state at the time the breakpoint is encountered whereas hard break points do The keyboard shortcut is F2 Chapter 14 Graphical User Interface 187 Toggle Hard Breakpoint Toggles a hard breakpoint at the location of the execution cursor A hard breakpoint differs from a soft breakpoint in that interrupts are disabled when the hard breakpoint is reached The keyboard shortcut is lt Alt F2 gt Clear All Breakpoints Self explanatory The keyboard shortcut is lt Ctrl A gt Toggle Interrupt Flag Toggles interrupt state The keyboard shortcut is lt Ctrl I gt Toggle Polling Prior to DC 7 30 Toggles polling mode When this option is chosen polling will be toggled until the next debugger operation If the program is currently running and Dynamic C is polling the target you may choose Toggle Polling to stop Dynamic C from polling the target However as soon as the program stops executing or Dynamic C sets a breakpoint or a watch expression is added etc Dynamic C will reenable polling When running in polling mode F9 the development PC polls or interrupts the target system every 100 ms to obtain or send information regarding target breakpoints watch lines key board entered target input and target output from printf statements Starting
164. ent will be discarded if No is 6699 clicked or n is typed Cancel results in a return to Dynamic C with no action taken Project Allows a project file to be opened saved saved as a different name and closed See Chapter 16 for more information Print Preview Shows approximately what printed text will look like Dynamic C switches to preview mode when this command is selected and allows the programmer to navigate through images of the printed pages Print Text can be printed from any Dynamic C window There is no restriction to printing source code For example the contents of the assembly window or the watch window can be printed Dynamic C displays the a standard print dialog box when the Print command is selected 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 If the Print to File option is selected Dynamic C creates a file it will ask for a pathname in the 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 Setup button in the Print dialog or choose the Print Setup command from the FILE menu Chapter 14 Graphical User Interface 181 Print Setup Allows choice of which printers to use and to set them up to print text There is a choice between using the computer system s default printer or selecting a specific pri
165. er of bytes to dump The option Save Entire Flash to File requires a file pathname If you are run ning in RAM then it will be RAM that is saved to a file not Flash because this option simply starts dumping physical memory at address 0 When displaying to the screen the Memory Dump window is opened A typical screen display appears below E Mia enemy Chiang DF ba 3E iv 321 gt w gt ww JE we 8 ope l wb 7m we wi G OF gt 2 32 2 The Memory Dump window may be scrolled Scrolling causes the contents of other memory addresses to appear in the window Hotkeys ArrowUp ArrowDown PageUp PageDown are active in the Memory Dump 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 breakpoint Chapter 14 Graphical User Interface 191 14 2 6 Options Menu Click the menu title or press lt Alt O gt to select the OPTIONS menu Options 14 2 6 1 Editor The Editor command gets Dynamic C to display the following dialog Editor Options 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 edi tor 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 19
166. error occurs a call is made to exception The run time error type is passed to exception which then pushes various parameters on the stack and calls the installed error handler The default error handler places information on the stack disables interrupts and enters an endless loop by calling the _xexit function in the BIOS Dynamic C notices this and halts execution reporting a run time error to the user 8 1 1 Error Code Ranges The table below shows the range of error codes used by Dynamic C and the range available for a custom error handler to use Please see section 8 2 on page 93 for more information on replacing the default error handler with a custom one Table 8 11 Dynamic C Error Types Ranges Error Type Meaning 0 127 Reserved for user defined error codes 128 255 Reserved for use by Dynamic C Chapter 8 Run Time Errors 91 8 1 2 Fatal Error Codes This table lists the fatal errors generated by Dynamic C Table 8 12 Dynamic C Fatal Errors Error Type Meaning 127 227 not used 228 Pointer store out of bounds 229 Array index out of bounds 230 233 not used 234 Domain error for example acos 2 235 Range error for example tan pi 2 236 Floating point overflow 237 Long divide by zero 238 Long modulus modulus zero 239 not used 240 Integer divide by zero 241 Unexpected interrupt 242 not used 243 Cod
167. es advantage of the natural delays that occur in most tasks to more efficiently use the available processor time The DEMO3 C sample program has two independent tasks The first task prints out a message to STDIO once per second The second task watches to see if the keyboard has been pressed and prints out which key was entered 10 Dynamic C User s Manual main int secs seconds counter sees 0 initialize counter 2 waite i 4 endless loop First task will print the seconds elapsed 2 COSstacea i secstt increment counter C3 waitfor DelayMs 1000 wait one second printf d seconds n secs print elapsed seconds 4 Second task will check if any keys have been pressed costate gt i Ukonic abort key been pressed primer Akey joressecl EAn EE eNO 6 end of while loop end of main The numbers in the left margin are reference indicators and not part of the code Load and run the program The elapsed time is printed to the STDIO window once per second Push several keys and note how they are reported The elapsed time message is printed by the costatement starting at the line marked 2 Costate ments need to be executed regularly often at least every 25 ms To accomplish this the costate ments are enclosed in a while loop The while loop starts at 1 and ends at 6 The statement at 3 waits for a time delay in this case 1000 ms one se
168. eserved in the first flash for use by FS2 and possibly other customer defined purposes This is defined in the BIOS as 0x0000 Memory set aside with XMEM_RESERVE_SIZE will NOT be available for xmem code Chapter 10 The Flash File System 103 10 2 5 FS2 and Use of the First Flash To use the first flash in FS2 follow these steps 1 Define XMEM_RESERVE_SIZE currently set to 0x0000 in the BIOS to the number of bytes to allocate in the first flash for the file system 2 Define FS2_USE_PROGRAM_FLASH to the number of KB 1024 bytes to allocate in the first flash for the file system Do this in the application code before use fs2 1ib 3 Obtain the LX number of the first flash Call s_get_other_1x when there are two flash memories call s_get_flash_1x when there is only one 4 If desired create additional logical extents by calling the FS2 function fs_setup to further partition the device This function can also change the logical sector sizes of an extent Please see the function description for fs_setup in the Dynamic C Function Reference Manual for more information 10 2 5 1 Example Code Using First Flash in FS2 If the target board has two flash memories the following code will cause the file system to use the first flash FSLXnum flashl logical extent number File f struct for file information flashl fs_get_other_1x if flashl fs_set_lx flashl flashl fcreate amp f 10
169. ess the declaration is preceded with extern 4 23 3 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 appli cation For this reason it is not wise to put many functions in one module regardless of whether they are actually going to be used by the program To minimize waste it is recommended that a module header contain only prototypes and extern declarations Prototypes and extern declarations 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 or a user defined replacement for LIB DIR anda use directive for the library must be placed somewhere in the code It should be noted that there is no way to define file scope variables other than having a file consist of a single module which would mean that all data and functions in the file would be compiled whenever a function specified in the header is compiled 38 Dynamic C User s Manual Example ers BOC Linteaclaie tieks extern unsigned long ticks
170. et and warnings or errors are written to myouputs txt dccl_cmp samples timerb timer_b c o myoutputs txt b pf myproject 15 5 3 Example 3 These examples will compile and run myProgram c with the current settings in default dcp but using different defines displaying up to 50 warnings and capture all output to one file with a header for each run dccl_cmp myProgram c d MAXCOUNT 99 nw 50 h o myOutput txt dccl_cmp myProgram c qd MAXCOUNT 15 nw 50 h oa myOutput txt dccl_cmp myProgram c d MAXCOUNT 15 d DEF1 nw 50 h oa myOutput txt The first run could have used the oa option if myOutput t xt were known to not initially exist myProgram c presumably uses a constant MAXCOUNT and contains one or more com piler directives that react to whether or not DEF 1 is defined 226 Dynamic C User s Manual 16 Project Files In Dynamic C a project is an environment that consists of opened source files a BIOS file avail able libraries and the conditions under which the source files will be compiled Projects allow dif ferent compilation environments to be separately maintained Projects are available in Dynamic C starting with version 7 10 16 1 Project File Names A project maintains a compilation environment in a file with the extension dcp 16 1 1 Factory dcp The environment originally shipped from the factory is kept in a project file named factory dcp If Dynamic C cannot find this file it will be recre
171. ete FS1 Deletes a file 10 3 1 1 FS1 API Details The functions fs_init and fs_format are similar in that they both start the file system Use fs_format to erase all blocks in the file system This function s third parameter wear level should be 1 for a new flash memory otherwise it should be 0 to use the current wear lev eling Use fs_init to preserve blocks that are in use and to do an integrity check of them In case of loss of power fs_init will delete any blocks that may be partially written and will substi tute the last known good block for that file This means that any changes to the file that occurred between the last write and the power outage would be lost Chapter 10 The Flash File System 105 10 3 2 FS2 API The API for FS2 is defined in FS2 LIB For more information please see the Dynamic C Function Reference Manual Table 10 16 FS2 API Command Description fs_setup FS2 Alters the initial default configuration fs_init FS2 Initialize the internal data structures for the file system fs_format FS2 Initialize flash and the internal data structures 1lx_format Formats a specified logical extent LX fs_set_lx FS2 Sets the default LX numbers for file creation fs_get_lx FS2 Returns the current LX number for file creation fcreate FS2 Creates a file and open it for writing fcreate_unused FS2
172. etting there and returning It takes a total of 12 additional machine cycles because of the differences between call Icall and ret Iret e Increase DATAORG Root code space can be increased by increasing DATAORG in RabbitBios c in increments of 0x1000 Unfortunately this comes at the expense of root data space but there are ways of reducing that too e Reduce usage of root constants and string literals Shortening literal strings and reusing them will save root space The compiler starting with version 7 20 automatically reuses identical string literals These two statements printf This is a literal string sprintf buf This is a literal string will share the same literal string space whereas sprintf buf this is a literal string will use its own space since the string is different 234 Dynamic C User s Manual e Use xdata to declare large tables of initialized data If you have large tables of initialized data consider using the keyword xdata to declare them The disadvantage is that data cannot be accessed directly with pointers The function xmem2 root allows xdata to be copied to a root buffer when needed This uses root code space const int root_tb1 8 300 301 302 103 304 305 306 307 This does not xdata xdata_table 300 301 302 103 304 305 306 307 main this only uses temporary stack space auto int table 8 xmem2root
173. example each of the following lines all define the string ABC Gig TAY BY Yee db ABC Glo OxA il OAZ A5 The numerical values and characters in strings are used to initialize sequential byte locations If separate I amp D space is enabled assembly constants should either be put in their own assembly block with the const keyword or be done in C asm const MV EOCOE COM SIEGIMNES 8 8 db 0x40 0x41 0x42 endasm or CONSE Chiaie mycoorcomstames et Y e4il Y xt2 Chapter 11 Using Assembly Language 117 If separate I amp D space is enabled db places bytes in the base segment of the data space when it is used with const If the const keyword is absent i e asm MV ROOECONS EANES db 0x40 Ox41 0x42 endasm the bytes are placed somewhere in the instruction space If separate I amp D space is disabled the default condition the bytes are placed in the base segment aka root segment interspersed with code The assembly language keyword dw defines 16 bit words least significant byte first The keyword dw should be followed immediately by numerical values chy O20I23 Obi Z This example defines three constants The first two constants are literals and the third constant is the address of variable xyz The numerical values initialize sequential word locations starting at the current code address 11 2 3 Multiline Macros The Dynamic C preprocessor has a special feature to allow multiline mac
174. f an attempt is made to allocate more than 10 virtual WDTs a fatal error occurs In debug mode this fatal error will cause the program to return with error code 250 The default run time error behavior is to reset the board The ID returned by VaGet FreewW is used as the argument when calling VaHitWd ID or VdReleaseWd ID to hit or deallocate a virtual watchdog The Virtual Driver counts down watchdogs every 62 5 ms If a virtual watchdog reaches 0 this is fatal error code 247 Once a virtual watchdog is active it should be reset periodically with a call to VdHitWd ID to prevent this If count 2 for a particular WDT then VaHitWd ID will need to be called within 62 5 ms for that WDT If count 255 VAHit Wd ID will need to be called within 15 94 seconds The Virtual Driver does not count down any virtual WDTs if the user is debugging with Dynamic C and stopped at a breakpoint 6 5 Preemptive Multitasking Drivers A simple scheduler for Dynamic C s preemptive slice statement is serviced by the Virtual Driver The scheduling for uC OS II a more traditional full featured real time kernel is also done by the Virtual Driver These two scheduling methods are mutually exclusive slicing and uC OS II must not be used in the same program Chapter 6 The Virtual Driver 67 68 Dynamic C User s Manual 7 The Slave Port Driver The Rabbit 2000 and the Rabbit 3000 have hardware for a slave port allowing a master controlle
175. f the pf switch is not used the values are taken from default dcp For more information please see Chapter 16 Project Files on page 227 15 2 User Input Applications requiring user input must be called with the i option dccl_cmp myProgram c i myProgramInputs txt where myProgramInputs txt isa text file containing the inputs as separate lines in the order in which myP rogram c expects them 15 3 Saving Output to a File The output consists of all program printf s as well as all error and warning messages Output to a file can be accomplished with the O option dccl_cmp myProgram c i myProgramInputs txt o myOutputs txt where myOutputs txt is overwritten if it exists or is created if it does not exist If the oa option is used myOutputs txt is appended if it exists or is created if it does not Chapter 15 Command Line Interface 209 15 4 Command Line Switches Each switch must be separated from the others on the command line with at least one space or tab Extra spaces or tabs are ignored The parameter s required by some switches must be added as separate text immediately following the switch Any of the parameters requiring a pathname including the source file pathname can have imbedded spaces by enclosing the pathname in quotes 15 4 1 Switches Without Parameters b Description Default GUI Equivalent Compile to bin file using attached target The resulting file is created or overwritten with th
176. file FILESYSTEM LIB if using FS1 10 1 5 Multitasking and the File System Neither FS1 nor FS2 are re entrant If using preemptive multitasking ensure that only one thread performs calls to the file system or implement locking around each call 100 Dynamic C User s Manual 10 2 Application Requirements The application requirements for FS1 and FS2 are slightly different This section covers both sets of requirements including e which library to use e which drivers to use e defaults and descriptions for configuration macros e detailed instructions for using the first flash 10 2 1 FS1 Requirements To use the file system a macro that determines which low level driver is loaded must be defined in the application program define FS FLASH use 2nd flash for file system define FS_RAM use SRAM supported for debug purposes The file system library must be compiled with the application use FILESYSTEM LIB 10 2 2 FS1 and Use of the First Flash To use FS1 in the first flash a low level driver must be used define FS FLASH SINGLE Because this particular low level driver must share the first flash with the program code the file system must be carefully placed such that the two do not collide Also it should be noted that any time the first flash is written to during runtime interrupts will be shut off for the duration of the write This could have serious implications for real time systems To re
177. file within a logical extent File numbers must be unique within the entire file system FS2 accepts file numbers in word format rather than the byte format of FS1 typedef word FileNumber The low order byte specifies the file number and the high order byte specifies the LX number of the metadata 1 through number of LXs If the high order byte is zero then a suitable default LX will be located by the file system The default LX will default to 1 but will be settable via a define for file creation For existing files a high order byte of zero will cause the file system to search for the LX that contains the file This will require no or minimal changes to existing cus tomer code Only the metadata LX may be specified in the file number This is called a fully qualified file number FQFN The LX number always applies to the file metadata The data can reside on a dif ferent LX however this is always determined by FS2 once the file has been created 10 5 2 File Names There are several functions in ZSERVER LIB that can be used to associate a descriptive name with a file The file must exist in the flash file system before using the auxiliary functions listed in the following table These functions were originally intended for use with an HTTP or FTP server so some of them take a parameter called servermask To use these functions for file naming purposes only this parameter should be SERVER_USER For a detailed descripti
178. g Flash Select the Options Compiler Code and BIOS in Flash menu dialog box option The BIOS and code are compiled to flash and then the BIOS copies the flash image to RAM to run the code Memory BIOS setting Flash Uncheck the Options Compiler Code and BIOS in Flash Run in RAM menu dialog box option Memory BIOS setting RAM Memory BIOS setting Flash Select the Options Compiler Code and BIOS in RAM menu dialog box option N Available starting with Dynamic C v 7 25 Description Null compile for errors and warnings without running the program The program will be downloaded to the target Default Program is run GUI Equivalent Select Run Run menu option 212 Dynamic C User s Manual rb Description Do not include BIOS when compiling to a file This option is ignored if not compiling to a file This switch is available only in Dynamic C v 7 05 and 7 06 Default BIOS is included if Compile to bin file is selected GUI Equivalent Uncheck the Compile Compile to bin file Include BIOS menu option rb Available starting with Dynamic C v 7 10 Description Include BIOS when compiling to a file Default BIOS is included if Compile to bin file is selected GUI Equivalent Check the Compile Compile to bin file Include BIOS menu option rb Available starting with Dynamic C v 7 10 Description Do not include BIOS when compiling to a file Default BIOS is included if Compile t
179. g Run in the Run menu The value of the counter should be printed repeatedly to the STDIO window if everything went well If this doesn t work review the follow ing points e The target should be ready indicated by the message BIOS successfully compiled If you did not receive this message or you get a communication error recompile the BIOS by typing lt Ctrl Y gt or select Recompile BIOS from the Compile menu e A message reports No Rabbit Processor Detected in cases where the wall transformer is not connected or not plugged in e The programming cable must be connected to the controller The colored wire on the program ming cable is closest to pin 1 on the programming header on the controller The other end of the programming cable must be connected to the PC serial port The COM port specified in the Dynamic C Options menu must be the same as the one the programming cable is connected to e To check if you have the correct serial port select Compile then Compile BIOS or press lt Ctrl Y gt If the BIOS successfully compiled message does not display try a different serial port using the Dynamic C Options menu until you find the serial port you are plugged into Don t change anything in this menu except the COM number The baud rate should be 115 200 bps and the stop bits should be 1 8 Dynamic C User s Manual 3 1 1 Single Stepping Compile DEMO1 C by clicking the Compile button on the task bar T
180. gical AND amp amp 173 logical NOT 1 173 logical OR ID 0 173 operator precedence 177 postfix expressions 173 parentheses 173 array indices 173 dot enrii 174 parentheses 0 173 right arrow gt eee 174 precedence oe 165 reference dereference opera LOTS aches ineo a i E 174 address amp cceeseeeeee 174 bitwise AND amp 174 indirection 0 175 multiplication 175 relational operators 171 greater than gt 172 greater than or equal gt 172 less than lt wc 171 less than or equal lt 171 SIZCOE sssestis a cieerest cies 176 UNALY so re e eeen 165 optimize size or speed 196 options communications 199 compiler oo eee 193 debugger oe eee 197 display oo eee 198 ELITO vesccenr gcse essciestens 192 MENU ses cece erer becca eves 192 P PageDown key secese 179 PageUp Key lt scec sssiescsucsessess 179 Partitioning we 107 passing arguments 29 122 127 128 129 pasting text oe 183 periodic interrupt 51 60 65 239 250 259 pointer checking 0 0 28 pointers o eeeeee 20 27 29 uninitialized ee 28 poll target wee 188 polling we 186 188 ports seral wisi inion ings 199 positioning text oe 184 power failure 0 150 precompile 0 ee 163 precompiler oo eee 37 preserving regi
181. gt lt memmap section gt lt memmapreg gt lt memmapreg gt lt register var gt lt 8 bit const gt lt register var gt XPCISEGSIZEIDATASEG lt function section gt lt function descripton gt lt function description gt lt identifier gt lt address gt lt size gt lt address gt lt logical address gt lt physical address gt lt logical address gt lt 16 bit constant gt lt physical address lt 8 bit constant gt lt 16 bit constant gt lt size gt lt 20 bit constant gt lt global section gt lt global description gt lt global description gt lt scoped name gt lt address gt lt scoped name gt lt global gt lt local static gt lt global gt lt identifier gt lt local static gt lt identifier gt lt identifier gt Comments are C style only Dynamic C User s Manual 261 262 Dynamic C User s Manual Appendix C Utility Programs This appendix documents the utility programs available from Z World All of these utilities are easy to use The file encryption utility may be obtained by calling our technical support staff at 530 757 3737 The other utilities are bundled with Dynamic C C 1 Font and Bitmap Converter Utility The Font and Bitmap Converter converts Windows fonts and monochrome bitmaps to a library file format compatible with Z World s Dynamic C applications and graphical displays Non Roman characters may also be converted by applying the monochrome bitmap
182. guration constant that differs from the library default is defined The configuration in this example differs from the default in that it allows only two events the minimum needed when using only one semaphore 20 tasks no queues no mailboxes and the system tick rate is set to 32 ticks per second 1 Next since this application uses tasks with 1024 byte stacks it is neces sary to define the configuration constants differently than the library default 2 Notice that one 512 byte stack is declared Every Dynamic C program starts with an initial stack and defining STACK_CNT_512 is crucial to ensure that the application has a stack to use during initialization and before multi tasking begins Finally ucos2 1ib is explicitly used 3 This ensures that the definitions in 1 and 2 are used rather than the library defaults The last step in initialization is to set the number of ticks per second via OSSet TicksPerSec 4 The rest of this application is identical to example 1 and is explained in the previous section 1 Define necessary configuration constants for uC OS II define OS MAX EVENTS 2 define OS MAX TASKS 20 define OS MAX OS 0 define OS_Q EN 0 define OS _MBOX_EN 0 define OS_TICKS_PER_SEC 32 2 Define necessary stack configuration constants define STACK _CNT_512 1 initial program stack define STACK_CNT_1K OS MAX TASKS task stacks 3 This ensures that the above definitions are used fuse ucos2 lib void R
183. h include user callable functions Please see the Dynamic C Function Reference Manual for detailed descriptions of these API functions Dynamic C libraries are in source code allowing the creation of customized libraries Before starting on your application read through the rest of this chapter to review C language fea tures and understand the differences between standard C and Dynamic C 4 1 C Language Elements A Dynamic C program is a set of files consisting of one file with a c extension and the requested library files Each file is a stream of characters that compose statements in the C language The language has grammar and syntax that is rules for making statements Syntactic elements often called tokens form the basic elements of the C language Some of these elements are listed in the table below Table 4 1 C Language Elements punctuation Symbols used to mark beginnings and endings names Words used to name data and functions numbers Literal numeric values strings Literal character values enclosed in quotes directives Words that start with and control compilation keywords Words used as instructions to Dynamic C operators Symbols used to perform arithmetic operations Chapter 4 Language 13 4 2 Punctuation and Tokens Punctuation marks serve as boundaries in C programs The table below lists the punctuation marks and tokens Table 4 2 Punctuation Marks and Tokens Symbol Descrip
184. h to run mode compilation succeeded In the case of a failed compile the editor will take on the Error Editor attributes In the case of a successful compile the editor will take on the Debug Editor attributes 198 Dynamic C User s Manual 14 2 6 5 Communications The Options Communications menu item displays the following dialog box Use it to tell Dynamic C how to communicate with the target controller Communications Options NeiWwork Adaress TCP IP Options In order to program and debug a controller across a TCP IP connection the Network Address field must have the IP address of either the Z World RabbitLink board that is attached to the controller or the IP address of a controller that has its own Ethernet interface To accept control commands from Dynamic C the Control Port field must be set to the port used by the ethernet enabled controller The Controller Name is for informational purposes only The Discover button makes Dynamic C broadcast a query to any RabbitLinks attached to the network Any RabbitLinks that respond to the broadcast can be selected and their infor mation will be placed in the appropriate fields Chapter 14 Graphical User Interface 199 Serial Options The following options are available when the Use Serial Connection radio button is selected Port This is the COM port of the PC that is connected to the target It defaults to COM1 Debug Baud Rate This defaults to 115200 bps It
185. handler function handler Pointer to the handler function This function must have a par ticular form which is described by the function description for MyHandler shown below Setting this parameter to NULL unloads the current handler handler_params Pointer that will be saved and passed to the handler function each time it is called This allows the handler function to be parameterized for multiple cases RETURN VALUE 1 Success the handler was set 0 Failure LIBRARY SLAVE_PORT LIB 72 Dynamic C User s Manual int MyHandler char command char data_in void params DESCRIPTION This function is a developer supplied function and can have any valid Dynamic C name Its purpose is to handle incoming commands from a master to one of the 256 channels on the slave port A handler function must be supplied for every channel that is being used on the slave port PARAMETERS command This is the received command byte data_in The optional data byte params The optional parameters pointer RETURN VALUE This function must return an integer The low byte must contains the response code and the high byte contains the returned data if there is any LIBRARY This is a developer supplied function Chapter 7 The Slave Port Driver 73 void SPtick void DESCRIPTION This function must be called periodically when the slave port is used in polling mode LIBRARY SLAVE_PORT LIB void SPclose void DESCRIPTION
186. he data in battery backed RAM on reset The default storage class is static not auto This avoids numerous bugs encountered in embedded systems due to the use of auto variables Starting with Dynamic C 7 x the default class can changed to auto by the compiler directive class auto The numerous include files found in typical C programs are not used because Dynamic C has a library system that automatically provides function prototypes and similar header information to the compiler before the user s program is compiled This is done via the use directive This is an important topic for users who are writing their own libraries Those users should refer to the Modules section of the language chapter It is important to note that the use directive is a replacement for the include directive and the include directive is not supported When declaring pointers to functions arguments should not be used in the declaration Argu ments may be used when calling functions indirectly via pointer but the compiler will not check the argument list in the call for correctness Bit fields are not supported Separate compilation of different parts of the program is not supported or needed There are minor differences involving extern and register keywords Chapter 2 Introduction to Dynamic C 2 3 Dynamic C Differences Between Rabbit and Z180 A major difference in the way Dynamic C interacts with a Rabbit based board compared to a Z180 or 386E
187. he list of watch expressions then press lt Ctrl U gt repeatedly to observe as secs increases Chapter 3 Quick Tutorial 11 3 4 Summary of Features This chapter provided a quick look at the intuitive interface of Dynamic C and some of the power ful options available for embedded systems programming Development Functions When you load a program it appears in an edit window You compile by clicking Compile on the task bar or from the Compile menu The program is compiled into machine language and down loaded to the target over the serial port The execution proceeds to the first statement of main where it pauses waiting to run Press the F9 key or select Run on the Run menu If want to com pile and run the program with one keystroke use F9 the run command if the program is not already compiled the run command compiles it Single Stepping This is done with the F8 key The F7 key can also be used for single stepping If the F7 key is used then descent into subroutines will take place With the F8 key the subroutine is executed at full speed when the statement that calls it is stepped over Setting Breakpoints The F2 key is used to toggle a breakpoint at the cursor position if the program has already been compiled You can set a breakpoint if the program is paused at a breakpoint You can also set a breakpoint in a program that is running at full speed This will cause the program to break if the execution thread hits your breakp
188. he program will compile and the screen will come up with a highlighted character green at the first executable statement of the program Use the F8 key to single step Each time the F8 key is pressed the cursor will advance one statement When you get to the statement for j 0 j lt it becomes impractical to single step further because you would have to press F8 thousands of times We will use this state ment to illustrate watch expressions 3 1 2 Watch Expression Press lt Ctrl W gt or choose Add Del Watch Expression in the Inspect menu A box will come up Type the lower case letter j and click on Add to top then Close Now continue single stepping by pressing F8 Each time you step the watch expression j will be evaluated and printed in the watch window Note how the value of j advances when the statement j is executed 3 1 3 Breakpoint Move the cursor to the start of the statement for j 0 3 lt 20000 j To set a breakpoint on this statement press F2 or select Breakpoint from the Run menu A red highlight appears on the first character of the statement To get the program running at full speed press F9 or select Run on the Run menu The program will advance until it hits the breakpoint The breakpoint will start flashing both red and green colors To remove the breakpoint press F2 or select Toggle Breakpoint on the Run menu To continue program execution press F9 or select Run from the Run menu Now the counter should
189. iables 236 Dynamic C User s Manual e Use xmem for large RAM buffers xalloc can be used to allocate chunks of RAM in extended memory The memory cannot be accessed by a 16 bit pointer so using it can be more difficult The functions xmem2root and root2xmem are available for moving from root to xmem and xmem to root Large buffers used by Dynamic C libraries are already allocated from RAM in extended memory Chapter 17 Hints and Tips 237 238 Dynamic C User s Manual 18 uC OS II Not available with SE versions of Dynamic C uC OS II is a simple clean efficient easy to use real time operating system that runs on the Rab bit microprocessor and is fully supported by the Dynamic C development environment uC OS II is capable of intertask communication and synchronization via the use of semaphores mailboxes and queues User definable system hooks are supplied for added system and configuration control during task creation task deletion context switches and time ticks For more information on uC OS IL please refer to Jean J Labrosse s book MicroC OS IT The Real Time Kernel ISBN 0 87930 543 6 The data structures e g Event Control Block refer enced in the Dynamic C uC OS II function descriptions are fully explained in Labrosse s book It can be purchased at the Z World store www zworld com store home html or at http www ucos ii com Starting with Dynamic C version 7 21 the Ra
190. in a wait for statement yield The yield statement makes an unconditional exit from a costatement or a cofunction Execu tion continues at the statement following yield the next time the costatement or cofunction is encountered abort The abort statement causes the costatement or cofunction to terminate execution If a cos tatement is always_on the next time the program reaches it it will restart from the top If the costatement is not always_on it becomes inactive and will not execute again until turned on by some other software A costatement can have as many C statements including abort yield and wait for state ments as needed Costatements can be nested 5 4 Advanced Costatement Topics Each costatement has a structure of type CoData This structure contains state and timing infor mation It also contains the address inside the costatement that will execute the next time the pro gram thread reaches the costatement A value of zero in the address location indicates the beginning of the costatement 5 4 1 The CoData Structure typedef struct char CSState unsigned int lastlocADDR char lastlocCBR char ChkSum char firsttime union unsigned long ul struct unsigned int ul unsigned int u2 us content char ChkSum2 CoData 48 Dynamic C User s Manual 5 4 2 CoData Fields CSState The CSState field contains two flags STOPPED and INIT The possible flag values and their meaning are in the
191. ing and house keeping The following table summarizes when to use a TA ISR Table 18 2 Use of TA ISR uC OS II Application Type 1 Type 22 Type 3 TA ISR Required No Yes Yes 1 Type 1 Leaves interrupts disabled and does not signal task to ready state 2 Type 2 Leaves interrupts disabled and signals task to ready state 3 Type 3 Reenables interrupts before completion Chapter 18 nC OS II 243 The following Figure shows the logical flow of a TA ISR Save registers used by TA ISR Clear interrupt source Increment nesting count Do work necessary for interrupt Reenable interrupts optional Call OSIntExit Y Decrement Nesting Count Y Is Nesting 0 Yes No Is switch pending e Restore Registers used by TA ISR Return from interrupt Switch to new task Figure 9 Logical Flow of a TA ISR 244 Dynamic C User s Manual 18 2 3 1 Sample Code for a TA ISR Fortunately the Rabbit BIOS and libraries provide all of the necessary flags to make TA ISRs work With the code found in Listing 1 minimal work is needed to make a TA ISR function correctly with uC OS II TA ISRs allow uC OS II the ability to have ISRs that communicate with tasks as well as the ability to let ISRs nest thereby reducing interrupt l
192. inter 126 127 149 231 pointer SP 122 128 129 136 163 snapshots eseese 204 WINdOW nsesssssesseessreerrsreees 204 STACKSEG vse sicestyseasteeiess 97 state machine example ssseciicisce sees 45 statements eee ee 21 STATIC wrist site dere csetects 153 RAM senetan 4 variables 5 119 122 status register F 204 Stdio window 197 202 203 STDIO_DEBUG_SERIAL 197 Step Oye n Ai 187 stop bits eeseseeseseeresreeree 199 stop program execution 187 storage class eseese 22 AUO Siarra paai eiren eSt 26 default nscersiiist inas 5 T Z S ET Groc esitis 26 27 Sta sasha inns ich 26 SCPI aaia atanapi 207 SINES ool enses 20 157 concatenation eee 20 FUNCTIONS oo eee tees 20 terminating null byte 20 struct keyword oe 153 structure COMPOSItES oo eee eee 26 Keyword 00 eeeeeeeeeeeneeeeeee 22 NESTING 2 05 secede eivedesesies seters 25 offset of element 119 pass by value oe 29 return space 122 128 129 returned by function 128 UNION 5 os sss rest esssccteaviycensteetns 26 subscripts ALL AY esse ese ieeeseeeticentsessesayss 25 support files oo eee 40 SWItCH wee 33 143 154 breaking out of oo 31 CASE priri haie inaina 154 switching to edit mode 184 symbolic constant 0 0 0 0 160 T target communications 199 configuration 201 targetless compilation 185 TCP P un
193. ion program will cause reinitialization of anything that was initialized in the call made by premain 5 3 1 Solving the Real Time Problem with Costatements The Dynamic C costatement provides an easier way to control the tasks It is relatively easy to add a task that checks for the use of an emergency stop button and then behaves accordingly while 1 Costate oso I task 1 costate task 2 waitfor buttonpushed EUeMOmMCeWaLeS I F waitfor DelaySec 60L turnondevice2 waitfor DelaySec 60L EWISIMOic ECE WALES IL 6 turnoffdevice2 GOSIEAEST soo task n The solution is elegant and simple Note that the second costatement looks much like the original description of the problem All the branching nesting and variables within the task are hidden in the implementation of the costatement and its wait for statements 46 Dynamic C User s Manual 5 3 2 Costatement Syntax costate name state statement yield abort waitfor expression The keyword costate identifies the statements enclosed in the curly braces that follow as a cos tatement name can be one of the following e A valid C name not previously used This results in the creation of a structure of type CoData of the same name e The name of a local or global CoData structure that has already been defined e A pointer to an existing structure of type CoData Costatements can be name
194. ion which overrides the defaults Example 1 In this application ten tasks are created and one semaphore is created Each task pends on the semaphore gets a random number posts to the semaphore displays its random number and finally delays itself for three seconds Looking at the code for this short application there are several things to note First since uC OS IL and slice statements are mutually exclusive both rely on the periodic interrupt for a heart beat use ucos2 1lib must be included in every uC OS II application 1 In order for each of the tasks to have access to the random number generator semaphore it is declared as a glo bal variable 2 In most cases all mailboxes queues and semaphores will be declared with global scope Next OSInit must be called before any other uC OS II function to ensure that the operating system is properly initialized 3 Before uC OS II can begin running at least one appli cation task must be created In this application all tasks are created before the operating system begins running 4 It is perfectly acceptable for tasks to create other tasks Next the semaphore each task uses is created 5 Once all of the initialization is done OSStart is called to start uC OS II running 6 In the code that each of the tasks run it is important to note the variable declarations The default storage class in Dynamic C is static so to ensure that the task code is reentrant all a
195. is not defined in the program code it will default to FS_MAX_DEVICES For a description of logical extents please see section 10 4 2 Logical Extents LX on page 108 FS_MAX FILES This macro is used to specify the maximum number of files that are allowed to coexist in the entire file system Most applications will have a fixed number of files defined so this parameter can be set to that number to avoid wasting root data memory The default is 6 files The maximum value for this parameter is 255 FS2_RAM RESERVE This BIOS defined macro determines the amount of space used for FS2 in RAM If some battery backed RAM is to be used by FS2 then this macro must be modified to specify the amount of RAM to reserve The memory is reserved near the top of RAM Note that this RAM will be reserved whether or not the application actually uses FS2 Prior to Dynamic C 7 06 this macro was defined as the number of bytes to reserve and had to be a multiple of 4096 It is now defined as the number of blocks to reserve with each block being 4096 bytes FS2_USE_PROGRAM FLASH The number of kilobytes reserved in the first flash for use by FS2 The default is zero The actual amount of flash used by FS2 is determined by the minimum of this macro and XMEM_RESERVE_SIZE The first flash may be used in FS las well See section 10 2 2 for details XMEM_RESERVE_SIZE This BIOS defined macro is the number of bytes which must be a multiple of 4096 r
196. iseconds then the granularity is 30 to 35 milliseconds Therefore the delay between the occurrence of a wait for event and the statement following the wait for can be as much as the granularity 30 to 35 ms The routine may also be interrupted by higher priority tasks or interrupt routines increasing the variation in delay The consequences of such variations in the time between steps depends on the program s objec tive Suppose that the typical delay between an event and the controller s response to the event is 58 Dynamic C User s Manual 25 ms but under unusual circumstances the delay may reach 50 ms An occasional slow response may have no consequences whatsoever If a delay is added between the steps of a process where the time scale is measured in seconds then the result may be a very slight reduction in throughput If there is a delay between sensing a defective product on a moving belt and activating the reject solenoid that pushes the object into the reject bin the delay could be serious If a critical delay cannot exceed 40 ms then a system will sometimes fail if its worst case delay is 50 ms 5 7 1 waitfor Accuracy Limits If an idle loop is used to implement a delay the processor continues to execute statements almost immediately within nanoseconds after the delay has expired In other words idle loops give pre cise delays Such precision cannot be achieved with wait for delays A particular application may not ne
197. itialized when the function chain __GLOBAL_INIT is called This call is made by premain 5 5 1 Syntax A cofunction definition is similar to the definition of a C function cofunc scofunc type name dim type argl type argN statement yield abort waitfor expression cofunc scofunc The keywords cofunc or scofunc a single user cofunction identify the statements enclosed in curly braces that follow as a cofunction type Whichever keyword cofunc or scofunc is used is followed by the data type returned void int etc name A name can be any valid C name not previously used This results in the creation of a structure of type CoData of the same name dim The cofunction name may be followed by a dimension if an indexed cofunction is being defined cofunction arguments argl argN As with other Dynamic C functions cofunction arguments are passed by value cofunction body A cofunction can have as many C statements including abort yield waitfor and waitfordone statements as needed Cofunctions can contain calls to other cofunctions 52 Dynamic C User s Manual 5 5 2 Calling Restrictions You cannot assign a cofunction to a function pointer then call it via the pointer Cofunctions are called using a wait fordone statement Cofunctions and the wait fordone statement may return an argument value as in the following example int We Sp Sp We Be j waitfordone x Cofuncl
198. itties eahestieae 40 lt CTRL Z gt libraries wo eee 3 37 K SOD nmana 187 prototypes na 23 24 37 key module oo eee 37 lt E10 gt returns sooner 127 128 129 keystrokes Assembly window 202 Saving registers 136 lt ALT Backspace gt lt F2 gt Stack space oo eee 231 undoing changes 182 Toggle Breakpoint 187 transferring control 30 lt ALT C gt lt F3 gt unbalanced stack 136 select Compile menu 185 Find Next oe 184 function lookup lt CTRL H gt lt ALT F gt lt F5 gt 206 207 select Pile meni xs 180 Compile to Target 185 G lt ALT F10 gt F gt Disassemble at Address 190 Trace into 0 eeeeeeees 187 Global Initialization 35 lt ALT F2 gt hoe global variables 0 0 0 0 26 Toggle Hard Breakpoint Step OVET srsrssssssseresserses 187 BONO ots ees 32 146 184 188 13 gt lt ALT F4 gt RUD oi aiora 186 H quitting Dynamic C 182 m aii 127 137 149 151 hard breakpoints 4 188 lt ALTE9 gt abort 137 Run w No Polling seated 186 A ee a AE oe header align 138 lt ALT H gt g Pee eee eee eee eee eee eee FUNCTION oo ee eeeeeeeeteceeeee ee 40 always on 138 select Help menu 205 YS_OM a ETES module eee 37 38 39 A vniem 138 lt ALT O gt y Pere eee eee eee eee eee eee ee Help Menu eceeeeeseeceees 205 e ET EE EEE 139 hexadecimal integer 19 select Options menu 1
199. j i 10 j gets i mod 10 or 3 const int k 11 Jj k 7 j gets k mod 7 or 4 168 Dynamic C User s Manual 13 2 Assignment Operators 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 H F c a gets the result of the calculation a a be 0 b gets O and a gets 0 Addition assignment a 5 Add 5 to a Sameas a a 5 Subtraction assignment a 5 Subtract 5 from a Sameas a a 5 Multiplication assignment a 5 Multiply a by5 Sameasa a 5 Division assignment a 5 Divide a by 5 Sameas a a 5 Modulo assignment o a 5 a mod 5 Sameas a a 5 Left shift assignment a lt lt 5 Shift a left5 bits Sameas a a lt lt 5 Right shift assignment a gt gt 5 Shift a right5 bits Sameas a a gt gt 5 Chapter 13 Operators 16 Bitwise AND assignment a amp b AND a with b Sameas a a amp b Bitwise XOR assignment a be XOR a with b Sameas a a b Bitwise OR assignment a b OR a with b Sameas a a b 13 3 Bitwise Operators Shift left This is a binary operator The result is the value of the left operand shifted by the num ber of bits specified by the right operand int i OxFOOF J i lt lt 4 j gets 0x00FO The most significant bits of the opera
200. lable Please note that if you are compiling to a 128K RAM there is only about 12K available for user code when separate I amp D space is enabled Type Checking This menu item allows the following choices e Prototypes Performs strict type checking of arguments of function calls against the function prototype The number of arguments passed must match the number of param eters in the prototype In addition the types of arguments must match those defined in the prototype Z World recommends prototype checking because it identifies likely run time problems To use this feature fully all functions should have prototypes including functions implemented in assembly e Demotion Detects demotion A demotion automatically converts the value of a larger or more complex type to the value of a smaller or less complex type The increasing order of complexity of 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 All demotion warnings are considered non serious as far as warning reports are concerned e Pointer Generates warnings if pointers to different types are intermixed without type casting While type casting has no effect in straightfo
201. lcall foo_xmem Ifthe assembly function modifies the XPC register with LD XPC A it should not be placed in xmem If it accesses data on the stack directly the data will be one byte away from where it would be with a root function because 1cal1 pushes the value of XPC onto the stack 17 3 2 Increasing Root Data Space Increasing the available amount of root data space may be done in the following ways e Decrease DATAORG Root data space can be increased by decreasing DATAORG in RabbitBios cin increments of 0x1000 This comes at the expense of root code space e Use class auto The default storage class of Dynamic C is static This can be changed to auto using the directive class auto This will make local variables with no explicit storage class specified in functions default to auto If you need the value in a local function to be retained between calls it should be static The default program stack size is 2048 0x800 bytes if not using uC OS II This could be increased to 0x1000 at most It already is increased if the TCP IP stack is used The code to change it is in pro gram 1lib ifndef MCOS define DEFAULTSTACKSIZE 0x1000 increased from 0x800 else define DEFAULTSTACKSIZE 0x200 endif Deeply nested calls with a lot of local auto arrays could exceed this limit but 0x1000 should ordinarily be plenty of space Using more temporary stack space for variables frees up static root data space for global and local static var
202. le in the Figure below the TA ISR increments the interrupt nesting counter does the work necessary for the ISR readies a higher priority task decrements the nesting count and returns to the higher priority task Task 2 Interrupt X r Nesting 1 Interrupt X TA ISR Task 1 is readied Nesting 0 ipres Task 1 Figure 7 Type 2 ISR 242 Dynamic C User s Manual It may seem as though the ISR in this Figure does not have to increment and decrement the nesting count This is however very important If the ISR for Interrupt X is called during an ISR that re enables interrupts before completion scheduling should not be performed when Interrupt X com pletes scheduling should instead be deferred until the least nested ISR completes The next Figure shows an example of this situation Task 2 Interrupt Z Nesting 1 Do critical code Interrupt Z TA ISR ipres Task 1 Interrupt X a Nesting 2 Interrupt X TA ISR Task 1 is readied Nesting 1 ipres Finish ISR Nesting 0 Figure 8 Type 2 ISR Nested Inside Type 3 ISR As can be seen here although the ISR for interrupt Z does not signal any tasks by posting to a semaphore mailbox or queue it must increment and decrement the interrupt nesting count since it re enables interrupts ipres prior to finishing all of its work 18 2 3 General Layout of a TA ISR A TA ISR is just like a standard ISR except that it does some extra check
203. ll bios_intexit pop iy pop be pop de pop hl exx pop af ex af af pop be pop de taisr_noswitch pop ip taisr_done pop hl 12 pop af ipres ret endasm 246 Dynamic C User s Manual 18 3 Library Reentrancy When writing a uwC OS II application it is important to know which Dynamic C library functions are non reentrant If a function is non reentrant then only one task may access the function at a time and access to the function should be controlled with a uC OS II semaphore The following is a list of Dynamic C functions that are non reentrant Library Non reentrant Functions MATH LIB randg randb rand RS232 LIB All RTCLOCK LIB write_rtc tm_wr STDIO LIB kbhit getchar gets getswf selectkey STRING LIB atof atoi strtok lockDoublerOn clockDoublerOff useMainOsc SYS LIB Onalar ai E useClockDivider use32kHzOsc VDRIVER LIB VdGetFreeWd VdReleaseWd XMEM LIB WriteFlash JRIO LIB digOut digOn digOff jrioInit anaIn anaOut cof_anaIn JR485 LIB All 1 reentrant but sets the global _xtoxErr flag The serial port functions RS232 LI1IB functions should be used in a restricted manner with uC OS II Two tasks can use the same port as long as both are not reading or both are not writing i e one task can read from serial port X and another task can write to serial port X at the same time without conflict Cha
204. ll slightly reduce the amount of root ram used With it unchecked the debug kernel will be compiled without watch expressions support and the user will receive an error message if they attempt to add a watch expression Enable Instruction Level Single Stepping If this is checked when the assembly window is open single stepping will be by instruction rather than by C statement Unchecking this box will disable instruction level single stepping on the target and if the assembly window is open the debug kernel will step by C statement 14 2 6 4 Display The Display command gets Dynamic C to display the following dialog Display Options x Window Attribute Error Editor Background Color Debug Editor Foreground Color Message Selection Bg Watch Selection Fg Stdio Help 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 switc
205. llowing special code blocks can appear inside a cofunction everytime statements This must be the first statement in the cofunction It will be executed every time program exe cution passes to the cofunction no matter where the statement pointer is pointing After the everytime statements are executed control will pass to the statement pointed to by the cofunction s statement pointer abandon statements This keyword applies to single user cofunctions only and must be the first statement in the body of the cofunction The statements inside the curly braces will be executed if the single user cofunction is forcibly abandoned A call to Lloophead defined in COFUNC LIB is necessary for abandon statements to execute Example SAMPLES COFUNC COFABAND C illustrates the use of abandon scofunc SCofTest int 1 abandon printf CofTest was abandoned n while i gt 0 oriwer Cotresie Sel ia 2 2 yield main LINE 38 EGE SHO PxxKH1O px 4 loophead aie 2X5 4 costate wid SCofTest 1 first caller costate wid SCofTest 2 second caller In this example two tasks in main are requesting access to SCofTest The first request is hon ored and the second request is held When loophead notices that the first caller is not being called each time around the loop it cancels the request calls the abandonment code and allows the second caller in
206. m run mode also called debug mode After a pro gram has been compiled or executed Dynamic C will not allow any modification to the pro gram unless the Edit Mode is selected The keyboard shortcut is F4 184 Dynamic C User s Manual 14 2 3 Compile Menu Click the menu title or press lt Alt C gt to select the COMPILE menu neem Aun Inspect Options Window Help Compile to Target F5 EET ET Compile to bin file Use attached target Reset Target Compile BIOS Ctrl Compile with defined target configuration Include debug code RST 28 instructions Include BIOS Compile to Target Compiles a program and loads it in the target controller s memory The keyboard shortcut is F5 Dynamic C determines whether to compile to RAM or flash based on the current compiler options set with the Options menu Any compilation errors are listed in the automatically activated message window Hit lt F1 gt to obtain a more descriptive message for any error mes sage that is high lighted in this window Compile to bin file Compiles a program and writes the image to a bin file The bin file can then be used with a device programmer to program multiple chips or the Rabbit Field Utility can load the bin files to the target In most cases the Include BIOS option is checked This causes the BIOS as well as the user program to be included in the bin file If you are creating special program such as a cold loader that starts at address 0x
207. mance tuning e High degree of backwards compatibility with its predecessor This file system known as the filesystem mk II or simply as FS2 uses the same API as the first file system with some additional functions Initialization is performed slightly differently and the data format is not compatible Z World recommends that FS2 be used for all new applications The first file system which we will refer to as FS1 will be maintained but enhancements will only be implemented for FS2 The Dynamic C file system supports a total of 255 files Unlike FS1 it is not possible to reserve a range of file numbers for system use with FS2 Equivalent functionality is available via partition ing of devices The low level flash memory access functions should not be used in the same area of the flash where the flash file system exists 10 1 General Usage The recommended use of a flash file system is for infrequently changing data or data rates that have writes on the order of tens of minutes instead of seconds Rapidly writing data to the flash could result in using up its write cycles too quickly For example consider a 256K flash with 64 blocks of 4K each Using a flash with a maximum recommendation of 10 000 write cycles means a limit of 640 000 writes to the file system If you are performing one write to the flash per second in a little over a week you will use up its recommended lifetime Increase the useful lifetime and performance of the fla
208. may not be acceptable because there is the potential to overflow the stack 7 Return There are three types of interrupt returns ret reti and retn 130 Dynamic C User s Manual 11 7 2 Modifying Interrupt Vectors Prior to Dynamic C 7 30 interrupt vector code could be modified directly By reading the internal and external interrupt registers IIR and EIR the location of the vector could be calculated and then written to because it was located in RAM This method will not work if separate I amp D space is enabled because the vectors must be located in flash To accommodate separate I amp D space the way interrupt vectors are set up and modified has changed slightly Please see the Rabbit 3000 Designer s Handbook for detailed information about how the interrupt vectors are set up This sec tion will discuss how to modify the interrupt vectors after they have been set up For backwards compatibility modifiable vector relays are provided in RAM In C they can be accessed through the SetVectIntern and Set VectExtern functions In assembly they are accessed through INTVEC_BASE lt vector offset gt or XINTVEC_BASE lt vector offset gt The values for lt vector offset gt are defined in sysio 1ib and are listed here for convenience Table 11 20 Internal Interrupts and their offset from INTVEC_BASE PERIODIC_OFS SERA_OFS RST10_OFS SERB_OFS RST18_OFS SERC_OFS RST20_OFS SERD_OFS R
209. mediately after one or more Undo operations The keyboard shortcut is lt Alt Shift Backspace gt 182 Dynamic C User s Manual Cut Removes selected text from a source file 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 short cut is lt Ctrl X gt Copy Makes a copy of selected text in a file or in one of the debugging windows The copy of the text is saved on the clipboard The contents of the clipboard may be pasted virtually any where The keyboard shortcut is lt Ctrl C gt 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 noth ing 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 lt Ctrl V gt Find Finds specified text Enter the text to be found in the Find box The Find command and the Find Next command will find occurrences of the entered text If Case sensitive is clicked the search will find occurrences that match exactly Otherwise the search will find matches having upper and lower case letters For example switch Switch and SWITCH would all match If Reverse is clicked the sea
210. more complicated but will allow you to spend the idle time doing a low priority background task main ine CIme lert long start_time Torka d Stare cime WiiCK WT IUMIINS slice 500 20 4 fj elice a waitfor IntervalTick 80 slice 500 50 4 fi elice b waitfor IntervalTick 105 cimes lerte 75 TTK A IMIR SEA CME if time_left gt 0 slice 500 75 TICK_TIMER start_time slice e 5 10 Summary Although multitasking may actually decrease processor throughput slightly it is an important con cept A controller is often connected to more than one external device A multitasking approach makes it possible to write a program controlling multiple devices without having to think about all the devices at the same time In other words multitasking is an easier way to think about the sys tem Chapter 5 Multitasking with Dynamic C 63 64 Dynamic C User s Manual 6 The Virtual Driver Virtual Driver is the name given to some initialization services and a group of services performed by a periodic interrupt These services are Initialization Services e Call _GLOBAL_INIT e Initialize the global timer variables e Start the Virtual Driver periodic interrupt Periodic Interrupt Services e Decrement software virtual watchdog timers e Hitting the hardware watchdog timer e Increment the global timer variables e Drive uC OS II preemptive multitasking e Drive slice statement
211. mples Break doere 31 Continue sssssssosseeneoseseeeeesee 31 for LOOP sonene onene 30 modules sennnnsosseeneosossseeese 39 Of array ee reersoniee 25 Liian LO a WAE 26 exit Dynamic C we 182 extended memory 4 127 157 asm blocks ceceeeeeeee 121 EXT siino 38 39 144 F file commands eeeeceeeeeee 181 ME Er 180 PANE erine a 181 A A EE EE EA 180 file system oo 99 113 in primary flash 101 104 in RAM 5 3cSccsestenccteisbets 100 multitasking 0 100 Find Next lt F3 gt e 184 firsttime o eee cece eeeeeeeeee 145 float eeens 23 145 157 VALUES ennenen 19 for LOOP ou eee eeeeeeeeeee 30 145 frame reference point 0 0 0 128 reference pointer 126 127 149 231 FUNCTION oo eee ccceeseeeeeeeeeneee 22 assistant 0 ceseceeeeeeseeeee 207 auto variables 000 139 calls o n 22 122 127 128 272 Dynamic C User s Manual calls from assembly 129 keyword for ISR 0 0 147 pasting text we 183 CHAINS soeren 34 151 latent y esirin 130 lt CTRL W gt check parameters 207 toggle state oe 188 Add Del Items 190 create Chains 0 0 162 VECLOLSsensk cessnnvessacesdes cee coses 148 lt CTRL X gt entry and exit we 231 ISR ess 130 234 cutting text we 183 execution time 00 231 IX index register 53 126 127 lt CTRL Y gt Headers nonren 40 149 155 232 Reset target 185 188 Nel pia cesses t
212. n Syntax warns Instructs the compiler to act as if a serious warning was issued The string in quotes following the directive is the message to be printed Syntax warnt Instructs the compiler to act as if a trivial warning was issued The string in quotes following the directive is the message to be printed Syntax ximport filename symbol This compiler directive places the length of filename stored as a long and its binary con tents at the next available place in xmem flash filename is assumed to be either relative to the Dynamic C installation directory or a fully qualified path symbol is a compiler generated macro that gives the physical address where the length and contents were stored The sample program ximport c illustrates the use of this compiler directive 164 Dynamic C User s Manual 13 Operators An operator is a symbol such as or amp that expresses some kind of operation on data Most operators are binary they have two operands a t0 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 oper ations are performed before other operations when there is a choice For example given the expressi
213. n of pure assembly language functions Library functions compiled in debug mode can be single stepped into and breakpoints can be set in them debug int func asm debug endasm 142 Dynamic C User s Manual Identifies the default case in a switch statement The default case is optional It executes only when the switch expression does not match any other case Switch expression case consti case const2 default 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 Indicates a false branch of an if statement if expression statement executes when expression is true else statement executes when expression is false Chapter 12 Keywords 143 Defines a list of named integer constants enum foo white default is O for the first item black willbe 1 brown willbe 2 spotted 2 will be 2 striped will be 3 i An enum can be declared in local or global scope The tag foo is optional but it allows further declarations enum foo rabbits This keyword is available starting with Dynamic C version 7 20 To see a colorful sample run samples enum c 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
214. n with a void return type returns no result If a function is declared without specifying a return type the compiler assumes that it is to return an int integer value A function may call another function including itself a recursive call 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 22 Dynamic C User s Manual 4 11 Prototypes A function may be declared with a prototype This is so that 1 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 func tion receive arguments of the expected type A function prototype describes how to call the function and is nearly identical to the function s ini tial code This is a function prototype long tick coumet clark clock iek Js This is the function s definition long ciek comme Char clock icl Ji It is not necessary to provide parameter names in a prototype but the parameter type is 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 leong tick count Claw Je This is a prototype that uses ellipsis lne starco Ceyica ioy sas IP 4 12 Type Definitions
215. namic C PREMIER For Rabbit Semiconductor Microprocessors Integrated C Development System User s Manual 019 0071 020813 R SE and Premier Editions This manual or an even more up to date revision is available for free download at the Z World website www zworld com ii Table of Contents 1 Installing Dynamic Cu eee 1 Branching scesssecseeseeeseeeteeeseesees 32 1 1 Requirement eeeeeeseeceeeeneceeeeees 1 4 19 Function Chaining 34 1 2 ASSUMPTIONS unsern a e 1 4 20 Global Initialization 222111 11115525212 35 A 4 2 Libraries ca sieeeestiepse ties 36 2 Introduction to Dynamic C 3 4 22 Heathers Seettassiessoutntesighowisteninite 37 2 1 The Nature of Dynamic C cse 3 4 23 MOUle Ssisssscasitansnesiearenteansventoat 37 Speed herori en e a E 3 The Key es ae 37 2 2 Dynamic C Enhancements and The Header csscsssessesseseessereees 38 Differences ni heed Seeks 4 The Body iscsccstccnchsgteiiesisewcrrduer 38 2 3 Dynamic C Differences Between Rabbit Function Description Headers 40 and ZIO aeae aieia eai ei iea 6 4 24 Support Files cccccsccsessesseseseeeseene 40 3 Quick Tutorials ances ata el oes Ff 5 Multitasking with Dynamic Cee LG 43 3 1 Run DEMOL C oeenn 7 5 1 Cooperative Multitasking etal Bild te 43 Single Stepping eeseeeeececien 9 5 2 A Real Time Problem ss0 45 Watch Expression cceeeeeeeeeees 9 Solving
216. nd 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 num ber of bits specified by the right operand int i OxFOOF j i gt gt 4 j gets OxFFOO The least significant bits of the operand are lost the vacated bits become zero for unsigned vari ables and are sign extended for signed variables Address operator or bitwise AND As a unary operator this provides the address of a variable int x Z amp X z 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 Ox0OFFF z i6 j z gets OxOFFO ok 70 Dynamic C User s Manual 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 Ox0OFFF z i J z gets OxFOOF Bitwise inclusive OR A binary operator this performs the bitwise OR of two integer 8 bit 16 bit or 32 bit values int i OxFF00 int j Ox0FFO z i j z gets OxFFFO Bitwise complement This is a unary operator Bits ina char int or Long value are inverted int switches switches OxFFFO j switches j becomes 0x000F 13 4 Relational Operators Less than This binary relational operator yields a Boolean value The result is 1 if the left oper and is less than the right operand and 0 otherwise if i lt gj
217. ne Assembly Code in Extended Memory Starting with Dynamic C 7 25 stand alone assembly functions may be placed in extended memory by adding the xmem keyword as a qualifier to asm as shown below Care needs be taken to make sure that branch instructions do not jump beyond the current xmem window To help prevent such bad jumps the compiler limits xmem assembly blocks to 4096 bytes Code that branches to other assembly blocks in xmem should always use 1 jp or 1call asm xmem main lcall fcn_in_xmem lret endasm asm xmem fcn_in_xmem lret endasm 11 3 2 Example of Stand Alone Assembly Code The stand alone assembly function foo can be called from a Dynamic C function int foo int z A function prototype can be declared for stand alone assembly functions which will cause the compiler to perform the appropriate type checking main int i j i 1 j foo i fasm foo ld hl 2 The return value expected by main is put ret in HL just before foo returns endasm The entire program can be written in assembly asm main ret endasm Chapter 11 Using Assembly Language 121 11 4 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 11 4 1 The Stack Frame The purpos
218. ng SPsetHandler 5 SPserAhandler NULL 7 3 2 3 Master Side of Protocol The following functions are in Master_serial 1ib They are for a master using a serial port handler on a slave int cof_MSgetc char address DESCRIPTION Yields to other tasks until a byte is received from the serial port on the slave PARAMETERS address Slave channel address of the serial handler RETURN VALUE Value of the received character on success 1 Failure LIBRARY MASTER_SERIAL LIB void cof_MSputc char address char ch DESCRIPTION Sends a character to the serial port Yields until character is sent PARAMETERS address Slave channel address of serial handler ch Character to send RETURN VALUE 0 Success character was sent 1 Failure character was not sent LIBRARY MASTER_SERIAL LIB 76 Dynamic C User s Manual int cof_MSread char address char buffer int length unsigned long timeout DESCRIPTION Reads bytes from the serial port on the slave into the provided buffer Waits until at least one character has been read Returns after buffer is full or t imeout has expired be tween reading bytes Yields to other tasks while waiting for data PARAMETERS address Slave channel address of serial handler buffer Buffer to store received bytes length Size of buffer timeout Time to wait between bytes before giving up on receiving anymore RETURN VALUE gt 0 Bytes read
219. ngs dccl_cmp pf myProject shows the current state of allmyProject dcp settings dccl_cmp myProgram c ne 25 pf myProject reads myProject dcp then compiles and runs myProgram c but with 25 errors maximum shown The command line compiler unlike Dynamic C never updates the project file it uses Any changes desired to a project file to be used by the command line compiler can be made within Dynamic C or changed by hand with an editor Making changes by hand should be done with caution using an editor which does not introduce carriage returns or line feeds with wordwrap which may be a problem if the global defines or any file pathnames are lengthy strings Be careful when changing by hand not to change any of the section names in brackets or any of the key phrases up to and including the If a macro is defined on the command line with the d switch any value that may have been defined within the project file used will be overwritten without warning or error Undefining a macro with the d switch has no consequence if it was not previously defined Chapter 16 Project Files 229 230 Dynamic C User s Manual 17 Hints and Tips This chapter offers hints on how to speed up an application and how to store persistent data at run time 17 1 Efficiency There are a number of methods that can be used to reduce the size of a program or to increase its speed Let s look at the events that occur when a program enters a fun
220. ns Now press lt Ctrl U gt Each time you press lt Ctrl U gt you will see the current value of k As an experiment add another expression to the watch window k 5 Then press lt Ctrl U gt several times to observe the watch expressions k and k 5 3 3 Run DEMO3 C The example below sample program DEMO3 C uses costatements A costatement is a way to perform a sequence of operations that involve pauses or waits for some external event to take place 3 3 1 Cooperative Multitasking Cooperative multitasking is a way to perform several different tasks at virtually the same time An example would be to step a machine through a sequence of tasks and at the same time carry on a dialog with the operator via a keyboard interface Each separate task voluntarily surrenders its compute time when it does not need to perform any more immediate activity In preemptive multi tasking control is forcibly removed from the task via an interrupt Dynamic C has language extensions to support both types of multitasking For cooperative multi tasking the language extensions are costatements and cofunctions Preemptive multitasking is accomplished with slicing or by using the uC OS II real time kernel that comes with Dynamic C Premier Advantages of Cooperative Multitasking Unlike preemptive multitasking in cooperative multitasking variables can be shared between dif ferent tasks without taking elaborate precautions Cooperative multitasking also tak
221. nsate for altered SP acel Init sie compute as normal Le ap all get the content pop hl restore HL SP again points to the low boundary of the call frame Registers not preserved In Dynamic C the caller is responsible for saving and restoring all reg isters An assembly routine that calls a C function must assume that all registers will be changed Unpreserved registers in interrupt routines cause unpredictable and unrepeatable problems In con trast to normal functions interrupt functions are responsible for saving and restoring all registers themselves 136 Dynamic C User s Manual 12 Keywords A keyword is a reserved word in C that represents a basic C construct It cannot be used for any other purpose There are many keywords and they are summarized in the following pages Used in single user cofunctions abandon must be the first statement in the body of the co function The statements inside the curly braces will be executed only if the cofunction is forc ibly abandoned and if a call to Loophead is made in main before calling the single user cofunction See Samples Cofunc Cofaband c for an example of abandonment handling Jumps out of a costatement for costate if condition abort Chapter 12 Keywords 137 Used in assembly blocks the align keyword outputs a padding of nops so that the next instruc tion to be compiled is placed at the boundary based on VALUE asm align lt
222. nstruction assuming no wait states The total cycle time for a block of instructions will be shown at the lowest row in the block in the cycle time column if that block is selected and highlighted with the mouse The total assumes one execu tion per instruction so the user must take looping and branching into consideration when eval uating execution times Use the mouse to select several lines in the Assembly window and the total cycle time for the instructions that were selected will be displayed to the lower right of the selection If the total includes an asterisk that means an instruction such as ldir or ret nz with an indetermi nate cycle time was selected Chapter 14 Graphical User Interface 203 Registers Click the Registers command to activate or deactivate the Register window The Register window displays the processor register set including the status register Letter codes indicate the bits of the status register F register The window also shows the source code line and col umn at which the snapshot of the register was taken It is possible to scroll back to see the pro gression of successive register snapshots Registers may be changed when program execution is stopped by clicking the right mouse button over the name or value of the register to be changed Registers PC XPC and SP may not be edited as this can adversely effect program flow and debugging n Registers lolx Stack Click the Stack command to ac
223. nted 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 Message Click the Message command to activate or deactivate the Message window A compilation with errors also activates the message window because the message window displays compila tion errors 202 Dynamic C User s Manual Watch The Watch menu option activates or deactivates the watch window The Add Del Items com mand on the INSPECT menu will do this too The watch window displays the results when ever Dynamic C evaluates watch expressions Stdio Click the Stdio command to activate or deactivate the Stdio window The Stdio window dis plays output from calls to printf If the program calls printf Dynamic C will activate the Stdio window automatically unless another request was made by the programmer See the Debugger Options under the OPTIONS menu Assembly Click the Assembly command to activate or deactivate 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 also activate the Assembly window A Disassembled Code Of x The Assembly window shows the memory address on the far left followed by the code bytes for the instruction at the address followed by the mnemonics for the instruction The last col umn shows the number of cycles for the i
224. nter Depending on the printer selected it may be possible to specify paper orientation por trait or tall vs landscape or wide and paper size Most printers have these options A specific printer may or may not have more than one paper source The Options button allows the print options dialog to be displayed for a specific printer The Network button allows printers to be added or removed from the list of printers 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 lt Alt F4 gt 14 2 2 Edit Menu Click the menu title or press lt Alt E gt to select the EDIT menu File Compile Run Inspect Option i gl Undo Alt Bksp Redo Shift Alt Bksp Cut Ctrl X Copy Ctrl C Paste Ctrl V Find Ctrl F Replace F6 Find Next F3 Goto Ctrl G Previous Error Giri Next Error Ciri N EditMode F4 Undo This option undoes recent changes in the active edit window The 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 opera tions or many lines of typing Dynamic C discards all undo information for an edit window when the file is saved The keyboard shortcut is lt Alt Backspace gt Redo Redoes modifications recently undone This command only works im
225. o bin file is selected GUI Equivalent Uncheck the Compile Compile to bin file Include BIOS menu option rd Description Do not include debug RST 28 code when compiling to a file This option is ignored if not compiling to a file This switch is available only in Dynamic C v 7 05 and 7 06 Default RST 28 is included if Compile to file is selected GUI Equivalent Uncheck the Compile Compile to bin file Include debug code RST 28 instructions menu option rd Available starting with Dynamic C v 7 10 Description Include debug code when compiling to a file Default RST 28 instructions are included GUI Equivalent Check the Compile Compile to bin file Include debug code RST 28 instructions menu option Chapter 15 Command Line Interface 213 rd Available starting with Dynamic C v 7 10 Description Do not include debug code when compiling to a file This option is ignored if not compiling to a file Default RST 28 instructions are included GUI Equivalent Uncheck the Compile Compile to bin file Include debug code RST 28 instructions menu option rf Available starting with Dynamic C v 7 10 Description Undo RTI file specification Default None GUI Equivalent Select the Compile Compile to Target menu option ri Description Disable runtime checking of array indices This switch is available only in Dynamic C v 7 05 and 7 06 Default Runtime checking of array indices is performe
226. oating point The operators are summarized in the following pages 13 1 Arithmetic Operators Unary plus or binary addition Standard C does not have unary plus Unary plus does not really do anything a b 10 5 binary addition z y jast for emphasis Unary minus or binary subtraction a b 10 5 binary subtraction z y z gets the negative of y 166 Dynamic C User s Manual Indirection or multiplication As a unary operator it indicates indirection When used in a declara tion indicates that the following item is a pointer When used as an indirection operator in an expression provides the value at the address specified by a pointer int py p isa pointer to an integer const int j 45 p amp j p 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 Sameas j 25 since p pointsto j Beware of using uninitialized pointers Also the indirection operator can be used in complex ways int list 10 array of 10 pointers to integers int list 10 pointer to array of 10 integers float y pointer to a pointer toa float Zz y z gets the value of y typedef char stp stp my_stuff my_stuff istyped char As a binary operator the indicates multiplication a b c a gets the productof b and c Divide is a binary operator Integer division truncates floating point divi
227. ocal variables is fairly inefficient The efficiency improves if IX is used as a frame pointer The arguments will have slightly different offsets because of the additional two bytes for the saved IX register value Now access to stack variables is easier Consider for example how to load ch into register A lel ay irem aech The IX offset load instruction takes 9 clock cycles and opcode is three bytes If the program needs to load a four byte variable such as 1g the IX offset instructions are as follows Ta hi ix lg 2 load LSB of 1g Lel a n longs are normally stored in BC DE Tel th ie tad IELI load MSB of 1g ex de hl This takes a total of 24 cycles 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 accessing vari ables out of this range The SP symbol may be used even if IX is the frame reference pointer 126 Dynamic C User s Manual 11 4 3 2 Functions in Extended Memory If the xmem keyword is present Dynamic C compiles the function to extended memory Otherwise Dynamic C determines where to compile the function Functions compiled to extended memory have a 3 byte return address instead of a 2 byte return address 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 me
228. of the if statement An else clause is optional Without an else clause an if else if state ment 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 Switch expression Case Const Staecememe sy break CASS Const statements break case const3 statements3 break default statement SDEFAULT First the switch expression is evaluated It must have an integer value If one of the consty values matches the switch expression the sequence of statements identified by the consty Chapter 4 Language 33 expression is executed If there is no match the sequence of statements identified by the default label is executed The default part is optional Unless the break keyword is included at the end of the case s statements the program will fall through and execute the state ments for any number of other cases The break keyword causes the program to exit the switch case statement The colons after break case and default are required 4 19 Function Chaining Function chaining 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 and other kinds of tasks on request There ar
229. 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 LE 88 aime C32 5 array in structure 1 node node Lise 12 array of structures Refer to an element of array c above as shown here Ibi st in E lim s List O e l22 Oxarw37 4 14 Storage Classes Variable storage can be auto or static The default storage class is st atic but can be changed by using class auto The default storage class can be superseded by the use of the keyword auto or static ina variable declaration 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 available anywhere in the program but there is no keyword in C to represent this fact Global variables always have st atic storage The term st at ic 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 26 Dynamic C User s Manual 4 15 Pointers A pointer is a variable that holds the 16 bit logical address of another variable a structure or a function Dynamic C does not currently support long pointers The indirection operator is used to declare a variable as a pointer The address operator amp is used to set the pointer to th
230. oint Watch Expressions A watch expression is a C expression that is evaluated on command in the watch window An expression is basically any type of C formula that can include operators variables and function calls but not statements that require multiple lines such as for or switch You can have a list of watch expressions in the watch window If you are single stepping then they are all evaluated on each step You can also command the watch expression to be evaluated by using the lt Ctrl U gt command When a watch expression is evaluated at a breakpoint it is evaluated as if the statement was at the beginning of the function where you are single stepping If your program is running you can also evaluate watch expressions with a lt Ctrl U gt if your program has a runwatch com mand that is frequently executed In this case only expressions involving global variables can be evaluated and the expression is evaluated as if it were in a separate function with no local vari ables Costatements A costatement is a Dynamic C extension that allows cooperative multitasking to be programmed by the user Keywords like abort and wait for are available to control multitasking operation from within costatements 12 Dynamic C User s Manual 4 Language Dynamic C is based on the C language The programmer is expected to know programming meth odologies and the basic principles of the C language Dynamic C has its own set of libraries whic
231. ointer for run time errors to the one passed to it When a run time error occurs exception pushes onto the stack the information detailed in the table below Table 8 13 Stack setup for run time errors Address Data at address SP 0 Return address for error handler SP 2 Error code SP 4 Additional data user defined XPC when exception was called upper SP 6 byte SP 8 Address where exception was called from Then exception calls the installed error handler If the error handler passes the run time error to Dynamic C i e it is a fatal error and the system needs to be halted or reset then registers must be loaded appropriately before calling the _xexit function Dynamic C expects the following values to be loaded Table 8 14 Register contents loaded by error handler before passing the error to Dynamic C Register Expected Value H XPC when exception was called L Run time error code HL Address where exception was called from Chapter 8 Run Time Errors 93 8 3 Run Time Error Logging Starting with Dynamic C 7 05 error logging is available as a BIOS enhancement for storing run time exception history It can be useful diagnosing problems in deployed Rabbit targets To sup port error logging the target must have battery backed RAM 8 3 1 Error Log Buffer A circular buffer in extended RAM will be filled with the following information for each run time er
232. on s body 5 5 5 2 Indexed Cofunction An indexed cofunction allows the body of a cofunction to be called more than once with different parameters and local variables The parameters and the local variable that are not declared static have a special lifetime that begins at a first time call of a cofunction instance and ends when the last curly brace of the cofunction is reached or when an abort or return is encountered The indexed cofunction call is a cross between an array access and a normal function call where the array access selects the specific instance to be run Typically this type of cofunction is used in a situation where N identical units need to be con trolled by the same algorithm For example a program to control the door latches in a building could use indexed cofunctions The same cofunction code would read the key pad at each door compare the passcode to the approved list and operate the door latch If there are 25 doors in the building then the indexed cofunction would use an index ranging from 0 to 24 to keep track of which door is currently being tested An indexed cofunction has an index similar to an array index WALEEGccome LCeiume in 2 5 5 ICetuMe2 im ssop The value between the square brackets must be positive and less than the maximum number of instances for that cofunction There is no runtime checking on the instance selected so like arrays the programmer is responsible for keeping this value in the p
233. on e s o ap e x O will the or the be performed first Since has higher precedence than it will be performed first The expression is equivalent to a Jo ar ee O Parentheses can be used to force any order of evaluation The expression a Io a e TO 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 el Io ae ee op b c performed first a e eNA now c d is performed first Tine a F function returning ptr to int ime 7a 1 ptr to function returning int Unary operators and assignment operators associate from right to left Most other operators associ ate from left to right Certain operators namely amp gt and dot can be used on the left side of an assignment to construct what is called an value For example close xP aomen 5 Ox lt il 7 5 low byte of x gets value Chapter 13 Operators 165 When the data types for an operation are mixed the resulting type is the more precise loat Xp We 2p aime a J lee char e B i f Rp sameas float i x a ee t e sameas 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 con verted to fl
234. on of these functions please refer to the Dynamic C s TCP IP User s Man ual or use lt Ct r1 H gt in Dynamic C to use the Library Lookup feature Table 10 17 Flash File System Auxiliary Functions Command Description Associate a name with the flash file system file number The return sspec_addfsfile value is an index into an array of structures associated with the named files Read a file represented by the return value of fil pepe sedi sspec_addfsfile into a buffer sspec_getlength Get the length number of bytes of the file Get the file system file number 1 255 Cast return value to filel sspec_getfileloc ILENUMBER Find the index into the array of structures associated with named files of the file that has the specified name sspec_findname Get file type For flash file system files this value will be SSPEC_FSFILE sspec_getfiletyp 110 Dynamic C User s Manual Table 10 17 Flash File System Auxiliary Functions Command Description sspec_findnextfile Find the next named file in the flash file system at or following the specified index and return the index of the file sspec_remove Remove the file name association SSpec_save Saves to the flash file system the array of structures that reference the named files in the flash file system sspec_restore Restores the array of structures that reference
235. onstants are Maximum number of events semaphores queues mailboxes define OS_MAX_EVENTS 10 Maximum number of tasks less stat and idle tasks define OS_MAX TASKS 10 Maximum number of queues in system define OS_MAX_QS 2 Maximum number of memory partitions define OS_MAX_MEM PART 1 Enable normal task creation define OS_TASK_CREATE_EN 1 Disable extended task creation defineOS_TASK_ CREATE _EXT_EN 0 Disable task deletion define OS TASK _DEL_EN 0 Disable statistics task creation define OS_TASK_STAT_EN 0 Enable queue usage define OS _Q EN 1 Disable memory manager define OS_MEM_EN 0 Enable mailboxes define OS _MBOX_EN 1 248 Dynamic C User s Manual Enable semaphores define OS_SEM_EN 1 number of ticks in one second define OS_TICKS_PER_SEC 64 number of 256 byte stacks idle task stack define STACK_CNT_256 1 number of 512 byte stacks task stacks initial program stack define STACK_CNT_512 OS_MAX_TASKS 1 If a particular portion of uC OS II is disabled the code for that portion will not be compiled mak ing the overall size of the operating system smaller Take advantage of this feature by customizing uC OS II based on the needs of each application 18 4 2 Custom Configuration In order to customize uC OS II by enabling and disabling components of the operating system simply redefine the configuration constants as necessary fo
236. ontinue and Break Two keywords are available to help in the construction of loops cont inue and break The continue statement causes the program control to skip unconditionally to the next pass of the loop In the example below if bad is true more statements will not execute control will pass back to the top of the while loop get_char while EOF some statements iE bacil Continus more statements The break statement causes the program control to jump unconditionally out of a loop In the example below if cond_RED is true more statements will not be executed and control will pass to the next statement after the ending curly brace of the for loop oie a Opi lt iap aspse f some statements Lit COMELINTD loirealcs more statements 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 Chapter 4 Language 31 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 towl sO Pa lt inp as 4 some statements iit COmel_ Ia Gore we some statements Li coce RLU Gore 2227 more statements yyy handle cond_RED Vhs Th Thy amp handle code_BLUE 4 18 3
237. or sale of the Software except upon the terms and conditions specified herein Any addi tional or different terms or conditions proposed by You or contained in any purchase order are hereby rejected and shall be of no force and effect unless expressly agreed to in writing by Z WORLD No amendment to or modification of this License will be binding unless in writing and signed by a duly authorized representative of Z WORLD Copyright 2000 Z World Inc All rights reserved 270 Dynamic C User s Manual Index Symbols and operators 17 HAS eein 115 159 232 debug eee 149 159 232 define oo 16 17 160 HOLE erasoan 161 aa E AAE S PEE AET 161 endasm 0000 115 119 160 HODGE Kearen EA 161 HOITOM nint dies 161 fatal sere errn eei 160 funcchain cccceeeeees 34 161 FELL perrin ne 161 FILMED hoses oehaceee anete 162 FINE Faresa 162 include absence Of ceeeeeeeeeseeees 36 interleave 0 0 eee ceeeeeeeeeee eens 162 HRIC Si cbocecstesevecssstsderecstseets 162 makechain 006 34 162 memmap eee 4 162 234 nodebug 149 159 186 232 nointerleave ceceeeeeees 162 FMOUSEIX ccceceeeccecesseceeeeeeeees 163 PUNCEL ennui 19 HUSE ceviche 36 38 163 HUISCAX yeei aee seereis 163 HPWALDS saranani 164 AWALDK aienea 164 FXIMPOLt 2 0 eects eeeeee 164 RETVAL eee 128 SP 122 126 127 128 136 _GLOBAL_INIT
238. or watch update requests and should be called periodically if watch expressions are used Normally the Watch window is updated every time the execution cursor is changed that is when a single step a breakpoint or a stop occurs in the program The key board shortcut is lt Ctrl U gt Disassemble at Cursor Loads disassembles and displays the code at the current editor cursor This command does not work in user application code declared as nodebug Also this command does not stop the execution on the target The keyboard shortcut is lt Ctrl F10 gt 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 or a 2 digit page number followed by a colon followed by a 4 digit logical address from 00 to FF The keyboard shortcut is lt Alt F10 gt Dump at Address Allows blocks of raw values in any memory location except the BIOS 0 2000H to be looked at Values can be displayed on the screen or written to a file If separate I amp D space is enabled you can choose which logical space to examine Dynamic C User s Manual Dump at Address tc k E H Bytes Dec rile Py e Code f Data When writing to a file the option Dump to File requires a file pathname and the numb
239. ou want to overwrite instead Dynamic C automatically opens the STDIO window when a program first attempts to print to it if a check appears in the checkbox labeled Auto Open STDIO Window The last three checkboxes allow the user to control the size and capabilities of the debug kernel The debug kernel has grown significantly in size so if there are tight code space requirements parts of the debug kernel can be disabled to save room The three checkboxes are Enable Breakpoints If this box is checked the debug kernel will be able to toggle breakpoints on and off and will be able to stop at set breakpoints Using the scroll bar to the right of Max breakpoints one may enter up to the maximum amount of breakpoints the debug kernel will support The debug kernel uses a small amount of root ram for each breakpoint so reducing the number of breakpoints will slightly reduce the amount of root ram used If this box is unchecked the debug kernel will be compiled without breakpoint support and the user will receive an error message if they attempt to add a breakpoint Chapter 14 Graphical User Interface 197 Enable Watch Expressions If this is checked watch expressions will be enabled Using the scroll bar to the right of Max watch expressions enter up to the maximum amount of watch expressions the debug kernel will support The debug kernel uses a small amount of root ram for evaluating each watch expression so reducing the amount of watches wi
240. p may be omitted pw TCPPassPhrase Description Enter the passphrase required for your TCP IP connection If no passphrase is required this option need not be used Default No passphrase GUI Equivalent Enter the passphrase required at the dialog prompt when compiling over a TCP IP connection Example dccl_cmp myProgram c pw My passphrase 222 Dynamic C User s Manual ret Retries Available starting with Dynamic C v 7 10 Description The number of times Dynamic C attempts to establish communication if the given timeout period expires Default 3 GUI Equivalent None Example dccl_cmp myProgram c ret 5 rf RTIFilePathname Description Compile to a bin file using targetless compilation parameters found in RTI FilePathname The resulting compiled file will have the same pathname as the source c file being compiled but with a bin extension Default None GUI Equivalent For Dynamic C v 7 05 and 7 06 select the Compile Compile to bin file Define target information Use Target Information File menu option For Dynamic C v 7 10 and later select the Options Define target configuration Use Target Information File menu option Example dccl_cmp myProgram c rf MyTCparameters rti dccl_cmp myProgram c rf My Long Pathname MyTCpa rameters rti Chapter 15 Command Line Interface 223 rti BoardID CpulD CrystalSpeed RAMSize FlashSize Description Default GUI Equivalent Example
241. ple projects LIB DIR These files hold the default compilation environment that is shipped from the factory DEFAULT DCP may be modified but not PROJECT DCP See Chapter 16 for details on project files PROJECT DCP DEFAULT DCP 40 Dynamic C User s Manual Chapter 4 Language 41 42 Dynamic C User s Manual 5 Multitasking with Dynamic C A task is an ordered list of operations to perform In a multitasking environment more than one task each representing a sequence of operations can appear to execute in parallel In reality a single processor can only execute one instruction at a time If an application has multiple tasks to perform multitasking software can usually take advantage of natural delays in each task to increase the overall performance of the system Each task can do some of its work while the other tasks are waiting for an event or for something to do In this way the tasks execute almost in par allel There are two types of multitasking available for developing applications in Dynamic C preemp tive and cooperative In a cooperative multitasking environment each well behaved task voluntar ily gives up control when it is waiting allowing other tasks to execute Dynamic C has language extensions costatements and cofunctions to support cooperative multitasking Preemptive multi tasking is supported by the slice statement which allows a computation to be divided into small sli
242. preemptive multitasking 6 1 Default Operation The user should be aware that by default the Virtual Driver starts and runs in a Dynamic C pro gram without the user doing anything This happens because before main is called a function called premain is called by the Rabbit kernel BIOS that actually calls main Before premain calls main it calls a function named VdInit that performs the initializa tion services including starting the periodic interrupt If the user were to disable the Virtual Driver by commenting out the call to VdInit in premain then none of the services performed by the periodic interrupt would be available Unless the Virtual Driver is incompatible with some very tight timing requirements of a program and none of the services performed by the Virtual Driver are needed it is recommended that the user not disable it 6 2 Calling GLOBAL_INIT VdInit calls _GLOBAL_INIT which runs all GLOBAL_INIT sections in a program _GLOBAL_INIT also initializes all of the CoData structures needed by costatements and cofunctions If VdInit is not called users could still use costatements and cofunctions if the call to VdInit was replaced by a call to__GLOBAL_INIT but the DelaySec and DelayMs functions often used with costatements and cofunctions in wait for statements would not work because those functions depend on timer variables which are maintained by the periodic interrupt Chapter 6
243. provided however any agreement entered into between You and such end users with respect to a Qualified Application is no less protective of Z Worlds intellectual property rights than the terms and conditions of this License iv use and distribute with Qualified Applications and Qualified Systems the program files distributed with Dynamic C named RFU EXE PILOT BIN and COLDLOAD BIN in their unaltered forms 3 Restrictions Except as otherwise stated You may not nor permit anyone else to decompile reverse engineer disassemble or otherwise attempt to reconstruct or discover the source code of the Software alter merge modify translate adapt in any way prepare any derivative work based upon the Software rent lease network loan distribute or otherwise transfer the Software or any copy thereof You shall not make copies of the copyrighted Software and or documenta tion without the prior written permission of Z WORLD provided that You may make one 1 hard copy of such documentation for each User and a reasonable number of back up copies for Your own archival purposes You may not use copies of the Software as part of a benchmark or comparison test against other similar products in order to produce results strictly for purposes of comparison The Software contains copyrighted material trade secrets and other proprietary material of Z WORLD and or its licensors and You must reproduce on each copy of the Soft ware all copyright notices
244. pter 18 nC OS II 247 18 4 How to Get a WC OS II Application Running uC OS II is a highly configureable real time operating system It can be customized using as many or as few of the operating system s features as needed This section outlines e The configuration constants used in uC OS II e How to override the default configuration supplied in UCOS2 LIB e The necessary steps to get an application running It is assumed that the reader has a familiarity with uwC OS II or has a uC OS II reference MicroC OS II The Real Time Kernel by Jean J Labrosse is highly recommended 18 4 1 Default Configuration uC OS II usually relies on the include file os_cfg h to get values for the configuration con stants In the Dynamic C implementation of uC OS II these constants along with their default values are in os_cfg 1lib A default stack configuration is also supplied in os_cfg 1ib uC OS II for the Rabbit uses a more intelligent stack allocation scheme than other uC OS II implementations to take better advantage of unused memory The default configuration allows up to 10 normally created application tasks running at 64 ticks per second Each task has a 512 byte stack There are 2 queues specified and 10 events An event is a queue mailbox or semaphore You can define any combination of these three for a total of 10 If you want more than 2 queues however you must change the default value of OS_MAX_OS Some of the default configuration c
245. pter 5 Multitasking with Dynamic C 57 Some tasks may not have an end They are endless loops For example a task to control a servo loop may run continuously to regulate the temperature in an oven If there are a a number of tasks that need to run continuously then they can be called using a single wait fordone statement as shown below costate WelTiEiorcdomes Baski Wask2 e kaS kS Or Waska p to come here is an error Each task will receive some execution time and assuming none of the tasks is completed they will continue to be called If one of the cofunctions should abort then the wait fordone state ment will abort and corrective action can be taken 5 7 Timing Considerations In most instances costatements and cofunctions are grouped as periodically executed tasks They can be part of a real time task which executes every n milliseconds as shown below using costate ments enter every n milliseconds costate costate costate costate Figure 2 Costatement as Part of Real Time Task If all goes well the first costatement will be executed at the periodic rate The second costatement will however be delayed by the first costatement The third will be delayed by the second and so on The frequency of the routine and the time it takes to execute comprise the granularity of the routine If the routine executes every 25 milliseconds and the entire group of costatements executes in 5 to 10 mill
246. r data int length DESCRIPTION Sends an array of bytes out the serial port on the slave behaves like serXwrite PARAMETERS address Slave channel address of serial handler data Array of bytes to send length Size of array RETURN VALUE Number of bytes actually sent LIBRARY MASTER_SERIAL LIB Chapter 7 The Slave Port Driver 83 7 3 2 4 Sample Program for Master This sample program Samples SlavePort master_demo c treats the slave like a serial port use master_serial lib define SP_CHANNEL 0x42 char const test_str Hello There main char buffer 100 int read_length MSinit 0 comment this line out if talking to a stream handler printf open returned 0x x n MSopen SP_CHANNEL 9600 while 1 costate wfd cof_MSwrite SP_CHANNEL test_str strlen test_str wfd cof_MSwrite SP_CHANNEL test_str strlen test_str costate wfd read_length cof_MSread SP_CHANNEL buffer 99 10 if read_length gt 0 buffer read_length 0 null terminator printf Read s n buffer else if read_length lt 0 printf Got read error d n read_length printf wrfree d n MSwrFree SP_CHANNEL 84 Dynamic C User s Manual 7 3 3 Byte Stream Handler The library SP_STREAM LIB implements a byte stream over the slave port If the master is a Rabbit the functions in MASTER_SERIAL LIB can be used to access
247. r to read and write certain internal registers on the Rabbit The library SLaveport lib imple ments a complete master slave protocol for the Rabbit slave port Sample libraries Master_serial lib and Sp_stream 1ib provide serial port and stream based communi cation handlers using the slave port protocol 7 1 Slave Port Driver Protocol Given the variety of embedded system implementations the protocol for the slave port driver was designed to make the software for the master controller as simple as possible Each interaction between the master and the slave is initiated by the master The master has complete control over when data transfers occur and can expect single immediate responses from the slave 7 1 1 Overview 1 Master writes to the command register after setting the address register and optionally the data register These registers are internal to the slave 2 Slave reads the registers that were written by the master 3 Slave writes to command response register after optionally setting the data register This also causes the SLAVEATTN line on the Rabbit slave to be pulled low 4 Master reads response and data registers 5 Master writes to the slave port status register to clear interrupt line from the slave 7 1 2 Registers on the Slave From the point of view of the master the slave is an I O device with four register addresses Table 7 7 The slave registers that are accessible by the master
248. r SetVectExtern3000 touse interrupt_vector instead The following code from Samples TIMERB TIMER_B C illustrates the change that should be made void main if _ SEPARATE_INST_DATA__ interrupt_vector timerb_intvec timerb_isr else SetVectIntern 0x0B timerb_isr setup ISR endif If interrupt_vector is used multiple times for the same interrupt vector the last one encountered by the compiler will override all previous ones interrupt_vector is syntactic sugar for using the origin directives and assembly code For example the line interrupt_vector timerb_intvec timerb_isr is equivalent to rcodorg timerb_intvec apply asm jp timerb_isr endasm rcodorg rootcode resume 134 Dynamic C User s Manual The following table lists the defined interrupt vector names that may be used with interrupt_keyword as well as their corresponding ISRs Table 12 Interrupt Vector and ISR Names Interrupt Vector Name ISR Name Default Condition periodic_intvec periodic_isr Fast and nonmodifiable rstl0_intvec User defined name User defined rst18_intvec rst20_intvec rst28_intvec These interrupt vectors and their ISRs should never be altered by the user because they are reserved for the debug kernel rst38_intvec User defined name User defined slave_intvec slave_isr Fast and nonmodifiable timera_intvec User defined name
249. r not to include the BIOS when compiling to a bin file This is set in the Compile menu _SECTOR_SIZE_ In all versions prior to Dynamic C 7 02 this macro near the top of LIB BIOSLIB FLASHWR LIB needs to be hard coded to the sector size of the first flash in bytes _TARGETLESS COMPILE _ Boolean value This is set in the Compile menu It defaults to 0 TIME The compiler substitutes this macro with the time that the file BIOS or c was compiled The character string literal is of the form hh mm ss _USE115KBAUD _ Boolean value Tells BIOS to use 115k baud if value is 1 This macro is not available starting with Dynamic C version 7 25 It was replaced with _BIOSBAUD_ The baud rate can be changed in the Options Communications menu 258 Dynamic C User s Manual A 2 Global Variables These variables may be read by any Dynamic C application program dc_timestamp This internally defined long is the number of seconds that have passed since 00 00 00 January 1 1980 Greenwich Mean Time GMT adjusted by the current time zone and daylight savings of the PC on which the program was compiled The recorded time indicates when the program finished compiling printf The date and time lx n dc_timestamp OPMODE This is a char It can have the following values e 0x88 debug mode e 0x80 run mode SEC_TIMER This unsigned long variable is initialized to the value of the real tim
250. r the application define OS MAX EVENTS 2 define OS_MAX_TASKS 20 define OS_MAX_QS iL define OS MAX MEM PART 15 define OS _TASK_STAT_EN T define OS_Q EN 0 define OS MEM _EN 1 define OS _MBOX_EN 0 define OS_TICKS_PER_SEC 64 If a custom stack configuration is needed also define the necessary macros for the counts of the different stack sizes needed by the application define STACK_CNT_256 1 idle task stack define STACK_CNT_512 2 initial program stat task stack define STACK_CNT_1K 10 task stacks define STACK_CNT_2K 10 number of 2K stacks In the application code follow the uC OS II and stack configuration constants with a use ucos2 1ib statement This ensures that the definitions supplied outside of the library are used rather than the defaults in the library This configuration uses 20 tasks two semaphores up to 15 memory partitions that the memory manager will control and makes use of the statistics task Note that the configuration constants for task creation task deletion and semaphores are not defined as the library defaults will suffice Also note that 10 of the application tasks will each have a 1024 byte stack 10 will each have a 2048 byte stack and an extra stack is declared for the statistics task Chapter 18 uC OS II 249 18 4 3 Examples The following sample programs demonstrate the use of the default configuration supplied in UCOS2 LIB and a custom configurat
251. r will load the BIOS to RAM on cold booting and compile the user program to RAM This option is useful if you want to use breakpoints while you are debugging your application but you don t want interrupts disabled while the debugger writes a breakpoint to flash this can take 10 ms to 20 ms or more depending on the flash type used Note that when you single step through code the debugger is writing breakpoints at the next point in code you will step to It is also possible to have a target that only has RAM for use as a slave pro cessor but this requires more than checking this option because hardware changes are necessary that in turn require a special BIOS and coldloader e Code and BIOS in Flash Run in RAM TIf you select this option the compiler will load the BIOS to flash when cold booting compile the user program to flash and then the BIOS will copy the flash image to the fast RAM attached to CS2 This option sup ports a CPU running at a high clock speed anything above 29 MHz This is the same as the command line compiler mf r option User Defined BIOS File Use this option to change from the default BIOS to a user specified file Enter or select the file using the browse button text box underneath this option The check box labeled use must be selected or else the default file BIOS defined in the system registry will be used Note that a single BIOS file can be made for compiling both to RAM and flash by using the preprocessor m
252. rary must be in cluded either in the BIOS using a use or recursively included by those librar ies e Internal BIOS functions will precompile but will not result in any improvement e Libraries that require the user to define parameters before being used can only be precompiled if those parameters are defined before the precompile state ment An example of this is included in precompile 1lib e Function chains and functions using segment chains cannot be precompiled e Precompiled functions will be placed in extended memory unless specifically marked root e All dependencies must be resolved Macros variables other functions etc be fore a function can be precompiled This may require precompiling other functions first See precompile 1lib for more information and examples Syntax undef identifier Removes undefines a defined macro Syntax use pathname Activates a library named in 1ib dir so modules in the library can be linked with the appli cation program This directive immediately reads in all the headers in the library unless they have already been read Chapter 12 Keywords 163 Controls whether functions use the IX register as a stack frame reference pointer or the SP stack pointer register nouseix is the default Note that the IX register is corrupted when any stack variable using function is called from within a cofunction or if a stack variable using function contains a call to a cofunctio
253. rch will proceed toward the beginning of the file rather than toward the end of the file Use the From cursor checkbox to choose whether to search the entire file or to begin at the cursor location The keyboard shortcut is lt Ctrl F gt Replace Replaces specified text Type the text to be found in the Find text box there is a pulldown list of previously entered strings Then type the text to substitute in the Change to text box If Case sensitive is selected the search will find an occurrence that matches exactly Other wise the search will find a match having upper and lower case letters For example reg7 REG7 and Reg7 all match If Reverse is clicked 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 entire file may be searched from the current cursor location by clicking the From cursor box or the search may begin at the current cursor location The Selection only box allows the substitution to be performed only within the currently selected text Use this in conjunction with the Change All button This box is disabled if no text is selected Normally Dynamic C will find the search text then prompts for whether to make the change This is an important safeguard particularly if the Change All button is clicked If No prompt is clicked Dynamic C will make the change or changes without prompting The keyboard shortcut
254. rds the place where execution of the block of statements has been paused to wait for an event To multitask using Dynamic C language extensions most application programs will have some flavor of this simple structure main ain a8 while 1 endless loop for multitasking framework costate task 1 body of costatement costate task 2 body of costatement 44 Dynamic C User s Manual 5 2 A Real Time Problem The following sequence of events is common in real time programming Start Wait for a pushbutton to be pressed Turn on the first device Wait 60 seconds Turn on the second device Wait 60 seconds Turn off both devices Go back to the start a AU FW NY The most rudimentary way to perform this function is to idle busy wait in a tight loop at each of the steps where waiting is specified But most of the computer time will used waiting for the task leaving no execution time for other tasks 5 2 1 Solving the Real Time Problem with a State Machine Here is what a state machine solution might look like tasklstate 1 initialization while 1 switch tasklstate case 1 if buttonpushed tasklistate 2 turnondevicel timerl time time incremented every second break case 2 wie eme rimen gt GOL tasklstate 3 turnondevice2 timer2 time break caben if time timer2 gt 60L taskistate 1 EUNEIMGIE ECESWaL
255. re declared auto 7 Each task runs as an infinite loop and once this application is started uC OS II will run indefinitely 250 Dynamic C User s Manual 1 Explicitly use uC OS II library use ucos2 lib void RandomNumberTask void pdata 2 Declare semaphore global so all tasks have access OS_EVENT RandomSem void main int i 3 Initialize OS internals OSInit for i 0 i lt OS_MAX_TASKS i 4 Create each of the system tasks OSTaskCreate RandomNumberTask NULL 512 i 5 semaphore to control access to random number generator RandomSem OSSemCreate 1 6 Begin multitasking OSStart void au aut to INT16U RNum au RandomNumberTask void pdata 7 Declare as auto to ensure reentrancy to OS_TCB data to INT8U err OSTaskQuery OS_PRIO_SELF amp data while 1 Rand is not reentrant so access must be controlled via a semaphore OSSemPend RandomSem 0 amp err RNum int rand 100 OSSemPost RandomSem printf Task d s random d n data OSTCBPrio RNum Wait 3 seconds in order to view output from each task OSTimeDlySec 3 Chapter 18 uC OS II 251 Example 2 This application runs exactly the same code as Example 1 except that each of the tasks are created with 1024 byte stacks The main difference between the two is the configuration of uC OS II First each confi
256. rection sesccccccses 167 typedef oes 154 root keyword oe ee 4 minus oe 166 UNION peireto 155 memory management unit 4 97 modulus P sesssccccssesee 168 unsigned E E A 155 menus multiplication 167 USEIX o eeeseeessssseeserresssceee 155 close all OPEN Fee cvesiseses seuss 180 plus H eee 166 waitfor EET 155 Compile ERAN 185 POINLETS ecccccccssesseseseeee 167 waitfordone E 156 Edit R a 182 post decrement 168 WIE seere hiar eee 156 E E EET 180 post increment 168 Kata pera iin 157 Helpeniesne rne 205 pre decrement 168 XMEM os sssssssssssssssssssssseeeeeey 157 Inspect Heed eee 189 203 pre increment 168 xstring EE ES 157 Options oo eee 192 assignment operators 169 yield iseni edee 158 Run A E ETA EEN 186 add assign se 169 L Window EET 202 AND assign amp 170 Message WINdowW sisin 184207 aSS gN E osisssa 169 language elements 13 16 20 metadata osesesessrerssesssroreerers 108 divide assign 169 137 MMU eiis ionian 4 97 modulo assign 169 C0 oo 2 1K tn 165 modes multiply assign 169 LIB DIR eee 38 163 debug esi geieise 184 180 231 OR assign I esses 170 libraries ssesccssssssssssesesoee sie SGA versre 1847188 shift left lt lt essen 169 finnish Past a 36 RRRVIE Whe Races steiner 181 shift right gt gt sc 169 modules sssssssesssseseseessseres 37 TU PS ieai 184 186 subtract assign
257. rence 208 lt CTRL P gt II ON eisithe 147 AT a AENEA EERE 23 147 157 previous CLTOL o 184 at EIRE EEE OE EA 147 INCE SOLS s erea aasi 19 lt CTRL U gt INCELTUPE sern hiere 147 INterrupts eee 130 136 Update Watch window 190 interrupt_VeCctor 4 148 breakpoints 0 187 lt CTRL V gt NOME iiinis 148 Dynamic C User s Manual 273 nodebug sses 149 TEStrictions oo eee 19 TOESC E E E EE 149 NOTSU arsi rr ia 149 with parameters s es 17 TIOUSEIK iiine ei 149 NOUSEIR e eeo 149 main function 22 36 149 231 NUE an eekates 149 NUDD erir eutk 149 memory protected wee 150 address space cee 97 O T T iiine 150 DATAORG 234 236 octal integer ussiisa 19 root soosseeneeeeeeeeeeesnannennnncece 151 CUM ie bh ha asain 189 offsets in assembly 119 126 SEGCHAIN oe eens 151 dump at address 190 127 Shared eisini 151 dump flash E 191 online help csssssesssseee 40 208 SHOT oponis 152 dump to file we 191 OPELAtOLS vasoiras 165 SIZE Gi teva Sats 152 extended 4 127 157 and Macros seessseeecee 17 SIZEOL ss caves eissssnsshvesistesbics sis 152 management 138 151 arithmetic operators 166 speed igbigh E EE 152 MAP erraien 9 decrement seeccssssssse 168 SUAUIC ennan seers 153 random access essees 4 division aeei 167 AE D O RE E 153 read only eee ee eee 4 increment 4 ccccscsse 168 SWIC o iiin 154 root 98 119 120 151 234 indi
258. ressions GUI Equivalent Select the Options Compiler Restrict watch expressions menu dialog box option rW Available starting with Dynamic C v 7 10 Description Restrict watch expressions may save root code space Default Allow any expressions in watch expressions GUI Equivalent Select the Options Compiler Restrict watch expressions menu dialog box option rw Available starting with Dynamic C v 7 10 Description Don t restrict watch expressions Default Allow any expressions in watch expressions GUI Equivalent Select Options Compiler Allow any expressions menu dialog box option Sp Description Optimize code generation for speed Default Optimize for speed GUI Equivalent Select the Options Compiler Speed menu dialog box option Chapter 15 Command Line Interface 215 SZ Description Optimize code generation for size Default Optimize for speed GUI Equivalent Select the Options Compiler Size menu dialog box option td Description Disable type demotion checking This switch is available only in Dynamic C v 7 05 and 7 06 Default Type demotion checking is performed GUI Equivalent Uncheck the Options Compiler Demotion menu dialog box option td Available starting with Dynamic C v 7 10 Description Enable type demotion checking Default Type demotion checking is performed GUI Equivalent Check the Options Compiler Demotion menu dialog box option
259. riable array structure union or of a data type Starting with Dynamic C 7 05 sizeof can be used inside of assembly blocks int list 10 99 33 2 7 63 217 x sizeof list x will be assigned 14 Declares a function to be optimized for speed as opposed to size speed int func 152 Dynamic C User s Manual Declares a local variable to have a permanent fixed location in memory as opposed to auto where the variable exists on the system stack Global variables are by definition static Lo cal variables are st at ic by default unlike standard C int func int static by default static float x explicitly static This keyword introduces a structure declaration which defines a type struct int x int y int z t ingl defines the variable thing to be a struct struct speed int x int y intz declares a struct type named speed struct speed thing2 defines the variable thing2 to be of type speed Structure declarations can be nested struct struct speed slow struct speed slower tortoise defines the variable tortoise to be a nested struct struct rabbit struct speed struct speed faster declares a nested struct type named rabbit E fast struct rabbit chips defines the variable chips to be of type rabbit Chapter 12 Keywords 153 Indicates the start of a switch statement Switch expression case
260. rights in the Software and its documentation will be as defined in Clause 52 227 19 c 2 of the FAR or in the case of NASA in Clause 18 52 227 86 d of the NASA Supplement to the FAR 268 Dynamic C User s Manual 6 Disclaimer of Warranty You expressly acknowledge and agree that the use of the Software and its documentation is at Your sole risk THE SOFTWARE DOCUMENTATION AND TECHNICAL SUPPORT ARE PROVIDED ON AN AS IS BASIS AND WITHOUT WAR RANTY OF ANY KIND Information regarding any third party services included in this pack age is provided as a convenience only without any warranty by Z WORLD and will be governed solely by the terms agreed upon between You and the third party providing such ser vices Z WORLD AND ITS LICENSORS EXPRESSLY DISCLAIM ALL WARRANTIES EXPRESS IMPLIED STATUTORY OR OTHERWISE INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICU LAR PURPOSE AND NON INFRINGEMENT OF THIRD PARTY RIGHTS Z WORLD DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE SOFTWARE WILL MEET YOUR REQUIREMENTS OR THAT THE OPERATION OF THE SOFT WARE WILL BE UNINTERRUPTED OR ERROR FREE OR THAT DEFECTS IN THE SOFTWARE WILL BE CORRECTED FURTHERMORE Z WORLD DOES NOT WAR RANT OR MAKE ANY REPRESENTATIONS REGARDING THE USE OR THE RESULTS OF THE SOFTWARE IN TERMS OF ITS CORRECTNESS ACCURACY RELIABILITY OR OTHERWISE NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY Z WORLD OR ITS AUTHORIZED REPR
261. ring a performance penalty Larger LSs are better for bulk data such as logs If the flash physical sector size i e the actual hardware sector size is large it is better to use a correspondingly large LS size This is especially the case for byte writable devices Large LSs should also be used for large LXs This minimizes the amount of time needed to initialize the file system and access large files As a rule of thumb there should be no more than 1024 LSs in any LX The ideal LS size for RAM which is the default is 128 bytes 256 or 512 can also be reasonable values for some applications that have a lot of spare RAM Sector writable flash devices require LS size PS size Byte writable devices however may use any allowable logical sector size regardless of the physical sector size Sample program Samples FileSystem FS2DEMO2 illustrates use of fs_setup This sample also allows you to experiment with various file system settings to obtain the best perfor mance FS2 has been designed to be extensible in order to work with future flash and other non volatile storage devices Writing and installing custom low level device drivers is beyond the scope of this document however see FS2 LIB and FS_DEV LIB for hints Chapter 10 The Flash File System 109 10 5 File Identifiers There are two ways to identify a particular file in the file system file numbers and file names 10 5 1 File Numbers The file number uniquely identifies a
262. ro or more times while expression 156 Dynamic C User s Manual Declares a block of data in extended flash memory xdata name value_l value_n The 20 bit physical address of the block is assigned to name by the compiler as an unsigned long variable The amount of memory allocated depends on the data type Each char is allo cated one byte and each int is allocated two bytes If an integer fits into one byte it is still allocated two bytes Each float and long cause four bytes to be allocated The value list may include constant expressions of type int float unsigned int long unsigned long char and quoted strings For example xdata namel x46 x47 x48 x49 x4A x20 x20 xdata name2 R ta b b tit ttt xdata name3 Rules yg xdata name4 1 0 2 0 float 3 40e 01 5e00 6e1 The data can be viewed directly in the dump window by doing a physical memory dump using the 20 bit address of the xdata block See Samples Xmem xdata c for more information Indicates that a function is to be placed in extended memory This keyword is semantically meaningful in function prototypes Its use must be consistent between the prototype and the function definition xmem int func memmap xmem Declares a table of strings in extended memory The strings are allocated in flash memory at compile time which means they can not be rewritten directly The table entries ar
263. roper range 5 5 5 2 1 Indexed Cofunction Restrictions Costatements are not supported inside indexed cofunctions Single user cofunctions can not be indexed 5 5 5 3 Single User Cofunction Since cofunctions are executing in parallel the same cofunction normally cannot be called at the same time from two places in the same big loop For example the following statement containing two simple cofunctions will generally cause a fatal error waitfordone cofunc_nameA cofunc_nameA This is because the same cofunction is being called from the second location after it has already started but not completed execution for the call from the first location The cofunction is a state machine and it has an internal statement pointer that cannot point to two statements at the same time 54 Dynamic C User s Manual Single user cofunctions can be used instead They can be called simultaneously because the sec ond and additional callers are made to wait until the first call completes The following statement which contains two single user cofunctions is okay waitfordone scofunc_nameA scofunc_nameA loopinit This function should be called in the beginning of a program that uses single user cofunctions It initializes internal data structures that are used by loophead loophead This function should be called within the big loop in your program It is necessary for proper single user cofunction abandonment
264. ror that occurs e The value of SEC_TIMER at the time of the error This variable contains the number of seconds since 00 00 00 on January 1st 1980 if the real time clock has been set correctly This variable is updated by the periodic timer which is enabled by default Z World sets the real time clock in the factory When the BIOS starts on boards with batteries it initializes SEC_TIMER to the value in the real time clock e The address where the exception was called from This can be traced to a particular func tion using the MAP file generated when a Dynamic C program is compiled e The exception type Please see Table 8 12 on page 92 for a list of exception types e The value of all registers This includes alternate registers SP and XPC This is a global option that is enabled by default e An 8 byte message This is a global option that is disabled by default The default error handler does nothing with this e A user definable length of stack dump This is a global option that is enabled by default e A one byte checksum of the entry 8 3 1 1 Error Log Buffer Size The size of the error log buffer is determined by the number of entries the size of an entry and the header information at the beginning of the buffer The number of entries is determined by the macro ERRLOG_NUM_ENTRIES default is 78 The size of each entry is dependent on the set tings of the global options for stack dump register dump and error message The defa
265. ros in assembly code The preprocessor expands macros before the assembler parses any text Putting a at the end of a line inserts a new line in the text This only works in assembly code Labels and comments are not allowed in multiline macros tdefine SAVEFLAG ld aria S push af y pDoD 9G asm tel lo 0x32 SAVEFLAG endasm 118 Dynamic C User s Manual 11 2 4 Labels A label is a name followed by one or two colons A label followed by a single colon is local whereas one followed by two colons is global A local label is not visible to the code out of the current embedded assembly segment i e code before the asm or after the endasm directive Unless it is followed immediately by the assembly language 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 equ whenever possible 11 2 5 Special Symbols This table lists special symbols that can be used in an assembly language expression Table 11 19 Special Assembly Language Symbols Symbol Description Indicates the amount of stack space in bytes used for stack CBE based variables This does not include arguments Evaluates the offset from the frame reference point to the RETVAL stack spac
266. rs Array elements are referenced 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 fol lowing doubly dimensioned array or array of arrays SiMe Wee alse 7 ESA is referenced in a similar way Secale matiiiz IJl The first dimension of an array does not have to be specified as long as an initialization list is specified dime x 2 tl 2hp 1S Are Se Fe eer sitting Yaloecdeiteg s 4 13 2 Structure Variables may be grouped together in structures struct in C or in arrays Structures may be nested SERUCER Ghar tlagsz Silesia ilemme WME 58 ian We y lLoes ECUR SON 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 Chapter 4 Language 25 4 13 3 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 tac awe lle long awa float xval u Unions can be nested Union members the variables within a union are referenced like struc ture elements using the dot operator J u ival 4 13 4 Composites Composites
267. rward pointer assignments of dif ferent types type casting does affect pointer arithmetic and pointer dereferences All pointer warnings are considered non serious as far as warning reports are concerned Warning Reports This 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 warning is a potential run time bug Demotions such as converting a Long to an int are considered non serious with regard to warning reports Chapter 14 Graphical User Interface 195 Optimize For Allows for optimization of the program for size or 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 where most code is not marked nodebug The speed gain by optimizing for speed is most obvious for functions that are marked nodebug and have no auto local stack based variables Max Shown This limits the number of error and warning messages displayed after compilation Defines The Defines button brings up a dialog box with a window for entering or modifying a list of defines that are global to any source file programs that are compiled and run The macros that are defined here are seen by the BIOS during its compilation
268. s breakpoints and other advanced debugging features Watch expressions can be used to compute C expressions involving the target s program variables or functions Watch expressions can be evalu ated while stopped at a breakpoint or while the target is running its program Dynamic C provides extensions to the C language such as shared and protected variables cos tatements and cofunctions that support real world embedded system development Dynamic C supports cooperative and preemptive multi tasking 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 2 1 1 Speed Dynamic C compiles directly to memory Functions and libraries are compiled and linked and downloaded on the fly On a fast PC Dynamic C might load 30 000 bytes of code in 5 seconds at a baud rate of 115 200 bps Chapter 2 Introduction to Dynamic C 3 2 2 Dynamic C Enhancements and Differences Dynamic C differs from a traditional C programming system running on a PC or under UNIX The reason To be better help customers write the most reliable embedded control software possible It is not possible to use standard C in an embedded environment without making adaptations Stan dard C makes many assumptions that do not apply to embedded systems For example standard C implicitly assumes that an operating system is present and that a program starts wi
269. s are use d in the file Lib default h The Modules section later in this chapter explains how Dynamic C knows which functions and global variables in a library to use 36 Dynamic C User s Manual 4 22 Headers The following table describes two kinds of headers used in Dynamic C libraries Table 4 4 Dynamic C Library Headers Header Name Description Module headers Makes functions and global variables in the library known to Dynamic C Function Description Describe functions Function headers form the basis for headers function lookup help You may also notice some Library Description headers at the top of library files These have no special meaning to Dynamic C they are simply comment blocks 4 23 Modules To write a custom source library modules must be understood because they provide Dynamic C with the ability to know which functions and global variables in a library to use It is important to note that the use directive is a replacement for the include directive and the include directive is not supported 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 funcl var2 Prototype Or wuMe I declaration for var2 77a macieader cerinricion Oi rumel andl possibly other functions and data 4 23 1 The Key The line a
270. sed on the needs of the application Suppose that an application needs 5 tasks and each task has a consecutively larger stack The macros and calls to OSTaskCreate would look as follows define STACK_CNT_256 2 number of 256 byte stacks define STACK_CNT_512 2 number of 512 byte stacks define STACK _CNT_1K 1 number of 1K stacks define STACK _CNT_2K 1 number of 2K stacks define STACK _CNT_4K 1 number of 4K stacks OSTaskCreate taskl NULL 256 0 OSTaskCreate task2 NULL 512 1 OSTaskCreate task3 NULL 1024 2 3 4 i OSTaskCreate task4 NULL 2048 OSTaskCreate task5 NULL 4096 Note that the macro STACK_CNT_2 56 is set to 2 instead of 1 uC OS II always creates an idle task which runs when no other tasks are in the ready state Note also that there are two 512 byte stacks instead of one This is because the program is given a 512 byte stack If the application uti lizes the uC OS II statistics task then the number of 512 byte stacks would have to be set to 3 Statistic task creation can be enabled and disabled via the macro OS_TASK_STAT_EN which is located in ucos2 1ib If only 6 stacks were declared one of the calls to OSTaskCreate would fail 240 Dynamic C User s Manual If an application uses OSTaskCreateExt which enables stack checking and allows an exten sion of the Task Control Block fewer parameters are needed in the Rabbit version of uC OS IL Using
271. serve space in the first flash such that Dynamic C will not clobber the file system a minor BIOS modification is necessary The macro XMEM_RESERVE_STZE in the BIOS is currently set to 0x0000 Increasing this value will reserve that much space between the end of xmem code that Dynamic C is building and the System ID block at the end of memory Unfortunately the file sys tem needs to start on a FS_BLOCK_SIZE boundary which is normally 4096 bytes Therefore slightly more space than is needed should be allocated to allow for the System ID block and that the end of xmem space might not lie on a 4096 byte boundary Chapter 10 The Flash File System 101 After this space has been allocated the beginning of the file system can be found The end of where Dynamic C will touch the flash is stored in the macro END_OF_XMEMORY and the file system may start at the next 4096 byte boundary after that point The following code computes what to pass to fs_format where to start the file system long fs_start start at the end of xmem fs_start END_OF_XMEMORY divide out the blocksize to meet requirements for fs_format fs_start fs_start FS_BLOCK_SIZE 1f fs_start FS_BLOCK_SIZE END_OF_XMEMORY rounding error move up 1 block so end of xmem is not clobbered fs_startt t fs_format fs_start NUM _BLOCKS 0 After this point the file system should act normally If the 4096 byte block size is too large
272. sh by buffering data before writing it to the flash Accumulating 1000 single byte writes into one can extend the life of the flash by an average of 750 times FS2 does not currently perform any in memory buffering If you write a single byte to a file that byte will cause write activity on the device This ensures that data is written to non volatile storage as soon as possible Buffering may be implemented within the application if possi ble loss of data is tolerable NOTE The use of USE_2NDFLASH_CODE is not compatible with the flash file system Chapter 10 The Flash File System 99 10 1 1 Maximum File Size The maximum file size for an individual file depends on the total file system size and the number of files present Each file requires at least two sectors at least one for data and always one for metadata for information used internally There also needs to be two free sectors to allow for moving data around It is not recommended to use the flash file system to store a large number of small files It is much more efficient to have a few large ones 10 1 2 Using SRAM The flash file system can be used with battery backed SRAM Internally RAM is treated like a flash device except that there is no write cycle limitation and access is much faster The file sys tem will work without the battery backup but would of course lose all data when the power went off Currently the maximum size file system supported in RAM is about 20
273. sion does not const int i 18 const j 7 k float x k i j result is 2 x float i j result is 2 591 Chapter 13 Operators 167 Pre or post increment 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 ANE di al 12 i 0 q alitt q gets a 0 then i becomes 1 r a itt r gets a 1 then i becomes 2 s i i becomes 3 then s i i i becomes 4 If the operator is used with a pointer the value of the pointer increments by the size of the object in bytes to which it points With operands other than pointers the value increments by 1 Pre or post decrement If the precedes an operand the operand is decremented before use If the operator follows an operand the operand is decremented after use int j a 12 j 12 q a l j becomes 11 then q gets a 11 r al j j becomes 10 then r gets a 10 s j s 10 then j becomes 9 j j becomes 8 Ifthe operator is used with a pointer the value of the pointer decrements by the size of the object in bytes to which it points With operands other than pointers the value decrements by 1 Modulus This is a binary operator The result is the remainder of the left hand operand divided by the right hand operand const int i 13
274. ss SRAM typi cally begins at address 0x80000 If BIOS code runs from flash memory the BIOS code starts in the root code section at address 0x00000 and fills upward The rest of the root code will continue to fill upward immediately fol lowing the BIOS code If the BIOS code runs from SRAM the root code section along with root data and stack sections will start at address 0x80000 9 1 1 Memory Mapping Control The advanced user of Dynamic C can control how Dynamic C allocates and maps memory For details on memory mapping refer to the Rabbit 2000 Microprocessor User s Manual or the Rabbit 3000 Microprocessor User s Manual 9 2 Extended Memory Functions A program can use many pages of extended memory Under normal execution code in extended memory maps to the logical address region EOOOH to FFFFH 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 To access xmem data use function calls to exchange data between xmem and root memory Use the Dynamic C functions root2xmem xmem2root and xmem2xmem to move blocks of data between logical memory and physical memory 9 2 1 Code Placement in Memory Code runs just as quickly in extended memory as it does in root memory but calls to and returns from the functions in extended memory take
275. ssembly language and architecture for controllers For a full treatment of C refer to one or both of the following texts e The C Programming Language by Kernighan and Ritchie published by Prentice Hall e C A Reference Manual by Harbison and Steel published by Prentice Hall Chapter 1 Installing Dynamic C 1 Dynamic C User s Manual 2 Introduction to Dynamic C Dynamic C is an integrated development system for writing embedded software It is designed for use with Z World controllers and other controllers based on the Rabbit microprocessor The Rab bit 2000 and the Rabbit 3000 are high performance 8 bit microprocessors that can handle C lan guage applications of approximately 50 000 C statements or 1 MB 2 1 The Nature of Dynamic C Dynamic C integrates the following development functions e Editing e Compiling e Linking e Loading e 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 or machine code level Pull down menus and keyboard shortcuts for most commands make Dynamic C easy to use Dynamic C also supports assembly language programming It is not necessary to leave C or the development system to write assembly language code C and assembly language may be mixed together Debugging under Dynamic C includes the ability to use print f commands watch expression
276. sters 129 136 Previous error lt CTRL P gt 184 primary register 120 127 129 primitive data types 15 print choosing a printer 181 182 print fle nk Acces 181 print preview oe 181 printf 21 24 186 187 188 197 203 program eXaMple eceeeeeeeeeneeeeee 24 POW carnete 30 OPtIMIZE oes 196 ESET oaeee atenen 187 spanning 2 flash 99 232 Speed oneris 232 programmable ROM 4 project files 181 227 229 PLOMOTION 0 ee eee 166 protected Keyword oe eee 150 variables 0 5 3 150 232 prototypes Checking seeen 195 function ee 23 24 37 in headers oo eee eee 37 punctuation oe eee eeeeeneeeee 14 Q quitting Dynamic C 182 R Rabbit restart protected variables 150 RAM Staller Sosa eee 4 read only memory eeee 4 real time programming oe 3 redoing changes 182 registers saving and restoring 130 SHACOW aen reee 260 snapshots eee 204 VaLlaDIES aries 27 WINDOW ececeeeseeeeeees 202 204 reset program oo eee eects 187 SOWAT E eines 188 TALBCt ra ited heeds 188 TOU less eaa hE 127 130 TEU eee tence crt E 130 TOM otter ites 130 return 127 128 150 154 return address cc cccceeees 122 ROM ponnn e 187 programmable eee 4 root memory assembly functions 120 file system usage
277. sters A listing of these register macros can be found in the Rabbit 2000 Microprocessor User s Manual and the Rabbit 3000 MIcroprocessor User s Manual A 4 1 Shadow Registers Shadow registers exist for many of the I O registers They are character variables defined in the BIOS The naming convention for shadow registers is to append the word Shadow to the name of the register For example the global control status register GCSR has a corresponding shadow register named GCSRShadow The purpose of the shadow registers is to allow the program to reference the last value pro grammed to the actual register This is needed because a number of the registers are write only 260 Dynamic C User s Manual Appendix B Map File Generation Starting with Dynamic C 7 05 all symbol information is put into a single file The map file has three sections a memory map section a function section and a globals section The map file format is designed to be easy to read but with parsing in mind for use in program down loaders and in other possible future utilities for example an independent debugger Also the memory map as defined by the org statements will be saved into the map file Map files are generated in the same directory as the file that is compiled If compilation is not suc cessful the contents of the map file are not reliable B 1 Grammar lt mapfile gt lt memmap section gt lt function section gt lt global section
278. stores except for one byte items and some two byte items 17 2 Run time Storage of Data Data that will never change in a program can be put in flash by initializing it in the declarations The compiler will put this data in flash See the description of the const xdata and xstring keywords for more information If data must be stored at run time and persist between power cycles there are several ways to do this using Dynamic C functions e User Block Recommended method for storing non file data This is where calibration constants for boards with analog I O are stored in the factory Space here is limited to as small as 8K sizeof SysIDBlock bytes or less if there are calibration constants e Flash File System The file system is best for storing data that must be organized into files or data that won t fit in the User block It is best used on a second flash chip It is not possible to use a second flash for both extra program code that doesn t fit into the first flash and the file system The macro USE_2NDFLASH_CODE must be uncommented in the BIOS to allow programs to grow into the second flash this precludes the use of the file sys tem e WriteFlash2 This function is provided for writing arbitrary amounts of data directly to arbitrary addresses in the second flash e Battery Backed RAM Storing data here is as easy as assigning values to global variables or local static variables The file system can also be configured
279. t bits are stored the high bit is 1 implicitly Rabbit controllers do not have floating point hardware Range 1 18 x 10 78 to 3 40 x 1078 enum Defines a list of named integer constants The integer constants are signed and in the range 32 768 to 32 767 This keyword is available starting with Dynamic C version 7 20 4 3 1 Data Type Limits The symbolic names for the hardcoded limits of the data types are defined in Limits h and are shown here define define define define define define define define define define define define define define CEARSB IMI 8 UCHAR_MAX 255 CHAR_MIN 0 CHAR_MAX 255 MB_LEN_MAX il SHRT_MIN 34 1 66 SHRT_MAX BAIT USHRT_MAX 65535 INT_MIN 32 767 INT_MAX 32767 UINT_MAX 65535 LONG_MIN 2147483647 LONG_MAX 2147483647 ULONG_MAX 42996295 Chapter 4 Language 15 4 4 Names Names identify variables 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 dis tinct up to 32 characters but may be longer Prior to Dynamic C version 6 19 names were distinct up to 16 characters but could be longer Names may not be the same as any keyword Names are case sensitive Examples my_function ok olok ok test32 ok jumper no
280. t ok uses a minus sign 3270type not ok begins with digit Cleanup_the_data_now These names are Cleanup_the_data_later not distinct References to structure and union elements require compound names The simple names in a com pound 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 con stants See Section 4 5 Macros define READ 10 define WRITE 20 define ABS 0 define REL il define READ ABS READ ABS define READ REL READER EI The term READ_ABS is the same as 10 0 or 10 and READ_REL is the same as 10 1 or 11 Note that Dynamic C does not allow anything to be assigned to a constant expression READ_ABS 27 produces compiler error 16 Dynamic C User s Manual 4 5 Macros Macros may be defined in Dynamic C by using def ine A macro is a name replacement fea ture Dynamic C has a text preprocessor that expands macros before the program text is compiled The programmer assigns a name up to 31 characters to a fragment of text Dynamic C then replaces the macro name with the text fragment wherever the name appears in the program In this example define OFFSET 12 define SCALE 72 aLIME ake SP i x S SCALDE ap OF SInI the variable i gets the value x 72 12 Macros can have parameters such as in the follow ing example jOISIE Lis WwOeCl
281. t the bottom of the dialog box The baud rate set in the Base Frequency MHz pulldown menu only applies to debugging The fastest baud rate for downloading is negotiated between the PC and the target Chapter 14 Graphical User Interface 201 14 2 6 7 Other Menu Choices Show Tool Bar The Show Tool Bar command toggles the display of the tool bar Dynamic C remembers the toolbar setting on exit Save Environment The Save Environment command gets Dynamic C to update the registry and DCW CFG ini tialization files immediately with the current options settings Dynamic C always updates these files on exit Saving them while working provides an extra measure of security against Windows crashes 14 2 7 Window Menu Click the menu title or press lt Alt W gt to select the Window menu es i Help Cascade Tile Horizontally Tile Yertically Arrange icons Watch Stdio Assembly F10 Registers Stack Information v 1 CADCRABBIT SAMPLES PONG C The first group of items is a set of standard Windows commands that allow the application win dows to be arranged in an orderly way 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 pri
282. t the response and returned data are valid and should be read before sending a new command Performing a dummy write to the status register will clear this bit so that it can be set by the next response Pin assignments for both the Rabbit 2000 and the Rabbit 3000 acting as a slave are as follows Table 7 9 Pin assignments for the Rabbit acting as a slave Pin Function PE7 SCS chip select active low to read write slave port PB2 SWR slave write assert for write cycle PB3 SRD slave read assert for read cycle PB4 SAO low address bit for slave port registers PB5 SA1 high address bit for slave registers PB7 SLVATTN asserted by slave when it responds to a command cleared by master write to status register PAO PA7 slave port data bus For more details and read write signal timing see the Rabbit 2000 Microprocessor User s Manual or the Rabbit 3000 Microprocessor User s Manual 70 Dynamic C User s Manual 7 1 3 Polling and Interrupts Both the slave and the master can use interrupt or polling for the slave The parameter passed to SPinit determines which one is used In interrupt mode the developer can indicate whether the handler functions for the channels are interruptible or non interruptible 7 1 4 Communication Channels The Rabbit slave has 256 configurable channels available for communication The developer must provide a handler function for each channel that is used Some b
283. table xdata_table 16 now the xmem data can be accessed via a 16 bit pointer into the table Both methods const and xdata create initialized data in flash at compile time so the data cannot be rewritten directly e Use xstring to declare a table of strings The keyword xst ring declares a table of strings in extended flash memory The dis advantage is that the strings cannot be accessed directly with pointers since the table entries are 20 bit physical addresses As illustrated above the function xmem2 root may be used to store the table in temporary stack space This uses root code space const char namel string_1 e string_n This does not xstring name string_1 string_n Both methods const and xst ring create initialized data in flash at compile time so the data cannot be rewritten directly e Turn off selected debugging features In Dynamic C 7 20 watch expressions breakpoints and single stepping can be selec tively disabled in the Options Debugging dialog to save some root code space Chapter 17 Hints and Tips 235 e Place assembly language code into xmem Pure assembly language code functions can go into xmem starting with Dynamic C 7 20 asm foo_root some instructions ret endasm The same function in xmem asm xmem foo_xmem some instructions lret use lret instead of ret endasm The correct calls are call foo_root and1
284. table below Table 5 6 Flags that specify the run status of a costatement STOPPED INIT State of Costatement 7 Done or has been initialized to run but set to yes YER inactive Set by CoReset yes no Paused waiting to resume Set by CoPause no yes Initialized to run Set by CoBegin Running CoResume will return the flags to no no 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 only if the costatement has a name The CSState flag has no meaning for unnamed costatements or cofunctions Last Location The two fields Last locADDR and last 1locCBR represent the 24 bit address of the location at which to resume execution of the costatement If Last locADDR is zero as it is when initial ized the costatement executes from the beginning subject to the CSSt ate flag If Last l ocADDR is nonzero the costatement resumes at the 24 bit address represented by lLastlocADDR and lastlocCBR These fields are zeroed whenever one of the following is true e the CoData structure is initialized by a call to _GLOBAL_INIT CoBegin or CoReset e the costatement is executed to completion e the costatement is aborted Check Sum The ChkSum field is a one byte check sum of the address It is the exclusive or result of the bytes in last locADDR and
285. talled The default library file extension is LIB Dynamic C uses functions and data from library files and compiles them with an applica tion program that is then downloaded to a controller or saved to a bin file An application program the default file extension is c consists of a source code file that con tains a main function called main and usually other user defined functions Any additional source files are considered to be libraries though they may have a c extension if desired and are treated as such The minimum application program is one source file containing only main Libraries both user defined and Z World defined are linked with the application through the use directive The use directive identifies a file from which functions and data may be extracted Files identified by use directives are nestable as shown below The use directive is a replacement for the include directive which is not supported in Dynamic C Any library that is to be used in a Dynamic C program must be listed in the file LIB DIR or another DIR file specified by the user Starting with version Dynamic C 7 05 a different DIR file may be specified by the user in the Compiler Options dialog to facilitate working on multiple projects Application use x 1ib use y 1ib main function function use z 1ib function use z lib Figure 2 Nesting Files in Dynamic C Most libraries needed by Dynamic C program
286. tate structure data Structure to read from slave port buffer length Number of bytes to read tmout Maximum wait in milliseconds for any byte from previous one RETURN VALUE The number of bytes read from the buffer LIBRARY SP_STREAM LIB int cof_SPSwrite SPStream stream void data int length DESCRIPTION Transmits length bytes to slave port output buffer This function is non reentrant PARAMETERS stream Pointer to the stream state structure data Structure to write to slave port buffer length Number of bytes to write RETURN VALUE The number of bytes successfully written to slave port LIBRARY SP_STREAM LIB 86 Dynamic C User s Manual void SPSinit void DESCRIPTION Initializes the circular buffers used by the stream handler LIBRARY SP_STREAM LIB int SPSread SPStream stream void data int length unsigned long tmout DESCRIPTION Reads length bytes from the slave port input buffer or until tmout milliseconds tran spires between bytes If no data is available when this function is called it will return im mediately This function will call SPt ick if the slave port is in polling mode This function is non reentrant PARAMETERS stream Pointer to the stream state structure data Buffer to read received data into length Maximum number of bytes to read tmout Time to wait between received bytes before returning RETURN VALUE Number of bytes read into the data buffer
287. text file does not exist it will be created otherwise it will be overwritten Default None GUI Equivalent Select Options Debugger Log STDOUT Log file menu dialog box option Example dccl_cmp myProgram c o MyOutput txt dccl_cmp myProgram c o MyOutput txt h dccl_cmp myProgram c h 0o MyOutput txt Chapter 15 Command Line Interface 221 oa OutputFilePathname Description Default GUI Equivalent Example Append header information if specified with h and all program errors warnings and outputs to a text file If the text file does not exist it will be created otherwise it will be appended None Select the Options Debugger Log STDOUT Log file Append Log menu dialog box option dccl_cmp myProgram c oa MyOutput txt pf projectFilePathname Available starting with Dynamic C v 7 10 Description Specify a project file to read before the command line switches are read The environment settings are taken from the project file specified with pf or default dcp if no other project file is specified Any switches on the command line regardless of their position relative to the pf switch will override the settings from the project file Default The project file default dcp GUI Equivalent Select the File Project Open menu dialog box option Example dccl_cmp myProgram c ne 25 pf myProject dcp dccl_cmp myProgram c ne 25 pf myProject Note The project file extension dc
288. th a clean slate whereas embedded systems may have battery backed memory and may retain data through power cycles Z World has extended the C language in a number of areas 2 2 1 Dynamic C Enhancements Many enhancements have been added to Dynamic C Some of these are listed below Function chaining a concept unique to Dynamic C allows special segments of code to be embedded within one or more functions When a named function chain executes all the seg ments belonging to that chain execute Function chains allow software to perform initializa tion data recovery or other kinds of tasks on request Costatements allow concurrent parallel processes to be simulated in a single program Cofunctions allow cooperative processes to be simulated in a single program Slice statements allow preemptive processes in a single program The interrupt keyword in Dynamic C allows the programmer to write interrupt service routines in C Dynamic C supports embedded assembly code and stand alone assembly code Dynamic C has shared and protected keywords that help protect data shared between different contexts or stored in battery backed memory Dynamic C has a set of features that allow the programmer to make fullest use of extended memory Dynamic C supports the 1 MB address space of the microprocessor The address space is segmented by a memory management unit MMU Normally Dynamic C takes care of memory management but there are instances
289. the Real Time Problem Breakpoint ENESE NAERAN ELENI lives cosnseousenecsesoes 9 with a State Machine 0 066 45 Editing the Program eee 9 5 3 Costatements cccesccseeecsecsseeseneens 46 3 2 Run DEMO2 C Loc ceeeeececeeeeees 10 Solving the Real Time Problem Watching Variables Dynamically 10 with Costatements ceceee 46 3 3 Run DEMO3 C wo eeeeececeeeeees 10 Costatement Syntax CEI eT 47 Cooperative Multitasking 10 Control Statements cceeee 48 3 4 Summary Of Features eee cece eee 12 5 4 Advanced Costatement Topics na Bee 48 A WAN GUA PC 2 t8 cSt ine diet 13 Pine 0 Data SPICE setae a CoData Fields cecceessseeeeteeees 49 4 1 C Language Elements 13 i Pointer to CoData Structure 50 4 2 Punctuation and Tokens 06 14 Functions for Use With Named 4 3 Datascccin tuning init deeds 15 bog Costatementt cccccceeseeereeeees 50 Data Type Limits eeeeeeeeee 15 ete 4 4 Names 16 Firsttime Functions cccseee 51 Sa lediadieavn a E diets Shared Global Variables 51 4 5 Macros rrene a 17 soot 5 5 Cofunctions ceceeceeeeseceeseeeesneeeees 52 REStriCtiONS ceceseeceeeeceeesseeeeeeees 19 Senne 52 4 6 NUMMbers ccssssssssssssscsssessscssesesesesesesesese 19 WN eA AC Siena ae Calling Restrictions 53 4 7 Strings and Character Data 20 CoData Structure 53 String Conc
290. the context of a C language func tion Before Dynamic C version 7 25 stand alone assembly functions were always placed in root memory A stand alone assembly function has no auto variables and no formal parameters It can how ever have arguments passed to it by the calling function 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 unsigned int char pointer the primary register is HL with register H containing the most significant byte If the first argument has four bytes long unsigned long float the primary register is BC DE 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 all arguments including the first pushed last are pushed on the stack C function values return in the primary register if they have four or fewer bytes either in HL or BC DE Assembly language allows assumptions to be made 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 120 Dynamic C User s Manual 11 3 1 Stand Alo
291. the macros in the example above the tasks would be created as follows taskl NULL 0 0 256 NULL OS_TASK_OPT_STK_CHK K_CLR OSTaskCreateExt task2 NULL 1 1 512 NULL OS_TASK_OPT_STK_CHK OSTaskCreateExt S t OS_TASK_OPT_STK_CLR t S OS_TASK_OP OSTaskCreateExt task3 NULL 2 2 1024 NULL OS_TASK_OPT_STK_CHK OS_TASK_OP K_CLR OSTaskCreateExt task4 ULL 3 3 2048 NULL OS_TASK_OPT_STK_CHK OS_TASK_OPT_STK_CLR OSTaskCreateExt task5 ULL 4 4 4096 NULL OS_TASK_OPT_STK_CHK OS_TASK_OPT_STK_CLR 18 1 3 Restrictions At the time of this writing uC OS II for Dynamic C is not compatible with the use of slice state ments Also see the function description for OSTimeTickHook for important information about preserving registers if that stub function is replaced by a user defined function Due to Dynamic C s stack allocation scheme special care should be used when posting messages to either a mailbox or a queue A message is simply a void pointer allowing the application to determine its meaning Since tasks can have their stacks in different segments auto pointers declared on the stack of the task posting the message should not be used since the pointer may be invalid in another task with a different stack segment
292. tion Terminates a statement label Terminates a simple statement or a do loop C requires these Separates items in a list such as an argument list declaration list initialization list or expression list Encloses argument or parameter lists Function calls always require parentheses Macros with parameters also require parentheses Also used for arithmetic and logical sub expressions Begins and ends a compound statement a function body a structure or union body or encloses a function chain segment Indicates that the rest of the line is a comment and is not compiled Comments are nested between the and tokens 14 Dynamic C User s Manual 4 3 Data Data variables and constants have type size structure and storage class Basic or primitive data types are shown below Table 4 3 Dynamic C Basic Data Types Type Description char 8 bit unsigned integer Range 0 to 255 OxFF int 16 bit signed integer Range 32 768 to 32 767 unsigned int 16 bit unsigned integer Range 0 to 65 535 long 32 bit signed integer Range 2 147 483 648 to 2 147 483 647 unsigned long 32 bit unsigned integer Range 0 to 23 1 float 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 significan
293. tion 2 License all Sections of this Agreement shall survive any expiration or termination of this License Dynamic C User s Manual 269 9 General Provisions No delay or failure to take action under this License will constitute a waiver unless expressly waived in writing signed by a duly authorized representative of Z WORLD and no single waiver will constitute a continuing or subsequent waiver This License may not be assigned sublicensed or otherwise transferred by You by operation of law or other wise without Z WORLD s prior written consent This License shall be governed by and con strued in accordance with the laws of the United States and the State of California exclusive of the conflicts of laws principles The United Nations Convention on Contracts for the Interna tional Sale of Goods shall not apply to this License If for any reason a court of competent jurisdiction finds any provision of this License or portion thereof to be unenforceable that provision of the License shall be enforced to the maximum extent permissible so as to affect the intent of the parties and the remainder of this License shall continue in full force and effect This License constitutes the entire agreement between the parties with respect to the use of the Software and its documentation and supersedes all prior or contemporaneous understandings or agreements written or oral regarding such subject matter There shall be no contract for pur chase
294. tions Compiler menu option then select the Defines button Chapter 15 Command Line Interface 219 d MacroToUndefine Available starting with Dynamic C v 7 10 Description Default GUI Equivalent Example Undefines a macro that might have been defined in the project file If a macro is defined in the project file read by the command line compiler and the same macro name is redefined on the command line the command line definition will generate a warning A macro previously defined must be undefined with the d switch before redefining it Undefining a macro that has not been defined has no consequence and so is always safe although possibly unnecessary In the example all compilation settings are taken from the project file specified except that now the macro MAXCHARS was first undefined before being redefined None None dccl_cmp myProgram c pf myproject d MAXCHARS qd MAXCHARS 512 eto EthernetResponseTimeout Available starting with Dynamic C v 7 10 Description Default GUI Equivalent Example Time in milliseconds Dynamic C waits for a response from the target on any retry while trying to establish ethernet communication 8000 milliseconds None dccl_cmp myProgram c eto 6000 i InputsFilePathname Description Execute a program that requires user input by supplying the input in a text file Each input required should be entered into the text file exactly as it would be when entered in
295. tions oo eee 162 nodebug 149 159 186 232 nointerleave 00 162 FMOUSEIX ccccceceeseeceeeenees 163 precompile 0 0 0 0 163 Hunde cceeeeeeeee 19 163 FUSE oeenn 36 38 163 HUSEIX OEE ERATE E E 163 FWAIMS aanas 164 Warnt ooenenesoooseeoessoseseeese 164 FXIMPOLt 0 ee eee eee 164 line continuation 159 compound NAMES ear chess Teir is 16 statements ceceeseeeeees 21 concatenation of strings 20 configuration ee 201 CONSE tet At eer Atta eee 141 CONTINUE cee 31 142 154 CXAMPlE soser iirst ris 31 copying text ee 182 183 costate ssssooseoseseseeesssseseeee 142 costatements eee 46 51 ADOL AAR 137 firsttime siniese 145 keyword 00 ceeeeeeeeseeees 142 suspend ssesseseseereeeeeee 155 SYNUAK REAREA 47 yields 158 curly braces wees 21 cursor execution eee 187 188 positioning 0 0 179 184 EXO cksttsantnnes 207 cutting text eee 183 D data structure COMPOS ItES oo eee 26 KeYWOTE 0 0 ceeeeeeeeeeseeeeees 22 NESTING oe eee eeeeeee 25 offset of element 119 pass by value oe 29 returned by function 128 niana t OEE ERE ceeues 26 data types ee i 25 aggregate eects 25 primitive oo eee 15 DATAORG LL 234 236 DATASEG srine cnno 97 date and time 00 eee 66 OD sa zsesh shes ieata te hee aaeits 117 DEW CFG iensen 202 DCWGIND onssa 202 CeDU 8 ainteis 231 dialog DOX oo 197 disassemble
296. tivate or deactivate the Stack window The Stack window dis plays 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 progression of successive stack snapshots Top of Stack Mi E3 204 Dynamic C User s Manual Information Click the Information menu option to activate the Information window Information The Information window displays how the memory is partitioned and how well the compila tion went 14 2 8 Help Menu Click the menu title or press lt Alt H gt to select the HELP menu The choices are given below Online Documentation Opens a browser page and displays a file with links to other manuals When installing Dynamic C from CD this menu item points to the hard disk after a Web upgrade of Dynamic C this menu item optionally points to the Web Keywords Opens a browser page and displays an HTML file of Dynamic C keywords with links to their descriptions in this manual Operators Opens a browser page and displays an HTML file of Dynamic C operators with links to their descriptions in this manual HTML Function Reference Opens a browser page and displays an HTML file that has two links one to Dynamic C func tions listed alphabetically the other to the functions listed by functional group Each function listed is linked to its description in the Dynamic C Function Reference Manual
297. to 1 Debug code will be included even if nodebug precedes the main function in the program __ FILE__ The compiler substitutes this macro with the current source code file name as a character string literal Dynamic C User s Manual 257 Table A 3 Macros Defined by the Compiler Macro Name Definition and Default _FAST_RAM _ _FLASH_ RAM These are used for conditional compilation of the BIOS to distinguish between the three options e compiling to flash and running in RAM available starting with Dynamic C 7 30 e compiling to and running in flash compiling to and running in RAM The compile mode choice is made in the Options Compiler dialog box The default is compiling to and running in flash Starting with Dynamic C version 7 26 the BIOS defines FAST_RAM_COMPTLE FLASH_COMPTLE and RAM COMPILE These macros are defined to 0 or 1 as opposed to the corresponding compiler defined macros which are either defined or not defined This difference makes possible statements such as if FLASH _COMPILE FAST_RAM_ COMPILE _FLASH_SIZE_ _RAM SIZE_ These are used to set the MMU registers and code and data sizes available to the compiler The values of the macros are the number of 4K blocks of memory available __LINE__ The compiler substitutes this macro with the current source code line number as a decimal constant NO_BIOS Boolean value Tells the compiler whether o
298. to a function is different than for ordinary pointers and Dynamic C syntax for this is slightly different than the standard C syntax Standard syntax for a pointer to a function is returntype name argument list for example ime ituine il aime a ame 19 2 VELE arwa elnaie p Dynamic C doesn t recognize the argument list in function pointer declarations The correct Dynamic syntax for the above examples would be ime itumeil VOLE itWiae2 Pp 28 Dynamic C User s Manual You can pass arguments to functions that are called indirectly by pointers but the compiler will not check them for correctness The following program shows some examples of using function pointers typedef int fnptr create pointer to function that returns an integer main Time Sp We diate ite Va imo FOZ Facil ime tmmes E fol imeirumes x ime 1 2 g Be y ia Sip 4 5 OE Le eae wie e primet Clin yp rae iLiaHe JE Wine ine xp ime WW PSECU Kry 4 17 Argument Passing declare var fncl1 asa pointer to an int function declare var fp2 as pointer to an int function initialize fnc1 to point to int func initialize fp2 to point to the same function call intfunc via fncl call intfunc via fp2 In C function arguments are generally passed by value That is arguments passed to a C function are generally
299. to the Stdio Window in dcwd exe Extra input is ignored and missing input causes dccl_cmp to wait for keyboard input at the command line Default None GUI Equivalent Using i is like entering inputs into the Stdio Window in dcwd exe Example dccl_cmp myProgram c i MyInputs txt 220 Dynamic C User s Manual If LibrariesFilePathname Description Compile using a file found in LibrariesFilePathname which lists all libraries to be made available to your programs Default Lib dir GUI Equivalent Select Options Compiler User Defined Libraries File Use from the menu dialog box Example dccl_cmp myProgram c lf MyPath MyLibs txt ne maxNumberOfErrors Description Change the maximum number of errors reported Default A maximum of 10 errors are reported GUI Equivalent Enter the maximum errors reported in the Options Compiler Errors menu dialog box option Example Allows up to 25 errors to be reported dccl_cmp myProgram c ne 25 nw maxNumberOfWarnings Description Change the maximum number of warnings reported Default A maximum of 10 warnings are reported GUI Equivalent Enter the maximum warnings reported in the Options Compiler Warnings menu dialog box option Example Allows up to 50 warnings to be reported dccl_cmp myProgram c nw 50 o OutputFilePathname Description Write header information if specified with h and all program errors warnings and outputs to a text file If the
300. to use RAM The important question is what will you do when your battery runs out 232 Dynamic C User s Manual 17 2 1 User Block The User block is an area near the top of flash reserved for run time storage of persistent data and calibration constants The size of the User block can be read in the global structure member SysIDBlock userBlockSize The functions readUserBlock and writeUser Block are used to access the User block These function take an offset into the block as a parameter The highest offset available to the user in the User block will be SysIDBlock userBlockSize 1 if there are no calibration constants or DAC_CALIB_ADDR 1 if there are See the Rabbit 3000 Designer s Handbook or the Rabbit 2000 Designer s Handbook for more details about the User block 17 2 2 Flash File System For a complete discussion of the file system please see The Flash File System on page 99 17 2 3 WriteFlash2 See the Dynamic C Function Reference Manual for a complete description NOTE There is aWriteFlash function available for writing to the first flash but its use is highly discouraged for reasons of forward source and binary compatibility should flash sector configuration change drastically in a product See Technical Notes 216 and 217 for more information on flash compatibility issues 17 2 4 Battery Backed RAM Static variables and global variables will always be located at the same addresses between power
301. ture errlog Info Resets the exception and restart type counts in the error log buffer header 8 3 5 Examples of Error Log Use To try error logging follow the instructions at the top of the sample programs samples ErrorHandl and ling Generate_runtime_errors c samples ErrorHandl ling Display_errorlog c 96 Dynamic C User s Manual 9 Memory Management Processor instructions can specify 16 bit addresses giving a logical address space of 64K 65 536 bytes Dynamic C supports a 1M physical address space 20 bit addresses An on chip memory management unit MMU translates 16 bit addresses to 20 bit memory addresses Four MMU registers SEGSIZE STACKSEG DATASEG and XPC divide and main tain the logical sections and map each section onto physical memory 9 1 Memory Map A typical Dynamic C memory mapping of logical and physical address space is shown in the fig ure below Xmem Code EA i Internal Interrupt ee External Interrupt Vectors a Root Data Watch Data Watch Code Logical Address Space Figure 3 Dynamic C Memory Mapping Root Code a Root Code Physical Address Space Chapter 9 Memory Management 97 Figure 3 illustrates how the logical address space is divided and where code resides in physical memory Both the static RAM and the flash memory are 128K in the diagram Physical memory starts at address 0x00000 and flash memory is usually mapped to the same addre
302. ty RFU will load a bin file created by Dynamic C to a Rabbit based con troller It can be used to load a program to a controller without Dynamic C present on the host computer and without recompiling the program each time it is loaded to a controller The Dynamic C installation created a desktop icon for the RFU The executable file rfu exe can be found in the directory where Dynamic C was installed Complete instructions are available by clicking on the Help button within the utility The Help document details setup information the file menu options and BIOS requirements A command line version of the RFU is new for DC 7 20 On the command line specify c1IRFU SourceFilePathName options where SourceFilePathName is the path name of the bin file to load to the connected tar get The options are as follows S port baudrate Description Select the comm port and baud rate for the serial connection Default COM1 and 115 200 bps RFU GUI From the Setup Communications dialog box choose values from the Baud Equivalent Rate and Comm Port drop down menus Example c1RFU myProgram bin s 2 115200 t ipAddress tcpPort Description Select the IP address and port Default Serial Connection RFU GUI From the Setup Communications dialog box click on Use TCP IP Con Equivalent nection then type in the IP address and port for the controller that is receiving the bin file or use the Discover radio button Example
303. u option the default project default dcp becomes the active project The active project file name without path or extension is always shown in the leftmost panel of the status bar at the bottom of the Dynamic C main window and is prepended to the Dynamic C version in the title bar except when the active project is the default project Chapter 16 Project Files 227 Changes made to the compilation environment of Dynamic C are automatically updated to the active project unless the active project is factory dcp 16 2 Updating a Project File Unless the active project is factory dcp changes made to any of the following Dynamic C menu selections will cause the active project file to be updated immediately e the Options Compiler dialog box e the Options Communication dialog box e the Options Define target configuration dialog box e the Compile Include debug code RST 28 instructions setting e the Compile Compile to bin file Include BIOS setting Opening or closing files will not immediately update the active project file The project file state of the recently used files appearing at the bottom of the File menu selection and any opened files in edit windows will only by updated when the project closes or when File Projects Save is selected The Message Assembly Memory Dump Registers and Stack debug windows are not edit windows and will not be saved in the project file if you exit Dynamic C while
304. ult size of the buffer is about 4K in extended RAM 94 Dynamic C User s Manual 8 3 2 Initialization and Defaults An initialization of the error log occurs when the BIOS is compiled when cloning takes place or when the BIOS is loaded via the Rabbit Field Utility RFU By default error logging is enabled with messages turned off stack and register dumps turned on and an error log buffer big enough for 78 entries The error log buffer contains header information as well as an entry for each run time error A debug start up will zero out this header structure but the run time error entries can still be exam ined from Dynamic C using the static information in flash The header is at the start of the error log buffer and contains e A status byte e The number of errors since deployment e The index of the last error e The number of hardware resets since deployment e The number of watchdog time outs since deployment e The number of software resets since deployment e A checksum byte Deployment is defined as the first power up without the programming cable attached Repro gramming the board through the programming cable RFU or RabbitLink and starting the pro gram again without the programming cable attached is a new deployment 8 3 3 Configuration Macros These macros are defined at the top of Bios RabbitBios c ENABLE_ERROR_LOGGING Default 0 Disables error logging Changing this to one in the BIOS enables error logging
305. unction is called and restored when the interrupt function returns Writing ISRs in C is not recommended when timing is critical interrupt isr An interrupt service routine returns no value and takes no arguments Chapter 12 Keywords 147 Sets up an interrupt vector at compile time This keyword is available starting with Dynamic C version 7 30 It is intended for use with separate I amp D space interrupt_vector lt INT_VECTOR_NAME gt lt ISR_NAME gt Set up an Interrupt Service Routine for Timer B asm timerb_isr ISR code ret endasm main Variables Setup ISR interrupt_vector timerb_intvec timerb_isr Compile time setup Code interrupt_vector overrides run time setup For run time setup you would replace the interrupt_vector statement above with rcodorg lt INT_VEC_NAME gt apply asm INTVEC_RELAY SETUP timerb_intvec TIMERB_OFS endasm rcodorg rootcode resume This results in a slower interrupt 80 clock cycles are added but a interrupt vector can be mod ified at run time Interrupt vectors that are set up using interrupt_vector are fast but can t be modified at run time since they are set at compile time Declares variables function return values or array elements to be 32 bit integers If nothing else is specified Long implies a signed integer long i j k 32 bit signed unsigned long int w 32 bit unsigned long funct long arg
306. urns 12 However if decrementing the nesting counter in 9 causes the counter to become zero then bios_swpend must be checked to see if a context switch needs to occur 10 If a context switch is not pending then the nesting level is set 9 and the TA ISR exits 12 Ifa context switch is pending then the remaining context of the previous task is saved and a long call which insures that the xpc is saved and restored properly is made to bios_intexit 11 bios_intexit is responsible for switching to the stack of the task that is now ready to run and executing a long call to switch to the new task The remainder of 11 is executed when a previ ously preempted task is allowed to run again Listing 1 asm taskaware_isr push af push regs needed by isr 1 push hl clear interrupt source 2 ld hl1 bios_intnesting increase the nesting count 3 inc h1 ipres optional 4 do processing necessary for interrupt ld a OSRunning MCOS multitasking yet 5 or a ape z taisr_decnesting possibly signal task to become ready 6 call OSIntExit sets bios_swpend if higher prio ready 7 Chapter 18 uC OS II 245 taisr_decnesting push ip 8 ipset 1 ld hl1 bios_intnesting nesting counter 1 dec hl 9 jr nz taisr_noswitch ld a bios_swpend switch pending 10 or a jr z taisr_noswitch push de 11 push be ex af af push af exx push hl push de push be push iy lca
307. vice and LX 2 is the RAM When creating a file the associated logical extents for the data and the metadata can be changed from the default by calling f s_set_1x This functions takes two parameters one to specify the LX for the metadata and the other to specify the LX for the data Thereafter all created files are associated with the specified LXs until a new call to s_set_1x is made Typically there will be a call to S_set_1x before each file is created in order to ensure that the new file gets created with the desired associations The file creation function fcreate may be used to specify the LX for the metadata by providing a valid LX number in the high byte of the func 108 Dynamic C User s Manual tion s second parameter This will override any LX number set for the metadata in fs_set_1x 10 4 2 1 1 Further Partitioning FS2 allows the initial default logical extents to be divided further This must be done before call ing fs_init The function to create sub partitions is called fs_setup This function takes an existing LX number divides that LX according to the given parameters and returns a newly created LX number The original partition still exists but is smaller because of the division For example in a system with LX 1 as a flash device of 256K and LX 2 as 4K of RAM an initial call to fS_setup might be made to partition LX 1 into two equal sized extents of 128K each LX 1 would then be 128K
308. y be used as a pointer to this location by putting the keyword useix before the function or the request can be specified globally by the compiler directive useix The default is nouseix If the IX register is used as a frame reference pointer its pre vious value is pushed on the stack after the function s return address The frame reference point moves to encompass the saved IX value Chapter 11 Using Assembly Language 123 11 4 2 Embedded Assembly Example The purpose of the following sample program asm1 c is to show the different ways to access stack based variables from assembly code void func char ch int i long 1g main char ch rni long 1g ch 0x113 1 0x2233 lg 0x44556677L func ch i 1g void func char ch int i long lg auto int x auto int z x 0x8888 z 0x9999 asm SP i gives the offset of i from the stack frame on entry On the Z180 this is how HL is loaded with the value in i The assembler combines i and SP into one constant ld hl SP i add hl sp ld hl hl On the Rabbit this code does the same ld hl sp SPti This works if func is useix however if the IX register has been changed by the user code this code will fail ld hl ix i This method works in either case because the assembler adjusts the constant SP so changing the function to nouseix with the keyword nouseix or the compiler

Download Pdf Manuals

image

Related Search

Related Contents

  HomeSullivan 405302C-36(3A)[5PC]-24 Instructions / Assembly  Compact 7 HD manuel V1 FR oct 2012  OntoBrowse: A World of Knowledge - ePrints Soton  Brukermanual MOLIFT Partner  DeviceXPlorer OPC Server ユーザーズガイド  PDF資料  User Manual  オットーボック製品 取扱説明書 ( 取扱販売店用 )  UCM6100 series Initial Setup Guide  

Copyright © All rights reserved.
Failed to retrieve file