Home
CodeVisionAVR User Manual - Sigma
Contents
1. Pointer 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 __ flash or eeprom __eeprom pointer storage memory attributes must be used as in the examples below Pointer stored in FLASH to a char string placed in RAM char flash flash _ptr_to_ram This string is placed in RAM Pointer stored in FLASH to a char string placed in FLASH flash char flash flash _ ptr to flash This string is placed in FLASH 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 string placed in RAM char eeprom eeprom ptr to ram This string is placed in RAM ct H 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 1998 2009 HP InfoTech S R L Page 108 CodeVisionAVR In order to improve the
2. Preprocessor Create Preprocessor Output Files V Include 1 0 Registers Bits Definitions 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 Maxim Dallas Semiconductor DS1820 DS18S20 DS18B20 Temperature Sensors Functions The required memory model can be selected by using the Memory Model list box 1998 2009 HP InfoTech S R L Page 39 CodeVisionAVR The compiled program can be optimized for minimum size respectively maximum execution speed using the Optimize for Size respectively Optimize for Speed settings The amount of code optimization can be specified using the Optimization Level setting The Maximal optimization level may make difficult the code debugging with AVR Studio 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 S Configure Project MULTFILEPR OOOO Files C Compiler Before Build After Build Code Generation Messages Globally Hdefine Paths RAM Chip AT megal 280 v Data Stack Size 1024 Clock 8 000000 4 MHz bytes Heap Size 0 bytes Memory Model Internal RAM Size
3. ccceceeeeeeeeeeeeeeeeees 24 2 2 4 4 Printing a Text SeleCtion ec ecceee een eee eet ee erent ee erent ee ee saeeeeeeaeeeeesaeeeeeeneeeeneaes 24 2 2 4 5 Indenting Unindenting a Text Selection c ccceccceeecceeeeceeeeeeeseaeeeeeeeseceeeseaeeeeneeenaees 24 2 2 4 6 Commenting Uncommenting a Text Selection eee eeccceeeeeeeeeeeeeeeeeeeeeneeeeeeeneeeeeeaas 24 P Ad MICI B ACOS iea EAE O ORE A E T T A 24 2 2 4 8 Inserting Special Characters in the Text sssesssssresssrrsseerrssrrrrssrtrrssrrinsserrrssrrens 25 2 2 4 9 Using the Auto Complete Functions essseeessresssrnsseennansannaatennannnannantennaanannaatennaananna 26 2 24 10 Using Code FOIGING tcccciecscais eiecdietedaci vita eid ee inal pena eld dees 26 2 2 2 SAVING BIE NS E E aa cedarpeveeadpvahelaaeeeseeday eabosdarnvnenhy abedaaeivneadubes 27 2 2 6 Renaming a Fil is cicteciitiwis ie asia ie ie deli atin i ei iain 27 2 2 7 Printing a File eee ter nr eee reer eee EAEAN ee EENEN EEA EARRANTA EEn 28 2 2 0 ClIOSING a RIG wesc cht a E dened O O OA O OTS 28 2 2 9 Closing Multiple FIGS arsina a A E ES 29 2 2 10 Using the Code Templates riesco ciccicnee etree ee eiinee ee ANNEE NUNAN EARRAN AREAK AA NETANE ANA ENERE AAEREN ARA 30 1998 2009 HP InfoTech S R L Page 2 CodeVisionAVR 2 2 11 Using the Clipboard HIStory ec ccceeeee een e etnies erties ee eeee iNES Nina SE ENNAN ANNERES EA 31 223 Working With Projete i
4. include the abs function prototype include lt stdlib h gt quartz crystal frequency Hz define xtal 4000000L Baud rate define baud 9600 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 main unsigned char i devices int temp initialize the USART control register TX enabled no interrupts 8 data bits UCSRA 0x00 UCSRB 0x08 UCSRC 0x86 initialize the USART s baud rate UBRRH xtal 16 baud 1 gt gt 8 UBRRL xtal 16 baud 1 amp OxFF 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 1998 2009 HP InfoTech S R L Page 183 CodeVisionAVR 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 i1 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 s10 unsigned char
5. 1998 2009 HP InfoTech S R L Page 36 CodeVisionAVR Multiple files can be added by holding the Ctrl key when selecting in the Add File to Project dialog SK Add File To Project x Look in J MULTFILE emm ase Name Date modified Type Size ne J ewe 17 04 2008 12 19 File Folder Recent Places tink 17 04 2008 12 19 File Folder a Dd list 17 04 2008 12 19 File Folder J obj 17 04 2008 12 19 File Folder Desktop E FILE1 14 03 2001 03 15 C compiler source to FILE2 14 03 2001 03 15 C compiler source D EJ FILE3 14 03 2001 03 15 C compiler source Pavel _ mainfile 17 03 2008 14 25 C compiler source Computer Aue 4 TT Network File name FILE3 C FILE1 C FILE2 C hd Open Files of type C Compiler files c X 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 The project s file compilation order can be changed by clicking on a file and moving it up respectively down using the Move Up respectively Move Down buttons Changes can be saved 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
6. 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 value for the PCF8563 Control Status 2 register The pcf8563 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 PCF 8563 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 outp
7. 1998 2009 HP InfoTech S R L Page 250
8. 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 2009 HP InfoTech S R L Page 107 CodeVisionAVR 3 12 Pointers Due to the Harvard architecture of the AVR microcontroller with separate address spaces for data RAM program FLASH and EEPROM memory the compiler implements three types of pointers The syntax for pointer declaration is lt memory attribute gt type lt memory attribute gt lt memory attribute gt pointer name or type lt memory attribute gt lt memory attribute gt lt memory attribute gt pointer name where type can be any data type Variables placed in RAM are accessed using normal pointers For accessing constants placed in FLASH memory the flash or __ flash memory attributes are used For accessing variables placed in EEPROM the eeprom or __ eeprom memory attributes are used Although the pointers may point to different memory areas they are by default stored in RAM Example Pointer to a char string placed in RAM char ptr_to_ram This string is placed in RAM 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
9. printf Now we will make a long jump to main n r longjmp cpu_state 1 ATmega8515 clock frequency Hz define xtal 4000000L Baud rate define baud 9600 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 int j7 1998 2009 HP InfoTech S R L Page 151 CodeVisionAVR initialize the USART control register TX enabled no interrupts 8 data bits UCSRA 0x00 UCSRB 0x08 UCSRC 0x86 initialize the USART s baud rate UBRRH xtal 16 baud 1 gt gt 8 UBRRL xtal 16 baud 1 amp OxFF if setjmp cpu_state 0 printf First call to setjmp n r foo else printf We jumped here from foo n r 1998 2009 HP InfoTech S R L Page 152 CodeVisionAVR 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 equivalent 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 IN
10. 84 D2 COMMIT TMS cece ss Sashes catalase fe ache cases ck pees ce seu aeicde on lie ck faites O eee dena epee hee eee 88 S S RESEIVEd KEY WOKS visi efaccesetcicievesdeacevuid dadbavetiaciavvtdds EEA 89 3 4 Identifiers 000 eet en ne ee rete erent ee eee ee ee AEAN AE RNAAR AENA AA ANANN 90 3 5 Data Typos crcr eao bhai bails Needles EA E EEE EE 90 3 0 CONSTANS ieri decade ives EEA EE EEEE E COE EEE 91 3 VanableS ented E Ae nei ia ee A AE EOE 93 3 7 1 Specifying the RAM and EEPROM Storage Address for Global Variables 05 95 Dl 2 BIC ANADICS 322 ios a T TT OEE REE TOE OET 96 3 7 3 Allocation of Variables to RegisterS s ssssseseerrnnssrnnseennanrannaneeennaanannnatennaanannantennaanannna anen 97 SCA SMUCWUICS icicles ssptecctelede TE ate stedeieesdedei AA 98 SLO UNO yee caesigae deed gncedaayel O decyl eves EEE A E OE 101 3 7 6 EMUMELations c c cece eect etree ee eee ee ere NANANA ARANAN K ANENE NENANA RN RANEREN AARNA N EEEN AEAEE 103 1998 2009 HP InfoTech S R L Page 4 CodeVisionAVR 3 8 Defining Data Types cccsccccsssssssssssssssssssssssssssssssssssusuussssnsessssssusussasssssessssuusuasssssssseessssen 104 3 9 Type COMVErSIONS enen i hid aed ee EEEE bleed enced teeta ied eee he 105 3 10 OPE ALORS nsen a EEEE ens E EE E e a r eaa aE oaa aa a aa 106 3 11 FUNCUOMNS cnra aiT EE ed eee ee 107 3 12 POMNUGIS usec ied i ae anes ieee aed eed ee ed cate E eee 108 3 13 Compiler Directives ccc cece
11. CodeVisionAVR 3 7 1 Specifying the RAM and EEPROM Storage Address for Global Varia bles Global variables can be stored at specific RAM and EEPROM locations at design time using the operator Example the integer variable a is stored in int a the in struct in ch the in RAM at address 80h 0x80 structure alfa is stored RAM at address 90h sl t a ar c alfa 0x90 float variable b is stored float the in EEPROM at address 10h b 0x10 structure beta is stored RAM at address 20h eeprom struct s2 in lo t i ng j beta 0x20 The following procedure must be used if a global variable placed at a specific address using the operator must be initialized during declaration the variable will be stored in RAM at address 0x182 float pi 0x182 and it will be initialized with float pi 3 14 the eeprom and eeprom variable will be stored in the value 3 14 EEPROM at address 0x10 int abc 0x10 it will be initialized with int abc 123 the value 123 1998 2009 HP InfoTech S R L Page 95 CodeVisionAVR 3 7 2 Bit Variables The global bit variables located in the GPIOR register s and R2 to R14 memory space These variables are declared using the bit keyword The syntax is bit lt identifier gt Example declaration and initializat
12. GF _put 66 Init the USART v amp DSTAC i void main void lt 4 m gt 4 m gt 4 m gt i L Messages 320 B Errors E Wwamings j H Messages ap Find in Files 48 43 Insert 1998 2009 HP InfoTech S R L Page 10 CodeVisionAVR In order to undock a window it s top bar must be clicked with the left mouse button and keeping the button pressed dragged to any suitable position on the desktop The window can be resized by dragging it s right and pressed File Edit Search View Project Tools Settings Help Bee HtECOSA NARS HAM 232 OK O Z RE Code Information E C cvavr2 examples ame Notes usartc eB usartc a H Includes H 4 Macrg HRe Type igned in 5AP Globa CodeVisionAVR a Btruct stru amp xX ek oP Project usart uns xX ef B Notes s px aq 0 usarte 4 m gt i i i B Headers f Function Ca a gt Bt void B f0 main Stest p ce E DSTACK Func 0 0 oO printf 61 7 increment some E DSTACK Fun 62 eeprom_struct b CE _print 63 eeprom_struct d amp DSTACKF 64 eeprom _struct f aft _put p E psTac T 66 iit the vsarT i b lt Messages B Errors B Warnings bottom margins with the left mouse button 1998 2009 HP InfoTech S R L Page 11 CodeVisionAVR An undocked window can be docked t
13. Test Attributes Use Editor Colors for 10 B void main void J Bold Text 11 Fy i 12 int Number 123 Italic F a A pa 13 int HexNumber Ox1FA7 Underlined v Background 14 Eloat FlostNumber 0 123e 2 J 5 char c D User Defined Keywords 16 char text Hello world 7 while Number 18 A 19 peeprort pflash t 20 Number 21 he z 22 4 m p X cance 36 pett 2 Hep Syntax Highlighting Enabled enables or disables source file syntax highlighting Syntax Highlighter list box selects the programming language for which the syntax highlighting settings will be applied The CodeVisionAVR Editor supports syntax highlighting for the C and Atmel AVR Assembler programming languages e e e Element e Language Element list box selects the element for which the text colors and attributes will be set Text Color specifies the text foreground color for the above selected Language Element Background Color specifies the text background color for the above selected Language Text Attributes specifies how the text is displayed for the above selected Language Element Text attributes can be combined by appropriately checking the Bold Italic and Underlined check boxes The displayed font will be the one selected in the Text Font settings The Text respectively Background check boxes from the Use Editor Colors group box when checked will set the foreground respectively background text colors for the sel
14. 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 RAM 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 RAM access 1998 2009 HP InfoTech S R L Page 117 CodeVisionAVR 3 15 Accessing the EEPROM Accessing the AVR internal EEPROM is accomplished using global variables preceded by the eeprom or eeprom memory attributes Example T The value 1 is stored in the eeprom int alfa 1 EPROM
15. enables more detailed custom configuration like the number and jump type of the interrupt vectors and memory usage Q Configure Project MULTFILE PRJ Ex Files C Compiler Before Build After Build Code Generation Advanced Messages Globally define Paths Interrupt Vectors Table Number of Yectors 57 KA Type of Jump JMP Int Vectors in External File RAM RAM area to be allocated by the Compiler for Data Stack global variables Hardware Stack and Heap Start 200 h End 3FFF h X Cancel Help The Int Vectors in External File option enables or disables placing the interrupt vectors in an external vectors asm file created by the user If this option is enabled the compiler will not generate any interrupt vectors by itself as the vectors will be present in the vectors asm file 1998 2009 HP InfoTech S R L Page 44 CodeVisionAVR The Messages tab allows to individually enable or disable various compiler and linker warnings EN Configure Project MULTFILE PRJ E Files C Compiler Before Build After Build Code Generation Advanced Messages Globally Hdefine Paths 7 Enable Warnings Warnings IV constant out of range A IV possible loss of precision V array index is out of range I global variable address out of range V interrupt vector exceeds the allowable range V uninitialized FLASH m
16. 6 DSTACK Func 0 Total 0 code Navigator AIR 3 C cvavr2 examples akmega Notes usartc eeprom unsigned int e SX CodeVisionAVR S Project usart 18 Notes usart c Headers B ioh A stdarg h A stdbool h B stdinth A stdio h A xmbits_at h B xmegal28a1 h xmstructh te Code Information i Code Navigator A workspace window can be hidden by left clicking on it s icon by pressing it s corresponding button on the View toolbar or by using the View menu A window s corresponding button on the View toolbar must be pressed or the View menu must be used in order to make a hidden window visible again Clicking on the icon will make the docked window temporarily hidden it s position will be displayed by a vertical bar located on the left or right of the docking site 5 f CodeVisionAVR C cvavr2 examples atxm File Edit Search View Project Tools S k gi mn E 3 2 aj 4 O g l a o ecs He adcg ml f h ap MD 4 at 2 CAcvavr2 examples akmega USARTC Notes usartc 48 eeprom unsigned int eeprom_ui 49 eeprom struct3_type struct3 50 eeprom unsigned int eeprom_ui 51 eeprom struct structS type 52 unsigned int t 53 structs 54 55 56 57 goag main void 58 59 eeprom stest p seeprom struc 61 increment some of the bit 62 eeprom _struct b 63 eeprom _struct d 64 eeprom _struct f 66 Init the USART 67 T
17. B01 0 B02 1 B11 0812 1 C BOOTSZ1 0 EESAVE 0 B01 0 BO2 0 B11 0812 0 WDTON 0 B01 1 B02 0 B11 1 B12 0 z aeg A V Check Signature V Check Erasure _ Preserve EEPROM V Verify You can select the type of the chip you wish to program using the Chip combo box 1998 2009 HP InfoTech S R L Page 66 CodeVisionAVR The SCK clock frequency used for In System Programming with the STK500 AVRISP or AVRISP MkIl can be specified using the SCK Freq listbox This frequency must not exceed of the chip s clock frequency If the chip you have selected has Fuse Bit s that may be programmed then a supplementary Program Fuse Bit s check box will appear If it is checked than the chip s Fuse Bit s will be programmed when the Program All menu command is executed or when the Program All button is pressed The Fuse Bit s 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 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 memo
18. Gal U La eno ia ida iia 230 5 13 1 Setting the LM S devices enira nenE s anaia ENA n KEE A KEENAN AA KE ERASE 231 5 13 2 Setting the D51621 GOVICES sce jadesvesee sites tebecneares svadet petacancesbeneased certah pedtheaes aecenbesaeee eee 232 5 13 3 Setting the PCF8563 devices eect eect ee eeeeee ee teeeee eee teeeaeeeeeeeeeeeteeeaeeetennaeeeeeenaaeees 233 5 13 4 Setting the PCF8583 deViICeS c cccesceeeeesieeedeeteeseceuieneedcastcnedeantennecasieneeenicetedestnenees 234 5 13 5 Setting the DS1307 devices 20 0 eect tree erent ee eet ne ee ee te ee ee taeee ee teeeee teaser sneeeeee 235 9 14 Setting the 1 Wire BUS ercncsniieacioniieiniiniitana i lend einai hte edd ena tieanelied 237 5 15 Setting the 2 Wire BUS 00 ei cee eer entre een e ee eee eet ne ee ert neee erties eeesieeeeenieeeeetineeereaa 239 5 16 Setting the CAN Controller 2 eccccseceecccteeeecceteseedanteseeccetecencectipencdanesedantepeeceetesendaceieeendactenees 240 5 17 Setting the ATmega169 329 3290 649 6490 LCD Conttroller ccccseceeeceeeeteeteteeeseees 242 5 18 Setting the LOD crescesse i i E EE E EE E E AREE 243 9 19 Setting the USB Controlar pcrerernii E A 244 5 20 Setting Bit Banged Peripherals 0 cect eter ee eetee eet ee ee tieee ee eeeeeetiieeeeeetiieeeeetieeeetaa 245 5 21 Specifying the Project Information ccc cece etter ee etneee erent ee ee eeeeeeteeeee teases eneeeereaa 246 6 License Agreement neendran aeaa aaea EEN
19. 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 the PCF8563 Timer 1998 2009 HP InfoTech S R L Page 172 CodeVisionAVR 4 12 4 Philips PCF8583 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the PCF8583 IC bus real time clock RTC The prototypes for these functions are placed in the file pef8583 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 IC bus Example the I C bus is connected to ATmega8515 PORTB the SDA signal is bit 3 the SCL signal is bit 4 asm eq
20. interrupt handler for example R30 R31 and SREG asm push r30 push r31 in r30 SR push r30 endasm ea Q place the C code here eara now restore SREG R31 and R30 asm pop r30 out SREG r30 pop T31 pop r30 endasm VER nable register saving for the other interrupts pragma saveregt The default state is automatic saving of registers during interrupts The pragma savereg directive is maintained only for compatibility with versions of the compiler prior to V1 24 1 This directive is not recommended for new projects 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 Global 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 RAM 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 1998 2009 HP InfoTech S R L Page 112 CodeVisionA
21. 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 1998 2009 HP InfoTech S R L Page 247 CodeVisionAVR 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 party 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 6 6 Terms This license is effective until terminated You may terminate it by destr
22. 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 I input size modifier is supported The more features are selected the larger is the code size generated for the printf and sprintf functions The s scanf features option allows to select which versions of the scanf and sscanf Standard C Input Oputput Functions will be linked in your project e int width the following conversion type characters are supported c s i d u x the width specifier is supported no input size modifiers are supported e long width the following conversion type characters are supported c s i d u x the width specifier is supported only the l input size modifier is supported The more features are selected the larger is the code size generated for the scanf and sscanf functions The Data Stack Size must be also specified If the dynamic memory allocation functions from the Standard Library are to be used the Heap Size must be also specified It can be calculated using the following formulae heap _size n 1 4 gt block _ size i l where n is the number of memory blocks that will be allocated in the heap block _ size is the size of
23. usart H struct3 gt EEPROM 0003h Notes X struct5 gt not used removed by the lin D usartc F Functions 28 Headers q A ioh Imm aaa D stdarg h zi A stdbool h f Function Call Tree n the b 5 f0 main stdioh E DSTACK Func 0 Total 0 0 printf 6 DSTACK Func 6 Total 6 if _print ye aA mT m a E a TA oe T Lii Messages Once docked the window will become a tabbed page C avr2 examp es atxmega USARTCO usart p File Edit Search View Project Tools Settings Help BeEee HeaCOSMAARS a rm HP lad ARE v 3 4 F Ls a Sees Code Navigator B7 0 C cvavri 6 CodeVisionAVR Notes ef sin usart ac E ik otes oe D usartc 50 leer a Headers Zll s1 aleer A ioh 52 A stdarg h 53 l stdbool h 54 stdint h WSS stdio h 56 A xmbits_al h 57 pvo i i E e 58 Elf ir Code Information fe Code Navigator b f Function Call Tree 2B 61 77 of main a SA a aT A E a e m Z To undock a single tabbed page the bottom tab must be dragged with the mouse 1998 2009 HP InfoTech S R L Page 13 CodeVisionAVR If the window s top bar will be dragged with the mouse the whole tabbed window will be undocked File Edit Search View Project Tools Settings Help bDeec H adq MARS HHM H f Function Call Tree 3880 h 0 0 main oF printf Messages
24. v Cancel 1998 2009 HP InfoTech S R L Page 201 CodeVisionAVR The File Save menu command or the 5 toolbar button allow saving the currently opened CodeWizardAVR project Sa The File Save As menu command or the toolbar button allow saving the currently opened CodeWizardAVR project under a new name E Save C cvavr bin untitled cwp As xn Save in work P E z Name Date modif Type Size DA This folder is empty Recent Places Pavel A n Computer L lt Network File name test F Save as type CodeWizardAVR project files cwp X Cancel By selecting the File Program Preview menu option or by clicking on the toolbar button the code generated by CodeWizardAVR can be viewed in the Program Preview window This may be useful when applying changes to an existing project as portions of code generated by the CodeWizardAVR can be selected copied to the clipboard and then pasted in the project s source files If the File Generate Save and Exit menu option is selected or the toolbar button is clicked CodeWizardAVR will generate 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 1998 2009 HP InfoTech S R L Page 202 CodeVisionAVR In the course of program generation the user will be prom
25. 19 v Line Numbers ao 24 24 J Highlight Syntax Units mm 3 Printer X 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 The print result can be previewed using the File Print Preview menu command or by pressing the toolbar button 2 2 8 Closing a File You can quit editing the current file by using the File Close menu command the Ctrl F4 shortcut or the G toolbar button The current editor tabbed window can be also closed by clicking on the icon located on the top right of the tabbed control If the file was modified and wasn t saved yet you will be prompted if you want to do that Confirm e Save changes to led c No Cancel 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 1998 2009 HP InfoTech S R L Page 28 CodeVisionAVR 2 2 9 Closing Multiple Files Closing several files can be performed using the File Close Multiple menu command or the fess toolbar button A dialog window which lists all the opened files will open for this purpose Fj Close Multiple Files i Ag M A Minc xmegal28a1 h I usart c Selec
26. 3 5 2 Compiling the Project To compile the Project you must use the Project Compile menu command press the F9 key or the P amp button of the toolbar The CodeVisionAVR C Compiler will be executed producing the object files needed by the linker Compilation will be performed only for the program modules that were modified since the previous similar process The compilation process can be stopped using the Project Stop Compilation menu command or by pressing the button on the toolbar After the compilation is complete an Information window will open showing the compilation results Information Compiler Chip ATmega8515 Clock frequency 3 686400 MHz Program type Application Memory model Small Optimize for Size s printf features int width s scanf features int width Promote char to int No char is unsigned Yes global const stored in FLASH No 8 bit enums Yes Enhanced core instructions On Automatic register allocation Off 201 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 4 byte s RAM Global variables size 0 byte s Hardware Stack area EOh to 25Fh Hardware Stack size 384 byte s Heap size 0 byte s EEPROM usage 0 bytefs 0 0 of EEPROM 1998 2009 HP InfoTech S R L Page 54 CodeVisionAVR Eventual compilation errors and or warnings will be l
27. 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 SPSR 0x00 the AD7896 will work in mode 1 high sampling performance CONVST 1 SCLK 0 PORTB 2 initialize the LCD lcd_init 16 1998 2009 HP InfoTech S R L Page 197 CodeVisionAVR 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 delay ms 100 1998 2009 HP InfoTech S R L Page 198 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 functio
28. 8192 bytes Small External RAM Size 0 bytes Optimize for F External RAM Wait State Speed Code Generation Optimization Level Bit Variables Size 24 E Use GPIOR gt 31 Maximal Promote char to int V char is unsigned 8 bit enums V Enhanced Core Instructions J Smart Register Allocation Program Type Boot Loader 4096 Automatic Global Register Allocation s printt Features Store Global Constants in FLASH Memory int width Use an External Startup Initialization File s scanf Features WJ Clear Global Variables at Program Startup p l Stack End Markers ile Qutput Format s COF ROM HEXEEP F Boot Loader Debugging in AVR Studio Preprocessor Create Preprocessor Output Files Vj Include 1 0 Registers Bits Definitions X Cancel Hep 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 1998 2009 HP InfoTech S R L Page 40 CodeVisionAVR For reduced core chips like ATtiny10 there is an additional option Enable auto Var Watch in AVR Studio If this option is enabled the compiler will generate additional code that allows local auto
29. ATmega8515 memory use summary bytes Segment Begin End cseg Ox000000 0x000106 252 10 262 8192 3 2 dseg Ox0000600x0000e1 OF 1 1 512 02 eseg Ox000000 0 000001 OF 1 1 512 02 Code Data Used Size Use Assembly complete 0 errors Program the chip 1998 2009 HP InfoTech S R L Page 58 CodeVisionAVR Pressing the Programmer tab will display the Chip Programming Counter which shows how many times was the AVR chip programmed so far li Information Ez Compiler Assembler Programmer Chip Programming Counter 2 Set Counter Program the chip x Cancel Pressing the Set Counter button will open the Set Programming Counter window Set Programming Coun New Counter Value 0 WA X Cancel This dialog window allows setting the new Chip Programming Counter value Pressing the Program the chip button allows automatic programming of the AVR chip after successful build Pressing Cancel will disable automatic programming 1998 2009 HP InfoTech S R L Page 59 CodeVisionAVR 2 3 5 4 Cleaning Up the Project Output Directories The various files created during the Project Build process can be deleted using the Project Clean Up menu or by pressing the t button on the toolbar The following Project Output Directories will be cleaned e Object Files directory all files will be deleted except the cof COFF object file e List Files directory all file
30. Definition Copy Selecting this option will highlight the source line where the previous declaration or definition was made The size of the Message window can be modified using the horizontal slider bar placed between it and the Editor window 1998 2009 HP InfoTech S R L Page 55 CodeVisionAVR 2 3 5 3 Building the Project To build the Project you must use the Project Build menu command press the Shift F9 keys or the F button of the toolbar The CodeVisionAVR C Compiler will be executed producing the object files needed by the linker Compilation will be performed only for the program modules that were modified since the previous similar process If the complete recompilation of all the program modules is needed then the Project Build All menu command or the amp button of the toolbar must be used After successful compilation the object files will be linked and an assembly asm file will be produced If no compilation or linking errors were encountered then the Atmel AVR assembler AVRASM2 will be executed obtaining the output file types specified in Project Configure C Compiler Code Generation The build process can be stopped using the Project Stop Compilation menu command or by pressing the amp button on the toolbar Eventual compilation errors and or warnings will be listed in the Message window located under the Editor window or in the Code Navigator window Messages Warming C cvavrhex
31. Disconnected v Overflow Interrupt Compare Match Interrupt Compare Match B Interrupt Timer Yalue 0 h Compare O h CompareB O h Clock Source specifies the timer counter 0 clock pulse source Clock Value specifies the timer counter 0 clock frequency Mode specifies if the timer counter 0 functioning mode Outp A specifies the function of the timer counter 0 compare A output and depends of the functioning mode e Outp B specifies the function of the timer counter 0 compare B output and depends of the functioning mode e Overflow Interrupt specifies if an interrupt is to be generated on timer counter 0 overflow 1998 2009 HP InfoTech S R L Page 211 CodeVisionAVR e Compare Match A Interrupt specifies if an interrupt is to be generated on timer counter 0 compare A match e Compare Match B Interrupt specifies if an interrupt is to be generated on timer counter 0 compare B match e Timer Value specifies the initial value of timer counter 0 at startup e Compare A specifies the initial value of timer counter 0 output compare A register e Compare B specifies the initial value of timer counter O output compare B 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_compa_isr for timer counter output compare A match e timer0_compb _isr for timer counter output compare B match You must note t
32. HP InfoTech S R L Page 97 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 memory attribute 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 structure variables gt Example Global structure located in RAM struct ram structure char a b Int 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 sf Global structure located in EEPROM eeprom struct eeprom structure char a int b char 15 7 se void main void Local structure struct local structure char a int b long c sl lt width gt The space allocated to the structure in memory is equal to sum of the sizes of all the members 1998 2009 HP InfoTech S R L Page 98 CodeVisionAVR Structures can be grouped in unidimmensional 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
33. If the Activation Code was copied to the clipboard from the e mail program it may be pasted in the dialog using the Paste from Clipboard button Once the correct Activation Code was entered pressing the Deactivate button will deactivate the license on the current computer On successful license deactivation a message containing the License Removal Code will be displayed 7 Information lees i The following License Removal Code must be sent to HP InfoTech s r l 29F8 9853 The License Removal Code must be sent by e mail to HP InfoTech in order to confirm that the license was indeed deactivated and that a new Activation Code may be sent to the user for a CodeVisionAVR installation on another computer or for a license on the same computer but with updated characteristics If the entered Activation Code is not correct the license is not deactivated the License Removal Code is not displayed and the application just closes In such situation the user must contact HP InfoTech for technical support 2 8 Connecting to HP InfoTech s Web Site The Help HP InfoTech on the Web menu command or the toolbar button opens the default web browser and connects to HP InfoTech s web site http Awww hpinfotech com 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
34. PI 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 2009 HP InfoTech S R L Page 144 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 RAM and FLASH memories char strcat 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 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 one 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
35. Parameters enables or disables displaying a pop up hint window with the function parameters declaration after the user writes the function name followed by a auto completion triggering character The function parameter auto completing works only for the functions defined in the currently edited source file e Auto Complete Structure or Union Members enables or disables displaying a pop up hint window with the structure union members list after the user writes the structure union or pointer to structure union name followed by the or gt auto completion triggering characters The structure or union members auto completion works only for global structures unions defined in the currently edited source file and after a Project Compile or Project Build was performed The Delay slider specifies the time delay that must elapse between entering the auto completion triggering characters and the displaying of the pop up hint window If the user writes any other character before this time delay no pop up hint window will show The Hint Window group box allows setting the Text and Background Colors of the auto complete pop up hint window 1998 2009 HP InfoTech S R L Page 77 CodeVisionAVR These colors will be also applied to the character grid pop up hint window that is invoked using the Edit Insert Special Characters menu the Insert Special Characters right click pop up menu or by pressing the Ctrl keys 2 5 4 Settin
36. Project menu command or the toolbar button If the Project files were modified and were not saved yet you will be asked if you want to do that Confirm Save changes to led c No Cancel 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 prj extension 1998 2009 HP InfoTech S R L Page 64 CodeVisionAVR 2 4 Tools Using the Tools menu you can execute other programs without exiting the CodeVisionAVR IDE 2 4 1 The AVR Studio Debugger The CodeVisionAVR C Compiler is designed to work in conjunction with the Atmel AVR Studio debugger version 4 14 or later for which it will generate an extended COFF object file that allows watching structures and unions Older versions of AVR Studio don t support the extended COFF object file format so these can t be used with CodeVisionAVR Before you can invoke the debugger you must first specify its location and file name using the Settings Debugger menu command amp Debugger Settings Directory and Filename C Program Files Atmel AVR Tools AvrStudio AVRStudio FS X cance 7 Hep Pressing the button allows to select the debugger s directory and file Changes can be saved respectively canceled using the OK respectively Cancel buttons The
37. SREG push r30 endasm place the C code here eara now restore SREG R31 and R30 asm pop r30 out SREG r30 pop r31 pop r30 endasm pew nable register saving for the other interrupts pragma saveregt The default state is automatic saving of registers during interrupts The pragma savereg directive is maintained only for compatibility with versions of the compiler prior to V1 24 1 This directive is not recommended for new projects 1998 2009 HP InfoTech S R L Page 120 CodeVisionAVR 3 17 RAM Memory Organization and Register Allocation A compiled program has the following memory map Working Registers I O Registers 60h or 100h DSTACKEND Data Stack Y initial value 60h or 100h Data Stack Size Global Variables 60h or 100h HSTACKEND Data Stack Size Global Var Size Hardware Stack SP initial value _HEAP_START_ RAM End The Working Registers area contains 32x8 bit general purpose working registers 1998 2009 HP InfoTech S R L Page 121 CodeVisionAVR The register usage depends on the type of the AVR core for which code is generated e standard core 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 R15 may be allocated by the compiler for global and local bit variables The rest of unused registers in this range are allocated for g
38. addr must be NULL 0 The contents of the SPD will be stored in the structure struct _ds18b20 scratch pad struct unsigned char temp l1sb temp_msb temp high temp_ low conf register resl res2 res3 Cre __ds18b20 scratch pad defined in the ds18b20 h header file unsigned char ds18b20_init unsigned char addr signed char temp_low signed char temp_high unsigned char resolution this function sets the low temp_low and high temp_high temperature alarms and specifies the temperature measurement resolution of the DS18B20 The resolution argument may take the value of one of the following macros defined in the ds18b20 h header file DS18B20_9BIT_RES for 9 bit tempearture measurement resolution 0 5 C DS18B20_10BIT_RES for 10 bit tempearture measurement resolution 0 25 C DS18B20_11BIT_RES for 11 bit tempearture measurement resolution 0 125 C DS18B20_12BIT_RES for 12 bit tempearture measurement resolution 0 0625 C 1998 2009 HP InfoTech S R L Page 186 CodeVisionAVR In case of success the function returns the value 1 else it returns 0 The alarm temperatures and resolution are stored in both the DS18B20 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 DS18B20 sensor is used no ROM code array is necessary and the pointer addr must be NULL 0 The alarm status for all the DS18B20 devices on the 1 Wire
39. aiccieessiacaet tecet a E E EE EN bacuebeniee 32 2 3 1 Creating a New Project cect ter ne eee erties ee tieee ee nieeees teaser tiieeeessneeeeena 32 2 3 2 Opening an Existing ProjeCt ieii cdieiie din edi abe ET dedi 34 2 3 3 Adding Notes or Comments to the Project ecceeeeeeeeeeeeeeeeeeeeeneeeeeeteeeeetieeeeetneeeerena 35 2 3 4 Configuring the ProCite ge iedsseeeeedant ged ons denevnnd ge levdat ATE OR 36 2 3 4 1 Adding or Removing a File from the Project c cc eececeeeeeteeeeeeeneeeeeenneeeeeentaeeeeeeaas 36 2 3 4 2 Setting the Project Output Directories 0 eee ee eet eect entree ee eeeeeeeaaeeeeeenaeeeeeeaas 38 2 3 4 3 Setting the C Compiler Options cccccceceeeeeeeceeeeeeeeeceeaeeeeeeeeeeeeseneaeaeeeeeeeeeteenaeas 39 2 3 4 4 Executing an User Specified Program before Build 0 eeccceeeeteeeeeeeteeeeeenneeeeeeeaas 48 2 3 4 5 Transferring the Compiled Program to the AVR Chip after Build 0 e 49 2 3 4 6 Executing an User Specified Program after Build ce eecceeeeeeteeeeeeteeeeeeneeeeeeeaes 51 2 3 5 Obtaining an Executable Program eececeeeceeeeeeeeneee ee etne ee ee eneee ee teeeeeeseeeeesieeeeeenaeeeee 53 2 3 5 1 CHECKING SYNtAX eee eeeee ee eeeeee ee eeee ener eeneae ee ARANAN AEAEE KAANANE ANNEER NANA AEAEE AANEEN 53 2 3 5 2 Compiling the Project esnie rennir EATER peateteiendileep heeds ages TE 54 2 3 9 3 Building the Projet cesoie A aE EE AA 56 2 3 5 4 C
40. alfa void declare and initialize the static variable static int n 1 return nt t void main void int i the function will return the value 1 i alfa the function will return the value 2 i alfa If not 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 to warn the compiler that it may be subject to outside change during evaluation Example volatile int abc Variables declared as volatile will not be allocated to registers All the global variables not allocated to registers are stored in the Global Variables area of RAM All the local variables not allocated to registers are stored in dynamically allocated space in the Data Stack area of RAM If a global variable declaration is preceded by the eeprom or __ eeprom memory attribute the variable will be located in EEPROM Example eeprom float xyz 12 9 _ eeprom int w 5 1 2 3 4 5 1998 2009 HP InfoTech S R L Page 94
41. bit field data type is unsigned char struct alphal unsigned char a 1 bit 0 unsigned char b 4 bits 1 4 unsigned char c 3 bits 5 7 this structure will occupy 2 bytes in RAM 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 F this structure will occupy 4 bytes in RAM 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 J 1998 2009 HP InfoTech S R L Page 100 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 memory attribute gt 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 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
42. c s i d u x the width specifier is supported no input size modifiers are supported e long width the following conversion type characters are supported c s i d u x the width specifier is supported only the l input size modifier is supported The more features are selected the larger is the code size generated for the scanf and sscanf functions 4 3 Standard Library Functions The prototypes for these functions are placed in the file stdlib 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 returns 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 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 1998 2009 HP InfoTech S R L Page 140 CodeVisionAVR 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 v
43. can be specified for the lower respectively upper memory pages using the Lower wait states respectively Upper wait states list boxes The MCUCR EMCUCR XMCRA registers in the startup initialization code are configured automatically according to these settings 1998 2009 HP InfoTech S R L Page 207 CodeVisionAVR 5 3 Setting the Input Output Ports By selecting the Ports tab of the CodeWizardAVR you can specify the input output Ports configuration amp CodeWizardAVR test cwp File Help ExtemalIRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C 1Wire 2wie2c LcD Bit Banged Project Information Chip Extemal SRAM Port Port B Port C Port D Pc Data Direction Pullup Output Value BitO In T Bo Bit1 In T Bit1 Bit2 _In T Bit2 Bit3 In T Bits Bit4 _In T Bit 4 Bit5 In Ti BitS Bit6 In Ti BitG Bit In T 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 if the 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 PO
44. complete Checking the USI Counter Overflow Interrupt check box will generate code for an interrupt service 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 2009 HP InfoTech S R L Page 229 CodeVisionAVR 5 13 Setting the I C Bus By selecting the IC tab of the CodeWizardAVR you can specify the I C bus configuration amp CodeWizardAVR test cwp File Help ExtemalIRQ Timers USARTO USART1 1Wire 2Wire 2c LoD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI 12C 12C Port PORTA SDABit o scLBit i LM75 D51621 PcFa563 F Te Enabled Using the I C Port list box you can specify which port is used for the implementation of the C bus The SDA Bit and SCL Bit list boxes allow you to specify which port bits the C bus uses 1998 2009 HP InfoTech S R L Page 230 CodeVisionAVR 5 13 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 test cwp File Help ExtemalIR Timers USARTO USART1 1wire 2Wire l2C LCD Bit Banged Project Inform
45. 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 RAM 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 RAM 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 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 strcspnf 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 th
46. debugger the value of the register is displayed instead of a single bit from it However it is quite simple to establish the value of the bit variable based on the register bit number allocated for it which is displayed in the Code Information tab of the CodeVisionAVR IDE and the register value displayed in hexadecimal in AVR Studio s Watch window 1998 2009 HP InfoTech S R L Page 96 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 global bit variables The register R15 can be allocated to local bit variables You may specify how many registers in the R2 to R14 range are allocated for global bit variables using the Project Configure C Compiler Code Generation Bit Variables Size list box This value must be as low as required by the program If the Project Configure C Compiler Code Generation Automatic Global 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 global bit variables are allocated to char and int global variables and global pointers If the Project Configure C Compiler Code Generation Smart Register Allocation option is checked the allocation of registers R2 to R14 not used for bit variables is perfo
47. 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 1998 2009 HP InfoTech S R L Page 84 CodeVisionAVR When defining macros you can use the operator to convert the macro parameter to a character string Example define PRINT MESSAGE t printf t JER essei the following code sequence will be replaced with printf Hello PRINT MESSAGE Hello 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 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
48. do that 1998 2009 HP InfoTech S R L Page 83 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 C Preprocessor The C 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 Preprocessor output is saved in a text file with the same name as the source but with the i extension The include directive may be used to include another file in your source You may nest as many as 300 include files 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
49. dropped below the Vlow value and the time values are incorrect Example the I C bus is connected to ATmega8515 PORTB 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 I c bus 126 anit 7 initialize the RTC Timer interrupt enabled Alarm interrupt enabled CLKOUT frequency 1Hz Timer clock frequency 1Hz rtc_init RTC_TIE ON RTC_ATE 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 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 2009 HP InfoTech S R L Page 171 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
50. 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 DS18S20 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 RAM 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 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 mega8515 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 stdlib 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 1998
51. 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 SPI communication there is no need to set the SPI Interrupt Enable Bit SPIE For the ATxmega chips the spi function use by default the SPIC controller on I O port PORTC If you wish to use another SPI controller you must define the ATXMEGA_SPI_ and _ATXMEGA_SPI_PORT_ preprocessor macros prior to include the spi h header file like in the example below use the ATxmegal28Al SPID for the spi function define ATXMEGA SPI_ SPID define _ATXMEGA SPI PORT PORTD use the SPI functions include lt spi h gt The _ATXMEGA_SPI_ and _ATXMEGA_SPI_PORT_ macros needs to be defined only once in the whole program as the compiler will treat them like they are globally defined For the ATxmega chips the SPI library also contains the following function void spi_init bool master_mode bool Isb_first SPI_MODE_t mode bool clk2x SPI_LPRESCALER_t clock_div unsigned char ss_ pin this function initializes the SPI controller and corresponding I O port as defined by the _ATXMEGA_SPI_ and _ATXMEGA_SPI_PORT_ macros If the master_mode parameter is true the SPI controller will function in master mode otherwise it will
52. 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 1998 2009 HP InfoTech S R L Page 187 CodeVisionAVR main unsigned char i devices initialize the USART control register TX enabled no interrupts 8 data bits UCSRA 0x00 UCSRB 0x08 UCSRC 0x86 initialize the USART s baud rate UBRRH xtal 16 baud 1 gt gt 8 UBRRL xtal 16 baud 1 amp OxFF detect how many DS18B20 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 set the temperature alarms amp temperature measurement resolutions for all the devices temp _low 25 C temp _high 35 C resolution 12bits for i 0 i lt devices i t printf INITIALIZING DEVICE u itl if ds18b20 init amp rom_codes i 0 25 35 DS18B20 12BIT RES putsf OK else putsf ERROR e while 1 measure and display the temperature s for i 0 i lt devices printf t u
53. function call The syntax is lt memory attribute gt lt storage modifier gt lt type definition gt lt identifier gt constant expression Example Global variables declaration char a aint p and initialization long c 1111111 void main void Local variables declaration char d int and initialization long 22222222 Variables can be grouped in arrays which can have up to 64 dimensions The first element of an 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 _arrayl 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 _arrayl 10 local array declaration and initialization int local array2 3 11 22 33 char local array3 7 Hello 1998 2009 HP InfoTech S R L Page 93 CodeVisionAVR Local variables that must conserve their values during different calls to a function must be declared as static Example int
54. in a new editor window 2 2 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 or the a toolbar button 1998 2009 HP InfoTech S R L Page 21 CodeVisionAVR 2 2 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 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 button on the toolbar By using the Edit Cut menu command by pressing the Ctrl X keys or by pressing the 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 button on the toolbar Clicking in the left margin of the editor window allows selection of a whole line of text Selected text can be deleted using th
55. int b char c 15 se 2 a 25 Hello b 50 world void main void char k1 k2 k3 k4 int il 223 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 i12 ep gt b k4 ep gt c 2 Because some AVR devices have a small amount of RAM 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 G 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 ine ay s gt c s gt a s gt b i s gt c i sum_struct amp s gt c 1998 2009 HP InfoTech S R L Page 99 CodeVisionAVR Structure members 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 RAM as the
56. 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 2009 HP InfoTech S R L Page 174 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 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 th
57. 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 pointer 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 2009 HP InfoTech S R L Page 148 CodeVisionAVR signed char memcmp void buf1 void buf2 unsigned int n for th
58. must be treated as a long int for the i d u x conversion type characters 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 1998 2009 HP InfoTech S R L Page 139 CodeVisionAVR 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 RAM In order to reduce program code size there is the Project Configure C Compiler Code Generation s scanf Features option It allows linking different versions of the scanf and sscanf functions with only the features that are really required by the program The following s scanf features are available e int width the following conversion type characters are supported
59. must use the spi_isr interrupt service routine declared by the CodeWizardAVR 1998 2009 HP InfoTech S R L Page 227 CodeVisionAVR 5 12 Setting the Universal Serial Interface USI By selecting the USI tab of the CodeWizardAVR you 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 File Help amp CodeWizardAVR test cwp 1 Wire Bit Banged Project Information Chip Ports External IRQ Timers USI Analog Comparator ADC 12C Mode Three wire SPI Clock Register amp Counter USICLK USI Counter Overflow Interrupt 1998 2009 HP InfoTech S R L Page 228 CodeVisionAVR The USI can also operate in the Two Wire I2C mode File Help amp CodeWizardAVR test cwp 1 Wire E Project Information Chip Ports External IRQ Timers USI Analog Comparator ADC Ea m Bit B anged Mode Two wire 12C Clock Register amp Counter USICLK The Shift Reg Clock list box sets the clock source for the USI Shift Register and Counter USI Counter Overflow Interrupt USI Start Condition Interrupt 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
60. only the I 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 1998 2009 HP InfoTech S R L Page 138 CodeVisionAVR void vprintf char flash fmtstr va_list argptr this function is identical to printf except that the argptr pointer of va_list type points to the variable list of arguments The va_list type is defined in the stdarg h header file void vsprintf char str char flash fmtstr va_list argptr this function is identical to sprintf except that the argptr pointer of va_list type points to the variable list of arguments The va_list type is defined in the stdarg h header file void vsnprintf char str unsigned char size char flash fmtstr va_list argptr for the TINY memory model void vsnprintf char str unsigned int size char flash fmtstr va_list arg
61. or deactivate this license you must specify below the Activation Code that corresponds to the license Serial Number Ifyou don t remember this Activation Code please send the Serial Number to HP InfoTech s r l at office hpinfotech com in order to obtain it again The Serial Number can be copied to the clipboard by pressing the Copy to Clipboard button After that the Serial Number can be pasted into your e mail program Serial Number 8433 764D C42C 8E68 8554 3069 Copy to Clipboard Paste here by pressing the Paste fram Clipboard button the Activation Code that you have received from HP InfoTech s r l for this computer The Activation Code may be also entered below manually Activation Code PLURURUR SARA RUE URURUR ER UR OED Paste from Clipboard The Serial Number displayed in the dialog is the current one for the computer on which CodeVisionAVR is installed If the user needs to write this Serial Number in an e mail that must be sent to technical support it can be copied to the clipboard using the Copy to Clipboard button and then pasted from the clipboard in the e mail program In order to deactivate the license the user must enter the Activation Code that was supplied by HP InfoTech when the license was initially activated This is necessary in order to prevent accidental license deactivation by unauthorized persons 1998 2009 HP InfoTech S R L Page 82 CodeVisionAVR
62. 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 strcmpf char str1 char flash str2 compares the string str1 located in RAM 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 2009 HP InfoTech S R L Page 145 CodeVisionAVR signed char strncmpf char str1 char flash str2 unsigned char n compares at most n characters of the string str1 located in RAM 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 RAM Returns a pointer to the string dest char strncpy char dest char src unsigned char n
63. portions of text can be commented respectively uncommented using the Edit Comment Selection respectively Edit Unindent Selection menu commands by pressing the Ctrl respectively Ctrl keys or the 4H respectively X toolbar buttons These functions are also available in the pop up menu invoked by mouse right clicking in the Editor window 2 2 4 7 Match Braces If the cursor is positioned before an opening respectively after a closing brace then selecting the Edit Match Braces menu command pressing the Ctrl M keys or the k toolbar button will position the cursor after respectively before the corresponding matching closing respectively opening brace This function is also available in the pop up menu invoked by mouse right clicking in the Editor window 1998 2009 HP InfoTech S R L Page 24 CodeVisionAVR 2 2 4 8 Inserting Special Characters in the Text Special characters can be inserted in the edited text at the cursor is position by using the Edit Insert Special Characters menu command by pressing the Ctrl keys or the toolbar button A pop up window containing a character map grid will be displayed allowing the user to select the appropriate character to be inserted OD 0 0 0 0 0 0 0 0 ol 1 1 Char code 0x40 ojojojojojojojojojajojo lv lalslxlal col l l Te 0 1 2 3 4 5 6 7 8 9 lt gt JAB CDEFGHIJKLMNO PIQIRIS TIUIVIWIXIYI ZI IAI lalble dje figijh i j iki
64. 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 2009 HP InfoTech S R L Page 218 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 USARTSs there will be two tabs present UARTO and UART1 respectively USARTO and USART1 The functions of configuration check and list boxes will be the same as described above The UARTO USARTO will use th
65. prototypes for these functions are placed in the file ctype h located in the INC subdirectory This file 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 1998 2009 HP InfoTech S R L Page 134 CodeVisionAVR char tolower char c returns the lower case of c if c is an upper case character else c char toupper char c returns the upper case of c if c is a lower case character else c 4 2 Standa
66. 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 e 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 compiler does not know what it is done in the assembler portion of the function 1998 2009 HP InfoTech S R L Page 127 CodeVisionAVR 3 20 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 5 toolbar button The following dialog window will open D Create New File e File Type Source lt S OK 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 functio
67. the Coulomb Counter 1998 2009 HP InfoTech S R L Page 226 CodeVisionAVR 5 11 Setting the SPI Interface By selecting the SPI tab of the CodeWizardAVR you can specify the SPI interface configuration amp CodeWizardAVR test cwp File Help ExtemalIRQ Timers USARTO USART1 USART2 USART3 Analog Comparator 2 Wire I2C LCD Bit Banged Project Information Chip ExtemalSRAM Ports ADC SPI 2c 1 Wire v SPI Enabled SPI Interrupt Clock Rate x2 SPI Mode Mode 0 X Clock Phase SPI Clock Rate Cycle Half 1000 000 kHz Cycle Start 250 000 kHz Clock Polarity 62 500 kHz Low High 31 250 kHz SPI Type esl aes Slave MSB First 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
68. the address chip The temperature is in C and is multiplied by 10 A 300ms delay must be present between two successive calls to the Im75_temperature_10 function 1998 2009 HP InfoTech S R L Page 164 CodeVisionAVR Example how to display the temperature of two LM75 sensors with addresses 0 and 1 the LM75 I C bus is connected to ATmega8515 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 include the LM75 Functions include lt lm75 h gt the LCD module is connected to ATmega8515 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 stdlib h gt include the prototypes for the delay functions include lt delay h gt char display buffer 33 void main void int 0 t1 initialize the LCD 2 rows by 16 columns led_init 16 initialize the I C bus i2c NTE F 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 1998 2009 HP InfoTech S R L Page 165 CodeVisionAVR temperature display loop while 1 read th
69. the mouse and then pressing Enter respectively the left mouse button The structure or union members auto completion works only for global structures unions defined in the currently edited source file and after a Project Compile or Project Build was performed 2 2 4 10 Using Code Folding The CodeVisionAVR Editor has the possibility of displaying staples on the left side of code blocks delimited by the characters For each code block there will be also displayed collapse or expansion amp marks on the gutter located on the left side of the Editor window Clicking on these marks allow to individually fold or unfold blocks of code The View Toggle Fold menu and the EF toolbar button allow to collapse expand the block of code where the cursor is located The View Expand All Folds menu and the I toolbar button allow to expand all folded blocks of code The View Collapse All Folds menu and the A toolbar button allow to collapse all blocks of code delimited by the characters These commands are also available in the pop up menu that is invoked by right clicking with the mouse in the Editor window If the Settings Editor General Visual Aids Save Folded Lines option is enabled the folded unfolded state of the code blocks is saved when the file is closed and it will be restored back when the file is opened again 1998 2009 HP InfoTech S R L Page 26 CodeVisionAVR 2 2 5 Saving a File The currently edited file can
70. zero is performed in this file or not For debugging purposes you have the option Stack End Markers If you select it the compiler will place the strings 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 1998 2009 HP InfoTech S R L Page 43 CodeVisionAVR Using the File Output Format s list box you can select the following formats for the files generated by the compiler e COFF required by the Atmel AVR Studio debugger ROM Intel HEX and EEP required by the In System Programmer e Atmel generic OBJ ROM Intel HEX and EEP required by the In System Programmer The following Preprocessor options can be set e Create Preprocessor Output Files when enabled an additional file with the i extension will be created for each compiled source file The preprocessor output files will contain the source files text will all the preprocessor macros expanded Enabling this option will slow down the compilation process e Include I O Registers Bits Definitions will enable the I O register bits definitions in the device header files The Advanced tab which is present only in the Advanced and Professional versions of the compiler
71. 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 2009 HP InfoTech S R L Page 85 CodeVisionAVR There are the following predefined macros __CODEVISIONAVR__ the version and revision of the compiler represented as an integer example for V2 04 0 this will be 2040 __STDC__ equals to 1 __LINE__ the current line number of the compiled file __FILE__ the current compiled file __TIME__ the current time in hh mm ss format __UNIX_TIME__ unsigned long that represents the number of seconds elapsed since midnight UTC of 1 January 1970 not counting leap seconds __DATE_ the current date in mmm dd yyyy format __ BUILD __ the build number _CHIP_ATXXXXX_ where ATXXXXxX is the chip type in uppercase letters specified in the Project Configure C Compiler Code Generation Chip o
72. 100 The 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 warning directive can be used to display a warning message The syntax is warning warning message Example warning This is a warning The message directive can be used to display a message dialog window in the CodeVisionAVR IDE The syntax is message general messag Example message Hello world 1998 2009 HP InfoTech S R L Page 87 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 isa 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 2009 HP InfoTech S R L Page 88 CodeVisionAVR 3 3 Reserved Keywords Following is a list of keywords reserved by the compiler These can not be used as identifier names break bit bool _Bool case char const continue default defined do double eeprom __eeprom else enum extern flash _ flash float for goto if inline int interrupt __ interrupt long register return short signed sizeof sfrb sfrw static struct switch typedef union unsigned void volatile while 1998 2009 HP InfoTech S R L Page 89 CodeVis
73. 1621_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 I7C 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 DS1621 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 chip Refer to the DS1621 data sheet for more information about this register 1998 2009 HP InfoTech S R L Page 167 CodeVisionAVR void ds1621_set_status unsigned char chip unsigned char data this function sets the contents of the configuration status register of the DS1
74. 20 DS18S20 temperature sensors you must check the DS1820 DS18S20 Enabled check box amp CodeWizardAVR test cwp z File Help ExtemalIRQ Timers USARTO USARTI Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI 12C Ld ite i o 2Wiel2c LCD 1 Wire Port PORTB x Data Bit 0 v DS1820 D518520 v Enabled v Multiple Devices 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 Maxim Dallas Semiconductor DS1820 DS18S20 Temperature Sensors Functions 1998 2009 HP InfoTech S R L Page 238 CodeVisionAVR 5 15 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 test cwp File Help External IRQ Timers USARTO USART1 Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI la eE E 2 Wire Enabled Generate Acknowledge Pulse Slave Address 0 h General Call Recognition 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
75. 2009 HP InfoTech S R L Page 184 CodeVisionAVR allocate space for ROM codes of the devices which generate an alarm unsigned char alarm_rom_codes MAX DEVICES 9 define xtal 4000000L quartz crystal frequency Hz define baud 9600 Baud rate main unsigned char i devices int temp initialize the USART control register TX enabled no interrupts 8 data bits UCSRA 0x00 UCSRB 0x08 UCSRC 0x86 initialize the USART s baud rate UBRRH xtal 16 baud 1 gt gt 8 UBRRL xtal 16 baud 1 amp OxFF 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 u DEVICE S DETECTED n r devices if no devices were detected then halt if devices 0 while 1 loop forever 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 F while 1 measure and display the temperature s for i 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 10 display the number of devices which genera
76. 233 CodeVisionAVR 5 13 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 test cwp xs File Help ExtemalIR Timers USARTO USART1 1wire 2Wire l2C LCD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI 2C 12C Port PORTA SDABit 0 SCLBit i i ps1307 4 gt 4 Enabled Address Mo The PCF8583 Address list box allows you to specify the low bit of the 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 2009 HP InfoTech S R L Page 234 CodeVisionAVR 5 13 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 test cwp File Help ExtemalIRQ Timers USARTO USART1 1wire 2Wire l2C LCD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI 2C 12C Port PORTA SDABit 0 SCLBit i pcress3 1307 T Square Wave Output v Enabled Enabled OUT o x The DS1307 device is accessed through the Maxim Dallas Semiconductor DS1307 Real Time Clock Functions In case the square wave signal output is disabled the state of the
77. 2430 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 itl stop while 1 Refer to the DS2430 data sheet for more information 1998 2009 HP InfoTech S R L Page 191 CodeVisionAVR 4 14 4 Maxim 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 Atmega8515 port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ _ wl bit 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 EEPRO
78. 621 with address chip Refer 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 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 multiplied 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 ATmega8515 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 include the DS1621 Functions include lt ds1621 h gt the LCD module is connected to ATmega8515 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 stdlib h gt char display buffer 33 void main void int t0 tl initialize the LCD 2 rows by 16 columns led_init 16 1998 2009 HP InfoTech S R L Page 168 CodeVisionAVR
79. AM 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 RAM 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 RAM in the DS2430 EEPROM starting from memory address addr 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 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 0 if not The DS2430 device is selected using it s ROM code stored in an array of 8 bytes located at address romcode 1998 2009 HP InfoTech S R L Page 189 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 by
80. C 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 2009 HP InfoTech S R L Page 153 CodeVisionAVR 4 10 Memory Access Macros The memory access macros are defined in the mem h header file located in the MNC subdirectory This file must be include ed before using these macros pokeb addr data this macro writes the unsigned char data to RAM at address addr pokew addr data this macro writes the unsigned int data to RAM at address addr The LSB is written at address addr and the MSB is written at address addr 1 peekb unsigned int addr this macro reads an unsigned char located in RAM at address addr peekw unsigned int addr this macro reads an unsigned int located in RAM at address addr The LSB is read from address addr and the MSB is read from address addr 1 1998 2009 HP InfoTech S R L Page 154 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 alphanu
81. CII 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 2009 HP InfoTech S R L Page 69 CodeVisionAVR 2 4 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 4 5 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 amp Configure Tools Ex E amp Tools _ avrasm2 exe 7i Ad ae A X canca 2 Her Using th
82. Code Information tree branches can be expanded respectively collapsed by clicking on the respectively buttons 1998 2009 HP InfoTech S R L Page 62 CodeVisionAVR By right clicking in the Code Information window you can open a pop up menu with the following choices e Toggle on or off alphabetically sorting the items in the Code Information tree e Toggle on or off expanding the Code Information tree branches 2 3 5 7 Using the Function Call Tree The Function Call Tree window displays the function call sequence that uses the largest amount of Data Stack during program execution Code Navigator Code Information Function Call Tree Code Templates ae f main E DSTACK Func 0 Total 0 timerl_overflow E DSTACK Func 4 Total 4 The Function Call Tree window is accessed using the tab with the same name and appears after the first Compile or Build process of the currently opened project The Data Stack usage information is represented in the form of a tree with two types of nodes e Function nodes Clicking on a function name moves the cursor to the corresponding definition in the source file e DSTACK amp nodes display the data stack used by the parent function and the total level of the Data Stack when the program is executed inside the function 1998 2009 HP InfoTech S R L Page 63 CodeVisionAVR 2 3 6 Closing a Project You can quit working with the current Project by using the File Close
83. CodeVisionAVR VERSION 2 04 1 HP InfoTech User Manual CodeVisionAVR CodeVisionAVR V2 04 1 User Manual Revision 16 3 2009 Copyright 1998 2009 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 2009 HP InfoTech S R L Page 1 CodeVisionAVR Table of Contents Table of Contents ssec AE sei cecntcepencentvenssoctsesceanteeretene se AREA aSa R 2 1 Introductions a a 9 fa r e EA E E E E O A IE E ep eae er oe sre omer I rrr oe 10 2 The CodeVisionAVR Integrated Development Environment sssssussssnnnssnnnnnrnnnnnnnnnnnnnnnnnnnnnnn nnn 10 2 1 Using the Integrated Development Environment Workspace cccceeeeeeeeteeeeetteeeeeetnneeeeeene 10 2 2 Working With PIGS ccsccenccndrenis nad iea EE N 20 221 Creatingra New Fie meelis a a A a E 20 222 Opening am Existing Files sstececdidecdee elie cceeasetedeqsstescehdsctedcgadi dedensslascehdecte AAE 21 2 29 PIlGS FISON sonssoiiai sited alinneilenenaihdinihi ad acide ad adnan 21 2 2 4 Editing a File serenate i i a a a trea deeee deeds 22 2 2 4 1 Sarching Replacing Text ssassn aeceeetedie i NANANA NAA NAANA ieee 23 2 2 4 2 Setting BOOKMArKS cece ee eeeee rere ee erent ee erent eset ae tu EAn NE Eunan EEEa nt Enna aE Ennn nenn nnne eE 23 2 2 4 3 Jumping to a Specific Line Number in the Edited File
84. Color specifies the foreground color of the default normal text in the Editor and Terminal windows e Default Background Color specifies the background color of the default normal text in the Editor and Terminal windows e Highlighted Text Color specifies the foreground color of the text highlighted by the user in the Editor window e Highlighted Background Color specifies the background color of the text highlighted by the user in the Editor window 1998 2009 HP InfoTech S R L Page 75 CodeVisionAVR Non Printable Text Color specifies the foreground color of the non printable character markers displayed in the Editor window when the View Visible Non Printable Characters menu option is checked The background color of the non printable character markers will be the same as the Default Background Color of the Editor window 2 5 3 3 Syntax Highlighting Settings The following Editor settings can be established by clicking on the Syntax Highlighting tab SX Editor Settings General Text Syntax Highlighting Auto Complete Sample Text 1 Multiple line V Syntax Highlighting Enabled 2 comment sai 3 f Single line comment Syntax Highlighter v 6 ong e 4 define MAX a b Language element Symbol x 5 a gt b a b Text Color HB Window Text oa 7j flash char pflash flash int 0 3 8 eeprom int peeprom eeprom int Background Color J Window v 3 aii i
85. 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 Negative Input Multiplexer check box will connect the analog comparator s negative input to the ADC s analog multiplexer If the Negative Input Multiplexer option is not enabled the Inputs list box allows to select which of the ADC s analog multiplexer inputs will be connected to the analog comparator s positive and negative inputs The Inputs Hysterezis list box allows to select the amount of hysterezis of the analog comparator inputs 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 1998 2009 HP InfoTech S R L Page 220 CodeVisionAVR For some AVR chips the analog comparator s output may be to be used for capturing the state of timer counter 1 In this case the Analog Comparator Input Capture check box must be checked if present 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
86. Example This function displays a string located in RAM void display ram char s This function displays a string located in FLASH void display flash flash char s T EPROM This function displays a string located in void display _ eeprom eeprom char s void main void The literal string Hello world will be placed by the compiler in FLASH memory and copied at program startup to RAM so it can be accessed by the pointer to RAM used as function parameter The cod fficiency is low because both FLASH and RAM memories are used for the string storage display_ram Hello world The literal string Hello world will be placed by the compiler in FLASH memory only good code fficiency beeing achieved display_flash Hello world The literal string Hello world will be placed by the compiler in EEPROM memory only The cod fficiency is very good because no FLASH memory will be allocated for the string display_eeprom Hello world while 1 1998 2009 HP InfoTech S R L Page 92 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 0 at program startup The local variables are not automatically initialized on
87. Example union declaration union alpha unsigned char lsb 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 amp 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 RAM 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 lsb void main void data word 0x1234 printf the LSB of Sx is 2x data word low amp data 1998 2009 HP InfoTech S R L Page 101 CodeVisionAVR Union members 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 RAM as the bit field data type is unsigned char union alphal unsigned char a l bit 0 unsigned char b 4 bits 0 3 unsigned char c 3 bits 0 2
88. II can use two programming modes e JTAG e ISP These can be selected using the Programming Mode list box amp Programmer Settings ese xs AVR Chip Programmer Type Atmel JTAG ICE MkII USB Programming Mode JTAG X v ATmegal69 CKDIVS Fuse Warning x Cancel Help Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2009 HP InfoTech S R L Page 80 CodeVisionAVR 2 5 6 Serial Communication Terminal Setup The serial communication Terminal is configured using the Settings Terminal menu command ca Terminal Settings Ex Handshaking Appearance Pott COMI v Catt A None jaers 25 A Baud rate 9600 x xon Xoff m BpSels Columns 80 Data bits 9 DTR DSR i LH E e aLla Stop bits 1 v On Reception Font a Parity re v On Transmission Emulation TTY v Echo X conce 2 Heb In the Terminal Settings 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 po
89. LL 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 ATmega8515 as follows DS2433 STK200 PORTA HEADER 1 GND 9 GND 2 DATA 7 PA6 All the devices must be connected in parallel AN 4 7k PULLUP RESISTOR MUST BE CONNECTED BETWEEN DATA PA6 AND 5V ee asm equ _ wl port 0xlb equ _ wl bit 6 endasm test the DS2433 functions include lt ds2433 h gt include lt mega8515 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 scratchpad boundary char buffer 100 define START ADDR 2 ATmega8515 clock frequency Hz define xtal 4000000L Baud rate define baud 9600 1998 2009 HP InfoTech S R L Page 193 CodeVisionAVR main unsigned char i devices initialize the USART control register T
90. M memory address addr and stores it in the string dest located in RAM It 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 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 RAM 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 RAM 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 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 1998 2009 HP InfoTech S R L Page 192 CodeVisionAVR If only one DS2433 EEPROM is used no ROM code array is necessary and the pointer romcode must be NU
91. MISO 6 DGND 20 GND 7 CONVST 2 PB1 8 BUSY 1 PBO Use an 2x16 alphanumeric LCD connected to PORTC as follows LCD ATmega8515 DIP40 1 GND 20 GND 2 5V 40 VCC 3 VLC 4 RS 21 PCO 5 RD 22 PCL 6 EN 23 PC2 11 D4 25 PC4 12 D5 26 PC5 13 D6 27 PC6 14 D7 28 PC7 asm equ _ lcd port 0x15 endasm 1998 2009 HP InfoTech S R L Page 196 CodeVisionAVR include lt lcd h gt LCD driver routines include lt spi h gt SPI driver routine include lt mega8515 h gt include lt stdio h gt include lt delay h gt AD7896 reference voltage mV define VREF 5000L AD7896 control signals PORTB bit allocation define ADC_BUSY PINB O 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
92. 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 2009 HP InfoTech S R L Page 221 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 amp CodeWizardAVR test cwp File Help 1 Wire LCD Bit Banged Project Information Chip Ports External IRQ _ Timers USI Analog Comparator ADC 12C ADC Enabled V Use 8 bits v Interrupt Noise Canceler v Bipolar Input Volt Ref AVEC pin v Clock 125 000 kHz x Auto Trigger Source Free Running v Automatically Scan Inputs v Enabled First 0 sj Last 7 zj Disable Digital Input Buffers 0 1 2 Aref3 4 5 6 Disable Digital Input Buffers T E 9 10 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 The ADC may be operated in bipolar mode if the Bipolar Input check box is checked 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 Spee
93. R30 1 ST X RO0 SBIW R24 1 BRNE GLOBAL INI LOOP MOV R30 R22 MOV R31 R23 RJMP GLOBAL INI NEXT GLOBAL INI END LDI R25 HIGH _ CLEAR _ SIZI T TION LDI R30 LOW GLOBAL INI TBL 2 I TBL 2 The _ CLEAR_START and __CLEAR_SIZE constants can be changed to specify which area of RAM 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 RAM This table is automatically generated by the compiler 1998 2009 HP InfoTech S R L Page 125 CodeVisionAVR 3 19 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 e Inline assembly may also be used Example asm Ssei 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 2009 HP InfoTech S R L Page 126 CodeVisionAVR 3 19 1 Calling Assembly Functions from C The following example shows how to access functions written in assembly language fro
94. RTx register will be initialized according to these settings 1998 2009 HP InfoTech S R L Page 208 CodeVisionAVR 5 4 Setting the External Interrupts By selecting the External IRQ tab of the CodeWizardAVR you can specify the external interrupt configuration amp CodeWizardAVR test cwp x File Help Analog Comparator ADC SPI 12C 1Wie 2wie 2c LcD Bit Banged Project Information Chip ExtemalSRAM Ports Enternal IAG Timers USARTO USARTI Z INTO Enabled Mode Lowlevel INT1 Enabled Mode Low level X INT2 Enabled Mode Lowlevel v INT4 Enabled Mode Low level kd INTS Enabled Mode Low level Z 7 v v V INT3 Enabled Mode Lowlevel v v V INT6 Enabled Mode Lowlevel v INTZ Enabled 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 2009 HP InfoTech S R L Page 209 CodeVisionAVR For some devices like the ATmega3290 the External IRQ tab may present the following options amp CodeWizardAVR test cwp ej File Help LUSI USART Analog Comparator ADC sp
95. S 3f xf8C n r itl1 ds18b20 temperature amp rom_codes i 0 display the number of devices which generated an alarm printf ALARM GENERATED BY u DEVICE S n r wl _search 0xec alarm_rom_codes e Refer to the DS18B20 data sheet for more information 1998 2009 HP InfoTech S R L Page 188 CodeVisionAVR 4 14 3 Maxim 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 the 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 Atmega8515 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 R
96. S R L Page 215 CodeVisionAVR If timer counter 3 interrupts are used the following interrupt service routines may be defined by the CodeWizardAVR e timer3_ovf_isr for timer counter overflow e timer3_comp_isr or timer3_compa_isr timer3_compb_isr and timer3_compc_isr for timer counter output compare match e timer3_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 By selecting the Watchdog tab you can configure the watchdog timer amp CodeWizardAVR test cwp File Help USART2 USART3 Analog Comparator apc sa c 1Wite 2 Wire I2C LCD Bit Banged Project Information Chip m Extemal SRAM Ports _ External IRQ Timers USARTO USART g v Watchdog Timer Enabled Oscillator Prescaler OSC 2k OSC 64k OSC 4k OSC 128k OSC 8k OSC 256k OSC 16k OSC 512k OSC 32k OSsc 1024k Watchdog Timeout Interrupt 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 If the Watchdog Timeout Interrupt check box is checked an interrupt serviced by the wdt_timeout_isr function will be generated instead of reset if a timeout occurs In case the watchdog timer is enabled you must include yourself the appropriate code sequence
97. SQW OUT pin can be specified using the OUT list box 1998 2009 HP InfoTech S R L Page 235 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 File a CodeWizardAVR test cwp Help Timers USARTO USART1 External IRQ 1Wwie Bit Banged Chp _ External SRAI 2 Analog Comparator abc SPI 2 wire I2C LCD I2C Port PORTA SDABit 0 SCLBit 1 Square Wave Output V Enabled Enabled Freq 1 v Hz Project Information External SRAM Parts 12C 1998 2009 HP InfoTech S R L Page 236 CodeVisionAVR 5 14 Setting the 1 Wire Bus By selecting the 1 Wire tab of the CodeWizardAVR you can specify the 1 Wire bus configuration amp CodeWizardAVR test cwp File Help Extemal IRQ Timers USARTO USART1 Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI 120 p Wie 2Wiel2c LCD 1 Wire Port PORTB Data Bit 0 v DS 1820 D518520 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 Bit list box allows you to specify which port bit the 1 Wire bus uses 1998 2009 HP InfoTech S R L Page 237 CodeVisionAVR If you use the DS18
98. VR 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 Example 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 The pragma vector directive is used for specifying that the next declared function is an interrupt service routine Example Vector numbers are for the AT90S8515 Specify the vector number using the pragma vector directive pragma vector 8 Called automatically on TIMERO overflow _ interrupt void timer0 overflow void Place your
99. Voltage Calibration list box allows for precision adjustment of the nominal value of the reference voltage in 2mV steps The Temperature Gradient Adjustment slider allows shifting the top of the Veer versus temperature curve to the center of the temperature range of interest thus minimizing the voltage drift in this range The Atmega406 datasheet may be consulted for more details 1998 2009 HP InfoTech S R L Page 224 CodeVisionAVR 5 10 Setting the ATmega406 Coulomb Counter The Atmega406 chip contains a dedicated Sigma Delta ADC optimized for Coulomb Counting to sample the charge or discharge current flowing through an external sense resistor Rs This ADC can be configured by selecting the Coulomb Counter tab of the CodeWizardAVR amp CodeWizardAVR test cwp Ex File Help 12C 1 Wire l 2 Wire 12C LCD Bit Banged Project Information Chip Ports External IRQ Timers ADC Voltage Reference Coulomb Counter v Coulomb Counter Enabled Accumulate Current Conversion Time 125 x ms v Regular Current Detection Mode Sampling Interval 266 x ms v Accumulate Current Interrupt v Regular Current Interrupt V Instantaneous Current Interrupt Regular Charge Current Rs 5 mohmi 535 mA Regular Discharge Current Rs 5 mohm 53 5 v mA Checking the Coulomb Counter Enabled check box enables the Coulomb Counter Sigma Delta ADC The Accumulate Current Conversion Time list box specifies the
100. X enabled no interrupts 8 data bits UCSRA 0x00 UCSRB 0x08 UCSRC 0x86 initialize the USART s baud rate UBRRH xtal 16 baud 1 gt gt 8 UBRRL xtal 16 baud 1 amp OxFF 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 it t make sure to select only the DS2433 types 0x23 is the DS2433 family code if 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 1 buffer else printf Error reading data from DS2433 u n r it1 else printf Error writing data to DS2433 u n r itl stop while 1 Refer to the DS2433 data sheet for more information 1998 2009 HP InfoTech S R L Page 194 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 include
101. a number of Application Notes that are available for download at http www atmel com dyn products app notes asp part_id 4310 The sample code for these Application Notes can be easily compiled with CodeVisionAVR For this purpose the header file avr_compiler h supplied for each Application Note must be replaced with the same file located in the INC directory of the CodeVisionAVR installation 3 23 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 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 smallest possible memory model TINY or SMALL e Always store constant strings in FLASH by using the flash or __ flash memory models e After finishing debugging your program compile it again with the Stack End Markers option disabled 3 24 Limitations The current version of the CodeVisionAVR C compiler has the following limitations the long long double _Complex and _Imaginary data types are not yet supported the bit data type is not supported for the reduced core used in chips like ATtiny10 functions with variable number of parameters are not supported for reduced core
102. aaa AAA AAIE AENEA Eaa 247 6 1 Sotware LICENS G ws wed weenie A eee ee ee ee Ae EEEE ET 247 6 2 Liability DISCIANMOR eseis iiie i E E EATE jew deneih A R 247 6 3 Resto ions naana a E T T T O E 247 6 4 Operating License carved iaccevuncica a ved iaa a hd aeeeeietee 247 6 5 Back Up and TranSter csunciscccaccssercccasseseicesneaicaasexenadceradvadsetecacdensandadde tedaddessasaendacsaganceeneudassneneacs 248 6 0 TOME sieivectiae htt iieeandy beled ec ete needa AE E E ied lanes 248 6 7 Other Rights and Restrictions cece eee et tree etnies erie ee tuuna Attn ee tieeeeeniieeeertieeeeeeaa 248 1998 2009 HP InfoTech S R L Page 7 CodeVisionAVR 7 Technical Support and Updates ceccccccceceeeeeeeee cece ee eeeseeaeee sees eeseeeseaeeeeeseeeseseeegeeeeeseeeseeeeeenenees 249 8 CONTACT IMPOR AT ON sassy sanaaa aaia ariaa iia EdEo aiandi 250 1998 2009 HP InfoTech S R L Page 8 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 designed to run under the Windows 98SE Me NT 4 2000 XP and Vista operating systems The C cross compiler implements 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
103. amming 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 2009 HP InfoTech S R L Page 50 CodeVisionAVR 2 3 4 6 Executing an User Specified Program after Build This option is available if you select the After Build 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 XN Configure Project MULTFILE PRJ Files C Compiler Before Build After Build Program the Chip v Execute User s Program Program Settings X conce 2 Her 1998 2009 HP InfoTech S R L Page 51 CodeVisionAVR Using the Program Settings button you can modify the e Program Directory and File Name e Program Command Line Parameters e Program Working Directory NL User Program Settings Program Directory and FileN ame f Command Line Parameters Working Directory 2 ETTI Pressing the button allows to select a direct
104. amp node which displays all the header h files included in the currently edited source file Clicking on a header F node moves the cursor to the corresponding include directive in the edited source file e Macros node which displays all the preprocessor macros defined in the currently edited source file Clicking on a macro node moves the cursor to the corresponding define directive in the edited source file e Typedefs node which displays all the data types defined in the currently edited source file Clicking on a type definition node moves the cursor to the corresponding data type definition in the edited source file If the defined data type is a structure union or enumeration then it s members are displayed as additional nodes e Global Static Variables F node which displays all the global and static variables declared in the currently edited source file Clicking on a RAM variable node or EEPROM variable node moves the cursor to the corresponding declaration in the edited source file e Global Constants node which displays all the global constants declared in the currently edited source file Clicking on a constant node moves the cursor to the corresponding declaration in the edited source file e Functions node which displays all the functions that were defined in the currently edited source file Clicking on a function node moves the cursor to the corresponding definition in the edited source file The
105. amplesSLED Ned c 32 global variable xyz declared but not referenced The Project Go to Next Error respectively Project Go to Previous Error menu commands the F8 respectively Ctrl F8 keys or the B respectively B toolbar buttons allow moving to the next respectively previous error message The Project Go to Next Warning respectively Project Go to Previous Warning menu commands the F4 respectively Ctrl F4 keys or the j respectively 2 toolbar buttons allow moving to the next respectively previous warning message By left clicking with the mouse on the error or warning message the source line with the problem will be highlighted Right clicking with mouse opens a pop up menu that contains the option to Copy the error message to the clipboard Messages C cvavrsexamples LED Mled c 32 lobal variable xyz declared but not referenced faning Copy 1998 2009 HP InfoTech S R L Page 56 CodeVisionAVR If the message refers also to a previous declaration or definition from a file that is different than the one where the error was signaled right clicking with the mouse opens a pop up menu with the Jump to Previous Declaration or Definition option Messages Error C cvavr examples MULTFILE Mile cf 3 function parameter 1 doesn t match it s previous declaration from file C cvavrexamples MULTFILE file1 h line 3 Jump to Previous Declaration or Definition Copy Selecting t
106. and its source file s You can later configure the Project by using the Project Configure menu command or by pressing the En toolbar button 1998 2009 HP InfoTech S R L Page 34 CodeVisionAVR 2 3 3 Adding Notes or Comments to the Project With every Project the CodeVisionAVR IDE creates an associated text file where you can place notes and comments You can access this file using the Project Notes or Windows menu commands EJ Project Notes MULTFILE PRJ oe This file can be edited using the standard Editor commands The file is automatically saved when you Close the Project or Quit the CodeVisionAVR program 1998 2009 HP InfoTech S R L Page 35 CodeVisionAVR 2 3 4 Configuring the Project The Project can be configured using the Project Configure menu command or the oo toolbar button 2 3 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 or the N toolbar button A Configure Project tabbed dialog window will open You must select the Files and Input Files tabs K Configure Project MULTFILE PRJ ese Files C Compiler Before Build After Build Input Files Qutput Directories A C cvavrexamples MULTFILESMULTFILE PRJ mainfile c 7i Add file1 c EF file2 c file3 c X Cancel Help By pressing the Add button you can add a source file to the project
107. arnings 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 2009 HP InfoTech S R L Page 105 CodeVisionAVR The compiler behaves differently for the following operators oe Nt oll gt R ll 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 x ia l lt gt lt gt amp amp amp lt lt gt gt ch gt amp A gt gt lt lt sizeof 1998 2009 HP InfoTech S R L Page 106 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 char parl int par2 long par3
108. ation Chip ExtemalSRAM Ports Analog Comparator ADC SPI 2C 12C Port PORTA SDABit 0 SCLBit 1 ViEnabled Address V 0 Output Active High Temperature C Hyst 75 240 5 80 24 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 2009 HP InfoTech S R L Page 231 CodeVisionAVR 5 13 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 test cwp File Help ExtemalIRQ Timers USARTO USART1 _ 1Wire 2Wire 120 LCD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator apc SPI 12C 12C Pott PORTA SDABit O SCLBit 1 7 Enabled Address V 0 Output Active High Temperature trigger C Low 50 4 High 55 44 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 temperatures f
109. ation window or left floating on the desktop to suit the user s preferences F CodeVisionAVR C cvavr2 examples atxmega USARTCO usart py usar o X File Edit Search View Project Tools Settings Help bes HeaCS MARS x B 4 Ov Bla E gt t CAW TROD O ARN BESS Agg MO i fE Code Navigator 7 E amp Code Information B 2 E C cvavr2 examples akmega USARTCO usartc E S Code Templates 7 By Clipboard 7 SX CodeVisionAVR e B fe a Notes usertc aif a a f Project usart Al Includes Wey z i by i 48 eeprom unsigned int eeprom uiA 2 a Notes KHO Macros 49 eeprom struct3_type struct3 3 if usartc co RB Typedets een eeprom unsigned int eeprom uiB 4 A Headers 4p Global Static Va 51 Bleeprom struct struct5_type tiad B ioh aX eeprom_struc 55 Sarai ane ao B stdarg h X eeprom_uiA 53 struct5 5 aw stdbool h X eeprom_uiB _ 54 while B stdinth SS l while a B stdio h Se Ue B xmbits_al f Function Call Tr E 7 E 57 fe EE E mare B xmegal 2il A main e E E for ca B mstructh 59 eeprom stest p seeprom struct z DSTACK Func 0 60 Other Files a f printf 61 increment some of the bit fields of switch DSTACK Funi 62 jeeprom_struct b Si n fO _print 63 eeprom_struct d S 8 DSTACKF 64 eeprom struct f switch 4 case
110. aws 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 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 the program only by a single person
111. b in the Project Configure window XN Configure Project MULTFILE PRI x Files C Compiler Before Build After Build V Program the Chip F Execute User s Program V Merge data from a ROM File for FLASH Programming ROM File Path cavr projects bootloader bootloader rom 3 Chip Programming Options SCK Freq 230400 Hz v Program Fuse Bit s FLASH Lock Bits T CKSELO 0 A No Protection CKSEL1 0 ne l CKSEL2 0 Programming disabled O CKSEL3 0 Programming and Verification disabled z tae CKOUT 0 Boot Lock Bit 0 Boot Lock Bit 1 cCKDIV8 0 B01 1 BO2 1 B11 1B12 1 BOOTRST 0 0 B02 a0B121 C BOOTSZ1 0 BO1 0 B02 1 B11 0 B12 1 z FESAVE O 0 BO2 B11 0 B12 0 WDTON 0 BO1 0 BO2 0 z JTAGEN 0 B01 1 1118122 OCDEN 0 He p Jik BODLEVELO 0 z V Check Signature Check Erasure Preserve EEPROM V Verify a aa If you check the Program the Chip option 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 1998 2009 HP InfoTech S R L Page 49 CodeVisionAVR The Merge data from a ROM File for FLASH Programming option if checked will merge in the FLASH programming buff
112. 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 AVRISP AVRISP MkII AVR Dragon JTAGICE MkII AVRProg AVR910 application note Kanda Systems STK200 STK300 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 e Philips I C bus e National Semiconductor LM75 Temperature Sensor e Philips PCF 8563 PCF8583 Maxim Dallas Semiconductor DS1302 and DS1307 Real Time Clocks e Maxim Dallas Semiconductor 1 Wire protocol Maxim Dallas Semiconductor DS1820 DS18S20 and DS18B20 Temperature Sensors Maxim Dallas Semiconductor DS1621 Thermometer Thermostat Maxim Dallas Semiconductor DS2430 and DS2433 EEPROMs SPI Power management Delays Gray code conversion CodeVisionAVR also contains the CodeWizardAVR Automatic Program Generator that allows you to write in a matter of minutes all the code needed for implementing the following f
113. be saved by using the File Save menu command by pressing the Ctrl S keys or by pressing the Wf button on the toolbar When saving the Editor will create a backup file with a character appended to the extension All currently opened files can be saved using the File Save All menu command by pressing the Ctrl Shift S keys or the Gil toolbar button 2 2 6 Renaming a File The currently edited file can be saved under a new name by using the File Save As menu command or the i toolbar button A Save As dialog window will open 4 Save C cvavr bin untitled c As rx Save in bin gt O EP iv z Name r Date modified Type Size wA No items match your search Recent Places 1 4 m P File name test c v Save Save as type C Compiler source file c X Cancel You will have the possibility to specify the new name and type of the file and eventually its new location 1998 2009 HP InfoTech S R L Page 27 CodeVisionAVR 2 2 7 Printing a File You can print the current file using the File Print menu command or by pressing the 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 or the toolbar button which opens the Page Setup dialog window HN Page Setup x Printing Options Margins Vi Fage Header left 25 Rie 19 v Page Numbers e7 Top 19 Bottom
114. 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 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 mega8515 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
115. bit wide 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 RAM 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 Declare some strings in EEPROM eeprom char ml1 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 RAM char eeprom pp 2 and initialize the array pp 0 m1 pp 1 m2 1998 2009 HP InfoTech S R L Page 109 CodeVisionAVR Pointers to functions always access the FLASH memory area There is no need to use the flash or __ flash memory attributes 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 i Call the function sum using the pointer i sum ptr 1 2 1998 2009 HP InfoTech S R L Page 110 CodeVisionAVR 3 13 Compiler Directives Compiler specific directives are specified
116. bus can be determined by calling the w1_search function with the Alarm Search ECh command float ds18b20_temperature unsigned char addr this function returns the temperature of the DS18B20 sensor with the ROM code stored in an array of 8 bytes located at address addr The temperature is measured in C In case of error the function returns the value 9999 If only one DS18B20 sensor is used no ROM code array is necessary and the pointer addr must be NULL 0 Prior on calling the the ds18b20_temperature function for the first time the ds18b20_init function must be used to specify the desired temperature measurement resolution If more several sensors are used then the program must first identify the ROM codes for all the sensors Only after that the ds18b20_temperature function may be used with the addr pointer pointing to the array which holds the ROM code for the needed device Example include lt mega8515 h gt specify the Atmega8515 port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ _ wl bit 2 endasm include the DS18B20 functions prototypes include lt ds18b20 h gt include the printf function prototype include lt stdio h gt quartz crystal frequency Hz define xtal 4000000L Baud rate define baud 9600 maximum number of DS18B20 connected to the bus define MAX DEVIC ES 8 DS18B20 devices ROM code storage area 9 bytes are used
117. chips signal handling signal h is not implemented yet date and time functions time h are not implemented yet extended multibyte wide character utilities wchar h are not implemented wide character classification and mapping utilities wctype h are not implemented the printf sprintf snprintf vprintf vsprintf and vsnprintf Standard C Input Output Functions can t output strings longer than 255 characters for the s format specifier e the LCD 1 Wire I2C Philips PCF8563 Philips PCF8583 Maxim Dallas Semiconductor DS1302 DS1307 DS1621 DS2430 DS2433 National Semiconductor LM75 libraries do not yet support the ATxmega chips e the size of the compiled code is limited for the Evaluation version e the libraries for Philips PCF8563 Philips PCF8583 Maxim Dallas Semiconductor DS1302 DS1307 4x40 character LCD functions are not available in the Evaluation version 1998 2009 HP InfoTech S R L Page 132 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 stdlib 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 2009 HP InfoTech S R L Page 133 CodeVisionAVR 4 1 Character Type Functions The
118. code efficiency several memory models are implemented The TINY memory model uses 8 bits for storing pointers to the variables placed in RAM In this memory model you can only have access to the first 256 bytes of RAM The SMALL memory model uses 16 bits for storing pointers the variables placed in RAM In this memory model you can have access to 65536 bytes of RAM In both TINY and SMALL memory models pointers to the FLASH memory area use 16 bits Because in these memory models pointers to the FLASH memory are 16 bits wide the total size of the constant arrays and literal char strings is limited to 64K However the total size of the program can be the full amount of FLASH In order to remove the above mentioned limitation there are available two additional memory models MEDIUM and LARGE The MEDIUM memory model is similar to the SMALL memory model except it uses pointers to constants in FLASH that are 32 bits wide The pointers to functions are however 16 bit wide because they hold the word address of the function so 16 bits are enough to address a function located in all 128kbytes of FLASH The MEDIUM memory model can be used only for chips with 128kbytes of FLASH The LARGE memory model is similar to the SMALL memory model except it uses pointers to the FLASH memory area that are 32 bits wide The LARGE memory model can be used for chips with 256kbytes or more of FLASH In all memory models pointers to the EEPROM memory area are 16
119. code here The pragma vector preprocessor directive and the __interrupt keyword are used for compatibility with other C compilers for the Atmel AVR The pragma keept directive forces a function global variable or global constant to be linked even if it wasn t used anywhere in the program 1998 2009 HP InfoTech S R L Page 113 CodeVisionAVR Example force the next function to be linked even if it s not used pragma keept int funcl int a int b return atb the next function will not be linked if it s not used pragma keep int func2 int a int b return a b 1998 2009 HP InfoTech S R L Page 114 CodeVisionAVR 3 14 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 Ox1111 Write to TCNT1IL amp TCNT1H registers The addresses of I O registers are predefined in the following header files located in the INC subdirectory tinylO h tinyl3 h tiny22 h tiny2313 h tiny24 h tiny25 h tiny26 h tiny261 h tiny44 h tiny45 h tiny461 h tiny48 h tiny84 h tiny85 h tiny86l1 h tiny88 h 90can32 h 90can64 h 90canl128 h 90pwm2 h 90
120. columns of the LCD must be specified e g 16 No cursor is displayed The function returns 1 if the LCD module is detected and 0 if it is not 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 1998 2009 HP InfoTech S R L Page 161 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 RAM 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 1 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 The C Functions functions do not yet support the ATxmega chips Prior to include ing the i2c h file you must declare which microcontroller port and port bits are used for communication through the 1 C bus Examp
121. conversion time for the Accumulate Current output The Regular Current Detection Mode check box specifies that the Coulomb Counter will repeatedly do one instantaneous current conversion before it is turned of for a timing interval specified by the Sampling Interval list box The interval selected using the above mentioned list box includes a sampling time having a typical value of 16ms The Accumulate Current Interrupt check box enable the generation of an interrupt after the accumulate current conversion has completed This interrupt is serviced by the ccadc_acc_isr ISR The Regular Current Interrupt check box enable the generation of an interrupt when the absolute value of the result of the last AD conversion is greater or equal to the values of the CADRCC and CADRDC registers This interrupt is serviced by the ccadc_reg_cur_isr ISR 1998 2009 HP InfoTech S R L Page 225 CodeVisionAVR The Instantaneous Current Interrupt check box enables the generation of an interrupt when an instantaneous current conversion has completed This interrupt is serviced by the ccadc_conv_isr ISR The Regular Charge Current respectively Regular Discharge Current list boxes determine the threshold levels for the regular charge respectively regular discharge currents setting the values for the CADRCC respectively CADRDC registers used for generating the Regular Current Interrupt The Atmega406 datasheet may be consulted for more details about
122. d 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 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 1998 2009 HP InfoTech S R L Page 142 CodeVisionAVR unsigned char isqrt unsigned int x returns the square root of the unsigned integer x unsigned int Isqrt unsigned 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 numb
123. d check box if present 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 The ADC clock frequency can be selected using the Clock list box If you want to generate interrupts when the ADC finishes the conversion then you must check the Interrupt check box 1998 2009 HP InfoTech S R L Page 222 CodeVisionAVR If ADC interrupts are used you have the possibility to enable the following functions e by checking the 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 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 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 w
124. d 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 2009 HP InfoTech S R L Page 204 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 amp CodeWizardAVR test cwp xs File Help External IRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C 1wire 2Wire 120 LCD Bit Banged Project Information External SRAM ii Ports Chip ATmega128 M Clock 4 000000 t MHz Crystal Oscillator Divider Enabled Check Reset Source Program Type Application v 1998 2009 HP InfoTech S R L Page 205 CodeVisionAVR 5 2 Setting the External SRAM For the AVR chips that allow connection o
125. d_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 _CDFRR 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 1998 2009 HP InfoTech S R L Page 242 CodeVisionAVR 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 5 18 Setting the LCD By selecting the LCD tab of the CodeWizardAVR you can specify the LCD configuration amp CodeWizardAVR test cwp File Help External IRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C Bit Banged Project Information Chip ExtemalSRAM Ports 1wire 2Wire 120 LCD Port PORTC Chars Line 16 x PORT Bit0 RAS LCD Pin 4 PORT Bit 1 RD LCD Pin 5 PORT B
126. d_write data 0xe 1998 2009 HP InfoTech S R L Page 155 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 ATmega8515 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 PCI 6 EN 3 PC2 11 D4 5 PC4 12 D5 6 PCS 13 D6 7 PCO 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 0b10000000 0b10001111 0b10000011 0b10000101 0b10001001 0b10010000 0b10100000 0b11000000 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 t 1998 2009 HP InfoTech S R L Page 156 CodeVisionAVR void main void initialize the LCD for 2 lines amp 16 columns lcd init 16 define user character 0 define_char char0 0 switch to
127. dasm include the DS2430 functions include lt ds2430 h gt include lt mega8515 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 2009 HP InfoTech S R L Page 190 CodeVisionAVR char text Hello world char buffer 32 define START ADDR 2 ATmega8515 clock frequency Hz define xtal 4000000L Baud rate define baud 9600 main unsigned char i devices initialize the USART control register TX enabled no interrupts 8 data bits UCSRA 0x00 UCSRB 0x08 UCSRC 0x86 initialize the USART s baud rate UBRRH xtal 16 baud 1 gt gt 8 UBRRL xtal 16 baud 1 amp OxFF 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 the 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 DS
128. data writes a byte to the LCD character generator or display RAM Example LCD user defined characters Chip ATmegaS8515 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 2009 HP InfoTech S R L Page 160 CodeVisionAVR table for the user defined character arrow that points to the top right corner flash byte char0 8 0b10000000 0b10001111 0b10000011 0b10000101 0b10001001 0b10010000 0b10100000 0b11000000 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 att pctt void main void initialize the LCD for 2 lines amp 16 columns lced_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 unsigned char 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
129. 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 2009 HP InfoTech S R L Page 177 CodeVisionAVR 4 13 Maxim 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 The DS1302 RTC Functions functions do not yet support the ATxmega chips 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 ATmega8515 PORTB the IO signal 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 diod
130. debugger is executed by selecting the Tools Debugger menu command or by pressing the W button on the toolbar 1998 2009 HP InfoTech S R L Page 65 CodeVisionAVR 2 4 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 AVRISP MkII AVR Dragon JTAGICE MkII AVRProg AVR910 application note Kanda Systems STK200 STK300 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 Programmer is executed by selecting the Tools Chip Programmer menu command or by pressing the button on the toolbar S CodeVisionAVR Chip Programmer STK500 AVRISP me lt n File Edit Program Read Compare Help Chip ATmega2560 7 E Program All G Reset Chip SCK Freq 57600 v Hz FLASH EEPROM Start 0 h End 1FFFF h Start 0 h End FFF h Checksum 0000h Checksum FOOO0h Chip Programming Options FLASH Lock Bits V Program Fuse Bit s l CKSELO 0 a No Protection I CkKSELI lt 0 Programming disabled z SEE Programming and Verification disabled z a 7 CKOUT 0 Boot Lock Bit 0 Boot Lock Bit 1 7 CKDIV8 0 BO1 1 602 1 Bit 1B12 1 BOOTAST 0
131. 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 2009 HP InfoTech S R L Page 37 CodeVisionAVR 2 3 4 2 Setting the Project Output Directories Selecting the Output Directories tab allows the user to specify distinct directories where will be placed the files resulted after the compilation and linking N Configure Project MULTFILE PRJ Ex Files C Compiler Before Build After Build Input Files Output Directories Executable Files exe E Object Files obj E List Files i list Ee Linker Files _ link is X Cancel 2 Heo Pressing the button allows to select an existing directory The rom and hex files resulted after the Build process will be placed in the Executable Files directory The object files resulted after the Compile process will be placed in the Object Files directory The COFF object file that results after the Build process will be also placed in the Object Files directory The asm lst and map files created during the Build process will be placed in the List Files directory Various files creat
132. during chip programming eeprom char beta eeprom long arrayl 5 T The string is stored in the eeprom char string Hello EPROM during chip programming void main void int i Pointer to EEPROM int eeprom ptr to eeprom Write directly the value 0x55 to the EEPROM alfa 0x55 or indirectly by using a pointer ptr to eeprom amp alfa ptr_ to eeprom 0x55 Read directly the value from the EEPROM i alfa or indirectly by using a pointer i ptr to eeprom Pointers to the EEPROM always occupy 16 bits in memory 1998 2009 HP InfoTech S R L Page 118 CodeVisionAVR 3 16 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 the affected registers when calling 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 correspondi
133. e appropriate file The Code Navigator tree branches can be expanded respectively collapsed by clicking on the respectively buttons By right clicking in the Code 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 currently edited file Close All opened files Toggle on or off alphabetically sorting the files in the Code Navigator Toggle on or off expanding the Errors and Warnings branches after a Compile or Build process Toggle on or off expanding the header file branches 1998 2009 HP InfoTech S R L Page 61 CodeVisionAVR 2 3 5 6 Using the Code Information The Code Information window allows for easy access to declarations and definitions made in the currently edited source file Code Navigator Code Information Function Call Tree Code Templates gt pD led c fan Includes E mega8515 h 40 Macros mal fmove mi xtal be Typedefs b gt abe a b c 3 Ap Global Static Variables X led_status gt RAM O0E0h X w gt EEPROM 0001h X xyz gt not used removed by the linker FQ Functions 0 mainfvoid fO timerl_overflow yvoid The Code Information window is accessed using the tab with the same name and appears after the first Compile or Build process of the currently opened project The information is displayed in the form of a tree with several types of nodes e Includes
134. e ANAN AN NAARAAN ANANN Ra 73 2 5 9 1 General Editor Settings ic oscce eset heii ete en eee ee EEEE 73 2 5 3 2 Editor Text Settings 20 0 ceceeeeeeeeeeeeeeeeneeeeeeeeaeeeeeeaaeeeeeeeaeeeseeeaeeeseeaaeeeesesaeeeeeeneeeeeas 75 2 5 3 3 Syntax Highlighting Settings 0 cc eee nisreen n EENAA EERENS REAN 76 2 5 3 4 Auto Complete Settings ecn vitleccaveticeaviaddicevs tecactapetiadia etd Avetrceave audi ett vate sh glace 77 2 5 4 Setting the Debugger Path s src eee ccceeeeeeeeeetteee ee enneeeee tees ee eaaeeeeetaeeeeeeaeeeseeaeeeenenaeeeeneas 78 2 9 0 AVR Chip Programmer Setup is iad ccecsactowananaactevsanicartanad dived aavaatasaaavedssaanduaeataavaeaseaauieanaadeees 79 2 5 6 Serial Communication Terminal Setup c ccccceceeceeeeeeecneeeeeeeeeesesecaeeeeeeeeeseescsaaeeeeeees 81 2 6 Accessing the Hel Pivi2 vik nae nied ahh eee edie behinds 82 2 7 Transferring or Deactivating the LICENSE eect eter ee eeteee ee etteee ee teeeeeteeeeetiaeeeeetneeeeees 82 2 8 Connecting to HP Info Tech s Web Site c ccciiicecscsieieseetdeeteseclideesacniebesacddbeesandebessetieeeseniaeeess 83 2 9 Quitting the CodeVisionAVR IDE 0 ecccecieeeee tere renner eee ee eet eee ee tieeeeetiieeeeetieeeeennieeeeeiaa 83 3 CodeVisionAVR C Compiler Reference 2 cccccceceseeeseeeceeeeeeeeeeeeneeceeeeeseaseeaneeseeeeeeseeeeeaneeeeeees 84 3 1 The C Preprocessor sisikii band cecuaaneaiavadavexsaduaastasand cecsaaneatiayandvensedueantanandede
135. e 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 2009 HP InfoTech S R L Page 70 CodeVisionAVR Using the Settings button you can modify the e Tool Menu Name e Tool Directory and File Name e Command Line Parameters e Working Directory of a selected Program from the list XN Tool Settings re lt n Tool Name avrasm2 exe Tool Directory and FileName C cvavribinavrasm2 exe 3 Command Line Parameters Working Directory C Aevavr bins 3 ET Changes can be saved respectively canceled using the OK respectively Cancel buttons The command line can accept the following parameters P substitutes the full project path p substitutes the project name without path h substitutes the name of the hex file created by the compiler e substitutes the name of the eep file created by the compiler f lt project_file_number gt substitutes the project s source file name without path F lt project_file_number gt substitutes the project s source file name with full path 1998 2009 HP InfoTech S R L Page 71 CodeVisionAVR 2 5 IDE Settings The CodeVisionAVR IDE is configured using the View and Settings menus 2 5 1 The View Menu The following settings can be configured using the View menu command e The View Visible Non Printable Characters option allows to turn on or off the displaying of non printab
136. e 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 i2c_stop return data T write a byte to the EEPROM void eeprom write unsigned char address unsigned char data i2c_start i2c_ 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 a2 anit 7 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 2009 HP InfoTech S R L Page 163 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 IC 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
137. e Edit Delete menu command by pressing the Ctrl Delete keys or the 7S toolbar button Dragging and dropping with the mouse can move portions of text Pressing the Ctrl Y keys deletes the text line where the cursor is currently positioned Changes in the edited text can be undone respectively redone by using the Edit Undo respectively Edit Redo menu commands by pressing the Ctrl Z respectively Shift Ctrl Z keys or by pressing the respectively buttons on the toolbar Clicking with the mouse right button in the Editor window opens a pop up menu that gives access to the above mentioned functions 1998 2009 HP InfoTech S R L Page 22 CodeVisionAVR 2 2 4 1 Searching Replacing Text You can find respectively replace portions of text in the edited file by using the Search Find respectively Search Replace menu commands by pressing the Ctrl F respectively Ctrl R keys or by pressing the 3 respectively ase buttons on the toolbar The Search Find Next respectively Search Find Previous functions can be used to find the next respectively previous occurrences of the search text The same can be achieved using the F3 respectively Ctrl F3 keys or the A respectively the g toolbar buttons Searching respectively replacing portions of text in files can be performed using the Search Find in Files respectively Search Replace in Files menu commands by pressing the Ctrl Shift F respectively Ctrl Shift H keys o
138. e 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 RAM 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 2009 HP InfoTech S R L Page 149 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 using 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 va
139. e 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 RAM 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 model returns the length of the string str in the range 0 255 excluding the null terminator unsigned int strlen char str for the SMALL memory model returns the length of the string str in the range 0 65535 excluding the null terminator unsigned int strlenf char flash str returns the length of the string str located in FLASH excluding the null terminator 1998 2009 HP InfoTech S R L Page 147 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
140. e 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_counter 1 All serial I O using functions declared in stdio h will be done using UARTO USARTO 1998 2009 HP InfoTech S R L Page 219 CodeVisionAVR 5 7 Setting the Analog Comparator By selecting the Analog Comparator tab of the CodeWizardAVR you can specify the analog comparator configuration amp CodeWizardAVR test cwp File Help 1 Wire LCD Bit Banged Project Information Chip Ports External IRQ Timers US Analog Comparator ADC 12c v Analog Comparator Enabled Inputs AINO AINT z Bandgap Voltage Reference Negative Input Multiplexer Inputs Hysterezis Om v V Analog Comparator Interrupt Analog Comparator Interrupt Mode Interrupt on Output Toggle Interrupt on Falling Output Edge Interrupt on Rising Output Edge Disable Digital Input Buffer on AINO Disable Digital Input Buffer on AIN1 Checking the Analog
141. e 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 2009 HP InfoTech S R L Page 146 CodeVisionAVR char strpbrkf char str char flash set searches the string str located in RAM 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 RAM for the last occurrence of a character 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 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 RAM for the first occurrence of the string str2 located in FLASH If there is a match returns a pointer to th
142. e temperature of sensor 0 10 C t0 lm75 temperature 10 0 300ms delay delay ms 300 read the temperature of sensor 1 10 C tl lm75 temperature 10 1 300ms delay delay ms 300 prepare the displayed temperatures in the display buffer sprintf display buffer t0O S i uScC nt1l S i uScc t0 10 abs t0 10 Oxdf t1 10 abs t1 10 Oxdf display the temperatures led_clear lcd puts display buffer 1998 2009 HP InfoTech S R L Page 166 CodeVisionAVR 4 12 2 Maxim Dallas Semiconductor DS1621 Thermometer Thermostat Functions These functions are intended for easy interfacing between C programs and the DS1621 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 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 C bus Example the I C bus is connected to ATmega8515 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 ds
143. ecccecceceeeeeeeeeaeee cece cece ceaeeaeceeeeeeacecaanaeceseeesadenaneeeeeeeeseusnnaneeeeeees 111 3 14 Accessing the I O Registers sesesctcccaaveededeapetGacisviadibeavaticcastbeteadas eadie ve teteaa yh etdanetecea ed diene 115 3 14 1 Bit level access to the I O ReGiSters eee cece ee settee ee eeneeeeeeaeeeeeeaeeeeeeiaeeeeeeaeeeeeeaas 117 3 15 Accessing the EEPROM sssrinin anns S E venice ban nb AAE NA 118 3 16 Using Interrupts oer tr rr ee ne eee EAA CENA AANER ENEA EKNE ERENER 119 3 17 RAM Memory Organization and Register Allocation cccceeeeeeeeeeeeeeeeeeteteeeeettneeeeeeetieeeeee 121 3 18 Using an External Startup Assembly File 0 00 0 cccecceeeeeeeneeeeeeeneeeeeeeneeeeeeeeeeeesiieeeeetieeeee 124 3 19 Including Assembly Language in Your Program ccccccecceeeeeeeeeeeeeeeeneeeeeetieeeeetiteeeeesneeeeee 126 3 19 1 Calling Assembly Functions from Co cecceeeeeeeeeente eee e tenner ee tenes eeeaeeeeesiaeeeenenaeeeeneaas 127 3 20 Creating Libraries aieiai rrera ENEE Augeste acc panies ee eet ec pees 128 3 21 Using the AVR Studio Debugger sanii aA ANAA A EAA denied 131 3 22 Compiling the Sample Code of the ATxmega Application Notes from Atmel 0 08 132 3 23 FINS 228 aoa a a a eee eee A eta IR 132 3 24 LIMITATIONS tee ne eee eee eee eee ee eee AEEA ENE EEEE eE 132 4 Library Functions Reference cccccsssceccsssseeeeessseneeeeseceeeenseceeeenseceeeeessseeeeessseeeeensseeeeseseseesenseeeens 133 4 1 Cha
144. ected Language Element to the default ones specified in the Text Default Text Color respectively Text Default Background Color settings 1998 2009 HP InfoTech S R L Page 76 CodeVisionAVR The User Defined Keywords list can contain additional keywords for which syntax highlighting is required Their text colors and attributes can be specified when selecting the Language Element as User defined keyword The results of the applied syntax highlighting settings can be viewed in the Sample Text portion of the window 2 5 3 4 Auto Complete Settings The following Editor settings can be established by clicking on the Auto Complete tab SX Editor Settings x General Text Syntax Highlighting Auto Complete Sample Text al Multiple line A v Auto Complete Function Parameters 2 comment 3 Single line comment v Auto Complete Structure or Union Members 4 define MAX a b Delay 5 a gt b a b amp U i Elash char pflash flash int 0 8 eeprom int peeprom eeprom int 0 1 sec 1 5 sec 3 Hint Window 10 E void main void Text Color BB Window Text X 11b t 2 int Number 123 Background Color C Window 13 int HexNumber 0x1FA7 14 float FloatNumber 0 123e 2 A5 char c D 16 char text Hello world YA while Number 4 19 peeprort pflasht 20 Number 21 22 la 4 m p X Cancel a Default Help e Auto Complete Function
145. ed by the linker during the Build process will be placed in the Linker Files directory 1998 2009 HP InfoTech S R L Page 38 CodeVisionAVR 2 3 4 3 Setting the C Compiler Options To set the C compiler options for the currently opened project you must use the Project Configure menu command or the amp amp toolbar button A Configure Project tabbed dialog window will open You must select the C Compiler and Code Generation tabs SM Configure Project MULTFILE PRJ n Fies C Compiler Before Build After Build Code Generation Messages Globally Hdefine Paths RAM Data Stack Size 1024 bytes Heap Size 0 bytes Chip ATmegal 280 Clock 8 000000 4 MHz Memory Model Internal RAM Size 8192 bytes Small External RAM Size 0 bytes Optimize for E External RAM Wait State Speed Code Generation Optimization Level Bit Variables Size 24 x0 Use GPIOR gt 31 Maximal E Promote chartoint V char is unsigned 8 bit enums X Enhanced Core Instructions Smart Register Allocation Santee aana Z Automatic Global Register Allocation s printt Features Store Global Constants in FLASH Memory int width Use an External Startup Initialization File Clear Global Variables at Program Startup Stack End Markers File Qutput Format s COF ROM HEXEEP Program Type s scanf Features int width
146. ed in the comment header located at the beginning of the C source file produced by CodeWizardAVR amp CodeWizardAVR test cwp File Help ExtemalIRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C 1wire 2Wire 20 LCD Chip External SRAM Bit Banged Project Name Test Version 1 0 Date 17 Apr 2008 Author Company Comments You can specify the Project Name Date Author Company and Comments 1998 2009 HP InfoTech S R L Page 246 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 prohibit after sale license agreements or limited disclaimers you must cease and desist using this product immediately This product is Copyright 1998 2009 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 l
147. ee as 4 o 0 main a j 5i E DSTACK Func 0 Total 0 a 5 printf p S DSTACK Func 6 Total 6 E O _print 3 E DSTACK Func 26 Total 32 3 Ft _put 6 E DSTACK Func 7 Total 39 i e 5 f0 putchar wills FA MOTAGY OM 4 Test An Messages clicking on the window s icon will maximize the window CodeVisionAVR C cvavr2 examples atxmega USARTCO File Edit Search View Project Tools Settings Help Bes He aoo s SRS g t nog M A v diay i R Code Information Ga C o O usart c n H A at A Macros A HR Typedets E 5 4F Global Static Variables A H eeprom_struct gt EEPROM 0000h 5 X eeprom_uiA gt notused removed by the 5 X eeprom_uiB gt not used removed bythe 5 H struct3 gt EEPROM 0009h 5 H struct5 gt not used removed by the linker 5 F Functions gt 5t 5 6 6 6 6 6 _ ___ i gt Ille f Function Call Tree 2B Messages Clicking on the icon will normalize the window s size 1998 2009 HP InfoTech S R L Page 16 CodeVisionAVR The menu toolbars can be placed to any position by clicking with the left mouse button on the handle and dragging it while keeping the button pressed If the toolbar is moved outside the menu it will become floating like in the following picture File Edit Search View Project Tools Settings Help ex B S alos eH HPA TF b d RB Code Information E C cva
148. emory I suspicious pointer conversion V register is already allocated v macro was redefined I function must have a return value IV function declared but not referenced I function parameter not referenced IV function parameter name doesn t match it s previous declaration I local variable declared but not referenced I local variable set but not used M local variable is used before it s value is set MV global variable constant declared but not referenced I label declared but not referenced IV empty line IV expression with possibly no effect M unknown escape sequence IV shift result will be 0 M overflow is possible in 8 bit addition X 4 T m X conce 7 Hep The generation of warning messages during compilation can be globally enabled or disabled by using the Enable Warnings check box 1998 2009 HP InfoTech S R L Page 45 CodeVisionAVR The Globally define tab allows to define macros that will be visible in all the project files For example XN Configure Project MULTFILE PRJ Files C Compiler Before Build After Build Code Generation Advanced Messages Globally define Paths ABC 1234 a will be equivalent with placing the macro definition define ABC 1234 in each project s program module 1998 2009 HP InfoTech S R L Page 46 CodeVisionAVR The Paths tabs allows to specify additional paths for include and lib
149. ended_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 include 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 seconds 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 2009 HP InfoTech S R L Page 200 CodeV
150. er 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 mantissa 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 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 1998 2009 HP InfoTech S R L Page 143 CodeVisionAVR 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 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
151. er 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 2009 HP InfoTech S R L Page 217 CodeVisionAVR For devices featuring an USART there will be an additional Mode list box amp CodeWizardAVR test cwp xs File Help Analog Comparator SPI E 1 Wire LCD Bit Banged Project Information Chip ExtemalSRAM Ports External IRQ Timers USART v Receiver v Rs Interrupt Receiver Buffer 8 A v Transmitter J Tx Interrupt Transmitter Buffer 8 vA Baud Rate 9600 x2 Baud Rate Error 0 2 Communication Parameters 8 Data 1 Stop No Parity v Mode Asynchronous Z 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 register s UCPOL bit set to 1 The serial communication is realized using the Standard Input Output Functions getchar gets scanf putchar puts and
152. er 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 You can select the type of the chip you wish to program using the Chip combo box The SCK clock frequency used for In System Programming with the STK500 AVRISP or AVRISP MkIl can be specified using the SCK Freq listbox This frequency must not exceed 1 4 of the chip s clock frequency If the chip you have selected has Fuse Bit s that may be programmed then a supplementary Program Fuse Bit s check box will appear If it is checked than the chip s Fuse Bit s will be programmed after Build The Fuse Bit s 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 you 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 progr
153. es 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 and seconds 1998 2009 HP InfoTech S R L Page 178 CodeVisionAVR Example the DS1302 is connected to ATmega8515 PORTB the IO signal 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 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 rtc_init 1 1 3 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
154. eturns the value 1 on succes and 0 in case of error If only one DS1820 DS18S20 sensor is used no ROM code array is necessary and the pointer addr must be NULL 0 The contents of the SPD will be stored in the structure struct _ds1820 scratch pad struct unsigned char temp lsb temp msb temp high temp_ low resl res2 cnt_rem cnt_c cre __ds1820 scratch_pad defined in the ds1820 h header file 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 measured 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 1998 2009 HP InfoTech S R L Page 182 CodeVisionAVR 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 mega8515 h gt specify the Atmega8515 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
155. ew project Confirm You are about to 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 2009 HP InfoTech S R L Page 32 CodeVisionAVR You must specify the new Project file name and its location SK Create New Project x Save in d examples hd E F p flv P Name Date modified Type Size FZ Ji 2USART_LCD Recent Places M ADC8535 a J AVR134 Jb C_ASM Desktop ps18B20 S D B D51820 J D51990 Pavel JJ EEPROM 7 J KEYPAD ikia J LCDCHAR Computer E LCDDEMO A jp LED J MAX1241 lt Network File name test v Save as type Project files pr Cancel The Project file will have the prj extension You can configure the Project by using the Project Configure menu command or by pressing the toolbar button 1998 2009 HP InfoTech S R L Page 33 CodeVisionAVR 2 3 2 Opening an Existing Project You can open an existing Project file using the File Open menu command or by pressing the amp button on the toolbar An Open dialog window appears 4 Open 2C Lookin ji MULTFILE PB ae he Pp 3 Recent Places Computer A lt Network 4 m p File name MULTFILE 7 Open Files of type Project files prj 7 Cancel You must select the file name of the Project you wish to open By pressing the Open button you will open the Project file
156. f external SRAM you can specify the size of this memory and wait state insertion by selecting the External SRAM tab amp CodeWizardAVR test cwp File Help External IRQ Timers als UART Analog Comparator ADC SPI 12C 1 wire LCD Bit Banged Project Information Chip External SRAM Ports External SRAM size 32k 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 2009 HP InfoTech S R L Page 206 CodeVisionAVR For devices like the ATmega128 that allow splitting the external SRAM in two pages the External SRAM configuration window will look like this amp CodeWizardAVR test cwp Ex File Help External IRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C 1wire 2Wire 20 LCD Bit Bange Project Information Chip External SRAM size 32k v External SRAM page configuration 1100h 1FFFh 2000h 7FFFh Lower wait states Upper wait states new x 2r x 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
157. function in slave mode If the Isb_first parameter is true the data byte sent received on the bus will start with bit O otherwise it will start with bit 7 The mode parameter specifies the SPI clock polarity and phase The SPI_MODE_t data type and SPI modes are defined in the header file xmbits_a1 h SPI_MODE_0_gc for SPI mode 0 SPI_MODE_1_gc for SPI mode 1 SPI_MODE_2_gc for SPI mode 2 SPI_MODE_3_gc for SPI mode 3 If the clk2x parameter is true the SPI master will function in double speed mode 1998 2009 HP InfoTech S R L Page 195 CodeVisionAVR The clock_div parameter specifies the SPI clock prescaler division factor The SPI_PRESCALER_t data type and SPI prescaler values are defined in the header file xmbits_a1 h SPI_LPRESCALER_DIV4_gc for System Clock 4 SPI_LPRESCALER_DIV16_gc for System Clock 16 SPI_LPRESCALER_DIV64_gc for System Clock 64 SPI_PRESCALER_DIV128_gc for System Clock 128 The ss_pin parameter specifies the SPI I O port pin that is used for SS It s values are defined in the header file xmbits_a1 h Example of using the spi function for interfacing to an AD7896 ADC Digital voltmeter using an Analog Devices AD7896 ADC connected to an AT90mega8515 using the SPI bus Chip AT90mega8515 Memory Model SMALL Data Stack Size 128 bytes Clock frequency 4MHz AD7896 connections to the ATmega8515 AD7896 ATmega8515 DIP40 1 Vin 2 Vref 5V 3 AGND 20 GND 4 SCLK 8 SCK 5 SDATA 7
158. g Color E Highlight REg c Ds 16 jchar text Helle world Non Printable Text Color Silver 7 while Number 18 A 19 peeprort t pflash 20 Number 21 he 22 1 Lh 4 m p X cence 38 Det 2 Hep e Auto Indent enables or disables text auto indenting during file editing e Backspace Unindents when enabled sets the Editor to align the insertion point to the previous indentation level outdents it when the user presses the Backspace key if the cursor is on the first nonblank character of a line If this option is disabled pressing the Backspace key just deletes the character located on the left of the cursor e Optimal Fill enables or disables the beginning of every auto indented line with the minimum number of characters possible using tabs and spaces as necessary e Convert Tabs to Spaces enables or disables the automatic replacement while typing of tab characters with the appropriate number of spaces as specified by the Tab Size option e Discard Trailing Spaces enables or disables the automatic deletion from the end of each line of spaces that are not followed by text e Tab Size specifies the number of spaces the Editor cursor is moved when the user presses the Tab key e Block Indent Size specifies the number of spaces the Editor indents a marked block of text e Font specifies the font type used by the Editor e Font Size specifies the font size used by the Editorl e Default Text
159. g int for the i d u x X conversion type characters 1998 2009 HP InfoTech S R L Page 137 CodeVisionAVR 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 dddddd e dd format E the function argument is a float that will be outputted using the d dddddd E dd format f the function argument is a float that will be outputted using the ddd dddddd 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 RAM p the function argument is a pointer to a null terminated char string located in FLASH the 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 st
160. g the Debugger Path The CodeVisionAVR C Compiler is designed to work in conjunction with the Atmel AVR Studio debugger version 4 14 or later Before you can invoke the debugger you must first specify its location and file name using the Settings Debugger menu command SK Debugger Settings Directory and Filename C Program Files Atmel AVR Tools AvrStudiod AVRStudio BS cancel 2 Hep Pressing the E button opens a dialog window that allows selecting the debugger s directory and filename Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2009 HP InfoTech S R L Page 78 CodeVisionAVR 2 5 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 and AVRISP serial connection Atmel AVRISP MkII USB connection Atmel AVR Dragon USB connection Atmel JTAGICE MkIl USB connection Atmel AVRProg AVR910 application note 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 Por
161. h LL Stack End Markers File Output Format s COF ROM HEXEEP Preprocessor Create Preprocessor Output Files Include 1 0 Registers Bits Definitions a A The maximum size of the global bit variables which are placed in the GPIOR if present and registers R2 to R14 can be specified using the Bit Variables Size list box The Use GPIOR gt 31 option when checked allows using GPIOR located at addresses above 31 for global bit variables Note that bit variables located in GPIOR above address 31 are accessed using the IN OUT OR AND instructions which leads to larger and slower code than for bit variables located in GPIOR with the address range 0 31 which use the SBI CBI instructions Also the access to bit variables located in GPIOR above address 31 is not atomic Therefore it is recommended to leave the Use GPIOR gt 31 option not checked if the number of global bit variables is small enough and no additional registers are needed for their storage 1998 2009 HP InfoTech S R L Page 42 CodeVisionAVR 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 increases code size and lowers speed for an 8 bit chip microcontroller like the AVR In order to assure code compatibility with othe
162. hat 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 2009 HP InfoTech S R L Page 212 CodeVisionAVR By selecting the Timer 1 tab you can have the following options amp CodeWizardAVR test cwp l File Help _USART2 USART3 Analog Comparator apc sri lac 1Wite 2 Wire I2C LCD Bit Banged Project Information Chip _EstemalSRAM Ports ExtemallRQ Timers USARTO USART1 Timer 2 Timer3 lajt Clock Source System Clock A Clock Value Timer 1 Stopped z Mode Normal top FFFFh v Out A Discon v Dut B Discon 4 Out C Discon Input Capt I Noise Cancel Interrupt on Timer 1 Overflow Value 0 h Inp Capture 0 h Comp 4 0 h BO h C 0 h 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 inte
163. he 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 outputted to the right of the decimal point The precision specifier has no effect on the c conversion type character The optional l input size modifier specifies that the function argument must be treated as a lon
164. hip 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 2009 HP InfoTech S R L Page 68 CodeVisionAVR If the programmer is an Atmel STK500 AVRISP AVRISP MkII or AVRProg AVR910 application note then an additional menu command is present Read Programmer s Firmware Version It allows reading the major and minor versions of the above mentioned programmers 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 2 4 3 The Serial Communication Terminal 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 3 button on the toolbar The characters can be displayed in ASCII or hexadecimal format The display mode can be toggled using the Hex AS
165. his PORT setting is only Messages 1998 2009 HP InfoTech S R L Page 14 CodeVisionAVR If the user will place the mouse cursor on the vertical bar the hidden window will be displayed for a short amount of time aa 1189 uonsuny i f CodeVisionAVR C cvavr2 examples atxmega USARTCO File Edit Search View Project Tools Settings Help bBec Htaoo mMARS d PAP RROD pf Function Call Tree O main g DSTACK Func 0 Total 0 O printf E DSTACK Func 6 Total 6 O _print 8 DSTACK Func 26 Total 32 fO _put E DSTACK Func 7 Total 39 5 f putchar i DSTACK Func 1 Total 40 48 43 Insert and then will become hidden again In order to lock the temporarily displayed window in position the user must click on the icon 1998 2009 HP InfoTech S R L Page 15 CodeVisionAVR When two workspace windows are docked to the same site one above the other like in the picture below F CodeVisionAVR C cvavr2 examples atxmega USARTCO File Edit Search View Project Tools Settings Help BeGeS HBaECOMARS eH A PAM F220 0 R Code Information z C eB usartc aii Al Includes 4i 28 Macros allla HR Typedefs E 5 4F Global Static Variables ai 5 X eeprom_struct gt EEPROM 0000h 5 X eeprom_uiA gt not used removed by 5 i X eeprom_uiB gt notused removed by 5 m b 5 f Function Call Tr
166. his option will highlight the source line where the previous declaration or definition was made After the build process is completed an Information window will open showing the build results Pressing the Compiler tab will display compilation results a Information x Compiler Assembler Programmer Chip ATmega8515 Clock frequency 3 686400 MHz Program type Application Memory model Small Optimize for Size s printf features int width s scanf features int width Promote char to int No char is unsigned Yes global const stored in FLASH No 8 bit enums Yes Enhanced core instructions On Automatic register allocation Off 201 line s compiled No errors 1 warnings Bit variables size 0 byte s Data Stack area 60h to DFh Data Stack size 128 byte s Estimated Data Stack usage 4 byte s RAM Global variables area E0h to EOh RAM Global variables size 1 byte s Hardware Stack area E1h to 25Fh Hardware Stack size 383 byte s Heap size 0 bytefs EEPROM usage 0 byte s 0 0 of EEPROM Program size 131 words 262 bytes 3 2 of FLASH Program the chip 1998 2009 HP InfoTech S R L Page 57 CodeVisionAVR Pressing the Assembler tab will display assembly results Information Compiler Assembler Programmer AVRASM AVA macro assembler 2 1 9 build 90 Jul 5 2006 11 06 16 Copyright C 1995 2006 ATMEL Corporation
167. ia this union will occupy 2 bytes in RAM as the bit field data 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 e this union will occupy 4 bytes in RAM 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 1 unsigned long c 6 bits 15 bits 10 31 are not used F3 1998 2009 HP InfoTech S R L Page 102 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 memory attribute gt 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 jJanuary 1 february march april may june july august september october november december months of year void main the
168. ill 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 use 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 c
169. ill use an additional interrupt service routine adc_isr This routine will store the conversion result in the adc_data global variable 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 For some chips 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 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 2009 HP InfoTech S R L Page 223 CodeVisionAVR 5 9 Setting the ATmega406 Voltage Reference Some AVR chips like the Atmega406 contain a low power precision bang gap voltage reference which can be configured by selecting the Voltage Reference tab of the CodeWizardAVR amp CodeWizardAVR test cwp File Help ala J _1Wite 2Wie l2C LCD Bit Banged Project Information Chip Ports External IRQ Timers ADC Voltage Reference Coulomb Counter v Voltage Reference Enabled Voltage Calibration ft x m Temperature Gradient Adjustment CC 15t 3C T 60T U Checking the Voltage Reference Enabled check box enables the precision voltage reference The
170. in FLASH 1998 2009 HP InfoTech S R L Page 159 CodeVisionAVR 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 The LCD functions do not yet support the ATxmega chips These functions can be used only with AVR chips that allow using external memory devices 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 LCD_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
171. initialize the I C bus i2c init 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 temperature display loop while 1 read the temperature of DS1621 0 10 C tO dsl621 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 tO S i uScC nt1l S i uScc t0 10 abs t0 10 Oxdf t1 10 abs t1 10 Oxdf display the temperatures led_clear lcd puts display buffer 1998 2009 HP InfoTech S R L Page 169 CodeVisionAVR 4 12 3 Philips PCF8563 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the PCF8563 C bus real time clock RTC The prototypes for these functions are placed in the file pef8563 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 pcf8563 h file you must declare which microcontroller port and port bits are used for communication with the PCF8563 through the IC bus Example the I C bus is connected to ATmega8515 PORTB the SDA signal is bit 3
172. ion for an ATtiny2313 chip which has GPIORO GPIOR1 and GPIOR2 registers bit alfa 1 bitO of GPIORO bit beta bitl of GPIORO void main void if alfa beta beta Memory allocation for the global bit variables is done in the order of declaration starting with bit O of GPIORO then bit 1 of GPIORO and so on in ascending order After all the GPIOR registers are allocated further bit variables are allocated in R2 up to R14 If the chip does not have GPIOR registers the allocation begins directly from register R2 The size of the global 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 global bit variables are automatically set to 0 at program startup The compiler allows also to declare up to 8 local bit variables which will be allocated in register R15 Example void main void bit alfa bit 0 of R15 bit beta bit 1 of R15 AR uate eects In expression evaluation bit variables are automatically promoted to unsigned char As there is no support for the bit data type in the COFF object file format the CodeVisionAVR compiler generates debugging information for the whole register where a bit variable is located Therefore when watching bit variables in the AVR Studio
173. ionAVR 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 Variable Identifiers can have up to 64 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 bool Bool 8 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 not allowed as the type of an array element or structure union member If the Project Configure C Compiler Code Generation char is unsigned option is checked or pragma uchart is used then char has by default the range 0 255 1998 2009 HP InfoTech S R L Page 90 CodeVisionAVR 3 6 Constants Integer or long integer constants may be written in decimal form e g 1234 in binary f
174. ional Semiconductor LM75 Temperature Sensor Functions c ceceeseeeeeeeees 164 4 12 2 Maxim Dallas Semiconductor DS1621 Thermometer Thermostat Functions 167 4 12 3 Philips PCF8563 Real Time Clock FUNCtiONS ccccecceceeeeeeeeeeeeeeeeeeeeeeeeeettennaeeeeees 170 4 12 4 Philips PCF8583 Real Time Clock FUNCtiOns c cceccceeeeeeeeeeceeceeeeeeeeeeteenennaneeeees 173 4 12 5 Maxim Dallas Semiconductor DS1307 Real Time Clock Functions 0 c eceee 176 4 13 Maxim Dallas Semiconductor DS1302 Real Time Clock Functions 178 4 14 1 Wire Protocol FUNCTIONS 000 0 eee ee eeeee ee eeeene ee teee eee eeeaaeeeeeneaeeeeeeaaeeeeecaeeeseeiaeeeseeiaeeeeenaes 180 4 14 1 Maxim Dallas Semiconductor DS1820 DS18S20 Temperature Sensors Functions 182 4 14 2 Maxim Dallas Semiconductor DS18B20 Temperature Sensor Functions 05 186 4 14 3 Maxim Dallas Semiconductor DS2430 EEPROM Functions 189 4 14 4 Maxim Dallas Semiconductor DS2433 EEPROM Functions 192 4 15 SPI Functions 00 0 eee eee reenter rene nant t uuant Enun ae eee eaae ee eenaaeeeeeeeaaeeeseedaeeeeeeaeeessieeeeeeaes 195 4 16 Power Management Fun ctions ccccceeeeeeneeeeeeeene ee eeeeaeeeeeeaaeeeeeeaaeeeeeenaeeeeeeeaeeeeeeneeeesenas 199 4 17 Delay FUN ction 0 0 cecce cece eee eenee teen eae ee ANAN ANANEK NARRAN AKNA KRAN AEEA AEA EEEN R AARAA ANENA EAE EARANN RAEE 200 5 CodeWizardAVR Automatic Program Generator s
175. is function sets the alarm date of the RTC 1998 2009 HP InfoTech S R L Page 175 CodeVisionAVR 4 12 5 Maxim 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 connected to Atmega8515 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 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 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
176. isionAVR 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 PCF8563 PCF8583 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 clicking on the toolbar button The File New menu command or the D toolbar button allow creating a new CodeWizardAVR project This project will be named by default untitled cwp The File Open menu command or the toolbar button allow loading an existing CodeWizardAVR project 4 Open Project Lookin J bin 02 amp fr I Name n Date modified Type a _ test 17 Apr 08 15 01 CodeWizardAVR project file Recent Places Desktop Computer A Network 4 i p File name test hd Open Files of type CodeWizardAVR project files cwp
177. isted in the Message window located under the Editor window or in the Code Navigator window Messages Warning C cvavrsexamples LED led c 32 global variable xyz declared but not referenced By left clicking with the mouse on the error or warning message the source line with the problem will be highlighted Right clicking with mouse opens a pop up menu that contains the option to Copy the error message to the clipboard Messages 32 global variable xyz declared but not referenced Warning C cvavrvexamples Copy The Project Go to Next Error respectively Project Go to Previous Error menu commands the F8 respectively Ctrl F8 keys or the respectively E toolbar buttons allow moving to the next respectively previous error message The Project Go to Next Warning respectively Project Go to Previous Warning menu commands the F4 respectively Ctrl F4 keys or the B respectively B toolbar buttons allow moving to the next respectively previous warning message If the message refers also to a previous declaration or definition from a file that is different than the one where the error was signaled right clicking with the mouse opens a pop up menu with the Jump to Previous Declaration or Definition option Messages previous declaration from file C cvavrexamples MULTFILE Mfile1 h line 3 3 function parameter 1 doesn t match it s Jump to Previous Declaration or
178. it2 EN LCD Pin 6 PORT Bit 3 Free PORT Bit 4 DB4 LCD Pin 11 PORT Bit 5 DB5 LCD Pin 12 PORT Bit 6 DB6 LCD Pin 13 PORT Bit 7 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 2009 HP InfoTech S R L Page 243 CodeVisionAVR 5 19 Setting the USB Controller By selecting the USB tab of the CodeWizardAVR you can specify the configuration of the USB controller for the AT9OUSB646 AT90USB647 AT90USB1286 and AT90USB1287 chips The USB controller can operate in two modes Device and Host specified using the Operating Mode list box amp CodeWizardAVR test cwp File Help ExtemalIRGQ Timers USART1 _ Analog Comparator ADC SPI 12c Bit Banged Project Information Chip ExtemalSRAM Ports Operating Mode Device z Fu OTG F USB Pad Regulator UYCON UYCON Hardware Control General Int SRP SRP Method Data line pulsing Low Speed Mode Device Int m Suspend Endpoint O0 pA Endpoint Enable Endpoint Cfg Control OUT ka Endpoint Size 8 x Banks 1 pA The operation of the USB controller in both modes and the various settings for them are desc
179. l AVR Studio debugger version 4 14 or later The compiler will generate for the AVR Studio debugger an extended COFF object file that allows watching structures and unions AVR Studio 4 prior to version 4 06 does not support the extended COFF object file format so it can t be used with CodeVisionAVR 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 C Compiler Code Generation menu option The AVR Studio Debugger is invoked using the Tools Debugger menu command or the toolbar button After AVR Studio is launched the user must first select File Open File Ctr O keys in order to load the COFF file to be debugged After the COFF file is loaded and no AVR Studio project file exists for this COFF file the debugger will open a Select device and debug platform dialog window In this window the user must specify the Debug Platform ICE or AVR Simulator and the AVR Device type Pressing the Finish button will create a new AVR Studio project associated with the COFF file If an AVR Studio project associated with the COFF file already exists the user will be asked if the debugger may load it Once the program is loaded it can be launched in execution using the Debug Run menu command by pressing the F5 key or by pressing the Run toolbar button Program execution can be stopped at any time using the Debug Break menu command by pressing Ctrl F5 keys or by
180. l mjnjo Piqiris tijujviw xiy z iF 71 SLOPES TEE UP Pye ry ry rye 1j j EU j eJ j S 7 j lt sgpggmggAggonnnap A AIAIAIAAICIEEJE E I I 1 1 NOOGOOxGBUUUUY PB a 4 amp SBec eee eiiii l l l l l l l l Py This function is also available in the pop up menu invoked by mouse right clicking in the Editor window 1998 2009 HP InfoTech S R L Page 25 CodeVisionAVR 2 2 4 9 Using the Auto Complete Functions The CodeVisionAVR Editor has the possibility to display pop up hint windows for function parameters and structure or union members These functions can be enabled and configured using the Settings Editor Auto Complete menu Function parameter auto complete is automatically invoked when the user types the name of a function defined in the currently edited file followed by a auto completion triggering character A pop up hint with parameter list will show like in the example below int aint b int c fool The parameter to be specified is highlighted with bold text Structure or union members auto complete is invoked after the user writes the name of a structure union or pointer to structure union followed by the or gt auto completion triggering characters A pop up hint with the members list will show like in the example below structl The user can select the member to be inserted in the text at the cursor position by using the arrow keys respectively
181. ld be disabled if the program was developed using CodeVisionAVR prior to V1 25 3 and it contains inline assembly code that accesses the variables located in registers R2 to R14 and R16 to R21 The registers in the range R2 to R14 not used for bit variables can be automatically allocated to char and int global variables and global pointers by checking the Automatic Global Register Allocation check box If the Store Global Constants in FLASH Memory check box is checked the compiler will treat the const type qualifier as equivalent to the flash memory attribute and will place the constants in FLASH memory If the option is not checked constants marked with the const type qualifier will be stored in RAM memory and the ones marked with the flash memory attribute will be stored in FLASH memory The Store Global Constants in FLASH Memory option is by default not enabled for newly created projects In order to maintain compatibility with V1 xx projects the Store Global Constants in FLASH Memory option must be checked An external startup asm file can be used by checking the Compilation Use an External Startup File check box The Clear Global Variables at Program Startup check box allows enabling or disabling the initialization with zero of global variables located in RAM and registers R2 to R14 at program startup after a chip reset If an external startup asm file is used this option must signal to the compiler if the variable initialization with
182. le 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 Functions include lt i2c h gt The lC Functions are void i2c_init void this function initializes the 1 C 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 1998 2009 HP InfoTech S R L Page 162 CodeVisionAVR 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 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 C EEPROM 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 Functions include lt i2c h gt function declaration for delay ms include lt delay h gt T define EEPROM BUS ADDRESS 0xa0 read a byte from th
183. le e Collapse Mark Text specifies the text foreground color of the collapse marks e Collapse Mark Bg specifies the text background color of the collapse marks e Block Staples Color specifies the foreground color of the folding block staples The background color of the staples will be the same as the Default Background Color of the Editor window e Matching Brace Text specifies the text foreground color of the matching braces which are automatically highlighted by the Editor when the user places the cursor before them e Matching Brace Bg specifies the text background color of the highlighted matching braces 1998 2009 HP InfoTech S R L Page 74 CodeVisionAVR 2 5 3 2 Editor Text Settings The following Editor settings can be established by clicking on the Text tab Editor Settings al General Text Syntax Highlighting Auto Complete Sample Text 2 Multiple line A v Auto Indent V Backspace Unindents comment Optimal Fill v Convert Tabs to Spaces v Discard Trailing Spaces Tab Size 4 vA Block Indent Size 4 WA 7 flesh char pflash flash int 0 0 8 jeeprom int peeprom eeprom int Fon Wp Courier New v Font Size 8 x m Default Text Color p Window Text X 10 H void main void E 11 i Default Background Color C Window v 12 int Number 123 Br ee 13 jint HexNumber 0x1FA7 Highlighted Text Color C Highlight Text v 14 Fost Winctiioskear 0 123612 Highlighted Back
184. le characters in the Editor window The T toolbar button can be also used for this purpose e The View Toolbar option allows to turn on or off the displaying of the various toolbars containing the IDE command buttons e The View Code Navigator Code Information Code Templates Clipboard History option allows to turn on or off the displaying of the Navigator Code Templates and Clipboard History window at the left of the Editor window The toolbar button can be also used for this purpose e The View Messages option allows to turn on or off the displaying of the Message window located under the Editor window The toolbar button can be also used for this purpose e The View Information Window after Compile Build option allows to turn on or off the displaying of the Information window after the Compile or Build processes 2 5 2 General IDE Settings Some general IDE settings can be specified using the Settings IDE menu or the toolbar button These settings are Load Last Used Project at Startup Show Hint for the Code Navigator window Show Hint for the Code Information window Show Hint for the Function Call Tree window The settings can be enabled or disabled by checking or unchecking the appropriate check boxes r RE IDE Settings v Load Last Used Project at Startup Show Hints v Code Navigator J Code Information v Function Call Tree Changes can be saved respectively canceled using the OK re
185. leaning Up the Project Output DirectorieS sssseeesssesssrresesrnaenssnnnneennaanannaatennaannanna 60 2 3 5 5 Using the Code Navigator nsss aa A e ARARA a tindilli 61 2 3 5 6 Using the Code Information cece ee etneeeeeenneeeee tates eeeaeeeeeeaeeeeeeaeeeeeenaeeeeneaas 62 2 3 0 Using the Function Call Tree enensenccecarcrconirriiiiirtii nun 63 2 3 6 Closing a PLOjOCt eee etree eet ener aa E E REEERE EAA sieeeeeeea 64 2 A TOONS css cies eieeh aeliel vai int a he ate eee ne Bie se ed St eee 65 24 1 The AVR Studio DGDUQGEN ec iiccsetcceducteacisuenacecuuanet caeet acdevyant gontuuaned desided ARAN AERES 65 2 4 2 THE AVR Chip Programmel iccciecsitcccheedcecagssseceeshesteechacdeecagvsnecsenostecdegesdacesayastecseneseeeeaiie 66 2 4 3 The Serial Communication Terminal 0 0 cccccceeccneeeee eens ee ecneeeeeenneeeeeenneeeeeetiieeeeeeneeeee 69 2 4 4 Executing User Programs cccccccceeecicneee etnies etnies erties ee ANANA NETERA ANANE NA EENAA ATEKA AA 70 2 4 5 Configuring the Tools MENU sssrinin naain R AREE 70 2 9 IDE Settings cic esscts tend siatecnnweaee edb aE aiecaeeatie edd Aaaknead ha steead Sesiesaeh gener sag ested Sreknsaeee dace akon 72 1998 2009 HP InfoTech S R L Page 3 CodeVisionAVR LoT TAG VIEW MGM erris Ea ested ecsvitacacetuatecensuetedeeddee EE aveea cdeeddasestae 72 2 9 2 General IDE SOS endea a Linced Peceeatd EE E EEEE 72 2 5 3 Configuring the Editor 2 0 00 iter inner eerie erie e
186. les atxmega USARTCO usart p File Edit Search View Project Tools Settings Help gt o H aca magana aP A Add or Remove Buttons 7 R Code Information Mo New b cvavn a m Open Notes H H Includes f vy oe R e ee cA Macros A A E 4 sei HR Typedefs M E save b ee T Global Static Vif v g Save As h alee X eeprom_stry i2 i All pm XK eeprom iA Save 3 LX eaprom_uiBe C Close 4 HX struct gt EEfv Close All Ei gt i E a loma noi Convert to Library h lwo j m Page Setup eat b 8 9 eej Mm Print Preview lp M amp Print A o2 ee 63 ee The visibility state of the toolbars can be also individually modified by right clicking with the mouse on the button A drop down menu will open for this purpose D usart prj usart c Help 1S cal File Ja 7 Edit E M Search f 7 M View mples al Project le Tools a ee Settings bm str V Help bm uns T 51 i str 52 All the workspace layout will be automatically saved at program exit and restored back on the next launch 1998 2009 HP InfoTech S R L Page 18 CodeVisionAVR The Editor uses a tabbed multiple window interface The following key shortcuts are available e Ctrl TAB switch to the next editor tabbed window e Ctrl Shift TAB switch to the previous editor tabbed window e Ctrl F4 close the current editor tabbed window The current editor tabbed wi
187. lied with the compiler distribution and is located in the BIN directory Here s the content of this file CodeVisionAVR C Compiler C 1998 2008 Pavel Haiduc HP InfoTech s r l EQU CLEAR START 0X60 START ADDRESS OF RAM AREA TO CLEAR SET THIS ADDRESS TO 0X100 FOR THE ATmegal28 OR ATmega64 CHIPS EQU _ CLEAR SIZE 256 7 SIZE OF RAM AREA TO CLEAR IN BYTES e CLI DISABLE INTERRUPTS CLR R30 OUT EECR R30 DISABLE EEPROM ACCESS DISABLE THE WATCHDOG LDI R31 0x18 OUT WDTCR R31 OUT WDTCR R30 OUT MCUCR R30 MCUCR 0 NO EXTERNAL RAM ACCESS CLEAR R2 R14 LDI R24 13 LDI R26 2 CLR R27 CLEAR REG ST X R30 DEC R24 BRNE CLEAR REG 1998 2009 HP InfoTech S R L Page 124 CodeVisionAVR CLEAR RAM LDI R24 LOW CLEAR SIZE T LDI R26 LOW CLEAR STAR LDI R27 HIGH CLEAR STA CLEAR RAM ST X R30 SBIW R24 1 BRNE CLEAR RAM GLOBAL VARIABLES INITIALIZA GLOBAL IN LDI R31 HIGH GLOBAL INI NEXT ADIW R30 1 MOV R24 R0 LPM ADIW R30 1 MOV R25 R0 SBIW R24 0 BREQ GLOBAL INI END LPM ADIW R30 1 MOV R26 RO LPM ADIW R30 1 MOV R27 R0 LPM ADIW R30 1 MOV R1 RO LPM ADIW R30 1 MOV R22 R30 MOV R23 R31 MOV R31 RO0 MOV R30 R1 GLOBAL _INI_LOOP ADIW
188. line number in the edited file by using the Edit Goto Line menu command by pressing the Ctrl G keys or the B toolbar button After a jump to a specific line was performed the Edit Go Back menu command or the toolbar button allow to return to the previous position in the file The Edit Go Forward menu command or the E toolbar button allow to return to the file position before the Edit Go Back menu command or the toolbar button were used These functions are also available in the pop up menu invoked by mouse right clicking in the Editor window 2 2 4 4 Printing a Text Selection Portions of text can be selected by dragging with the mouse The Edit Print Selection menu command or the amp toolbar button allows the printing of the selected text This function is also available in the pop up menu invoked by mouse right clicking in the Editor window 2 2 4 5 Indenting Unindenting a Text Selection Portions of text can be selected by dragging with the mouse Selected portions of text can be indented respectively unindented using the Edit Indent Selection respectively Edit Unindent Selection menu commands by pressing the Ctrl l respectively Ctrl U keys or the respectively toolbar buttons These functions are also available in the pop up menu invoked by mouse right clicking in the Editor window 2 2 4 6 Commenting Uncommenting a Text Selection Portions of text can be selected by dragging with the mouse Selected
189. lobal char and int variables and pointers Registers R16 to R21 are allocated for local char and int variables e reduced core ATtiny10 the compiler uses the following registers R16 R17 R22 R23 R24 R25 R26 R27 R28 R29 R30 and R31 No registers may be allocated by the compiler for global and local bit variables Registers R18 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 The Data Stack area is used to dynamically store local variables passing function parameters and saving registers during interrupt routine servicing e standard core RO R1 R15 R22 R23 R24 R25 R26 R27 R30 R31 and SREG e reduced core R16 R17 R22 R23 R24 R25 R26 R27 R30 R31 and SREG The Data Stack Pointer is implemented using the Y register At start up the Data Stack Pointer is initialized with the value 5Fh or FFh for some chips Data Stack Size When saving a value in the Data Stack the Data Stack Pointer is decremented When the value is retrieved the Data Stack Pointer is 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 The Global Variables area is
190. m a C program function in assembler declaration this function will return atbt c 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 r34 727 ld r26 y R26 c clr r27 promote unsigned char c to int add r30 r26 R31 R30 R31 R30 c adc r31 r27 endasm pragma warn enable warnings void main void int rx now we call the function and store the result in r r sum_abc 2 4 6 The compiler passes function 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
191. matic variables saved in the Data Stack to be watched in AVR Studio 4 15 or later After finishing debugging the program this option should be disabled and the project rebuild This will allow to reduce the size of the program and increase it s execution speed 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 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 I 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
192. meric 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 The LCD functions do not yet support the ATxmega chips 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 RD pin 5 bit 1 EN pin 6 bit 2 DB5 pin 12 DB6 pin 13 bit 6 DB7 pin 14 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 Example enables the displaying of the cursor _lcd_ready _lc
193. mory block allocated in the heap The ptr pointer must point to a block of memory previously allocated in the heap The size argument specifies the new size of the memory block On success the function returns a pointer to the start of the newly allocated memory block the contents of the previously allocated block being copied to the newly allocated one If the newly allocated memory block is larger in size than the old one the size difference is not filled with zeroes If there wasn t enough contiguous free memory in the heap to allocate the function returns a null pointer void free void ptr frees a memory block allocated in the heap by the malloc calloc or realloc functions and pointed by the ptr pointer 1998 2009 HP InfoTech S R L Page 141 CodeVisionAVR After being freed the memory block is available for new allocation If ptr is null then it is ignored 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 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 signe
194. n 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 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 2009 HP InfoTech S R L Page 199 CodeVisionAVR void ext
195. n 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 SK Save C cvavr work untitled c As x Savein inc amp fv r Name 7 Date modified Type Size ay 1WIRE 01 Mar 01 03 15 C compiler header s Recent Places 5 43U5B355 05 Mar 07 13 39 C compiler header a 76C711 05 Mar 07 13 40 C compiler header __ 86RF401 05 Mar 07 13 41 C compiler header Desktop 9008534 05 Mar 07 13 55 C compiler header 90can32 05 Mar 07 14 03 C compiler header J __ 90can64 05 Mar 07 14 07 C compiler header Pavel 90can128 05 Mar 07 14 08 C compiler header L 90pwm2 05 Mar 07 14 10 C compiler header A __ 90pwm2b 05 Mar 07 14 12 C compiler header Computer 90pwm3 05 Mar 07 14 13 C compiler header E __ 90pwm3b 05 Mar 07 14 15 C compiler header A 90owm216 17 Apr 07 14 12 C compiler header 5 4 w p Network File name mylib v Save Save as type c Compiler header file h v l Cancel 1998 2009 HP InfoTech S R L Page 128 CodeVisionAVR 2 Create the library file Select the File New menu command or press the New toolbar button The following dialog window will open BD Create New File E
196. ndow can be also closed by clicking on the icon located on the top right of the tabbed control 1998 2009 HP InfoTech S R L Page 19 CodeVisionAVR 2 2 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 2 1 Creating a New File You can create a new source file using the File New menu command by pressing the Ctrl N keys or the 5D button on the toolbar A dialog box appears in which you must select File Type Source and press the Ok button Create New File E File Type 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 or the i toolbar button 1998 2009 HP InfoTech S R L Page 20 CodeVisionAVR 2 2 2 Opening an Existing File You can open an existing file using the File Open menu command by pressing the Ctrl O keys or the amp button on the toolbar An Open dialog window appears E Open Ea Lookin LED Q F W ii z Name Date modified Type Size wA led 29 03 2007 13 50 C compiler source file Recent Places Computer A Network 4 Ai p File name LED hd Open Files of type C Compiler source files c v Cancel You must select the name and type of file you wish to open By pressing the Open button you will open the file
197. ng bits in the peripheral control registers to configure the interrupt system and enable the interrupts Another possibility to declare an interrupt service routine is by using the pragma vector preprocessor directive and the __interrupt keyword pragma vector is used for specifying that the next declared function is an interrupt service routine Example Vector numbers are for the AT90S8515 Specify the vector number using the pragma vector directive pragma vector 2 Called automatically on external interrupt _ interrupt void external _intO void Place your code here Specify the vector number using the pragma vector directive pragma vector 8 Called automatically on TIMERO overflow _ interrupt void timer0 overflow void Place your code here The pragma vector preprocessor directive and the __interrupt keyword are used for compatibility with other C compilers for the Atmel AVR 1998 2009 HP InfoTech S R L Page 119 CodeVisionAVR The automatic saving and restoring of registers affected by the interrupt handler 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 interrupt handler for example R30 R31 and SREG asm push r30 push r31 in r30
198. nt abc 3 1 2 3 The first two elements will be 1 and 2 the rest will be 0 const int integer array2 10 1 2 multidimensional array const int multidim array 2 3 1 2 3 4 5 6 If the Project Configure C Compiler Code Generation Store Global Constants in FLASH Memory option is enabled global constants that were declared using the const keyword will be placed by the compiler in FLASH memory If the above option is not enabled global constants declared using the const keyword will be located in RAM memory Local constants will be always placed in RAM memory 1998 2009 HP InfoTech S R L Page 91 CodeVisionAVR The flash or __ flash keywords can be used to specify that a constant must be placed in FLASH memory no matter what is the state of the Store Global Constants in FLASH Memory option flash lt type definition gt lt identifier gt constant expression _ flash lt type definition gt lt identifier gt constant expression 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 flash char string constantl This is a string constant located in FLASH The constant literal char strings enclosed in double quotation marks that are passed as function arguments are stored in the memory type pointed by the pointer used as function parameter
199. o any position in the main application window or even to another docked window In order to dock the window it s top bar must be dragged keeping the left mouse button pressed until it s future docked position is outlined like in the picture below File Edit Search View Project Tools S bee Hwado M g dA h AAD nR R Code Information E 3 oD usarte A Includes cA Macros CA cvavr2 e a Project sart F Notes 7 ft _put L DSTA B Errors LA Wwarninne When the mouse button will be released the window will become docked 1998 2009 HP InfoTech S R L Page 12 CodeVisionAVR If the window is desired to be docked to another docked window the future position of the window will be that of a tabbed page like in the picture below File Edit Search View Project Tools Settings Help Dee Hygoi g a e asl AHE v t ee oy R Code Information tome x ale PIAN 4 C cvavr2 examples atxmega USAR FG usartc Notes usare OO A Includes eeprom unsigned int eeprom T Macros eeprom struct3 _type struct RB Typedets EA g md Global Static Variables z g cde Navigator eeprom_struct gt EEPROM 0000h ed ini eeprom_uiA gt not used removed by M CodeVisionAVR X eeprom_uiB gt notused removed by 2 a Project
200. oad Save settings e Visual Aids settings The File Load Save settings allow for the following options to be set e Auto Load Modified Files enables or disables the automatic reloading in the CodeVisionAVR Editor of source files that were externally modified by some other program another editor for example If this option is disabled the user will be prompted before the modified file will be reloaded in the Editor e Create Backup Files enables or disables the creation of backup copies of the files modified in the Editor Backup copies will have the character appended to their extension e Auto Save Interval specifies at which time interval all the modified source files will be automatically saved by the Editor 1998 2009 HP InfoTech S R L Page 73 CodeVisionAVR The Visual Aids settings allow for the following options to be set e Show Line Numbers enables or disables the displaying of line numbers on the gutter located on the left side of the Editor windows e Save Bookmarks enables or disables saving the bookmarks set in each edited source file e Enable Code Folding enables or disables displaying of staples on the left side of code blocks delimited by the characters If this option is enabled block collapse expansion marks will be also displayed on the gutter located on the left side of the Editor window e Save Folded Lines enables or disables saving the state of the folded blocks of lines for each edited source fi
201. ode Templates window Move Up in the list the currently selected code template Move Down in the list the currently selected code template Delete the currently selected code template from the list 1998 2009 HP InfoTech S R L Page 30 CodeVisionAVR 2 2 11 Using the Clipboard History The Clipboard History window allows viewing and accessing text fragments that were recently copied to the clipboard Function Call Tree Code Templates Clipboard History 4 gt interrupt TIM1 OVF void timeri_ over void main void t By right clicking in the Clipboard History window you can open a pop up menu with the following choices e Copy to the Edit Window the currently selected text fragment from the Clipboard History window e Delete the currently selected text fragment from the list e Delete All the text fragments from the list 1998 2009 HP InfoTech S R L Page 31 CodeVisionAVR 2 3 Working with Projects The Project groups the source file s and compiler settings that you use for building a particular program 2 3 1 Creating a New Project You can create a new Project using the File New menu command or by pressing the O button on the toolbar A dialog box appears in which you must select File Type Project and press the OK button D Create New File Ex File Type Project X Cancel A dialog will open asking you to confirm if you would like to use the CodeWizardAVR to create the n
202. oid 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 void malloc unsigned int size allocates a memory block in the heap with the length of size bytes On success the function returns a pointer to the start of the memory block the block being filled with zeroes The allocated memory block occupies size 4 bytes in the heap This must be taken into account when specifying the Heap size in the Project Configure C Compiler Code Generation menu If there wasn t enough contiguous free memory in the heap to allocate the function returns a null pointer void calloc unsigned int num unsigned int size allocates a memory block in the heap for an array of num elements each element having the size length On success the function returns a pointer to the start of the memory block the block being filled with zeroes If there wasn t enough contiguous free memory in the heap to allocate the function returns a null pointer void realloc void ptr unsigned int size changes the size of a me
203. or the Tout output The DS1621 devices are accessed through the Maxim Dallas Semiconductor DS1621 Thermometer Thermostat functions 1998 2009 HP InfoTech S R L Page 232 CodeVisionAVR 5 13 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 test cwp File Help ExtemalIRQ Timers USARTO USART1 1wire 2Wire l2C LCD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI 2C 12C Port PORTA SDABit Q SCLBit 1 7 Enabled CLKOUT OFF Alarm Interrupt Timer Clock OFF v Int Enabled Value 1 MA V 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 1998 2009 HP InfoTech S R L Page
204. orm with Ob prefix e g 00101001 in hexadecimal form with 0x 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 Literal string constants must be enclosed in double quotation marks E g Hello world Constant expressions are automatically evaluated during compilation Program constants can be declared as global accessible to all the functions in the program or local accessible only inside the function they are declared The constant declarations syntax is similar to that of variables but preceded by the const keyword const lt type definition gt lt identifier gt constant expression Example Global constants declaration const char char _constant a const int b 1234 5 const long long_int_constant1 99L const long long_int_constant2 0x10000000 const float pi 3 14 void main void Local constants declaration const long 22222222 const float x 1 5 Constants can be grouped in arrays which can have up to 64 dimensions The first element of an array has always the index 0 Example const char string constant2 This is a string constant const i
205. ory and file Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2009 HP InfoTech S R L Page 52 CodeVisionAVR 2 3 5 Obtaining an Executable Program Obtaining an executable program requires the following steps 1 Compiling the Project s C program modules using the CodeVisionAVR C Compiler and obtaining object files needed by the linker 2 Linking the object files files created during compilation and obtaining a single assembler source file 3 Assembling the assembler source file using the Atmel AVR assembler AVRASM2 Compiling executes step 1 Building executes step 1 2 and 3 Compilation is performed only for the program modules that were modified since the previous similar process This leads to significant project build reduction times compared with the old CodeVisionAVR V1 xx where all the program modules were compiled even if they were not changed 2 3 5 1 Checking Syntax Checking the currently edited source file for syntax errors can be performed by using the Project Check Syntax menu or by pressing the toolbar button This function is useful because it s faster than Project Compile menu command which compiles all the modified files in a project It can also be executed by selecting Check Syntax in the pop up menu which is invoked by right clicking with the mouse in the editor window 1998 2009 HP InfoTech S R L Page 53 CodeVisionAVR 2
206. oying 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 2009 HP InfoTech S R L Page 248 CodeVisionAVR 7 Technical Support and Updates Registered users of commercial versions of CodeVisionAVR receive one year of free updates and technical support starting from the date of license purchase The technical support is provided by e mail in English or French languages The e mail support address is office hpinfotech com 1998 2009 HP InfoTech S R L Page 249 CodeVisionAVR 8 Contact Information HP InfoTech S R L can be contacted at HP INFOTECH S R L BD DECEBAL NR 3 BL 12B SC 2 AP 29 SECTOR 3 BUCHAREST ROMANIA phone 40 213261875 fax 40 213261876 GSM 40 723469754 e mail office hpinfotech com Internet http Awww hpinfotech com http www hpinfotech biz http www hpinfotech eu http www hpinfotech ro
207. p CodeWizardAVR test cwp l File Help USART2 USART3 Analog Comparator apc sri lac 1Wite 2 Wire I2C LCD Bit Banged Project Information Chip _EstemalSRAM Ports Extemal IRQ Timers USARTO USART1 Timer 0 Timer 1 Timer 2 PT Clock Source System Clock A Clock Value Timer 3 Stopped z Mode Normal top FFFFh 7 Dut A Discon x Out B Discon Input Capt I Noise Cancel _ Interrupt on O Timer 3 Overflow Value 0 h Inp Capture 0 h Comp 4 0 h BO h C 0 h 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 specifies 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 1998 2009 HP InfoTech
208. 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 Atmega8515 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 2009 HP InfoTech S R L Page 176 CodeVisionAVR include lt ds1307 h gt void main void unsigned char h m s initialize the I C bus i2c_init 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
209. pressing the Break toolbar button To single step the program the Debug Step Into F11 key Debug Step Over F10 key Debug Step Out Shift F11 keys menu commands or the corresponding toolbar buttons should be used In order to stop the program execution at a specific source line the Debug Toggle Breakpoint menu command the F9 key or the corresponding toolbar button should be used In order to watch program variables the user must select Debug Quickwatch Shift F9 keys menu command or press the Quickwatch toolbar button and specify the name of the variable in the QuickWatch window in the Name column The AVR chip registers can be viewed using the View Register menu command or by pressing the Alt 0 keys The registers can be also viewed in the Workspace I O window in the Register 0 15 and Register 16 31 tree branches The AVR chip PC SP X Y Z registers and status flags can be viewed in the Workspace I O window in the Processor tree branch The contents of the FLASH RAM and EEPROM memories can be viewed using the View Memory menu command or by pressing the Alt 4 keys The I O registers can be viewed in the Workspace I O window in the I O branch To obtain more information about using AVR Studio please consult it s Help system 1998 2009 HP InfoTech S R L Page 131 CodeVisionAVR 3 22 Compiling the Sample Code of the ATxmega Application Notes from Atmel In order to support the new ATxmega chips Atmel has released
210. pted for the name of the main C file SE Save C Compiler Source File mym Savein work BP o T Name Date modif Type Size ny No items match your search Recent Places Desktop T Pavel Me Computer A Network File name test Save as type C Compiler files c v Cancel and for the name of the project file GK Save C Compiler Project File Savein J work reo tz Name Date modif Type Size wp No items match your search Recent Places Desktop Pavel LS TEn Computer A lt 2 Network File name test af Save as type Project files prj Cancel 1998 2009 HP InfoTech S R L Page 203 CodeVisionAVR Selecting the File Exit menu option allows the user to exit the CodeWizardAVR without generating any program files By selecting the Help menu option or by clicking on the toolbar button the user can see the help topic that corresponds to the current CodeWizardAVR configuration menu 5 1 Setting the AVR Chip Options By selecting the Chip tab of the CodeWizardAVR you can set the AVR chip options amp CodeWizardAVR test cwp x File Help External IRQ __ Timers UART Analog Comparator ADC SPI 12C 1Wie LCD Project Information Extemal SRAM Ports Chip ATmega103 4 Clock 4 000000 t MHz Crystal Oscillator Divider Enabled Check Reset Source The chip type can be specifie
211. ption _MCU_CLOCK_FREQUENCY_ the AVR clock frequency specified in the Project Configure C Compiler Code Generation Clock option expressed as an unsigned long 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 _MODEL_MEDIUMN_ if the program is compiled using the MEDIUM memory model _MODEL_LARGE_ if the program is compiled using the LARGE memory model _OPTIMIZE_SIZE_ if the program is compiled with optimization for size Project Configure C Compiler Code Generation Optimize for Size option or pragma optsizet _OPTIMIZE_SPEED_ if the program is compiled with optimization for speed Project Configure C Compiler Code Generation Optimize for Speed option or pragma optsize _WARNINGS_ON_ if the warnings are enabled by the Project Configure C Compiler Messages Enable Warnings option or pragma warn _WARNINGS_OFF_ if the warnings are disabled by the Project Configure C Compiler Messages Enable Warnings option or pragma warn _PROMOTE_CHAR_TO_INT_ON_ if the automatic ANSI char to int type promotion is enabled by the Project Configure C Compiler Code Generation Promote char to int option or pragma promotechar _PROMOTE_CHAR_TO_INT_OFF_ if the automatic ANSI char to int type promotion is disabled by the Project Configure C Compiler Code Generation Promote char to int option or pragma promotechar _AVR8L_CORE_ signals that the program is compiled
212. ptr for the other memory models this function is identical to vsprintf except that at most size including the null terminator characters are placed in the character string str 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 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 implementation would require a large amount of FLASH memory space The format specifier string has the following structure width l 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 optional l input size modifier specifies that the function argument
213. 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 TWCR 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 1998 2009 HP InfoTech S R L Page 239 CodeVisionAVR As both the receiver and transmitter may stretch the duration of the low period of the SCL line when waiting for response the frequency 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 5 16 Setting the CAN Cont
214. pwm2b h 90pwm216 h 90pwm3 h 90pwm3b h 90pwm316 h 90usb1286 h 90usb1287 h 90usb162 h 90usb646 h 90usb647 h 90usb82 90s2313 9052323 90 523334 90s2343 90s4414 90s4433 90s4434 90s8515 90s8534 yp p gt gt pp p gt p gt p gt pS 1998 2009 HP InfoTech S R L Page 115 CodeVisionAVR 90s8535 h egal03 h egal28 h egal280 h egal281 h egal284p h egal6 h egal6 l1 h egal62 h egal63 h egal64 h egal65 h egal68 h egal68p h egal69 h ega2560 h ega2561 h ega32 h ega323 h ega324 h ega325 h ega325p h ega3250 h ega3250p h ega328p h ega329 h ega329p h ega3290 h ega3290p h ega406 h ega48 h ega48p h ega603 h ega64 h ega640 h ega644 h ega644p h ega645 h ega6450 h ega649 h ega6490 h ega8 h ega8515 h ega8535 h ega88 h ega88p h xmegal28al h xmegal28a3 h xmegal28a4 h xmegal6oa4 h xmegal92al h xmegal92a3 h xmega256al h xmega256a3 h xmega32a4 xmega64al xmega64a3 xmega64a4 ata6285 h ata6286 h a ae ae ae ae ee ee ee ee ee a a ee TTS 1998 2009 HP InfoTech S R L Page 116 CodeVisionAVR ata6289 h 43usb355 h 7oc71l1 h 86rf401 h 94k h The header file corresponding to the chip that you use must be included at the beginning of your program Alternatively the io h header file can be included This file contains the definitions for the I O registers for all the chips supported by the compiler 3 14 1 Bit level access to the I O Registers
215. r void snprintf char str unsigned char size char flash fmtstr arg1 arg2 for the TINY memory model void snprintf char str unsigned int size char flash fmtstr arg1 arg2 for the other memory models this function is identical to sprintf except that at most size including the null terminator characters are placed in the 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
216. r j 0 j lt 8 j printf X rom codes i j printf nir y while 1 loop forever 1998 2009 HP InfoTech S R L Page 181 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 pointed by p 4 14 1 Maxim 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 bit are used for communication with the DS1820 DS18S20 through the 1 Wire bus Example specify the Atmega8515 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 The DS1820 DS18S20 functions are unsigned char ds1820_read_spd unsigned char addr this function reads the contents of the SPD for the DS1820 DS18S20 sensor with the ROM code stored in an array of 8 bytes located at address addr The functions r
217. r C compilers the Promote char to int option is enabled by default for newly created projects If the char is unsigned 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 new ATmega and AT94K FPSLIC devices The Smart Register Allocation check box enables allocation of registers R2 to R14 not used for bit variables and R16 to R21 in such a way that 16bit variables will be preferably located in even register pairs thus favouring the usage of the enhanced core MOVW instruction for their access This option is effective only if the Enhanced Instructions check box is also checked If Smart Register Allocation is not enabled the registers will be allocated in the order of variable declaration The Smart Register Allocation option shou
218. r by pressing the HP respectively D buttons on the toolbar These functions are also available in the pop up menu invoked by mouse right clicking in the Editor window 2 2 4 2 Setting Bookmarks Bookmarks can be inserted or removed at the line where the cursor is positioned by using the Edit Toggle Bookmark menu command by pressing the Shift Ctrl 0 9 keys or the toolbar button The Edit Jump to Bookmark menu command the Ctrl 0 9 keys or the toolbar button will position the cursor at the start of the corresponding bookmarked text line Jumping to the next bookmark can be achieved by using the Edit Jump to Next Bookmark menu command by pressing the F2 key or by using the g toolbar button Jumping to the previous bookmark can be achieved by using the Edit Jump to Previous Bookmark menu command by pressing the Shift F2 keys or by using the toolbar button After a jump to a bookmark was performed the Edit Go Back menu command or the toolbar button allow to return to the previous position in the file The Edit Go Forward menu command or the toolbar button allow to return to the file position before the Edit Go Back menu command or the toolbar button were used These functions are also available in the pop up menu invoked by mouse right clicking in the Editor window 1998 2009 HP InfoTech S R L Page 23 CodeVisionAVR 2 2 4 3 Jumping to a Specific Line Number in the Edited File You can go to a specific
219. r jac 1 Wire Lco LCD Controller Bit Banged Project Information Chip Ports ExtemallRQ Timers J INTO Enabled Mode Lowlevel gt v Any change on 1 0 pins PCINTO v Any change on 1 0 pins PEINT8S 15 V Any change on 1 0 pins PCINT16 23 J Any change on 1 0 pins PCINT24 30 PCINTO PCINTS 15 PCI gt Ot 2 So 47 5 OF The Any change on I O pins 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 pin_change_isr1 for PCINT8 15 pin_change_isr2 for PCINT16 23 and pin_change_isr3 for PCINT24 30 1998 2009 HP InfoTech S R L Page 210 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 By selecting the Timer 0 tab you can have the following options amp CodeWizardAVR test cwp File Help USART2 USART3 Analog Comparator ADC l SPl falc fat Wine 2 Wire 12C LCD Bit Banged Project Information Chip _EstemalSRAM Ports Extemal IRQ Timers USARTO USART Timer 1 Timer 2 Timer3 fa Ea Clock Source System Clock 7 4 Clock Value Timer 0 Stopped Mode Normal top FFh ne Outp Aj Disconnected z Outp B
220. racter Type Functions 00 0 0 cece cece erence ee eeeaae ee eeeaaeeeeecaaeeeeeeaeeeseeaeeeeseeiaeeeeneneeeenaes 134 4 2 Standard C Input Output FUNCTIONS 0 00 0 cecccceeeeeteeeeeeeeeeeeecaeeeeeecsaeeeeceaeeseeeseeeeseseeeeeeeaas 135 4 3 Standard Library FUNCIONS isi ste cevet eek vy enirir enana EE ETR RRA E NAN E 140 4 4 Mathematical FUNCUONS sucrrssorirroni r a A A ORTE EA A 142 4 5 SIring FUNCUONS atr ae ae Ai ae iad aaa ace eee 145 4 6 Variable Length Argument Lists Macros ccccceeeeeeeeeeeneeeeeeeaeeeeeeaaeeeeeenaeeeeeeaeeeeeenaeeeeneaas 150 4 7 Non local JUMP FUNCHIONS enracina Gata nae teases ade ated eres 151 4 8 BCD Conversion Functions cece ener eeeene eee eeeee ee eeeaaeeeeeeaeeeeeeaeeeseeiaeeeeeeiaeeeeseeneeeeseaes 153 1998 2009 HP InfoTech S R L Page 5 CodeVisionAVR 4 9 Gray Code Conversion FUNCTIONS see ieireiiireeniirierindinkidradinnki en Kdin unind ERAAN ANNEKE ENAKAN NARESE 153 4 10 Memory Access MaCroS cicconcccnnieniii a A ENE east EOE 154 4 11 LOD FUNCOMS oceanici narai aeaea EEE EEE EEEE ERE ERNA 155 4 11 1 LCD Functions for displays with up to 2x40 characters ccccccecceeececeeeeeeeeeeeeenaees 155 4 11 2 LCD Functions for displays with 4x40 Characters ssseeeeseeeeneseerreserrreseerrssrrrressrernsse 158 4 11 3 LCD Functions for displays connected in 8 bit memory mapped mode 2 000 160 AAD C Bus FUNCUONS iirin iaiia a eaaa REALE aa ee 162 4 12 1 Nat
221. rary files These paths must be entered one per line in the appropriate edit controls KM Configure Project MULTFILE PRI l Files C Compiler Before Build After Build Code Generation Advanced Messages Globally ttdefine Paths include paths one per line C cvayrkinc Amy_header_files Library paths one per line C cvayr lib Amy_libraries a Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2009 HP InfoTech S R L Page 47 CodeVisionAVR 2 3 4 4 Executing an User Specified Program before Build This option is available if you select the Before Build 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 before the compilation assembly process XN Configure Project MULTFILE PRJ Files C Compiler Before Build After Build v Execute User s Program Program Directory and FileName Command Line Parameters Working Directory X conce 7 Her The following parameters can be specified for the program to be executed e Program Directory and File Name e Program Command Line Parameters e Program Working Directory 1998 2009 HP InfoTech S R L Page 48 CodeVisionAVR 2 3 4 5 Transferring the Compiled Program to the AVR Chip after Build This option is available if you select the After Build ta
222. rd C Input Output Functions The prototypes for these functions are placed in the file stdio h located in 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 mega8515 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 USART control register TX and RX enabled no interrupts 8 data bits UCSRA 0x00 UCSRB 0x18 UCSRC 0x86 initialize the USART s baud rate UBRRH xtal 16 baud 1 gt gt 8 UBRRL xtal 16 baud 1 amp OxFF 1998 2009 HP InfoTech S R L Page 135 CodeVisionAVR while 1 receive the character k getchar and echo it back putchar k e If you intend to use other peripherals for Input Output you must modify accordingly the getchar and putchar functions like in the example below include lt stdio h gt inform the compiler that an alternate
223. re stored in EEPROM eeprom struct type struct3 1998 2009 HP InfoTech S R L Page 104 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 a 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 required The compiler issues w
224. riable 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 l i lt nsum i add each argument resultt va_arg argptr int terminate the use of argptr 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 2009 HP InfoTech S R L Page 150 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
225. ribed in detail in the AT90USB datasheet 1998 2009 HP InfoTech S R L Page 244 CodeVisionAVR 5 20 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 test cwp File Help ExtemalIRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C 1wire 2wie 2c LCD Chip ExtemalSRAM Ports Bit Banged Project Information D51302 Port PORTD vost o SCLKBit 1 CE AST Bit 2 Trickle Charge v Enabled Diodes l1 x Charge Resistor 2K 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 which 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 Maxim Dallas Semiconductor DS1302 Real Time Clock Functions 1998 2009 HP InfoTech S R L Page 245 CodeVisionAVR 5 21 Specifying the Project Information By selecting the Project Information tab you can specify the information plac
226. rmatted 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 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 t
227. rmed in such a way that 16bit variables will be preferably located in even register pairs thus favouring the usage of the enhanced core MOVW instruction for their access Otherwise the allocation is performed 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 Local char int and pointer local variables are allocated to registers R16 to R21 If the Project Configure C Compiler Code Generation Smart Register Allocation option is checked the allocation of these registers for local variables is performed in such a way that 16bit variables will be preferably located in even register pairs thus favouring the usage of the enhanced core MOVW instruction for their access Otherwise the local variables are automatically allocated to registers in the order of declaration The Project Configure C Compiler Code Generation Smart Register Allocation option should be disabled if the program was developed using CodeVisionAVR prior to V1 25 3 and it contains inline assembly code that accesses the variables located in registers R2 to R14 and R16 to R21 1998 2009
228. rograms 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 lcd4x40 h located in the INC subdirectory This file must be include ed before using the functions The LCD functions do not yet support the ATxmega chips 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 DB7 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 _en1_m
229. roller By selecting the CAN tab of the CodeWizardAVR you can specify the CAN interface configuration ab CodeWizardAVR test cwp eS File Help Extemal IRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C LCD Bit Banged Project Information Chip ExtemalSRAM Ports 1Wwie 2Wie 20 J CAN Enabled Baud Rate 1000 000 kHz Interrupts 7 CAN Timer Overrun Enable MOb Reaisters E MOb0 Enable MOb Interrupts I Mobo gt Highest Interrupt Priority MOb MObO X CAN System Clock 8000 0 kHz Propagation Time Segment 0 625 us X Re Sync Jump Width 0 125 us z Phase Segment 1 0 125 us z Phase Segment 2 0 125 us z Sample Points 1 X CAN Timer Clock Period 1 000 us X The AVR chip s CAN interface can be enabled by checking the CAN Enabled check box The Interrupts list box allows enabling disabling the following interrupts generated by the CAN controller e CAN Timer Overrun interrupt serviced by the can_timer_isr function e General Errors bit error stuff error CRC error form error acknowledge error interrupt serviced by the can_isr function Frame Buffer Full interrupt serviced by the can_isr function MOb Errors interrupt serviced by the can_isr function Transmit completed OK interrupt serviced by the can_isr function Receive completed OK interrupt serviced by the can_isr function Bus Off interrupt serviced by the can_isr function All interrupts except Timer O
230. rrupt 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 2009 HP InfoTech S R L Page 213 CodeVisionAVR By selecting the Timer 2 tab you can have the following options amp CodeWizardAVR test cwp z File Help USART2 USART3 Analog Comparator abc sPL i2c_ 1 Wite 2 Wire I2C LCD Bit Banged Project Information Chip _EstemalSRAM Ports ExtemallRQ Timers USARTO USART1 Clock Source System Clock 7 Clock Value Timer 2 Stopped z Mode Normal top FFh Z Outp Al Disconnected Z Outp B Disconnected z Overflow Interrupt Compare Match Interrupt Compare Match B Interrupt Timer Value O h Compae4 O h CompareB O h Clock Source specifies
231. ry 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 Edit FLASH Buffer o 0000x 0001x 0002x 0003x 0004x O00Sx F 0006x 0007x 0008x 0009x OOOAx 000Bx 000Cx O00Dx F 000Ex OOOFx 4 F2 edits value Tab saves edited value Arrow keys Tab Shift T ab PgUp PgDn moves selection Mouse right click fills memory block The buffer s contents at the highlighted address can be edited by pressing the F2 key and typing in the new value The edited value is saved by pressing the Tab or arrow keys The highlighted address can be modified using the arrow Tab Shift Tab PageUp or PageDown keys 1998 2009 HP InfoTech S R L Page 67 CodeVisionAVR The Fill Memory Block window can be opened by right clicking in the Edit window amp Fill Memory Block Start ddress 0 h End ddress 1FFFF h Fill Value 0 h ETA This window lets you specify the Start Address End Address and F
232. s the size of the memory block i If the memory allocation functions will not be used then the Heap size must be specified as zero 1998 2009 HP InfoTech S R L Page 123 CodeVisionAVR 3 18 Using an External Startup Assembly 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 RAM access and wait state enable if necessary clear registers R2 R14 for AVR8 standard core chips clear the RAM initialize the global variables located in RAM initialize the Data Stack Pointer register Y 10 initialize the Stack Pointer register SP 11 initialize the UBRR register if necessary OONOARWN gt The automatic generation of code sequences 2 to 8 can be disabled by checking the 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 supp
233. s 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 2009 HP InfoTech S R L Page 216 CodeVisionAVR 5 6 Setting the UART or USART By selecting the UART tab of the CodeWizardAVR you can specify the UART configuration amp CodeWizardAVR test cwp File Help Analog Comparator ADC SPL 12C 1 Wire LCD Bit Banged Project Information Chip ExtemalSRAM Ports External IRQ Timers UART v Receiver v As Interrupt Receiver Buffer 8 zj v Transmitter v Tx Interrupt Transmitter Buffer 8 vA Baud Fate 9600 v Baud Rate Error 0 2 Communication Parameters 8 Data 1 Stop No Parity w 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 driven mode you can specify the size of the circular buffer using the Transmitt
234. s will be deleted except the asm and vec assembly source files e Linker Files directory all files will be deleted 1998 2009 HP InfoTech S R L Page 60 CodeVisionAVR 2 3 5 5 Using the Code Navigator The Code Navigator window allows displaying or opening of the project source files along with errors or warnings that occured during the compile or build processes Code Navigator Code Information Code Templates Clipboard History S CodeVision VR Bi Project LED S Notes led c B Errors p L94 undefined symbol k B Warnings B L51 local variable q was declared but not referenced fai Headers E mega8515 h J F Other Files D LED asm The project s program modules are listed as children of the Project node Other opened files that are not part of the project are listed as children of the Other Files A node By clicking on a file D node the appropriate file is maximized or opened After a Compile or Build process there is also displayed a list of header h files that were included in the project s program modules during this process The headers files are available as children of the Headers node By clicking on a header file F node the appropriate header file is maximized or opened If during compilation there are errors or warnings these are also displayed in the Code Navigator window By clicking on the error or warning node the corresponding source line is highlighted in th
235. se Segment 1 and Phase Segment 2 parameters If the CAN Baud Rate value is correct it s value is displayed in black color otherwise it is displayed in red and must be corrected by modifying the above mentioned parameters 1998 2009 HP InfoTech S R L Page 241 CodeVisionAVR 5 17 Setting the ATmega169 329 3290 649 6490 LCD Controller By selecting the LCD Controller tab of the CodeWizardAVR you can specify the configuration of the LCD controller built in the ATmega169 329 3290 649 6490 chips amp CodeWizardAVR test cwp File Help USI USART Analog Comparator ADC spl lac 1 Wire LoD Bit Banged Project Information Chip Ports External IRQ Timers v LCD Enabled LCD Low Power Waveform LCD Frame Complete Interrupt Duty Cycle Static Clock Source System v Frame Rate 50 4 Hz Frame Rate Error 2 3 Used Segments SEGO 12 7 Contrast Control 2 60 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 waveform mode this interrupt will be generated every second frame The frame complete interrupt will be serviced by the lc
236. sk must be set to LCD_EN1 respectively LCD_ENZ2 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 0Qxe 1998 2009 HP InfoTech S R L Page 158 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 unsigned char 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 The function returns 1 if the LCD module is detected and 0 if it is not 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 RAM void Icd_putsf char flash str displays at the current display position the string str located
237. spectively Cancel buttons 1998 2009 HP InfoTech S R L Page 72 CodeVisionAVR 2 5 3 Configuring the Editor The Editor can be configured using the Settings Editor menu command 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 2 5 3 1 General Editor Settings The following groups of Editor settings can be established by clicking on the General tab SQ Editor Settings General Text Syntax Highlighting Auto Complete Sample Text 1 Multiple line a File Load Save 2 comment v Auto Load Modified Files 3 f Single line comment J Create Backup Files 3 pia MAX a b i ila gt b a b Auto Save Interval Disabled x J flash char pflash flash int 0 Visual Aids 8 eeprom int peeprom eeprom int J Show Line Numbers 3 casa 10 void main void v Save Bookmarks 11 A7 v Enable Code Folding 2 int Number 123 v Save Folded Lines 13 int HexNumber O0x1FA7 14 Eloat FloatNumber 0 123e 2 Collapse Mark Text BB Window Text v Bs lchar c D Collapse Mark Bg C Window v ee cee eee Dene 7 jwhile Number Block Staples Color Silver S 18 B S 19 peepror pflasht Matching Brace Text jg Window Text 20 Number 21 he Matching Brace Ba oO Yellow 22 El 4 m p c i aZ e File L
238. ssibility to append LF characters after CR characters on reception and transmission enabling or disabling the echoing of the transmitted characters number of character Rows and Columns in the Terminal window Font type used for displaying characters in the Terminal window Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2009 HP InfoTech S R L Page 81 CodeVisionAVR 2 6 Accessing the Help The CodeVisionAVR help system is accessed by invoking the Help Help menu command or by pressing the toolbar button 2 7 Transferring or Deactivating the License The CodeVisionAVR license is locked to the hardware of the PC on which the software is installed After CodeVisionAVR is installed for the first time on a PC it displays a computer dependant Serial Number which must be sent by e mail to HP InfoTech in order to receive an Activation Code needed to unlock the license The Activation Code contains computer specific information but also additional information about the license type and update technical support validity period In case the user wishes to transfer his license to another computer upgrade his license type or update technical support validity period he needs to use the Help Transfer Deactivate License menu Once this menu option is selected the following dialog window will be displayed e CodeVisionAVR License Transfer Deactivation In order to transfer
239. sssssseennenennnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nennen 201 5 1 Setting the AVR Chip Options cesccsisedecstsedeaacceaandanauns deedabaadcueasaedieadanaiaesdesaedaadaaaadsaeanencaasansanee 204 5 2 9etling the Extemal SRAM cic oedccscoeiet vtectiee ie ieeeeteisecteebeteteak ieee te iecadesedtiee vlad eda ans 206 5 3 Setting the Input Output Poms sieri ai aa aa aaa a 208 5 4 Setting the External Interrupts 2 2 c cccicccneceececteecnecetee sebceete cendactepencdetesendactesendeetetendactepenndateeente 209 9 5 Setting the Timers COUNLCNS i encerc EE RA E EEEE E 211 5 6 Setting the UART or USART 0 cccccecececeeeeeeeeeeeeeaeeeeeeeceaeeeecaaeeeeeeeseaeeeseaeeesaaeseeeeeseeeesiaeeseaeeees 217 1998 2009 HP InfoTech S R L Page 6 CodeVisionAVR 5 7 Setting the Analog Comparator cccccsssssssssssssssssessssssssssssssssssssuessssssssssssusunssnsssssesssssens 220 5 8 Setting the Analog Digital Converter eccceeeceeeeeeeteeeeenneeeee etree eeeaeeeeeesaeeeeeeaeeeesenaeeeeeeas 222 5 9 Setting the ATmega406 Voltage Reference ee ceeeeeeeteeeeeeeeneeeeetineeeeetnieeeeetiieeeeeetneeeer 224 5 10 Setting the ATmega406 Coulomb Counter cece tener ee eeteee erties eeeiieeeeetieeeeetieeeere 225 5 11 Setting the SPI Interface ee ter nr eerie erties eee rieee ee teeeeetieeeeetineeeread 227 5 12 Setting the Universal Serial Interface USI eee nner eeeeieee ee tneeeeee teaser tieeeeetieeeere 228 543 Setting th
240. t All a Invert Clear eec g amp Selection Selection lt S OK x Cancel Files to be closed can be selected by checking the appropriate check boxes All the listed files can be selected using the Select All button The state of the check boxes can be reversed using the Invert Selection button The Clear Selection button can be used to un check all the check boxes Pressing the OK button will close all the selected files from the list Pressing the Cancel button will close the dialog window without closing any file 1998 2009 HP InfoTech S R L Page 29 CodeVisionAVR 2 2 10 Using the Code Templates The Code Templates window allows easy adding most often used code sequences to the currently edited file Function Call Tree Code Templates Clipboard History 4 1 gt if do while while Le iv switch case switch case void main void This is achieved by clicking on the desired code sequence in the Code Templates window and then dragging and dropping it to the appropriate position in the Editor window New code templates can be added to the list by dragging and dropping a text selection from the Editor window to the Code Templates window By right clicking in the Code Templates window you can open a pop up menu with the following choices Copy to the Edit Window the currently selected code template Paste a text fragment from the clipboard to the C
241. t radio group box e LPT1 at base address 378h e LPT2 at base address 278h e LPT3 at base address 3BCh amp Programmer Settings AVR Chip Programmer Type Kanda Systems STK200 300 Printer Port LPT1 378h x Delay Multiplier 1 4 v Tmega169 CKDIVS Fuse Warning x Cancel Hep 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 2009 HP InfoTech S R L Page 79 CodeVisionAVR The STK500 AVRISP and AVRProg programmers use the RS232C serial communication port which can be specified using the Communication Port list box amp Programmer Settings Ex AVR Chip Programmer Type Atmel STK500 AVRISP 7 Communication Port COM2 v ATmegal69 CKDIVS8 Fuse Warning x Cancel The Atmel AVRISP MkII AVR Dragon and JTAGICE MkII use the USB connection for communication with the PC Usage of this programmer requires the Atmel s AVR Studio V4 14 or later software to be installed on the PC Help The Atmel AVR Dragon and JTAGICE Mk
242. ted an alarm printf ALARM GENERATED BY u DEVICE S n r wl _search 0xec alarm_rom_codes e Refer to the DS1820 DS18S20 data sheet for more information 1998 2009 HP InfoTech S R L Page 185 CodeVisionAVR 4 14 2 Maxim Dallas Semiconductor DS18B20 Temperature Sensor Functions These functions are intended for easy interfacing between C programs and the DS18B20 1 Wire bus temperature sensor The prototypes for these functions are placed in the file ds18b20 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 ds18b20 h Prior to include ing the ds18b20 h file you must declare which microcontroller port and port bit are used for communication with the DS18B20 through the 1 Wire bus Example specify the Atmega8515 port and bit used for the 1 Wire bus asm equ _ wl port 0x18 PORTB equ _ wl bit 2 endasm include the DS18B20 functions prototypes include lt ds18b20 h gt The DS18B20 functions are unsigned char ds18b20_read_spd unsigned char addr this function reads the contents of the SPD for the DS18B20 sensor with the ROM code stored in an array of 8 bytes located at address addr The functions returns the value 1 on succes and 0 in case of error If only one DS18B20 sensor is used no ROM code array is necessary and the pointer
243. tes starting from the DS2430 application register address addr and stores it in the string dest located in RAM 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 RAM 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 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 ATmegaS8515 as follows DS2430 STK200 PORTA HEADER 1 GND 9 GND 2 DATA 7 PA6 All the devices must be connected in parallel AN 4 7k PULLUP RESISTOR MUST BE CONNECTED BETWEEN DATA PA6 AND 5V a asm equ _ wl port 0xlb equ _ wl bit 6 en
244. the memory block i If the memory allocation functions will not be used then the Heap Size must be specified as zero Eventually you may also specify the External RAM Size in case the microcontroller have external SRAM memory connected 1998 2009 HP InfoTech S R L Page 41 CodeVisionAVR The External RAM Wait State option enables the insertion of wait states during access to the external RAM 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 RAM Size in Kwords N Configure Project MULTFILE PRI _ Files C Compiler Before Build After Build Code Generation Messages Globally define Paths RAM Chip AT94K z i Data Stack Size 1024 Clock 8 000000 4 MHz bytes Heap Size 0 bytes Memory Model Program RAM Size 10 Kwords Small Data RAM Size 16288 bytes Optimize for Speed Code Generation Optimization Level Bit Variables Size 16 Maximal Promote char to int V char is unsigned 8 bit enums V Enhanced Core Instructions J Smart Register Allocation Automatic Global Register Allocation s printt Features Store Global Constants in FLASH Memory int width 7 Use an External Startup Initialization File s scanf Features Clear Global Variables at Program Startup int widt
245. 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 Out A specifies the function of the timer counter 2 output A and depends of the functioning mode Out B specifies the function of the timer counter 2 output B and depends of the functioning mode Overflow Interrupt specifies if an interrupt is to be generated on timer counter 2 overflow Compare Match A Interrupt specifies if an interrupt is to be generated on timer counter 2 compare register A match e Compare Match B Interrupt specifies if an interrupt is to be generated on timer counter 2 compare register B match e Timer Value specifies the initial value of timer counter 2 at startup e Compare A specifies the initial value of timer counter 2 output compare A register e Compare B specifies the initial value of timer counter 2 output compare B 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_isra and timer2_compb_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 2009 HP InfoTech S R L Page 214 CodeVisionAVR By selecting the Timer 3 tab you can have the following options am
246. to identify the ROM codes of the devices and to be able to address them ata later stage in the program 1998 2009 HP InfoTech S R L Page 180 CodeVisionAVR Example include lt mega8515 h gt specify the Atmega8515 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 RAM 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 USART control register TX enabled no interrupts 8 data bits UCSRA 0x00 UCSRB 0x08 UCSRC 0x86 initialize the USART s baud rate UBRRH xtal 16 baud 1 gt gt 8 UBRRL xtal 16 baud 1 amp OxFF 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 ROM codes for each detected device printf u DEVICE S DETECTED n r devices if devices for i 0 i lt devices i printf DEVICE u ROM CODE IS itl fo
247. u _ 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 IC bus their chip address 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 B
248. ude 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 DS18S20 or other similar commands sent to the 1 Wire device The pointer p points to an area of RAM 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 RAM 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
249. unctions External memory access setup Chip reset source identification Input Output Port initialization External Interrupts initialization Timers Counters initialization Watchdog Timer initialization UART USART initialization and interrupt driven buffered serial communication Analog Comparator initialization ADC initialization SPI Interface initialization Two Wire Interface initialization CAN Interface initialization I C 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 e J gt o o oo This product is Copyright 1998 2009 Pavel Haiduc and HP InfoTech S R L all rights reserved 1998 2009 HP InfoTech S R L Page 9 CodeVisionAVR 1 1 Credits The HP InfoTech team wishes to thank Mr Jack Tidwell for his great help in the implementation of the floating point routines Mr Yuri G Salov for his excellent work in improving the Mathematical Functions Library Mr Olivier Wuillemin and Mr Franc Marx for their help in beta testing Mr Lee H Theusch for his support in improving the compiler 2 The CodeVisionAVR Integrated Development Environment 2 1 Using the Integrated Development Environment Workspace The CodeVisionAVR IDE workspace consist from several windows that may be docked to the main applic
250. 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 2009 HP InfoTech S R L Page 179 CodeVisionAVR 4 14 1 Wire Protocol Functions The 1 Wire Functions are intended for easy interfacing between C programs and various peripherals using the Maxim 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 subdirectory This file must be include ed before using the functions The 1 Wire Functions functions do not yet support the ATxmega chips 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 ATmega8515 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 incl
251. 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 the _HEAP_START_ 1 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 The Heap is a memory area located between the Hardware Stack and the RAM end It is used by the memory allocation functions from the Standard Library malloc calloc realloc and free 1998 2009 HP InfoTech S R L Page 122 CodeVisionAVR The Heap size must be specified in the Project Configure C Compiler Code Generation menu It can be calculated using the following formulae heap _size n 1 4 X block _ size i l where n is the number of memory blocks that will be allocated in the Heap block _ size i
252. using the pragma command You can use the pragma warn directive to enable or disable compiler warnings Example Warnings are disabled pragma warn Write some code here Warnings are enabled pragma warnt 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 optt 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 affected by the interrupt handler can be turned on or off using the pragma savereg directive 1998 2009 HP InfoTech S R L Page 111 CodeVisionAVR 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
253. using the reduced core instruction set used in chips like ATtiny10 No ADIW SBIW LDD and STD instructions are generated in this case _ENHANCED_CORE_ if the program is compiled using the enhanced core instructions available in the new ATmega chips _IO_BITS_DEFINITIONS_ if the Project Configure C Compiler Code Generation Preprocessor Include I O Registers Bits Definitions option is enbaled _HEAP_START_ the heap starting address _HEAP_SIZE_ the heap size specified in the Project Configure C Compiler Code Generation Heap size option _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_enumst is used _ATXMEGA_USART_ specifies which ATxmega chip USART is used by the getchar and putchar Standard C Input Output Functions _ATXMEGA_SPI_ specifies which ATxmega chip SPI controller is used by the SPI Functions _ATXMEGA_SPI_PORT_ specifies which ATxmega chip I O port is used by the SPI controller The line directive can be used to modify the predefined _ LINE and__FILE___ macros The syntax is line integer constant file name 1998 2009 HP InfoTech S R L Page 86 CodeVisionAVR Example This will set _ LINE to 50 and __ FILE to file2 c line 50 file2 c This will set _ LINE __ to 100 line
254. ut 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 RTC_TIMER_OFF disables the PCF8563 Timer countdown RTC_TIMER_CLK_1_60 sets the PCF8563 Timer countdown clock frequency to 1 60Hz RTC_TIMER_CLK_1 sets the PCF8563 Timer countdown clock frequency to 1Hz RTC_TIMER_CLK_64 sets the PCF8563 Timer countdown clock frequency to 64Hz RTC_TIMER_CLK_4096 sets the PCF8563 Timer countdown clock frequency to 4096Hz Refer to the PCF8563 data sheet for more information 1998 2009 HP InfoTech S R L Page 170 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
255. variable days of week is initialized with the integer value 6 days of week saturday Enumerations can be stored in RAM EEPROM or FLASH The eeprom or __ eeprom memory attributes must be used to specify enumeration storage in EEPROM Example eeprom enum days sunday monday tuesday wednesday thursday friday saturday days of week The flash or __ flash memory attributes must be used to specify enumeration storage in FLASH memory Example flash enum months january february march april may june july august september october november december months of year 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 2009 HP InfoTech S R L Page 103 CodeVisionAVR 3 8 Defining Data Types User defined data types are declared using the typedef reserved keyword The syntax is typedef 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 struct int a char b 5 struct_type variable declarations byte alfa structure stored in RAM struct_type structl structure stored in FLASH flash struct type struct2 structu
256. verrun serviced by the can_isr function 1998 2009 HP InfoTech S R L Page 240 CodeVisionAVR The Enable MOb Registers list box allows for individual enabling disabling of the CAN Message Object registers The Enable MOb Interrupts list box allows for enabling disabling the interrupts generated by individual Message Object registers The Highest Interrupt Priority MOb list box allows selecting the Message Object register that has the highest interrupt priority The CAN System Clock list box allows selecting the frequency of the CAN controller system clock The Propagation Time Segment list box allows for compensation of physical delay times within the network The duration of the propagation time segment must be twice the sum of the signal propagation time on the bus line the input comparator delay and the output driver delay The Re Sync Jump Width list box allows for compensation of phase shifts between clock oscillators of different bus controllers by controller re synchronization on any relevant signal edge of the current transmission The Phase Segment 1 and Phase Segment 2 list boxes allow for compensation of phase edge errors The Sample Point s list box allows selecting the number of times 1 or 3 the bus is sampled The CAN Timer Clock Period list box allows selecting the period of the CAN timer clock pulses The CAN Baud Rate is calculated based on the durations of the CAN System Clock Propagation Time Segment Pha
257. version of the getchar function will be used define ALTERNATE GETCHAR_ now define the new getchar function char getchar void write your code here inform the compiler that an alternate version of the putchar function will be used define ALTERNATE PUTCHAR_ now define the new putchar function void putchar char c write your code here For the ATxmega chips the getchar and putchar functions use by default the USARTCO If you wish to use another USART you must define the ATXMEGA_USART_ preprocessor macro prior to include the stdio h header file like in the example below use the ATxmegal28A1 USARTDO for getchar and putchar functions define _ATXMEGA USART_ USARTDO use the Standard C I O functions include lt stdio h gt The _ATXMEGA_USART_ macro needs to be defined only once in the whole program as the compiler will treat it like it is globally defined 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 RAM followed by a new line character void putsf char flash str outputs using putchar the null terminated character string str located in FLASH followed by a new line character 1998 2009 HP InfoTech S R L Page 136 CodeVisionAVR void printf char flash fmtstr arg1 arg2 outputs fo
258. vr2 e GB usartc Notes ust E A Includes H x x x aX aK 24 Macros HRe Typedets 5 4 Global Static Varia FO Functions eeprom_struct eeprom_uiA gt eeprom_uiB gt struct3 gt EEPROwruuns struct gt not used removed by the linker and can be placed anywhere on the desktop 48 eeprol 49 eeprol 50 eepro 51 eeproi 52 53 55 56 57 void se Aly 59 eepro 61 in 62 eepro 22 nase A toolbar can be also docked anywhere in the application s main window f CodeVisionAVR C cvavr2 examples File Edit Search View Project Toc x B 4 E H T g D R Code Information ma is e B fA Includes X MO Macros HR Typedefs 4p Global Static Variable H X eeprom_struct gt E qi X eeprom_uiA gt not i X eeprom_uiB gt not H struct3 gt EEPROM tiara H struct6 gt notused ili F0 Functions c amp 4 4 w of Function Call Tree Messages B Errors B Warnings l Messages Ca Find in Files 48 43 Insert 1998 2009 HP InfoTech S R L Page 17 CodeVisionAVR An undocked toolbar can be hidden by clicking on it s icon Alternatively the toolbars visible state can be changed by using the View Toolbars menu The buttons on a toolbar can be individually enabled or disabled by left clicking with the mouse on the button A drop down menu will open for this purpose CodeVisionAVR C cvavr2 examp
259. with the LM75 through the C bus Example the I C bus is connected to ATmega8515 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 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 I 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 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
260. 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 unsigned char 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 The function returns 1 if the LCD module is detected and 0 if it is not 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 RAM void Icd_putsf char flash str displays at the current display position the string str located in FLASH 1998 2009 HP InfoTech S R L Page 157 CodeVisionAVR 4 11 2 LCD Functions for displays with 4x40 characters The LCD Functions are intended for easy interfacing between C p
261. x File Type 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 pd Save C cvavr inc untitled c As x Save in work OA PE T Name Date modif Type Size wA No items match your search Recent Places Computer A Network File name mylib X Save as type C Compiler source file c v Cancel 1998 2009 HP InfoTech S R L Page 129 CodeVisionAVR Finally use the File Convert to Library menu command or the fi toolbar button to save the currently opened c file under the name mylib lib in the LIB directory fi New Library Name ese mylib lib x Cancel In order to use the newly created mylib lib library just include the mylib h header file in the beginning of your program Example include 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 2009 HP InfoTech S R L Page 130 CodeVisionAVR 3 21 Using the AVR Studio Debugger CodeVisionAVR is designed to work in conjunction with the Atme
262. y 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 2009 HP InfoTech S R L Page 173 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 the I C bus is connected to ATmega8515 PORTB asm equ _ i2c 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 i2c_ 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
Download Pdf Manuals
Related Search
Related Contents
Samsung NP300V5ZI Manual de utilizare (FreeDos) Gasoline Inverter Generator dt 3, dt 3n stopwatch operating instrustions CL-3684 Wireless Digital Video Doorbell USER`S MANUAL Pour bien commencer le droit - Bibliothèque Clermont Université 食推おすすめ料理・カレンダー 888 service 取付説明書 Copyright © All rights reserved.
Failed to retrieve file