Image Craft C Com 4 AVR
Image Craft C Com 4 AVR
Image Craft C Com 4 AVR
tm
iMAGEcraft
tm
tm
INTRODUCTION _____________________________________________ 4
IMPORTANT: Registering the Software ______________________________5 Software License Agreement_________________________________________6 About ImageCraft Development Environment __________________________7 Support __________________________________________________________8 Tutorial __________________________________________________________9 Anatomy of a C Program __________________________________________10 Frequently Asked Questions ________________________________________12 File Types and File Extensions ______________________________________14 C References and Tutorials_________________________________________15 Acknowledgments ________________________________________________16
IDE ________________________________________________________ 17
IDE Overview____________________________________________________18 Compiling a Single File ____________________________________________19 Project Manager__________________________________________________20 Editor Windows __________________________________________________21 Status Window ___________________________________________________22 Terminal Emulator _______________________________________________23 Pop Up Menus ___________________________________________________24
REFERENCES ______________________________________________ 25
File Menu _______________________________________________________26 Edit Menu _______________________________________________________27 Search Menu_____________________________________________________28 View Menu ______________________________________________________29 Project Menu ____________________________________________________30 RCS Menu_______________________________________________________31 Tools Menu ______________________________________________________32 Terminal Menu___________________________________________________33 Compiler Options_________________________________________________34 Compiler Options: Paths___________________________________________35 Compiler Options: Compiler _______________________________________36 Compiler Options: Target__________________________________________37 Environment Options _____________________________________________38 Editor and Print Options___________________________________________39 Terminal Options _________________________________________________41
1
DEBUGGING _______________________________________________ 70
Testing Your Program Logic _______________________________________71 COFF Debug and Working With AVR Studio _________________________72 Listing File ______________________________________________________73
INTRODUCTION
LIMITED WARRANTY
LIMITED WARRANTY. ImageCraft warrants that the SOFTWARE will perform substantially in accordance with the accompanying written materials and will be free from defects in materials and workmanship under normal use and service for a period of ninety (90) days from the date of receipt. Any implied warranties on the SOFTWARE are limited to 90 days. Some states do not allow limitations on the duration of an implied warranty, so the above limitations may not apply to you. This limited warranty gives you specific legal rights. You may have others, which vary from state to state. CUSTOMER REMEDIES. ImageCraft entire liability and your exclusive remedy shall be, at ImageCraft s s option, (a) return of the price paid or (b) repair or replacement of the SOFTWARE that does not meet ImageCraft Limited Warranty and that is returned to ImageCraft. This Limited Warranty is void if failure s of the SOFTWARE has resulted from accident, abuse, or misapplication. Any replacement SOFTWARE will be warranted for the remainder of the original warrant period or 30 days, whichever is longer. NO OTHER WARRANTIES. ImageCraft disclaims all other warranties, either express or implied, including but not limited to implied warranties of merchantability and fitness for a particular purpose, with respect to the SOFTWARE, the accompanying written materials, and any accompanying hardware. NO LIABILITY FOR CONSEQUENTIAL DAMAGES. In no event shall ImageCraft or its supplier be liable for any damages whatsoever (including, without limitation damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the SOFTWARE, even if ImageCraft has been advised of the possibility of such damages. The SOFTWARE is not designed, intended, or authorized for use in applications in which the failure of the SOFTWARE could create a situation where personal injury or death may occur. Should you use the SOFTWARE for any such unintended or unauthorized application, you shall indemnify and hold ImageCraft and its suppliers harmless against all claims, even if such claim alleges that ImageCraft was negligent regarding the design or implementation of the SOFTWARE.
Support
Before contacting us, find out the version number of the software by selecting "About ICCAVR" in the Help menu. If you believe you have found a bug, please create the samllest complete example program that exhibits the behavior so we can duplicate the problem. Internet and email are the preferred methods of support. Program updates are available free of charge for the first six months. Files are available from our website: http://www.imagecraft.com Email support questions to support@imagecraft.com
We have two mailing lists pertinent to the AVR users: icc-general and icc-avr, to subscribe, email minimalist@imagecraft.com with the subject subscribe icc-general or subscribe icc-avr
Our postal address and telephone numbers are ImageCraft 706 Colorado Ave. Suite 10-88 Palo Alto, CA 94303 U.S.A. (650) 493-9326 (650) 493-9329 (FAX) If you purchased the product from one of our international distributors, you may wish to query them for support first.
Tutorial
Once you invoke the IDE, choose Project->Open from the menu system. Navigate to the \icc\examples directory and select the project "led." The project manager displays the filename led.c indicating there is one file in this project. Select the project compilation option by Project->Options. Under the "Target" tab, select the target processor. Make changes to the "Paths" tab to match the location where Now select Project->Make. The IDE will now invoke the compiler to compile the project files and display any messages in the Status Window. Assuming there is no error, an output file called led.hex is produced in the same directory as your source file; in this case, \icc\examples. This is a file in Intel HEX format. Most AVR programmers and simulators understand this format, and you can load this program into your target. That's all there is to build a program! If you want to test your program on a tool that accepts COFF debug information, for example the AVR Studio, then you need to select COFF as the output file format under Project->Options. Notice that the often used functions are also available in the button bar and as context sensitive right mouse pop-up menus. For example, you can choose the compiler options by right clicking on the Project Window. Double clicking a file name in the Project Window opens it in the Editor. Go ahead and open led.c this way. For experimentation, try introduce errors, for example, delete a semicolon ";" from a line. Now select Project->Build. The IDE will ask you if you want save the changes first. Select yes and the compilation will commence. This time there should be an error displayed in the Status Window. Clicking on the error line, or clicking on the error symbol on the left on the error line will move the cursor to the offending line in the Editor.
Anatomy of a C Program
A C program must define a function called main. The compiler links your program with the startup code and the library functions into an "executable" file, so called because you can execute it on your target. The purpose of the startup code is described in detail in Startup File. In summary, a C programs needs the target environment to be set up in certain ways and the startup code initializes the target to satisfy these requirements. In general, your main routine performs some initialization stuff and then execute an infinite loop. As an example, lets examine the file led.c in the \icc\examples directory: #include <avr.h> /* This seems to produce the right amount of delay for the LED to be * seen */ void Delay() { unsigned char a, b; for (a = 1; a; a++) for (b = 1; b; b++) ; } void LED_On(int i) { PORTC = ~BIT(i); Delay(); } void main() { int i; DDRC = 0xFF; PORTC = 0xFF;
while (1) { /* forward march */ for (i = 0; i < 8; i++) LED_On(i); /* backward march */ for (i = 8; i > 0; i--) LED_On(i); /* skip */ for (i = 0; i < 8; i += 2) LED_On(i); for (i = 7; i > 0; i -= 2) LED_On(i); } } The main routine is very straightforward. After initializing some IO registers, it executes an infinite loop and changes the LEDs in walking patterns. The LEDs are changed in the routine LED_On, which simply writes the correct values to the IO port. Since the CPU runs very fast, LED_On calls a delay loop so that the patterns can be seen. Since the actual amount of delay is not critical, a pair of nested loops seem to give the right amount of delay. If the actual timing is important, then the routine should use the timer register to count time. The other example, 8515intr.c is very similar but also shows how simple it is to write an interrupt 10
handler in C. While small, these two programs can serve as starting point for your programs.
11
Can you support ISP of the STK-200 or STK-300 boards? Kanda Systems advised us that we should not include ISP support within our IDE since the algorithms is still being revised. Please use the Kanda software instead.
13
14
15
Acknowledgments
The front end of the compiler is lcc: "lcc source code (C) 1995, by David R. Hanson and AT&T. Reproduced by permission." The assembler/linker is a distant descendent of Alan Baldwin's public domain assembler/linker package. The 16-bit arithmetic multiply/divide/modulo routines are written by Atmel. The 32-bit floating point and long arithmetic routines are written by Jack Tidwell. Check out http://www3.igalaxy.net/~jackt for Jack's AVR BASIC compiler, utilities and AVR circuits. The Make utility is by Jacob Navia. Check out Jacob's low cost Win32 compiler http://www.cs.virginia.edu/~lcc-win32. The PROFESSIONAL version includes the GNU RCS utilities and the grep program. The GNU copyleft license specifies that you may redistribute the GNU programs. This does not apply to any other software in this package that is not GNU based. ImageCraft has not modified the GNU programs. The PROFESSIONAL version also includes the Application Builder from Kanda Inc. (http://www.kanda.com) and Jack Tidwell's AvrCalc program. Please report ALL bugs to us directly. All code used with permission.
16
IDE
17
IDE Overview
The IDE is divided into three window panes:
The top left pane is the editor and terminal tabs. The editor is capable of syntax highlighting C elements, plus bookmarks and other features. When opened, the built in terminal emulator also displays as one of the tabbed windows in the editor pane. The top right is the Project Manager window. This pane contains the list of C and assembly files in a project. The bottom pane is the Status Window. Any compilation status is displayed on this pane. In addition, the bottom status bar displays useful information such as the full file name of the currently active editor, the cursor position, and the full file name of the project file. The panes are resizable and you may hide the status window or the project window from view to maximize the editor display. This is done by toggling the appropriate menu item in the View menu. User operations are input through the menus. Frequently used operations are also available on the button bar and as context sensitive right mouse button pop-up menus. The IDE is highly configurable. Browse the choices available from the Option menus.
18
19
Project Manager
The Project Manager allows you to group a list of files into a project and defines compilation options for them. This allows you to break down your program into small modules. When you perform a project Build function, only source files that have been changed are recompiled. Header file dependencies are automatically generated. That is, if a source file includes a header file, then the source file will be automatically recompiled if the header file changes. The Project Manager creates a makefile in standard format. You may examine the generated makefile if you wish. A source file can be written in either C or in assembly. C files must have the .c extension and assembly files must have the .s extension. You may keep any files in the project list. For example, you may keep project documentation files in the Project Manager window. The Project Manager ignores non-source files when performing a Build. Compiler options are kept with the project files so you can have different projects with different targets. When you start a new project, a default set of options is used. You may set the current options as the default or load the default options into the current option set. The default options are kept in the file default.prj in the executable directory where the compiler is located.
20
Editor Windows
The Editor Windows section is the main area of interaction between you and the IDE. It contains a list of opened files in a tabbed notebook control. If you invoke the IDE builtin terminal emulator, it is opened in this section as well. The editor is highly configurable. See Environment Options and Editor Options. If you choose not to use the IDE's builtin editor, you can use your editor of choice. The compiler's output is fairly simple and should be parseable by most advanced editors. Contact us or the editor vendors for details. To enable concurrent viewing and editing of the same file in the IDE's editor and an external editor, you can direct the IDE to detect if any opened files have been changed on the disk (e.g. by an external editor) and to reload the file if changed. To the left of the editor is the gutter where informational glyths are displayed. These include line numbers and bookmarks. Up to 10 bookmarks can be set in the editor.
21
Status Window
The Status Window displays the status information from the IDE, such as from a Project Build. Compiler error messages start with "!E.." and are tagged with a small red sign on the gutter. Clicking on an error status line brings the cursor to the offending line in the editor. The contents of the Status Window can be selected and copied into the Windows Clipboard. When you are performing a Build function, the last line indicates the status of the build. If there is any error, you may scroll backward to find the source of the error(s).
22
Terminal Emulator
The IDE contains a built in terminal emulator. Note that it does not contain any ISP (in System Programming) functions but is a simple terminal, perhaps for your target device to display debugging messages. An ASCII file downloader is also provided.
23
Pop Up Menus
Context sensitive popup menus are available in most places by right-clicking on the mouse. Usually they are a subset of the most popular commands for that window.
24
REFERENCES
25
File Menu
This menu contains file and program related operations. The active editor is the editor tab with the focus. If you select to open a file that is already opened, its editor tab will be made active. The status bar at the bottom gives information about the current active editor tab, including cursor location, whether the file is READONLY or modified, and the full path name of the file. New - Creates an empty editor tab where you can enter text. Reopen... - Contains a list of recently opened files. Select file to reopen it. Open... - Opens a file for editing. Reload... from Disk - Abandons all changes and reload the active file from the disk. Reload... from Back Up - Reloads the active file from the last backup'ed file. See "Save." Save - Saves the active file to the disk. It optionally creates a backup file, of the form <file>.~<ext> before the new contents is saved. See Environment Options. Save As... - Saves the active file to the disk with a new name. Close - Closes the active file. Prompts if the file contains unsaved changes. Compile File... to Object - Compiles the active file to an object file with .o extension. Note that an object file is not directly loadable into a device programmer or simulator such as AVR Studio. See File Types. This is useful to check for any compilation errors with the file, or to create an object file for a library, or a new startup file. Compile File... to Output - Compiles the active file to an output, suitable to be loaded into a device programmer or AVR Studio. Normally you would use the Project Manager to manage a list of the files for your project, but if your project is small, you can simply use this command to create an output. Thecompiler uses the default Compiler Options. Save All - Saves all the currently opened files. Close All - Closes all the currently opened files and the Terminal Tab if opened. Prompts for unsaved changes. Print - Prints the active file. See Print Options for options. Exit - Quits the program. Prompt for unsaved changes.
26
Edit Menu
This menu contains editing operations for the editor. Undo - Undoes last editing changes. Redo - Undoes the last "undo." That is, reapplies the changes you have undone. Cut - Cuts the selected text into the Windows Clipboard. Copy - Copies the selected text into the Windows Clipboard. Note that this works for the Status Window content. Paste - Pastes the Window Clipboard content into the cursor point. Delete - Deletes the selected text. Select All - Selects the entire contents of the active editor. Block Indent - Indents (i.e. shift right) the selected text by the amount specified in the Environment Options -> Editor. Block Outdent - Outdents (i.e. shift left) the selected text by the amount specified in the Environment Options -> Editor.
27
Search Menu
This menu contains the searching functions of the editor. Find... - Finds text in the editor. The search options are: Match Case - If checked, match the case exactly Whole Word - If checked, find match only if the search string is surrounded by white spaces or punctuations. Direction Up/Down - Selects whether to perform the search upward or downward from the cursor. Find in Files... - Available only in the PROFESSIONAL version. Finds text in all the opened files, or all files in the project, or all the files matching the specified filemask (default is *.* or all files). The result of the search is displayed in the Status Window. The search options are: Case Sensitive - If checked, match the case exactly Whole Word - If checked, find match only if the search string is surrounded by white spaces or punctuation. Regular Expression - If checked, then allow grep regular expression. Some of the more commonly used expressions are: . (dot) - any character ^ - the beginning of a line $ - the end of a line [0-9] - any digit [a-z] - any lower case letter (<expr1>|<expr2>) - match either "expr1" or "expr2" ? - match 0 or 1 occurence of the previous expression * - match 0 or more occurences of the previous expression Replace... - Replaces text in the editor. Find Again - Performs another search using the last search string. Jump To Matching Brace - if the cursor is on (i.e. in front of) a brace character, the cursor is moved forward or backward to go the matching brace character. For example, '(' is the matching brace character for ')'. The brace characters are: (, ), [, ], {, }, <, and > Goto Line Number - Prompts for a line number to jump to. Note that you can also have the editor display line numbers in the gutter. Add Bookmark - Adds a bookmark to the line. Note that it is often quicker to simply click on the gutter of a line to add or delete a bookmark. Delete Bookmark - Deletes a bookmark on a line. Next Bookmark - Searches forward until a line with a bookmark is encountered. Goto Bookmark - Jumps to a specific bookmark.
28
View Menu
Project File List - If checked, the Project File List (the right pane) window is displayed. Uncheck it to maximize the editor window size. Status Window - If checked, the Status Window (the bottom pane) is displayed. Uncheck it to maximize the top pane display. Project Makefile - Opens the makefile in READONLY mode. When you Build a project, the Project Builder creates a makefile that describes the dependencies of the project files. Dependencies between the header files (.h files) are determined automatically by the Project Builder. Output Listing File - Opens the listing file (.lst) in READONLY mode. The listing file contains final code addresses for all your program code, excluding the library routines. See Listing File.
29
Project Menu
The menu contains the interface to the Project Builder. Only one project may be open at a time. If there is an open project with unsaved changes and you try to create new project or open another project, you will be prompted to save the changes. New... - Creates a new project file. Prompts for a directory and file name to store the project file. Usually you would keep your project file in the same directory as your source files, although it is not required. Long file names are supported except that paths with embedded spaces are not allowed. The name you give to the project will be used as the name of the program output. For example, if your project is named "foo.prj," then the output is called foo.hex, or foo.cof, depending on the output file format. Open - Opens an existing project file. Open All Files... - Opens all the project source files. Close All Files - Closes all project files that are open. Reopen... - Contains a list of recently opened projects, select to reopen one. Make Project - Determines the project file dependencies and compile changed files to output. Rebuild All - Recompile all project files. Useful if somehow things get out of sync, but if you find that your files are not being recompiled even if they are changed, there may be other causes such as incorrect system dates. Add File(s) - Opens a dialog box and adds files to the project. You may add any files to your project but source files must either be C files (with .c extension) or assembly files (with .s extension). Nonsource files are kept on the project file list but are otherwise ignored by the Project Builder. Remove Selected Files - Removes selected files in the project file list window from the project. Option... - Opens the Compiler Options dialog box. See Compiler Options. Close - Closes the project. Prompts to save changes if needed. Save - Saves the project, including list of project files and compiler options. Save As... - Saves the project to a different name.
30
RCS Menu
Please see Configuration Management with RCS for a general overview of RCS. IDE RCS functions Checkin Selected File(s) - checks in all the selected files in the project list window. A dialog box is displayed for you to enter the checkin message (or in the case of initial checkin, the file description, and to enter an optional label). The files are checked out immediately afterward. This uses the "ci" command with the -l option to check out the files. Checkin Project - checks in all the files in the project. You will get an error message from "ci" if a file has not been changed, you may ignore those errors. The files are checked out immediately afterward. Diff Selected File - displays the differences between different revisions of a file. The default is to compare the last revision with the version that you are currently working on. You can also compare any two versions of the file. The output is displayed in the Status Window. This uses the "rcsdiff" command. Show Log of the Selected File(s) - shows the log entries of the selected files. This is useful to find out the different revision numbers and labels of the files. This uses the "rlog" command.
31
Tools Menu
Environment Options - Opens up the Environment Options and the Terminal Options dialog box. Editor and Print Options - Opens up the Editor and Print Options dialog box. App Builder - Available only in the PROFESSIONAL version. Invokes the Application Builder, which is a program that creates AVR initialization routines based on the selections you make in a series of dialog boxes. Currently only the MEGA device is supported. AVR Calc - Available only in the PROFESSIONAL version. Invokes the AVRCalc program, which is a handy program that displays 32-bits floating point as hexidecimal, and calculates the UART constants and timer registers for a given baudrate or crystal frequency. Configure Tools - Available only in the PROFESSIONAL version. Allows you to add tools to the Tools Menu. When invoked, you can use the dialog box to change the Tools Menu content. The fields of this dialog box are: Menu Name - Name to use in the Tools menu. Program - Full path to the executable. You may use the Browse button to select an executable. Parameters - Parameters to the program. If you specify %f in the content, it will be replaced by the filename of the topmost file being edited. Initial Directory - The directory the IDE switches to before running the program. Capture Output - If checked, the IDE captures the output (standard output and standard error) of the program and displays it on the Status Window. This should only be checked for Win32 Console Mode or DOS programs. Run - Simple interface to run a program. Similar to Windows "Run" function on the Start menu.
Any tools that you configure will appear after the "Run" command.
32
Terminal Menu
This menu interacts with the terminal emulator. View - Toggles whether to display the terminal emulator. Clear Window - Clears the terminal window. ASCII Download... Last File - Downloads the last file. ASCII Download... Browse - Prompts for a file to download. Capture... - Toggles capturing of the terminal output. Prompts for file name when turned on.
33
Compiler Options
There are three tabs in the option dialog box: Paths, Compiler, and Target. There are two buttons in addition to the standard OK, Cancel, and Help: Set As Default - Writes the options to the default option file \icc\bin\default.prj. When you start the IDE or create a new project, it is loaded with the default options. Load Default - Loads the default options into the current setting.
34
35
36
37
Environment Options
This dialog controls the general environment settings of the IDE: Beep on Completing Build - Emits a beep when a build is completed. Verbose Compiler Output - Directs the compiler driver to print out each pass as it processes the file. This shows the exact command line switches passed to each compiler pass. Multiple Row Editor Tabs - Changes the appearance of the editor tabs to use multiple row display instead of single row with scroll arrow when the number of editor labels grows too large to fit in the display. Auto Save Files Before Compiling - Saves the project files automatically when you request a Build. Normally, you are prompted to save unsaved changes for each changed file. Create Backup on Save - When saving a file, copies the last version to a file of the form <file>.~<ext> before overwriting it with the latest modifications. Undo Across Save - Allows undoing of changes even if the file has been saved. Scan for Changes in Opened Files - Periodically scans the opened files to see if the disk version has been changed. This is useful if you are using an external editor while keeping a file opened on this IDE as well. Close Files on Project Closes - Automatically closes all the project files when a project is closed. Printer Setup - Invokes the Printer Setup dialog box.
38
Key Assignments The page allows you to modify the key assignments for editing commands. Code Templates Available only in the PROFESSIONAL version, this page allows you to define and edit "code templates" that you can access with a hotkey combination (defaults to Control-J, or ^J). Code templates are useful for filling out the basic syntactic elements without you doing all the typing. A list of templates for commonly used elements such as the C control structures is provided.
40
Terminal Options
Changing the COM port or the baud rate closes the COM port and reopens it if it was already opened. COM Port - Specifies which COM port the terminal emulator should use. Baudrate - Specifies the Baudrate to use. All Windows standard Baudrate are supported. Flow Control - Controls the method of flow control. ASCII Transfer Protocol - If using ASCII Downloading to transfer output file to a programming device, certain target programmers need certain protocol to be used. Note that the terminal emulator does not support the AVR ISP (In System Programming) function.
41
42
Startup File
The linker links in the startup file before your files, and links the standard library libcavr.a with your program. The startup file is either crtavr.o or crtatmega.o depending on the target device. The startup file defines a global symbol __start which is the starting point of your program. The startup file functions are: I. II. III. IV. V. Initialize the hardware and software stack pointers. Copy the initialized data from the idata area to the data area. Initialize the bss area to zero Call the user main routine. Define the entry point for exit, which is defined as an infinite loop. If main ever returns, it will enter exit and gets stuck there (so much for "exit").
The startup also defines the reset vector. You do not need to modify the startup file to use other interrupts, see Interrupt Handlers. To modify and use a new startup file: cd \icc\libsrc.avr <edit crtavr.s> <open crtavr.s using the IDE> ; ;generate a new crtavr.o ; or wherever you install the compiler
Substitute "crtatmega" for "crtavr" if you are targeting the Mega devices. Note that Mega devices use two words per interrupt entry whereas non-Mega devices only use one word per entry. You can also have multiple startup files. You simply specify the name of the startup file to use in your Project Options dialog box. Note that you must either specify the startup with an absolute pathname or it must be located in the directory specified by the Project Options Library path.
43
44
45
46
Standard IO functions
Since standard file IO is not meaningful for an embedded microcontroller, much of the standard stdio.h content is not applicable. Nevertheless, some IO functions are supported. Use "#include <stdio.h>" before using these functions. You will need to initialize the output port. The lowest level of IO routines consist of the single character input (getchar) and output (putchar) routines. Thus, if you want to use a higher level function on a different device, for example printf to an LCD, all you need to do is to redefine the low level function. See Librarian. To use the standard IO functions with the AVR Studio simulator (the Terminal IO Window), select the appropriate radio button in Compiler Options. int getchar() returns a character from the UART using polled mode. int printf(char *fmt, ..) prints out formatted text according to the format specifiers in the fmt string. The format specifiers are a subset of the standard formats: %d - prints the next argument as a decimal integer %o - prints the next argument as an unsigned octal integer %x - prints the next argument as an unsigned hexadecimal integer %u - prints the next argument as an unsigned decimal integer %s - prints the next argument as a C null terminated string %c - prints the next argument as an ASCII character %f - prints the next argument as a floating point number If a character is specified between and or , then a leading 0 or 0x is printed respectively. If # % o x you specify (letter el) between % and one of the integer format characters, then the argument is l taken to be long, instead of int. printf is supplied in three versions, depending on your code size and features requirements (the more features, the higher the code size): Basic: only %c, %d, %x, %u, and %s format specifier without modifiers are accepted. Long: the long modifier: %ld, %lu, %lx are supported, in addition to the width and precision fields. Floating point: all formats including %f for floating point are supported. The code size is significantly larger as you progress down the list. You select the version to use in the Compiler Options dialog box. int putchar(int c) prints out a single character. The library routine uses the UART in polled mode to output a single character. For convenience, writing a newline character causes a carriage return character to \n \r be output first. int puts(char *s) prints out a string followed by NL. int sprintf(char *buf, char *fmt) prints a formatted text into buf according to the format specifiers in fmt. The format specifiers are the same as in printf().
47
0X indicates a hexadecimal integer, 0 indicates an octal integer, with a decimal integer assumed otherwise. If "endptr" is not NULL, then *endptr will be set to where the conversion ends in s. unsigned long strtoul(char *s, char **endptr, int base) is the same thing as "strtol" except that the number to be converted is an unsigned long and the return value is unsigned long.
49
String Functions
The following String functions are supported. Use "#include <string.h>" before using these functions. <string.h> defines NULL and typedefs size_t, and the following string and character array functions: void *memchr(void *s, int c, size_t n) searches for the first occurrence of "c" in the array "s" of size "n." It returns the address of the matching element or the null pointer if no match is found. int memcmp(void *s1, void *s2, size_t n) compares two arrays, each of size "n." It returns 0 if the arrays are equal and greater than 0 if the first different element in "s1" is greater than the corresponding element in "s2." Otherwise, it returns a number less than 0. void *memmove(void *s1, void *s2, size_t n) copies "s2" into "s1," each of size "n." The routine works correctly even if the inputs overlap. It returns s1. void *memset(void *s, int c, size_t n) stores "c" in all elements of the array "s" of size "n." It returns s. char *strcat(char *s1, char *s2) concatenates "s2" into "s1." It returns s1. char *strchr(char *s, int c) searches for the first occurrence of "c" in "s," including its terminating null character. It returns the address of the matching element or the null pointer if no match is found. int strcmp(char *s1, char *s2) compares two strings. It returns 0 if the strings are equal, and greater than 0 if the first different element in "s1" is greater than the corresponding element in "s2." Otherwise, it returns a number less than 0. char *strcpy(char *s1, char *s2) copies "s2" into "s1." It returns s1. size_t strcspn(char *s1, char *s2) searches for the first element in "s1" that matches any of the elements in "s2." The terminating nulls are considered part of the strings. It returns the index where the match is found. size_t strlen(char *s) returns the length of "s." The terminating null is not counted. char *strncat(char *s1, char *s2, size_t n) concatenates up to "n" elements, not including the terminating null, of "s2," into "s1." It then copies a null character onto the end of s1. It returns s1. int strncmp(char *s1, char *s2, size_t n) is the same as the strcmp function except it compares at most "n" characters. char *strncpy(char *s1, char *s2, size_t n) is the same as the strcpy function except it copies at most "n" characters. char *strpbrk(char *s1, char *s2) does the same search as the strcspn function except that it returns the pointer to the matching element in "s1" if the element is not the terminating null. Otherwise, it returns a null pointer. char *strrchr(char *s, int c) 50
searches for the last occurrence of "c" in "s" and returns a pointer to it. It returns a null pointer if no match is found. size_t strspn(char *s1, char *s2) searches for the first element in "s1" that does not match any of the elements in "s2." The terminating null of s2 is considered part of s2. It returns the index where the condition is true. char *strstr(char *s1, char *s2) finds the substring of "s1" that matches "s2." It returns the address of the substring if found and a null pointer otherwise.
51
52
53
54
55
Stacks
The generated code uses two stacks: a hardware stack that is used by the subroutine calls and interrupt handlers, and a software stack for allocating stack frame for parameters, temporary and local variables. Although it may seem cumbersome, using two stacks instead of one allows the most transparent use of the data RAM. The hardware stack is allocated at top of the data memory, and the software stack is allocated a number of bytes below that. The size of the hardware stack and the size of the data memory are controlled by settings in the target tab of the Compiler Options. The data area is allocated starting at 0x60, right after the IO space. This allows the data area and the software stack to grow toward each other. You must not allow the hardware stack to grow into the software stack, otherwise Bad Things Can Happen (tm). A later release of the linker may automatically choose an optimal size of the hardware stack, unless recursive functions are involved. A downside of allocating the stacks at the top of the data memory is that if external SRAM is used for additional data memory, then accesses to the stacks are slowed down by at least one additional clock cycle. A different method would place the stacks in the internal SRAM (which does not incur the additional clock penalty), and place global data in the external SRAM. Fortunately, since we provide the full source code to the startup file (and the library functions), you may modify the startup file to use this method instead.
56
Inline Assembly
Besides writing assembly functions in assembly files, inline assembly allows you to write assembly code within your C file. The syntax is: asm("<string>"); Multiple assembly statements can be separated by the newline character \n. String concatenations can be used to specify multiple statements without using additional asm keywords. To access a C variable inside an assembly statement, use the %<name> format: register unsigned char uc; asm("wdt\n" "sleep\n" "in %uc,$16"); // read PORT B
Any C variable can be referenced this way (excluding C goto labels). If you use an assembly instruction that requires a CPU register, then you must use the register storage class to force a local variable to be allocated in a CPU register. Since the register storage class is meaningless for function arguments, you must copy function arguments into local register variables before using them in such context. It is possible that no CPU registers are available if you have declared too many register variables in that function. Inline assembly may be used inside or outside of a C function. The compiler indents each line of the inline assembly for readability. Unlike the AVR assembler, the ImageCraft assembler allows labels to be placed anywhere (not just the first column) so you may create assembly labels in your inline assembly code.
57
IO Registers
IO registers, including the Status Register SREG, can be accessed in two ways. The IO addresses between 0x00 to 0x3F can be used with the IN and OUT instructions to read and write the IO registers, or the data memory addresses between 0x20 to 0x5F can be used with the normal data accessing instructions and addressing modes. Both methods are available in C: Data memory addresses. A direct address can be used directly through pointer indirection and type casting. For example, SREG is at data memory address 0x5F: unsigned char c = *(volatile unsigned char *)0x5F; // read SREG *(volatile unsigned char *)0x5F |= 0x80; Interrupt bit // turn on the Global
Note that data memory 0 to 31 refer to the CPU registers! Extreme care must be taken not to change the CPU registers inadvertently. This is the preferred method since the compiler automatically generates the low level instructions such as in, out, sbrs, sbrc, etc. when accessing data memory in the IO register region. IO addresses. You may use inline assembly and preprocessor macros to access IO addresses: register unsigned char uc; asm("in %uc,$3F"); asm("out $3F,%uc"); // read SREG // turn on the Global Interrupt bit
In some early releases, this is the only way to use the faster low level in, out instructions but this is no longer the case.
58
Interrupt Handling
C Interrupt Handlers Interrupt handlers can be written in C. In the file where you define the function, before the function definition you must inform the compiler that the function is an interrupt handler by using a pragma: #pragma interrupt_handler <name>:<vector number> * "vector number" is the interrupt's vector number. Note that the vector number starts with one, which is the reset vector. This pragma has two effects: For an interrupt function, the compiler generates the reti instruction instead of the ret instruction, and saves and restores all registers used in the function. The compiler generates the interrupt vector based on the vector number and the target device. For example, #pragma interrupt_handler ... void timer_handler() { ... } The compiler generates the instruction rjmp _timer_handler jmp _timer_handler ; for classic devices, or ; for Mega devices timer_handler:4
on location 0x06 (byte address) for the classic devices and 0xC (byte address) for the Mega devices (Mega devices use 2 word interrupt vector entries vs. 1 word for the classic non-Mega devices). You may place multiple names in a single interrupt_handler pragma, separated by spaces. If you wish to use one interrupt handler for multiple interrupt entries, just declare it multiple times with different vector numbers. For example: #pragma interrupt_handler timer_ovf:7 timer_ovf:8 Assembly Interrupt Handlers You may write interrupt handlers in assembly. However, beware that if you call C functions inside your assembly handler, then the assembly routine must save and restore the volatile registers (see Assembly Interface) since the C functions do not do that (unless they are declared as interrupt handlers, but then they should not be called directly). If you use assembly interrupt handlers, then you must define the vectors yourself. You use the "abs" attribute to declare an absolute area (see Assembler Directives) and use the ".org" statement to assign the rjmp or jmp instruction at the right location: ; for all but the ATMega devices .area vectors(abs) .org 0x6 rjmp _timer ; interrupt vectors
; for the ATMega devices .area vectors(abs) .org 0xC 59 ; interrupt vectors
jmp _timer
60
Accessing EEPROM
The EEPROM can be accessed at runtime using library functions. Use "#include <avr.h> before calling these functions: unsigned char EEPROMread(int location) Reads a byte from the specified EEPROM location. int EEPROMwrite(int location, unsigned char byte) Writes a byte to the specified EEPROM location. Returns 0 if successful.
61
62
C RUNTIME ARCHITECTURE
63
(*) "char" is equivalent to "unsigned char" floats and doubles are in IEEE standard 32-bit format with 7 bit exponent and 23-bit mantissa. Bitfield types must be either signed or unsigned but they will be packed into the smallest space. For example: struct { unsigned a : 1, b : 1; }; Sizeof this structure is only 1 byte.
64
65
66
C Machine Routines
Most C operations are translated into direct AVR instructions. However, there are some operations that are translated into subroutine calls since they involve many machine instructions and would cause too much code bloat if the translations are done inline. These routines are written in assembly language and can be distinguished by the fact that the routine names do not start with an underscore. Since they are known to the compiler, they do not use the standard calling convention for increased performance. Some of the commonly encountered routines with the following prefixes: lsr16, lsr32, ... - perform shift operations on 16-bit and 32-bit data mpy, div, mod, neg, rmpy, rdiv, rmod, ... - 32-bit long and floating point routines
67
SW Stack
Heap
Low Address
The bottom of the memory map is address 0. The first 96 (0x60) locations are CPU and IO registers. The compiler places global variables and strings from 0x60 on up. On top of the variables is the area where you can allocate dynamic memory. See Memory Allocation Functions. At the high address, the hardware stack starts at the end of the SRAM. Below that is the software stack which grows downward. It is up to you, the programmer, to ensure that the hardware stack does not grow past the software stack, and the software stack does not grow into the heap. Otherwise, unexpected behaviors will result (oops...).
68
Program Areas
The compiler generates code and data into different "areas." See Assembler Directives. The areas used by the compiler are: Read-Only Memory text - text area containing program code, constant tables, and other read-only data. idata - a read-only area allocated after the "text" area. The initial values for the global data and strings are stored in here. interrupt vectors - usually defined as "memory" area in the startup file. This contains the interrupt vectors. Data Memory data - data area containing global and static variables, and strings. The initial values of the global variables and strings are stored in the "idata" area and copied to the data area at startup time. bss - data area containing "uninitialized" C global variables. Per ANSI C definition, these variables will get initialized to zero at startup time. The job of the linker is to collect areas of the same types from all the input object files and concatenate them together to the output file. See Linker Operations.
69
DEBUGGING
70
71
Once this is done, the simulator uses its Terminal IO Window for UART IO. Limitations of AVR Studio You need AVR Studio 1.52 or higher to work effectively with output from the compiler. As of V2.0 of the Studio, the following bugs remain: AVR Studio displays an extra brace at the end of the source file window AVR Studio does not display stack variables correctly in the Watch window. We are working with Atmel to resolve these issues.
72
Listing File
One of the output files produced by the compiler is a listing file of the name <exec file>.lst. The listing file contains your program's assembly code as generated by the compiler, interspersed with the C source code and the machine code and program locations. While global code and data are always displayed, due to the unfortunate nature of a relocatable linker, some of the static code or data will not be displayed with the final program locations. In addition, library code is not included. Nevertheless, even with these limitations, the listing file is invaluable for debugging your program if you do not have debugging tools that understand the COFF debug format. Some low-cost In Circuit Emulators (ICE) may also use the listing file to drive their debugging, in addition or in place of COFF.
73
74
Compilation Process
[ Underneath the user friendly IDE is a set of command line compiler programs. While you do not need to understand this chapter to use the compiler, this chapter is good for those who want to find out "what's under the hood." ] Given a list of files in a project, the compiler's job is to translate the files into an executable file in Intel HEX format. Normally, the compilation process is hidden from you through the use of the IDE's Project Manager. However, it can be important to have an understanding of what happens under the hood: I. II. III. The compiler compiles each C source file to an AVR assembly file. The assembler translates each assembly file (either from the compiler or assembly files that you have written) into a relocatable object file. After all the files have been translated into object files, the linker combines them together to form an executable file. In addition, a map file, a listing file, and debug information files are also output.
All these details are handled by the compiler driver. You give it a list of files and ask it to compile them into an executable file (default) or to some intermediate stage (e.g. to the object files). The driver invokes the compiler, the assembler and the linker as needed. Actually, the IDE does not even interface with the compiler driver directly. It generates a makefile and invokes the "make" program to interpret the makefile, which causes the compiler driver to be invoked.
75
Driver
The compiler driver examines each input file and acts on the file based on the file's extension and the command line arguments it received. .c files are C source files and .s files are assembly source files respectively. The design philosophy for the IDE is to make it as easy to use as possible. The command line compiler though is extremely flexible. You control its behavior by passing command line arguments to it. If you want to interface with the compiler with your own GUI, for example, the Codewright or Multiedit editor, here are some of the things you need to know. Error messages referring to the source files begin with "!E file(line):.." To bypass the command line length limit on Windows 95/NT, you may put command line arguments in a file, and pass it to the compiler as @file. If you pass it as @-file, the compiler will delete "file" after it is run. The next page, Compiler Arguments, elobarates further on the subject.
76
Compiler Arguments
The IDE controls the behaviors of the compiler by passing command line arguments to the compiler Driver. Normally you do not need to know what these command line arguments do, but you can see them in the generated makefile and in the Status Window when you perform a build. Nevertheless, this page documents the options as used by the AVR IDE in case you want to drive the compiler using your own editor/IDE such as Codewright. All arguments are passed to the driver and the driver in turn passes the appropriate arguments down to different passes. The general format of a command is iccavr [ command line arguments ] <file1> <file2> ... [ <lib1> ... ] where iccavr is the name of the compiler driver. As you can see, you can invoke the driver with multiple files and the driver will perform the operations on all of the files. By default, the driver then links all the object files together to the output file. For most of the common options, the driver knows which arguments are destined for which compiler passes. You can also specify which pass an argument applies to by using a -W<c> prefix. For example: -Wp -Wf -Wa -Wl is the preprocessor. e.g -Wp-e is the compiler proper. e.g. -Wf-atmega is the assembler (letter el) is the linker
Arguments Affecting the Driver itself -c Compiles the file to the object file level only and does not invoke the linker.
-o <name> Names the output file. By default, the output file name is the same as the input file name, or the same as the first input file if you supply a list of files -v Verbose mode. Prints out each compiler pass as it is being executed.
Preprocessor Arguments -D<name>[=value] Defines a macro. See Compiler Options: Macro Define(s). Note that you should define ATMEGA if the target is a ATMega device since there are some definitions in the header file avr.h which depend on this being defined. -U<name> Undefines a macro. See Compiler Options: Macro Undefine(s). -e -I<dir> supplied. Accepts C++ comments. (Capital letter i) Specifies the location(s) to look for header files. Multiple -I flags can be
Compiler Arguments -l -A -A -g (letter el) Generates a listing file. (two -As) Turns on strict ANSI checking. Single -A turns on some ANSI checking. Generates debug information.
-atmega Generate ATMega instructions such as call and jmp instead of rcall and rjmp. Note that you need to use the -Wf prefix since the driver does not know of this option directly (i.e. -Wf-atmega). Assembler Arguments -W Turns on relocation wrapping. See Relative Jump/Call Wrapping. Note that you need to use the -Wa prefix since the driver does not know of this option directly (i.e. -Wa-W). Linker Arguments -L<dir> Specifies the library directory. Only one library directory (the last specified) will be used. 77
-m -g
-u<crt> Uses <crt> instead of the default startup file. If the file is just a name without path information, then it must be located in the library directory. -W Turns on relocation wrapping. See Relative Jump/Call Wrapping. Note that you need to use the -Wl prefix since the driver does not know of this option directly (i.e. -Wl-W). -fcoff -fintelhex -fmots19 Output format is COFF Output format is Intel HEX Output format is Motorola S19 (not used on AVR).
-btext:<address ranges> Assigns the address ranges for the area or section named "text," which is the program memory on the AVR. The format is <start address>[.<end address>] where addresses are word address. For example, some typical values are: -btext:0x60.0x10000 -btext:0x1a.0x800 -btext:0x1a.0x2000 for ATMega for 23xx for 85xx
-bdata:<address ranges> Assigns the address ranges for the area or section named "data," which is the data memory on the AVR. For example, some typical values are: -bdata:0x60.0x800 -bdata:0x60.0x80 -bdata:0x60.0x200 for ATMega for 23xx for 85xx
-dram_end:<address> Defines the end of the data area. This is used by the startup file to initialize the value of the hardware stack. For the classic non-Mega devices without external SRAM, "ram_end" is the size of the SRAM plus 96 bytes of IO and CPU registers minus one. For the Mega devices, it is the size of the SRAM minus one. If a 64K external SRAM is attached, then it is 0xFFFF for all devices. -dhwstk_size:<size> Defines the size of the hardware stack. The hardware is allocated at the top of SRAM, then the software stack follows it. See Stacks. -l<lib name> Links in the specific library files in addition to the default libcavr.a. This can be used to change the behavior of a function in libcavr.a since libcavr.a is always linked in last. The "libname" is the library file name without the "lib" prefix and without the ".a" suffix. For examples: -lstudio -llpavr -lfpavr "libstudio.a" "liblpavr.a" "libfpavr.a" using withAVR Studio IO using full printf using floating point printf
78
TOOLS REFERENCES
79
80
Assembler Syntax
The assembler has the following syntax Names All names in the assembler must conform to the following specification: (_ | [a-Z]) [ [a-Z] | [0-9] | _ ] * That is, a name must start with either an underscore ( _ ) or an alphabetic character, and followed by a sequence of alphabetics, digits, or underscores. In this document, names and symbols are synonyms with each other. A name is either the name of a symbol, which is a constant value, or the name of a label, which is the value of the Program Counter (PC) at that moment. A name can be up to 30 characters in length. Names are case sensitive except for instruction mnenomics and assembler directives. Name Visibility A symbol may either be used only within a program module or it can be made visible to other modules. In the former case, the symbol is said to be a local symbol, and in the latter case, it is called a global symbol. If a name is not defined within the file it is referenced in, then it is assumed to be defined in another module and its value will be resolved by the linker. The linker is sometimes referred as a relocatable linker precisely because one of its purposes is to relocate the values of global symbols to their final addresses. Numbers If a number is prefixed with 0x or $, then the number is taken to be a hexadecimal number: Example: 10 0x10 $10 0xBAD 0xBEEF 0xC0DE -20 Input File Format Input to the assembler must be an ASCII file that conforms to certain conventions. Each line must be of the form: [label: [:]] [command] [operands] [;comments] [] optional field Each field must be separated from another field by a sequence of one or more space characters,which are either spaces or tabs. Labels A name followed by one or two colons denotes a label. The value of the label is the value of the Program Counter (PC) at that point of the program. A label with two colons is a global symbol; that is, it is visible to other modules. Commands A command can be an AVR instruction, an assembler directive or a macro invocation. The operands 81
field denotes the operands needed for the command. Expressions An instruction operand may involve an expression. For example, the direct addressing mode is simply an expression: lds R10,asymbol asymbolis an example of the simplest expression, which is just a symbol or label name. In general, an expression is described by: expr: term | { expr } unop expr expr binop expr term: . name | #name Parentheses () provide grouping. Operator precedents are given below. Expressions cannot be arbitrarily complex, due to the limitations of relocation information communicated to the linker. The basic rule is that for an expression, there can only be only one relocatable symbol. For example, lds R10,foo+bar is invalid if both foo and bar are external symbols. Operators The following is the list of the operators and their precedents. Operators with higher precedents are applied. Only the addition operator may apply to a relocatable symbol (i.e. an external symbol). All other operators must be applied to constants or symbols resolvable by the assembler (i.e. a symbol defined in the file). OPERATOR * / % << >> ^ & | FUNCTION multiply divide modulo left shift right shift bitwise exclusive OR bitwise exclusive AND bitwise OR negate TYPE binary binary binary binary binary binary binary binary unary PRECEDENT 10 10 10 5 5 4 4 4 11 <- current program counter
82
~ < >
11 11 11
Dot or Program Counter If a dot (.) appears in an expression, then the current value of the Program Counter (PC) is used in place of the dot.
83
Assembler Directives
Assembly directives are commands to the assembler. Directives are case insensitive. .area <name> [(attributes)] Defines a memory region to load the following code or data. The linker gathers all areas with the same name together and either concatenates or overlays them depending on the area attributes. The attributes are: s abs, or rel followed by con, or ovr <- concatenated <- overlay <- absolute area <- relocatable area
The starting address of an absolute area is specified within the assembly file itself whereas the starting address of a relocatable area is specified as a command option to the linker. For an area with the con attribute, the linker concatenates areas of that name one after another. For an area with the ovr attribute, for each file, the linker starts an area at the same address. The following illustrates the differences: file1.o: .area text <- 10 bytes, call this text_1 .area data <- 10 bytes .area text <- 20 bytes, ca ll this text_2 file2.o: .area data <- 20 bytes .area text <- 40 bytes, call this text_3 text_1, text_2, and so on are just names used in this example. In practice, they are not given individual names. Lets assume that the starting address of the text area is set to zero. Then, if the text area has the "conattribute, text_1 would start at 0, text_2 at 10, and text_3 at 30. If the text area has the ovr attribute, then text_1 and text_2 would again have the addresses 0 and 10 respectively, but text_3, since it starts in another file, would also have 0 as the starting address. All areas of the same name must have the same attributes, even if they are used in different modules. Here are examples of the complete permutations of all acceptable attributes: .area foo(abs) .area foo(abs,con) .area foo(abs,ovr) .area foo(rel) .area foo(rel,con) .area foo(rel,ovr) .ascii strings 84
.asciz strings These directives are used to define strings, which must be enclosed in a delimiter pair. The delimiter can be any character as long as the beginning delimiter matches the closing delimiter. Within the delimiters, any printable ASCII characters are valid, plus the following C-style escape characters, all of which start with a backslash ( ): \ \e \b \f \n \r \t escape backspace form feed line feed carriage return tab
\<up to 3 octal digits> character with value equal to the octal digits ASCIZ adds a NUL character (\0) at the end. It is acceptable to embed \0 within the string. Examples: asciz Hello World\n asciz 123\0456
.byte
<expr> [,<expr>]*
.word <expr> [,<expr>]* .long <expr> [,<expr>]* These directives define constants. The three directives denote byte constant, word constant (2 bytes) and long word constant (4 bytes) respectively. Word and long word constants are output in little endian format, the format used by the AVR microcontrollers. Note that .long can only have constant values as operands. The other two may contain relocatable expressions. Example: .byte 1, 2, 3 .word label,foo
.blkb <value>
.blkw <value> .blkl <value> These directives reserve space without giving them values. The number of items reserved is given by the operand. .define <symbol> <value> Defines a textual substitution. Whenever "symbol" is used inside an expression (e.g. a register specifier or a label), it is replaced with "value." For example: .define quot R15 mov .else 85 quot,R16
Forms a conditional clause together with a preceding .if and following .endif. If the "if" clause conditional is true, then all the assembly statements from the .else to the ending .endif (the else clause) are ignored. Otherwise, if the "if" clause conditional is false, then the "if" clause is ignored and the elseclause is processed by the assembler. See .if. .endif Ends a conditional statement. See .if and .else. .endmacro Ends a macro statement. See .macro. <symbol> = <value> Defines a constant value for a symbol. Example: .if <symbol name> If the symbol namehas a non zero value, then the following code, up to either the .elsestatement or the .endifstatement (whichever occurs first), is assembled. Conditionals can be nested up to 10 levels. For example: .if cond lds R10,a .else lds R10,b .endif would load "a" into R10 if the symbol condis non zero, and load "b" into R10 if condis zero. .include <filename> Processes the contents in the file specified by filename.If the file does not exist, then the assembler will try to open the file name created by concatenating the path specified via the I command line switch with the specified filename. Example: .macro <macroname> Defines a macro. The body of the macro consists of all the statements up to the .endmacro statement. Any assembly statement is allowed in a macro body except for another macro statement. Within a macro body, the expression @digit where digit is between 0 and 9 is replaced by the corresponding macro argument when the macro is invoked. You cannot define a macro name that conflicts with an instruction mnemonic or an assembly directive. See .endmacro and Macro Invocation. For example, Defines a macro named foo: .macro foo lds @0,a mov @1,@0 .endmacro .include registers.h foo = 5
86
Invoking foo with two arguments: foo R10,R11 is equivalent to writing lds R10,a mov R11,R10 .org <value> Sets the Program Counter (PC) to "value." This directive is only valid for areas with the "abs" attribute. Example: .area interrupt_vectors(abs) org 0xFFD0 dc.w reset
.extern <symbol> [, <symbol>]* Makes the symbols defined in the current module visible to other modules. This is the same as having a label name followed by two periods (.). Otherwise, symbols are local to the current module. <macro> [<arg0> [,<args>]*] Invokes a macro by writing the macro name as an assembly command followed by a number of arguments. The assembler replaces the statement with the body of the macro, expanding expressions of the form @digit with the corresponding macro argument. You may specify more arguments than are needed by the macro body but it is an error if you specify less arguments than needed. Example: foo bar,x
87
Linker Operations
The main purpose of the linker is to combine multiple object files into an output file suitable to be loaded by a device programmer or target simulator. The linker can also take input from a "library" which is basically a file containing multiple object files. In producing the output file, the linker resolves any references between the input files. In some details, the linking steps involve: I. II. Makes the Startup File to the first file to be linked. The startup file initializes the execution environment for the C program to run. Appends any libraries that you explicitly requested (or in most cases, as were requested by the IDE) to the list of files to be linked. Library modules that are directly or indirectly referenced will be linked in. All the user specified object files (e.g. your program files) are linked. Appends the standard C library libcavr.a and a special object module endavr.o to the end of the file list. Scans the object files to find unresolved references. Marks the object file (possibly in the library) that satisfies the references and adds to its list of unresolved references. Repeats the process until there are no outstanding unresolved references. Combines all marked object files into an output file. Generates map and listing files as needed.
III. IV.
V.
88
Librarian
A library is a collection of object files in a special form that the linker understands. When a library's component object file is referenced by your program directly or indirectly, then the linker pulls out the library code and links it to your program. The standard supplied library is libcavr.a, which contains the standard C and AVR specific functions. Other libraries, for example, libstudio.a, overrides some functions in libcavr.a so that a different behavior can be achieved without changing your program code. For example, by linking in libstudio.a, your program may use the Terminal IO window under AVR Studio. Of course, the linking process is mostly transparent to you - by choosing the appropriate Compiler Options, the IDE generates the correct switches to the compiler programs. Nevertheless, there are times where you need to modify or create libraries. A command line tool called ilibw.exe is provided for this purpose (note: the PROFESSIONAL version may include capabilities that handle library files within the IDE, please inquire for details). Note that a library file must have the .a extension. See Linker Operations. Compiling a File into a Library Module Each library module is simply an object file. Therefore, to create a library module, you need to compile a source file into an object file. This can be done by opening the file into the IDE, and invoking the File>Compile File To Object command. Listing the Contents of a Library On a command prompt window, change the directory to where the library is, and give the command "ilibw -t <library>". For example, ilibw -t libcavr.a Adding or Replacing a Module I. II. III. Compile the source file into an object module. Copy the library into the work directory Use the command "ilibw -a <library> <module>" to add or replace a module.
For example, the following replaces the putchar function in libcavr.a with your version. cd \icc\libsrc.avr <modify putchar() in iochar.c> <compile iochar.c into iochar.o> copy \icc\lib\libcavr.a ilibw -a libcavr.a iochar.o copy libcavr.a \icc\lib ; copy back ; copy library
ilibw creates the library file if it does not exist. So to create a new library, just give ilibw a new library file name. Deleting a Module The command switch -d deletes a module from the library. For example, the following deletes iochar.o from the libcavr.a library: cd \icc\libsrc.avr copy \icc\lib\libcavr.a ilibw -d libcavr.a iochar.o copy libcavr.a \icc\lib ; copy library ; delete ; copy back
89
libraries
Subset of ANSI C library including printf, memory allocation, strings, and math functions. Target-specific functions such as those for accessing EEPROM and various subsystems (SPI, ADC, etc.)
tools
Make utility. Librarian to manage library file. RCS for source code management. Grep for file searching.
documentation
Online WinHelp also available as printed manual (> 100 pages) and in HTML Help format.
ANSI C compiler
Modern fast C Compiler with full support for the ANSI C language. Support for 32-bit longs and 32-bit IEEE single precision floating point. Target-specific pragmas for writing interrupt handlers. Supports inline assembly and can interface with assembly modules. Optimizations include optimized switch handling, algebraic simplifications, byte operations. Generates reentrant code except for floating point operations. ICC12 supports code paging addressing (*).
technical support
Excellent technical support via email. Typical turnaround time is the same day! Free 6 months maintenance update via download from the web. Low cost annual maintenance plans.
assembler / linker
Relocatable assembler and linker. Assembler directives include conditional processing, include files, macros and textual defines. Multiple named sections, memory address may contain holes for discontiguous memory spaces. Industry standard output formats include Motorola S19 and EABI conformant output, Intel HEX, and AVR COFF.
debugger support
ICC11 supports P&E map file, NoICE11, ImageCraft Integrated Debugger, and COFF and IEEE 695 capable debuggers / ICEs. ICC12 supports P&E map file, Axiom's BDM-12, Motorola's EABI (DWARF) debug format. ICC16 supports P&E map file. ICCAVR supports Atmel's AVR Studio and other COFF capable debuggers. All compilers produce listing files that are usable by most assembly level debuggers using conversion programs.
notes:
iMAGEcraft
www.imagecraft.com
tm
706 Colorado Ave. Palo Alto, CA (650) 493-9326 FAX (650) 493-9329 info@imagecraft.com
libraries
Subset of ANSI C library including printf, memory allocation, strings, and math functions. Target-specific functions such as those for accessing EEPROM and various subsystems (SPI, ADC, etc.)
tools
Make utility. Librarian to manage library file. RCS for source code management. Grep for file searching.
documentation
Online WinHelp also available as printed manual (> 100 pages) and in HTML Help format.
ANSI C compiler
Modern fast C Compiler with full support for the ANSI C language. Support for 32-bit longs and 32-bit IEEE single precision floating point. Target-specific pragmas for writing interrupt handlers. Supports inline assembly and can interface with assembly modules. Optimizations include optimized switch handling, algebraic simplifications, byte operations. Generates reentrant code except for floating point operations. ICC12 supports code paging addressing (*).
technical support
Excellent technical support via email. Typical turnaround time is the same day! Free 6 months maintenance update via download from the web. Low cost annual maintenance plans.
assembler / linker
Relocatable assembler and linker. Assembler directives include conditional processing, include files, macros and textual defines. Multiple named sections, memory address may contain holes for discontiguous memory spaces. Industry standard output formats include Motorola S19 and EABI conformant output, Intel HEX, and AVR COFF.
debugger support
ICC11 supports P&E map file, NoICE11, ImageCraft Integrated Debugger, and COFF and IEEE 695 capable debuggers / ICEs. ICC12 supports P&E map file, Axiom's BDM-12, Motorola's EABI (DWARF) debug format. ICC16 supports P&E map file. ICCAVR supports Atmel's AVR Studio and other COFF capable debuggers. All compilers produce listing files that are usable by most assembly level debuggers using conversion programs.
notes:
iMAGEcraft
www.imagecraft.com
tm
706 Colorado Ave. Palo Alto, CA (650) 493-9326 FAX (650) 493-9329 info@imagecraft.com