Home
CodeVisionAVR User Manual
Contents
1. and initialize the array pp 0 m1 pp 1 m2 Pointers to functions are always 16 bits wide because they are used to access the FLASH memory area There is no need to use the flash keyword for these types of pointers Example Declare a function int sum int a int b return atb Declare and initialize a global pointer to the function sum int sum_ ptr int a int b sum void main void int ae Call the function sum using the pointer i sum ptr 1 2 1998 2003 HP InfoTech S R L Page 81 CodeVisionAVR 3 13 Accessing the I O Registers The compiler uses the sfrb and sfrw keywords to access the AVR microcontroller s I O Registers using the IN and OUT assembly instructions Example Define the SFRs sfrb PINA 0x19 8 bit access to the SFR sfrw TCNT1 0x2c 16 bit access to the SFR void main void unsigned char a a PINA Read PORTA input pins TCNT1 0x1111 Write to TCNT1IL amp TCNT1H registers The addresses of I O registers are predefined in the following header files located in the INC subdirectory tiny22 h tiny26 h 9082313 9082323 9082333 9082343 90s4414 9084433 90s4434 90s8515 9088534 90s8535 megal03 egal28 egal6 h egal6l h egal62 h egal63 h egal69 h ega32 h ega323 h ega603 h ega64 h ega8 h ega8515 h mega8535 h 43usb355 h 76c711 h 86rf401 h 94k h TyTTTeee ves
2. Enumerations can be stored in SRAM or EEPROM To specify the storage in EEPROM the eeprom keyword must be used Example eeprom enum days sunday monday tuesday wednesday thursday friday saturday days of week It is recommended to treat enumerations as having 8 bit char data type by checking the 8 bit enums check box in Project Configure CompilerCode Generation This will improve the size and execution speed of the compiled program 1998 2003 HP InfoTech S R L Page 75 CodeVisionAVR 3 7 7 Global Variables Memory Map File During compilation the C compiler generates a Global Variables Memory Map File in which are specified the SRAM address location register allocation and size of the global variables used by the program This file has the map extension and can be viewed using the menu File Open command or by pressing the Open button on the toolbar Structure and union members are listed individually along with their corresponding address and size This file is useful during program debugging using the AVR Studio debugger 3 8 Defining Data Types User defined data types are declared using the typedef reserved keyword The syntax is typedef lt storage modifier gt lt type definition gt lt identifier gt The symbol name lt identifier gt is assigned to lt type definition gt Examples type definitions typedef unsigned char byte typedef eeprom struct int a char b 5 eepr
3. 1998 2003 HP InfoTech S R L Page 37 CodeVisionAVR 2 3 Tools Using the Tools menu you can execute other programs without exiting the CodeVisionAVR IDE 2 3 1 The AVR Studio Debugger The CodeVisionAVR C Compiler is designed to work in conjunction with the Atmel AVR Studio debugger version 3 or 4 Before you can invoke the debugger you must first specify its location and file name using the Settings Debugger menu command Debugger Settings Ea Directory and Filename C Program Files Atmel AVR Tools AvrStudio4 AYR Studi El Debugger Atmel AVR Studio 4 xX Cancel The AVR Studio version must be specified in the Debugger list box Changes can be saved respectively canceled using the OK respectively Cancel buttons The debugger is executed by selecting the Tools Debugger menu command or by pressing the Debugger button on the toolbar 1998 2003 HP InfoTech S R L Page 38 CodeVisionAVR 2 3 2 The AVR Chip Programmer The CodeVisionAVR IDE has a built in In System AVR Chip Programmer that lets you easily transfer your compiled program to the microcontroller for testing The Programmer is designed to work with the Atmel STK500 AVRISP Kanda Systems STK200 300 Dontronics DT006 Vogel Elektronik VTEC ISP Futurlec JRAVR or the MicroTronics ATCPU Mega2000 development boards The type of the used programmer and the printer port can be selected by using the Settings Programmer menu command The Pr
4. A macro can be undefined using the undef directive Example undef ALFA The ifdef ifndef else and endif directives may be used for conditional compilation The syntax is ifdef macro name set of statements 1 else set of statements 2 endif If alfa is a defined macro name then the ifdef expression evaluates to true and the set of statements 1 will be compiled Otherwise the set of statements 2 will be compiled The else and set of statements 2 are optional If alfa is not defined the ifndef expression evaluates to true The rest of the syntax is the same as that for ifdef The if elif else and endif directives may be also used for conditional compilation if expressionl set of statements 1 elif expression2 set of statements 2 else set of statements 3 endif If expression evaluates to true the set of statements 1 will be compiled If expression2 evaluates to true the set of statements 2 will be compiled Otherwise the set of statements 3 will be compiled The else and set of statements 3 are optional 1998 2003 HP InfoTech S R L Page 58 CodeVisionAVR There are the following predefined macros __CODEVISIONAVR__ the version and revision of the compiler represented as an integer example for V1 23 8 this will be 1238 __LINE__ the current line number of the compiled file __FILE__ the current compiled file __TIME__ the current time in hh mm ss form
5. 1998 2003 HP InfoTech S R L Page 185 CodeVisionAVR 5 11 4 Setting the PCF8583 devices If you use the PCF8583 RTC you must select the PCF8583 tab and check the PCF8583 Enabled check box amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USARTI 1Wire 2Wire 2c Lcd BitBanged Project Information Chip External SRAM Ports Analog Comparator ADC SPI l2C l2C Port PORTA SDA Bit 0 SCL Bit fi Ds1621 PoFeses PCFa58 gt M Enabled Address 0 The PCF8583 Address list box allows you to specify the low bit of the I C addresses of the PCF8583 devices connected to the bus Maximum 2 PCF8583 devices can be used The PCF8583 devices are accessed through the Philips PCF8583 Real Time Clock Functions 1998 2003 HP InfoTech S R L Page 186 CodeVisionAVR 5 11 5 Setting the DS1307 devices If you use the DS1307 RTC you must select the DS1307 tab and check the DS1307 Enabled check box amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USART1 1Wire 2Wire 2c Lcd BitBanged Project Information Chip External SRAM Ports Analog Comparator ADC SPI l2C l2C Port PORTA SDA Bit fo SCL Bit fi pirescesrsenesecerssessnees Seoneseovenssereeevessereed Square Wave Output M Enabled Enabled ouT a The DS1307 device is accessed through
6. SRAM End The Working Registers area contains 32x8 bit general purpose working registers The compiler uses the following registers RO R1 R15 R22 R23 R24 R25 R26 R27 R28 R29 R30 and R31 Also some of the registers from R2 to R14 may be allocated by the compiler for global bit variables The rest of unused registers in this range are allocated for global char and int variables Registers R16 to R21 are allocated for local char and int variables The I O Registers area contains 64 addresses for the CPU peripheral functions as Port Control Registers Timer Counters and other I O functions You may freely use these registers in your assembly programs 1998 2003 HP InfoTech S R L Page 86 CodeVisionAVR The Data Stack area is used to dynamically store local variables passing function parameters and saving registers RO R1 R15 R22 R23 R24 R25 R26 R27 R30 R31 and SREG during interrupt routine servicing The Data Stack Pointer is implemented using the Y register At start up the Data Stack Pointer is initialized with the value 5Fh Data Stack Size When saving a value in the Data Stack the Data Stack Pointer decrements When the value is retrieved the Data Stack Pointer in incremented back When configuring the compiler in the Project Configure C Compiler Code Generation menu you must specify a sufficient Data Stack Size so it will not overlap the I O Register area during program execution Th
7. ps1621 Pcrese3 Pc gt M Enabled Address we T Output Active High gt Temperature C Hyst 75 4 o s feo WA The LM75 Address list box allows you to specify the 3 lower bits of the I C addresses of the LM75 devices connected to the bus Maximum 8 LM75 devices can be used The Output Active High check box specifies the active state of the LM75 O S output The Hyst respectively O S spinedit boxes specify the hysterezis respectively O S temperatures The LM75 devices are accessed through the National Semiconductor LM75 Temperature Sensor Functions 1998 2003 HP InfoTech S R L Page 183 CodeVisionAVR 5 11 2 Setting the DS1621 devices If you use the DS1621 thermometer thermostat you must select the DS1621 tab and check the DS1621 Enabled check box amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USART1 1Wire 2Wire 2c Lcd BitBanged Project Information Chip External SRAM Ports Analog Comparator ADC SPI l2C l2C Port PORTA SDA Bit fo SCL Bit fi pevessesscessscesessesensees Racesvecvesvevsseneeusesened M Enabled Address 0 H M Output Active High Temperature trigger C Low Eo 4 High 55 WA The Output Active High check box specifies the active state of the DS1621 Tout output The Low respectively High spinedit boxes specify the low respectively high temperatures trigger
8. i2c_stop return data T write a byte to the EEPROM void eeprom write unsigned char address unsigned char data i2c_start 12c_ write EEPROM BUS ADDRESS i2c_write address i2c_write data i2c_stop 10ms delay to complete the write operation delay ms 10 void main void unsigned char i initialize the I C bus E2C init write the byte 55h at address AAh eeprom write 0xaa 0x55 read the byte from address AAh i eeprom_read 0xaa while 1 loop forever 1998 2003 HP InfoTech S R L Page 124 CodeVisionAVR 4 12 1 National Semiconductor LM75 Temperature Sensor Functions These functions are intended for easy interfacing between C programs and the LM75 C bus temperature sensor The prototypes for these functions are placed in the file Im75 h located in the INC subdirectory This file must be include ed before using the functions The I C bus functions prototypes are automatically include ed with the Im75 h Prior to include ing the Im75 h file you must declare which microcontroller port and port bits are used for communication with the LM75 through the C bus Example the I C bus is connected to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ _ i2c port 0x18 equ _ sda bit 3 equ scl bit 4 endasm
9. break bit case char const continue default defined do double eeprom else enum extern flash float for funcused goto af inline int interrupt long register return short signed sizeof sfrb sfrw static struct switch typedef union unsigned void volatile while 1998 2003 HP InfoTech S R L Page 63 CodeVisionAVR 3 4 Identifiers An identifier is the name you give to a variable function label or other object An identifier can contain letters A Z a z and digits 0 9 as well as the underscore character _ However an identifier can only start with a letter or an underscore Case is significant i e variable1 is not the same as Variable1 Identifiers can have up to 32 characters 3 5 Data Types The following table lists all the data types supported by the CodeVisionAVR C compiler their range of possible values and their size Type Size Bits Range bit 1 0 1 char 8 128 to 127 unsigned char 8 0 to 255 signed char 8 128 to 127 int 16 32768 to 32767 short int 16 32768 to 32767 unsigned int 16 0 to 65535 signed int 16 32768 to 32767 long int 32 2147483648 to 2147483647 unsigned long int 32 0 to 4294967295 signed long int 32 2147483648 to 2147483647 float 32 1 175e 38 to 3 402e38 double 32 1 175e 38 to 3 402e38 The bit data type is supported only for global variables If the Project Configure C
10. Example File will be looked for in the inc directory of the compiler include lt file name gt or File will be looked for in the current project directory If it s not located there then it will be included from the inc directory of the compiler include file name The define directive may be used to define a macro Example define ALFA Oxff This statement defines the symbol ALFA to the value Oxff The C preprocessor will replace ALFA with Oxff in the source text before compiling Macros can also have parameters The preprocessor will replace the macro with it s expansion and the formal parameters with the real ones Example define SUM a b a b the following code sequence will be replaced with int i 2 3 int i SUM 2 3 When defining macros you can use the operator to convert the macro parameter to a character string Example define PRINT MESSAGE t printf t SB RE ees 2 the following code sequence will be replaced with printf Hello PRINT MESSAGE Hello 1998 2003 HP InfoTech S R L Page 57 CodeVisionAVR Two parameters can be concatenated using the operator Example define ALFA a b a b the following code sequence will be replaced with char xy 1 char ALFA x y 1 A macro definition can be extended to a new line by using Example define MESSAGE This is a very long text
11. M ADC Enabled M ADC Interrupt M ADC Noise Canceler M ADC Bandgap ADC Clock fi 25 000 kHz Automatically Scan Inputs M Enabled First p Pd Last i fw Some AVR devices allow the AD conversion to be triggered by an event which can be selected using the Auto Trigger Source list box If you want to generate interrupts when the ADC finishes the conversion then you must check the ADC Interrupt check box If ADC interrupts are used you have the possibility to enable the following functions e by checking the ADC Noise Canceler check box the chip is placed in idle mode during the conversion process thus reducing the noise induced on the ADC by the chip s digital circuitry e by checking the Automatically Scan Inputs Enabled check box the CodeWizardAVR will generate code to scan an ADC input domain and put the results in an array The start respectively the end of the domain are specified using the First Input respectively the Last Input spinedit boxes If the automatic inputs scanning is disabled then a single analog digital conversion can be executed using the function unsigned int read_adc unsigned char adc_input This function will return the analog digital conversion result for the input adc_input The input numbering starts from 0 If interrupts are enabled the above function will use an additional interrupt service routine adc_isr This routine will store the conversion result in the adc_data global variable
12. character will be outputted void sprintf char str char flash fmtstr arg1 arg2 this function is identical to printf except that the formatted text is placed in the null terminated character string str In order to reduce program code size there is the Project Configure C Compiler Code Generation s printf features option It allows linking different versions of the printf and sprintf functions with only the features that are really required by the program The following s printf features are available e int the following conversion type characters are supported c s p i d u x X no width or precision specifiers are supported only the and flags are supported no input size modifiers are supported e int width the following conversion type characters are supported c s p i d u x X the width specifier is supported the precision specifier is not supported only the 0 and flags are supported no input size modifiers are supported e long width the following conversion type characters are supported c s p i d u x X the width specifier is supported the precision specifier is not supported only the 0 and flags are supported only the l input size modifier is supported e long width precision the following conversion type characters are supported c s p i d u x
13. in each project file 1998 2003 HP InfoTech S R L Page 25 CodeVisionAVR The Paths tabs allows to specify additional paths for include and library files These paths must be entered one per line in the appropriate edit controls 4 Configure Project Multfile_prj CACVAYR inc my_header_files CACVAYR lib A my_library_files Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP InfoTech S R L Page 26 CodeVisionAVR 2 2 4 3 Transferring the Compiled Program to the AVR Chip after Make This option is available if you select the After Make tab in the Project Configure window 4 Configure Project Multfile_prj Files C Compiler After Make M Program the Chip l Execute User s Program M Merge data from a ROM File for FLASH Programming ROM File Path c cvavr projects bootloader bootloader rom l Chip Programming Options FLASH Lock Bits Fuse Bit s l CKSELO 0 iG No Protection C CkKSELI lt 0 C Programming disabled Ae MC SUTO 0 C Programming and Verification disabled r SUTI 0 C BODEN 0 Boot Lock Bit 0 BootLock Biti C BODLEVEL 0 C BOOTRST 0 BOl 1 BO2 1 Bll 1 B12 1 C BO1 0 BO2 1 C B11 0B12 1 C B01 0 BO2 0 C B11 0B12 0 C B01 1 B02 0 C B11 1 B12 0 C OCDEN 0 E M Check Signature M Check Erasure Preserve EEPROM M Verify X Cancel Help If you check the Program the Chip opti
14. 0 eee cece entre erent rene eee ee erties ee taeeeeeteeeeetieeeeenieeeetaa 167 5 6 Setting the UART or USART issiran ennaii scence aei aE Aa e A 172 5 7 Setting the Analog Comparator cceceeiineeeee eter ee etieee eee eneeeeeeiieeeeetieeeeesieeeeetieeeeeenieeeeetaa 175 5 8 Setting the Analog Digital Converter cccceeceeeeceeeneeeeeeeneeeeeeaeeeeeeaaeeeeeesnaeeeeeenaeeeenenaeeeensas 176 2 9 Setting the SPlilmterace fists zest ieectihiiecs A E tandeialensetisetintan aT 179 5 10 Setting the Universal Serial Interface USI eee eeeee erties ee eieeeeeeteeeeetaeeeeeteeeer 180 SASettingthe Ire BUS here nts enana e a a aa a aa 182 O21 tel Setting the LM75 UOvViCES er aaa arrra A EEE KENARA ERARE KERETA EENEN ARENA EDERRETAN AERIANA 183 9 12 Setting he D S162 1 AEVO Sen ea Ea EKE 184 5 11 3 Setting the PCF8563 devices eect ee entre erent ee eee ae eee e teases taeeeeeteeeestiaeeeeeeaa 185 5 11 4 Setting the PCF8583 devices eee ceeeee ee enteee erent ee eee e ee ee teee ee taeeeeetieeeeeeiaeeeeeeea 186 5 11 5 Setting the DS1307 devices o v ccccccicsececceeseeeeceteeececeeneeccecheseiencd bautecebnaeececdeneebecbesweec edeeare 187 512 Setting the T Wire BUS aii Nees eea eaae E E ees sedate OARA Aea AA EARE EE EAA AANER subeeddestbecstennerteniee 189 9 13 Seting the 2 Wire BUS mE A E A EEA EEA 191 5 14 Setting the ATmega169 LCD Controller eceeeeecceeeeeeeeteeeee tenets ee tiieeeeeteeeeeetieeeeesneeeeee 192 5 15 Setting the
15. Pressing the Ctrl End keys moves the cursor to the end of the file Portions of text can be selected by dragging with the mouse You can copy the selected text to the clipboard by using the Edit Copy menu command by pressing the Ctrl C keys or by pressing the Copy button on the toolbar By using the Edit Cut menu command by pressing the Ctrl X keys or by pressing the Cut button on the toolbar you can copy the selected text to the clipboard and then delete it from the file Text previously saved in the clipboard can be placed at the current cursor position by using the Edit Paste menu command by pressing the Ctrl V keys or pressing the Paste button on the toolbar Clicking in the right margin of the editor window allows selection of a whole line of text Selected text can be deleted using the Edit Delete menu command or pressing the Ctrl Delete keys The Edit Print Selection menu command allows the printing of the selected text Dragging and dropping with the mouse can move portions of text Pressing the Ctrl Y keys deletes the text line where the caret is currently positioned Selected portions of text can be indented respectively unindented using the Edit Indent Block respectively Edit Unindent Block menu commands or by pressing the Ctrl I respectively Ctrl U keys You can find respectively replace portions of text in the edited file by using the Edit Find respectively Edit Replace menu commands by pressing the Ctrl F respe
16. UT WDTCR R31 DI R31 0x10 UT WDTCR R31 CLEAR R2 R14 LDI R24 13 EDI R26 2 CIR R27 CLEAR REG ST X R30 DEC R24 BRNE CLEAR REG 1998 2003 HP InfoTech S R L Page 88 CodeVisionAVR CLEAR SRAM DI R24 LOW CLEAR SIZE LDI R25 HIGH CLEAR SIZI DI R26 LOW CLEAR START LDI R27 HIGH CLEAR START CLEAR SRAM ST X R30 SBIW R24 1 BRNE CLEAR SRAM T ti GLOBAL VARIABLES INITIALIZATION LDI R30 LOW GLOBAL INI TBL 2 LDI R31 HIGH GLOBAL INI TBL 2 GLOBAL INI NEXT MOV R1 RO ADIW R30 1 ADIW R30 1 MOV R22 R30 MOV R23 R31 MOV R31 RO0 MOV R30 R1 SBIW R30 0 BREQ GLOBAL INI END E3 V R26 R0 IW R30 1 F W R30 1 R24 RO D O D D OV R27 R0 D P OV DIW R30 1 PM MOV R25 R0 ADIW R30 1 GLOBAL INI LOOP L ST X RO0 ADIW R30 1 SBIW R24 1 B M M RNE GLOBAL INI LOOP OV R30 R22 OV R31 R23 RJMP GLOBAL INI NEXT GLOBAL INI END The _CLEAR_START and __CLEAR_SIZE constants can be changed to specify which area of SRAM to clear at program initialization The __GLOBAL_INI_TBL label must be located at the start of a table containing the information necessary to initialize the global variables located in SRAM This table is automatically generated by the compiler 1998 2003 HP InfoTech S R L P
17. X the width and precision specifiers are supported only the 0 and flags are supported only the l input size modifier is supported e float width precision the following conversion type characters are supported c s p i d u e E f x X the width and precision specifiers are supported only the 0 and flags are supported only the l input size modifier is supported The more features are selected the larger is the code size generated for the printf and sprintf functions char gets char str unsigned char len inputs using getchar the character string str terminated by the new line character The new line character will be replaced with 0 The maximum length of the string is len If len characters were read without encountering the new line character then the string is terminated with 0 and the function ends The function returns a pointer to str 1998 2003 HP InfoTech S R L Page 101 CodeVisionAVR signed char scanf char flash fmtstr arg1 address arg2 address formatted text input by scanning using getchar a series of input fields according to the format specifiers in the fmtstr string The format specifier string fmtstr is constant and must be located in FLASH memory The implementation of scanf is a reduced version of the standard C function This was necessary due to the specific needs of an embedded system and because the full
18. ae a ee ee ee E E e You may include the corresponding file for the processor that you use at the beginning of your program 1998 2003 HP InfoTech S R L Page 82 CodeVisionAVR 3 13 1 Bit level access to the I O Registers The bit level access to the I O registers is accomplished using bit selectors appended after the name of the I O register Because bit level access to I O registers is done using the CBI SBI SBIC and SBIS instructions the register address must be in the 0 to 1Fh range for sfrb and in the 0 to 1Eh range for sfrw Example sfrb PORTA 0x1b sfrb DDRA 0x18 sfrb PINA 0x19 void main void set bit 0 of Port A as output DDRA 0 1 set bit 1 of Port A as input DDRA 1 0 set bit 0 of Port A output PORTA 0 1 test bit 1 input of Port A if PINA 1 place some code here To improve the readability of the program you may wish to define symbolic names to the bits in I O registers sfrb PINA 0x19 define alarm input PINA 2 void main void test bit 2 input of Port A if alarm_input place some code here It is important to note that bit selector access to I O registers located in internal SRAM above address 5Fh like PORTF for the ATmega128 for example will not work because the CBI SBI SBIC and SBIS instructions can t be used for SRAM access 1998 2003 HP InfoTech S R L Page 83 CodeVisio
19. aud rate P RTEICTS Data bits E C DTR DSR E ho E Append LF Dioki M On Reception Parity None M On Transmission Emulation Tv M Echo xX Cancel In the Terminal Setup window you can select the computer s communication port used by the Terminal COM1 to COM6 Baud rate used for communication 110 to 115200 number of data bits used in reception and transmission 5 to 8 number of stop bits used in reception and transmission 1 1 5 or 2 parity used in reception and transmission None Odd Even Mark or Space type of emulated terminal TTY VT52 or VT100 type of handshaking used in communication None Hardware CTS or DTR or Software XON XOFF possibility to append LF characters after CR characters on reception and transmission e enabling or disabling the echoing of the transmitted characters Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP InfoTech S R L Page 52 CodeVisionAVR 2 5 Accessing the Help CodeVisionAVR help system is accessed by invoking the Help Help menu command or by pressing the Help toolbar button 2 6 Transferring the License to another computer The CodeVisionAVR C compiler features a computer locked licensing system This means that the first time after purchase you will receive from the author a license file that is specific to your particular computer This prevents you from using the software on anot
20. initialize the LCD for 2 lines amp 16 columns led_init 16 define user character 0 define char char0 0 switch to writing in Display RAM lcd _gotoxy 0 0 lcd putsf User char 0 display used defined char 0 lcd _ putchar 0 while 1 loop forever unsigned char Icd_read_byte unsigned char addr reads a byte from the LCD character generator or display RAM The high level LCD Functions are void Icd_init unsigned char Icd_columns initializes the LCD module clears the display and sets the printing character position at row 0 and column 0 The numbers of columns of the LCD must be specified e g 16 No cursor is displayed This is the first function that must be called before using the other high level LCD Functions void Icd_clear void clears the LCD and sets the printing character position at row 0 and column 0 void Icd_gotoxy unsigned char x unsigned char y sets the current display position at column x and row y The row and column numbering starts from 0 void Icd_putchar char c displays the character c at the current display position void Icd_puts char str displays at the current display position the string str located in SRAM void Icd_putsf char flash str displays at the current display position the string str located in FLASH 1998 2003 HP InfoTech S R L Page 118 CodeVisionAVR 4 11 2 LCD Functions for displays with 4x40 characters The L
21. long c 1111111 void main void Local variables declaration char d int e and initialization long 22222222 Variables can be grouped in arrays which can have up to 8 dimensions The first element of the array has always the index 0 If not specifically initialized the elements of global variable arrays are automatically set to 0 at program startup Example All the elements of the array will be 0 int global arrayl1 32 Array is automatically initialized int global array2 1 2 3 int global array3 4 1 2 3 4 char global array4 This is a string Only the first 3 elements of the array are initialized the rest 29 will be 0 int global array5 32 1 2 3 Multidimensional array int multidim array 2 3 1 2 3 4 5 6 void main void local array declaration int local _arrayl1 10 local array declaration and initialization int local array2 3 11 22 33 char local _array3 7 Hello 1998 2003 HP InfoTech S R L Page 66 CodeVisionAVR Local variables that must conserve their values during different calls to a function must be declared as static Example int alfa void declare and initialize the static variable static int n 1 return nt t void main void int 1 the function will return the value 1 i alfa the function will return the value 2 i alfa If n
22. t1 10 Oxdf display the temperatures led_clear lcd puts display buffer 1998 2003 HP InfoTech S R L Page 129 CodeVisionAVR 4 12 3 Philips PCF8563 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the PCF8563 I C bus real time clock RTC The prototypes for these functions are placed in the file pcef8563 h located in the INC subdirectory This file must be include ed before using the functions The I C bus functions prototypes are automatically include ed with the pcf8563 h Prior to include ing the pef8563 h file you must declare which microcontroller port and port bits are used for communication with the PCF8563 through the I7C bus Example the I C bus is connected to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ _ i2c port 0x18 equ _ sda bit 3 equ scl bit 4 endasm now you can include the PCF8563 Functions include lt pcf8563 h gt The PCF8563 Functions are void rtc_init unsigned char ctrl2 unsigned char clkout unsigned char timer_ctrl this function initializes the PCF8563 chip Before calling this function the C bus must be initialized by calling the i2c_init function This is the first function that must be called prior to using the other PCF8563 Functions Only one PCF8583 chip can be connected to the IC bus The ctrl2 parameter specifies the initialization val
23. temperatures for the Tout output The DS1621 devices are accessed through the Dallas Semiconductor DS1621 Thermometer Thermostat functions 1998 2003 HP InfoTech S R L Page 184 CodeVisionAVR 5 11 3 Setting the PCF8563 devices If you use the PCF8563 RTC you must select the PCF8563 tab and check the PCF8563 Enabled check box amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USARTI 1Wire 2Wire 2c Lcd Bit Banged Project Information Chip ExemalSRAM Pors Analog Comparator ADC SPI lC l2C Port PORTA SDA Bit 0 SCL Bit fi Pca gt V Enabled CLKOUT OFF Alarm Interrupt 0 e clock OFF M Int Enabled Value f1 lv INT Pulses The CLKOUT list box specifies the frequency of the pulses on the CLKOUT output The Alarm Interrupt check box enables the generation of interrupts on the INT pin when the alarm conditions are met The Timer Clock list box specifies the countdown frequency of the PCF8563 Timer If the Int Enabled check box is checked an interrupt will be generated when the Timer countdown value will be 0 If the INT Pulses check box is checked the INT pin will issue short pulses when the Timer countdown value reaches 0 The Timer Value spinedit box specifies the Timer reload value when the countdown reaches 0 The PCF8563 devices are accessed through the Philips PCF8563 Real Time Clock Functions
24. the SCL signal is bit 4 asm equ _ i2c port 0x18 equ _ sda _ bit 3 equ scl bit 4 endasm 1998 2003 HP InfoTech S R L Page 125 CodeVisionAVR include the LM75 Functions include lt lm75 h gt the LCD module is connected to PORTC asm equ _ lcd _port 0x15 endasm include the LCD Functions include lt lcd h gt include the prototype for sprintf include lt stdio h gt include the prototype for abs include lt math h gt char display buffer 33 void main void int CO ei initialize the LCD 2 rows by 16 columns lcd init 16 initialize the I C bus i2c_init initialize the LM75 sensor with address 0 thyst 20 C tos 25 C Im75_init 0 20 25 0 initialize the LM75 sensor with address 1 thyst 30 C tos 35 C Im75_init 1 30 35 0 temperature display loop while 1 read the temperature of sensor 0 10 C tO lm75_ temperature 10 0 read the temperature of sensor 1 10 C tl lm75_ temperature 10 1 prepare the displayed temperatures in the display buffer sprintf display buffer tCO 3 i uScC nt1l 3 i uScc t0 10 abs t0 10 Oxdf t1 10 abs t1 10 Oxdf display the temperatures led_clear lcd puts display buffer 1998 2003 HP InfoTech S R L Page 126 CodeVisionAVR 4 12 2 Dallas
25. 2 endasm include the DS2433 functions prototypes include lt ds2433 h gt The DS2433 functions are unsigned char ds2433_read_block unsigned char romcode unsigned char dest unsigned int addr unsigned int size this function reads a block of size bytes starting from the DS2433 EEPROM memory address addr and stores it in the string dest located in SRAM It returns 1 if successful 0 if not The DS2433 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode unsigned char ds2433_read unsigned char romcode unsigned int addr unsigned char data this function reads a byte from the DS2433 EEPROM memory address addr and stores it in the SRAM memory location pointed by data It returns 1 if successful 0 if not The DS2433 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode unsigned char ds2433_write_block unsigned char romcode unsigned char source unsigned int addr unsigned int size this function writes a block of size bytes from the string source located in SRAM in the DS2433 EEPROM starting from memory address addr It returns 1 if successful 0 if not The DS2433 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode unsigned char ds2433_write unsigned char romcode unsigned int addr unsigned char data this function writes the byte data at DS2433 EEPROM memory address addr I
26. 4 11 3 LCD Functions for displays connected in 8 bit memory mapped mode These LCD Functions are intended for easy interfacing between C programs and alphanumeric LCD modules built with the Hitachi HD44780 chip or equivalent The LCD is connected to the AVR external data and address buses as an 8 bit peripheral This type of connection is used in the Kanda Systems STK200 and STK300 development boards For the LCD connection please consult the documentation that came with your development board These functions can be used only with AVR chips that allow using external memory devices AT90S4414 AT90S8515 ATmega603 ATmega103 ATmega128 ATmega161 and ATmega162 The prototypes for these functions are placed in the file Icdstk h located in the INC subdirectory This file must be include ed before using the functions The following LCD formats are supported in Icdstk h 1x8 2x12 3x12 1x16 2x16 2x20 4x20 2x24 and 2x40 characters The LCD Functions are void _Icd_ready void waits until the LCD module is ready to receive data This function must be called prior to writing data to the LCD with the LLCD_RSO and_LCD_RS1 macros Example enables the displaying of the cursor _lcd_ready _LCD_RSO Oxe The _LCD_RSO respectively LCD_RS1 macros are used for accessing the LCD Instruction Register with RS 0 respectively RS 1 void Icd_write_byte unsigned char addr unsigned char data writes a byte to the LCD character generator
27. AKATAA ERAR PERE ARET AATE EA REAA ERRA FENT ARRENE 103 4 4 Mathematical FUNCUONS ccein an NEEE A 104 Ao SUING FUMCUOMS n TA E A states 107 4 6 Variable Length Argument Lists Macros sseeesseseeeseerreserresetrrssttrrsssttnnssttnnssttnnssttnnnsttnnnnenn 112 4 7 Non local JUMP FUNCTIONS 00 2 ce eee enr ee e a a a a 113 4 8 BCD Conversion Functions assina Ean aeran AEEA EAA ENEEK ROAK A RI NER ER AAAA AEAEE RENARE EINER ERAR 114 4 9 Gray Code Conversion FUNCTIONS ecs resene eaae eE EE AAEE AENEA AEEA 114 4 10 Memory Access Functions 0 ecccecceeeeeeeeeeeeeeeeeeeeeeeeeceneeeeeseeeaeeeeeeeaeeeeseeeaeeeseneaeeeseeaeeeeeeaeegs 115 4 41 LOD FONCIONS viszs seit Hoe i he ae et odd eee ee eee ges aden ives 116 4 11 1 LCD Functions for displays with up to 2x40 characters 20 ceceeeeceeceeeeeeeeeetteneeeeees 116 4 11 2 LCD Functions for displays with 4x40 characters 00 cccccceeeeeeeeeeeeeeeeeeteeeeeeeneeeeteenaees 119 4 11 3 LCD Functions for displays connected in 8 bit memory mapped mode 08 121 AAPG BUS FUNC OMS cing sie n a Meals inchoate a Maeda ite 123 4 12 1 National Semiconductor LM75 Temperature Sensor Functions sceeceeeeeeees 125 4 12 2 Dallas Semiconductor DS1621 Thermometer Thermostat Functions ceeeeeeeees 127 4 12 3 Philips PCF8563 Real Time Clock FUNCtIONS ccccecceceeeeeeeeeeeeeeeeeeeeteeeeeneetaeeeeees 130 4 12 4 Philips PCF8583 Real Time Clock
28. Compiler Code Generation char is unsigned option is checked or pragma uchart is used then char has by default the range 0 255 1998 2003 HP InfoTech S R L Page 64 CodeVisionAVR 3 6 Constants Integer or long integer constants may be written in decimal form e g 1234 in binary form with Ob prefix e g 00101001 in hexadecimal form with Ox prefix e g Oxff or in octal form with 0 prefix e g 0777 Unsigned integer constants may have the suffix U e g 10000U Long integer constants may have the suffix L e g 99L Unsigned long integer constants may have the suffix UL e g 99UL Floating point constants may have the suffix F e g 1 234F Character constants must be enclosed in single quotation marks E g a String constants must be enclosed in double quotation marks E g Hello world If you place a string between quotes as a function parameter this string will automatically be considered as constant and will be placed in FLASH memory Example this function displays a string located in SRAM void display ram char s FE opua wise 7 this function displays a string located in FLASH void display flash char flash s ETT xy void main void this will not work because the function addresses the string as it is located in SRAM but the string Hello world is constant and is placed in FLASH display ram Hello world this wil
29. DS1302 and DS1307 Real Time Clocks initialization e 1 Wire Bus and DS1820 DS18S20 Temperature Sensors initialization e LCD module initialization The Automatic Program Generator is invoked using the Tools CodeWizardAVR menu command or by pressing the CodeWizardAVR command bar button The File New menu command allows creating a new CodeWizardAVR project This project will be named by default untitled cwp The File Open menu command allows loading an existing CodeWizardAVR project Open Project 21x Look in S Bin ics iS c ajtest File name ftest F Files of type CodeWizardAVR projectfiles cwp Cancel 1998 2003 HP InfoTech S R L Page 157 CodeVisionAVR The File Save menu command allows saving the currently opened CodeWizardAVR project The File Save As menu command allows saving the currently opened CodeWizardAVR project under a new name Save C CVAVR BIN untitled cwp As eix Save in S Bin amp al cl File name test i Save as type CodeWizardAVR projectfiles cwp Cancel By selecting the File Program Preview menu option the code generated by CodeWizardAVR can be viewed in an editor window This may be useful when applying changes to an existing project as portions of code generated by the CodeWizardAVR can be copied to the clipboard and then pasted in the project s source files If the File Generate Save and Exit menu option is selected CodeWizardAVR will gene
30. External IRQ Timers USARTO USARTI 1Wire 2Wire 2c Lcd BitBanged Project Information Chip ExternalSRAM Ports Analog Comparator ADC V SPI Enabled M SPI Interrupt T Clock Ratex2 Clock Phase SPI Clock Rate Oycle Halt 1000 000kHz Cycle Start C 250 000 kHz Cock Polarity C 62 500 kHz Bonin C 31 250kHz C High SPI Type rData Order Slave MSB First C Master LSB First Checking the SPI Enabled check box enables the on chip SPI interface If you want to generate interrupts upon completion of a SPI transfer then you must check the SPI Interrupt check box You have the possibility to specify the following parameters e SPI Clock Rate used for the serial transfer Clock Phase the position of the SCK strobe signal edge relative to the data bit Clock Polarity low or high in idle state SPI Type the AVR chip is master or slave Data Order in the serial transfer Checking the Clock Rate x2 check box available for some AVR chips will double the SPI Clock Rate For communicating through the SPI interface with disabled SPI interrupt you must use the SPI Functions If the SPI interrupt is enabled you must use the spi_isr interrupt service routine declared by the CodeWizardAVR 1998 2003 HP InfoTech S R L Page 179 CodeVisionAVR 5 10 Setting the Universal Serial Interface USI By selecting the USI tab of the CodeWizardAVR you
31. FUNCtiONS ccececccceeeeeeeeeeeeeeeeeeeeeesetesntnnaeeeeees 133 4 12 5 Dallas Semiconductor DS1307 Real Time Clock Functions 0 cceeeeeeeeeeeeeeeneees 136 1998 2003 HP InfoTech S R L Page 4 CodeVisionAVR 4 13 Dallas Semiconductor DS1302 Real Time Clock FUNCTIONS 138 4 14 7 Wire ProtoGol FUMGUONS ersen sheceasdieenet dezcetesepcheues ht theca bade neete ten ihghea hd chess ide ceedacteatteeteeta dies 140 4 14 1 Dallas Semiconductor DS1820 DS18S20 Temperature Sensors Functions 142 4 14 2 Dallas Semiconductor DS2430 EEPROM Functions ec cccccceeeeeeeeeeeeeeeeeeeeeeeeeeeaees 146 4 14 3 Dallas Semiconductor DS2433 EEPROM Functions 0 eeccececeeeeeeeeeeeeeeeeeeneeeeeeenaees 149 A193 SPIFUNGCUONS 22 tat aie ee AeA a aes Ale ee Aa al tea Ae ees 152 4 16 Power Management Function Soene asinen a e naa E E EEEE EE AEREE 155 4AT Delay FUnCtOnS osani rie T A A A bie asieatie 156 5 CodeWizardAVR Automatic Program Generator ssssussesnunnennnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn na 157 5 1 Setting the AVR Chip Options iii nunare ane e aaa aae a e a 160 5 2 Setting the External SRAM pesisire r eNA A a hia a RNE AKA AEAN AER 162 5 3 Setting the Input Output Poms i232 ran asena aa aa a a aaa ae aaa a 164 5 4 Setting the External INterrupts cccccccccesetecceeeeeceeeteeeeaeeenedeceeeeneaaeeeseseaeteneeaaeeenebeceeeeeeseaeteeses 165 5 5 Setting the Timers COUNters
32. SRAM tab CodeWizardAVR untitled cwp File Help ExternalIRQ Timers UART Analog Comparator ADC SPI jic 1 Wire LCD Bit Banged Project Information Chip Pots External SRAM size 32k T External SRAM Wait State The size of external SRAM can be specified using the External SRAM Size list box Additional wait states in accessing the external SRAM can be inserted by checking the External SRAM Wait State check box The MCUCR register in the startup initialization code is configured automatically according to these settings 1998 2003 HP InfoTech S R L Page 162 CodeVisionAVR For devices like the ATmega161 that allow splitting the external SRAM in two pages the External SRAM configuration window will look like this CodeWizardAVR untitled cwp File Help External IRQ Timers UARTO UARTI Analog Comparator SPI l2C 1 Wire LCD Bit Banged Project Information Chip ExtemalSRAM Pons External SRAM size 32k External SRAM page configuration 0460h 1FFFh 2000h FFFFh Lower wait states Upper wait states Trw riw Y The External SRAM page configuration list box allows selection of the splitting address for the two external SRAM pages The wait states that are inserted during external SRAM access can be specified for the lower respectively upper memory pages using the Lower wait states respectively Upper wait s
33. Semiconductor DS1621 Thermometer Thermostat Functions These functions are intended for easy interfacing between C programs and the DS1621 I C bus thermometer thermostat The prototypes for these functions are placed in the file ds1621 h located in the INC subdirectory This file must be include ed before using the functions The I C bus functions prototypes are automatically include ed with the ds1621 h Prior to include ing the ds1621 h file you must declare which microcontroller port and port bits are used for communication with the DS1621 through the IC bus Example the I C bus is connected to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ _ i2c port 0x18 equ _ sda bit 3 equ scl bit 4 endasm now you can include the DS1621 Functions include lt ds1621 h gt The DS1621 Functions are void ds1621_init unsigned char chip signed char tlow signed char thigh unsigned char pol this function initializes the DS1621 chip Before calling this function the C bus must be initialized by calling the i2c_init function This is the first function that must be called prior to using the other DS1621 Functions If more then one chip is connected to the C bus then the function must be called for each one specifying accordingly the function parameter chip Maximum 8 DS1621 chips can be connected to the IC bus their chip address can be from 0 to 7 Besides measuring temperature the DS16
34. This is useful when using slow memory devices If an Atmel AT94K05 AT94K10 AT94K20 or AT94K40 FPSLIC device will be used than there will be the possibility to specify the Program SRAM size in Kwords a Configure Project Multfile_prj Files C Compiler After Make Code Generation Globally define Paths SRAM Chip JAT94K 4072 bytes Data Stack size Clock 4 000000 MHz Program SRAM size fi 0 Kwords Memory Model Tiny Data SRAM size fi 6208 bytes Small Code Generation Optimize for Bit Variables size 16 Size f Promote char to int M charis unsigned C Speed i V 8bitenums M Enhanced Core Instructions M Automatic Register Allocation M Use an External Startup Initialization File s printf features Seana amna I Stack End Markers int width Output Format s COF ROM HEXEEP gt I Use the Terminal 1 0 in AVR Studio X Cancel Help 1998 2003 HP InfoTech S R L Page 23 CodeVisionAVR The size of the bit variables which are placed in registers R2 to R14 can be specified using the Bit Variables size list box Checking the Promote char to int check box enables the ANSI promotion of char operands to int This option can also be specified using the pragma promotechar compiler directive Promoting char to int leads to increased code size and lower speed for an 8 bit chip microcontroller like the AVR If the char is uns
35. Variables size 16 z Size I Promote charto int M charis unsigned C Speed V 8bitenums V Enhanced Core Instructions Program Type M Automatic Register Allocation Application M Use an External Startup Initialization Eile M Enable Warnings I Stack End Markers fit width File Output Format s COF ROM HEX EEP M Use the Terminal O in AVR Studio s printf features X Cancel Help You can select the target AVR microcontroller chip by using the Chip combo box You must also specify the CPU Clock Frequency in MHz which is needed by the Delay Functions 1 Wire Protocol Functions and Dallas Semiconductor DS1820 DS18S20 Temperature Sensors Functions The required memory model can be selected by using the Memory Model radio group box The compiled program can be optimized for minimum size respectively maximum execution speed using the Optimize for Size respectively Optimize for Speed settings 1998 2003 HP InfoTech S R L Page 21 CodeVisionAVR For devices that allow self programming the Program Type can be selected as e Application e Boot Loader If the Boot Loader program type was selected a supplementary Boot Loader Debugging in AVR Studio option is available 4 Configure Project Multfile_prj Files C Compiler After Make Code Generation Globally define Paths Chip ATmegal 28 Clock 4 000000 MHz Memory Model Tiny f Small Optimize
36. address 278h e LPT3 at base address 3BCh Programmer Settings EJ AVR Chip Programmer Type Kanda Systems STK200 300 Printer Port LPT2 2786h Z Delay Multiplier fi zj l ATmegal69 CKDIV8 Fuse Warning The Delay Multiplier value can be increased in case of programming problems on very fast machines Of course this will increase overall programming time The Atmega169 CKDIV8 Fuse Warning check box if checked will enable the generation of a warning that further low voltage serial programming will be impossible for the Atmega169 Engineering Samples if the CKDIV8 fuse will be programmed to 0 For usual Atmega169 chips this check box must be left unchecked 1998 2003 HP InfoTech S R L Page 50 CodeVisionAVR The STK500 AVRISP programmers use the RS232C serial communication port which can be specified using the Communication Port list box Programmer Settings Ea AVR Chip Programmer Type Atmel STKS00 AVRISP Communication Port comi l ATmegal69 CKDIV8 Fuse Warning xX Cancel Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP InfoTech S R L Page 51 CodeVisionAVR 2 4 6 Serial Communication Terminal Setup The serial communication Terminal is configured using the Settings Terminal menu command Terminal Settings Eg comz Handshaking Port COM2 v goe C Xon Xoft Baud rate 19600 v Q
37. but never used By double clicking on the error or warning message the line with the problem will be highlighted If no errors were encountered then the Atmel AVR assembler AVRASM32 will be executed obtaining the output file type specified in Project Configure C Compiler Code Generation 1998 2003 HP InfoTech S R L Page 33 CodeVisionAVR After the make process is completed an Information window will open showing the compilation results Pressing the Compiler tab will display compilation results i Information x Compiler Assembler Programmer Chip AT9058515 Memory model Small Optimize for Size s printf features int width Promote char to int No char is unsigned Yes 8 bit enums Yes Automatic register allocation On Use AVR Studio Terminal 70 No 2552 line s compiled No errors No warnings Bit variables size 0 byte s Data Stack area 60h to DFh Data Stack size 128 byte s Estimated Data Stack usage 30 byte s Global variables area E0h to 155h Global variables size 118 byte s Hardware Stack area 156h to 25Fh Hardware Stack size 266 byte s Program size 1349 words FLASH memory usaqe 32 9 1998 2003 HP InfoTech S R L Page 34 CodeVisionAVR Pressing the Assembler tab will display assembly results i Information Compiler Assembler Programmer Creating ds1820 eep Creating ds1820 0bj Creating ds1820 lst Assembling ds1820 asm Inclu
38. compiler does not know what it is done in the assembler portion of the function 1998 2003 HP InfoTech S R L Page 91 CodeVisionAVR 3 19 Creating Libraries In order to create your own libraries the following steps must be followed 1 Create a header h file with the prototypes of the library functions Select the File New menu command or press the New toolbar button The following dialog window will open b Create New File E4 File Type Source C Project X Cancel Select Source and press the OK button A new editor window will be opened for the untitled c source file Type in the prototype for your function Example this pragma directive will prevent the compiler from generating a warning that the function was declared but not used in the program pragma usedt library function prototypes int sum int a int b int mul int a int b pragma used this pragma directive will tell the compiler to compile link the functions from the mylib lib library pragma library mylib lib Save the file under a new name in the INC directory using the File Save As menu command for example mylib h Save C Delphi5 AVRC untitled c As MES Save in inc amp l c a Iwire a 9084434 a Delay ja Lm75 aS fa 90c8534 a 908515 a Ds1302 a Math DE a 9082313 a 9088535 ja Ds1307 a Megal03 BE x 9052323 a 94k10 a Ds1820 a Megal6t ja S a 9052333 ja 94
39. devices are connected to the bus and store their ROM codes in the rom_codes array devices wl search 0xf0 rom_codes display the ROM codes for each detected device printf S u DEVICE S DETECTED n r devices if devices for i O0 i lt devices it t printf DEVICE u ROM CODE IS itl for j 0 3 lt 8 j printf s xX rom_codes i j printf n r 3 he while 1 loop forever 1998 2003 HP InfoTech S R L Page 141 CodeVisionAVR unsigned char w1_crc8 void p unsigned char n this function returns the 8 bit DOW CRC for a block of bytes with the length n starting from address p 4 14 1 Dallas Semiconductor DS1820 DS18S20 Temperature Sensors Functions These functions are intended for easy interfacing between C programs and the DS1820 DS18S20 1 Wire bus temperature sensors The prototypes for these functions are placed in the file ds1820 h located in the INC subdirectory This file must be include ed before using the functions The 1 Wire bus functions prototypes are automatically include ed with the ds1820 h Prior to include ing the ds1820 h file you must declare which microcontroller port and port bits are used for communication with the DS1820 DS18820 through the 1 Wire bus Example specify the port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ wl bit 2 endasm includ
40. h located in the INC subdirectory This file must be include ed before using the functions int atoi char str converts the string str to integer long int atol char str converts the string str to long integer void itoa int n char str converts the integer n to characters in string str void Itoa long int n char str converts the long integer n to characters in string str void ftoa float n unsigned char decimals char str converts the floating point number n to characters in string str The number is represented with a specified number of decimals void ftoe float n unsigned char decimals char str converts the floating point number n to characters in string str The number is represented as a mantissa with a specified number of decimals and an integer power of 10 exponent e g 12 35e 5 float atof char str converts the characters from string str to floating point int rand void generates a pseudo random number between 0 and 32767 void srand int seed sets the starting value seed used by the pseudo random number generator in the rand function 1998 2003 HP InfoTech S R L Page 103 CodeVisionAVR 4 4 Mathematical Functions The prototypes for these functions are placed in the file math h located in the INC subdirectory This file must be include ed before using the functions unsigned char cabs signed char x returns the absolute value of the byte x unsigned int abs int x retur
41. or display RAM Example LCD user defined characters Chip AT90S8515 Memory Model SMALL Data Stack Size 128 bytes Use an 2x16 alphanumeric LCD connected to the STK200 LCD connector include the LCD driver routines include lt lcdstk h gt typedef unsigned char byte 1998 2003 HP InfoTech S R L Page 121 CodeVisionAVR table for the user defined character arrow that points to the top right corner flash byte char0 8 0b0000000 0b0001111 0b0000011 0b0000101 0b0001001 0b0010000 0b0100000 0b1000000 function used to define user characters void define char byte flash pc byte char code byte i a a char_code lt lt 3 0x40 for i 0 i lt 8 i lcd_write byte at pct void main void initialize the LCD for 2 lines amp 16 columns led_init 16 define user character 0 define char char0 0 switch to writing in Display RAM led_gotoxy 0 0 lcd putsf User char 0 display used defined char 0 lcd putchar 0 while 1 loop forever unsigned char Icd_read_byte unsigned char addr reads a byte from the LCD character generator or display RAM void Icd_init unsigned char Icd_columns initializes the LCD module clears the display and sets the printing character position at row 0 and column 0 The numbers of columns of the LCD must be specified e g 16 No cursor is displayed This i
42. parameters using the Data Stack First it pushes the integer parameter a then b and finally the unsigned char parameter c On every push the Y register pair decrements by the size of the parameter 4 for long int 2 for int 1 for char For multiple byte parameters the MSB is pushed first As it is seen the Data Stack grows downward After all the functions parameters were pushed on the Data Stack the Y register points to the last parameter c so the function can read its value in R26 using the instruction Id r26 y The b parameter was pushed before c so it is at a higher address in the Data Stack The function will read it using Idd r27 y 2 MSB and Idd r26 y 1 LSB The MSB was pushed first so it is at a higher address The a parameter was pushed before b so it is at a higher address in the Data Stack The function will read it using Idd r31 y 4 MSB and Idd r30 y 3 LSB The functions return their values in the registers from LSB to MSB e R30 for char and unsigned char e R30 R31 for int and unsigned int R30 R31 R22 R23 for long and unsigned long So our function must return its result in the R30 R31 registers After the return from the function the compiler automatically generates code to reclaim the Data Stack space used by the function parameters The pragma warn compiler directive will prevent the compiler from generating a warning that the function does not return a value This is needed because the
43. pointers must point to the variables that must receive the values of hours minutes seconds and hundreds of a second void rtc_set_alarm_time unsigned char chip unsigned char hour unsigned char min unsigned char sec unsigned char hsec this function sets the alarm time of the RTC The hour min sec and hsec parameters represent the values of hours minutes seconds and hundreds of a second void rtc_get_alarm_date unsigned char chip unsigned char date unsigned char month this function returns the alarm date of the RTC The day and month pointers must point to the variables that must receive the values of date and month void rtc_set_alarm_date unsigned char chip unsigned char date unsigned char month this function sets the alarm date of the RTC 1998 2003 HP InfoTech S R L Page 135 CodeVisionAVR 4 12 5 Dallas Semiconductor DS1307 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the DS1307 C bus real time clock RTC The prototypes for these functions are placed in the file ds1307 h located in the INC subdirectory This file must be include ed before using the functions The IC bus functions prototypes are automatically include ed with the ds1307 h Prior to include ing the ds1307 h file you must declare which microcontroller port and port bits are used for communication with the DS1307 through the C bus Example the I C bus is connect
44. respectively canceled using the OK respectively Cancel buttons When creating a project with multiple files the following rules must be preserved e only C files must be added to the project s Files list e there s no need to include the C files from the Files list as they will be automatically linked e data type definitions and function declarations must be placed in header H files that will be include ed as necessary in the C files e global variables declarations must be placed in the C files where necessary e there s no need to declare global variables that are not static in header H files because if these files will be include ed more than once the compiler will issue errors about variable redeclarations 1998 2003 HP InfoTech S R L Page 20 CodeVisionAVR 2 2 4 2 Setting the C Compiler Options To set the C compiler options for the currently opened project you must use the Project Configure menu command A Configure Project tabbed dialog window will open You must select the C Compiler and Code Generation tabs a Configure Project Multfile_prj Files C Compiler After Make Code Generation Globally define Paths SRAM Chip ATmegal 28 fi 024 bytes Data Stack size Clock 4 000000 MHz Internal SRAM size 4096 bytes Memory Model H External SRAM size fo bytes C Tiny l External SRAM Wait State Small mP Code Generation j Optimize for Bit
45. subdirectory This file must be include ed before using the functions Prior to include ing the 1wire h file you must declare which microcontroller port and port bit is used for communication through the 1 Wire protocol Example the 1 Wire bus is connected to PORTB the data signal is bit 2 asm equ _ wl port 0x18 equ _ wl bit 2 endasm now you can include the 1 Wire Functions include lt lwire h gt Because the 1 Wire Functions require precision time delays for correct operation the interrupts must be disabled during their execution Also it is very important to specify the correct AVR chip clock frequency in the Project Configure C Compiler Code Generation menu The 1 Wire Functions are unsigned char w1_init void this function initializes the 1 Wire devices on the bus It returns 1 if there were devices present or 0 if not unsigned char w1_read void this function reads a byte from the 1 Wire bus unsigned char w1_write unsigned char data this function writes the byte data to the 1 Wire bus It returns 1 if the write process completed normally or 0 if not unsigned char w1_search unsigned char cmd void p this function returns the number of devices connected to the 1 Wire bus If no devices were detected then it returns 0 The byte cmd represents the Search ROM FOh Alarm Search ECh for the DS1820 DS18S820 or other similar commands sent to the 1 Wire device The pointer p po
46. the Dallas Semiconductor DS1307 Real Time Clock Functions In case the square wave signal output is disabled the state of the SQW OUT pin can be specified using the OUT list box 1998 2003 HP InfoTech S R L Page 187 CodeVisionAVR By checking the Square Wave Output Enabled check box a square wave signal will be available on the DS1307 s SQW OUT pin The frequency of the square wave can be selected using the Freq list box Xt CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USART1 1Wire 2Wire 2c BitBanged Project Information Chip ExternalSRAM Pors Analog Comparator ADC SPI l2C 2C Port PORTA SDA Bit 0 SCL Bit 1 piscacscssssessessessssnsens Secessenvensserenscensvenen Square Wawe Outpu M Enabled M Enabled Freg fi v Hz 1998 2003 HP InfoTech S R L Page 188 CodeVisionAVR 5 12 Setting the 1 Wire Bus By selecting the 1 Wire tab of the CodeWizardAVR you can specify the 1 Wire bus configuration amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USART1 BitBanged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI l2C Wie zwe o 1 Wire Port PORTB Data Bit fo DS1820 DS1822 l Enabled Using the 1 Wire Port list box you can specify which port is used for the implementation of the 1 Wire bus The Data Bi
47. to write in a matter of minutes all the code needed for implementing the following functions External memory access setup Chip reset source identification Input Output Port initialization External Interrupts initialization Timers Counters initialization Watchdog Timer initialization UART initialization and interrupt driven buffered serial communication Analog Comparator initialization ADC initialization SPI Interface initialization IC Bus LM75 Temperature Sensor DS1621 Thermometer Thermostat and PCF8563 PCF8583 1302 DS1307 Real Time Clocks initialization 1 Wire Bus and DS1820 DS18S20 Temperature Sensors initialization LCD module initialization oevoeeseeeeeeeee This product is Copyright 1998 2003 Pavel Haiduc and HP InfoTech S R L all rights reserved The author of the program wishes to thank Mr Jack Tidwell for his great help in the implementation of floating point routines and to Mr Yuri G Salov for his excellent work in improving the Mathematical Functions Library and beta testing CodeVisionAVR 1998 2003 HP InfoTech S R L Page 7 CodeVisionAVR 2 CodeVisionAVR Integrated Development Environment 2 1 Working with Files Using the CodeVisionAVR IDE you can view and edit any text file used or produced by the C compiler or assembler 2 1 1 Creating a New File You can create a new source file using the File New menu command or by pressing the Create new file button on the toolbar A dialog b
48. tor Size C Speed Program Type Boot Loader 4096w gt s printf features fint width gt SRAM Data Stack size fi 024 bytes Internal SRAM size 4096 bytes External SRAM size fo bytes I External SRAM Wait State Code Generation Bit Variables size fis I Promote char to int M charis unsigned V 8bitenums V Enhanced Core Instructions M Automatic Register Allocation M Use an External Startup Initialization File MV Enable Warnings T Stack End Markers File Output Format s COF ROM HEX EEP gt I Use the Terminal O in AVR Studio l Boot Loader Debugging in AVR Studio If this option is enabled the compiler will generate supplementary code that allows the Boot Loader to be source level debugged in the AVR Studio simulator emulator When programming the chip with the final Boot Loader code the Boot Loader Debugging option must be disabled The s printf features option allows to select which versions of the printf and sprintf Standard C Input Oputput Functions will be linked in your project e int the following conversion type characters are supported c s p i d w X dee 10 no width or precision specifiers are supported only the and flags are supported no input size modifiers are supported e int width the following conversion type characters are supported c s p i d u x X the width spec
49. type is unsigned int union alpha2 unsigned int a 2 bits 0 1 unsigned int b 8 bits 0 7 unsigned int c 4 bits 0 3 bits 8 15 are not used he this union will occupy 4 bytes in SRAM as the bit field data type is unsigned long union alpha3 unsigned long a 10 bits 0 9 unsigned long b 8 bits 0 7 0 dd unsigned long c 6 bits 5 7 bits 10 31 are not used ae 1998 2003 HP InfoTech S R L Page 74 CodeVisionAVR 3 7 6 Enumerations The enumeration data type can be used in order to provide mnemonic identifiers for a set of char or int values The enum keyword is used for this purpose The syntax is lt storage modifier gt enum lt enum tag name gt lt constant name constant initializer constant name gt lt enum variables gt Example The enumeration constants will be initialized as follows sunday 0 monday 1 tuesday 2 saturday 6 enum days sunday monday tuesday wednesday thursday friday saturday days of week The enumeration constants will be initialized as follows jJanuary 1 february 2 march 3 december 12 enum months january 1 february march april may june july august september october november december months of year void main the variable days of week is initialized with the integer value 6 days of week saturday
50. waveform mode this interrupt will be generated every second frame The frame complete interrupt will be serviced by the Icd_sof_isr function The LCD Duty Cycle list box selects one of the following duty cycles Static 1 2 1 3 or 1 4 The LCD Bias list box selects the 1 3 or 1 2 bias Please refer to the documentation of the LCD manufacturer for bias selection The Clock Source list box selects the system clock or an external asynchronous clock as the LCD controller clock source The Frame Rate spin edit allows specifying the LCD frame rate The LCD Frame Rate Register LCDFRR is initialized based on the frequency of the clock source and the obtainable frame rate that is as close as possible to the one that was specified The Frame Rate Error is calculated based on the specified Frame Rate and the real one obtained from LCDFRR The Used Segments list box setting determine the number of port pins used as LCD segment drivers The Contrast Control list box specifies the maximum voltage on LCD segment and common pins VLCD The VLCD range is between 2 60 and 3 35 Vcc 1998 2003 HP InfoTech S R L Page 192 CodeVisionAVR 5 15 Setting the LCD By selecting the LCD tab of the CodeWizardAVR you can specify the LCD configuration amp CodewizardAVR untitled cwp x File Help External IRQ Timers USARTO USART1 BitBanged Project Information Chip ExtermalSRAM Ports Analog Comparator ADC SPI l2C in
51. 1 and SREG asm push r30 push r31 in r30 SR push r30 endasm zal Q place the C code here now restore SREG R31 and R30 asm pop r30 out SREG r30 pop r3l pop r30 endasm nable register saving for the other interrupts pragma saveregt The default state is automatic saving of registers during interrupts 1998 2003 HP InfoTech S R L Page 60 CodeVisionAVR The automatic allocation of global variables to registers can be turned on or off using the pragma regalloc directive The default state is determined by the Project Configure C Compiler Code Generation Automatic Register Allocation check box Example the following global variable will be automatically allocated to a register pragma regalloct unsigned char alfa the following global variable will not be automatically allocated to a register and will be placed in normal SRAM pragma regalloc unsigned char beta The ANSI char to int operands promotion can be turned on or off using the pragma promotechar directive Example turn on the ANSI char to int promotion pragma promotechart turn off the ANSI char to int promotion pragma promotechar This option can also be specified in the Project Configure C Compiler Code Generation Promote char to int menu Treating char by default as an unsigned 8 bit can be turned on or off using the pragma uchar directive Exam
52. 2003 HP InfoTech S R L Page 40 CodeVisionAVR The Fill Memory Block window can be opened by right clicking in the Edit window EJ Fill Memory Block Ea Start Address fo h End Address FF h Fill Value fo h x Cancel This window lets you specify the Start Address End Address and Fill Value of the memory area to be filled If you wish to check the chip s signature before any operation you must use the Check Signature option To speed up the programming process you can uncheck the Check Erasure check box In this case there will be no verification of the correctness of the FLASH erasure The Preserve EEPROM checkbox allows preserving the contents of the EEPROM during chip erasure To speed up the programming process you also can uncheck the Verify check box In this case there will be no verification of the correctness of the FLASH and EEPROM programming For erasing a chip s FLASH and EEPROM you must select the Program Erase menu command After erasure the chip s FLASH and EEPROM are automatically blank checked For simple blank checking you must use the Program Blank Check menu command If you wish to program the FLASH with the contents of the FLASH buffer you must use the Program FLASH menu command For programming the EEPROM you must use the Program EEPROM menu command After programming the FLASH and EEPROM are automatically verified To program the Lock respectively the Fuse Bit s you must u
53. 21 functions also like a thermostat The Tout output becomes active when the temperature exceeds the thigh limit and leaves the active state when the temperature drops below the tlow limit Both tlow and thigh are expressed in C pol represents the polarity of the DS1621 Tout output in active state If pol is 0 the output is active low and if pol is 1 the output is active high Refer to the DS1621 data sheet for more information unsigned char ds1621_get_status unsigned char chip this function reads the contents of the configuration status register of the DS1621 with address ae to the DS1621 data sheet for more information about this register void ds1621_set_status unsigned char chip unsigned char data this function sets the contents of the configuration status register of the DS1621 with address ee to the DS1621 data sheet for more information about this register void ds1621_start unsigned char chip this functions exits the DS1621 with address chip from the power down mode and starts the temperature measurements and the thermostat 1998 2003 HP InfoTech S R L Page 127 CodeVisionAVR void ds1621_stop unsigned char chip this functions enters the DS1621 with address chip in power down mode and stops the temperature measurements and the thermostat int ds1621_temperature_10 unsigned char chip this function returns the temperature of the DS1621 sensor with the address chip The temperature is in C and is multi
54. 3 4 Executing User Programs User programs are executed by selecting the corresponding command from the Tools menu You must previously add the Program s name to the menu 2 3 4 1 Configuring the Tools Menu You can add or remove User Programs from the Tools menu by using the Tools Configure menu command A Configure Tools dialog window with a list of User Programs will open Configure Tools EG amp Tools amp Avrealce P Add ti Remove N Settings tl X Cancel Help Using the Add button you can add a Program to the Tools menu Using the Remove button you can remove a Program from the Tools menu 1998 2003 HP InfoTech S R L Page 44 CodeVisionAVR Using the Settings button you can modify the e Tool Menu Name Tool Directory and File Name Command Line Parameters Working Directory of a selected Program from the list 4 Tool Settings Ea Tool Name Avrcalc Tool Directory and FileName C CVAVRBIN Avrealc exe El Command Line Parameters Working Directory CACVAVRABIN Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP InfoTech S R L Page 45 CodeVisionAVR 2 4 IDE Settings The CodeVisionAVR IDE is configured using the Settings menu 2 4 1 General Settings The General Settings can be configured using the Settings General menu command General Settings Eg M Show T
55. 40 h By selecting the Timer 1 tab you can have the following options Clock Source specifies the timer counter 1 clock pulse source Clock Value specifies the timer counter 1 clock frequency Mode specifies if the timer counter 1 functioning mode Out A specifies the function of the timer counter 1 output A and depends of the functioning mode Out B specifies the function of the timer counter 1 output B and depends of the functioning mode Out C specifies the function of the timer counter 3 output C and depends of the functioning mode Inp Capt specifies the timer counter 1 capture trigger edge and if the noise canceler is to be used Interrupt on specifies if an interrupt is to be generated on timer counter 1 overflow input capture and compare match e Timer Value specifies the initial value of timer counter 1 at startup e Comp A B and C specifies the initial value of timer counter 1 output compare registers A B and C If timer counter 1 interrupts are used the following interrupt service routines may be defined by the CodeWizardAVR e timer1_ovf_isr for timer counter overflow e timer1_comp_isr or timer1_compa_isr timer1_compb_isr and timer1_copmc_isr for timer counter output compare match e timer1_capt_isr for timer counter input capture You must note that depending of the used AVR chip some of these options may not be present For more information you must consult the corresponding Atmel data sheet 1998 2003 HP InfoT
56. 8 2003 HP InfoTech S R L Page 143 CodeVisionAVR The alarm status for all the DS1820 DS18S20 devices on the 1 Wire bus can be determined by calling the w1_search function with the Alarm Search ECh command Example include lt 90s8515 h gt specify the port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ wl bit 2 endasm include the DS1820 DS18S20 functions prototypes include lt ds1820 h gt include the printf function prototype include lt stdio h gt include the abs function prototype include lt math h gt maximum number of DS1820 DS18S20 connected to the bus define MAX DEVICES 8 DS1820 DS18S20 devices ROM code storage area 9 bytes are used for each device see the wl_search function description but only the first 8 bytes contain the ROM code and CRC unsigned char rom codes MAX DEVICES 9 allocate space for ROM codes of the devices which generate an alarm unsigned char alarm_rom_codes MAX DEVICES 9 main unsigned char i j devices int temp initialize the UART s baud rate UBRR xtal 16 baud 1 initialize the UART control register TX enabled no interrupts 8 data bits UCR 8 detect how many DS1820 DS18S20 devices are connected to the bus and store their ROM codes in the rom_codes array devices wl search 0xf0 rom codes display the numbe
57. 8 2003 HP InfoTech S R L Page 39 CodeVisionAVR If you wish to protect your program from copying you must select the corresponding option using the FLASH Lock Bits radio box The Programmer has two memory buffers e The FLASH memory buffer e The EEPROM memory buffer You can Load or Save the contents of these buffers using the File menu Supported file formats are e Atmel rom and eep e Intel HEX e Binary bin After loading a file in the corresponding buffer the Start and End addresses are updated accordingly You may also edit these addresses if you wish The contents of the FLASH respectively EEPROM buffers can be displayed and edited using the Edit FLASH respectively Edit EEPROM menu commands When one of these commands is invoked an Edit window displaying the corresponding buffer contents will open keys xO xl x2 x3 ond FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF eC Coe coer coor coer 5 x6 x x8 9 FFFF FFFF FFFF FF
58. CD Functions are intended for easy interfacing between C programs and alphanumeric LCD modules with 4x40 characters built with the Hitachi HD44780 chip or equivalent The prototypes for these functions are placed in the file Ilcd4x40 h located in the INC subdirectory This file must be include ed before using the functions Prior to include ing the Icd4x40 h file you must declare which microcontroller port is used for communication with the LCD module Example the LCD module is connected to PORTC asm equ _ lcd port 0x15 endasm now you can include the LCD Functions include lt lcd4x40 h gt The LCD module must be connected to the port bits as follows LCD AVR Port RS pin 11 bit 0 RD pin 10 bit 1 EN1 pin 9 bit 2 EN2 pin 15 bit 3 DB4 pin 4 bit 4 DB5 pin 3 bit 5 DB6 pin 2 bit 6 pin 1 bit 7 You must also connect the LCD power supply and contrast control voltage according to the data sheet The low level LCD Functions are void _Icd_ready void waits until the LCD module is ready to receive data This function must be called prior to writing data to the LCD with the _Icd_write_data function void _Icd_write_data unsigned char data writes the byte data to the LCD instruction register This function may be used for modifying the LCD configuration Prior calling the low level functions _Icd_ready and _Icd_write_data the global variable _e
59. CD es ci sat oe Stace cea ee test ae ae et a od ca ets ee ee 193 5 16 Setting Bit Banged Peripherals c cccecceeeeeceeeeeeeene reer enneee ee tieeeeeteeeeeeiieeeeeetieeeeetiaeeeetaa 194 5 17 Specifying the Project Information s a sse reer irri rien kitra naria REEE ANAKA TENE EA ARTANA EA REEERE KACE NEKANE ERE AA 195 6 License Agreement airsean naina AEAN CARNS AA ARTANA EAA AAAA NSAN A EISS EAKA EAIA AAA AAA RSENS ASSEN AAAA 196 6 1 Software LIGGNSe siae aeria le io lee eat i E iaa ordinei NA 196 1998 2003 HP InfoTech S R L Page 5 CodeVisionAVR 6 2 Liability DISClAINGR 23a ics detent E cae eek eava tec vaedveex N E E 196 6 3 RESUICHONS inai EE E EEE AE 196 6 4 Operating LICCMSE erri Ta AO T T OA ATTRA 196 6 5 Back Up and Transferi naierir ek et ei eae ee nce 196 6 67 16IMS E E ae Ai ie ene ae ee eee 197 6 7 Other Rights and Restrictions s eissaia nEn E Een teens ee etneee ee EA REFEREA KAIRE EARRA TAERAA ERER K RIA UE ERREEN nA 197 TEAK aall Sup olo a EPEAT E TT 198 8 Contact Informati n ossein a a EA A E AE EERE 199 1998 2003 HP InfoTech S R L Page 6 CodeVisionAVR 1 Introduction CodeVisionAVR is a C cross compiler Integrated Development Environment and Automatic Program Generator designed for the Atmel AVR family of microcontrollers The program is a native 32bit application that runs under the Windows 95 98 NT 4 2000 and XP operating systems The C cross compiler implements nearly
60. CodeVisionAVR VERSION 1 23 8b User Manual CodeVisionAVR CodeVisionAVR V1 23 8a User Manual Revision 15 02 2003 Copyright 1998 2003 Pavel Haiduc and HP InfoTech S R L All rights reserved No part of this document may be reproduced in any form except by written permission of the author All rights of translation reserved 1998 2003 HP InfoTech S R L Page 1 CodeVisionAVR Table of Contents Table 0f Content wivisiecicscicreesicteet a A aa aR AAN aaa aaa ai 2 Te mtroduehomM nesan a N N O E E AE 7 2 CodeVisionAVR Integrated Development Environment sssssssssensssennnnrnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn 8 2 1 Working With Files einer da eet vee dice nana evi ieee dn ae dete aie 8 2 1 sCreating a New Fiesse aa eGuide Sian aetna eae aie a 8 2 1 2 Opening an Existing File asi sisccsets ctteat cesteechs REA 9 2 459 FES RIO a EAE E A AA 9 2 NA Editing AFiS eierne ai a a a Mien a a aaa at 10 215 Saving a Flesini ieia i awe Leeda ee eid eds 11 2 16 RENAMING aiFilG 5 tetas eater este TE TA A E E TE A tele reas 11 2 CAPANNA moll beeen rey eee rereer err erre ra a yerrer tree cernre renner er cerr rr eter errr cern ae 12 2 4 6 Closing a Filey innnethehal nanan dee eA ee 13 21 9 Using the Navigator s ic acccetiie aenitin e tii dient esi E A ES 14 2 2 Working with Projects soeia nade it dead ened deactivate 15 2 2 Greating ai New Project siririn an a EE E EE RAEE 15 22 2 Opening an Existing Projects ari
61. DSTACKEND respectively HSTACKEND at the end of the Data Stack respectively Hardware Stack areas When you debug the program with the AVR Studio debugger you may see if these strings are overwritten and consequently modify the Data Stack Size When your program runs correctly you may disable the placement of the strings in order to reduce code size Using the File Output Format s list box you can select one of the following formats for the files generated by the compiler e Intel HEX e COFF required by the Atmel AVR Studio debugger ROM and EEP required by the In System Programmer e Atmel generic OBJ ROM and EEP required by the In System Programmer If the COFF file format is selected and the Use the Terminal I O in AVR Studio check box is checked special debugging information is generated in order to use the AVR Studio Terminal I O window for communication with the simulated AVR chip s UART If the Use the Terminal I O in AVR Studio option is enabled the UART or USART code will not run correctly on the real AVR chip This option is only for debugging purposes 1998 2003 HP InfoTech S R L Page 24 CodeVisionAVR The Globally define tab allows to define macros that will be visible in all the project files For example a Configure Project Multfile_prj Files C Compiler After Make Code Generation Globally define Paths ABC 1234 will be equivalent with placing the definition define ABC 1234
62. FF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF fo p x B xC xD E FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF xF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF M Edit FLASH Buffer BE EI P pre e ee eT ee ee A The buffer s contents at the highlighted address can be modified by typing in the new value The highlighted address can be modified using the arrow Tab Shift Tab PageUp or PageDown 1998
63. Generation Bit Variables Size list box should be as low as possible in order to free registers for allocation to other global variables e f possible use the TINY memory model e Always store constant strings in FLASH by using the flash keyword e After finishing debugging your program compile it again with the Stack End Markers option disabled 3 22 Limitations This version of the CodeVisionAVR C compiler has the following limitations e pointers to pointers are not supported yet e arrays of structures or unions can have only one dimension e for the EVALUATION version the size of the compiled code is limited e the Philips PCF8563 Philips PCF8583 Dallas Semiconductor DS1302 DS1307 4x40 character LCD functions are not available in the EVALUATION version 1998 2003 HP InfoTech S R L Page 96 CodeVisionAVR 4 Library Functions Reference You must include the appropriate header files for the library functions that you use in your program Example Header files are included before using the functions include lt math h gt for abs include lt stdio h gt for putsf void main void int a b a 99 Here you actually use the functions b abs a putsf Hello world 1998 2003 HP InfoTech S R L Page 97 CodeVisionAVR 4 1 Character Type Functions The prototypes for these functions are placed in the file ctype h located in the INC subdirectory This fi
64. If the automatic inputs scanning is enabled the adc_isr service routine will store the conversion results in the adc_data global array The user program must read the conversion results from this array 1998 2003 HP InfoTech S R L Page 177 CodeVisionAVR For some chips like the Atmega169V L there is also the possibility to disable the digital input buffers on the inputs used by the ADC thus reducing the power consumption of the chip CodeWizardAVR untitled cwp x File Help Us USARTO Analog Comparator LCD Controller BitBanged Project Information Chip Ports External IRQ Timers ADC spi jic 1Wire LcD V ADC Enabled Use S bits M ADC Interrupt I High Speed M ADC Noise Canceler Volt Ref AREF pin ADC Clock fi 25 000 kHz Auto Trigger Source None ba Automatically Scan Inputs Enabled Disable Digital Input Buffers VW Ww vw vw i vw i G 1 2 3 5 6 F This is accomplished by checking the corresponding Disable Digital Input Buffers check boxes If the Automatically Scan Inputs option is enabled then the corresponding digital input buffers are automatically disabled for the ADC inputs in the scan range 1998 2003 HP InfoTech S R L CodeVisionAVR 5 9 Setting the SPI Interface By selecting the SPI tab of the CodeWizardAVR you can specify the SPI interface configuration amp CodeWizardAVR untitled cwp x File Help
65. Nu ecceeeeeceeeeeeeneeeeeeenneeeeeeeaeeeeeeaeeeeeeaeeeeeeeaeeeeeenaeeeeneaas 44 ZA IDE SOUINGS i iiecc setiectetccnecte oeocietes beetectbeceethe oebeieen tht Maa abt lesaa dh etecta bbicccee abt lene tected odie eis ee 46 24 T GOMEMALSSMINGS is ec suds ge ne ved Stee indice da ed adeedandictade sa 0h yez asa geedanuiiebe sald yez shag devieeeteaatte ss 46 242 Contiguring the Editor s 4 sanitised 47 2 4 3 Configuring the Assembler eee eeeeeeeeeeneeeeeeeaeeeeeeeaaeeeeeeaaeeeeeeaaeeeeeecaeeeeesenaeeeseenaeeeeeas 48 2 4 4 Setting the Debugger Path 0 000 ec eeceeeeenneeeeeeeteeeeeeneeeeeeaeeeeeetaeeeeeeiaeeeeesaeeesseneeeeneaes 49 Z 4 5 AVR ChipsProgrammMen SQtup ereina use ans leeeesditecteasacnched becuse ateetesieadbuaaiei id teeteabhieed 50 2 4 6 Serial Communication Terminal Setup ccccceeeeeeeeeceeceeeeeeeseeeneaeeeeeeeseeeseicaeeeeeeeeeeeees 52 2 9 ACCESSING the El Ps vores eat tet etcetera eee eases ees ei end Md et 53 2 6 Transferring the License to another computer eceeeceeeeeeee eee eete eee eeteeeeeteeeeetneeeeetneeeeenae 53 2 7 Connecting to HP InfoTech s Web Site occ eeeeree eter terete ee ene seer teaser teeeeetaeeeessieeeeene 56 2 3 Contacting HP InfoTech by E Mall ic cicscce cco geceed cceicte a ERa 56 2 9 Quitting the CodeVisionAVR IDE erena Taia ea AATE EARE eA EATE TES 56 3 CodeVisionAVR C Compiler Reference 2 ccccccceseeseeeeceeeeeeeeeeneeeeeeeeseneeeaneeseeeeeeseneeesneeeeee
66. RAM initialize the Data Stack Pointer register Y 10 initialize the Stack Pointer register SP 11 initialize the UBRR register if necessary OCONDARWN gt The automatic generation of code sequences 2 to 8 can be disabled by checking the Code Generation Use an External Startup Initialization File check box in the Project Configure C Compiler Code Generation dialog window The C compiler will then include in the generated asm file the code sequences from an external file that must be named STARTUP ASM This file must be located in the directory where your main C source file resides You can write your own STARTUP ASM file to customize or add some features to your program The code sequences from this file will be immediately executed after the chip reset A basic STARTUP ASM file is supplied with the compiler distribution and is located in the BIN directory Here s the content of this file CodeVisionAVR C Compiler C 1998 2003 Pavel Haiduc HP InfoTech S R L EXAMPLE STARTUP FILE EQU CLEAR START 0X60 START ADDRESS OF SRAM AREA TO CLEAR SET THIS ADDRESS TO 0X100 FOR THE ATmegal28 OR ATmega64 CHIPS EQU CLEAR SIZE 256 SIZE OF SRAM AREA TO CLEAR IN BYTES CLI DISABLE INTERRUPTS CIR R30 OUT EECR R30 DISABLE EEPROM ACCESS OUT MCUCR R30 MCUCR 0 NO EXTERNAL SRAM ACCESS DISABLE THE WATCHDOG DI R31 0x18
67. This function may be used for modifying the LCD configuration Example enables the displaying of the cursor _lcd_ready _ilcd_write data 0xe 1998 2003 HP InfoTech S R L Page 116 CodeVisionAVR void Icd_write_byte unsigned char addr unsigned char data writes a byte to the LCD character generator or display RAM Example LCD user defined characters Chip AT90S8515 Memory Model SMALL Data Stack Size 128 bytes Use an 2x16 alphanumeric LCD connected to the STK200 PORTC header as follows LCD STK200 PORTC HEADER 1 GND 9 GND 2 5V 10 VCC 3 VLC LCD HEADER Vo 4 RS 1 PCO 5 RD 2 Pel 6 EN 3 PC2 11 D4 5 PC4 12 DS 6 PCS 13 D6 7 PC6 14 D7 8 PCT the LCD is connected to PORTC outputs asm equ _ lcd port 0x15 PORTC endasm include the LCD driver routines include lt lcd h gt typedef unsigned char byte table for the user defined character arrow that points to the top right corner flash byte char0 8 0b0000000 0b0001111 0b0000011 0b0000101 0b0001001 0b0010000 0b0100000 0b1000000 function used to define user characters void define char byte flash pc byte char code byte i a a char_code lt lt 3 0x40 for i 0 1 lt 8 i lcd write byte at pctt 1998 2003 HP InfoTech S R L Page 117 CodeVisionAVR void main void
68. able or disable compiler warnings Example Warnings are disabled pragma warn Write some code here Warnings are enabled pragma warn 1998 2003 HP InfoTech S R L Page 59 CodeVisionAVR The compiler s code optimizer can be turned on or off using the pragma opt directive This directive must be placed at the start of the source file The default is optimization turned on Example Turn optimization off for testing purposes pragma opt or Turn optimization on pragma opt If the code optimization is enabled you can optimize some portions or all the program for size or speed using the pragma optsize directive The default state is determined by the Project Configure C Compiler Code Generation Optimization menu setting Example The program will be optimized for minimum size pragma optsizet Place your program functions here Now the program will be optimized for maximum execution speed pragma optsize Place your program functions here The automatic saving and restoring of registers RO R1 R15 R22 R23 R24 R25 R26 R27 R30 R31 and SREG during interrupts can be turned on or off using the pragma savereg directive Example Turn registers saving off pragma savereg interrupt handler interrupt 1 void my irq void now save only the registers that are affected by the routines in the handler for example R30 R3
69. age 175 CodeVisionAVR 5 8 Setting the Analog Digital Converter Some AVR chips contain an analog digital converter ADC By selecting the ADC tab of the CodeWizardAVR you can specify the ADC configuration CodeWizardAVR untitled cwp x Eile Help LCD Controller BitBanged ProjectInformation Chip Ports External IRQ Timers USI USARTO Analog Comparator Besa zc 1wire ico M ADCEnabled Use 8 bits M ADC Interrupt I High Speed ADC Noise Canceler Volt Ref AREF pin ADC Clock 125 000 kHz Auto Trigger Source External IRQO Automatically Scan Inputs M Enabled First p P Last h wy Checking the ADC Enabled check box enables the on chip ADC On some AVR devices only the 8 most significant bits of the AD conversion result can be used This feature is enabled by checking the Use 8 bits check box Some AVR devices allow the ADC to use a high speed conversion mode but with lower precision This feature is enabled by checking the High Speed check box If the ADC has an internal reference voltage source than it can be selected using the Volt Ref list box or activated by checking the ADC Bandgap check box 1998 2003 HP InfoTech S R L Page 176 CodeVisionAVR CodeWizardAVR untitled cwp x File Help 12C 1Wire LCD Bit Banged Project Information Chip Ports External IRQ Timers UART Analog Comparator ADC SPI
70. age 89 CodeVisionAVR 3 18 Including Assembly Language in Your Program You can include assembly language anywhere in your program using the asm and endasm directives Example void delay unsigned char i while i Assembly language code sequence asm nop nop endasm he Inline assembly may also be used Example asm Sei enable interrupts The registers RO R1 R22 R23 R24 R25 R26 R27 R30 and R31 can be freely used in assembly routines However when using them in an interrupt service routine the programmer must save respectively restore them on entry respectively on exit of this routine 1998 2003 HP InfoTech S R L Page 90 CodeVisionAVR 3 18 1 Calling Assembly Functions from C The following example shows how to access functions written in assembly language from a C program function in assembler declaration this function will return atbtc pragma warn this will prevent warnings int sum_abc int a int b unsigned char c asm ldd r30 y 3 R30 LSB a ldd r31 y 4 R31 MSB a ldd r26 y 1 R26 LSB b ldd r27 y 2 R27 MSB b add r30 r26 R31 R30 a b adc r31 r27 ld r26 y R26 c clr TZI promote unsigned char c to int add r30 r26 R31 R30 R31 R30 c adc 31 027 endasm pragma warn enable warnings void main void EAG 67 now we call the function and store the result in r r sum abc 2 4 6 The compiler passes function
71. all the elements of the ANSI C language as allowed by the AVR architecture with some features added to take advantage of specificity of the AVR architecture and the embedded system needs The compiled COFF object files can be C source level debugged with variable watching using the Atmel AVR Studio debugger The Integrated Development Environment IDE has built in AVR Chip In System Programmer software that enables the automatical transfer of the program to the microcontroller chip after successful compilation assembly The In System Programmer software is designed to work in conjunction with the Atmel STK500 Kanda Systems STK200 300 Dontronics DT006 Vogel Elektronik VTEC ISP Futurlec JRAVR and MicroTronics ATCPU Mega2000 development boards For debugging embedded systems which employ serial communication the IDE has a built in Terminal Besides the standard C libraries the CodeVisionAVR C compiler has dedicated libraries for e Alphanumeric LCD modules Philips I C bus National Semiconductor LM75 Temperature Sensor Philips PCF8563 PCF8583 Dallas Semiconductor DS1302 and DS1307 Real Time Clocks Dallas Semiconductor 1 Wire protocol Dallas Semiconductor DS1820 DS18S20 Temperature Sensors Dallas Semiconductor DS1621 Thermometer Thermostat Dallas Semiconductor DS2430 and DS2433 EEPROMs SPI Power management Delays Gray code conversion CodeVisionAVR also contains the CodeWizardAVR Automatic Program Generator that allows you
72. at __DATE__ the current date in mmm dd yyyy format _CHIP_ATXXXXX_ where ATXXXXxX is the chip type in uppercase letters specified in the Project Configure C Compiler Code Generation Chip option _MCU_CLOCK_FREQUENCY_ the AVR clock frequency specified in the Project Configure C Compiler Code Generation Clock option expressed as an integer in Hz _MODEL_TINY_ if the program is compiled using the TINY memory model _MODEL_SMALL_ if the program is compiled using the SMALL memory model _OPTIMIZE_SIZE_ if the program is compiled with optimization for size _OPTIMIZE_SPEED_ if the program is compiled with optimization for speed _UNSIGNED_CHAR_ if the Project Configure C Compiler Code Generation char is unsigned compiler option is enabled or pragma uchart is used _8BIT_ENUMS__ if the Project Configure C Compiler Code Generation 8 bit enums compiler option is enabled or pragma 8bit_enums is used The line directive can be used to modify the predefined _ LINE and _ FILE ___ macros The syntax is line integer constant file name Example This will set _ LINE to 50 and _ FILE to file2 c line 50 file2 c This will set _ LINE _ to 100 line 100 There error directive can be used to stop compilation and display an error message The syntax is error error message Example error This is an error The pragma directive allows compiler specific directives You can use the pragma warn directive to en
73. atchpad boundary char buffer 100 define START ADDR 2 main unsigned char i devices init UART UCR 8 UBRR 25 Baud 9600 4MHz detect how many 1 Wire devices are present on the bus devices wl search 0xF0 amp rom_code 0 0 printf S u 1 Wire devices found n r devices 1998 2003 HP InfoTech S R L Page 150 CodeVisionAVR for i1 0 i lt devices itt make sure to select only the DS2433 types 0x23 is the DS2433 family code EE rom code i 0 DS2433 FAMILY CODE printf n r write text in each DS2433 at START ADDR if ds2433 write block amp rom_code i 0 text START ADDR sizeof text printf Data written OK in DS2433 u n r itl display the text written in each DS2433 if ds2433 read_block amp rom_code i 0 buffer START ADDR sizeof text printf Data read OK n rDS2433 u text s n r i 1l buffer else printf Error reading data from DS2433 u n r itl else printf Error writing data to DS2433 u n r itl 3 stop while 1 Refer to the DS2433 data sheet for more information 1998 2003 HP InfoTech S R L Page 151 CodeVisionAVR 4 15 SPI Functions The SPI Functions are intended for easy interfacing between C programs and various peripherals using the SPI bus The prototypes for these functions are placed in the file spi h located in the INC subdirectory This file must be
74. ated in the register R2 to R14 memory space These variables are declared using the bit keyword The syntax is bit lt identifier gt Example declaration and initialization bit alfa 1 bitO of R2 bit beta bitl of R2 void main void if alfa beta beta Memory allocation for the bit variables is done in the order of declaration starting with bit 0 of R2 then bit 1 of R2 and so on in ascending order A number of maximum 104 bit variables can be declared The size of the bit variables allocated to the program can be specified in the Project Configure C Compiler Code Generation Bit Variables Size list box This size should be as low as possible in order to free registers for allocation to other global variables If not specifically initialized the bit global variables are automatically set to 0 at program startup In expression evaluation bit variables are automatically promoted to unsigned char 1998 2003 HP InfoTech S R L Page 68 CodeVisionAVR 3 7 3 Allocation of Variables to Registers In order to fully take advantage of the AVR architecture and instruction set the compiler allocates some of the program variables to chip registers The registers from R2 up to R14 can be allocated for bit variables You may specify how many registers in this range are allocated using the Project Configure C Compiler Code Generation Bit Variables Size list box This value must be as low as required by the p
75. ay ms 100 1998 2003 HP InfoTech S R L Page 154 CodeVisionAVR 4 16 Power Management Functions The Power Management Functions are intended for putting the AVR chip in one of its low power consumption modes The prototypes for these functions are placed in the file sleep h located in the INC subdirectory This file must be include ed before using the functions The Power Management Functions are void sleep_enable void this function enables entering the low power consumption modes void sleep_disable void this function disables entering the low power consumption modes It is used to disable accidental entering the low power consumption modes void idle void this function puts the AVR chip in the idle mode Prior to using this function the sleep_enable function must be invoked to allow entering the low power consumption modes In this mode the CPU is stopped but the Timers Counters Watchdog and interrupt system continue operating The CPU can wake up from external triggered interrupts as well as internal ones void powerdown void this function puts the AVR chip in the powerdown mode Prior to using this function the sleep_enable function must be invoked to allow entering the low power consumption modes In this mode the external oscillator is stopped The AVR can wake up only from an external reset Watchdog time out or external level triggered interrupt void powersave void this function puts
76. b unsigned int word data void main void unsigned char k define a pointer to the union union alpha dp direct access to union members data word 0x1234 k data lsb get the LSB of 0x1234 same access to union members using a pointer dp data initialize the pointer with the union address dp gt word 0x1234 k dp gt lsb get the LSB of 0x1234 Because some AVR devices have a small amount of SRAM in order to keep the size of the Data Stack small it is recommended not to pass unions as function parameters and use pointers for this purpose Example include lt stdio h gt printf union alpha unsigned char lsb unsigned int word data define the function unsigned char low union alpha up return the LSB of word return up gt l1sb void main void data word 0x1234 printf the LSB of Sx is 2x data word low amp data 1998 2003 HP InfoTech S R L Page 73 CodeVisionAVR Union elements can be also declared as bit fields having a width from 1 to 32 Bit fields are allocated in the order of declaration starting from the least significant bit Example this union will occupy 1 byte in SRAM as the bit field data type is unsigned char union alphal unsigned char a 1l bit 0 unsigned char b 4 bits 0 3 unsigned char c 3 bits 0 2 this union will occupy 2 bytes in SRAM as the bit field data
77. bit 0 unsigned char b 4 bits 1 4 unsigned char c 3 bits 5 7 this structure will occupy 2 bytes in SRAM as the bit field data type is unsigned int struct alpha2 unsigned int a 2 bits 0 1 unsigned int b 8 bits 2 9 unsigned int c 4 bits 10 13 bits 14 15 are not used he this structure will occupy 4 bytes in SRAM as the bit field data type is unsigned long struct alpha3 unsigned long a 10 bits 0 9 unsigned long b 8 bits 10 17 unsigned long c 6 bits 18 23 bits 24 31 are not used e 1998 2003 HP InfoTech S R L Page 72 CodeVisionAVR 3 7 5 Unions Unions are user defined collections of named members that share the same memory space The union members can be any of the supported data types arrays of these data types or pointers to them Unions are defined using the union reserved keyword The syntax is lt storage modifier gt union lt union tag name gt lt type gt lt variable name gt lt variable name gt lt type gt lt bitfield id gt lt width gt lt bitfield id gt lt width gt lt union variables gt Unions are always stored in SRAM The space allocated to the union in memory is equal to the size of the largest member Union members can be accessed in the same way as structure members Example union declaration union alpha unsigned char ls
78. can specify the USI configuration The USI operatinging mode can be selected using the Mode list box One of the USI operating modes is the Three Wire SPI mode CodeWizardAVR untitled cwp x File Help LCD Controller Bit Banged Project Information Chip Ports ExtemaliRQ Timers ADC spPi izc 1wie LcD USARTO Analog Comparator Mode Three Wire SPI Clock Reg ext pos Cnt ext both edges T USI Counter Overflow Interrupt 1998 2003 HP InfoTech S R L Page 180 CodeVisionAVR The USI can also operate in the Two Wire I2C mode CodeWizardAVR untitled cwp x File Help LCD Controller BitBanged Project Information ADC spl i2c 1Wire LCD gocescescoeecesesoesesesecsesese Chip Ports External IRQ Timers USI USARTO Analog Comparator Reccessssssnsenserssessssssssseed Mode Two Wire l2C y Clock Reg ext neg Cnt ext both edges M USI Counter Overflow Interrupt M USI Start Condition Interrupt The Shift Reg Clock list box sets the clock source for the USI Shift Register and Counter As both the USI Shift Register and Counter are clocked from the same clock source the USI Counter may be used to count the number of received or transmitted bits and generate an overflow interrupt when the data transfer is complete Checking the USI Counter Overflow Interrupt check box will generate code for an interrupt se
79. ce is selected using it s ROM code stored in an array of 8 bytes located at address romcode unsigned char ds2430_write unsigned char romcode unsigned char addr unsigned char data this function writes the byte data at DS2430 EEPROM memory address addr It returns 1 if successful O if not The DS2430 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode 1998 2003 HP InfoTech S R L Page 146 CodeVisionAVR unsigned char ds2430_read_appreg_block unsigned char romcode unsigned char dest unsigned char addr unsigned char size this function reads a block of size bytes starting from the DS2430 application register address addr and stores it in the string dest located in SRAM It returns 1 if successful 0 if not The DS2430 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode unsigned char ds2430_write_appreg_block unsigned char romcode unsigned char source unsigned char addr unsigned char size this function reads a block of size bytes starting from the DS2430 application register address addr and stores it in the string dest located in SRAM It returns 1 if successful 0 if not The DS2430 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode If only one DS2430 EEPROM is used no ROM code array is necessary and the pointer romcode must be NULL 0 If several 1 Wire device are used then
80. cecsccesocsecesccsesececcooi Chip ATmega103 Clock fa 0000000 ZA MHz M Crystal Oscillator Divider Enabled Crystal Oscillator Divider 2 JA l Check Reset Source The chip type can be specified using the Chip list box The chip clock frequency in MHz can be specified using the Clock spinedit box For the AVR chips that contain a crystal oscillator divider a supplementary Crystal Oscillator Divider Enabled check box is visible This check box allows you to enable or disable the crystal oscillator divider If the crystal oscillator is enabled you can specify the division ratio using the Crystal Oscillator Divider spinedit box For the AVR chips that allow the identification of the reset source a supplementary Check Reset Source check box is visible If it s checked then the CodeWizardAVR will generate code that allows identification of the conditions that caused the chip reset 1998 2003 HP InfoTech S R L Page 160 CodeVisionAVR For the AVR chips that allow self programming a supplementary Program Type list box is visible It allows to select the type of the generated code e Application e Boot Loader CodeWizardAVR untitled cwp ATmeqal 28 Application 1998 2003 HP InfoTech S R L Page 161 CodeVisionAVR 5 2 Setting the External SRAM For the AVR chips that allow connection of external SRAM you can specify the size of this memory and wait state insertion by selecting the External
81. char sec this function sets the current time of the RTC The hour min and sec parameters represent the values of hour minutes and seconds void rtc_get_date unsigned char date unsigned char month unsigned year this function returns the current date measured by the RTC The date month and year pointers must point to the variables that must receive the values of day month and year void rtc_set_date unsigned char date unsigned char month unsigned year this function sets the current date of the RTC 1998 2003 HP InfoTech S R L Page 131 CodeVisionAVR void rtc_alarm_off void this function disables the RTC alarm function void rtc_alarm_on void this function enables the RTC alarm function void rtc_get_alarm unsigned char date unsigned char hour unsigned char min this function returns the alarm time and date of the RTC The date hour and min pointers must point to the variables that must receive the values of date hour and minutes void rtc_set_alarm unsigned char date unsigned char hour unsigned char min this function sets the alarm time and date of the RTC The date hour and min parameters represent the values of date hours and minutes If date is set to 0 then this parameter will be ignored After calling this function the alarm will be turned off It must be enabled using the rtc_alarm_on function void rtc_set_timer unsigned char val this function sets the countdown value of th
82. characters then it s field will be padded with spaces If the flag is used the result field will be padded on the right otherwise it will be padded on the left On at least n characters are outputted If the result has less than n characters it is padded on the left with zeros The optional precision specifier sets the maximal number of characters or minimal number of integer digits that may be outputted For the e E and f conversion type characters the precision specifier sets the number of digits that will be outputted to the right of the decimal point The precision specifier always begins with a character in order to separate it from the width specifier The following precision specifiers are supported none the precision is set to 1 for the i d u x X conversion type characters For the s and p conversion type characters the char string will be outputted up to the first null character 0 the precision is set to 1 for the i d u x X type characters n n characters or n decimal places are outputted For the i d u x X conversion type characters if the value has less than n digits then it will be padded on the left with zeros If it has more than n digits then it will not be truncated For the s and p conversion type characters no more than n characters from the char string will be outputted For the e E and f conversion type characters n digits will be
83. clude ed before using the functions Before calling the functions the interrupts must be disabled otherwise the delays will be much longer then expected Also it is very important to specify the correct AVR chip clock frequency in the Project Configure C Compiler Code Generation menu The functions are void delay_us unsigned int n generates a delay of n pseconds n must be a constant expression void delay_ms unsigned int n generates a delay of n milliseconds This function automatically resets the wtachdog timer every 1ms by generating the wdr instruction Example void main void disable interrupts fasm cli 100us delay delay us 100 10ms delay delay ms 10 enable interrupts asm sei 1998 2003 HP InfoTech S R L Page 156 CodeVisionAVR 5 CodeWizardAVR Automatic Program Generator The CodeWizardAVR Automatic Program Generator allows you to easily write all the code needed for implementing the following functions e External memory access setup e Chip reset source identification e Input Output Port initialization e External Interrupts initialization e Timers Counters initialization e Watchdog Timer initialization e UART initialization and interrupt driven buffered serial communication e Analog Comparator initialization e ADC initialization e SPI Interface initialization e C Bus LM75 Temperature Sensor DS1621 Thermometer Thermostat PCF 8563 PCF8583
84. ctions include lt i2c h gt The I C Functions are void i2c_init void this function initializes the IC bus This is the first function that must be called prior to using the other C Functions unsigned char i2c_start void issues a START condition Returns 1 if bus is free or 0 if the IC bus is busy void i2c_stop void issues a STOP condition unsigned char i2c_read unsigned char ack reads a byte from the bus The ack parameter specifies if an acknowledgement is to be issued after the byte was read Set ack to 0 for no acknowledgement or 1 for acknowledgement 1998 2003 HP InfoTech S R L Page 123 CodeVisionAVR unsigned char i2c_write unsigned char data writes the byte data to the bus Returns 1 if the slave acknowledges or 0 if not Example how to access an Atmel 24C02 256 byte I C EEPROM the I C bus is connected to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ 1i2c_ port 0x18 equ _ sda bit 3 equ _ scl bit 4 endasm now you can include the I C Functions include lt i2c h gt function declaration for delay ms include lt delay h gt define EEPROM BUS ADDRESS 0xa0 read a byte from the EEPROM unsigned char eeprom read unsigned char address unsigned char data i2c_ start i2c write EEPROM BUS ADDRESS i2c_write address i2c_ start i2c_ write EEPROM BUS ADDRESS 1 data i2c read 0
85. ctively Ctrl R keys or by pressing the Find respectively Replace buttons on the toolbar Changes in the edited text can be undone respectively redone by using the Edit Undo respectively Edit Redo menu commands by pressing the CtrI Z respectively Shift Ctrl Z keys or by pressing the Undo respectively Redo buttons on the toolbar You can go to a specific line number in the edited file by using the Edit Goto Line menu command or by pressing the Alt G keys Bookmarks can be inserted or removed at the line where the cursor is positioned by using the Edit Toggle Bookmark menu command or by pressing the Shift Ctrl 0 9 keys The Edit Jump to Bookmark menu command or the Ctrl 0 9 keys will position the cursor at the start of the corresponding bookmarked text line If the cursor is positioned on an opening respectively closing brace then the Edit Match Braces menu command or the Ctri M key will highlight the portion of text until the corresponding matching closing respectively opening brace Pressing any key or clicking the mouse will hide the highlighting Clicking with the mouse right button opens a pop up menu that also gives the user access to the above mentioned functions 1998 2003 HP InfoTech S R L Page 10 CodeVisionAVR 2 1 5 Saving a File The currently edited file can be saved by using the File Save menu command by pressing the Ctrl S keys or by pressing the Save button on the toolbar When saving the Edit
86. d Mode Lowlevel M Any change on O pins PCINTO 7 M Any change on l 0 pins PCINT8 15 Pin Change Interrupts Enable vee E E me me D woo og oa g Bo Boo p Pin Change Interrupts Enable vE S ee E D D E 18 11 12 13 14 15 The Pin Change Interrupt Enable check boxes if checked will specify which of the PCINT I O pins will trigger an external interrupt The interrupt service routines for these interrupts will be pin_change_isr0 for PCINTO 7 and pin_change_isr1 for PCINT8 15 1998 2003 HP InfoTech S R L CodeVisionAVR 5 5 Setting the Timers Counters By selecting the Timers tab of the CodeWizardAVR you can specify the timers counters configuration A number of Timer tabs will be displayed according to the AVR chip type amp CodeWizardAVR untitled cwp x File Help Analog Comparator ADC SPI 12C 1Wire 2Wire 2c Bit Banged Project Information Chip ExternalSRAM Pors ExternalIRQ Timers USARTO USARTI Timer Timer 1 Timer 2 Timer3 v4 gt Reosccnevevencsscveseouses Clock Source System Clock Clock Value Timer 0 Stopped Mode Normaltop FFh xl Output Disconnected M OverlowIRQ T Compare Match IRQ TimerValue j0 h Compare 0 h By selecting the Timer 0 tab you can have the following options Clock Source specifies the timer counter 0 clock pulse source Clock Value specifies the timer counter 0 clock f
87. d be used In order to watch program variables the user must select Watch Add Watch menu command or press the Add Watch toolbar button and specify the name of the variable in the Watch column The AVR chip registers can be viewed using the View Registers menu command or by pressing the Alt 0 keys The AVR chip PC SP X Y Z registers and status flags can be viewed using the View Processor menu command or by pressing the Alt 3 keys The contents of the FLASH SRAM and EEPROM memories can be viewed using the View New Memory View menu command or by pressing the Alt 4 keys The I O registers can be viewed using the View New IO View menu command or by pressing the Alt 5 keys In order to use the Terminal I O window invoked with the View Terminal I O menu command for communication with the simulated AVR chip s UART the COFF file format must be selected and the Use the Terminal I O in AVR Studio check box must be checked in the Project Configure C Compiler Code Generation dialog To obtain more information about using AVR Studio please consult it s Help system 1998 2003 HP InfoTech S R L Page 95 CodeVisionAVR 3 21 Hints In order to decrease code size and improve the execution speed you must apply the following rules e f possible use unsigned variables e Use the smallest data type possible i e bit and unsigned char e The size of the bit variables allocated to the program in the Project Configure C Compiler Code
88. ddress can be 0 or 1 The dated_alarm parameter specifies if the RTC alarm takes in account both the time and date dated_alarm 1 or only the time dated_alarm 0 Refer to the PCF8583 data sheet for more information After calling this function the RTC alarm is disabled unsigned char rtc_read unsigned char chip unsigned char address this function reads the byte stored in the PCF8583 SRAM void rtc_write unsigned char chip unsigned char address unsigned char data this function stores the byte data in the PCF8583 SRAM When writing to the SRAM the user must take in account that locations at addresses 10h and 11h are used for storing the current year value unsigned char rtc_get_status unsigned char chip this function returns the value of the PCF8583 control status register By calling this function the global variables __rtc_status and __rtc_alarm are automatically updated The __rtc_status variable holds the value of the PCF8583 control status register The __rtc_alarm variable takes the value 1 if an RTC alarm occurred 1998 2003 HP InfoTech S R L Page 133 CodeVisionAVR void rtc_get_time unsigned char chip unsigned char hour unsigned char min unsigned char sec unsigned char hsec this function returns the current time measured by the RTC The hour min sec and hsec pointers must point to the variables that must receive the values of hour minutes seconds and hundreds of a second Example asm equ 1i2c
89. del returns the length of the string str in the range 0 255 unsigned int strlen char str for the SMALL memory model returns the length of the string str in the range 0 65535 unsigned int strlenf char flash str returns the length of the string str located in FLASH 1998 2003 HP InfoTech S R L Page 109 CodeVisionAVR void memcpy void dest void src unsigned char n for the TINY memory model void memcpy void dest void src unsigned int n for the SMALL memory model Copies n bytes from src to dest dest must not overlap src else use memmove Returns a pointer to dest void memcpyf void dest void flash src unsigned char n for the TINY memory model void memcpyf void dest void flash src unsigned int n for the SMALL memory model Copies n bytes from src located in FLASH to dest Returns a pointer to dest void memccpy void dest void src char c unsigned char n for the TINY memory model void memccpy void dest void src char c unsigned int n for the SMALL memory model Copies at most n bytes from src to dest until the character c is copied dest must not overlap src Returns a NULL pointer if the last copied character was c or a pointer to dest n 1 void memmove void dest void src unsigned char n for the TINY memory model void memmove void dest void src unsigned int n for the SMALL memory model Copies n bytes from src to dest dest may overlap src Returns a poi
90. ding ds1820 vec Including ds1820 inc Program memory usage Code 1286 words Constants dw db 63 words 0 words 1349 words Assembly complete with no errors 1998 2003 HP InfoTech S R L Page 35 CodeVisionAVR Pressing the Programmer tab will display the Chip Programming Counter which shows how many times was the AVR chip programmed so far i Information x Compiler Assembler Programmer Chip Programming Counter 0 Set Counter Pressing the Set Counter button will open the Set Programming Counter window 11 Set Programming Counter EG New Counter Value fo 4 X Cancel This dialog window allows setting the new Chip Programming Counter value Pressing the Program button allows automatic programming of the AVR chip after successful compilation Pressing Cancel will disable automatic programming 1998 2003 HP InfoTech S R L Page 36 CodeVisionAVR 2 2 6 Closing a Project You can quit working with the current Project by using the File Close Project menu command If the Project files were modified and weren t saved yet you will be prompted if you want to do that 2 Save changes to C CYAYR Examples MULTFILE mainfile c Pressing Yes will save changes and close the project Pressing No will close the project without saving the changes Pressing Cancel will disable the project closing process When saving the IDE will create a backup file with a pr extension
91. e Global Variables area is used to statically store the global variables during program execution The size of this area can be computed by summing the size of all the declared global variables The Hardware Stack area is used for storing the functions return addresses The SP register is used as a stack pointer and is initialized at start up with value of last SRAM address During the program execution the Hardware Stack grows downwards to the Global Variables area When configuring the compiler you have the option to place the strings DSTACKEND respectively HSTACKEND at the end of the Data Stack respectively Hardware Stack areas When you debug the program with AVR Studio you may see if these strings are overwritten and consequently modify the Data Stack Size using the Project Configure C Compiler Code Generation menu command When your program runs correctly you may disable the placement of the strings in order to reduce code size 1998 2003 HP InfoTech S R L Page 87 CodeVisionAVR 3 17 Using an External Startup File In every program the CodeVisionAVR C compiler automatically generates a code sequence to make the following initializations immediately after the AVR chip reset interrupt vector jump table global interrupt disable EEPROM access disable Watchdog Timer disable external SRAM access and wait state enable if necessary clear registers R2 R14 clear the SRAM initialize the global variables located in S
92. e PCF8563 Timer 1998 2003 HP InfoTech S R L Page 132 CodeVisionAVR 4 12 4 Philips PCF8583 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the PCF8583 C bus real time clock RTC The prototypes for these functions are placed in the file pcef8583 h located in the INC subdirectory This file must be include ed before using the functions The I C bus functions prototypes are automatically include ed with the pcf8583 h Prior to include ing the pcf8583 h file you must declare which microcontroller port and port bits are used for communication with the PCF8583 through the I7C bus Example the I C bus is connected to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ __ i2c port 0x18 equ _ sda _ bit 3 equ scl bit 4 endasm now you can include the PCF8583 Functions include lt pcf8583 h gt The PCF8583 Functions are void rtc_init unsigned char chip unsigned char dated_alarm this function initializes the PCF8583 chip Before calling this function the C bus must be initialized by calling the i2c_init function This is the first function that must be called prior to using the other PCF8583 Functions If more then one chip is connected to the C bus then the function must be called for each one specifying accordingly the function parameter chip Maximum 2 PCF8583 chips can be connected to the I C bus their chip a
93. e the DS1820 DS18S20 functions prototypes include lt ds1820 h gt The DS1820 DS18S20 functions are int ds1820_temperature_10 unsigned char addr this function returns the temperature of the DS1820 DS18S20 sensor with the ROM code stored in an array of 8 bytes located at address addr The temperature is in C and is multiplied by 10 In case of error the function returns the value 9999 If only one DS1820 DS18S20 sensor is used no ROM code array is necessary and the pointer addr must be NULL 0 If several sensors are used then the program must first identify the ROM codes for all the sensors Only after that the ds1820_temperature_10 function may be used with the addr pointer pointing to the array which holds the ROM code for the needed device Example include lt 90s8515 h gt specify the port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ _ wl bit 2 endasm include the DS1820 DS18S20 functions prototypes include lt ds1820 h gt include the printf function prototype include lt stdio h gt include the abs function prototype include lt math h gt 1998 2003 HP InfoTech S R L Page 142 CodeVisionAVR maximum number of DS1820 DS18S20 connected to the bus define MAX DEVICES 8 DS1820 DS18S20 devices ROM code storage area 9 bytes are used for each device see the wl search function description but only the fi
94. e variables gt Example Global structure located in SRAM struct ram structure char a b ine G7 char d 30 e 10 char pp sr Global constant structure located in FLASH flash struct flash _ structure int a char b 30 c 10 host Global structure located in EEPROM eeprom struct eeprom structure char a int b char c 15 se void main void Local structure struct local structure char a ant p long c sl The space allocated to the structure in memory is equal to sum of the sizes of all the members There are some restrictions that apply to the structures stored in FLASH and EEPROM Due to the fact that pointers must be always located in SRAM they can t be used in these structures Because with the Atmel AVRASM32 Assembler single bytes defined with DB in FLASH occupy in reality 2 bytes the CodeVisionAVR C compiler will replace the char members of structures stored in FLASH with int Also it will extend the size of the char arrays members of such structures to an even value 1998 2003 HP InfoTech S R L Page 70 CodeVisionAVR Structures can be grouped in unidimensional arrays Example how to initialize and access an global structure array stored in EEPROM Global structure array located in EEPROM eeprom struct eeprom structure char a int b char c 15 se 2 a 25 Hello b 50 world void mai
95. ech S R L Page 168 CodeVisionAVR amp CodeWizardAVR untitled cwp x Eile Help Analog Comparator ADC SPI 12C 1Wire 2Wire 2c Led BitBanged Project Information Chip ExternalSRAM Pors ExtemaliRQ Timers USARTO USARTI Timer 0 Timer1 Timer vale Clock Source SystemClock Clock Value Timer2 Stopped Mode Normaltop FFh xl Output Disconnected gt F OverlowlIRQ P Compare Match IRQ Timer alue J0 h Compare j0 h By selecting the Timer 2 tab you can have the following options Clock Source specifies the timer counter 2 clock pulse source Clock Value specifies the timer counter 2 clock frequency Mode specifies if the timer counter 2 functioning mode Output specifies the function of the timer counter 2 output and depends of the functioning mode Overflow IRQ specifies if an interrupt is to be generated on timer counter 2 overflow Compare Match IRQ specifies if an interrupt is to be generated on timer counter 2 compare match e Timer Value specifies the initial value of timer counter 2 at startup e Compare specifies the initial value of timer counter 2 output compare register If timer counter 2 interrupts are used the following interrupt service routines may be defined by the CodeWizardAVR e timer2_ovf_isr for timer counter overflow e timer2_comp_isr for timer counter output compare match You must note that depending of the used AVR chip some of these optio
96. ed to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ _ i2c port 0x18 equ _ sda bit 3 equ scl bit 4 endasm now you can include the DS1307 Functions include lt ds1307 h gt The DS1307 Functions are void rtc_init unsigned char rs unsigned char sqwe unsigned char out this function initializes the DS1307 chip Before calling this function the IC bus must be initialized by calling the i2c_init function This is the first function that must be called prior to using the other DS1307 Functions The rs parameter specifies the value of the square wave output frequency on the SQW OUT pin e 0 for 1Hz e 1 for 4096Hz e 2 for 8192Hz e 3 for 32768Hz If the sqwe parameter is set to 1 then the square wave output on the SQW OUT pin is enabled The out parameter specifies the logic level on the SQW OUT pin when the square wave output is disabled sqwe 0 Refer to the DS1307 data sheet for more information void rtc_get_time unsigned char hour unsigned char min unsigned char sec this function returns the current time measured by the RTC The hour min and sec pointers must point to the variables that must receive the values of hours minutes and seconds Example the I C bus is connected to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ _ i2c port 0x18 equ _ sda _ bit 3 equ _ scl bit 4 endasm 1998 2003 HP InfoTech S R L Page 136 CodeVi
97. es 82 3 13 1 Bit level access to the I O ReGIStErS eee eeeeeeeeeeneeeeeeeaeeeeeeaeeeeeeaeeeeeeeaeeeseenaeeeeeenas 83 3 14 Accessing the EEPROM nnie aA ga edie ie dan dicta abt deaz inl T T TA 84 3 15 Using Nerus onnee ee i a es 85 3 16 SRAM Memory Organization sremski iaeiiai A iaaii i EENE AEA 86 3 17 Using an External Startup File ecceeeeeeeeeeeee ener cece ecneeeeeeaeeeeeeaeeeeeesaeeeseeiaeeeeeeneeeeeaaes 88 3 18 Including Assembly Language in Your Program ccceeeeceeeeeeeneeeeeseneeeeeeceeeeeenaeeeeeeneeeeseaas 90 3 18 1 Calling Assembly Functions from Co eee eeeeeeeeeeeeneeeeeeeaeeeeeeaeeeeeeaeeeeeecaeeeeeeenneeeeeaas 91 3 19 Creating Libraries ie n icici et Set esctieie tides tits ees cca eee eis 92 3 20 Using the AVR Studio Debugger ei eceeeee seer eeeeente eter etieee ee taeeeeetaeeeeeeeaeeeeeeieeeenenaeeeeneaes 95 SPATE IO AE E eT ace aches TET epee ac eeah ease Bev ah eae eed aa E EEA 96 Bi 22 LIMMAIONS ss ccc siticescchvneeeten tt choke E Heeecsedlolackabid Weeks Linecdt havdees batebetdt dead 96 4 Library Functions Reference ccccccssccceesenceeeeeeeneeeeeeeeeeeeeeeneeseseeneeeesseeneeseseeneeeaseeeeeeaseeneeeeseeeeenaes 97 4 1 CGharacter Type FUNCIONS oroc erena ident feds a cassie Mae eine date ae 98 4 2 Standard C Input Output Functions 2000 22 eee cee ee cece cece cece cece aeeeee cnet eeeceeaaeaeeeeeeesesenceeeeeeeeeseeseeaees 99 4 3 Standard Library FUNCtIONS aa ker aenn Erre AEn E EEEa ERRETA
98. foTech S R L Page 12 CodeVisionAVR 2 1 8 Closing a File You can quit editing the current file by using the File Close menu command If the file was modified and wasn t saved yet you will be prompted if you want to do that Q Save changes to C CVAVR EXAMPLES DS1620 ds1620 c Pressing Yes will save changes and close the file Pressing No will close the file without saving the changes Pressing Cancel will disable the file closing process All currently opened files can be closed using the File Close All menu command 1998 2003 HP InfoTech S R L Page 13 CodeVisionAVR 2 1 9 Using the Navigator The Navigator window allows easy displaying or opening of source files By clicking on the file name the appropriate file is maximized or opened Navigator SY CodeVisionAVR Hl Project ds1820 Notes ds1820 c S Included Files F Icc h E ds1820 h E 1wire h B delay h E math h El stdio h F ctype h B stdarg h E string h 5 4 Global Variables X Iccd_buffer X rom_code B F0 Functions FO main Other Files After a Compile or Make process there is also displayed a list of include ed files global variables and functions declared in each compiled C source file By clicking on the variable s respective function s name the variable respective function declaration is highlighted in the appropriate C source file If during compilation there are errors or warnings these are al
99. foTech S R L Page 107 CodeVisionAVR signed char strncmpf char str1 char flash str2 unsigned char n compares at most n characters of the string str1 located in SRAM with the string str2 located in FLASH Returns lt 0 0 gt 0 according to str1 lt str2 str1 str2 str1 gt str2 char strcpy char dest char src copies the string src to the string dest char strcpyf char dest char flash src copies the string src located in FLASH to the string dest located in SRAM Returns a pointer to the string dest char strncpy char dest char src unsigned char n copies at most n characters from the string src to the string dest null padding Returns a pointer to the string dest char strncpyf char dest char flash src unsigned char n copies at most n characters from the string src located in FLASH to the string dest located in SRAM null padding Returns a pointer to the string dest unsigned char strspn char str char set returns the index of the first character from the string str that doesn t match a character from the string set If all characters from set are in str returns the length of str unsigned char strspnf char str char flash set returns the index of the first character from the string str located in SRAM that doesn t match a character from the string set located in FLASH If all characters from set are in str returns the length of str unsigned char strcspn char str char set
100. g ete Ce Resovevscesncercecscnceseasvensevenseasores LCD Port PORTD Chars Line fie PORT Bit 0 RS LCD Pin 4 PORT Bit 1 RD LCD Pin 5 PORT Bit 2 EN LCD Pin 6 PORT Bit 3 Free PORT Bit 4 DB4 LCD Pin 11 PORT Bit 5 DBS LCD Pin 12 PORT Bit 6 DB6 LCD Pin 13 PORT Bit DB LCD Pin 14 Using the LCD Port list box you can specify which port is used for connecting the alphanumeric LCD The Chars Line list box allows you to specify the number of characters per display line This value is used by the Icd_init function The LCD can be accessed using the standard LCD Functions 1998 2003 HP InfoTech S R L Page 193 CodeVisionAVR 5 16 Setting Bit Banged Peripherals By selecting the Bit Banged tab of the CodeWizardAVR you can specify the configuration of the peripherals connected using the bit banging method If you use the DS1302 RTC you must select the DS1302 tab amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USARTI Chip External SRAM Ports Analog Comparator ADC sPi l2c 1Wire 2Wire 2c LCD Project Information DS1302 Pot PORTE vost fo x scikBit x IRSTBitj2 v peg Charge EN EES V Enabled Diodes f Charge Resistor None v Using the Port list box you can specify which port is used for connecting with the DS1302 The I O Bit SCLK Bit and RST Bit list boxes allow you to specify w
101. ge 164 CodeVisionAVR 5 4 Setting the External Interrupts By selecting the External IRQ tab of the CodeWizardAVR you can specify the external interrupt configuration CodeWizardAVR untitled cwp File Help Analog Comparator ADC SPI l2C 1Wie 2Wire 2c LCD Chip ExternalSRAM Ports BitBanged Project Information Extemal RG Timers USARTO USART M INTO Enabled Mode lowlevel gt M INTI Enabled Mode lowlevel M INT2Enabled Mode Lowlevel gt M INT3Enabled Mode Lowlevel gt MV INT4Enabled Mode Lowlevel gt M INTSEnabled Mode Lowlevel gt M INTBEnabled Mode Lowlevel gt M INTZEnabled Mode Lowlevel gt Checking the appropriate INTx Enabled check box enables the corresponding external interrupt If the AVR chip supports this feature you can select if the interrupt will be edge or level triggered using the corresponding Mode list box For each enabled external interrupt the CodeWizardAVR will define an ext_intx_isr interrupt service routine where x is the number of the external interrupt 1998 2003 HP InfoTech S R L Page 165 CodeVisionAVR For some devices like the Atmega169V L the External IRQ tab may present the following options CodeWizardAVR untitled cwp x File Help USI USARTO Analog Comparator ADC sP c 1Wire Lco LCD Controller BitBanged Project Information Chip Ports External IRQ Timers M INTO Enable
102. gptr va_end argptr return result void main void int s calculate the sum of 5 arguments s sum_all1 5 10 20 30 40 50 1998 2003 HP InfoTech S R L Page 112 CodeVisionAVR 4 7 Non local Jump Functions These functions can execute a non local goto They are usually used to pass control to an error recovery routine The prototypes for the non local jump functions are placed in the file setjmp h located in the INC subdirectory This file must be include ed before using the functions int setjmp char env This function saves the current CPU state Y SP SREG registers and the current instruction address in the env variable The CPU state can then be restored by subsequently calling the longjmp function Execution is then resumed immediately after the setjmp function call The setjmp function will return O when the current CPU state is saved in the env variable If the function returns a value different from 0 it signals that a longjmp function was executed In this situation the returned value is the one that was passed as the retval argument to the longjmp function In order to preserve the local variables in the function where setjmp is used these must be declared with the volatile attribute void longjmp char env int retval This function restores the CPU state that was previously saved in the env variable by a call to setjmp The retval argument holds the integer non zero
103. h S R L Page 15 CodeVisionAVR You must specify the new Project file name and its location Create New Project 21x Svein Geers aaaea C_asm 9 Therm 5 Ds1820 CI Thermicd Eeprom Keypad Leddemo Led Max1 241 Spi File name test n Save as type Projectiles pri Cancel The Project file will have the prj extension You can configure the Project by using the Project Configure menu command 1998 2003 HP InfoTech S R L Page 16 CodeVisionAVR 2 2 2 Opening an Existing Project You can open an existing Project file using the File Open menu command or by pressing the Open file button on the toolbar An Open dialog window appears Open RIES Look in E Multfile amp gl c Multfile File name Multfile Files of type Projectiles pri You must select the file name of the Project you wish to open By pressing the Open button you will open the Project file and its source file s You can configure the Project by using the Project Configure menu command 1998 2003 HP InfoTech S R L Page 17 CodeVisionAVR 2 2 3 Adding Notes or Comments to the Project With every Project the CodeVisionAVR IDE creates a text file wnere you can place notes and comments You can access this file using the Project Notes or Windows menu commands amp Project Notes Multfile prj This file can be edited using the standard Editor commands The file is automatically saved when y
104. he DS2430 types 0x14 is the DS2430 family code if rom_code i 0 DS2430 FAMILY CODE printf n r write text in each DS2430 at START ADDR if ds2430 write block amp rom_code i 0 text START ADDR sizeof text printf Data written OK in DS2430 u n r itl display the text written in each DS2430 if ds2430 read block amp rom_code i 0 buffer START ADDR sizeof text printf Data read OK n rDS2430 u text s n r i l buffer else printf Error reading data from DS2430 u n r itl else printf Error writing data to DS2430 u n r it1 stop while 1 Refer to the DS2430 data sheet for more information 1998 2003 HP InfoTech S R L Page 148 CodeVisionAVR 4 14 3 Dallas Semiconductor DS2433 EEPROM Functions These functions are intended for easy interfacing between C programs and the DS2433 1 Wire bus EEPROM The prototypes for these functions are placed in the file ds2433 h located in the INC subdirectory This file must be include ed before using the functions The 1 Wire bus functions prototypes are automatically include ed with the ds2433 h Prior to include ing the ds2433 h file you must declare which microcontroller port and port bits are used for communication with the DS2433 through the 1 Wire bus Example specify the port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ _ wl bit
105. he ds2430 h file you must declare which microcontroller port and port bits are used for communication with the DS2430 through the 1 Wire bus Example specify the port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ _ wl bit 2 endasm include the DS2430 functions prototypes include lt ds2430 h gt The DS2430 functions are unsigned char ds2430_read_block unsigned char romcode unsigned char dest unsigned char addr unsigned char size this function reads a block of size bytes starting from the DS2430 EEPROM memory address addr and stores it in the string dest located in SRAM It returns 1 if successful 0 if not The DS2430 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode unsigned char ds2430_read unsigned char romcode unsigned char addr unsigned char data this function reads a byte from the DS2430 EEPROM memory address addr and stores it in the SRAM memory location pointed by data It returns 1 if successful 0 if not The DS2430 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode unsigned char ds2430_write_block unsigned char romcode unsigned char source unsigned char addr unsigned char size this function writes a block of size bytes from the string source located in SRAM in the DS2430 EEPROM starting from memory address addr It returns 1 if successful 0 if not The DS2430 devi
106. her computer until you will Export the license to this computer After the license Export the compiler on the first computer will be disabled and you will only be able to run the compiler on the second one You can always Export the license back to the first computer but the license on the second one will be disabled after that By this procedure only one person can use the compiler at a time To Export the license from the computer 1 to the computer 2 you must proceed like this e install the CodeVisionAVR C compiler on the computer 2 e execute the compiler on computer 2 it will display a specific serial number x CodeVisionAVR License x Your Serial Number is 5AD5 4F7C ECD7 E225 To purchase a license please send this Serial Number to HP InfoTech 5 R L at dhptechn ir ro or hpinfotech mail com Ifyou allready purchased the program then you must Import the license fram a valid CodeVisionAVR installation X Cancel 1998 2003 HP InfoTech S R L Page 53 CodeVisionAVR e execute the compiler on computer 1 and select the Help Export menu command an Export CodeVisionAVR License dialog window will open e enter the serial number from computer 2 in the Destination Serial Number edit box amp Export CodeVisionAVR License Ed Serial of the destination computer BAD 5 4F C ECD E225 X Cancel e press the Export button if you press the Cancel button the Export will be ca
107. hich port bits are used for this The DS1302 s trickle charge function can be activated by checking the Trickle Charge Enabled check box The number of diodes respectively the charge resistor value can be specified using the Trickle Charge Diodes respectively Trickle Charge Resistors list boxes The DS1302 device is accessed through the Dallas Semiconductor DS1302 Real Time Clock Functions 1998 2003 HP InfoTech S R L Page 194 CodeVisionAVR 5 17 Specifying the Project Information By selecting the Project Information tab you can specify the information placed in the comment header located at the beginning of the C source file produced by CodeWizardAVR amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USART1 Chip ExtermslSRAM Ports Analog Comparator ADC SPI 2C 1Wie 2Wire 2c LcD BitBanged Project Information Project Name Version Date Author Company Comments You can specify the Project Name Date Author Company and Comments 1998 2003 HP InfoTech S R L Page 195 CodeVisionAVR 6 License Agreement 6 1 Software License The use of CodeVisionAVR indicates your understanding and acceptance of the following terms and conditions This license shall supersede any verbal or prior verbal or written statement or agreement to the contrary If you do not understand or accept these terms or your local regulations p
108. ifier is supported the precision specifier is not supported only the 0 and flags are supported no input size modifiers are supported 1998 2003 HP InfoTech S R L Page 22 CodeVisionAVR e long width the following conversion type characters are supported c s p i d u x X the width specifier is supported the precision specifier is not supported only the 0 and flags are supported only the l input size modifier is supported e long width precision the following conversion type characters are supported c s p i d u x X the width and precision specifiers are supported only the 0 and flags are supported only the l input size modifier is supported e float width precision the following conversion type characters are supported c s p i d u e E f x X the width and precision specifiers are supported only the 0 and flags are supported only the l input size modifier is supported The more features are selected the larger is the code size generated for the printf and sprintf functions The Data Stack Size must be also specified Eventually you may also specify the External SRAM Size in case the microcontroller have external SRAM memory connected The External SRAM Wait State option enables the insertion of wait states during access to the external SRAM
109. ignals PORTB bit allocation define ADC BUSY PINB 0O define NCONVST PORTB 1 LCD display buffer char lcd_buffer 33 unsigned read_adc void unsigned result start conversion in mode 1 high sampling performance NCONVST 0 NCONVST 1 wait for the conversion to complete while ADC BUSY read the MSB using SPI result unsigned spi 0 lt lt 8 read the LSB using SPI and combine with MSB result spi 0 calculate the voltage in mv result unsigned unsigned long result VREF 4096L return the measured voltage return result void main void initialize PORTB PB O input from AD7896 BUSY PB 1 output to AD7896 CONVST PB 2 amp PB 3 inputs PB 4 output SPI SS pin PB 5 input PB 6 input SPI MISO PB 7 output to AD7896 SCLK DDRB 0x92 initialize the SPI in master mode no interrupts MSB first clock phase negative SCK low when idle clock phase 0 SCK fxtal 4 SPCR 0x54 the AD7896 will work in mode 1 high sampling performance CONVST 1 SCLK 0 DowPN EH 1998 2003 HP InfoTech S R L Page 153 CodeVisionAVR PORTB 2 initialize the LCD led_init 16 lcd _putsf AD7896 SPI bus nVoltmeter delay ms 2000 led_clear read and display the ADC input voltage while 1 sprintf lcd_ buffer Uadc s4umv read adc led_clear lcd puts lcd buffer del
110. igned check box is checked the compiler treats by default the char data type as an unsigned 8 bit in the range 0 255 If the check box is not checked the char data type is by default a signed 8 bit in the range 128 127 This option can also be specified using the pragma uchar compiler directive Treating char as unsigned leads to better code size and speed If the 8 bit enums check box is checked the compiler treats the enumerations as being of 8 bit char data type leading to improved code size and execution speed of the compiled program If the check box is not checked the enumerations are considered as 16 bit int data type as required by ANSI The Enhanced Instructions check box allows enabling or disabling the generation of Enhanced Core instructions for the ATmega128 ATmega16 ATmega161 ATmega162 ATmega163 ATmega32 ATmega323 ATmega64 ATmega8 and AT94K FPSLIC devices The rest of the registers in the range R2 to R14 not used for bit variables can be automatically allocated to char and int global variables by checking the Compilation Automatic Register Allocation check box An external startup file can be used by checking the Compilation Use an External Startup File check box The generation of warning messages during compilation can be enabled or disabled by using the Compilation Enable Warnings check box For debugging purposes you have the option Stack End Markers If you select it the compiler will place the strings
111. implementation would require a large amount of FLASH memory space The format specifier string has the following structure width type char The optional width specifier sets the maximal number of characters to read If the function encounters a whitespace character or one that cannot be converted then it will continue with the next input field if present The type_char conversion type character is used to specify the way the input field will be processed The following conversion type characters are supported d inputs a signed decimal integer in a pointer to int argument i inputs a signed decimal integer in a pointer to int argument u inputs an unsigned decimal integer in a pointer to unsigned int argument x inputs an unsigned hexadecimal integer in a pointer to unsigned int argument c inputs an ASCII character in a pointer to char argument s inputs an ASCII character string in a pointer to char argument no input is done a is stored The function returns the number of successful entries or 1 on error signed char sscanf char str char flash fmtstr arg1 address arg2 address this function is identical to scanf except that the formatted text is inputted from the null terminated character string str located in SRAM 1998 2003 HP InfoTech S R L Page 102 CodeVisionAVR 4 3 Standard Library Functions The prototypes for these functions are placed in the file stdlib
112. include ed before using the functions The SPI functions are unsigned char spi unsigned char data this function sends the byte data simultaneously receiving a byte Prior to using the spi function you must configure the SPI Control Register SPCR according to the Atmel Data Sheets Because the spi function uses polling for SP communication there is no need to set the SPI Interrupt Enable Bit SPIE Example of using the spi function for interfacing to an AD7896 ADC Digital voltmeter using an Analog Devices AD7896 ADC connected to an AT90S8515 using the SPI bus Chip AT90S8515 Memory Model SMALL Data Stack Size 128 bytes Clock frequency 4MHz AD7896 connections to the AT90S8515 AD7896 AT9S8515 DIP40 1 Vin 2 Vref 5V 3 AGND 20 GND 4 SCLK 8 SCK 5 SDATA 7 MISO 6 DGND 20 GND 7 CONVST 2 PB1 8 BUSY 1 PBO Use an 2x16 alphanumeric LCD connected to PORTC as follows LCD AT90S8515 DIP40 1 GND 20 GND 2 5V 40 VCC VLC RS 21 PCO RD 22 PCl 6 EN 23 PC2 11 D4 25 PC4 12 D5 26 PC5 13 D6 27 PCO 14 D7 28 PC7 Oe Ww 1998 2003 HP InfoTech S R L Page 152 CodeVisionAVR asm equ _ lcd port 0x15 endasm include lt lcd h gt LCD driver routines include lt spi h gt SPI driver routine include lt 90s8515 h gt include lt stdio h gt include lt delay h gt AD7896 reference voltage mV define VREF 5000L AD7896 control s
113. infotech ro Here you can check for the latest HP InfoTech s products and updates to CodeVisionAVR 2 8 Contacting HP InfoTech by E Mail The Help E Mail HP InfoTech menu command opens the default e mail program and allows you to send an e mail to office hpinfotech ro 2 9 Quitting the CodeVisionAVR IDE To quit working with the CodeVisionAVR IDE you must select the File Exit menu command If some source files were modified and were not saved yet you will be prompted if you want to do that 1998 2003 HP InfoTech S R L Page 56 CodeVisionAVR 3 CodeVisionAVR C Compiler Reference This section describes the general syntax rules for the CodeVisionAVR C compiler Only specific aspects regarding the implementation of the C language by this compiler are exposed This help is not intended to teach you the C language you can use any good programming book to do that You must also consult the appropriate AVR data sheets from Atmel 3 1 The Preprocessor The Preprocessor directives allows you to e include text from other files such as header files containing library and user function prototypes e define macros that reduce programming effort and improve the legibility of the source code e set up conditional compilation for debugging purposes and to improve program portability e issue compiler specific directives The include directive may be used to include another file in your source You may nest as many as 16 include files
114. ing the macros void va_start argptr previous_par This macro when used in a function with a variable length argument list initializes the argptr pointer of va_list type for subsequent use by the va_arg and va_end macros The previous_par argument must be the name of the function argument immediately preceding the optional arguments The va_start macro must be called prior to any access using the va_arg macro type va_arg argptr type This macro is used to extract successive arguments from the variable length argument list referenced by argptr type specifies the data type of the argument to extract The va_arg macro can be called only once for each argument The order of the parameters in the argument list must be observed On the first call va_arg returns the first argument after the previous_par argument specified in the va_start macro Subsequent calls to va_arg return the remaining arguments in succession void va_end argptr This macro is used to terminate use of the variable length argument list pointer argptr initialized using the va_start macro Example include lt stdarg h gt declare a function with a variable number of arguments int sum_all int nsum va_list argptr int i result 0 initialize argptr va_start argptr nsum add all the function arguments after nsum for i 1 i lt nsum i add each argument resultt va_arg argptr int terminate the use of ar
115. ints to an area of SRAM where are stored the 8 bytes ROM codes returned by the device After the eighth byte the function places a ninth status byte which contains a status bit returned by some 1 Wire devices e g DS2405 Thus the user must allocate 9 bytes of SRAM for each device present on the 1 Wire bus If there is more then one device connected to the 1 Wire bus than the user must first call the w1_search function to identify the ROM codes of the devices and to be able to address them at a later stage in the program 1998 2003 HP InfoTech S R L Page 140 CodeVisionAVR Example include lt 90s8515 h gt specify the port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ wl bit 2 endasm include the 1 Wire bus functions prototypes include lt lwire h gt include the printf function prototype include lt stdio h gt specify the maximum number of devices connected to the 1 Wire bus define MAX DEVICES 8 allocate SRAM space for the ROM codes amp status bit unsigned char rom codes MAX DEVICES 9 quartz crystal frequency Hz define xtal 4000000L Baud rate define baud 9600 void main void unsigned char i j devices initialize the UART s baud rate UBRR xtal 16 baud 1 initialize the UART control register TX enabled no interrupts 8 data bits UCR 8 detect how many DS1820 DS18S20
116. ister s UCPOL bit set to 1 The serial communication is realized using the Standard Input Output Functions getchar gets scanf putchar puts and printf For interrupt driven serial communication CodeWizardAVR automatically redefines the basic getchar and putchar functions The receiver buffer is implemented using the global array rx_buffer The global variable rx_wr_index is the rx_buffer array index used for writing received characters in the buffer The global variable rx_rd_index is the rx_buffer array index used for reading received characters from the buffer by the getchar function The global variable rx_counter contains the number of characters received in rx_buffer and not yet read by the getchar function If the receiver buffers overflows the rx_buffer_overflow global bit variable will be set 1998 2003 HP InfoTech S R L Page 173 CodeVisionAVR The transmitter buffer is implemented using the global array tx_buffer The global variable tx_wr_index is the tx_buffer array index used for writing in the buffer the characters to be transmitted The global variable tx_rd_index is the tx_buffer array index used for reading from the buffer the characters to be transmitted by the putchar function The global variable tx_counter contains the number of characters from tx_buffer not yet transmitted by the interrupt system For devices with 2 UARTs respectively 2 USARTs there will be two tabs present UARTO and UART1 respec
117. k20 ja 2c ja Mega163 BDE ja 9052343 a 94k40 a Led ja MeqabO3 a T 9054414 ja Bcd a Led4x40 a Mem ja 9054433 la Ctype ja Ledstk a Pcf8583 File name mylib Save as type Ic Compiler header file h gt Cancel 1998 2003 HP InfoTech S R L Page 92 CodeVisionAVR 2 Create the library file Select the File New menu command or press the New toolbar button The following dialog window will open b Create New File E4 File Type Source C Project X Cancel Select Source and press the OK button A new editor window will be opened for the untitled c source file Type in the definitions for your functions Example int sum int a int b return atb int mul int a int b return a b Save the file under a new name for example mylib c in any directory using the File Save As menu command Save C Delphi5 AVRC untitled c As x Save in Si work gt BI al c Filename myi TE Save as type Ic Compiler source file c gt ancel 1998 2003 HP InfoTech S R L Page 93 CodeVisionAVR Finally use the File Convert to Library menu command to save the currently opened file under the name mylib lib in the LIB directory New Library Name EJ mylib lib In order to use the newly created mylib lib library just include the mylib h header file in the beginning of your program Example i
118. l work the function addresses the string as it is located in FLASH display flash Hello world Constant can be grouped in arrays which can have up to 8 dimensions Constants are stored in FLASH memory to specify this you must use the flash or const keywords Constant expressions are automatically evaluated during compilation Example flash int integer constant 1234 5 flash char char _constant a flash long long int constant1 99L flash long long int _constant2 0x10000000 flash int integer arrayl 1 2 3 The first two elements will be 1 and 2 the rest will be 0 flash int integer array2 10 1 2 flash int multidim array 2 3 1 2 3 4 5 6 flash char string constantl This is a string constant const char string constant2 This is also a string constant Constants can t be declared inside functions 1998 2003 HP InfoTech S R L Page 65 CodeVisionAVR 3 7 Variables Program variables can be global accessible to all the functions in the program or local accessible only inside the function they are declared If not specifically initialized the global variables are automatically set to O at program startup The local variables are not automatically initialized on function call The syntax is lt storage modifier gt lt type definition gt lt identifier gt Example Global variables declaration char a int b and initialization
119. le must be include ed before using the functions unsigned char isalnum char c returns 1 if c is alphanumeric unsigned char isalpha char c returns 1 if c is alphabetic unsigned char isascii char c returns 1 if c is an ASCII character 0 127 unsigned char iscntrl char c returns 1 if c is a control character 0 31 or 127 unsigned char isdigit char c returns 1 if c is a decimal digit unsigned char islower char c returns 1 if c is a lower case alphabetic character unsigned char isprint char c returns 1 if c is a printable character 32 127 unsigned char ispunct char c returns 1 if c is a punctuation character all but control and alphanumeric unsigned char isspace char c returns 1 c is a white space character space CR HT unsigned char isupper char c returns 1 if c is an upper case alphabetic character unsigned char isxdigit char c returns 1 if c is a hexadecimal digit char toascii char c returns the ASCII equivalent of character c unsigned char toint char c interprets c as a hexadecimal digit and returns an usigned char from 0 to 15 char tolower char c returns the lower case of c if c is an upper case character else c 1998 2003 HP InfoTech S R L Page 98 CodeVisionAVR char toupper char c returns the upper case of c if c is a lower case character else c 4 2 Standard C Input Output Functions The prototypes for these functions are placed in the file stdio h located i
120. lent The number n values must be from 0 to 99 4 9 Gray Code Conversion Functions The prototypes for these functions are placed in the file gray h located in the INC subdirectory This file must be include ed before using the functions unsigned char gray2binc unsigned char n unsigned char gray2bin unsigned int n unsigned char gray2binl unsigned long n Convert the number n from Gray code representation to it s binary equivalent unsigned char bin2grayc unsigned char n unsigned char bin2gray unsigned int n unsigned char bin2grayl unsigned long n Convert the number n from binary representation to it s Gray code equivalent 1998 2003 HP InfoTech S R L Page 114 CodeVisionAVR 4 10 Memory Access Functions The prototypes for these functions are placed in the file mem h located in the INC subdirectory This file must be include ed before using the functions void pokeb unsigned int addr unsigned char data this function writes the byte data to SRAM at address addr void pokew unsigned int addr unsigned int data this function writes the word data to SRAM at address addr The LSB is written at address addr and the MSB is written at address addr 1 unsigned char peekb unsigned int addr this function reads a byte located in SRAM at address addr unsigned int peekw unsigned int addr this function reads a word located in SRAM at address addr The LSB is read from address addr and the MSB is read from add
121. lling the interrupt functions and restore them back on exit A RETI assembly instruction is placed at the end of the interrupt function Interrupt functions can t return a value nor have parameters You must also set the corresponding bits in the peripheral control registers to configure the interrupt system and enable the interrupts The automatic saving and restoring of registers RO R1 R15 R22 R23 R24 R25 R26 R27 R30 R31 and SREG during interrupts can be turned on or off using the pragma savereg directive Example Turn registers saving off pragma savereg interrupt handler interrupt 1 void my irq void now save only the registers that are affected by the routines in the handler for example R30 R31 and SREG asm push r30 push r31 in r30 SREG push r30 endasm place the C code here ries now restore SREG R31 and R30 asm pop r30 out SREG r30 pop r31 pop r30 endasm ERS nable register saving for the other interrupts pragma saveregt The default state is automatic saving of registers during interrupts 1998 2003 HP InfoTech S R L Page 85 CodeVisionAVR 3 16 SRAM Memory Organization A compiled program has the following memory map Working Registers 20h I O Registers 60h DSTACKEND Data Stack 60h Data Stack Size Global Variables 60h Data Stack Size Global Var Size HSTACKEND Hardware Stack
122. n the INC subdirectory This file must be include ed before using the functions The standard C language I O functions were adapted to work on embedded microcontrollers with limited resources The lowest level Input Output functions are char getchar void returns a character received by the UART using polling void putchar char c transmits the character c using the UART using polling Prior to using these functions you must e initialize the UART s Baud rate e enable the UART transmitter e enable the UART receiver Example include lt 90s8515 h gt include lt stdio h gt quartz crystal frequency Hz define xtal 4000000L Baud rate define baud 9600 void main void char k initialize the UART s baud rate UBRR xtal 16 baud 1 initialize the UART control register RX amp TX enabled no interrupts 8 data bits UCR 0x18 while 1 receive the character k getchar and echo it back putchar k F3 If you intend to use other peripherals for Input Output you must modify accordingly the getchar and putchar functions The source code for these functions is available in the file stdio h 1998 2003 HP InfoTech S R L Page 99 CodeVisionAVR All the high level Input Output functions use getchar and putchar void puts char str outputs using putchar the null terminated character string str located in SRAM followed by a new line character
123. n void char k1 k2 k3 k4 TAC Elp T23 define a pointer to the structure struct eeprom structure eeprom ep direct access to structure members kl se 0 a il se 0 b k2 se 0 c 2 k3 se 1 a i2 se 1 b k4 se 1 c 2 same access to structure members using a pointer ep se initialize the pointer with the structure address kl ep gt a il ep gt b k2 ep gt c 2 ep increment the pointer k3 ep gt a 12 ep gt b k4 ep gt c 2 Because some AVR devices have a small amount of SRAM in order to keep the size of the Data Stack small it is recommended not to pass structures as function parameters and use pointers for this purpose Example struct alpha int a b c s 2 3 define the function struct alpha sum struct struct alpha sp member c member a member b sp gt c sp gt a sp gt b return a pointer to the structure return sp void main void int iy s gt c s gt a s gt b i s gt c i sum struct amp s gt c 1998 2003 HP InfoTech S R L Page 71 CodeVisionAVR Structure elements can be also declared as bit fields having a width from 1 to 32 Bit fields are allocated in the order of declaration starting from the least significant bit Example this structure will occupy 1 byte in SRAM as the bit field data type is unsigned char struct alphal unsigned char a 1
124. n1_msk must be set to LCD_EN 1 respectively LCD_EN2 to select the upper respectively lower half LCD controller Example enables the displaying of the cursor on the upper half of the LCD _en1 msk LCD_EN1 _lcd_ready _lcd_write data 0xe 1998 2003 HP InfoTech S R L Page 119 CodeVisionAVR void Icd_write_byte unsigned char addr unsigned char data writes a byte to the LCD character generator or display RAM unsigned char Icd_read_byte unsigned char addr reads a byte from the LCD character generator or display RAM The high level LCD Functions are void Icd_init void initializes the LCD module clears the display and sets the printing character position at row 0 and column 0 No cursor is displayed This is the first function that must be called before using the other high level LCD Functions void Icd_clear void clears the LCD and sets the printing character position at row 0 and column 0 void Icd_gotoxy unsigned char x unsigned char y sets the current display position at column x and row y The row and column numbering starts from 0 void Icd_putchar char c displays the character c at the current display position void Icd_puts char str displays at the current display position the string str located in SRAM void Icd_putsf char flash str displays at the current display position the string str located in FLASH 1998 2003 HP InfoTech S R L Page 120 CodeVisionAVR
125. nAVR 3 14 Accessing the EEPROM Accessing the AVR internal EEPROM is accomplished using global variables preceded by the keyword eeprom Example The value 1 is stored in the eeprom int alfa 1 T eeprom char beta eeprom long arrayl 5 The string is stored in the eeprom char string Hello void main void int i Pointer to EEPROM int eeprom ptr_ to eeprom Write directly the value 0x55 to alfa 0x55 or indirectly by using a pointer ptr to eeprom alfa ptr_ to _eeprom 0x55 Read directly the value from the i alfa or indirectly by using a pointer i ptr_ to eeprom Pointers to the EEPROM always use 16 bits EPROM during chip programming EPROM during chip programming the EEPROM ey EEPROM ay 1998 2003 HP InfoTech S R L Page 84 CodeVisionAVR 3 15 Using Interrupts The access to the AVR interrupt system is implemented with the interrupt keyword Example Vector numbers are for the AT90S8515 Called automatically on external interrupt interrupt 2 void external intO void Place your code here Called automatically on TIMERO overflow interrupt 8 void timer0 overflow void Place your code here Interrupt vector numbers start with 1 The compiler will automatically save all the used registers when ca
126. nabled I Generate Acknowledge Pulse Slave Address J0 h l General Call Recognition Bit Rate 250 000 kHz M 2 Wire Interrupt The AVR chip s 2 Wire interface can be enabled by checking the 2 Wire Enabled check box If the Generate Acknowledge Pulse check box is checked the ACK pulse on the 2 Wire bus is generated if one of the following conditions is met e the device s own slave address has been received e a General Call has been received and the General Call Recognition check box is checked e adata byte has been received in master receiver or slave receiver mode If the Generate Acknowledge Pulse check box is not checked the chip s 2 Wire interface is virtually disconnected from the 2 Wire bus This check box will set the state of the TWEA bit of the TVCR register The Slave Address edit box sets the slave address of the 2 Wire serial bus unit This address must be specified in hexadecimal and will be used to initialize the bits 1 7 of the TWAR register Checking the General Call Recognition check box enables the recognition of the General Call given over the 2 Wire bus This check box will set the state of the TWGCE bit of the TWAR register The Bit Rate list box allows you to specify maximum frequency of the pulses on the SCL 2 Wire bus line It will affect the value of the TWBR register As both the receiver and transmitter may stretch the duration of the low period of the SCL line when waiting for response the freq
127. nal is bit 3 the SCLK signal is bit 4 the RST signal is bit 5 asm equ _ds1302 port 0x18 equ _ds1302 io 3 equ _ ds1302_sclk 4 equ _ ds1302_rst 5 endasm now you can include the DS1302 Functions include lt ds1302 h gt The DS1302 Functions are void rtc_init unsigned char tc_on unsigned char diodes unsigned char res this function initializes the DS1302 chip This is the first function that must be called prior to using the other DS1302 Functions If the tc_on parameter is set to 1 then the DS1302 s trickle charge function is enabled The diodes parameter specifies the number of diodes used when the trickle charge function is enabled This parameter can take the value 1 or 2 The res parameter specifies the value of the trickle charge resistor e 0 for no resistor e 1 for a 2kQ resistor e 2 fora 4kQ resistor e 3 fora 8kQ resistor Refer to the DS1302 data sheet for more information unsigned char ds1302_read unsigned char addr this function reads a byte stored at address addr in the DS1302 registers or SRAM void ds1302_write unsigned char addr unsigned char data this function stores the byte data at address addr in the DS1302 registers or SRAM void rtc_get_time unsigned char hour unsigned char min unsigned char sec this function returns the current time measured by the RTC The hour min and sec pointers must point to the variables that must receive the values of hours minutes a
128. nceled e you will be prompted where to place the new license file for the computer 2 usually you can chose a diskette in drive A Save License File HEI Save in E 3 5 Floppy A al c File name license fi Save as type License files dat Cancel e press Save After the new license file is successfully copied to the diskette the compiler on computer 1 will cease running 1998 2003 HP InfoTech S R L Page 54 CodeVisionAVR e place the diskette with the license file in drive A of computer 2 and press the Import button After that the license transfer is completed and the compiler will run only on computer 2 CodeVisionAVR License Your Serial Number is 5AD5 4F7C ECD E225 To purchase a license please send this Serial Number to HP InfoTech 5 R L at dhptechn ir ro or hpinfotech mail com Ifyou allready purchased the program then you must Import the license from a valid CodeVisionAVR installation X Cancel Please note that after the Export procedure the serial number of the computer 1 will change In this situation when you will try to Import a license back to this computer you must enter this new serial number not the old one 1998 2003 HP InfoTech S R L Page 55 CodeVisionAVR 2 7 Connecting to HP InfoTech s Web Site The Help HP InfoTech on the Web menu command opens the default web browser and connects to HP InfoTech s web site http www hp
129. nclude lt mylib h gt Library files usually reside in the LIB directory but paths to additional directories can be added in the Project Configure C Compiler Paths Library paths menu 1998 2003 HP InfoTech S R L Page 94 CodeVisionAVR 3 20 Using the AVR Studio Debugger CodeVisionAVR is designed to work in conjunction with Atmel AVR Studio debugger version 3 or 4 In order to be able to do C source level debugging using AVR Studio you must select the COFF output file format in the Project Configure Assembler menu option The AVR Studio Debugger is invoked using the Tools Debugger menu command or the Debugger toolbar button After AVR Studio is executed the user must select File Open in order to load the COFF file to be debugged Below are some commands that can be used with AVR Studio 3 Once the program is loaded it can be launched in execution using the Debug Go menu command by pressing the F5 key or by pressing the Execute program toolbar button Program execution can be stopped at any time using the Debug Break menu command by pressing Ctrl F5 keys or by pressing the Break toolbar button To single step the program the Debug Trace Into F11 key Debug Step F10 key Debug Step Out menu commands or the corresponding toolbar buttons should be used In order to stop the program execution at a specific source line the Breakpoints Toggle Breakpoint menu command the F9 key or the corresponding toolbar button shoul
130. nd seconds 1998 2003 HP InfoTech S R L Page 138 CodeVisionAVR Example asm equ _ds1302 port 0x18 equ _ds1302 io 3 equ _ ds1302_sclk 4 equ _ ds1302_rst 5 endasm include lt ds1302 h gt void main void unsigned char h m s initialize the DS1302 RTC use trickle charge with 1 diode and 8K resistor rhe angel 3 5 read time from the DS1302 RTC rtc_get_ time amp h amp m amp s void rtc_set_time unsigned char hour unsigned char min unsigned char sec this function sets the current time of the RTC The hour min and sec parameters represent the values of hour minutes and seconds void rtc_get_date unsigned char date unsigned char month unsigned char year this function returns the current date measured by the RTC The date month and year pointers must point to the variables that must receive the values of date month and year void rtc_set_date unsigned char date unsigned char month unsigned char year this function sets the current date of the RTC 1998 2003 HP InfoTech S R L Page 139 CodeVisionAVR 4 14 1 Wire Protocol Functions The 1 Wire Functions are intended for easy interfacing between C programs and various peripherals using the Dallas Semiconductor 1 Wire protocol These functions treat the microcontroller as a bus master and the peripherals as slaves The prototypes for these functions are placed in the file 1wire h located in the INC
131. nk spaces inserted when pressing the Tab key can be specified using the Tab Size spin edit The font used by the text Editor and the Terminal can be specified using the Font button The different colors used for displaying the text in the Editor windows and for C syntax highlighting can be specified by clicking on the appropriate panels in the Colors group The Background and Text color settings are the same for both the EditorEdit File and the TerminalTerminal The Editor configuration changes can be saved respectively canceled using the OK respectively Cancel buttons By pressing the Default button the default Editor settings are restored 1998 2003 HP InfoTech S R L Page 47 CodeVisionAVR 2 4 3 Configuring the Assembler The Assembler can be configured using the Settings Assembler menu command Assembler Settings x On Assembler Eror Open the listfile C Open the asm file xX Cancel The On Assembler Error options allow to select which file will be automatically opened by the Editor in the case of an assembly error The Assembler configuration changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP InfoTech S R L Page 48 CodeVisionAVR 2 4 4 Setting the Debugger Path The CodeVisionAVR C Compiler is designed to work in conjunction with the Atmel AVR Studio debugger version 3 or 4 Before you can invoke the debugger you m
132. now you can include the LM75 Functions include lt lm75 h gt The LM75 Functions are void Im75_init unsigned char chip signed char thyst signed char tos unsigned char pol this function initializes the LM75 sensor chip Before calling this function the C bus must be initialized by calling the i2c_init function This is the first function that must be called prior to using the other LM75 Functions If more then one chip is connected to the C bus then the function must be called for each one specifying accordingly the function parameter chip Maximum 8 LM75 chips can be connected to the I C bus their chip address can be from 0 to 7 The LM75 is configured in comparator mode where it functions like a thermostat The O S output becomes active when the temperature exceeds the tos limit and leaves the active state when the temperature drops below the thyst limit Both thyst and tos are expressed in C pol represents the polarity of the LM75 O S output in active state If pol is 0 the output is active low and if pol is 1 the output is active high Refer to the LM75 data sheet for more information int lm75_temperature_10 unsigned char chip this function returns the temperature of the LM75 sensor with the address chip The temperature is in C and is multiplied by 10 Example how to display the temperature of two LM75 sensors with addresses 0 and 1 the LM75 I C bus is connected to PORTB the SDA signal is bit 3
133. ns may not be present For more information you must consult the corresponding Atmel data sheet 1998 2003 HP InfoTech S R L Page 169 CodeVisionAVR amp CodeWizardAVR untitled cwp x File Help Analog Comparator ADC SPI 12C 1Wire 2Wire 2c LCD BitBanged Project Information Chip ExternalSRAM Ports Extemal IRQ Timers oe USART1 Timer 0 Timer 1 Timer 2 3v a gt Clock Source System Clock Clock Value Timer3Stopped gt Mode Normal top FFFFh x Out A Discon Out B Discon Out c Discon Input Capt Noise Cancel Interrupt on Ir Timer 3 Overflow Value fo h Comp A J0 h 6 0 h C40 h By selecting the Timer 3 tab you can have the following options Clock Source specifies the timer counter 3 clock pulse source Clock Value specifies the timer counter 3 clock frequency Mode specifies if the timer counter 3 functioning mode Out A specifies the function of the timer counter 3 output A and depends of the functioning mode Out B specifies the function of the timer counter 3 output B and depends of the functioning mode Out C specifies the function of the timer counter 3 output C and depends of the functioning mode Inp Capt specifies the timer counter 3 capture trigger edge and if the noise canceler is to be used Interrupt on specifies if an interrupt is to be generated on timer counter 3 overflow input capture and compare match e Timer Value s
134. ns the absolute value of the integer x unsigned long labs long int x returns the absolute value of the long integer x float fabs float x returns the absolute value of the floating point number x signed char cmax signed char a signed char b returns the maximum value of bytes a and b int max int a int b returns the maximum value of integers a and b long int Imax long int a long int b returns the maximum value of long integers a and b float fmax float a float b returns the maximum value of floating point numbers a and b signed char cmin signed char a signed char b returns the minimum value of bytes a and b int min int a int b returns the minimum value of integers a and b long int Imin long int a long int b returns the minimum value of long integers a and b float fmin float a float b returns the minimum value of floating point numbers a and b signed char csign signed char x returns 1 0 or 1 if the byte x is negative zero or positive signed char sign int x returns 1 0 or 1 if the integer x is negative zero or positive 1998 2003 HP InfoTech S R L Page 104 CodeVisionAVR signed char Isign long int x returns 1 0 or 1 if the long integer x is negative zero or positive signed char fsign float x returns 1 0 or 1 if the floating point number x is negative zero or positive unsigned char isqrt unsigned int x returns the square root of the unsigned integer x unsigned int Isqrt u
135. nsigned long x returns the square root of the unsigned long integer x float sqrt float x returns the square root of the positive floating point number x float floor float x returns the smallest integer value of the floating point number x float ceil float x returns the largest integer value of the floating point number x float fmod float x float y returns the remainder of x divided by y float modf float x float ipart splits the floating point number x into integer and fractional components The fractional part of x is returned as a signed floating point number The integer part is stored as floating point number at ipart float Idexp float x int expn returns x 2 float frexp float x int expn returns the mantisa and exponent of the floating point number x float exp float x returns e float log float x returns the natural logarithm of the floating point number x float log10 float x returns the base 10 logarithm of the floating point number x 1998 2003 HP InfoTech S R L Page 105 CodeVisionAVR float pow float x float y returns x float sin float x returns the sine of the floating point number x where the angle is expressed in radians float cos float x returns the cosine of the floating point number x where the angle is expressed in radians float tan float x returns the tangent of the floating point number x where the angle is expressed in radians float sinh float x
136. nter to dest void memchr void buf unsigned char c unsigned char n for the TINY memory model void memchr void buf unsigned char c unsigned int n for the SMALL memory model Scans n bytes from buf for byte c Returns a pointer to c if found or a NULL pointer if not found signed char memcmp void buf1 void buf2 unsigned char n for the TINY memory model 1998 2003 HP InfoTech S R L Page 110 CodeVisionAVR signed char memcmp void buf1 void buf2 unsigned int n for the SMALL memory model Compares at most n bytes of buf1 with buf2 Returns lt 0 0 gt 0 according to buf1 lt buf2 buf1 buf2 buf1 gt buf2 signed char memcmpf void buf1 void flash buf2 unsigned char n for the TINY memory model signed char memcmpf void buf1 void flash buf2 unsigned int n for the SMALL memory model Compares at most n bytes of buf1 located in SRAM with buf2 located in FLASH Returns lt 0 0 gt 0 according to buf1 lt buf2 buf1 buf2 buf1 gt buf2 void memset void buf unsigned char c unsigned char n for the TINY memory model void memset void buf unsigned char c unsigned int n for the SMALL memory model Sets n bytes from buf with byte c Returns a pointer to buf 1998 2003 HP InfoTech S R L Page 111 CodeVisionAVR 4 6 Variable Length Argument Lists Macros These macros are defined in the file stdarg h located in the INC subdirectory This file must be include ed before us
137. ogrammer is executed by selecting the Tools Chip Programmer menu command or by pressing the Chip Programmer button on the toolbar CodeVisionAYR Chip Programmer Atmel STK500 AVRISP Ea File Edit Program Read Compare Help EEPROM Start 0 h End FFFF h Start 0 h End FFF h Checksum 0000h Checksum F000h Chip Programming Options FLASH Lock Bits Fuse Bit s No Protection CKSELO 0 C Programming disabled C Programming and Verification disabled C BODLEVEL 0 Boot Lock Bit 0 Boot Lock Bit 1 C BOOTRST 0 B01 1 BO2 1 B11 1 B12 1 C BOOTS70 0 C B01 0 B02 1 Bii 08i2 1 C BO0TSZ1 0 C B01 0 B02 0 B11 0 B12 0 C B01 1 B02 0 C B11 1 B12 0 C OCDEN 0 E M Check Signature MW Check Erasure Preserve EEPROM M Verify You can select the type of the chip you wish to program using the Chip combo box If the chip you have selected has Fuse Bit s that may be programmed then a supplementary Fuse Bit s check box will appear Using this check box you can set various chip options which are described in the Atmel data sheets If a Fuse Bit s check box is checked then the corresponding fuse bit will be set to 0 the fuse being considered as programmed as per the convention from the Atmel data sheets If a Fuse Bits s check box is not checked then the corresponding fuse bit will be set to 1 the fuse being considered as not programmed 199
138. om struct _type variable declaration byte alfa eeprom eeprom struct type structl 1998 2003 HP InfoTech S R L Page 76 CodeVisionAVR 3 9 Type Conversions In an expression if the two operands of a binary operator are of different types then the compiler will convert one of the operands into the type of the other The compiler uses the following rules If either of the operands is of type float then the other operand is converted to the same type If either of the operands is of type long int or unsigned long int then the other operand is converted to the same type Otherwise if either of the operands is of type int or unsigned int then the other operand is converted to the same type Thus char type or unsigned char type gets the lowest priority Using casting you can change these rules Example void main void int ap c long b The long integer variable b will be treated here as an integer c at int b It is important to note that if the Project Configure C Compiler Code Generation Promote char to int option isn t checked or the pragma promotechart isn t used the char respectively unsigned char type operands are not automatically promoted to int respectively unsigned int as in compilers targeted for 16 or 32 bit CPUs This helps writing more size and speed efficient code for an 8 bit CPU like the AVR To prevent overflow on 8 bit addition or multiplication casting may be
139. on then after successful compilation assembly your program will be automatically transferred to the AVR chip using the built in Programmer software The following steps are executed automatically e Chip erasure FLASH and EEPROM blank check FLASH programming and verification EEPROM programming and verification Fuse and Lock Bits programming The Merge data from a ROM File for FLASH Programming option if checked will merge in the FLASH programming buffer the contents of the ROM file created by the compiler after Make with the data from the ROM file specified in ROM File Path This is useful for example when adding a boot loader executable compiled in another project to an application program that will be programmed in the FLASH memory 1998 2003 HP InfoTech S R L Page 27 CodeVisionAVR You can select the type of the chip you wish to program using the Chip combo box If the chip you have selected has Fuse Bit s that may be programmed then a supplementary Fuse Bit s check box will appear Using this check box you can set various chip options which are described in the Atmel data sheets If a Fuse Bit s check box is checked then the corresponding fuse bit will be set to 0 the fuse being considered as programmed as per the convention from the Atmel data sheets If a Fuse Bits s check box is not checked then the corresponding fuse bit will be set to 1 the fuse being considered as not programmed If yo
140. oolbar M Show Navigator M Show Messages MV Show Information If the Show Toolbar check box is checked the command buttons toolbar will be displayed If the Show Navigator check box is checked the Navigator window is displayed in the left of the main program window If the Show Information check box is checked there will be an Information window displayed after Compiling or Making The General Settings changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP InfoTech S R L Page 46 CodeVisionAVR 2 4 2 Configuring the Editor The Editor can be configured using the Settings Editor menu command Editor Settings Ea Colors M Syntax Highlighting Aenean O Deteut W M Show Line Numbers Text E Default Autoindent C Keywords E Defut Preprocessor MM Dea Tab Size 4 pd Storage modif E Defut F Strings Default Font A Comments D Default X Cancel z Default By checking or unchecking the Syntax Highlighting check box you can enable or disable the C syntax color highlighting of the files displayed in the Editor windows By checking or unchecking the Show Line Numbers check box you can enable or disable the displaying of the line numbers in the Editor windows By checking or unchecking the Autoindent check box you can enable or disable the autoindenting during file editing The number of bla
141. or will create a backup file with an character appended to the extension All currently opened files can be saved using the File Save All menu command 2 1 6 Renaming a File The currently edited file can be saved under a new name by using the File Save As menu command A Save dialog window will open Save C CVAVR BIN untitled c As HEI Save in S Bin amp al c File name ftest Save as type Ic Compiler source file c Cancel You will have the possibility to specify the new name and type of the file and eventually its new location 1998 2003 HP InfoTech S R L Page 11 CodeVisionAVR 2 1 7 Printing a File You can print the current file using the File Print menu command or by pressing the Print button on the toolbar The contents of the file will be printed to the Windows default printer The paper margins used when printing can be set using the File Page Setup menu command which opens the Page Setup dialog window amp Page Setup x Printing Options M Page Header M Page Numbers M Highlight Syntax Top fi 9 A Units rm Bottom fig WA amp Printer XxX Cancel The units used when setting the paper margins are specified using the Units list box The printer can be configured by pressing the Printer button in this dialog window Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP In
142. oso outs EE E NE 17 2 2 3 Adding Notes or Comments to the Project seessssssssesirssesrrsstrrsssttrrssttnnssttnnsstennssrtnnnnt 18 2 2 4 Contiguring the Projeti sroiissiieseanana areni Aa al eel dieser ents 19 2 2 4 1 Adding or removing a File from the Project 0 ccceeeeceeeeeeeneeeeeeeneeeeeeeeeeeeentaeeeeeeaas 19 2 2 4 2 Setting the C Compiler Options ccccccccceeeeseceeeeeeeeeceeceeeeeeeeeeeeseccueaeeeeeeeeetenaeas 21 2 2 4 3 Transferring the Compiled Program to the AVR Chip after Make n e 27 2 2 4 4 Running an User Specified Program after Make ecceeeeeeeeeeeeeeeeeeeeenaeeeeeennaeeeeeeaas 29 2 2 5 Obtaining an Executable Program cccceccccceeeeeeeeeeeeeeeeeeeenneeeeeeeeeeeeeneeeeeeneeeeeenaeeeeeeaas 31 2 2 5 1 Compiling the Project x icc Gh ani aie Bn eleva 31 2 2 0 2 Making the Projecto ar den eteete E A baad tegen oo E cadens eee 33 226 GCIOSING a PIO OChisrececei checescti toced E stoeek fends EEE bhicenet Latieadl sheets 37 2S TOONS Anite eee ne Dee ee a 38 2a t ThREAVR Studio Debuggen aiena aa A a A east E AA aA TANARA 38 2 3 2 The AVR Chip Programme o eiserniieiriiirine inii ininda rine eien E Eei ia in Ae Ere EREE E 39 2 3 3 The Serial Communication Terminal seeseesssseessrrsssernnirsnnesesnnsetenassteanaatenanesetnnaatenanetennaaa 43 2 3 4 Executing User Programs xerci aa E E E R 44 1998 2003 HP InfoTech S R L Page 2 CodeVisionAVR 2 3 4 1 Configuring the Tools Me
143. ot specifically initialized static variables are automatically set to 0 at program startup Variables that are declared in other files must be preceded by the extern keyword Example extern int xyz now include the file which contains the variable xyz definition include lt file xyz h gt To instruct the compiler to allocate a variable to registers the register modifier must be used Example register int abc The compiler may automatically allocate a variable to registers even if this modifier is not used The volatile modifier must be used in order to prevent a variable to be allocated to registers and to warn the compiler that it may be subject to outside change during evaluation Example volatile int abc All the global variables not allocated to registers are stored in the Global Variables area of SRAM All the local variables not allocated to registers are stored in dynamically allocated space in the Data Stack area of SRAM 1998 2003 HP InfoTech S R L Page 67 CodeVisionAVR 3 7 1 Specifying the SRAM Storage Address for Global Variables Global variables can be stored at specific SRAM locations at design time using the operator Example the integer variable a is stored in SRAM at address 80h int a 0x80 the structure alfa is stored in SRAM at address 90h struct x int a char c alfa 0x90 3 7 2 Bit Variables The bit variables are special global variables loc
144. ou Close the Project or Quit the CodeVisionAVR program 1998 2003 HP InfoTech S R L Page 18 CodeVisionAVR 2 2 4 Configuring the Project The Project can be configured using the Project Configure menu command or the Project Configure toolbar button 2 2 4 1 Adding or removing a File from the Project To add or remove a file from the currently opened project you must use the Project Configure menu command A Configure Project tabbed dialog window will open You must select the Files tab Configure Project Multfile_prj Files C Compiler After Make a H C cvavre Examples Multfile Multile prj D mainfile c D filet c D file2 c D file3 c X Cancel Help By pressing the Add button you can add a source file to the project The first file added to the project is the main project file This file will always be Make ed The rest of the files added to the project will be automatically linked to the main project file on Make 1998 2003 HP InfoTech S R L Page 19 CodeVisionAVR Multiple files can be added by holding the Ctrl key when selecting in the Add File to Project dialog Add File To Project HEI Fieneme fiesc e2 eet Files of type Ic Compiler files c Cancel When the project is Open ed all project files will be opened in the editor By clicking on a file and then pressing the Remove button you will remove this file from the project Changes can be saved
145. outputted to the right of the decimal point The precision specifier has no effect on the c conversion type character 1998 2003 HP InfoTech S R L Page 100 CodeVisionAVR The optional l input size modifier specifies that the function argument must be treated as a long int for the i d u x X conversion type characters The type_char conversion type character is used to specify the way the function argument will be treated The following conversion type characters are supported i the function argument is a signed decimal integer d the function argument is a signed decimal integer u the function argument is an unsigned decimal integer e the function argument is a float that will be outputted using the d ddddd e dd format E the function argument is a float that will be outputted using the d ddddd E dd format f the function argument is a float that will be outputted using the ddd ddddd format X the function argument is an unsigned hexadecimal integer that will be outputted with lowercase characters X the function argument is an unsigned hexadecimal integer that will be outputted with with uppercase characters c the function argument is a single character s the function argument is a pointer to a null terminated char string located in SRAM p the function argument is a pointer to a null terminated char string located in FLASH the
146. ox appears in which you must select File Type Source and press the Ok button b Create New File x File Type Source Project X Cancel A new editor window appears for the newly created file The new file has the name untitled c You can save this file under a new name using the File Save As menu command 1998 2003 HP InfoTech S R L Page 8 CodeVisionAVR 2 1 2 Opening an Existing File You can open an existing file using the File Open menu command or by pressing the Open file button on the toolbar An Open dialog window appears Open 21x Lookin amp Ds1820 J amp Al l 0s1820 File name Ds1 620 Files of type Ic Compiler files c h You must select the name and type of file you wish to open By pressing the Open button you will open the file in a new editor window 2 1 3 Files History The CodeVisionAVR IDE keeps a history of the opened files The most recent eight files that where used can be reopened using the File Reopen menu command 1998 2003 HP InfoTech S R L Page 9 CodeVisionAVR 2 1 4 Editing a File A previously opened or a newly created file can be edited in the editor window by using the Tab Arrows Backspace and Delete keys Pressing the Home key moves the cursor to the start of the current text line Pressing the End key moves the cursor to the end of the current text line Pressing the Ctrl Home keys moves the cursor to the start of the file
147. pecifies the initial value of timer counter 3 at startup e Comp A B and C specifies the initial value of timer counter 3 output compare registers A B and C If timer counter 1 interrupts are used the following interrupt service routines may be defined by the CodeWizardAVR e timer1_ovf_isr for timer counter overflow e timer1_comp_isr or timer1_compa_isr timer1_compb_isr and timer1_copmc_isr for timer counter output compare match e timer1_capt_isr for timer counter input capture You must note that depending of the used AVR chip some of these options may not be present For more information you must consult the corresponding Atmel data sheet 1998 2003 HP InfoTech S R L Page 170 CodeVisionAVR By selecting the Watchdog tab you can configure the watchdog timer amp CodeWizardAVR untitled cwp x Eile Help Analog Comparator ADC SPI 12C 1Wie 2Wire 2c LcD Bit Banged Project Information Chip ExternalSRAM Pors External IRQ Timers USARTO USARTI Timer 2 Timer3 Watchdog 4 gt Receecessenvenssnseeseeconcssesnee M Watchdog Timer Enabled Oscillator Prescaler OSC 1E C OSC 256 C OSC 32 OSC 512 C Osc 64 C 050 1024 C 05C 128 C OSC 2048 Checking the Watchdog Timer Enabled check box activates the watchdog timer You will have then the possibility to set the watchdog timer s Oscillator Prescaller In case the watchdog timer is enabled yo
148. ple char will be unsigned by default pragma uchart char will be signed by default pragma uchar This option can also be specified in the Project Configure C Compiler Code Generation char is unsigned menu The pragma library directive is used for specifying the necessity to compile link a specific library file Example pragma library mylib lib The pragma glbdef directive is used for compatibility with projects created with versions of CodeVisionAVR prior to V1 0 2 2 where the Project Configure C Compiler Global define option was enabled It signals the compiler that macros are globally visible in all the program modules of a project This directive must be placed in beginning of the first source file of the project By default this directive is not active so macros are visible only in the program module where they are defined 1998 2003 HP InfoTech S R L Page 61 CodeVisionAVR 3 2 Comments The character string marks the beginning of a comment The end of the comment is marked with Example This is a comment This is a multiple line comment One line comments may be also defined by using the string Example This is also a comment Nested comments are not allowed 1998 2003 HP InfoTech S R L Page 62 CodeVisionAVR 3 3 Reserved Keywords Following is a list of keywords reserved by the compiler These can not be used as identifier names
149. plied by 10 Example how to display the temperature of two DS1621 sensors with addresses 0 and 1 the DS1621 I C bus is connected to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ 1i2c port 0x18 equ _ sda bit 3 equ scl bit 4 endasm include the DS1621 Functions include lt ds1621 h gt the LCD module is connected to PORTC asm equ _ lcd port 0x15 endasm include the LCD Functions include lt lcd h gt include the prototype for sprintf include lt stdio h gt include the prototype for abs include lt math h gt EY char display buffer 33 void main void int 0 1 initialize the LCD 2 rows by 16 columns lcd_init 16 initialize the TO bus P26 ANTE initialize the DS1621 sensor with address 0 tlow 20 C thigh 25 C ds1621 init 0 20 25 0 initialize the DS1621 sensor with address 1 tlow 30 C thigh 35 C ds1621 init 1 30 35 0 1998 2003 HP InfoTech S R L Page 128 CodeVisionAVR temperature display loop while 1 read the temperature of DS1621 0 10 C t0 ds1621 temperature 10 0 read the temperature of DS1621 1 10 C tl ds1621 temperature 10 1 prepare the displayed temperatures in the display buffer sprintf display buffer t0 S i uScC ntl S i uScc t0 10 abs t0 10 Oxdf t1 10 abs
150. port 0x18 equ _ sda _ bit 3 equ scl bit 4 endasm include lt pcf8583 h gt void main void unsigned char h m s hs initialize the I C bus i2e init initialize the RTC 0 no dated alarm rtc_init 0 0 read time from RTC 0 rtc_get_ time 0 amp h amp m amp s amp hs void rtc_set_time unsigned char chip unsigned char hour unsigned char min unsigned char sec unsigned char hsec this function sets the current time of the RTC The hour min sec and hsec parameters represent the values of hour minutes seconds and hundreds of a second void rtc_get_date unsigned char chip unsigned char date unsigned char month unsigned year this function returns the current date measured by the RTC The date month and year pointers must point to the variables that must receive the values of day month and year void rtc_set_date unsigned char chip unsigned char date unsigned char month unsigned year this function sets the current date of the RTC void rtc_alarm_off unsigned char chip this function disables the RTC alarm function void rtc_alarm_on unsigned char chip this function enables the RTC alarm function 1998 2003 HP InfoTech S R L Page 134 CodeVisionAVR void rtc_get_alarm_time unsigned char chip unsigned char hour unsigned char min unsigned char sec unsigned char hsec this function returns the alarm time of the RTC The hour min sec and hsec
151. r printf S u DEVICE S DETECTED n r devices if no devices were detected then halt if devices 0 while 1 loop forever 1998 2003 HP InfoTech S R L Page 144 CodeVisionAVR set the temperature alarms for all the devices temp low 25 C temp high 35 C for i 0 i lt devices i t printf INITIALIZING DEVICE u itl if ds1820 set alarm amp rom_codes i 0 25 35 putsf OK else putsf ERROR he while 1 measure and display the temperature for i 0 i lt devices temp ds1820 temperature 10 amp rom_codes i 0 printf t u i u xf8C n r i temp 10 abs temp 310 display the number of devices which generated an alarm printf ALARM GENERATED BY u DEVICE S n r wl search 0xec alarm_rom_codes be Refer to the DS1820 DS18S20 data sheet for more information 1998 2003 HP InfoTech S R L Page 145 CodeVisionAVR 4 14 2 Dallas Semiconductor DS2430 EEPROM Functions These functions are intended for easy interfacing between C programs and the DS2430 1 Wire bus EEPROM The prototypes for these functions are placed in the file ds2430 h located in the INC subdirectory This file must be include ed before using the functions The 1 Wire bus functions prototypes are automatically include ed with the ds2430 h Prior to include ing t
152. r parl int par2 long par3 Write some statements here The old Kernighan amp Ritchie style of writing function definitions is not supported Function parameters are passed through the Data Stack Function values are returned in registers R30 R31 R22 and R23 from LSB to MSB 1998 2003 HP InfoTech S R L Page 79 CodeVisionAVR 3 12 Pointers Due to the Harvard architecture of the AVR microcontroller with separate address spaces for data SRAM program FLASH and EEPROM memory the compiler implements three types of pointers The syntax for pointer declaration is lt type storage modifier gt type lt pointer storage modifier gt pointer name or type lt type storage modifier gt lt pointer storage modifier gt pointer name where type can be any data type Variables placed in SRAM are accessed using normal pointers For accessing constants placed in FLASH memory the flash type storage modifier is used For accessing variables placed in EEPROM the eeprom type storage modifier is used Although the pointers may point to different memory areas they are by default stored in SRAM Example Pointer to a char string placed in SRAM char ptr_to_ram This string is placed in SRAM Pointer to a char string placed in FLASH flash char ptr to flashl This string is placed in FLASH char flash ptr to flash2 This string is also placed in FLASH Poin
153. rate the main C source and project PRJ files save the CodeWizardAVR project CWP file and return to the CodeVisionAVR IDE Eventual pin function conflicts will be prompted to the user allowing him to correct the errors In the course of program generation the user will be prompted for the name of the main C file Save C Compiler Source File 21x Save in GI Examples S A eX 3 Therm 5 Ds1820 CI Thermled File name test Save as type Ic Compiler files c Cancel 1998 2003 HP InfoTech S R L Page 158 CodeVisionAVR and for the name of the project file Save C Compiler Project File 21x Save in Examples al c C_asm 9 Therm 5 Ds1820 CI Thermiecd Eeprom Keypad Leddemo Led Maxl 241 Spi File name test Save as type Projectiles pri Selecting the File Exit menu option allows you to exit the CodeWizardAVR without generating any program files By selecting the Help menu option you can see the help topic that corresponds to the current CodeWizardAVR configuration menu 1998 2003 HP InfoTech S R L Page 159 CodeVisionAVR 5 1 Setting the AVR Chip Options By selecting the Chip tab of the CodeWizardAVR you can set the AVR chip options CodeWizardAVR untitled cwp File Help ExternalIRQ Timers UART Analog Comparator ADC SPI Jic 1 Wire LCD Bit Banged Project Information Chip ExtemalSRAM Pors Reccecosccec
154. requency Mode specifies if the timer counter 0 functioning mode Output specifies the function of the timer counter 0 output and depends of the functioning mode Overflow IRQ specifies if an interrupt is to be generated on timer counter 0 overflow Compare Match IRQ specifies if an interrupt is to be generated on timer counter 0 compare match e Timer Value specifies the initial value of timer counter O at startup e Compare specifies the initial value of timer counter 0 output compare register If timer counter 0 interrupts are used the following interrupt service routines may be defined by the CodeWizardAVR e timer0_ovf_isr for timer counter overflow e timer0_comp_isr for timer counter output compare match You must note that depending of the used AVR chip some of these options may not be present For more information you must consult the corresponding Atmel data sheet 1998 2003 HP InfoTech S R L Page 167 CodeVisionAVR amp CodeWizardAVR untitled cwp x File Help Analog Comparator ADC SPI 12C 1Wire 2Wire 2c Led BitBanged Project Information Chip ExemaiSRAM Pors ExtemaliRQ Timers USARTO USARTI I Timer2 Timer3 va gt Clock Source System Clock Clock Value Timer1 Stopped Mode Normal top FFFFh x Out A Discon Out B Discon Out c Discon Input Capt Noise Cancel Interrupt on I Timer 1 Overflow Value a h Comp A J0 h 6 0 h C
155. required The compiler issues warnings in these situations Example void main void unsigned char a 30 unsigned char b 128 unsigned int c This will generate an incorrect result because the multiplication is done on 8 bits producing an 8 bit result which overflows Only after the multiplication the 8 bit result is promoted to unsigned int c a b Here casting forces the multiplication to be done on 16 bits producing an 16 bit result without overflow c unsigned int a b 1998 2003 HP InfoTech S R L Page 77 CodeVisionAVR The compiler behaves differently for the following operators ae Nt oll gt R ll gt gt For these operators the result is to be written back onto the left hand side operand which must be a variable So the compiler will always convert the right hand side operand into the type of left hand side operand 3 10 Operators The compiler supports the following operators pen lt gt lt gt amp amp amp t lt lt gt gt 5 Orns amp A gt gt lt lt 1998 2003 HP InfoTech S R L Page 78 CodeVisionAVR 3 11 Functions You may use function prototypes to declare a function These declarations include information about the function parameters Example int alfa char parl int par2 long par3 The actual function definition may be written somewhere else as int alfa cha
156. ress addr 1 1998 2003 HP InfoTech S R L Page 115 CodeVisionAVR 4 11 LCD Functions 4 11 1 LCD Functions for displays with up to 2x40 characters The LCD Functions are intended for easy interfacing between C programs and alphanumeric LCD modules built with the Hitachi HD44780 chip or equivalent The prototypes for these functions are placed in the file Icd h located in the INC subdirectory This file must be include ed before using the functions Prior to include ing the Icd h file you must declare which microcontroller port is used for communication with the LCD module The following LCD formats are supported in Ied h 1x8 2x12 3x12 1x16 2x16 2x20 4x20 2x24 and 2x40 characters Example the LCD module is connected to PORTC asm equ _ lcd port 0x15 endasm now you can include the LCD Functions include lt lcd h gt The LCD module must be connected to the port bits as follows LCD AVR Port RS pin4 bit 0 bit 5 0 jee O ann D xvn i D O You must also connect the LCD power supply and contrast control voltage according to the data sheet The low level LCD Functions are void _Icd_ready void waits until the LCD module is ready to receive data This function must be called prior to writing data to the LCD with the _Icd_write_data function void _Icd_write_data unsigned char data writes the byte data to the LCD instruction register
157. returns the hyperbolic sine of the floating point number x where the angle is expressed in radians float cosh float x returns the hyperbolic cosine of the floating point number x where the angle is expressed in radians float tanh float x returns the hyperbolic tangent of the floating point number x where the angle is expressed in radians float asin float x returns the arc sine of the floating point number x in the range PI 2 to PI 2 x must be in the range 1 to 1 float acos float x returns the arc cosine of the floating point number x in the range 0 to Pl x must be in the range 1 to 1 float atan float x returns the arc tangent of the floating point number x in the range PI 2 to PI 2 float atan2 float y float x returns the arc tangent of the floating point numbers y x in the range PI to Pl 1998 2003 HP InfoTech S R L Page 106 CodeVisionAVR 4 5 String Functions The prototypes for these functions are placed in the file string h located in the INC subdirectory This file must be include ed before using the functions The string manipulation functions were extended to handle strings located both in SRAM and FLASH memories char strceat char str1 char str2 concatenate the string str2 to the end of the string str1 char strcatf char str1 char flash str2 concatenate the string str2 located in FLASH to the end of the string str1 char strncat char str1 char str2
158. riven mode you can specify the size of the circular buffer using the Transmitter Buffer spinedit box The communication Baud rate can be specified using the UART Baud Rate list box CodeWizardAVR will automatically set the UBRR according to the Baud rate and AVR chip clock frequency The Baud rate error for these parameters will be calculated and displayed The Communications Parameters list box allows you to specify the number of data bits stop bits and parity used for serial communication 1998 2003 HP InfoTech S R L Page 172 CodeVisionAVR For devices featuring an USART there will be an additional Mode list box amp CodeWizardAVR untitled cwp x 1Wire 2Wire 2c LCD Bit Banged Project Information Chip Pors ExtemaliRQ Timers grreeeeeesoesoeescesoeeseeseseeeseesg USART Analog Comparator ADC Enesocssesoensossssosssnsessesosesond V Receiver V Rx Interrupt Receiver Buffer fe vA M Transmitter M Tx Interrupt Transmitter Buffer fe ZA Baud rate 9600 vit x2 Baud Rate Error 0 2 Communication Parameters E Data 1 Stop No Parity Mode Asynchronous It allows you to specify the following communication modes e Asynchronous Synchronous Master with the UCSRC register s UCPOL bit set to 0 Synchronous Master with the UCSRC register s UCPOL bit set to 1 Synchronous Slave with the UCSRC register s UCPOL bit set to 0 Synchronous Slave with the UCSRC reg
159. rminal The Terminal is intended for debugging embedded systems which employ serial communication RS232 RS422 RS485 The Terminal is invoked using the Tools Terminal menu command or the Terminal button on the toolbar Terminal Jor x Hex Code Send BxFile IxFile Hex Clear GReset Chip a Z a Po COM2 9600 8N1 Nohandsh ASCII TTY Echo on yy The characters can be displayed in ASCII or hexadecimal format The display mode can be toggled using the Hex ASCII button The received characters can be saved to a file using the Rx File button Any characters typed in the Terminal window will be transmitted through the PC serial port The entered characters can be deleted using the Backspace key By pressing the Send button the Terminal will transmit a character whose hexadecimal ASCII code value is specified in the Hex Code edit box By pressing the Tx File button the contents of a file can be transmitted through the serial port By pressing the Reset button the AVR chip on the STK200 300 VTEC ISP DT006 ATCPU or Mega2000 development board is reseted At the bottom of the Terminal window there is a status bar in which are displayed the computer s communication port communication parameters handshaking mode received characters display mode type of emulated terminal the state of the transmitted characters echo setting 1998 2003 HP InfoTech S R L Page 43 CodeVisionAVR 2
160. rogram If the Project Configure C Compiler Code Generation Automatic Register Allocation option is checked or the pragma regalloc compiler directive is used the rest of registers in the R2 to R14 range that aren t used for bit variables are allocated to char and int global variables The allocation is realized in order of variable declaration until the R14 register is allocated If the automatic register allocation is disabled you can use the register keyword to specify which global variable to be allocated to registers Example disable automatic register allocation pragma regalloc allocate the variable alfa to a register register int alfa allocate the variable beta to the register pair R10 R11 register int beta 10 The char and int local variables are automatically allocated in order of declaration to registers R16 up to R21 1998 2003 HP InfoTech S R L Page 69 CodeVisionAVR 3 7 4 Structures Structures are user defined collections of named members The structure members can be any of the supported data types arrays of these data types or pointers to them Structures are defined using the struct reserved keyword The syntax is lt storage modifier gt struct lt structure tag name gt lt type gt lt variable name gt lt variable name gt lt type gt lt bitfield id gt lt width gt lt bitfield id gt lt width gt lt structur
161. rohibit after sale license agreements or limited disclaimers you must cease and desist using this product immediately This product is Copyright 1998 2003 by Pavel Haiduc and HP InfoTech S R L all rights reserved International copyright laws international treaties and all other applicable national or international laws protect this product This software product and documentation may not in whole or in part be copied photocopied translated or reduced to any electronic medium or machine readable form without prior consent in writing from HP InfoTech S R L and according to all applicable laws The sole owners of this product are Pavel Haiduc and HP InfoTech S R L 6 2 Liability Disclaimer This product and or license is provided as is without any representation or warranty of any kind either express or implied including without limitation any representations or endorsements regarding the use of the results of or performance of the product its appropriateness accuracy reliability or correctness The user and or licensee assume the entire risk as to the use of this product Pavel Haiduc and HP InfoTech S R L do not assume liability for the use of this program beyond the original purchase price of the software In no event will Pavel Haiduc or HP InfoTech S R L be liable for additional direct or indirect damages including any lost profits lost savings or other incidental or consequential damages arising from any defects or
162. rom the string set located in FLASH If there is a match returns a pointer to the character in str If there are no matching characters returns a NULL pointer char strstr char str1 char str2 searches the string str1 for the first occurrence of the string str2 If there is a match returns a pointer to the character in str1 where str2 begins If there is no match returns a NULL pointer char strstrf char str1 char flash str2 searches the string str1 located in SRAM for the first occurrence of the string str2 located in FLASH If there is a match returns a pointer to the character in str1 where str2 begins If there is no match returns a NULL pointer char strtok char str1 char flash str2 scans the string str1 located in SRAM for the first token not contained in the string str2 located in FLASH The function considers the string str1 as consisting of a sequence of text tokens separated by spans of one or more characters from the string str2 The first call to strtok with the pointer to str1 being different from NULL returns a pointer to the first character of the first token in str1 Also a NULL character will be written in str1 immediately after the returned token Subsequent calls to strtok with NULL as the first parameter will work through the string str1 until no more tokens remain When there are no more tokens strtok will return a NULL pointer unsigned char strlen char str for the TINY memory mo
163. rs to the variables placed in SRAM In this memory model you can only have access to the first 256 bytes of SRAM The SMALL memory model uses 16 bits for storing pointers the variables placed in SRAM In this memory model you can have access to 65536 bytes of SRAM For improving program speed and size you must always try to use the TINY memory model Pointers to the FLASH and EEPROM memory areas always use 16 bits 1998 2003 HP InfoTech S R L Page 80 CodeVisionAVR Because pointers to the FLASH memory are 16 bits wide the total size of the constant arrays and char strings can t exceed 64K for the ATmega103 or ATmega128 However the total size of the program can be 128K for these chips Pointers can be grouped in arrays which can have up to 8 dimensions Example Declare and initialize a global array of pointers to strings placed in SRAM char strings 3 One Two Three Declare and initialize a global array of pointers to strings placed in FLASH The pointer array itself is also stored in FLASH flash char flash messages 3 Message 1 Message 2 Message 3 T EPROM Declare some strings in eeprom char m1 aaaa eeprom char m2 bbbb void main void Declare a local array of pointers to the strings placed in EEPROM You must note that although the strings are located in EEPROM the pointer array itself is located in SRAM char eeprom pp 2
164. rst 8 bytes contain the ROM code and CRC unsigned char rom_codes MAX DEVICES 9 main unsigned char i j devices int temp initialize the UART s baud rate UBRR xtal 16 baud 1 initialize the UART control register TX enabled no interrupts 8 data bits UCR 8 detect how many DS1820 DS18S20 devices are connected to the bus and store their ROM codes in the rom_codes array devices wl search 0xf0 rom codes display the number printf S u DEVICE S DETECTED n r devices if no devices were detected then halt if devices 0 while 1 loop forever measure and display the temperature s while 1 for 1 0 i lt devices temp ds1820 temperature 10 amp rom_codes i 0 printf t u S i u xf8C n r i temp 10 abs temp 310 e unsigned char ds1820_set_alarm unsigned char addr signed char temp_low signed char temp_high this function sets the low temp_low and high temp_high temperature alarms of the DS1820 DS18820 In case of success the function returns the value 1 else it returns 0 The alarm temperatures are stored in both the DS1820 DS18S20 s scratchpad SRAM and its EEPROM The ROM code needed to address the device is stored in an array of 8 bytes located at address addr If only one DS1820 DS18S20 sensor is used no ROM code array is necessary and the pointer addr must be NULL 0 199
165. rvice routine that will be executed upon the overflow of the USI Counter If the USI Start Condition Interrupt check box is checked then the CodeWizardAVR will generate code for an interrupt service routine that will be executed when a Start Condition is detected on the I2C bus in USI Two Wire operating mode 1998 2003 HP InfoTech S R L Page 181 CodeVisionAVR 5 11 Setting the I C Bus By selecting the I7C tab of the CodeWizardAVR you can specify the I C bus configuration File Help External IRQ Timers USARTO USART1 1Wire 2Wire 2c Led BitBanged Project Information Chip ExtemalSRAM Pors Pa Analog Comparator aDC SPI 2C Port PORTA SDA Bit 0 SCLBit 1 gt LM75_ ps1621 Pcrese3 al gt I Enabled Using the I C Port list box you can specify which port is used for the implementation of the I7C bus The SDA Bit and SCL Bit list boxes allow you to specify which port bits the IC bus uses 1998 2003 HP InfoTech S R L Page 182 CodeVisionAVR 5 11 1 Setting the LM75 devices If you use the LM75 temperature sensor you must select the LM75 tab and check the LM75 Enabled check box amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USARTI 1Wire 2Wire 2c Lcd BitBanged Project Information Chip External SRAM Ports Analog Comparator ADC SPI l2C l2C Port PORTA SDA Bit 0 SCL Bit fi
166. s 57 3 1 Th Preprocessor as is cciteeecanitanleieaniniie A e E E A aa a eae Ea 57 3 2 COMIMEMNMS aaea EEE NAN EI A N OARE R 62 3 3 RESEMVEd KE WOI S eaea Ea EAE E EEE EA 63 SEE E e EE EIE IE EEEE EE E EE EENS P ETNE E ET EAA ee 64 39 Data TYPES oaan Seer ire a a a es ii S 64 SATEEN D E E E T E E ie ee aed 65 Sif E E EE E E Wasted ET A T E E E E 66 3 7 1 Specifying the SRAM Storage Address for Global Variables cccceeeeeeeeesteeeeeeeees 68 3 f 2 Bit Va abloS aeee ane eadarra aves Wl Aa A even died And DEE debe end EA ASEE ENEN 68 3 7 3 Allocation of Variables to RegisterSs eesssseesseerrsserrssttrrtttttrresttrnssttnnssttnnstetnnsstennnnetna 69 3 TA SUCIOS iion wean eater iain ei a E ee eed 70 SECS UMIONS EA E EAE A AE TEA N AIT E N A OE EA EA 73 3 7 O EMUMEFAUOMNS oii era e EE O EEA 75 3 7 7 Global Variables Memory Map File ccccceceeeeeeeeeeeneeeeeeeaeeeeeeaeeeeeenaeeeeeeecaeeeseeneeeeeeaas 76 3 8 Defining Data Ty peSic3 sncirnt ete ci ie a ee i ea ie ied 76 3 9 Type Conversions yi02 cat ute a a Ged ed 77 DVO OPC ALORS janet ET ceca Sites Asia sachet ae Send TE E TEE se cetheasackeiet ae toanea 78 Se TA RUNCONS roie oera hehe ppale abhi E oka ppbldehed eacose a A E 79 3 12 PONES A heehee Anaad esivaei ai Andes et eid aes 80 1998 2003 HP InfoTech S R L Page 3 CodeVisionAVR 3 13 Accessing the VO Registers ccccsssssssssssssusssssesssususssssssssussssssssssssssssssssussssssssssnsusnsse
167. s size 0 byte s Data Stack area 60h to DFh Data Stack size 128 byte s Estimated Data Stack usage 30 byte s Global variables area E0h to 155h Global variables size 118 byte s Hardware Stack area 156h to 25Fh Hardware Stack size 266 byte s 1998 2003 HP InfoTech S R L Page 31 CodeVisionAVR Eventual compilation errors and or warnings will be listed in the Message window located under the Editor window or in the Navigator window Waring C CVAYVRYEXAMPLES DS1820 ds1620 cf1 28 global symbol ds1620_set_alarm declared but never used By double clicking on the error or warning message the line with the problem will be highlighted The size of the Message window can be modified using the horizontal slider bar placed between it and the Editor window 1998 2003 HP InfoTech S R L Page 32 CodeVisionAVR 2 2 5 2 Making the Project To make the Project you must use the Project Make menu command press the Shift F9 keys or press the Make button of the toolbar The CodeVisionAVR C Compiler will be executed producing an assembler source file with the asm extension The rest of the files added to the project will be automatically linked to the main project file Eventual compilation errors and or warnings will be listed in the Message window located under the Editor window or in the Navigator window Waring C CVAVRYEXAMPLES DS1620 ds1620 cf128 global symbol ds1620_set_alarm declared
168. s the first function that must be called before using the other high level LCD Functions void Icd_clear void clears the LCD and sets the printing character position at row 0 and column 0 void Icd_gotoxy unsigned char x unsigned char y sets the current display position at column x and row y The row and column numbering starts from 0 1998 2003 HP InfoTech S R L Page 122 CodeVisionAVR void Icd_putchar char c displays the character c at the current display position void Icd_puts char str displays at the current display position the string str located in SRAM void Icd_putsf char flash str displays at the current display position the string str located in FLASH 4 12 C Bus Functions The I C Functions are intended for easy interfacing between C programs and various peripherals using the Philips I C bus These functions treat the microcontroller as a bus master and the peripherals as slaves The prototypes for these functions are placed in the file i2c h located in the INC subdirectory This file must be include ed before using the functions Prior to include ing the i2c h file you must declare which microcontroller port and port bits are used for communication through the C bus Example the I C bus is connected to PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm equ _ i2c port 0x18 equ _ sda bit 3 equ scl bit 4 endasm now you can include the I C Fun
169. se the Program Fuse Bit s respectively Program Lock Bits menu commands The Program All menu command allows to automatically e Erase the chip FLASH and EEPROM blank check Program and verify the FLASH Program and verify the EEPROM Program the Fuse and Lock Bits If you wish to read the contents of the chip s FLASH respectively EEPROM you must use the Read FLASH respectively Read EEPROM menu commands For reading the chip s signature you must use the Read Chip Signature menu command To read the Lock respectively the Fuse Bits you must use the Read Lock Bits respectively Read Fuse Bits menu commands For some devices there s also the Read Calibration Byte s option available It allows reading the value of the calibration bytes of the chip s internal RC oscillator 1998 2003 HP InfoTech S R L Page 41 CodeVisionAVR If the programmer is an Atmel STK500 or AVRISP then an additional menu command is present Read Programmer s Firmware Version It allows reading the major and minor versions of the STKSOO AVRISP programmer s firmware For comparing the contents of the chip s FLASH respectively EEPROM with the corresponding memory buffer you must use the Compare FLASH respectively Compare EEPROM menu commands For exiting the Programmer and returning to the CodeVisionAVR IDE you must use the File Close menu command 1998 2003 HP InfoTech S R L Page 42 CodeVisionAVR 2 3 3 The Serial Communication Te
170. searches the string str for the first occurrence of a character from the string set If there is a match returns the index of the character in str If there are no matching characters returns the length of str unsigned char strespnf char str char flash set searches the string str for the first occurrence of a character from the string set located in FLASH If there is a match returns the index of the character in str If there are no matching characters returns the length of str char strpbrk char str char set searches the string str for the first occurrence of a char from the string set If there is a match returns a pointer to the character in str If there are no matching characters returns a NULL pointer 1998 2003 HP InfoTech S R L Page 108 CodeVisionAVR char strpbrkf char str char flash set searches the string str located in SRAM for the first occurrence of a char from the string set located in FLASH If there is a match returns a pointer to the character in str If there are no matching characters returns a NULL pointer char strrpbrk char str char set searches the string str for the last occurrence of a character from the string set If there is a match returns a pointer to the character in str If there are no matching characters returns a NULL pointer char strrpbrkf char str char flash set searches the string str located in SRAM for the last occurrence of a character f
171. sionAVR include lt ds1307 h gt void main void unsigned char h m s initialize the I C bus L26 Angee ys initialize the DS1307 RTC rtc_init 0 0 0 read time from the DS1307 RTC rtc_get_ time amp h amp m amp s void rtc_set_time unsigned char hour unsigned char min unsigned char sec this function sets the current time of the RTC The hour min and sec parameters represent the values of hour minutes and seconds void rtc_get_date unsigned char date unsigned char month unsigned char year this function returns the current date measured by the RTC The date month and year pointers must point to the variables that must receive the values of date month and year void rtc_set_date unsigned char date unsigned char month unsigned char year this function sets the current date of the RTC 1998 2003 HP InfoTech S R L Page 137 CodeVisionAVR 4 13 Dallas Semiconductor DS1302 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the DS1302 real time clock RTC The prototypes for these functions are placed in the file ds1302 h located in the INC subdirectory This file must be include ed before using the functions Prior to include ing the ds1302 h file you must declare which microcontroller port and port bits are used for communication with the DS1302 Example the DS1302 is connected to PORTB the IO sig
172. so displayed in the Navigator window By clicking on the error or warning the corresponding source line is highlighted in the appropriate file The Navigator tree branches can be expanded respectively collapsed by clicking on the respectively buttons By right clicking in the Navigator window you can open a pop up menu with the following choices Open a file Save the currently edited file Save All opened files Close Current File Close Project Close All opened files Toggle on or off expanding the file branches Toggle on or off expanding the Errors and Warnings branches for the file whose Editor window has focus 1998 2003 HP InfoTech S R L Page 14 CodeVisionAVR 2 2 Working with Projects The Project groups the source file s and compiler settings that you use for building a particular program 2 2 1 Creating a New Project You can create a new Project using the File New menu command or by pressing the Create new file button on the toolbar A dialog box appears in which you must select File Type Project and press the OK button b Create New File x File Type C Source J Project X Cancel A dialog will open asking you to confirm if you would like to use the CodeWizardAVR to create the new project C You are aboutto create a new project Do you want to use the CodeWizardAVR If you select No then the Create New Project dialog window will open 1998 2003 HP InfoTec
173. t list box allows you to specify which port bit the 1 Wire bus uses 1998 2003 HP InfoTech S R L Page 189 CodeVisionAVR If you use the DS1820 DS18S20 temperature sensors you must check the DS1820 DS18S20 Enabled check box amp CodeWizardAVR untitled cwp x Eile Help External IRQ Timers USARTO USARTI Bit Banged Project Information Chip ExtermalSRAM Ports Analog Comparator ADC SPI l2c ie re Recenscessnsseesecsnsesssenssnseessseeneed 1 Wire Port PORTB Data Bit fo D51820 D51 Be E M Enabled I Multiple Devices Seite If you use several DS1820 DS18S20 devices connected to the 1 Wire bus you must check the Multiple Devices check box Maximum 8 DS1820 DS18S20 devices can be connected to the bus The ROM codes for these devices will be stored in the ds1820_rom_codes array The DS1820 DS18S20 devices can be accessed using the Dallas Semiconductor DS1820 DS18S20 Temperature Sensors Functions 1998 2003 HP InfoTech S R L Page 190 CodeVisionAVR 5 13 Setting the 2 Wire Bus By selecting the 2 Wire I C tab of the CodeWizardAVR you can specify the 2 Wire bus interface configuration amp CodeWizardAVR untitled cwp x File Help External IRQ Timers USARTO USARTI BitBanged Project Information Chip ExtemalSRAM Pors Analog Comparator ADC SPI l2C 1 Wire LCD lV 2 Wire E
174. t on Falling Output Edge C Interrupt on Rising Output Edge M Disable Digital Input Buffer on AINO M Disable Digital Input Buffer on AINT Checking the Analog Comparator Enabled check box enables the on chip analog comparator Checking the Bandgap Voltage Reference check box will connect an internal voltage reference to the analog comparator s positive input Checking the Input Multiplexer check box will connect the ADCs analog multiplexer to the analog comparator s negative input If you want to generate interrupts if the analog comparator s output changes state then you must check the Analog Comparator Interrupt check box The type of output change that triggers the interrupt can be specified in the Analog Comparator Interrupt Mode settings If the analog comparator s output is to be used for capturing the state of timer counter 1 then the Analog Comparator Input Capture check box must be checked The Disable Digital Input Buffer on AINO respectively Disable Digital Input Buffer on AIN1 check boxes if checked will deactivate the digital input buffers on the AINO respectively AIN1 pins thus reducing the power consumption of the chip The corresponding bits in the PIN registers will always read 0 in this case Some of this check boxes may not be present on all the AVR chips If the analog comparator interrupt is enabled the CodeWizardAVR will define the ana_comp_isr interrupt service routine 1998 2003 HP InfoTech S R L P
175. t returns 1 if successful O if not The DS2433 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode 1998 2003 HP InfoTech S R L Page 149 CodeVisionAVR If only one DS2433 EEPROM is used no ROM code array is necessary and the pointer romcode must be NULL 0 If several 1 Wire device are used then the program must first identify the ROM codes for all the devices Only after that the DS2433 functions may be used with the romcode pointer pointing to the array which holds the ROM code for the needed device Example specify the port and bit used for the 1 Wire bus The DS2433 devices are connected to bit 6 of PORTA of the AT90S8515 as follows DS2433 STK200 PORTA HEADER 1 GND 9 GND 2 DATA or 7 PA6 All the devices must be connected in parallel AN 4 7k PULLUP RESISTOR MUST BE CONNECTED BETWEEN DATA PA6 AND 5V as asm equ _ wl port 0xlb equ _ wl bit 6 endasm test the DS2433 functions include lt ds2433 h gt include lt 90s8515 h gt include lt stdio h gt DS2433 devices ROM code storage area 9 bytes are used for each device see the wl_ search function description but only the first 8 bytes contain the ROM code and CRC define MAX DEVICES 8 unsigned char rom_code MAX DEVICES 9 char text This is a long text to be able to test writing across the scr
176. tates list boxes The MCUCR and EMCUCR registers in the startup initialization code are configured automatically according to these settings 1998 2003 HP InfoTech S R L Page 163 CodeVisionAVR 5 3 Setting the Input Output Ports By selecting the Ports tab of the CodeWizardAVR you can specify the input output Ports configuration 3 CodeWizardAVR untitled cwp xi File Help External IRQ Timers USARTO USART1 Analog Comparator ADC SPI l2c 1Wire 2Wire 2c cDo BitBanged Projectinformation Chip External SRAM PortA PornB Porte Poro F4 gt Data Direction Pullup Output Value BitO In BitO Bit In T Bit1 Bit2 In T Bit2 Bit3 In T Bit3 Bit4 In T Bit4 BitS In T Bits Bits In Bit6 Bit In Bit You can chose which port you want to configure by selecting the appropriate PORT x tab By clicking on the corresponding Data Direction bit you can set the chip pin to be output Out or input In The DDRx register will be initialized according to these settings By clicking on the corresponding Pullup Output Value bit you can set the following options e ifthe pin is an input it can be tri stated T or have an internal pull up P resistor connected to the positive power supply e if the pin is an output it s value can be initially set to 0 or 1 The PORTx register will be initialized according to these settings 1998 2003 HP InfoTech S R L Pa
177. ter to a char string placed in EEPROM eeprom char ptr_to_eeproml This string is placed in EEPROM char eeprom ptr_ to eeprom2 This string is also placed in EEPROM In order to store the pointer itself in other memory areas like FLASH or EEPROM the flash or eeprom pointer storage modifiers must be used as in the examples below Pointer stored in FLASH to a char string placed in SRAM char flash flash ptr to _ ram This string is placed in SRAM Pointer stored in FLASH to a char string placed in FLASH flash char flash flash _ptr_to_flash This string is placed in FLASH T Pointer stored in FLASH to a char string placed in EEPROM eeprom char flash eeprom ptr to eeprom This string is placed in EEPROM Pointer stored in EEPROM to a char s char eeprom eeprom ptr_to_ram This s ring placed in SRAM ring is placed in SRAM Pointer stored in EEPROM to a char string placed in FLASH flash char eeprom eeprom ptr _ to flash This string is placed in FLASH Pointer stored in EEPROM to a char string placed in EEPROM eeprom char eeprom eeprom ptr _to_eeprom This string is placed in EEPROM For improving the code efficiency two memory models are implemented The TINY memory model uses 8 bits for storing pointe
178. the AVR chip in the powersave mode Prior to using this function the sleep_enable function must be invoked to allow entering the low power consumption modes This mode is similar to the powerdown mode with some differences please consult the Atmel Data Sheet for the particular chip that you use void standby void this function puts the AVR chip in the standby mode Prior to using this function the sleep_enable function must be invoked to allow entering the low power consumption modes This mode is similar to the powerdown mode with the exception that the external clock oscillator keeps on running Consult the Atmel Data Sheet for the particular chip that you use in order to see if the standby mode is available for it 1998 2003 HP InfoTech S R L Page 155 CodeVisionAVR void extended_standby void this function puts the AVR chip in the extended standby mode Prior to using this function the sleep_enable function must be invoked to allow entering the low power consumption modes This mode is similar to the powersave mode with the exception that the external clock oscillator keeps on running Consult the Atmel Data Sheet for the particular chip that you use in order to see if the standby mode is available for it 4 17 Delay Functions These functions are intended for generating delays in C programs The prototypes for these functions are placed in the file delay h located in the INC subdirectory This file must be in
179. the program must first identify the ROM codes for all the devices Only after that the DS2430 functions may be used with the romcode pointer pointing to the array which holds the ROM code for the needed device Example specify the port and bit used for the 1 Wire bus The DS2430 devices are connected to bit 6 of PORTA of the AT90S8515 as follows DS2430 STK200 PORTA HEADER 1 GND 9 GND 2 DATA F 7 PA6 All the devices must be connected in parallel AN 4 7k PULLUP RESISTOR MUST BE CONNECTED BETWEEN DATA PA6 AND 5V ey asm equ _ wl port 0xlb equ _ wl bit 6 endasm test the DS2430 functions include lt ds2430 h gt include lt 90s8515 h gt include lt stdio h gt DS2430 devices ROM code storage area 9 bytes are used for each device see the wl search function description but only the first 8 bytes contain the ROM code and CRC define MAX DEVICES 8 unsigned char rom_code MAX DEVICES 9 1998 2003 HP InfoTech S R L Page 147 CodeVisionAVR char text J Hello world char buffer 32 define START ADDR 2 main unsigned char i devices init UART UCR 8 UBRR 25 Baud 9600 4MHz detect how many 1 Wire devices are present on the bus devices wl_ search 0xF0 amp rom_code 0 0 printf S u 1 Wire devices found n r devices for i 0 i lt devices i make sure to select only t
180. the use or inability to use these programs even if Pavel Haiduc or HP InfoTech S R L have been advised of the possibility of such damages 6 3 Restrictions You may not use copy modify translate or transfer the programs documentation or any copy except as expressly defined in this agreement You may not attempt to unlock or bypass any copy protection or authentication algorithm utilized by the program You may not remove or modify any copyright notice or the method by which it may be invoked 6 4 Operating License You have the non exclusive right to use any enclosed program only by a single person on a single computer at a time You may physically transfer the program from one computer to another provided that the program is used only by a single person on a single computer at a time In group projects where multiple persons will use the program you must purchase an individual license for each member of the group Use over a local area network within the same locale is permitted provided that only a single person on a single computer uses the program at a time Use over a wide area network outside the same locale is strictly prohibited under any and all circumstances 6 5 Back up and Transfer You may make one copy of the program solely for back up purposes as prescribed by international copyright laws You must reproduce and include the copyright notice on the back up copy You may transfer the product to another part
181. tively USARTO and USART1 The functions of configuration check and list boxes will be the same as described above The UARTO USARTO will use the normal putchar and getchar functions In case of interrupt driven buffered communication VARTO USARTO will use the following variables rx_buffer0 rx_wr_index0 rx_rd_index0 rx_counter0 rx_buffer_overflow0 tx_buffer0 tx_wr_index0 tx_rd_index0 tx_counter0 The UART1 USART1 will use the putchar1 and getchar1 functions In case of interrupt driven buffered communication VART1 USART1 will use the following variables rx_buffer1 rx_wr_index1 rx_rd_index1 rx_counter1 rx_buffer_overflow1 tx_buffer1 tx_wr_index1 tx_rd_index1 tx_counter1 All serial I O using functions declared in stdio h will be done using UARTO USARTO 1998 2003 HP InfoTech S R L Page 174 CodeVisionAVR 5 7 Setting the Analog Comparator By selecting the Analog Comparator tab of the CodeWizardAVR you can specify the analog comparator configuration CodeWizardAVR untitled cwp x Eile Help ADC sPi izc 1Wire Lco LCD Controller BitBanged Project Information Chip Ports External IRQ Timers Us USARTO M Analog Comparator Enabled M Bandgap Voltage Reference Input Multiplexer MV Analog Comparator Input Capture M Analog Comparator Output M Analog Comparator Interrupt Analog Comparator Interrupt Mode Interrupt on Output Toggle C Interrup
182. tory a User Program Settings Ea Program Directory and FileName fe Command Line Parameters Working Directory es Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP InfoTech S R L Page 30 CodeVisionAVR 2 2 5 Obtaining an Executable Program Obtaining an executable program requires the following steps 1 Compiling the Project s C source file using the CodeVisionAVR C Compiler and obtaining an assembler source file 2 Assembling the assembler source file using the Atmel AVR assembler AVRASM32 Compiling a File executes step 1 Making executes step 1 and 2 for the main project file 2 2 5 1 Compiling the Project To compile the Project you must use the Project Compile File menu command press the F9 key or press the Compile button of the toolbar The CodeVisionAVR C Compiler will be executed producing an assembler source file with the asm extension The assembly source file can be examined and modified by opening it with the Editor After the compilation an Information window will open showing the compilation results i Information Compiler Chip AT9058515 Memory model Small Optimize for Size s printf features int width Promote char to int No char is unsigned Yes 8 bit enums Yes Automatic register allacation On Use AYR Studio Terminal 70 No 2552 linefs compiled No errors No warnings Bit variable
183. u must include yourself the appropriate code sequences to reset it periodically Example asm wdr For more information about the watchdog timer you must consult the Atmel data sheet for the chip that you use 1998 2003 HP InfoTech S R L Page 171 CodeVisionAVR 5 6 Setting the UART or USART By selecting the UART tab of the CodeWizardAVR you can specify the UART configuration amp CodeWizardAVR untitled cwp x Eile Help Analog Comparator ADC SPI 12C 1 Wire LCD Bit Banged Project Information Chip External SRAM Ports ExtemallRQ Timers UART V Receiver M Rx Interrupt Receiver Buffer fe 7 M Transmitter M Tx Interrupt Transmitter Buffer fe 7 Baud rate 9600 Baud Rate Error 0 2 Communication Parameters fe Data 1 Stop No Parity Checking the Receiver check box activates the UART receiver The receiver can function in the following modes e polled the Rx Interrupt check box isn t checked e interrupt driven circular buffer the Rx Interrupt check box is checked In the interrupt driven mode you can specify the size of the circular buffer using the Receiver Buffer spinedit box Checking the Transmitter check box activates the UART transmitter The transmitter can function in the following modes e polled the Tx Interrupt check box isn t checked e interrupt driven circular buffer the Tx Interrupt check box is checked In the interrupt d
184. u wish to protect your program from copying you must select the corresponding option using the FLASH Lock Bits radio box If you wish to check the chip s signature before programming you must use the Check Signature option To speed up the programming process you can uncheck the Check Erasure check box In this case there will be no verification of the correctness of the FLASH erasure The Preserve EEPROM checkbox allows preserving the contents of the EEPROM during chip erasure To speed up the programming process you can uncheck the Verify check box In this case there will be no verification of the correctness of the FLASH and EEPROM programming Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2003 HP InfoTech S R L Page 28 CodeVisionAVR 2 2 4 4 Running an User Specified Program after Make This option is available if you select the After Make tab in the Project Configure window If you check the Execute User s Program option then a program that you have previously specified will be executed after the compilation assembly process 4 Configure Project Multfile prj Files CCompiler After Make Program the Chip M Execute User s Program N Program Settings 1998 2003 HP InfoTech S R L Page 29 CodeVisionAVR Using the Program Settings button you can modify the e Program Directory and File Name e Program Command Line Parameters e Program Working Direc
185. ue for the PCF8563 Control Status 2 register The pcef8563 h header file defines the following macros which allow the easy setting of the ctrl2 parameter e RTC_TIE_ON sets the Control Status 2 register bit TIE to 1 e RTC_AIE_ON sets the Control Status 2 register bit AIE to 1 e RTC_TP_ON sets the Control Status 2 register bit TI TP to 1 These macros can be combined using the operator in order to set more bits to 1 The clkout parameter specifies the initialization value for the PCF8563 CLKOUT Frequency register The pef8563 h header file defines the following macros which allow the easy setting of the clkout parameter e RTC_CLKOUT_OFF disables the generation of pulses on the PCF8563 CLKOUT output RTC_CLKOUT_1 generates 1Hz pulses on the PCF8563 CLKOUT output RTC_CLKOUT_32 generates 32Hz pulses on the PCF8563 CLKOUT output RTC_CLKOUT_1024 generates 1024Hz pulses on the PCF8563 CLKOUT output RTC_CLKOUT_32768 generates 32768Hz pulses on the PCF8563 CLKOUT output The timer_ctrl parameter specifies the initialization value for the PCF8563 Timer Control register The pcef8563 h header file defines the following macros which allow the easy setting of the timer_ctrl parameter e RTC_TIMER_OFF disables the PCF8563 Timer countdown e RTC_TIMER_CLK_1_60 sets the PCF8563 Timer countdown clock frequency to 1 60Hz e RTC_TIMER_CLK_1 sets the PCF8563 Timer countdown clock frequency to 1Hz e RTC_TIMER_CLK_64 sets the PCF8563 Timer countdown clock frequenc
186. uency of the pulses may be lower than specified If the 2 Wire Interrupt check box is checked the 2 Wire interface will generate interrupts These interrupts will be serviced by the twi_isr function 1998 2003 HP InfoTech S R L Page 191 CodeVisionAVR 5 14 Setting the ATmega169 LCD Controller By selecting the LCD Controller tab of the CodeWizardAVR you can specify the configuration of the LCD controller built in the ATmega169V L chips CodeWizardAVR untitled cwp x Eile Help USI USARTO Analog Comparator apc sPi ic 1Wire Lco BitBanged Project Information Chip Ports External IRQ Timers geeescesocossecossesososososcossesesosossesososcosoesesesoseocososocesssescoessesesososessessssosssossosesossosessossssessssssesesossssesessesosp M LCD Enabled I LCD Low Power Waveform I LCD Frame Complete Interrupt Duty Cycle fi f2 Bias 1 3 v Clock Source System v Frame Rate fso Hz Frame Rate Error 2 3 Used Seqments 5EG0 12 Contrast Control 260v The ATmega169V L on chip LCD controller can be enabled by checking the LCD Enabled check box By checking the LCD Low Power Waveform check box the low power waveform will be outputted on the LCD pins This allows reducing the power consumption of the LCD If the LCD Frame Complete Interrupt check box is checked the LCD controller will generate an interrupt at the beginning of a new frame In low power
187. unsigned char n concatenate maximum n characters of the string str2 to the end of the string str1 Returns a pointer to the string str1 char strncatf char str1 char flash str2 unsigned char n concatenate maximum n characters of the string str2 located in FLASH to the end of the string aoe a pointer to the string str1 char strchr char str char c returns a pointer to the first occurrence of the character c in the string str else a NULL pointer char strrchr char str char c returns a pointer to the last occurrence of the character c in the string str else a NULL pointer signed char strpos char str char c returns the index to first occurrence of the character c in the string str else 1 signed char strrpos char str char c returns the index to the last occurrence of the character c in the string str else 1 signed char stremp char str1 char str2 compares the string str1 with the string str2 Returns lt 0 0 gt 0 according to str1 lt str2 str1 str2 str1 gt str2 signed char strempf char str1 char flash str2 compares the string str1 located in SRAM with the string str2 located in FLASH Returns lt 0 0 gt 0 according to str1 lt str2 str1 str2 str1 gt str2 signed char strncmp char str1 char str2 unsigned char n compares at most n characters of the string str1 with the string str2 Returns lt 0 0 gt 0 according to str1 lt str2 str1 str2 str1 gt str2 1998 2003 HP In
188. upport period for the commercial version of CodeVisionAVR Light is six months The e mail support address is office hpinfotech ro 1998 2003 HP InfoTech S R L Page 198 CodeVisionAVR 8 Contact Information HP InfoTech S R L can be contacted at HP INFOTECH S R L STR LIVIU REBREANU 13A BL N20 SC B AP 58 SECTOR 3 BUCHAREST 746311 ROMANIA phone 40 213261875 fax 40 213261876 GSM 40 723469754 e mail office hpinfotech ro Internet http www hpinfotech ro 1998 2003 HP InfoTech S R L Page 199
189. ust first specify its location and file name using the Settings Debugger menu command Debugger Settings Ea Directory and Filename C Program Files Atmel AVR Tools AvrStudio4 AYRStudi i Debugger Atmel AVR Studio 4 gt The AVR Studio version must be specified in the Debugger list box Changes can be saved respectively canceled using the OK respectively Cancel buttons Pressing the Browse button opens a dialog window that allows selecting the debugger s directory and filename Debugger Directory and FileName eix Look in S AvrStudio4 amp l al c bin dll edit Resources Skins AVR Studio 4 File name AVRStudio i t Files of type Executables exe gt Cancel Zi 1998 2003 HP InfoTech S R L Page 49 CodeVisionAVR 2 4 5 AVR Chip Programmer Setup Using the Settings Programmer menu command you can select the type of the in system programmer that is used and the computer s port to which the programmer is connected The current version of CodeVisionAVR supports the following in system programmers Kanda Systems STK200 and STK300 Atmel STK500 Dontronics DT006 Vogel Elektronik VTEC ISP Futurlec JRAVR MicroTronics ATCPU and Mega2000 The STK200 STK300 DT006 VTEC ISP JRAVR ATCPU and Mega2000 in system programmers use the parallel printer port The following choices are available through the Printer Port radio group box e LPT1 at base address 378h e LPT2 at base
190. value that will be returned by setjmp after the call to longjmp If a 0 value is passed as the retval argument then it will be substituted with 1 In order to facilitate the usage of these functions the setjmp h header file also contains the definition of the jmp_buf data type which is used when declaring the env variables Example include lt 90s8515 h gt include lt stdio h gt include lt setjmp h gt declare the variable used to hold the CPU state jmp_buf cpu_state void foo void printf Now we will make a long jump to main n r longjmp cpu_state 1 void main void this local variable will be preserved after a longjmp volatile int i this local variable will not be preserved after a longjmp Ine J init the AT90S8515 UART UCR 8 Baud 9600 4MHz UBRR 25 1998 2003 HP InfoTech S R L Page 113 CodeVisionAVR if setjmp cpu_state 0 printf First call to setjmp n r foo else printf We jumped here from foo n r 4 8 BCD Conversion Functions The prototypes for these functions are placed in the file bed h located in the INC subdirectory This file must be include ed before using the functions unsigned char bcd2bin unsigned char n Converts the number n from BCD representation to it s binary equivalent unsigned char bin2bcd unsigned char n Converts the number n from binary representation to it s BCD equiva
191. void putsf char flash str outputs using putchar the null terminated character string str located in FLASH followed by a new line character void printf char flash fmtstr arg1 arg2 outputs formatted text using putchar according to the format specifiers in the fmtstr string The format specifier string fmtstr is constant and must be located in FLASH memory The implementation of printf is a reduced version of the standard C function This was necessary due to the specific needs of an embedded system and because the full implementation would require a large amount of FLASH memory space The format specifier string has the following structure flags width precision 1 type char The optional flags characters are left justifies the result padding on the right with spaces If it s not present the result will be right justified padded on the left with zeros or spaces signed conversion results will always begin with a or sign if the value isn t negative the conversion result will begin with a space If the value is negative then it will begin with a sign The optional width specifier sets the minimal width of an output value If the result of the conversion is wider than the field width the field will be expanded to accommodate the result so not to cause field truncation The following width specifiers are supported n at least n characters are outputted If the result has less than n
192. y only if the other party agrees to the terms and conditions of this agreement and completes and returns registration information name address etc to Pavel Haiduc and HP InfoTech S R L within 30 days of the transfer If you transfer the program you must at the same time transfer the documentation and back up copy or transfer the documentation and destroy the back up copy You may not retain any portion of the program in any form under any circumstance 1998 2003 HP InfoTech S R L Page 196 CodeVisionAVR 6 6 Terms This license is effective until terminated You may terminate it by destroying the program the documentation and copies thereof This license will also terminate if you fail to comply with any terms or conditions of this agreement You agree upon such termination to destroy all copies of the program and of the documentation or return them to Pavel Haiduc or HP InfoTech S R L for disposal Note that by registering this product you give Pavel Haiduc and HP InfoTech S R L permission to reference your name in product advertisements 6 7 Other Rights and Restrictions All other rights and restrictions not specifically granted in this license are reserved by Pavel Haiduc and HP InfoTech S R L 1998 2003 HP InfoTech S R L Page 197 CodeVisionAVR 7 Technical Support Registered users of the commercial version of CodeVisionAVR Standard get one year free technical support by e mail The free technical s
193. y to 64Hz e RTC_TIMER_CLK_4096 sets the PCF8563 Timer countdown clock frequency to 4096Hz Refer to the PCF8563 data sheet for more information 1998 2003 HP InfoTech S R L Page 130 CodeVisionAVR unsigned char rtc_read unsigned char address this function reads the byte stored in a PCF8563 register at address void rtc_write unsigned char address unsigned char data this function stores the byte data in the PCF8583 register at address unsigned char rtc_get_time unsigned char hour unsigned char min unsigned char sec this function returns the current time measured by the RTC The hour min and sec pointers must point to the variables that must receive the values of hour minutes and seconds The function return the value 1 if the read values are correct If the function returns 0 then the chip supply voltage has dropped below the Vlow value and the time values are incorrect Example asm equ _ i2c port 0x18 equ _ sda _ bit 3 equ scl bit 4 endasm include lt pcf8563 h gt void main void unsigned char ok h m s initialize the IC bus i2c init initialize the RTC Timer interrupt enabled Alarm interrupt enabled CLKOUT frequency 1Hz Timer clock frequency 1Hz rtc_init RTC_ TIE ON RTC_AIE ON RTC CLKOUT 1 RTC_TIMER CLK 1 read time from the RTC ok rtc_get_ time amp h amp m amp s void rtc_set_time unsigned char hour unsigned char min unsigned
Download Pdf Manuals
Related Search
Related Contents
PDF版カタログダウンロード:FL無線機 Philips Micro Hi-Fi System MCM138D Tecumseh AEA9415ZXCSS Technical Data Sheet Overture VDM-10 Tool Support: User Guide U100-0 U103-0 U100-S U103-S - Uni Princess Panini Grill Vérins EUROBAT + + ULTRAGLIDE EASYCORD Handbuch Copyright © All rights reserved.
Failed to retrieve file