Home
CodeVisionAVR User Manual
Contents
1. SI PORTB Bit 2 so PORTB Bit 3 SCK PORTE Bit 1 CS PORTD Bit 6 CD PORTG Bit 4 CDactiveLow WP PORTG x Bit 3 7 WP active High x VCC 3 GND GND The Enable MMC SD SD HC Card and FAT Support check box activates the appropriate MMC SD SD HC FLASH Memory Card Driver and FAT Access Functions libraries The SPI Slow Clock options allows to use a two times slower data rate when communicating with the MMC SD SD HC Card in order to provide better compatibility with some hardware designs 1998 2012 HP InfoTech S R L Page 61 CodeVisionAVR The user has the possibility to specify the polarity of the CD Card Detect signal as active Low or High and even to disable it s usage In this situation no I O port signal is allocated for this purpose and the presence of the card must be detected by calling the sdcard_present function from the MMC SD SD HC FLASH Memory Card Driver library The polarity of the WP Write Protect signal can also be specified as active Low or High or it s usage can be totally disabled In this later case no I O port signal will be allocated for it 1998 2012 HP InfoTech S R L Page 62 CodeVisionAVR 2 3 5 7 Setting the Alphanumeric LCD Library Options The Libraries tab is used for configuring specific driver libraries used by the compiler The Alphanumeric LCD tab is used for configuring th
2. USART Baud rate define BAUD _ RATE 19200 define BAUD INIT _MCU_CLOCK_FREQUENCY_ BAUD_RATE 16L 1 100Hz timer interrupt generated by ATmegal28 Timerl overflow interrupt TIM1_ OVF void timer _comp_isr void ve initialize Timerl TCNT1H T1 INIT gt gt 8 TCNTIL T1_ INITS amp OxXFF MMC SD SD HC card access low level timing function disk timerproc 1998 2012 HP InfoTech S R L Page 318 CodeVisionAVR error message list flash char flash error msg not used r FR_DISK_ERR FR_INT_ERR FR_INT_ERR FR_NOT_READY FR_NO FILE FR_NO PATH FR_INVALID_NAME FR_DENIED FR_EXIST VALID_OBJECT l j v5 HS 2AaHS WOH 44 AHH FR WRITE PROTECTED FR INVALID DRIVE FR NOT ENABLED FR NO FILESYSTEM FR _MKFS ABORTED R TIMEOUT l display error message and stop void error FRESULT res if res gt FR_DISK_ ERR amp amp res lt FR_TIMEOUT printf ERROR p r n error msg res stop here while 1l will hold file directory information returned by f_readdir FILINFO file info recursively scan directory entries and display them FRESULT directory scan char path will hold the directory information DIR directory FAT function result FRESULT re
3. define SSD1963 CM define SSD1963 CM define SSD1963 PIXEL DATA 8BIT 0 8 bit define SSD1963 PIXEL DATA 9BIT 6 9 bit define SSD1963 PIXEL DATA 12BIT 1 12 bit define SSD1963 PIXEL DATA 16BIT 2 16 bit packed define SSD1963 PIXEL DATA 16BIT565 3 16 bit 565 format define SSD1963 PIXEL DATA 18BIT 4 18 bit define SSD1963 PIXEL DATA 24BIT 5 24 bit define SSD1963 CMD GET PDATA INTERFACE OxFl Get the pixel data format used for parallel mode communication with the uC void ssd1963_wrdata unsigned char data Writes data byte s to the SSD1963 controller after a command was issued using the ssd1963_wrcmd function Parameter data to be sent to the controller unsigned char ssd1963_rddata void Reads result data byte s from the SSD1963 controller after a command was issued using the ssd1963_wremd function void ssd1963_wrdram GLCDCOL t color Writes color data for 1 pixel to the SSD1963 controller s display RAM Parameter color data to be sent to the controller Note Before calling this function a SSD1963_CMD_WR_MEM_START or SD1963_CMD_WR_MEM_CONT command must be issued to the controller using the ssd1963_wrcmd function 1998 2012 HP InfoTech S R L Page 243 CodeVisionAVR GLC
4. DS18B20 devices ROM code storage area 9 bytes are used for each device see the wl search function description but only the first 8 bytes contain the ROM code and CRC unsigned char rom_codes MAX DEVICES 9 allocate space for ROM codes of the devices which generate an alarm unsigned char alarm_rom_codes MAX DEVICES 9 1998 2012 HP InfoTech S R L Page 367 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
5. 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 2012 HP InfoTech S R L Page 143 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 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_
6. ADCA Settings 7 ADC Enabled ADC Clock Frequency 125 000 kHz 7 ADC Resolution 12 Bits ADC Conversion Mode Unsigned me ADC Reference Internal 1 00 Y z Conversion Start Mode Event Channel s ADC Compare Register C Temperature Measurement Reference Enabled Channels Triggered by the Event System k 01 2 3 Triggers Channel s 0 1 2 3 ADC Input Connected to GND for Offset Compensation ADC pin v 0 h Channel 0 Channel 1 Channel 2 Channel 3 Input Mode Internal positive input signal z Positive Input Temp Reference v Negative Input GND ae Interrupt Low Level Interrupt Mode Conversion Complete z In the above example figure event channel 0 will trigger ADC channel 0 event channel 1 will trigger ADC channel 1 event channel 2 will trigger ADC channel 2 and event channel 3 will trigger ADC channel 3 1998 2012 HP InfoTech S R L Page 482 CodeVisionAVR In the Channels Sweeped by the Event System and Channels Sweeped by the Event System Synchronized conversion start modes an event that occurs on Event Channel will trigger a sweep of all the ADC channels specified by the Sweeps Channel s list box ADCA Settings 7 ADC Enabled ADC Clock Frequency 125 000 kHz x ADC Resolution 12 Bits ADC Conversion Mode Unsigned v ADC Reference Intern
7. 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 application window or left floating on the desktop to suit the user s preferences r a SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usart prj 5 8 File Edit Search View Project Tools Settings Help rE Ryan a BeES HBEOREC MARS x B S x Ql e 1 ER 2 G eA BPS ROO AIN BEE 2 XO FE Code Navigator 9 F E R Code Information Y EJ CNevayid evamples stimega USARTCO usertie C Acvawr2 inc xmegal 28a1 h E Code Templates 9 7 EJ a Clipboard Y F EF CodeVision amp VR usart c He Oo 4 He Project usart R A Includes Nosy usate Ed moga128a1 h E r Notes MQ Macros 1 07 a 1 CodeVisionAVR C Compiler V2 a usatt c H Typedefs 2 Sample program to test the A 2 C 1998 2009 Pavel Haiduc if O Headers H P Global Static Varia 3 Use STK600 development boal _ 3 B stdioh 5 FC Functions 4 sTK600 Rc100x 13 addapters 4 Peripheral Modules and Inter B stdarg h fO main void 5 5 lao B ioh 6 The STK600 programmer must b 6 ignde _XMEGA128A1_INCLUDED__ amegal 28a 7 in the Tools Programmer menu 7 define _XMEGA12 A1_INCLUDED_ wnite e 4 hile H cap 4 eae ne 9 sinciude lt xmseruct h gt
8. lt 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 2012 HP InfoTech S R L Page 46 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 a XN Configure Project MULTFILE PRJ Files C Compiler Before Build After Build Code Generation Libraries Messages Globally define Paths FAM Chip AT megal 280 Z Data Stack Size 1024 bytes Clock 8 000000 4 MH 24 5 Heap Size 0 bytes Memory Model Internal RAM Size 8192 bytes Small External RAM Size 0 F External RAM Wait State Optimize for Size Code Generation
9. set bit 5 of I O Port A output to logic 1 for XMEGA chips SETBIT PORTA OUT 5 CLRBIT port b sets bit b of port to logic 0 state Example set bit 5 of I O Port A output to logic 0 for non XMEGA chips CLRBIT PORTA 5 set bit 5 of I O Port A output to logic 0 for XMEGA chips LRBIT PORTA OUT 5 Q TGLBIT port b toggles inverts the logic state of bit b of port Example toggles bit 5 of I O Port A output for non XMEGA chips TGLBIT PORTA 5 toggles bit 5 of I O Port A output for XMEGA chips TGLBIT PORTA OUT 5 EQUBIT port b value assigns a value to bit b of port If the assigned value is different from 0 then the bit is set to logic 1 state If the assigned value is 0 then the bit is set to logic 0 state 1998 2012 HP InfoTech S R L Page 134 CodeVisionAVR Example sets bit 5 of I O Port A output to the logic state of variable i for non XMEGA chips EQUBIT PORTA 5 i sets bit 5 of I O Port A output to the logic state of variable i for XMEGA chips EQUBIT PORTA OUT 5 1i Note The SETBIT CLRBIT TGLBIT and EQUBIT macros always perform atomic I O port bit access for the XMEGA chips For non XMEGA chips the atomic I O port bit access using the SETBIT CLRBIT and EQUBIT macros can be performed only for I O ports with addresses located in I O register space in the 0 to 1Fh range TSTBIT port b returns the l
10. using AVR Studio The VIARGET LED on the STK600 Make the following connections PC3 RS232 SPARE TXD annant the STVYANN RO222 animn 1998 2012 HP InfoTech S R L Page 20 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 SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usa File Edit Search View Project Tools Settings Help BEE B 4 p MO PRM BP WrWwROrslel f ap Code Information Y 9 CAcvavi2 examples atemege oji B oi k J Notes usart c EY E Includes S 28 Macros 1 G 4 a 2 Sample program H Ap Global Vse a STK600 de SFO Function I STK6E00 RC100X 1 fD mal D G wea c e R amp The STK600 prog an the Tools Pr ke sure that using AVR Studi The VIARGET LEL Make the follow f Function Call Tree PC3 RS232 SPA S main 2 and can be placed anywhere on the desktop 1998 2012 HP InfoTech S R L Page 21 CodeVisionAVR A toolbar can be also docked anywhere in the application s main window SX CodeVisionAVR C cvavr2 examp File Edit Search View Project amp X I g ep we BB f be Code Information S b c3
11. Write in RGB order define SSD1963 DEFAULT CL BITS SSD1963 CL BITS RGB The following colors are predefined in the glcd_ssd1963 h header file GLCD_CL_BLACK GLCD_CL_WHITE GLCD_CL_GRAY GLCD_CL_LIGHT_GRAY GLCD_CL_GREEN GLCD_CL_LIME GLCD_CL_BLUE GLCD_CL_RED GLCD_CL_AQUA GLCD_CL_YELLOW GLCD_CL_MAGENTA GLCD_CL_CYAN GLCD_CL_DARK_CYAN GLCD_CL_ORANGE GLCD_CL_PINK GLCD_CL_BROWN GLCD_CL_VIOLET GLCD_CL_SILVER GLCD_CL_GOLD GLCD_CL_NAVY GLCD_CL_MAROON GLCD_CL_PURPLE GLCD_CL_OLIVE 1998 2012 HP InfoTech S R L Page 246 CodeVisionAVR The SSD1963 library functions can operate the display in 256 or 64k color modes For 256 color mode the following color bit allocation in a data byte is used e Bits 0 2 Blue color bits 0 2 e Bits 3 5 Green color bits 0 2 e Bits 6 7 Red color bits 0 1 For 64k color mode the following color bit allocation in a 16bit data word is used e Bits 0 4 Blue color bits 0 4 e Bits 5 10 Green color bits 0 5 e Bits 11 15 Red color bits 0 4 Notes e In order to reduce image storage size and improve speed it is recommended to use the 256 color mode if possible e The glcd_ssd1963 h header file is automatically included when the main gled h header file is included Therefore there is no need to explicitly include gled_ssd1963 h e The EXAMPLES Graphic LCD SSD1963 directory contains fully functional code samples that may be used as references for SSD1963 in
12. all status flags are 0 disk initialization OK else led _puts Init OK wait 2 seconds delay ms 2000 clear the LCD lcd_clear get the sector size if disk _ioctl 0 GET SECTOR SIZE amp sector_size RES_ OK sector size read OK display it sprintf display buffer Sector size u sector size lcd _puts display buffer wait 2 seconds delay ms 2000 clear the LCD lced_clear get the sector count if disk _ioct1 0 GET_ SECTOR COUNT amp sector count RES_ OK sector count read OK display it sprintf display buffer Sector count lu sector_ count lcd _ puts display buffer else lcd puts Error reading nsector count else lcd puts Error reading nsector size 1998 2012 HP InfoTech S R L Page 307 CodeVisionAVR wait 2 seconds delay ms 2000 the rest of the program EP aaa Ff while 1 cee nL Note When compiling the above example make sure that the s printf Features option in the Project Configure C Compiler Code Generation menu will be set to long width This will ensure that the unsigned long int sector_count variable will be displayed correctly by the sprintf function 1998 2012 HP InfoTech S R L Page 308 CodeVisionAVR 4 21 FAT Access Functions These functions are intended for high level data access to MM
13. Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2012 HP InfoTech S R L Page 89 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 4 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 4 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 pflash Matching Brace Text jg Window Text 20 Number 7 21 he Matching Brac
14. ccccecceeeeeeeeceeceeeeeeeseeeneaeeeeeeeeeseneiaeeeeeeeeeeee 98 2 6 Accessing the Hel eccrine nner ee ine ee ieee eerie en ieee ee tieee ee neee eee eiieeeeesieeeenieeeeeia 99 2 7 Connecting to HP InfoTech s Web Site cieeccncneesesteneeecesectaeeesnenseeesteneeeesnetaueeusetaebesnantaeeest 99 2 8 Quitting the CodeVisionAVR IDE ecceeeeeeeetttee ee etiee erties ee tne eee ee teeeeetieeeeetiieeeeesieeeereae 99 3 CodeVisionAVR C Compiler Reference ccccccceseeeeeeeceeeeeseeeeeaneeeeeseeeseneeeeneeseaeeeseesseeneesees 100 3 1 The C Preprocessor svssccszsaainciersaa ceases aadeveavandnaanesanaveahaanadtas a aaa aaa a aaa aaa 100 3 2 COMMMOMNMS araa aa T E TE T T 104 3 3 Rosorved Keywords oii iiccevutcicas ved dacesvaid dete vetetcaa vd Aecaspeetecaayhd dotenyettidaadbaetacaayh ded evita yh aerate 105 Bi Genin E vases fade se ers ceste aes TO ee ee a ee ie aes 106 3 5 Data Type S crena aii eid eed ead hed eee ede cee 106 3 0 CONSTANS icr stein di ccd leben iad Aledo EEA nantes tidak ania A ene 107 1998 2012 HP InfoTech S R L Page 4 CodeVisionAVR 3 7 1 Specifying the RAM and EEPROM Storage Address for Global Variables 111 3 7 2 Bit VAriADICS ieee ett eerie ar EEEE EEEE ee enna EEEE EE TEERAA 112 3 7 3 Allocation of Variables to Registers 2 0 0 ccceeeeeeeeeeeete teeter ee eeeaeeeeeetteeeeeeaeeeenenaeeeeneaas 113 Sif A SMUCUUIOS A E E E E E 114 Bs UMOS see Fa he e
15. l display error message and stop void error FRESULT res if res gt FR_DISK_ ERR amp amp res lt FR_TIMEOUT printf ERROR p r n error msg res stop here while 1 display file s attribute size and time stamp void display status char file name if res f_stat file_name amp finfo FR_OK printf File s Attributes c c c c c r n Date 02u 02u u Time 02u 02u 02u r n Size lu bytes r n finfo fname finfo fattrib amp AM DIR D finfo fattrib amp AM RDO R finfo fattrib amp AM HID H finfo fattrib amp AM SYS S i finfo fattrib amp AM ARC A finfo fdate amp 0x1F finfo fdate gt gt 5 amp OxF finfo fdate gt gt 9 1980 finfo ftime gt gt 11 finfo ftime gt gt 5 amp Ox3F finfo ftime amp OxF lt lt 1 finfo fsize else an error occured display it and stop error res 1998 2012 HP InfoTech S R L Page 329 CodeVisionAVR void main void initialize Timerl overflow interrupts in Mode 0 Normal TCCRIA 0x00 clkio 1024 TCCRIB 1 lt lt CS12 1 lt lt CS10 timer overflow interrupts will occur with 100Hz frequency TCNTIH T1_ INIT gt gt 8 TCNTIL T1_ INITS amp OXFF enable Timerl overflow interrupt TIMSK 1 lt lt TOIE1 initialize the USARTO TX 8N1 Baud rate 19
16. read the byte back into the eeprom rd data variable twi master trans amp twid master EEPROM TWI BUS ADDRESS unsigned char amp twi_ eeprom 2 amp eeprom rd data 1 stop here while 1 1998 2012 HP InfoTech S R L Page 284 CodeVisionAVR 4 15 2 Two Wire Interface Functions for Slave Mode Operation The following structure data type is defined in the twix h header file for operating the XMEGA TWI in slave mode typedef struct TWI_t module pointer to the used TWI interface module 7 unsigned char rx buffer pointer to receive buffer unsigned char rx buffer size receive buffer size unsigned char rx index index in the receive buffer of the last received byte unsigned char tx buffer pointer to transmit buffer unsigned char tx index index in the transmit buffer of the last transmitted byte unsigned char bytes to tx number of bytes to transmit to the master z void twi_trans void pointer to TWI slave transaction processing function unsigned result transaction result TWI SLAVE INFO t The TWI_SLAVE_INFO_t data type is used for declaring the structure variables used to hold the information required by each TWI module when operating in slave mode These structure variables are updated automatically by the TWI functions during bus transactions The result of a TWI slave transaction is r
17. 3 define MINUTI define HOUR 14 finfo fdate DAY MONTH lt lt 5 YEAR 1980 lt lt 9 finfo ftime SECOND gt gt 1 MINUTE lt lt 5 HOUR lt lt 11 if res f utime path amp finfo FR_OK printf New time stamp 02u 02u u 02u 02u 02u set OK r n DAY MONTH YEAR HOUR MINUTE SECOND else an error occured display it and stop error res display file s new attribute and time stamp display status path change file s attributes clear the Read Only attribute if res f_chmod path 0 AM RDO FR_OK printf Read Only attribute cleared OK r n path else an error occured display it and stop error res display file s new attribute and time stamp display status path stop here while 1 Note When compiling the above example make sure that the s printf Features option in the Project Configure C Compiler Code Generation menu will be set to int width 1998 2012 HP InfoTech S R L Page 332 CodeVisionAVR FRESULT f_rename const char path_old const char path_new renames a file or directory If the new path contains a different directory than the old path the file will be also moved to this directory The logical drive is determined by the old path it must not be specified in the new path Parameters path_old points to a RAM based NULL terminated char string that represents the path na
18. If the Calibrate Internal Oscillator option is enabled the internal 2MHz or 32MHz RC oscillator used as system clock source will be calibrated using one of the Calibration Reference sources e 32 768kHz Internal RC Oscillator e 32 768kHz External Crystal Oscillator The 32 768kHz Oscillator Low Power Mode option allows to run this external crystal oscillator with reduced voltage swing on the TOSC2 pin The Prescaler A option allows to divide the system clock by a factor between 1 and 512 obtaining the ClkPer4 peripheral clock The Prescaler B C option allows to divide the ClkPer4 peripheral clock by a factor of 1 2 or 4 obtaining the ClkPer2 ClkPer peripheral clocks and the CIkCPU clock used by the CPU and Non Volatile Memory If the Lock Clock Configuration option is enabled the system clock selection and prescaler settings are protected against further updates until the next chip reset The ClkPer Output list box allows to specify if the ClkPer signal will be fed to the bit 7 of PORTC PORTD or PORTE 1998 2012 HP InfoTech S R L Page 445 CodeVisionAVR If an External Oscillator or Clock is used as System Clock Source the following specific configuration options are available System Clocks Settings System Clock Source External Osc or Clock X External Clock 8000 000 tH kHz External Clock Source Start up Time External Clock on XTAL1 6 CLK X Prescaler 1 X CikPer4 8000 00
19. 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 int 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 2012 HP InfoTech S R L Page 107 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
20. define SSD2119 DEFAULT _VCIX2 SSD2119 VCIX2_5V1 Default value for VLCD63 voltage define SSD2119 DEFAULT VLCD63 SSD2119 VLCD63 4V80 Default value for VcomL alternating drive voltage define SSD2119 DEFAULT VCOML SSD2119 VCOML 0 72 Default value for VcomH VLCD63 0 35 0x1A 0 01 define SSD2119 DEFAULT VCOMH Ox1lA Default value for driving waveform control FLD bit splits one frame into 3 fields to reduce flicker define SSD2119 DEFAULT FLD 1 Default value for LCD frame frequency define SSD2119 DEFAULT FRAME FREQ SSD2119 FRAME80 Default initialization values for the gamma control register bits PKPOO PKPO2 positive gamma micro adj define SSD2119 DEFAULT PKPOO 7 PKP10 PKP12 positive gamma micro adj define SSD2119 DEFAULT PKP10 7 PKP20 PKP22 positive gamma micro adj define SSD2119 DEFAULT PKP20 4 PKP30 PKP32 positive gamma micro adj define SSD2119 DEFAULT PKP30 2 PKP40 PKP42 positive gamma micro adj define SSD2119 DEFAULT PKP40 4 PKP50 PKP52 positive gamma micro adj define SSD2119 DEFAULT PKP50 2 PRPOO PRPO2 positive gamma gradient adj define SSD2119 DEFAULT PRPOO 2 1998 2012 HP InfoTech S R L Page 253 CodeVisionAVR PRP10 P define SSD VRPOO V define SSD VRP10 V define SSD PKNOO P define SSD PKN10 P define SSD PKN20 P define SSD PKN30 define
21. r A ae NANDA NN HA we H ct ct ct 3 to LCD ch RS define SSD1963 CMD SI eal Q define SSD1963 CMD G eal Q define SSD1963 CMD SI Gl A Q define SSD1963 CMD G eal Q define SSD1963 CMD SI eal Q define SSD1963 CMD G eal Q define SSD1963 CMD SI Gl H Q define SSD1963 CMD G Gl define SSD1963 CMD SI eal define SSD1963 CMD G Ly define SSD1963 CMD SI ral 1998 2012 HP InfoTech S R L Page 242 CodeVisionAVR define SSD1963 CMD GET DBC THRES 0xD5 Get the threshold for each level of power saving ET PLL OxEO Start the PLL ET MN OxE2 Set the PLL divider M and multiplier N define SSD1963 CMD GET PLL MN OxE3 Get the PLL divider M and multiplier N GET PLL STATUS OxE4 Get the current PLL status DEEP SLEEP OxE5 Set deep sleep mode PLL will be stopped define SSD1963 CMD SET PCLK 0xE6 Set pixel clock LSHIFT signal frequency define SSD1963 CMD GET PCLK 0xE7 Get pixel clock LSHIFT signal frequency settings define SSD1963 CMD SET PDATA INTERFACE OxF0O Set the pixel data format used for parallel mode communication with the uC define SSD1963 CM define SSD1963 CM gr
22. u x X the width and precision specifiers are supported only the t 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 2012 HP InfoTech S R L Page 162 CodeVisionAVR int 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 The function returns the number of outputed characters int 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 The function returns the number of outputed characters int vsnprintf char str unsigned char size char flash fmtstr va_list argptr for the TINY memory model int vsnprintf char str unsigned int size char flash fmtstr va_list argptr for the other memory models this functi
23. 1998 2012 HP InfoTech S R L Page 296 CodeVisionAVR 4 18 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 d before using the functions The Power Management Functions are void sleep_enable void this function enables entering the low power consumption modes void sleep_disable void this function disables entering the low power consumption modes It is used to disable accidental entering the low power consumption modes void idle void this function puts the AVR chip in the idle mode Prior to using this function the sleep_enable function must be invoked to allow entering the low power consumption modes In this mode the CPU is stopped but the Timers Counters Watchdog and interrupt system continue operating The CPU can wake up from external triggered interrupts as well as internal ones void powerdown void this function puts the AVR chip in the powerdown mode Prior to using this function the sleep_enable function must be invoked to allow entering the low power consumption modes In this mode the external oscillator is stopped The AVR can wake up only from an external reset Watchdog time out or external level triggered interrupt void powersave void this function puts the AVR chip in the powe
24. 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 2012 HP InfoTech S R L Page 110 CodeVisionAVR 3 7 1 Specifying the RAM and EEPROM Storage Address for Global Variables 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 EEPROM at address 10h eeprom the in float b 0x10 structure beta is stored EEPROM at address 20h eeprom in lo struct s2 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 e
25. Current data sector unsigned long dir sect Sector containing the directory entry unsigned char dir ptr Pointer to the directory entry in the window unsigned char buf 512 File R W buffer FIL This structure is initialized by the f_open and discarded by the f_close functions 1998 2012 HP InfoTech S R L Page 310 CodeVisionAVR e The FILINFO type structure is used to hold the information returned by the f_stat and f_readdir functions typedef struct _FILINFO_ unsigned long fsize File size unsigned short fdate Last modified date unsigned short ftime Last modified time unsigned char fattrib Attribute char fname 13 Short file name DOS 8 3 format FILINFO The fdate structure member indicates the date when the file was modified or the directory was created It has the following format bits 0 4 Day 1 31 bits 5 8 Month 1 12 bits 9 15 Year starting with 1980 0 127 The ftime structure member indicates the time when the file was modified or the directory was created It has the following format bits 0 4 Second 2 0 29 bits 5 10 Minute 0 59 bits 11 15 Hour 0 23 The fattrib structure member indicates the file or directory attributes combination defined by the following macros AM_RDO Read Only attribute AM_HID Hidden attribute AM_SYS System attribute AM_VOL Volume attribute AM_DIR Directory a
26. ET_CGRAM_ADDR 0x40 into address counter AC text AC 0x00 text AC 0x10 text AC horizontal display resolution 16 text AC 0x1l0thorizontal_display_resolution 16 ET DDRAM ADDR 0x80 a 0x01 enter standby mode T CGRAM ADDR command define ST7920 ENABLE n ET CGRAM ADDR 0x02 enable vertical scroll mode and disable the ST7920 SET CG define ST7920 V RAM ADD ERT_SCR toggle reverse condi R command OLL 0x03 tion for a line of text define ST7920 REVERSE INE 0x04 set vertical scroll displacement address define ST7920 SET SCRO LL ADDR 0x40 set the vertical and horizontal addresses for the graphic display RAM into address counter define ST7920 SET _GDRA M ADDR 0x80 A detailed description of the above mentioned commands can be found in the ST7920 datasheet void st7920_wrdata unsigned char data Writes a data byte to the ST7920 controller Parameter data byte to be sent to the controller unsigned char st7920_rddata void Reads a data byte from the ST7920 controller 1998 2012 HP InfoTech S R L Page 261 CodeVisionAVR void glcd_cleartext void Clears the text overlay area when the character generator is used and sets the text display position at row 0 and column 0 void glcd_cleargraphics void Clears the LCD graphics overlay area by setting it s color to the cur
27. G8 Tools TE avrasm2 exe X conce 2 Her Using the Add button you can add a Program to the Tools menu Using the Remove button you can remove a Program from the Tools menu 1998 2012 HP InfoTech S R L Page 87 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 eS 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 2012 HP InfoTech S R L Page 88 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 Ch
28. The following ctrl command codes specified by the macros defined in the sdcard h header file can be issued to the disk_ioctl function e CTRL_SYNC wait until the disk drive has finished the write process The buff pointer must be NULL e GET_SECTOR_SIZE returns the size of the drive s sector The buff pointer must point to a 16bit unsigned int variable that will contain the sector size For MMC SD SD HC cards the returned sector size will be 512 bytes e GET _SECTOR_COUNT returns the total number of sectors on the drive The buff pointer must point to a 32bit unsigned long int variable that will contain the sector count e GET_BLOCK_SIZE returns the erase block size of the drive s memory array in sectors count The buff pointer must point to a 32bit unsigned long int variable that will contain the block size If the erase block size is not known the returned value will be 1 Example ATmegal28 I O register definitions include lt megal28 h gt MMC SD SD HC card support include lt sdcard h gt delay functions include lt delay h gt sprintf include lt stdio h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt Timerl overflow interrupt frequency Hz define T1 OVF_FREQ 100 Timerl clock prescaler value define Tl PRESC 10241 Timerl initializatio
29. VLCD set bits 0 127 GLCDINIT t The detailed description of the above mentioned initialization parameters can be found in the PCD8544 datasheet Notes e The glcd_pcd8544 h header file is automatically included when the main glcd h header file is included Therefore there is no need to explicitly include glcd_pcd8544 h e The EXAMPLES Graphic LCD PCD8544 directory contains fully functional code samples that may be used as references for PCD8544 initialization and usage 1998 2012 HP InfoTech S R L Page 223 CodeVisionAVR 4 12 3 Graphic LCD Functions Specific to the 1D13700 Controller In order to take full advantage of the S1D13700 controller s features the following specific functions declared in the glcd_s1d13700 h header file were implemented void s1d_wrcmd unsigned char cmd Writes a command to the 1D13700 controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the glcd_s1d13700 h header file define S1D13700 SYSTEM SET 0X40 Initialize device and display define S1D13700 MWRITE 0X42 Write to display memory define S1D13700 MREAD 0x43 Read from display memory define S1D13700 SCROLL 0X44 Set display start address and display regions define S1D13700 CSRW 0X46 Set cursor address define S1D13700_ CSRR 0X47 Read cursor address define S1D13700 CSRDIR_RIGHT OX4C Set dir
30. e The gled_block function doesn t access the text overlay display if present e The GLCD_PUTXOR GLCD_PUTOR GLCD_PUTNOT GLCD_PUTAND modes are supported only for displays with 2 colors monochrome e The GLCD_PUTTP mode is supported only for displays with more than 2 colors 1998 2012 HP InfoTech S R L Page 202 CodeVisionAVR unsigned long glcd_imagesize GLCDX_t width GLCDY_t height Returns the memory size in bytes needed to store a rectangular bitmap image Parameters width specifies the horizontal size of the rectangular display area height specifies the vertical size of the rectangular display area Return values image size or 0 if the width or height values are not valid unsigned long gicd_putimage GLCDX_t left GLCDY_t top unsigned char pimg GLCDBLOCKMODE_t mode Displays a bitmap image located in RAM at specified coordinates Parameters left specifies the horizontal coordinate of the left top corner of the image top specifies the vertical coordinate of the left top corner of the image pimg pointer to the image data which is located in RAM mode specifies how the display operation must be performed e GLCD_PUTCOPY copy a bitmap from memory to LCD overwriting previous display data e GLCD_PUTTP copy a bitmap from memory to LCD overwriting previous display data using transparent mode when an image pixel with the current transparency color must be displayed the background color at the pixel coor
31. 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 2012 HP InfoTech S R L Page 118 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 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
32. now define the new putchar function void putchar char c write your code here For the XMEGA 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 2012 HP InfoTech S R L Page 160 CodeVisionAVR int printf char flash fmtstr arg1 arg2 outputs formatted text using putchar according to the format specifiers in the fmtstr string The format specifier string fmtstr is constant and must be located in FLASH memory The implementation of printf is a reduced version of the standard C function This was necessary due to the specific needs of an embedded system and because the
33. 1998 2012 HP InfoTech S R L Page 387 CodeVisionAVR 5 2 Setting the External SRAM For the AVR chips that allow connection of external SRAM you can specify the size of this memory and wait state insertion by clicking on the External SRAM tl node of the CodeWizardAVR selection tree a CodeWizardAVR test cwp File Help External IRQ Timers UART Analog Comparator ADC SPI 12C 1 Wire LCD Bit Bange Project Information Chip Ports External SRAM size 32k v 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 2012 HP InfoTech S R L Page 388 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 configur
34. Non Inverted Pw Z Overflow Interrupt Compare Match amp Interrupt Compare Match B Interrupt Timer Value 0 h Compare 40 Compare B 80 1998 2012 HP InfoTech S R L Page 395 CodeVisionAVR By selecting the Timer 1 tab you can have the following options Timers Counters Settings Timert Status Requirements Period 1 000000 4 ms Duty Cycle A 25 00 4 x B 50 00 4 x c 75 00 4 x Obtained Period 1 ms 0 00 error Apply rae Timer Timer2 Timer3 Time 4 gt Clock Source System Clock z Clock Value 16000 000kHz Mode Ph amp ff cor PWM top ICR1 Out 4 Nonny v ut B Nonny x Dut C Nondny Input Capture Noise Cancel T Rising Edge Interrupt on TE Timer Overflow a Input Capture v Value 0 h Inp Capture 1F40 h Comp 7D0 hB FAQ hCO 1770 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 1 output C and depends of the functioning mode Inp Capt specifies the timer counter 1 capture trigger edge and if the
35. 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 XMEGA chips the SPI library also contains the following function void spi_init bool master_mode bool Isb_first SPILMODE_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 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 2012 HP InfoTech S R L Page 293 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_DI
36. defini P z B are 10 using AVR Studio 10 include lt xmbits_al h gt bit d a t i 11 11 The VTARGET LED on the STK60 jp a ae ete A 12 General Purpose 1 0 Register oe Ti er Files 0x00 k 13 Make the folloving connectio R latcbseglacsa eerie PC3 R P i 14 Pc3 RS232 SPARE TXD esas corde bat witch 16 sfrb GPIO3 0x03 SER 16 Connect the STK600 RS232 out 17 afrb cPros 0x04 17 Make sure to configure the C 1e afrb Gpros 0x0s switch Cdo oia 19 sfrb GPIO6 0x06 case 19 L 7 20 sfrb GPIO7 0x07 20 21 sfrb GPIO8 0x08 void main void 21 1 22 sfrb GPIO9 0x09 22 23 sfrb cproa ox0a 4 n lt m 4 4 m EH Messages vi B Ernos B wamings 20 1 Insert p K 1998 2012 HP InfoTech S R L Page 13 CodeVisionAVR In order to undock a window its top bar must be clicked with the left mouse button and keeping the button pressed dragged to any suitable position on the desktop SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usart prj File Edit Search View Project Tools Settings Help Besc r Heacoa mMRRe AOA BEE SE Code Information v 7 E Aias o usart c E Al Includes H A Macros ea Typedefs 47 Global Static Fi Functions f mainfvoid Code Navigator x E amp Y CodeVisionAVR The 2 a Hian usart Wan ti usart c Meke Al Headers stdio h The
37. read the temperature of DS1621 0 10 C t0O dsl621 temperature 10 0 read the temperature of DS1621 1 10 C ti dsl621 temperature 10 1 prepare the displayed temperatures in the display buffer sprintf display buffer t0 i u cC nt1l i u scC t0 10 abs t0 10 Oxdf t1 10 abs t1 10 Oxdf display the temperatures led_clear lcd puts display buffer 1998 2012 HP InfoTech S R L Page 361 CodeVisionAVR 4 22 6 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 d before using the functions The 1 Wire bus functions prototypes are automatically include d with the ds1820 h The 1 Wire functions must be configured by specifying the I O port and bit used for communication through the 1 Wire protocol This is accomplished in the Project Configure C Compiler Libraries 1 Wire menu e the Enable 1 Wire Bus Interface Support option must be activated e the I O Port and Bit must be specified in Data Connection The DS1820 DS183820 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 co
38. 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 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 sp
39. 0 x 2x ClkPer Initialization Delay 0 t4 2x CikPer Refresh Period 1 4 2x CikPer SDRAM Self Refresh X Cancel 2 Help These options are described in detail in Atmel s XMEGA A Manual in the EBI External Bus Interface chapter Note All the necessary code for EBI setup will be automatically added by the compiler in the startup initialization that is executed immediately after the chip reset There is no need for the programmer to write his own code for this purpose When SDRAM is used as external memory and a different clock source is used instead of the internal 2MHz oscillator it is necessary to execute the function that configures the system clocks before the EBI setup sequence which will ensure that correct timing is used for later SDRAM access by the startup code 1998 2012 HP InfoTech S R L Page 54 CodeVisionAVR This can be achieved by using the __ reset attribute applied to the clock initialization function _ reset void system clocks init void Initialization code The code generated by the CodeWizardAVR for XMEGA chips automatically handles such situations The Advanced tab which is present only in the Advanced and Professional versions of the compiler enables more detailed custom configuration like the number and jump type of the interrupt vectors and memory usage NX Configure Project MULTFILE PRJ Ez l Files c Compiler Before Bu
40. 2 v DB3 PORTA Bit 3 DB4 PORTA Bit 4 v DB5 PORTA Bit 5 v DB6 PORTA Bit 6 v DB PORTA Bi v AD PORTB Bit 0 v CS PORTS Bit 1 v RD PORTB mam Bit 2 AWR PORTE Bit 3 v RST PORTE Bit 4 v The Display Type list box allows to select the graphic controller type and LCD resolution The Use Image Storage in External Memory check box specifies if additional code will be generated for functions needed to read or write data from external memory used for graphic image storage The Use Internal Font Only check box specifies for the gled_init function that only the internal character generator of the controller is used for displaying text Note This option is available only for graphic LCD controllers that have a built in character generator The connections between the graphic LCD module and the AVR I O ports can be specified individually for each signal in the Connections group box Note In order to obtain maximum performance it is advised to set the LCD controller s data bus bits to match the bits with the same numbers of the same AVR I O port 1998 2012 HP InfoTech S R L Page 491 CodeVisionAVR 6 19 Specifying the Project Information The information placed in the comment header located at the beginning of the C source file produced by CodeWizardAVR can be specified by clicking on the Project Information i node of the selection tree Project Information Proj
41. Bit Variables Size 24 y E Use GPIOR gt 31 Maximal Promote char to int V char is unsigned V 8 bit enums V Enhanced Par Passing 4 Smart Register Allocation Optimization Level Program Type Boot Loader 4096w V Automatic Global Register Allocation s printf Features int width s scanf Features Store Global Constants in FLASH Memory T Use an Extemal Startup Initialization File J Clear Global Variables at Program Startup F Stack End Markers File Output Format s COF ROM HEXEEP F Boot Loader Debugging in AVA Studio int width Preprocessor F Create Preprocessor Output Files V Include 1 0 Registers Bits Definitions Kites Gna 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 2012 HP InfoTech S R L Page 47 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 automatic variables saved in the Data Stack to be watched in AVR Studio 4 18 SP2 or later After finishing debugging the program this option should be
42. STK600 PORTC HEADER 1 GND 9 GND 2 5V 10 VCC 3 VLC LCD HEADER Vo 4 RS 1 PCO 5 RD 2 Pel 6 EN 3 PC2 11 D4 5 PC4 12 D5 6 PCS 13 D6 7 PCG 14 D7 8 PCT The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu 1998 2012 HP InfoTech S R L Page 182 CodeVisionAVR include the LCD driver routines include lt alcd 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 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 writing in Display RAM led_gotoxy 0 0 lced_putsf User char 0 display used defined char 0 lcd_putchar 0 while 1 loop forever unsigned char Icd_read_byte unsigned char addr reads a byte from the LCD character generator or display RAM The high level LCD Functions are void Icd_init unsigned char Icd_columns initializes the LCD module clears the displa
43. XN Configure Project sdcard4 prj f Files C Compiler Before Build After Build Code Generation Libraries Messages l Globally define Paths 1 Wire 120 MMC SD SD HC Card Alphanumeric LCD aled h V Enable Bit Banged 12C Support Data Connection 0 Port PORTD SDA 1 sct fo BitRate 100 4 kHz The following settings are available e Enable Bit Banged I2C Support allows the activation of the IC Bus Functions library e I O Port SDA and SCL specify in Data Connection the port and bits used for I C bus communication e Bit Rate specifies the frequency of the clock pulses on the SCL line 1998 2012 HP InfoTech S R L Page 60 CodeVisionAVR 2 3 5 6 Setting the MMC SD SD HC Card Library Options The Libraries tab is used for configuring specific driver libraries used by the compiler The MMC SD SD HC Card tab is used for configuring the I O port allocation for the MMC SD SD HC FLASH Memory Card Driver Functions fa Configure Project sdeard4 prj _ Files C Compiler Before Build After Build Code Generation Advanced Libraries Messages Globally define Paths 1wie 120 MMC SD SD HC Card Alphanumeric LCD aled h Grapl V Enable MMC SD SD HC Card and FAT Support E SPI Slow Clock Connections SPI Controller onPORTB Card Socket AVR
44. a Default Help e Auto Complete Function 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 2012 HP InfoTech S R L Page 94 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
45. cursor moves right address counter 1 define ST7920 ENTRY CURSOR_RIGHT 0x02 shift entire display define ST7920 ENTRY SHIFT DISPL 0x01 display control define ST7920 DISPLAY CTRL 0x08 display control bits display on define ST7920 DISPLAY ON 0x04 cursor on define ST7920 CURSOR_ON 0x02 character blinks at cursor position define ST7920 BLINK 0x01 cursor display shift control define ST7920 CURSOR DISPLAY SHIFT CTRL 0x10 cursor display shift control bits shift display define ST7920 SHIFT DISPLAY 0x08 shifts right define ST7920 SHIFT RIGHT 0x04 1998 2012 HP InfoTech S R L Page 260 CodeVisionAVR function set define ST7920 FUNC_SET function set control bits must not be applied at the same time change ST7920 8BIT o 8 bit interface select th x tended define ST7920 EXTENDED turn graphics define ST7920 G define ST7920 S displa RAPHICS writes DDRAM address start for line 1 of start for line 2 of start for line 3 of start for line 4 of define ST7920 S Extended command set define ST7920_ STANDBY enable the ST7920_SE 0x20 r ST7920 GRAPHICS ON first then ST7920 EXTENDED define ST7920 8BIT 0x10 command set 0x04 y on _ON 0x02 writes CGRAM address into address counter AC
46. define define define define define define define define define define define define define define define define define define define define define define define define define define SSD1963 CMD RD MEM STA SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS RT 0x2E Trans fer image information from 63 to uC starting with the ion specified by 63_CMD_SET_COLUMN_ADDR and 63 CMD SET PAGE ADDR efines the partial display ode area fines the vertical scrolling d fixed areas EAR OFF 0x34 Disable sending synchronization information from the display sending synchronization ation from the display read order from uC to frame er and from frame buffer to display panel LL START 0x37 Set the start of the vertical crolling area in the frame uffer t idle mode r idle mode et pixel format el el el el SSD19 locat SSD19 8SD19 D1963 CMD SET PARTIAL AREA 0x30 D m D1963 CMD SET SCROLL AREA 0x33 D an D1963 CMD SET T D1963 CMD SET TEAR ON 0x35 Enable inform D1963_ CMD SET ADDR MODE 0x36 Set buff the D1963_CMD_SET_SCRO S b D1963 CMD EXIT IDLE MODE 0x38 Exi D1963 CMD ENT IDLE MODE 0x39 Ente D1963 CMD SET PIXEL FORMAT 0
47. define define define define define Initi VR SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS al bits V define define define define define define define define define define define define define define define define define define define define define define define SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS xJ ay g Z S y E 60 63 66 69 T2 75 78 81 84 87 0 90 0 93 0 96 0 99 1 02 1 05 1 08 1 11 1 14 Ald 1 20 1 23 D2119 VCIX2_ 5V1 0 5 1V D2119 VCIX2_5V3 1 5 3V D2119 VCIX2_ 5V5 2 5 5V D2119 VCIX2_ 5V7 3 5 7V D2119 VCIX2_ 5V9 4 5 9V D2119 VCIX2 6V1 5 6 1V ization values for the VLCD63 voltage HO 3 from Power Control Reg 3 D2119 VLCD63_ 3V56 3 VLCD63 3 56V D2119 VLCD63_ 3V70 4 VLCD63 3 70V D2119 VLCD63 3V86 5 VLCD63 3 86V D2119 VLCD63 4V04 6 VLCD63 4 04V D2119 VLCD63 4V18 7 VLCD63 4 18V D2119 VLCD63 4V33 8 VLCD63 4 33V D2119 VLCD63 4V49 9 VLCD63 4 49V D2119 VLCD63 4V67 10 VLCD63 4 67V D2119 VLCD63 4V80 11 VLCD63 4 80V D2119 VLCD63 5V00 12 VLCD63 5 00V D2119 VLCD63_ 5V14 13 VLCD63 5 14V D2119 VLCD63_ 5V29 14 VLCD63 5 29V D2119 VLCD63_ 5V45 15 VLCD63 5 45V D
48. 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 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 1998 2012 HP InfoTech S R L Page 295 CodeVisionAVR the AD7896 will work in mode 1 high sampling performance CONVST 1 SCLK 0 PORTB 2 initialize the LCD led_init 16 lcd _putsf AD7896 SPI bus nVoltmeter delay ms 2000 led_clear read and display the ADC input voltage while 1 sprintf lcd_ buffer Uadc s4umv read adc led_clear lcd puts lcd buffer delay ms 100
49. fault state and restore normal operation when the fault condition is no longer active e Latched Mode the waveform output will remain in the fault state until the the fault condition is no longer active and the fault detection flag FDF in the AWEXn STATUS register will be cleared by software When both these conditions are met the waveform will return to normal operation at the next UPDATE condition e Cycle by Cycle Mode the waveform output will remain in the fault state until the the fault condition is no longer active When this condition is met the waveform will return to normal operation at the next UPDATE condition The On Chip Debug Break Request Triggers a Fault Condition option specifies if an OCD break request will be treated as a fault The Change Protection option allows to prevent unintentional changes to the Timer Counter CTRLA and AWeX OUTOVEN FDEMASK registers In order to initialize enabled Timers Counters the CodeWizardAVR generates the functions void temn_init void where m is the lowercase suffix of the I O port where the Timer Counter is implemented n is the number of the Timer Counter on the port starting with 0 An unused Timer Counter of type 0 can be disabled by calling the function void tc0_disable TC0_t ptc where ptc is a pointer to the correspoding TC0_t structure Example TCCO is not used so disable it tc0 disable amp TCCO0 An unused Timer Counter of type 1 can be disabled
50. flash unsigned char font default font after initialization pointer to the function used for reading a byte from external memory unsigned char readxmem GLCDMEMADDR t addr pointer to the function used for writing a byte to external memory void writexmem GLCDMEMADDR t addr unsigned char data unsigned char lcd_bias 1 0 1 9 LCD bias 1 1 7 LCD bias unsigned char lcd_bias 1 0 1 6 LCD bias 1 1 5 LCD bias unsigned char reverse x 1 reverse display horizontally ADC unsigned char revl132_x0 1 set to 1 for displays that use reversed RAM column address reverse x 1 driver and the pixel with x 0 is connected to column driver 132 unsigned char reverse y 1 reverse display vertically COM unsigned char volt_reg_v5 3 set V5 voltage regulator internal resistor ratio 0 7 unsigned char driving mode 2 set LCD driving mode 0 mode 1 1 mode 2 2 mode 3 3 mode 4 unsigned char lcd_contrast 5 LCD contrast voltage 0 63 GLCDINIT t The following macros are defined for initializing the members of the GLCDINIT_t structure values used for lcd_bias initialization define SPLC501 LCD BIAS 19 0 sets LCD bias drive ratio 1 9 define SPLC501 LCD BIAS 17 1 sets LCD bias drive ratio 1 7 values used for reverse x initialization define SPLC501 REVX_NORM 0 set relationship between RAM colum
51. lt stdio h gt include lt setjmp h gt declare the variable used to hold the CPU state jmp buf cpu_state void foo void printf Now we will make a long jump to main n r longjmp cpu_state 1 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 2012 HP InfoTech S R L Page 178 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 2012 HP InfoTech S R L Page 179 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 d before using the functions unsigned char bcd2bin unsigned char n Converts the number n from BCD representation to its binary equivalent unsigned char bin2bcd unsigned char n Converts the number n from binary representation to its BCD equivalent The number n values must be fr
52. set relationship between RAM column address and display driver normal MX 0 define UC1701 REVX_REV 1 set relationship between RAM column address and display driver reversed MX 1 values used for rev132_x0 initilization effective only when reverse x 1 UC1701 REVX_REV define UC1701 REV132 XONC 0 pixel with x 0 is not connected to column driver 132 when MX 1 define UC1701 REV132 XOCON 1 pixel with x 0 is connected to column driver 132 when MX 1 values used for reverse y initialization sets the vertical output scan direction 0 gt 63 define UC1701_REVY_NORM 0 sets the vertical output scan direction 63 gt 0 define UC1701_REVY_REV 1 values used for lcd_temp_comp initialization define UC1701 LCD TEMP COMP 005 0 0 05 C define UC1701 LCD TEMP COMP 011 1 0 11 C defaul initialization values default value for LCD bias define UC1701_ DEFAULT LCD BIAS UC1701_LCD BIAS LOW H c default value for reverse x define UC1701_ DEFAULT REVX UC1701 REVX NORM default value for rev132_x0 effective only when reverse_x 1 UC1701 REVX_REV define UC1701 DEFAULT REV132 X0 UC1701_ REV132_XONC default value for reverse y define UC1701_ DEFAULT REVY UC1701 REVY NORM default VLCD voltage regulator internal re
53. specifying accordingly the function parameter chip Maximum 8 DS1621 chips can be connected to the I C 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 void ds1621_twi_init TWI_MASTER_INFO_t ptwim this function is used to initialize the DS1621 library s internal variables when using the TWI Functions for Master Mode Operation for XMEGA Devices It is not used for non XMEGA devices The ptwim parameter must point to a TWI_LMASTER_INFO _t structure variable that is used to hold the information required by the TWI module when operating in master mode The ds1621_twi_init function must be called before ds1621_ init Refer to the supplied example at the end of this chapter for more details 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 2012 HP InfoTech S R L Page 357 CodeVisi
54. voltage follower bit 0 voltage regulator bit 1 voltage booster bit 2 define SED1530 VOLT FOLLOWER_ON 1 lt lt 0 enable voltage follower define SED1530 VOLT REGULATOR ON 1 lt lt 1 enable voltage regulator define SED1530 VOLT BOOSTER_ON 1 lt lt 2 enable voltage booster define SED1530 CMD ELECTRONIC VOLUME 0x80 sets the electronic volume register in order to control the V5 LCD drive voltage define SED1530 CMD RESET 0xE2 resets the controller A detailed description of the above mentioned commands can be found in the SED1530 datasheet 1998 2012 HP InfoTech S R L Page 227 CodeVisionAVR void sed1530_setcontrast unsigned char contrast Controls the LCD contrast Parameter contrast sets the value of the V5 LCD drive voltage allowed range is 0 31 The glcd_sed1530 h header file also contains the definition of the GLCDINIT_t type specific for the SED1530 controller used as parameter for the gled_init function typedef struct flash unsigned char font default font after initialization pointer to the function used for reading a byte from external memory unsigned char readxmem GLCDMEMADDR t addr pointer to the function used for writing a byte to external memory void writexmem GLCDMEMADDR t addr unsigned char data unsigned char lcd_bias 1 0 1 6 LCD bias 1 1 5 LCD bias unsigned char reverse x 1 reverse
55. 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 The ATmega8515 port and bit used for the 1 Wire bus must be specified in the Project Configure C Compiler Libraries 1 Wire menu 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 Ry 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 2012 HP InfoTech S R L Page 373 CodeVisionAVR m
56. 0 ol 1 0 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 TIUIVIWIXIY ZI CIN J 7 IL lalble dje figi hji j kil 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 2012 HP InfoTech S R L Page 31 CodeVisionAVR 2 2 4 10 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 characte
57. 1 The clkout parameter specifies the initialization value for the PCF 8563 CLKOUT Frequency register The pcef8563 h header file defines the following macros which allow the easy setting of the clkout parameter e RTC_CLKOUT_OFF disables the generation of pulses on the PCF8563 CLKOUT output RTC_CLKOUT_1 generates 1Hz pulses on the PCF8563 CLKOUT output RTC_CLKOUT_32 generates 32Hz pulses on the PCF8563 CLKOUT output RTC_CLKOUT_1024 generates 1024Hz pulses on the PCF8563 CLKOUT output RTC_CLKOUT_32768 generates 32768Hz pulses on the PCF8563 CLKOUT output 1998 2012 HP InfoTech S R L Page 335 CodeVisionAVR The timer_ctrl parameter specifies the initialization value for the PCF8563 Timer Control register The pcf8563 h header file defines the following macros which allow the easy setting of the timer_ctrl parameter e RTC_TIMER_OFF disables the PCF8563 Timer countdown 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 void pcf8563_twi_init TWI_MASTER_INFO_t ptwim this function is used to initialize the PCF8563 library s internal variables when using the TWI Functions for Master Mode Operation for XMEGA Devices It is not used
58. 11 1 LCD Functions for displays with up to 2x40 characters The Alphanumeric LCD Functions are intended for easy interfacing between C programs and alphanumeric LCD modules built with the Hitachi HD44780 controller or equivalent The prototypes for these functions are placed in the file aled h located in the INC subdirectory This file must be include d before using the functions For LCD modules that use the Samsung KS0073 controller the aled_ks0073 h header file must be used The LCD functions do support both the XMEGA and non XMEGA chips The following LCD formats are supported in aled h 1x8 2x12 3x12 1x16 2x16 2x20 4x20 2x24 and 2x40 characters The allocation of LCD module signals to the I O ports must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu The LCD power supply and contrast control voltage must also be connected according to the module data sheet The low level LCD Functions are 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_write data 0xe 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 Use an 2x16 alphanumeric LCD connected to the STK600 PORTC header as follows LCD
59. 2 for a 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 1998 2012 HP InfoTech S R L Page 348 CodeVisionAVR 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 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 day unsigned char month unsigned char year this function returns the current date measured by the RTC The day 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 day unsigned char month unsigned char year this function sets the current date of the RTC Example program for a DS1302 connected to an ATmega8515 chip the DS1302 is connected to ATmega8515 PORTB the IO signal is bit 3 the SCLK signal is bit 4 the RST
60. 29 SECTOR 3 BUCHAREST ROMANIA Phone 40 723469754 Fax 40 213261876 e mail office hpinfotech com Internet http Awww hpinfotech com http www hpinfotech biz http www hpinfotech ro 1998 2012 HP InfoTech S R L Page 501
61. 53 5 v md Checking the Coulomb Counter Enabled check box enables the Coulomb Counter Sigma Delta ADC The Accumulate Current Conversion Time list box specifies the 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 2012 HP InfoTech S R L Page 411 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 settin
62. AVR Studio 5 1 and Atmel Studio 6 Debuggers eessssseesssriesssrreserrrrssrerrssrernss 151 3 23 Compiling the Sample Code of the XMEGA Application Notes from Atmel 0 ce8 156 3 24 AIMS einan aa a a aa a a E a a aE Mista naan A 156 ILALA Genan a ech ad E et ed Lee ee 156 4 Library Functions Reference c ecccceceeeeeeseeeee cece eeeensceeeee seen seesensseaneeseeeeeseeseaeeeseeeseseenseeees 157 1998 2012 HP InfoTech S R L Page 5 CodeVisionAVR AA Character Type F unclone aime meusinch nas indineanamianas iasi toe 4 2 Standard C Input Output FUNCTIONS ccc ccececeeeesteeeeeeseeeeeeaeeeeescaeeseecsaeeeeeeseeeesesieeeeeseaas 159 4 3 Standard Library Functions 0 cece eect reece ee eeee eee eeeaae ee eenaaeeeeeeaaeeeeecaeeeeeeenaeeeeneneeesniaes 167 4 4 Mathematical FUNCUONS 1 i 2 4 is visi adiee ci viele eine denne hie 169 4 5 String FUNCtIONS 000 ee eee cece e centr eee e eee tenant reece RATANA AA Eaa E EARTE R NEEE EE TEAREN ea 172 4 6 Variable Length Argument Lists Macros sssseeeessesssrresesnnansannnseennaanannaaattnnaanannaaeennaanannaatennaanan 177 4 7 Non local JUMP FUNCTIONS senis aaa a anaa 178 4 8 BCD Conversion Functions cccecececceeeeeeeeeenee eee AEn AETERNE KERE E 180 4 9 Gray Code Conversion FUNCTIONS assesses recasin inii iraina Ea AAAA ANANA ARAA 180 4 10 Memory Access Macros 000 cece eeeeeeeeeeeeee ee eeeeeeeeeeeeaeeeeeeaaeeeseeaeeeeeeaeee
63. 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 for the Tout output The DS1621 devices are accessed through the Maxim Dallas Semiconductor DS1621 Thermometer Thermostat functions 1998 2012 HP InfoTech S R L Page 418 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
64. CMD HORIZ RAM ADDR 0x44 Addresses of horizontal start end window positions define SSD1289 CMD VERT RAM ADDR START 0x45 Address of vertical start window positions define SSD1289 CMD VERT RAM ADDR END 0x46 Address of vertical end window positions define SSD1289 CMD DRV POS START1 0x48 Driving start line position for screen 1 define SSD1289 CMD DRV POS END1 0x49 Driving end line position for screen 1 define SSD1289 CMD DRV POS START2 0x4a Driving start line position for screen 2 define SSD1289 CMD DRV POS END2 0x4b Driving end line position for screen 2 define SSD1289 CMD GDDRAMX 0x4e Set GDDRAM X address counter register define SSD1289 CMD GDDRAMY 0x4f Set GDDRAM Y address counter register A detailed description of the above mentioned command registers can be found in the SSD1289 datasheet void ssd1289_wrreg unsigned char index unsigned short data Writes data to a command register of the SSD1289 controller Parameters index command register index data to be written unsigned short ssd1289_rdreg unsigned char index Reads the contents of a command register of the SSD1289 controller Parameters index command register index void ssd1289_wrdata unsigned short data Writes data to the SSD1289 controller s Graphic Display RAM Parameters data to be written unsigned short ssd1289_rddata void Reads data from the SSD1289
65. Chinese BIG 5 and user defined characters use a 16x16 pixel matrix therefore may be displayed only on even horizontal text x coordinates 1998 2012 HP InfoTech S R L Page 262 CodeVisionAVR void glcd_definechar unsigned char c flash unsigned char data Defines a character in the LCD controller s character generator RAM Parameters c specifies the defined character s code must be 0 2 4 or 6 for the ST7920 controller data points to a 32 byte array located in FLASH that contains the character s definition The data in the array is organized as 16 horizontal rows each row containing 2 bytes of pixels byte 0 bit 0 gt pixel 7 on row 0 byte 0 bit 1 gt pixel 6 on row 0 byte O bit 7 gt pixel 0 on row 0 byte 1 bit 0 gt pixel 15 on row 0 byte 1 bit 1 gt pixel 14 on row 0 byte 1 bit 7 gt pixel 8 on row 0 byte 2 bit 0 gt pixel 7 on row 1 byte 2 bit 1 gt pixel 6 on row 1 byte 2 bit 7 gt pixel 0 on row 1 byte 3 bit O gt pixel 15 on row 1 byte 3 bit 1 gt pixel 14 on row 1 byte 3 bit 7 gt pixel 8 on row 1 Example include lt glcd h gt include lt delay h gt User defined characters flash char user def char 4 32 Character with code 0 0b00000000 0b11111111 0b00000000 ObO00000011 0600000000 Ob00000101 0600000000 Ob00001001 0600000000 0b00010001 0600000000 0Ob00100001 0600000000 0Ob01000001 0600000000 0b10000001 060
66. Chip ExtemalSRAM Ports 1wire TWI I2C Alphanumeric LCD v Two Wire Enabled Mode Twi Master x Bit Rate 100 24 kHz The AVR chip s Two Wire interface can be enabled by checking the Two Wire Enabled check box One of the two operating modes can be selected e TWI Master e TWI Slave In TWI Master mode the Bit Rate list box allows to specify maximum frequency of the pulses on the SCL Two Wire bus line This value will be passed to the twi_master_init function twi h called for initialization and will affect the value of the TWBR register When operating in TWI Master mode the twi_master_trans function from twi h must be used for bus communication 1998 2012 HP InfoTech S R L Page 425 CodeVisionAVR In TWI Slave mode the following options are available External IRQ Timers USARTO USART1 Analog Comparator ADC SPI 2E Bit Banged Project Information Chip l External SRAM Ports 1wire TWI I2C Alphanumeric LCD v Two Wire Enabled Mode Tw Slave x Match Any Slave Address 12C Slave Address 50 h Receive Buffer Size 16 MA Transmit Buffer Size 16 4 The Slave Address edit box sets the 7 bit slave address of the Two 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 Match Any Slave Address check box enables the slave to acknowledge for any slave address issued by the master
67. Chip Programmel cccceeeeeeeeeeeetneee erence ee erent ee eeeaeeeeeeeeeeeeiaeeeseeneeeeeeneeeeeeaas 83 2 4 3 The Serial Communication Terminal 0 ccccceeeeeeceeeeeeeeeeeeeeneeeeeenneeeeeeneeeeeeecaeeeseeneeeeeeaas 86 2 4 4 The LCD Vision Font and Image Editor Converter cccceeeeeeeeeeeeeenneeeeeeneeeeeeenaneeeeeaas 87 2 45 Executing User Programs i sisscicct ca hadewnsssacead eei aA OAR 87 2 4 6 Configuring the Tools Menu esseesid nananana KARNE ANARAN ANERKANNT 87 29 DE SeN Saena N T TN a fiade alvnteten AY 89 281 The Vow MON nises iraa AE EA E AEA EAE NEE 89 2 5 2 General IDE Settings eeeeeeesseeessresrrrreeerrrrssrnnnenisnaaattnneannntaatanaeatdnnnattanaaananaaaeaaaaaa annaa 89 2 95 9 Contiguring the Editi scien aaa ieee en ee i eee 90 2 5 3 1 General Editor Settings 0 0 22 ececeeee cence eeene ee ee etie test tees eeeeaeeeeesaeeeeesnaeeeeseneeeeeeeaas 90 2 9 9 2 Editor Text SOttINn GS eeann E E E EE eee Whites 92 2 5 3 3 Syntax Highlighting Settings eeeeeeeeeeeeeneeeeeneeeerresetrresttrrnsttrrrnnttnnnstnnnnnttnnnnnnrnnenn n 93 2 5 3 4 Auto Complete Settings sesse cece eect eee inatin iiei KATKERAN ERRANA ANR AEEA KATKERAAN 94 2 9 4 Setting the Debugger Pat i iicecicieesidectitieeeseiiieeneiiesihdaieasbnieereiiestblaibieeadaies 95 2 5 5 AVR Chip Programmer Setup cccccceeeeeeeceeceeeeeeeeeceneaeeeeeeeeeseceeaaeaeeeeeeeseeeenieeeeeeeeeees 96 2 5 6 Serial Communication Terminal Setup
68. 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 2012 HP InfoTech S R L Page 299 CodeVisionAVR 4 20 MMC SD SD HC FLASH Memory Card Driver Functions The MMC SD SD HC FLASH Memory Card Driver Functions are intended for interfacing between C programs and MMC SD SD HC cards using the SPI bus interface These low level functions are referenced by the high level FAT Access Functions The unctions are based on the open source drivers provided by Mr ChaN from Electronic Lives Mfg http elm chan org Before using the card driver functions the I O port signals employed for communication with the MMC SD SD HC card must be configured in the Project Configure C Compiler Libraries MMC SD SD HC Card menu Note The MMC SD SD HC card driver functions are not re entrant They must not be called from interrupt service routines The MMC SD SD HC card must be connected to the AVR microcontroller using a CD4050 CMOS buffer that will translate the 5V logic signals to 3 3V as needed by the card The co
69. Configure C Compiler Code Generation Enhanced Function Parameter Passing option enabled _ATXMEGA_DEVICE_ signals that the program is compiled for an XMEGA chip type _EXTERNAL_STARTUP_ signals that the Project Configure C Compiler Code Generation Use an External Startup Initialization File option is enabled _IO_BITS_DEFINITIONS _ if the Project Configure C Compiler Code Generation Preprocessor Include I O Registers Bits Definitions option is enbaled _SRAM_START_ the start address of on chip SRAM _SRAM_END_ the end address of the SRAM accessible to the compiled program including the eventual external memory _DSTACK_START_ the data stack starting address _DSTACK_END_ the last address of SRAM allocated for the data stack _DSTACK_SIZE_ the data stack size specified in the Project Configure C Compiler Code Generation Data Stack Size option _HEAP_START_ the heap starting address _HEAP_SIZE_ the heap size specified in the Project Configure C Compiler Code Generation Heap Size option 1998 2012 HP InfoTech S R L Page 102 CodeVisionAVR _UNSIGNED_CHAR_ if the Project Configure C Compiler Code Generation char is unsigned compiler option is enabled or pragma uchar 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 XMEGA chip USART is used by the getchar and putchar Standard C Input Output Functions _ATXMEGA_SP
70. DEFAULT TFT HOR PULSE WIDTH 41 D1963 DEFAULT TFT HOR FRONT PORCH 2 TFT D1963 DEFAULT HOR BACK PORCH 2 TET R PULSE WIDTH 10 D1963 DEFAULT D1963 DEFAULT R FRONT PORCH 2 V TFT V TFT V w a m R D1963 DEFAULT BACK PORCH 2 tft24bit to 18 bit TF D1963 DEFAU T T TFT DATA WIDTH SSD1963_ TFT DATA WIDTH18 1998 2012 HP InfoTech S R L Page 245 CodeVisionAVR elif _GLCD _ MAXX 800 amp amp _GLCD MAXY 480 7 800x480 display TFT LCD pixel clock frequency kHz define SSD1963 DEFAULT TFT PIXEL CLK FREQ 30000 define SSD1963 DEFAULT TFT HOR PULSE WIDTH 1 define SSD1963 DEFAULT TFT HOR FRONT PORCH 45 define SSD1963 DEFAULT TFT HOR BACK PORCH 210 define SSD1963 DEFAULT TFT VER PULSE WIDTH 1 define SSD1963 DEFAULT TFT VER FRONT PORCH 10 define SSD1963 DEFAULT TFT VER BACK PORCH 34 m F Py m F ai default tft24bit to 24 bit TFT define SSD1963 DEFAULT TFT DATA WIDTH SSD1963 TFT DATA WIDTH24 endif Default value for reverse x No horizontal reverse define SSD1963 DEFAULT REVX SSD1963_ REVX NORM Default value for reverse y No vertical reverse define SSD1963 DEFAULT REVY SSD1963_ REVY NORM Default value for cl_bits order
71. Error C cvavr examples MULTFILE Mile cf 3 function parameter 1 doesn t match it s previous declaration from file C cvavr examples MULTFILE file1 h line 3 Jump to Previous Declaration or Definition Copy Selecting this 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 EOh 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 2012 HP InfoTech S R L Page 74 CodeVisionAVR Press
72. 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 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
73. GLCDINIT t init Specify the current font init font font5x7 Specify the function used for reading data from external memory If not used set value to NULL init readxmem read_ext_ memory Specify the function used for writing data to external memory If not used set value to NULL init writexmem write ext _memory Initialize the LCD controller and graphics glcd_init amp init Follows the rest of the code 1998 2012 HP InfoTech S R L Page 195 CodeVisionAVR void glcd_display bool on Turns LCD on off Parameter on specifies display on off state void glcd_setcolor GLCDCOL_t foreground_color Sets the current foreground color that will be used for displaying text and graphics Parameter foreground_color specifies the foreground color void glcd_setbkcolor GLCDCOL_t background_color Sets the current background color that will be used for displaying text and graphics Parameter background_color specifies the background color void glcd_settpcolor GLCDCOL_t transparent_color Sets the transparency color for image displaying in transparent mode Parameter transparent_color specifies the transparency color When an image pixel with this color must be displayed in transparent mode GLCD_PUTTP the background color at the pixel coordinates will be used instead Note This function is available only for displays with more than 2 colors GLCDCOL_t gicd_g
74. HP InfoTech S R L Page 45 CodeVisionAVR 2 3 5 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 NN Configure Project MULTFILE PRJ Files C Compiler Before Build After Build Code Generation Libraries Messages Globally define Paths i RAM Chip AT megal 280 z Data Stack Size 1024 bytes Clock 8 000000 MH 24 Heap Size 0 bytes Memory Model Intemal RAM Size 8192 bytes Small External RAM Size 0 Optimize for F External RAM Wait State Size Code Generation Optimization Level Bit Variables Size 24 o Use GPIOR gt 31 Maximal Promote chartoint 4 char is unsigned J 8 bit enums V Enhanced Par Passing Z Smart Register Allocation Program Type Application i pp V Automatic Global Register Allocation s printt Features F Store Global Constants in FLASH Memory int width F Use an External Startup Initialization File s scant Features Clear Global Variables at Program Startup F Stack End Markers File Output Format s COF ROMHEXEEP int width Preprocessor E Create Preprocessor Output Files Z Include 1 0 Registers Bits Definitions
75. ILI9325 FRAME128 13 128Hz Default value for reverse x define IL19325 DEFAULT REVX I Default value for reverse y define IL19325 DEFAULT REVY I Default value for cl_bits order color bits writing order to display RAM write in RGB order define ILI9325 DEFAULT CL BITS ILI9325 CL BITS RGB Power control 1 BTO BT2 step up factor of the step up circuit DDVDH Vcil 2 VCL Vcil VGH Vcil 6 VGL Vcil 3 define ILI 9325 DEFAULT STEPUP FACTOR 2 Power control 1 APO AP2 adjusts the amount of current from the constant current source in the internal op amplififier circuit define ILI9325 DEFAULT CRT SOURCE 2 Power control 2 DC00 DC02 step up circuit 1 frequency define IL19325 DEFAULT STEPUP1 FREQ IL19325 STEPUP1_ FOSC4 Power control 2 DC10 DC12 step up circuit 2 frequency define IL19325 DEFAULT STEPUP2 FREQ ILI9325 STEPUP2 FOSC128 Default value for VREGIOUT voltage define ILI9325 DEFAULT VREGIOUT ILI9325 VREGLOUT_4Vv000 Default value for Vcom alternating drive voltage define ILI9325 DEFAULT VCOM ILI9325 VCOM 0 94 Default value for VcomH voltage VcomH VREG1OUT 0 835 define ILI9325 DEFAULT VCOMH ILI9325 VCOMH 835 Default value for LCD frame frequency define IL19325 DEFAULT FRAME FREQ ILI9325 FRAME96 Default i
76. InfoTech S R L Page 288 CodeVisionAVR PORTA PINOCT PORTA PINICT PORTA PIN2CT PORTA PIN3CT PORTA PIN4CT PORTA PINSCT PORTA PIN6CT PORTA PIN7CT aca fc Cr cg Ca a initialize pullup resi PORTE DIR 0x00 general TWI no external no SDA hold twi_init amp TWIC initialize PORT_INVEN bm PORT _OPC_TOTEM gc PORT INVEN bm PORT OPC TOTEM gc PORT INVEN bm PORT _OPC_ TOTEM gc PORT INVEN bm PORT _OPC_TOTEM gc PORT INVEN bm PORT _OPC_TOTEM gc PORT INVEN bm PORT OPC TOTEM gc PORT INVEN bm PORT _OPC_TOTEM gc PORT INVEN bm PORT _OPC_TOTEM gc PORTE as inputs used for reading switches stors are already present on the STK600 board d C initialization driver interface time false false the TWIC master use low pri twi _ master ini ority level interrupt t amp twi_master amp TWIC TWI MASTER INTLVL LO gc TWI BAUD REG MCU CLOCK FREQUENCY TWI_CLK RATE general TWI no external no SDA hold twi_init amp TWID initialize use low pri D initialization driver interface time false false the TWID slave ority level interrupt twi_slave_ init amp twi_slave amp TWID TWI_SLAVE INTLVL_LO gc false SLAVE ADDR 0 twi_slave_ test_data enable low PMIC CTRL PMI rx buffer sizeof twi_slave_ r
77. Page 215 CodeVisionAVR void ili9325_wrdata unsigned short data Writes data to the ILI9325 controller s Graphic Display RAM Parameters data to be written unsigned short ili9325_rddata void Reads data from the ILI9325 controller s Graphic Display RAM The glced_ili9325 h header file also contains the definition of the GLCDINIT_t type specific for the ILI9325 controller used as parameter for the gled_init function typedef struct flash unsigned char font pointer to the function used for reading a byte from external memory unsigned char memory void unsigned unsigned power unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned writexmem unsigned char reverse x 1 readxmem GLCDMEMADDR _ t addr char reverse y 1 char cl bits order 1 selects order to 0 gt RGI GLCDMEMADDR t addr pointer to the function used for writing a byte to external unsigned char data reverse display horizontally reverse display vertically the color bits writing the display RAM control registers bits char char char char char char char char stepup_factor 3 stepup_ freql 3 stepup freq2 3 rt_source 3 vreglout 4 veom 5 adjus al VREG1 adjus 6 vcomh frame _freq 4 adjusts the amplit ternating drive voltag
78. R L Page 376 CodeVisionAVR prepare the displayed temperatures in the display buffer sprintf display buffer tCO 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 The same example but the LM75 chips are accessed using the TWI Functions for Master Mode Operation for XMEGA Devices using the TWI of PORTD TWID of an ATxmega128A11 chip include the LM75 functions for TWI include lt lm75_ twi h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd 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 structure that holds information used by the TWID master for performing a TWI bus transaction TWI_ MASTER INFO t twid_master interrupt service routine for TWID master interrupt TWID TWIM vect void twid_master_ isr void twi_master int handler amp twid_ master TWI clock rate Hz define TWI CLK RATE 100000 void main void int t0 Elz initialize the LCD 2 rows by 16 columns lcd _init 16 general TWID initiali
79. RATE enable the Low interrupt level PMIC CTRL PMIC_LOLVLEN_ bm set the PCF8583 functions to use TWID pcf8583 twi _init amp twid master enable interrupts so that TWI can be used asm sei initialize the RTC 0 no dated alarm rtc_init 0 0 rtc_set_time 0 12 0 0 0 set time 12 00 00 00 on RTC 0 rtc_set_date 0 1 2 2011 set date 1 02 2011 on RTC 0 display the time and date continuously while 1 read the time from the RTC 0 rtc_get_time 0 amp hour min amp sec amp hsec read the date from the RTC 0 rtc_get_ date 0 amp day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec led_clear lcd puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month year lcd _ puts display buffer delay ms 500 0 5 second delay 1998 2012 HP InfoTech S R L Page 346 CodeVisionAVR PCF8583 example using the Software Bit Banged I2C Bus Functions include the PCF8583 functions for bit banged I2C The I2C bus connections and bit rate must be specified in the Project Configure C Compiler Libraries I2C menu include lt pcf8583 h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD me
80. RS232 out ie Mie FO printf H aaah ME cones ed 17 sfrb GPIO 0x04 stdarg ieee eta 18 sfrb GPIOS 0x05 mate o C E OSTADE Eu Tats B ioh oui 19 frb GPIO6 0x06 case FO _print 2 s s 0x06 a DSIA xmegal2Bal h 20 s rb GPIO7 0x07 iz 4 xmstruct h 21 sfrb GPIOs 0x08 void main void fQ stien E xmbits_at h 22 afrb cpros 0x09 DSTACK Func g unc B stdinth i lt 23 sfrb GPIOA 0x0A X BB stdbooth A meen H Messages v 30 B Eros B warnings 20 1 Insert After the mouse button will be released the window will become docked 1998 2012 HP InfoTech S R L Page 15 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 SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usart prj File Edit Search View Project Tools Settings Help LOeGS HeaOSOMARS o BE M H OPA BIBBBOL S 25 alg RB Code Information Y FO CAcvavr2 examples atkmege o B usart c HA E Notes usart c EJ gly 1 A Macros H Typedefs 4p Global Static Var SFO Functions ion FY mainfv dai lt E pf Function Call Tree oR Shain DSTACK Func 0 Total 0 B f printf B f _print DSTACK Func 26 T B f strlen Messages E DSTACK Func 10 T
81. Return values FR_OK success FR_NO_PATH couldn t find the path FR_INVALID_NAME the file or directory name is invalid FR_INVALID_DRIVE the drive number is invalid FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTENM there is no valid FAT partition on the disk 1998 2012 HP InfoTech S R L Page 333 CodeVisionAVR FRESULT f_chdrive unsigned char drv changes the current logical drive The initial logical drive is 0 Note After f_chdrive is called all subsequent file directory access function operations will be performed by default on the new logical drive if no other drive is specified when calling these functions Parameter drv specifies the logical drive number 0 9 to be set as current drive Return values FR_OK success FR_INVALID_DRIVE the drive number is invalid FRESULT f_mkfs unsigned char drv unsigned char number_fats unsigned short bytes_cluster creates a single primary partition on the drive and formats it Parameter drv specifies the logical drive number 0 9 to be formatted number_fats specifies the number of FATs to be created on the drive during formatting This parameter may take the values 1 o
82. STEPUP_FLINES 5 Fline 5 define SSD1289 STEPUP_FLINE4 6 Fline 4 define SSD1289 STEPUP_FLINE3 7 Fline 3 define SSD1289 STEPUP FLINE2 8 Fline 2 define SSD1289 STEPUP FLINE1 9 Fline 1 define SSD1289 STEPUP FOSC4 10 Fosc 4 Fosc 510kHz define SSD1289 STEPUP_FOSC6 11 Fosc 6 define SSD1289 STEPUP_FOSC8 12 Fosc 8 define SSD1289 STEPUP_FOSC10 13 Fosc 10 define SSD1289 STEPUP_FOSC12 14 Fosc 12 define SSD1289 STEPUP_FOSC16 15 Fosc 16 Initialization values for the VCIX2 voltage define SSD1289 VCIX2_ 5V1 0 5 1V define SSD1289 VCIX2_ 5V2 1 5 2V define SSD1289 VCIX2_ 5V3 2 5 3V define SSD1289 VCIX2_ 5V4 3 5 4V define SSD1289 VCIX2_ 5V5 4 5 5V define SSD1289 VCIX2_ 5V6 5 5 6V define SSD1289 VCIX2_ 5V7 6 5 7V define SSD1289 VCIX2_ 5V8 7 5 8V 1998 2012 HP InfoTech S R L Page 236 CodeVisionAVR Initialization values for the define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS Initial D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD D1289 VLCD 63_3V08 63 3v24 63 3v40 63 3V56 63 3V70 63 3V86 63 4v04 63 4v18 63 4V33 63 4v4
83. Select the Object File To Debug edit box allows to specify the path where the COFF object file created by CodeVisionAVR for the current project is located The path can be selected using the button The Project Name edit box must contain the name for the new debugger s project solution to be created The Location edit box allows to specify the path where the files associated with the newly created project solution will be located This path can be selected using the button After the above information was completed the Next button must be pressed 1998 2012 HP InfoTech S R L Page 151 CodeVisionAVR A new dialog window will open Open Object File For Debugging Project Creation Wizard Device Selection Select the Target MCU device Device Family All x Search for device Name App Boot Memory Kbytes Data Memory bytes EEPROM bytes Device Info ATxmega128A1 136 8192 2048 Device Name ATxmega128A1 ATxmega128A1U 136 8192 2048 ATxmega128A1U 136 8192 2048 Speed 32 ATxmega128A3 136 8192 2048 Vee 1 6 3 6 ATxmegal28A3 136 8192 2048 ATxmega128A3U 136 8192 2048 Ea en ATxmegal28A3U 136 8192 2048 B Datasheets 4 ATxmegal28A4U 136 8192 2048 y ATxmegal28A4U 136 8192 2048 AVR Studio Supported Tools ATxmega128B1 136 8192 2048 ATxmega12881 136 8192 2048 gt AVR Dragon allowing to select the Target MCU device for debugging A
84. The alarm status for all the DS18B20 devices on the 1 Wire 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 the ATmega8515 port and bit used for the 1 Wire bus must be specified in the Project Configure C Compiler Libraries 1 Wire menu 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
85. The sizes of the Receive and Transmit Buffers can be set accordingly All the above mentioned options will be passed to the twi_slave_init function twi h called for initialization The CodeWizardAVR will also generate code for the twi_rx_handler and twi_tx_handler functions used for TWI slave reception and transmission An example of usage for these functions can be found in the chapter 4 13 2 Two Wire Interface Functions for Slave Mode Operation 1998 2012 HP InfoTech S R L Page 426 CodeVisionAVR 5 16 Setting the Two Wire Bus Slave Interface for the ATtiny20 40 chips The Two Wire Interface slave configuration for the ATtiny20 40 chips can be specified by clicking on the corresponding Tull node of the CodeWizardAVR selection tree Analog Comparator ADC SPI 120 Bit Banged Project Information Chip Ports External IRQ Timers 1 Wire TWI Slave LCD v Two Wire Enabled General Call Recognition Slave Address 0 oh Use TWI Slave Mask Address Second Slave Address 0 h SDA Hold Time Enabled TWI Smart Mode TW Promiscous Mode Two Wire Data Interrupt Two Wire Address Stop Interrupt Two Wire Stop Interrupt TWI Acknowledge Action Send ACK z The AVR chip s Two Wire Slave interface can be enabled by checking the Two Wire Enabled check box If the General Call Recognition check box is checked the general call recognition logic is enabled and bit 0 of the TWSA register will be set The Slave Address edit box
86. Typedefs 2 Sample program to test the A 2 C 1998 2009 Pavel Haiduc lie AF Global Static Van 3 Use a STK600 development boa 3 Ft Functions 4 STK600 RC100xX 13 addapters 7 4 Peripheral Modules and Inter FO mainly 5 E s Go 6 The STK600 programmer must b 6 ifndef _XMEGA128A1_INCLUDED_ 7 in the Tools Programmer menu 7 define __XMEGA128A1_INCLUDED__ while 8 e a while O a he VIARGET a 9 include lt xmstruct h gt defini fe Code Navigator 10 include lt xmbits_al h gt bit d ra f the STK60 Sal for G EY CodeVision VR 12 General Purpose I O Register ns S Project usart E id 13 sfrb GPIO0 0x00 ef Function Call Tree Notes J 14 sfrb GPIO1 0x01 S TXD rare switch O 8 aain usart c 15 sfrb GPIO2Z 0x02 mens DSTACK Func 0 Total 0 Headers 26292 ont 16 sfrb GPIO3 0x03 80 printf BA stdio h Se tiara 17 sfrb GPIO4 0x04 E DSTACK Fune 10 Total 10 A stdarg h 18 sfrb GPIOS 0x0 switch A iF _print ioh 19 sfrb GPIO6 0x06 case E DSTACK Func 26 Total 36 xmegal28a1 h 20 sfrb GPIO7 0x07 B f strlen B xmstructh 21 sfrb GPIO8 0x08 oid mainivoid DSTACK Func eee bec gt 22 strb GPIO9 0x09 8 ne NSS a pies J 23 sfrb GPIOA 0x0A B stdinth gt o a a B stdboolh Oe ee r Messages 7 m B Ers B Wamings 20 1 Insert When the mouse cursor arrives on one of the docking markers the future docking position w
87. Use a S i i stdio h 4 stK600 A stdarg h 5 B ioh 6 The STK xmegal 28 H in the xmstruct h 8 Bi xmbits_a1 9 Meke su B stdint h 10 using A B stdbool h 11 The VTA Bi Other Files 12 13 Make th 14 PCS E 25 16 Connect 17 Make su 18 to 9600 19 7 20 21 includ 22 includ aa 4 m r 20 1 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 2012 HP InfoTech S R L Page 19 CodeVisionAVR Clicking with the mouse on the window icon will open a specific drop down menu SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usart prj File Edit Search View Project Tools Settings Help BeS HPEAOCES GS NRG Liv amp y fo 8 RAM Bt ef Function Call Tree 70 BF main E DSTACK Func 0 Total C Alternatively this menu can be also invoked by right clicking with the mouse inside the window oy on vV Expand Functions Branches 10 11 12 13 14 15 16 20 0 52 8 8 a fiz RE Code Information Y FG CAcvavi2 examples atimega USARTCO usart c 9 o B V Sort Alphabetically T E Includes amp Mt Macros Expand Includes Branches a oe Ra Typedets a i i the ATx 5 4 Global Static Va Sr ee t board F Functions Expand Typedefs Branches ters f main void F Expand Variables Branches ae Expand Constants Branches menu
88. a circle at specified center coordinates using the current foreground color and line thickness Parameters x specifies the horizontal coordinate of the circle s center y specifies the vertical coordinate of the circle s center radius specifies the circle s radius void glcd_arc GLCDX_t x GLCDY_t y unsigned short start_angle unsigned short end_angle GLCDRAD_t radius Draws an arc of a circle at specified center coordinates using the current foreground color and line thickness The angles are measured in degrees starting from the three o clock position counter clockwise Parameters x specifies the horizontal coordinate of the circle s center y specifies the vertical coordinate of the circle s center start_angle specifies the arc s starting angle end_angle specifies the arc s ending angle radius specifies the circle s radius void glcd_getarccoords GLCDARCCOORDS t arccoords Fills aGLCDARCCOORDS type structure with information about the last call to the glcd_arc function Parameter arccoords points to a GLCDARCCOORDS t type structure void glcd_setfill unsigned char pattern GLCDCOL_t color Sets an user defined 8x8 pixel fill pattern from RAM used by the gled_bar and glcd_barrel functions and the fill color Parameters pattern points to an 8 byte array that holds the fill pattern color specifies the current color used by the filling functions void glcd_setfillf flash unsigned char pattern GLCDCOL_t color Set
89. 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 2012 HP InfoTech S R L Page 117 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 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
90. be also closed by clicking on the icon located on the top right of the tabbed control The Editor can display the edited files in one of the following modes e Single Editor Pane e Dual Vertical Editor Pane e Dual Horizontal Editor Pane Switching between the above mentioned modes is performed using the View File Panes menu or the buttons of the View toolbar 1998 2012 HP InfoTech S R L Page 24 CodeVisionAVR In dual editor pane mode the active pane is selected by left clicking with the mouse on the pane s top caption bar C cvavr2 examples atxymega USART CO usart c C cvayr2 inc xmegal 28a1 h All File Edit Search menu operations will be performed on the active editor pane The editor panes can be resized by dragging the pane splitter with the mouse An editor pane can be maximized by double clicking with the mouse left button on its top caption bar By double clicking once again the pane is restored to its original size 1998 2012 HP InfoTech S R L Page 25 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
91. 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 its 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 its 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 The ATmega8515 port and bit used for the 1 Wire bus must be specified in the Project Configure C Compiler Libraries 1 Wire menu 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 D
92. by the f_chdrive function file txt a file located in the root directory of the current drive O file txt a file located in the current directory specified previously by the f_chdir function on the logical drive 0 0 the root directory of logical drive 0 0 file txt a file located in the root directory of logical drive 0 current directory parent directory of the current directory The file_name must have the DOS 8 3 short file name format 1998 2012 HP InfoTech S R L Page 313 CodeVisionAVR mode is the file access type and open method represented by a combination of the flags specified by the following macros FA_READ Read access to the object Data can be read from the file For read write access it must be combined with FA_WRITE FA_WRITE Write access to the object Data can be written to the file For read write access it must be combined with FA_READ FA_OPEN_ EXISTING Opens the file If the file doesn t exist the function will fail FA_OPEN_ALWAYS If the file exists it will be opened If the file doesn t exist it will be first created and then opened FA_CREATE_NEW Creates a new file If the file already exists the function will fail FA_CREATE_ALWAYS Creates a new file If the file already exists it will be overwritten and its size set to 0 Return values FR_OK success FR_NO_FILE couldn t find the file FR_NO_PATH couldn t find the path FR_INVALID_NAME t
93. bypassed and I O pin direction must be configured by the user software sda_hold enables an internal hold time on the SDA signal with respect to the negative edge of SCL For XMEGA AU chips sda_hold can take one of the following predefined values TWI_SDAHOLD_OFF_gc SDA Hold Time off TWI_SDAHOLD_50NS_gc SDA Hold Time 50 ns TWI_SDAHOLD_300NS_gc SDA Hold Time 300 ns TWI_SDAHOLD_400NS_gc SDA Hold Time 400 ns For the rest of XMEGA chips sda_hold can take one of the following values 0 SDA Hold Time off TWI_SDAHOLD_bm SDA Hold Time on 1998 2012 HP InfoTech S R L Page 280 CodeVisionAVR 4 15 1 Two Wire Interface Functions for Master Mode Operation The following structure data type is defined in the twix h header file for operating the XMEGA TWI in master mode typedef struct TWI_t module pointer to the used TWI interface module unsigned char slave address I2C slave address unsigned char tx buffer pointer to the transmit buffer unsigned char bytes to tx number of bytes to transmit to the slave unsigned char tx counter number of transmitted bytes unsigned char rx buffer pointer to receive buffer unsigned char bytes to rx number of bytes to receive from the slave ey unsigned char rx counter number of received bytes unsigned char result transaction result TWI_MASTER INFO t The TWI_MASTER_INFO _t data type is used for d
94. can specify the size of the circular buffer using the Transmitter Buffer spinedit box The communication Baud rate can be specified using the UART Baud Rate list box CodeWizardAVR will automatically set the UBRR according to the Baud rate and AVR chip clock frequency The Baud rate error for these parameters will be calculated and displayed The Communications Parameters list box allows you to specify the number of data bits stop bits and parity used for serial communication 1998 2012 HP InfoTech S R L Page 403 CodeVisionAVR For devices featuring an USART there will be an additional Mode list box amp CodeWizardAVR test cwp 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 I
95. channel 0 in differential mode with both and inputs connected internally together e ADC Compare Register allows to specify the initial value for the ADC CMPL and CMPH registers For each ADC channel there is the possibility to specify the following options e Input Mode specifies which signals are applied to the ADC channel Internal positive input Single ended external positive input signal Differential external input signal and Differential external input signal with gain For the last input mode there is also the option to select the Gain Factor Channel 0 Channel 1 Channel 2 Channel 3 Input Mode Differential input signal with gain Gain Factor 1 x Positive Input ADCOpin ss Negative Input ADC4 pin X Interrupt Low Level z Interrupt Mode Conversion Complete z Note Differential input modes are available only for Signed ADC conversion mode e Positive Input allows to select which ADC pin will be used as channel s positive input for modes that use external input signals e Negative Input allows to select which ADC pin will be used as channel s negative input for Differential input modes e Interrupt allows to specify if an interrupt will be generated for the ADC channel by one of the events specified in the Interrupt Mode option Conversion Complete Compare Result Below Threshold and Compare Result Above Threshold For the last two Interrupt Modes the analog to digital conv
96. char vcoml 5 adjusts the amplitude of the VcomL alternating drive voltage unsigned char vcomh 5 adjusts the amplitude of the VcomH voltage VcomH VLCD63 0 35 vcomh 0 01 V unsigned char frame freq 4 LCD frame frequency positive gamma control registers bits unsigned char pkp00 3 PKPOO PKP02 positive gamma micro adj unsigned char pkpl0 3 PKP10 PKP12 positive gamma micro adj unsigned char pkp20 3 PKP20 PKP22 positive gamma micro adj unsigned char pkp30 3 PKP30 PKP32 positive gamma micro adj unsigned char pkp40 3 PKP40 PKP42 positive gamma micro adj unsigned char pkp50 3 PKP50 PKP52 positive gamma micro adj unsigned char prp00 3 PRPOO PRPO2 positive gamma gradient adj unsigned char prpl0 3 PRP10O PRP12 positive gamma gradient adj unsigned char vrp00 4 VRPOO VRPO3 positive gamma amplification adj unsigned char vrpl0 5 VRP10O VRP14 positive gamma amplification adj negative gamma control registers bits unsigned char pkn00 3 PKNOO PKNO2 negative gamma micro adj unsigned char pkn10 3 PKN10 PKN12 negative gamma micro adj unsigned char pkn20 3 PKN20 PKN22 positive gamma micro adj unsigned char pkn30 3 PKN30 PKN32 positive gamma micro adj unsigned char pkn40 3 PKN40 PKN42 negative gamma micro adj unsigned char pkn50 3 PKN50 PKN52 negative gamma micro adj unsigned char prn00 3 PR
97. code blocks is saved when the file is closed and it will be restored back when the file is opened again 1998 2012 HP InfoTech S R L Page 32 CodeVisionAVR 2 2 5 Saving a File The currently edited file can be saved by using the File Save menu command by pressing the Ctrl S keys or by pressing the 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 Ell 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 E Save C cvavr bin untitled c As rx Save in bin ae EP iv z Name r Date modified Type Size wP 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 2012 HP InfoTech S R L Page 33 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 usin
98. color line thickness and bit pattern The current pixel plot position will be updated to the ending point of the last line of the polygon Parameters npoints specifies the number of points of the polygon polypoints points to a an array of polygon point coordinates located in FLASH 1998 2012 HP InfoTech S R L Page 209 CodeVisionAVR Example Include the graphic LCD driver functions The LCD controller type and connections must be specified in the Project Configure C Compiler Libraries Graphic LCD menu include lt glcd h gt Array located in FLASH that holds the hexagon point coordinates The coordinate of the last point must match the ones of the first point so that the polygon will be closed So there will be 6 1 7 points for a hexagon flash GLCDPOINT t hexagon 7 40 0 57 10 57 30 40 40 23 30 23 10 40 0 void main void GLC DINIT t init We will not display any text so there s need for a font init font NULL No need for reading data from external memory init readxmem NULL No need for writing data to external memory init writexmem NULL 17 Initialize the LCD controller and graphics glcd_init amp init Draw the hexagon glcd_drawpoly 7 hexagon Stop here while 1 1998 2012 HP InfoTech S R L Page 210 CodeVisionAVR void glcd_circle GLCDX_t x GLCDY_t y GLCDRAD_t radius Draws
99. 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 XMEGA 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 lcdstk h located in the INC subdirectory This file must be include d 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 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 g
100. controller Parameter data byte to be sent to the controller unsigned char sed1335_rddata void Reads a data byte from the SED1335 controller 1998 2012 HP InfoTech S R L Page 225 CodeVisionAVR void sed1335_fastmode unsigned char on Specifies if the BUSY flag should be tested on data read write in order to reduce display flicker Parameter on if set to a non zero value specifies that the BUSY flag will not be tested in order to increase display speed however flicker will appear Notes e When the gled_init function is called it enables BUSY flag testing so that the display will not flicker e The gled_sed1335 h header file is automatically included when the main gled h header file is included Therefore there is no need to explicitly include glcd_sed1335 h e The EXAMPLES Graphic LCD SED1335 directory contains fully functional code samples that may be used as references for SED1335 initialization and usage 1998 2012 HP InfoTech S R L Page 226 CodeVisionAVR 4 12 5 Graphic LCD Functions Specific to the SED1530 Controller In order to take full advantage of the SED1530 controller s features the following specific functions declared in the glcd_sed1530 h header file were implemented void sed1530_wrcmd unsigned char cmd Writes a command to the SED1530 controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the follow
101. disk I O layer FR_INT_ERR 2 Assertion failed FR_NOT READY 3 The physical drive doesn t work FR_NO FILE 4 Could not find the file FR_NO_PATH 5 Could not find the path FR INVALID NAME 6 The path name format is invalid FR_DENIED 7 Acces denied due to prohibited access or directory full FR_EXIST 8 Acces denied due to prohibited access FR INVALID OBJECT 9 The file directory object is invalid FR WRITE PROTECTED 10 The physical drive is write protected FR_INVALID DRIVE 11 The logical drive number is invalid FR NOT ENABLED 12 The volume has no work area FR_NO_ FILESYSTEM 13 There is no valid FAT volume FR_MKFS_ ABORTED 14 f mkfs aborted due to a parameter error FR_TIMEOUT 15 Could not access the volume within the defined period FR_INVALID PARAMETER 19 19 Given parameter is invalid FRESULT 1998 2012 HP InfoTech S R L Page 309 CodeVisionAVR e The FATES type structure is used for holding the work area associated with each logical drive volume typedef struct _FATFS_ unsigned char fs_type FAT sub type unsigned char drive Physical drive number unsigned char csize Number of sectors per cluster unsigned char n_fats Number of FAT copies unsigned char wflag win dirty flag l must be written back unsigned s
102. display horizontally ADC unsigned char revl132_x0 1 set to 1 for displays that use reversed RAM column address reverse x 1 driver and the pixel with x 0 is connected to column driver 132 unsigned char reverse y 1 reverse display vertically COM unsigned char lcd_contrast 4 V5 LCD drive voltage 0 31 GLCDINIT t The following macros are defined for initializing the members of the GLCDINIT_t structure values used for lcd_bias initialization define SED1530 LCD BIAS 16 0 sets LCD bias drive ratio 1 6 define SED1530 LCD BIAS 15 1 sets LCD bias drive ratio 1 5 values used for reverse x initialization define SED1530 REVX_NORM 0 set relationship between RAM column address and display driver normal ADC 0 D1530 REVX REV 1 set relationship between RAM column address and display driver reversed ADC 1 sa define SI Gl values used for rev132_x0 initilization effective only when reverse x 1 SED1530 REVX_REV define SED1530 REV132 X0NC 0 pixel with x 0 is not connected to column driver 132 when ADC 1 define SED1530 REV132 X0CON 1 pixel with x 0 is connected to column driver 132 when ADC 1 Tr values used for reverse y initialization define SED1530 REVY_ NORM 0 sets the vertical COM output scan direction 0 gt 63 define SED1530 REVY REV 1 sets the vert
103. display the temperature s for i 0 i lt devices printf t u 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 2012 HP InfoTech S R L Page 368 CodeVisionAVR 4 22 8 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 d before using the functions The 1 Wire bus functions prototypes are automatically include d with the ds2430 h The 1 Wire functions must be configured by specifying the I O port and bit used for communication through the 1 Wire protocol This is accomplished in the Project Configure C Compiler Libraries 1 Wire menu e the Enable 1 Wire Bus Interface Support option must be activated e the I O Port and Bit must be specified in Data Connection 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 str
104. 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 2012 HP InfoTech S R L Page 106 CodeVisionAVR 3 6 Constants Integer or long integer constants may be written in decimal form e g 1234 in binary form with Ob prefix e g 0b101001 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
105. file that was previously initialized using the f_open function On success the function returns a positive value the number of written characters In case of error the function returns the value of the predefined macro EOF 1 1998 2012 HP InfoTech S R L Page 165 CodeVisionAVR int fscanf FIL fp char flash fmtstr this function is identical to scanf except that the formatted text is read from a file The fp pointer must point to a FIL type structure defined in the ff h header file that was previously initialized using the f_open function On success the function returns a positive value the number of read entries In case of error the function returns the value of the predefined macro EOF 1 1998 2012 HP InfoTech S R L Page 166 CodeVisionAVR 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 d 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 con
106. horizontal and vertical text justification settings will have no effect the text will be aligned to character cell boundaries specific to the controller If init_data is NULL then the default settings for the specific LCD controller will be used including the internal character generator if present Return values true on success false in case of error Note A 5x7 pixel font is supplied as standard with CodeVisionAVR 1998 2012 HP InfoTech S R L Page 194 CodeVisionAVR In order to use this font the font5x7 h header file must be include d and the GLCDINIT_t structure member font must be initialized with the font5x7 array address when glcd_init is called Additional fonts can be created using the LCD Vision font editor supplied with the Advanced version of CodeVisionAVR Example Include the graphic LCD driver functions The LCD controller type and connections must be specified in the Project Configure C Compiler Libraries Graphic LCD menu include lt glcd h gt Include the font definition include lt font5x7 h gt Function used for reading image data from external memory unsigned char read_ext_memory GLCDMEMADDR t addr unsigned char data Place your code here return data Function used for writing image data to external memory void write _ext_memory GLCDMEMADDR t addr unsigned char data Place your code here void main void
107. 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 2012 HP InfoTech S R L Page 101 CodeVisionAVR There are the following predefined macros __CODEVISIONAVR__ the version and revision of the compiler represented as an integer example for V2 05 2 this will be 2052 __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 option _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
108. included when the main gled h header file is included Therefore there is no need to explicitly include gled_st7920 h e The EXAMPLES Graphic LCD ST7920 directory contains fully functional code samples that may be used as references for ST7920 initialization and usage 1998 2012 HP InfoTech S R L Page 265 CodeVisionAVR 4 12 12 Graphic LCD Functions Specific to the T6963C Controller In order to take full advantage of the T6963C controller s features the following specific functions declared in the glcd_t6963 h header file were implemented void t6963_busy void Waits for the T6963 controller to become ready for reading or writing data by polling the STAO and STA1 flags Also sets C D 1 void t6963_wrcmd unsigned char cmd Writes a command to the T6963C controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the gled_t6963 h header file define T6963 SET CURSOR PTR 0x21 Set cursor pointer define T6963 SET OFFS REG 0x22 Set offset register define T6963 SET ADDR PTR 0x24 Set address pointer define T6963 SET TXT HOME ADDR 0x40 Set text RAM starting address define T6963 SET TXT_AREA 0x41 Set the number of text columns define T6963 SET GFX HOME ADDR 0x42 Set graphics RAM starting address define T6963 SET GFX AREA 0x43 Set the number of columns for graphic mode d
109. 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 2012 HP InfoTech S R L Page 137 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 corresponding 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 numb
110. 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 using the reduced core instruction set used in chips like ATtiny10 ATtiny20 ATtiny40 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 _ENHANCED_FUNC_PAR_PASSING_ if the program is compiled with the Project
111. it can be released If the file was opened in read only mode the memory allocated for the FIL type structure pointed by fp can be released without the need for previously calling the f_close function Parameter fp points to the FIL type structure that contains the file parameters This structure must have been previously initialized by calling the f_open function Return values FR_OK success FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_INVALID_ OBJECT the file was not opened with f_open 1998 2012 HP InfoTech S R L Page 316 CodeVisionAVR FRESULT f_sync FIL fp flushes the cached data when writing a file This function is useful for applications when a file is opened for a long time in write mode Calling f_sync periodically or right after f_write minimizes the risk of data loss due to power failure or media removal from the drive Note There is no need to call f_sync before f_close as the later also performs a write cache flush Parameter fp points to the FIL type structure that contains the file parameters This structure must have been previously initialized by calling the f_open function Return values FR_OK success FR_NOT_READY no disk access was possible due to missing media or other
112. kbytes 512 sector size in bytes 1024 1 2 kbytes we need to do the division by 2 directly in order to prevent unsigned long multiplication overflow for 8GB SD HC cards 2 display the number of free kbytes printf Free space on logical drive 0 lu kbytes r n free kbytes else an error occured display it and stop error res stop here while 1 Note When compiling the above example make sure that the s printf Features option in the Project Configure C Compiler Code Generation menu will be set to long width This will ensure that the unsigned long int file sizes will be displayed correctly by the printf function FRESULT f_mkdir const char path creates a new directory Parameter path points to a RAM based NULL terminated char string that represents the path name for the directory to be created Return values FR_OK success FR_NO_PATH couldn t find the path FR_INVALID_NAME the directory name is invalid FR_INVALID_DRIVE the drive number is invalid FR_EXIST the directory already exists FR_DENIED the directory couldn t be created because the directory table or disk are full FR_NOT_READY no disk access was possible due to missing media or other reason FR_WRITE_PROTECTED creating the directory was not possible because the media is write protected FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the fun
113. 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 the 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 t
114. memcmp void buf1 void buf2 unsigned char n for the TINY memory model signed char memcmp void buf1 void buf2 unsigned int n for the SMALL memory model Compares at most n bytes of buf1 with buf2 Returns lt 0 0 gt 0 according to buf1 lt buf2 buf1 buf2 buf1 gt buf2 signed char memcmpf void buf1 void flash buf2 unsigned char n for the TINY memory model signed char memcmpf void buf1 void flash buf2 unsigned int n for the SMALL memory model Compares at most n bytes of buf1 located in 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 2012 HP InfoTech S R L Page 176 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 d 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 cal
115. memory address addr and stores it in the string dest located in RAM It returns 1 if successful 0 if not The DS2433 device is selected using its 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 its 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 its 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 its ROM code stored in an array of 8 bytes located at address romcode 1998 2012 HP InfoTech S R L Page 372 CodeVisionAVR If only one DS2433 EEPROM is used no ROM code array is necessary and the pointer romcode must be NULL
116. must be called repeatedly When all items were read the function will return a empty NULL char string in the fname member of the FILINFO structure without any error Note The and directory entries are not filtered and will appear in the read entries Parameters dj points to the DIR type structure that holds directory information previously initialized by calling the f_opendir function fno points to the FILINFO type structure that will hold the file information for a read directory entry If a NULL pointer is passed as fno the directory entry read process will start from the begining Return values FR_OK success FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NO_FILESYSTENM there is no valid FAT partition on the disk Example ATmegal28 I O register definitions include lt megal28 h gt FAT on MMC SD SD HC card support include lt ff h gt printf include lt stdio h gt string functions include lt string h gt Timerl overflow interrupt frequency Hz define Tl OVF_FREQ 100 Timerl clock prescaler value define Tl PRESC 10241 Timerl initialization value after overflow define Tl_INIT 0x10000L _MCU_CLOCK_FREQUENCY_ T1_PRESC T1_OVF_FREQ
117. operation of the USB controller in both modes and the various settings for them are described in detail in the AT90USB datasheet 1998 2012 HP InfoTech S R L Page 434 CodeVisionAVR 5 22 Setting Bit Banged Peripherals The configuration of the peripherals connected using the bit banging method can be specified by clicking on the Bit Banged Peripherals BIT node of the CodeWizardAVR selection tree If you use the DS1302 RTC you must select the DS1302 tab a CodeWizardAVR test cwp File Help External IRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C 1wire 2wie 2c LCD Chip ExtemalSRAM Ports Bit Banged Project Information Pot PORTD x 1 0 Bit ov SCLKBit 1 CE RST Bit 2 v Trickle Charge Enabled Diodes 4 X Charge Resistor 2k v Using the Port list box you can specify which port is used for connecting with the DS1302 The I O Bit SCLK Bit and RST Bit list boxes allow you to specify 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 2012 HP InfoTech S R L Page 435 CodeVisionA
118. oscillator 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 5 button on the toolbar The characters can be displayed in ASCII or hexadecimal format The display mode can be toggled using the Hex ASCII button The received characters can be saved to a file using the Rx File button Any characters typed in the Terminal window will be transmitted through the PC serial port The entered characters can be deleted using the Backspace key By pressing the Send button the Terminal will transmit a character whose hexadecimal ASCII code value is specified in the Hex Code edit box By pressing the Tx File button the contents of a file can be transmitted through the serial port By pressing the Reset button the AVR chip on
119. pop up menu or by pressing the Ctrl keys 2 5 4 Setting the Debugger Path The CodeVisionAVR C Compiler is designed to work in conjunction with the Atmel AVR Studio debugger version 4 18 SP2 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 cence 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 2012 HP InfoTech S R L Page 95 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 MkII USB connection Atmel JTAGICE 3 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 programmer
120. r itl display the text written in each DS2430 if ds2430 read_block amp rom_code i 0 buffer START ADDR sizeof text printf Data read OK n rDS2430 u text s n r i l buffer else printf Error reading data from DS2430 u n r itl else printf Error writing data to DS2430 u n r itl stop while 1 Refer to the DS2430 data sheet for more information 1998 2012 HP InfoTech S R L Page 371 CodeVisionAVR 4 22 9 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 MINC subdirectory This file must be include d before using the functions The 1 Wire bus functions prototypes are automatically include d with the ds2433 h The 1 Wire functions must be configured by specifying the I O port and bit used for communication through the 1 Wire protocol This is accomplished in the Project Configure C Compiler Libraries 1 Wire menu e the Enable 1 Wire Bus Interface Support option must be activated e the I O Port and Bit must be specified in Data Connection The DS2433 functions are unsigned char ds2433_read_block unsigned char romcode unsigned char dest unsigned int addr unsigned int size this function reads a block of size bytes starting from the DS2433 EEPROM
121. ratio for LCD bias to 1 9 duty cycle 1 65 1 8 duty cycle 1 49 1 6 duty cycle 1 33 1 8 duty cycle 1 55 1 8 duty cycle 1 53 define ST7565 CMD LCD BIAS HIGH 0xA3 sets voltage ratio for LCD bias to 1 7 duty cycle 1 65 1 6 duty cycle 1 49 1 5 duty cycle 1 33 1 6 duty cycle 1 55 1 6 duty cycle 1 53 define ST7565 CMD COMO 63 DUTY OxCO sets the COM output scan direction 0 gt 63 and duty cycle define ST7565 CMD COM63 0 DUTY OxC8 sets the COM output scan direction 63 gt 0 and duty cycle 1998 2012 HP InfoTech S R L Page 256 CodeVisionAVR set the relationship between the ST7565 oscillator frequency Fosc display clock frequency Fcl and liquid crystal frame rate Ffr define ST7565 DUTY 1 65 0 duty cycle 1 65 Fcl Fosc 4 fr Fosc 4 65 132x65 max uty cycle 1 49 Fcl Fosc 4 fr Fosc 4 49 132x49 max uty cycle 1 33 Fcl Fosc 8 fr Fosc 8 33 132x33 max uty cycle 1 55 Fcl Fosc 4 fr Fosc 4 55 132x55 max uty cycle 1 53 Fcl Fosc 4 Ffr Fosc 4 53 132x53 max define ST7565 DUTY 1 49 1 define ST7565 DUTY 1 55 3 d F d E define ST7565 DUTY 1 33 2 d E d E d define ST7565 DUTY 1 53 4 define ST7565 CMD POWER CTRL 0x28 turns on off the voltage follower bit 0 voltage regulato
122. receive the bytes sent by the master and will display them on the LCD in ASCII form After a packet of bytes has been received the slav will transmit the char string Data packet received OK n r back to the master The LCD connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt io h gt include lt stdio h gt include lt twi h gt include lt delay h gt include lt alcd h gt include lt string h gt 7 bit slave I2C address define TWI SLAVE ADDR 0x50 slave receive buffer char rx_buffer 32 slave transmission buffer char tx_buffer 32 flag that signals that the TWI slave reception was OK bit received_ok false status messages flash char flash status_msg 8 OK Buffer overflow Arbitration lost Bus error NACK received Bus timeout Fail Unknown error J 1998 2012 HP InfoTech S R L Page 277 CodeVisionAVR bool slave _rx handler bool rx complete if twi_result TWI_RES_ OK received _ok true signal that data was received without errors else TWI receive error display the twi_result value on the LCD led_clear led putsf Receive error n led_putsf status_msg twi_result received _ok false signal that data was received with errors return false stop reception if rx _complete the TWI master has
123. reserved by the compiler These can not be used as identifier names _ eeprom _ flash interrupt _ task _Bool break bit bool case char const continue default defined do double eeprom else enum extern flash float for goto if inline int interrupt long register return short signed sizeof sfrb sfrw static struct switch typedef union unsigned void volatile while 1998 2012 HP InfoTech S R L Page 105 CodeVisionAVR 3 4 Identifiers An identifier is the name you give to a variable function label or other object An identifier can contain letters A Z a z and digits 0 9 as well as the underscore character _ However an identifier can only start with a letter or an underscore Case is significant i e variable1 is not the same as 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
124. 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 2012 HP InfoTech S R L Page 188 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 1998 2012 HP InfoTech S R L Page 189 CodeVisionAVR 4 12 Graphic LCD Functions The Graphic LCD Functions are intended for easy interfacing between C programs and graphic LCD modules built with a large variety of controllers The prototypes for these functions are placed in the file gled h located in the INC subdirectory This file must be include d before using the functions Before using these functions the type of the graphic LCD controller the I O port signals employed for communication with it and the display resolution must be specified in the Project Configure C Compiler Libraries Graphic LCD menu The following graphic LCD controllers are supported llitek ILI9325 for color 240x320 TFT displays Samsung KS0108 equivalent HD61202 Philips PCD8544 Epson 1D13700 S MOS Systems SED1520 equivalents NJU6450 PT6520 Epson SED1335 equivalent RA8835 Epson SED1530 Sunplus SPLC5
125. scroll control for screen 1 define SSD2119 CMD _VERT_SCROLL2 0x42 Vertical scroll control for l screen 2 1998 2012 HP InfoTech S R L Page 248 CodeVisionAVR define SSD2119 CMD HORIZ RAM ADDR 0x44 Addresses of horizontal start end window positions define SSD2119 CMD VERT RAM ADDR START 0x45 Address of vertical start window positions define SSD2119 CMD VERT RAM ADDR END 0x46 Address of vertical end window positions define SSD2119 CMD DRV POS START1 0x48 Driving start line position for screen 1 define SSD2119 CMD DRV POS END1 0x49 Driving end line position for screen 1 define SSD2119 CMD DRV POS START2 0x4a Driving start line position for screen 2 define SSD2119 CMD DRV POS END2 0x4b Driving end line position for screen 2 define SSD2119 CMD GDDRAMX 0x4e Set GDDRAM X address counter register define SSD2119 CMD _GDDRAMY 0x4f Set GDDRAM Y address counter register A detailed description of the above mentioned command registers can be found in the SSD2119 datasheet void ssd2119_wrreg unsigned char index unsigned short data Writes data to a command register of the SSD2119 controller Parameters index command register index data to be written unsigned short ssd2119_rdreg unsigned char index Reads the contents of a command register of the SSD2119 controller Parameters index command regi
126. sets the slave address of the Two Wire serial bus unit This address must be specified in hexadecimal and will be used to initialize the bits 1 7 of the TWSA register If the Use TWI Slave Mask Address option is enabled the contents of bits 1 7 of the TWSAM register will be used to mask disable the corresponding bits in the TWSA register If the mask bit is one the address match between the incoming address bit and the corresponding bit in TWSA is ignored In other words masked bits will always match 1998 2012 HP InfoTech S R L Page 427 CodeVisionAVR If the Use TWI Slave Mask Address option is disabled the contents of bits 1 7 of the TWSAM register will be used as a second slave address In this mode the slave will match on two unique addresses one in TWSA register and the other in TWSAM register The Second Slave Address or Slave Mask Address edit box sets the contents of bits 1 7 of the TWSAM register The value must be specified in hexadecimal The SDA Hold Time Enabled option specifies if the internal hold time on SDA with respect to the negative edge on SCL must be generated If the TWI Smart Mode option is enabled the TWI slave enters Smart Mode where the TWI Acknowledge Action is sent immediately after the TWI data register TWSD has been read When the TWI Promiscous Mode option is enabled the address match logic of the TWI slave responds to all received addresses ignoring the contents of the TWSA and TWSA
127. signal is bit 5 asm equ _ds1302 port 0x18 Address of the PORTB register equ _ ds1302_io 3 equ _ ds1302_sclk 4 equ __ds1302_rst 5 endasm include the D81302 include lt ds1302 h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line void main void unsigned char hour min sec day month year initialize the LCD 2 rows by 16 columns lcd_init 16 1998 2012 HP InfoTech S R L Page 349 CodeVisionAVR initialize the DS1302 RTC use trickle charge with 1 diode and 8K resistor rtc_init 1 1 3 rtc_set_time 12 0 0 set time 12 00 00 rtc_set_date 1 2 2011 set date 1 02 2011 display the time and date continuously while 1 read the time from the RTC rtc_get_time amp hour amp min amp Sec read the date from the RTC rtc_get_ date amp day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec led_clear lced_puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month 20
128. stdara h io h ef Function Call Tree xmegal28al h E 0 main oo A xmstruct h E DSTACK Func ow xmbits_ al h MEREN Ef0 printf By Mske E DSTACK a to 3 B f _print DSTACK Func 26 Eli strlen 21 ine E DSTACK Func 2 Total 38 22 inc Messages B Errors I The window can be resized by dragging its margins and corners with the left mouse button pressed 1998 2012 HP InfoTech S R L Page 14 CodeVisionAVR An undocked window can be docked to any position in the main application window or even to another docked window In order to dock the window its top bar must be dragged keeping the left mouse button pressed The possible dock locations of the window are outlined with special docking markers like in the picture below X CodeVisionAVR C cvavr2 examples atxmega USARTCO usart prj amp File Edit Search View Project Tools Settings Help Des HRPOGCMARS noc we S F x orvo S 2 88 BH tT eA 2 AX APP AS BP PBROrlel SSSS B N GES RAGS 2 KO R Code Infomation Y CNevaw2 evamples atamegatUSAATCOusaitc C ovavi2 ine wmegat28a1 E Code Templates 3 EJ R Clipboard Y 3 EJ D usate SE o t Includes Notes usart c Ed fry xmega128a1 h EJ Fe 5 4 Macros 1 j a 1 CodeVisionAVR C Compiler V2 a Ej
129. struct flash unsigned char font default font after initialization pointer to the function used for reading a byte from external memory unsigned char readxmem GLCDMEMADDR t addr pointer to the function used for writing a byte to external memory void writexmem GLCDMEMADDR t addr unsigned char data unsigned char lcd _bias 1 0 LCD bias voltage ratio low 1 LCD bias voltage ratio high unsigned char reverse xil reverse display horizontally MX unsigned char rev132_x0 1 set to 1 for displays that use reversed RAM column address reverse x 1 driver and the pixel with x 0 is connected to column driver 132 unsigned char reverse y 1 reverse display vertically MY 1998 2012 HP InfoTech S R L Page 269 CodeVisionAVR unsigned char volt_reg_ vlcd 3 set VLCD voltage regulator internal resistor ratio 0 7 unsigned char lcd_contrast 5 LCD contrast voltage 0 63 unsigned char lcd_temp_comp 1 LCD temperature compensation coefficient TC 0 0 05 C 1 0 11 C GLCDINIT t The following macros are defined for initializing the members of the GLCDINIT_t structure values used for lcd_bias initialization define UC1701 LCD BIAS 19 0 sets LCD bias drive ratio 1 9 1 8 1 7 define UC1701 LCD BIAS 17 1 sets LCD bias drive ratio 1 7 1 6 1 5 values used for reverse x initialization define UC1701 REVX_NORM 0
130. 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 2012 HP InfoTech S R L Page 86 CodeVisionAVR 2 4 4 The LCD Vision Font and Image Editor Converter LCD Vision is an application designed for creating editing font and image data and exporting it in form of C source code compatible with the CodeVisionAVR Graphic LCD Functions Fonts can be created from scratch or imported from the installed system fonts Images can be also created from scratch or imported from popular graphic formats like BMP JPG GIF PNG ICO WMF EMF LCD Vision is invoked using the Tools LCD Vision menu command or the button on the toolbar Note The LCD Vision editor converter can be used only with an Advanced CodeVisionAVR license 2 4 5 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 6 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 CS Configure Tools E
131. the USI Shift Register and Counter As both the USI Shift Register and Counter are clocked from the same clock source the USI Counter may be used to count the number of received or transmitted bits and generate an overflow interrupt when the data transfer is complete Checking the USI Counter Overflow Interrupt check box will generate code for an interrupt 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 12C bus in USI Two Wire operating mode 1998 2012 HP InfoTech S R L Page 415 CodeVisionAVR 5 13 Setting the I C Bus The I C bus configuration can be specified by clicking on the Bit Banged I C Bus Interface E node of the CodeWizardAVR selection tree amp CodeWizardAVR test cwp x File Help External IRQ Timers USARTO USART1 1 Wire 2Wire 20 LcD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC saa I2C Port PORTA SDA Bit o x SCL Bit 1 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 I C bus The SDA Bit and SCL Bit list boxes allow you to specify which port bits the IC bus uses 1998 2012 HP InfoTech S R L Page 416 CodeVis
132. the disk_initialize function has failed e STA_NODISK 0x02 bit 1 of function result This flag is set if no card is inserted in the socket Note the STA_NOINIT flag is also set in this situation e STA_PROTECT 0x04 bit 2 of function result Card is write protected If the STA_NODISK flag is also set the STA_PROTECT flag is not valid On success the function returns 0 which means all status flags are reset Note For the MMC SD SD HC card driver using the SPI interface the drv parameter must be always 0 otherwise the function will return with the STA_NOINIT flag set Example ATmegal28 I O register definitions include lt megal28 h gt MMC SD SD HC card support include lt sdcard h gt delay functions include lt delay h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt Timerl overflow interrupt frequency Hz define T1 OVF_FREQ 100 Timerl clock prescaler value define T1 PRESC 10241 Timerl initialization value after overflow define Tl_INIT 0x10000L _MCU_CLOCK_FREQUENCY_ T1_PRESC T1_OVF_FREQ 100Hz timer interrupt generated by ATmegal28 Timerl overflow interrupt TIM1_ OVF void timer comp_isr void re initialize Timerl TCNTIH T1_ INIT gt gt 8 TCNTIL T1_ INITS amp OxFF card access low level
133. the hardware TWI Functions for for Master Mode Operation XMEGA Devices The chip is connected to the TWI of PORTD TWID of an ATxmega128A1 include the PCF8583 functions for TWI include lt pcf8583 twi h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line structure that holds information used by the TWID master for performing a TWI bus transaction TWI_ MASTER INFO t twid_master interrupt service routine for TWID master interrupt TWID_TWIM vect void twid master_isr void twi_master int handler amp twid_ master TWI clock rate Hz define TWI_CLK_RATE 1998 2012 HP InfoTech S R L Page 345 CodeVisionAVR void main void unsigned char hour min sec hsec day month unsigned int year initialize the LCD 2 rows by 16 columns led_init 16 general TWID initialization no external driver interface no SDA hold time twi_init amp TWID false false enable and initialize the TWID master interrupt level low twi master init amp twid_ master amp TWID TWI MASTER INTLVL_LO gc TWI BAUD REG MCU CLOCK FREQUENCY TWI_CLK
134. 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 2012 HP InfoTech S R L Page 122 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 2012 HP InfoTech S R L Page 123 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 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 M
135. the order of variable declaration The 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 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 u
136. this function Parameters x specifies the horizontal pixel coordinate y specifies the vertical pixel coordinate void glcd_cirpixel GLCDX_t x GLCDY_t y Sets the color of the pixel at specified coordinates to the current background color Note The current pixel plot position coordinates are not affected by this function Parameters x specifies the horizontal pixel coordinate y specifies the vertical pixel coordinate 1998 2012 HP InfoTech S R L Page 197 CodeVisionAVR GLCDCOL_t glcd_getpixel GLCDX_t x GLCDY_t y Returns the color of the pixel at specified coordinates If the pixel coordinates are outside the display area the returned color will be 0 Note The current pixel plot position coordinates are not affected by this function Parameters x specifies the horizontal pixel coordinate y specifies the vertical pixel coordinate void glcd_moveto GLCDX_t x GLCDY_t y Moves the current pixel plot position to the specified coordinates Parameters x specifies the horizontal pixel coordinate y specifies the vertical pixel coordinate void glcd_moverel GLCDDX_t dx GLCDDY_t dy Moves the current pixel plot position to a new relative position Parameters dx specifies the horizontal displacement relative to the current pixel plot position dy specifies the vertical displacement relative to the current pixel plot position GLCDX_t glcd_getx void Returns the value of the current pixel plot position horizontal coordi
137. 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 2012 HP InfoTech S R L Page 119 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 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
138. to 5V on the SCL and SDA signals e The bit banged C Functions functions do not support the XMEGA chips The prototypes for these functions are placed in the file i2c h located in the INC subdirectory This file must be include d before using the functions These functions must be configured by specifying the I O port and bits used for communication through the C bus and the bit rate of the SCL clock This is accomplished in the Project Configure C Compiler Libraries I2C menu e the Enable Bit Banged I2C Support option must be activated e the I O Port SDA and SCL bits must be specified in Data Connection e the Bit Rate of the SCL signal must be set Note For compatibility with projects developed with CodeVisionAVR prior to V2 05 1 the C Functions can also be configured as outlined in the example below However in this case the Enable Bit Banged I2C Support option must be disabled in the Project Configure C Compiler Libraries I2C menu Example ATmega8515 PORTB bits 0 and 1 are used for the I2C bus signals SDA and SCL asm equ _ i2c port 0x18 equ _ sda bit 0 equ _ scl _bit 1 endasm now you can include the I2C Functions include lt i2c h gt This method is not recommended for new projects 1998 2012 HP InfoTech S R L Page 290 CodeVisionAVR The I C Functions are void i2c_init void this function initializes the 1 C bus This is the first function that must be called prior to u
139. to be sent to the controller This index may take one of the values defined in the following macros from the glcd_ssd1289 h header file SSD1289 command register definitions define SSD1289 CMD OSC 0x00 Oscillator register define SSD1289 CMD DRIVER _OUT 0x01 Driver output control define SSD1289 CMD DRIVING WAVEFORM 0x02 LCD driving waveform control OWER_CONTROL1 0x03 Power control 1 MP REG1 0x05 Compare register 1 _REG2 0x06 Compare register 2 PLAY CONTROL 0x07 Display control register E CYCLE 0x0b Frame cycle control register ER_CONTROL2 0x0c Power control 2 register ER_CONTROL3 0x0d Power control 3 register ER_CONTROL4 0x0e Power control 4 register E SCAN POS Ox0f Gate scan position register P_ MODE 0x10 Sleep mode register Y_MODE 0x11 Entry mode register IRIC_IF_CTRL 0x15 Generic interface control register ORIZ PORCH 0x16 Horizontal porch register ERT PORCH 0x17 Vertical porch register ER CONTROLS Oxle Power control 5 register RAM DATA 0x22 GDDRAM read write data register RAM WR_MASK1 0x23 GDDRAM write data mask 1 register define SSD1289 CMD GDDRAM WR _MASK2 0x24 GDDRAM write data mask 2 register 0x25 Frame frequency control register ROL1 0x30 Gamma control 1 ROL2 0x31 Gamma control ROL3 0x32 Gamma control 7 ROL4 0x33 Gamma control A ROL5 0x34 Gamma
140. transaction If no data must be transmitted to the slave the tx_data parameter should be a NULL pointer and tx_count must be 0 rx_data represents a pointer to the buffer that will hold the data received from the slave during the transaction rx_count specifies the number of bytes to be received from the slave during the transaction If no data must be received from the slave the rx_data parameter should be a NULL pointer and rx_count must be 0 Return values true on success false in case of error 1998 2012 HP InfoTech S R L Page 274 CodeVisionAVR The nature of the error can be established by reading the value of the twi_result global variable which can take the values defined in the following macros define TWI_LRES_OK 0 define TWI_LRES_BUFFER_OVERFLOW 1 define TWILRES_ARBITRATION_LOST 2 define TWI_LRES_BUS_ERROR 3 define TWI_LRES_NACK_RECEIVED 4 define TWI_LRES_BUS_TIMEOUT 5 define TWI_RES_FAIL 6 define TWI_LRES_UNKNOWN 7 Note Operating the TWI in master mode requires the interrupts to be globally enabled This must be done by using the asm sei inline assembly code before attempting any communication through the IC bus TWI master operation example accessing an external AT24C16B EEPROM using the TWI running in master mode TWI functions include lt twi h gt delay functions include lt delay h gt 7 bit TWI bus slave address of the AT24C16B 2kbyte
141. unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned ch char ch char ch char char ch ar ar ar ar char char GLCDINIT t pkn00 3 PKNOO PKNO2 negative gamma micro adj pkn10 3 PKN10 PKN12 negative gamma micro adj pkn20 3 PKN20 PKN22 positive gamma micro adj pkn30 3 PKN30 PKN32 positive gamma micro adj pkn40 3 PKN40 PKN42 negative gamma micro adj pkn50 3 PKN50 PKN52 negative gamma micro adj prn00 3 PRNOO PRNO2 negative gamma gradient adj prnl0 3 PRN1O PRN12 negative gamma gradient adj vrn00 4 VRNOO VRNO3 negative gamma amplification adj vrnl0 5 VRN1O VRN14 negative gamma amplification adj The following macros are defined for initializing the members of the GLCDINIT_t structure Initialization val ues for reverse x define SSD2119 REVX NORM 0 No horizontal reverse define SSD2119 REVX_REV 1 Horizontal reverse Initialization values for reverse y define SSD2119 REVY NORM 0 No vertical reverse define SSD2119 REVY REV 1 Vertical reverse Initialization values for first_out_gate define SSD2119 FIRST OUT GATE1 0 Gate 1 on left sid
142. variables will be declared during code generation The receiver buffer is implemented using the global array rx_buffer_usartpn The global variable rx_wr_index_usartpn is the rx_buffer_usartpn array index used for writing received characters in the buffer The global variable rx_rd_index_usartpn is the rx_buffer_usartpn array index used for reading received characters from the buffer by the getchar_usartpn function The global variable rx_counter_usartpn contains the number of characters received in rx_buffer_usartpn and not yet read by the getchar_usartpn function If the receiver buffers overflows the rx_buffer_overflow_usartpn global bit variable will be set 1998 2012 HP InfoTech S R L Page 470 CodeVisionAVR The transmitter buffer is implemented using the global array tx_buffer_usartpn The global variable tx_wr_index_usartpn is the tx_buffer_usartpn array index used for writing in the buffer the characters to be transmitted The global variable tx_rd_index_usartpn is the tx_buffer_usartpn array index used for reading from the buffer the characters to be transmitted by the putchar_usartpn function If the Infrared Module communication mode is used some specific options are available USARTCO Settings Communication Mode Infrared Module IrDA 1 4 x Data Bits ls X Stop Bits l1 Parity Disabled z Baud Rate 57600 RealBaud Rate 57554 0 Error 0 1 IRCOM Receiver Pulse Length Filtering D
143. yourself the appropriate code sequences to reset it periodically Example asm wdr For more information about the watchdog timer you must consult the Atmel data sheet for the chip that you use 1998 2012 HP InfoTech S R L Page 402 CodeVisionAVR 5 6 Setting the UART or USART The UART or USART configuration can be specified by clicking on the USART a node s of the CodeWizardAVR selection tree a CodeWizardAVR test cwp File Help Analog Comparator ADC SPI p m 1 Wire LCD Bit Banged Project Information Chip ExtemalSRAM Ports ExtemallRQ Times UART v Receiver As Interrupt Receiver Buffer 8 zj v Transmitter 4 Tx Interrupt Transmitter Buffer 8 vA Baud Rate 9600 v Baud Rate Error 0 2 Communication Parameters 8 Data 1 Stop No Parity v 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
144. 0 read the temperature of DS1621 1 10 C ti dsl621 temperature 10 1 prepare the displayed temperatures in the display buffer sprintf display buffer t0 1 t0 10 abs t0 10 Oxdf t1 10 abs C nt1 i u cC 0 O0xd m Po oe FO display the temperatures lced_clear lcd _ puts display buffer 1998 2012 HP InfoTech S R L Page 360 CodeVisionAVR The same example but the DS1621 chips are accessed using the Software Bit Banged I2C Bus Functions include the DS1621 functions The I2C bus connections and bit rate must be specified in the Project Configure C Compiler Libraries I2C menu include lt ds1621 h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd 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 initialize the I c bus i2c_init initialize the DS1621 sensor with address 0 tlow 20 C thigh 25 C dsl621 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
145. 00 year lcd _ puts display buffer delay ms 500 0 5 second delay Example program for a DS1302 connected to an ATxmega128A1 chip on PORTA pins 0 1 and 2 The PORTA is mapped to the virtual port VPORTO the DS1302 is connected to ATxmega 128A1 VPORTO the IO signal is bit 0 the SCLK signal is bit 1 the RST signal is bit 2 asm equ _ ds1302_port 0x11 Address of the VPORTO OUT register equ _ds1302 io 0 equ _ ds1302_sclk 1 equ _ ds1302_rst 2 endasm include the DS1302 include lt ds1302 h gt include the ATxmegal28Al1 I O register definitions include lt io h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt 1998 2012 HP InfoTech S R L Page 350 CodeVisionAVR include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line void main void unsigned char hour min sec day month year PORTA is mapped to VPORTO PORTB is mapped to VPORT1 PORTCFG VPCTRLA PORTCFG VPIMAP PORTB gc PORTCFG VPOMAP PORTA gc initialize the LCD 2 rows by 16 columns lcd_init 16 initialize the DS1302 RTC use trickle charge with 1 diode and 8K resistor rte init 1 1 3 7 rtc_set_time 1
146. 000 0b00000101 0b10000000 0b00000011 0b11111111 0b11111111 e 1998 2012 HP InfoTech S R L Page 264 CodeVisionAVR void main unsigned char c GLCDINIT t init No font is used init font NULL No need for reading data from external memory init readxmem NULL No need for reading data from external memory init writexmem NULL Initialize the LCD controller and graphics glcd init amp init Display text using the built in character generator lcd putsf Sitronix ST7920 nCodeVisionAVR nDemo 2 seconds delay delay ms 2000 lcd_clear Define 4 characters with codes 0 2 4 6 for c 0 c lt 3 c glcd_definechar c 2 user def char c lcd putsf User defined n characters n User defined characters must be located on even x coordinates Display user defined characters with codes 0 2 4 6 for c 0 c lt 6 ct 2 lcd_putchar 0 Always first write MSB 0 lcd putchar ec Write LSB character code 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 void Icd_putse char eeprom str Displays at the current display position the string str located in EEPROM Notes e The gled_st7920 h header file is automatically
147. 0000001 0b00000000 0600000010 Ob00000000 0600000100 Ob00000000 0600001000 Ob00000000 0600010000 Ob00000000 0600100000 Ob00000000 0601000000 Ob00000000 0610000000 0b00000000 y 1998 2012 HP InfoTech S R L Page 263 CodeVisionAVR Character with code 2 0600000000 Ob00000001 0600000000 Ob00000010 0600000000 0b00000100 0600000000 0b00001000 0600000000 0b00010000 0600000000 0b00100000 0600000000 0b01000000 0600000000 0b10000000 0610000001 0Ob00000000 0610000010 Ob00000000 0610000100 Ob00000000 0610001000 Ob00000000 0610010000 Ob00000000 0610100000 Ob00000000 0611000000 Ob00000000 0611111111 0Ob00000000 hy Character with code 4 0b11111111 0b11111111 0610000000 0Ob00000011 0610000000 0b00000101 0610000000 0b00001001 0610000000 0b00010001 0610000000 0b00100001 0610000000 0b01000001 0610000000 0b10000001 0610000001 0b00000001 0610000010 Ob00000001 0610000100 Ob00000001 0610001000 Ob00000001 0610010000 Ob00000001 0610100000 Ob00000001 0611000000 Ob00000001 0b11111111 0b11111111 Fy Character with code 6 0b11111111 0b11111111 0b11000000 0b00000001 0b10100000 0b00000001 0b10010000 0b00000001 0b10001000 0b00000001 0b10000100 0b00000001 0b10000010 0b00000001 0b10000001 0b00000001 0b10000000 0b10000001 0b10000000 0b01000001 0b10000000 0b00100001 0b10000000 0b00010001 0b10000000 0b00001001 0b10000
148. 01C Solomon Systech SSD1289 for color 240x320 TFT displays Solomon Systech SSD1963 for color 320x240 480x272 and 800x480 TFT displays Solomon Systech SSD2119 for color 320x240 TFT displays Sitronix ST7565 Sitronix ST7920 Toshiba T6963C UltraChip UC1701 Delcomp XG7100 Note The library functions for color TFT displays are supported only for the Advanced or Professional CodeVisionAVR licenses The Graphic LCD functions do support both the XMEGA and non XMEGA AVR chips The coordinate system employed by these functions has the origin 0 0 in the upper left corner of the display with the x coordinates increasing from left to right and the y coordinates increasing from top to bottom Coordinate clipping is performed therefore no graphic data will be displayed for invalid coordinates The following helper data types are defined in the header file glcd_types h GLCDX_t type used for specifying the X horizontal display coordinate GLCDY_t type used for specifying the Y vertical display coordinate GLCDDX_t type used for specifying a horizontal displacement GLCDDY_t type used for specifying a vertical displacement GLCDRAD _t type used for specifying a circle radius GLCDCOL_t type used for specifying foreground and background display colors GLCDMEMADDR t type used for specifying RAM EEPROM FLASH or external memory addresses for bitmap image storage 1998 2012 HP InfoTech S R L Page 190 CodeVisionAVR e GLCDBLOCKM
149. 0kHz Prescalers B C B 1 C1 v ClkPer2 8000 000kHz CikPer 8000 000kHz CIkCPU 8000 000kHz External Clock Source Failure Monitor Lock Clock Configuration ClkPer Output Disabled Z The External Clock option specifies the value of the external clock frequency in kHz The External Clock Source Start up Time list box allows to select the type of external clock source external clock signal crystal or ceramic resonator and its start up time If the External Clock Source Failure Monitor option is enabled the device will perform the following actions if the external clock stops e switch to the 2MHz internal oscillator independently of any clock system lock setting by reseting the System Clock Selection Register to its default value e reset the Oscillator Control Register Register to its default value e Set the External Clock Source Failure Detection Interrupt Flag in the XOSC Failure Detection Register e Issue a Non Maskable Interrupt NMI 1998 2012 HP InfoTech S R L Page 446 CodeVisionAVR If a Phase Locked Loop PLL is used as System Clock Source the following specific configuration options are available System Clocks Settings System Clock Source Phase Locked Loop Me v Calibrate the 2MHz internal oscillator Calibration Reference 32 768kH2 Ext Crystal Osc 32 768kH2 Oscillator Low Power Mode Phase Locked Loop Clock Source 2MHz Internal Osc z Multiplication Facto
150. 0x240 CS Active low z Connections LCD Module AYR DBO PORTA DBI PORTA DB2 PORTA DB3 PORTA DB4 PORTA DB5 PORTA DBE PORTA PORTA PORTB PORTB PORTB PORTB PORTB ceca Gate The Display Type list box allows to select the graphic controller type and LCD resolution The connections between the graphic LCD module and the AVR I O ports can be specified individually for each signal in the Connections group box Note In order to obtain maximum performance it is advised to set the LCD controller s data bus bits to match the bits with the same numbers of the same AVR I O port 1998 2012 HP InfoTech S R L Page 64 CodeVisionAVR 2 3 5 9 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 Hee The following parameters can be specified for the program to be executed e Program Directory and File Name e Program Command Line Param
151. 12 HP InfoTech S R L Page 51 CodeVisionAVR For the XMEGA chips that feature an External Bus Interface EBI an additional EBI Configuration tab is present i KN Configure Project sdcard4 prj Files C Compiler Before Build After Build Libraries Messages Memory Type and Connection EBI Disabled SRAM 3P ALE1 mux A 0 415 8 D SRAM 3P ALE1 ALE2 mux Globally define Paths LPC 2 P ALE1 mux 47 0 D7 0 LPC 2 P 4LE1 ALE2 mux LPC 3P ALE1 mux A7 0 D7 0 SDRAM 3P Code Generation EBI Configuration Advanced X conce 2 Hep The check boxes from the Memory Type and Connection group allow to specify the EBI operating mode and kind of external RAM connected to the chip 1998 2012 HP InfoTech S R L Page 52 CodeVisionAVR Depending on the EBI operating mode additional tabs are displayed for the configuration of the CS0 CS3 chip select signals e N Configure Project sdcard4 prj Files C Compiler Before Build After Build Libraries Messages Globally define Paths Code Generation EBI Configuration Advanced al Memory Type and Connection EBI Disabled LPC 2 P 4LE1 mux 47 0 D 0 SRAM 3P ALE1 mux 47 0 415 8 LPC 2 P ALE1 ALE2 mux SRAM 3P ALE ALE2 mus LPC 3P ALE1 mux 47 0 D7 0 SDRAM 3P cso csi cs2_ cs3 7 Enabled Base Address 0 h Address Sp
152. 1_OVF_FREQ 100Hz timer interrupt generated by ATmegal28 Timerl overflow interrupt TIM1_ OVF void timer _comp_isr void ve initialize Timerl TCNTIH T1 INIT gt gt 8 TCNTIL T1_ INITS amp OxFF card access low level timing function disk timerproc the rest of the interrupt service routine sens E void main void initialize Timerl overflow interrupts in Mode 0 Normal TCCRIA 0x00 clkio 1024 TCCRIB 1 lt lt CS12 1 lt lt CS10 timer overflow interrupts will occur with 100Hz frequency TCNTIH T1_ INIT gt gt 8 TCNTIL T1_ INITS amp OxFF enable Timerl overflow interrupt TIMSK 1 lt lt TOIE1 globally enable interrupts asm sei the rest of the program E ea T7 while 1 PR gets RY 1998 2012 HP InfoTech S R L Page 301 CodeVisionAVR unsigned char disk_initialize unsigned char drv performs the initialization including the SPI bus interface and I O ports of a physical drive located on a MMC SD or SD HC card Parameters drv represents the drive number Drive numbering starts with 0 Return value The function returns 1 byte containing the disk status flags specified by the following macros defined in sdeard h e STA_NOINIT 0x01 bit 0 of function result Disk drive not initialized This flag is set after microcontroller reset card removal or when
153. 2 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 copies at most n characters from the string src to the string dest Returns a pointer to the string dest If there is no null character among the first n characters of src then dest will not be null terminated If n is less then the length of src then the remainder of dest will be padded with nulls char strncpyf char dest char flash src unsigned char n copies at most n characters from the string src located in FLASH to the string dest located in SRAM Returns a pointer to the string dest If there is no null character among the first n characters of src then dest will not be null terminated If n is less then the length of src then the remainder of dest will be padded with nulls unsigned char stricpy char dest char src unsigned char n copies at most n 1 characters from the string src to the string dest ensuring that it will be always null terminated even if the src string was truncated to fit If n is less then the length of src then the remainder of dest after the null terminator will not be padded with nulls The function returns t
154. 2 0 0 set time 12 00 00 rtc_set_date 1 2 2011 set date 1 02 2011 display the time and date continuously while 1 read the time from the RTC rtc_get_time amp hour min amp Sec read the date from the RTC rtc_get_ date amp day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec lcd_clear lcd _ puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month 2000 year lcd puts display_buffer delay ms 500 0 5 second delay 1998 2012 HP InfoTech S R L Page 351 CodeVisionAVR 4 22 4 Maxim Dallas Semiconductor DS1307 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the DS1307 IC bus real time clock RTC using both the hardware TWI and software bit banged C bus functions One of the following header files located in the INC subdirectory must be include d before using these functions e ds1307_twi h for hardware TWI e ds1307 h for software bit banged C bus The appropriate header files for hardware TWI twi h or twix h or software bit banged C bus i2c h functions prototypes are automatically include d with the ds1307_twi h or ds1307 h The Project Configure C Compiler Libraries I2C menu must be used for specifying the I O port allocation of the SCL and SDA signa
155. 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 2012 HP InfoTech S R L Page 109 CodeVisionAVR Local variables that must conserve their values during different calls to a function must be declared as static Example int alfa void declare and initialize the static variable static int n 1 return nt t void main void int 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
156. 20 DS18S20 temperature sensor devices 1 Wire Bus Interface Settings Enable 1 Wire Bus Interface Support Data Connection 0 Port PORTA Bit 6 DS1820 D518S20 v Enabled v Multiple Devices If several DS1820 DS18S20 devices are connected to the 1 Wire bus the Multiple Devices option must be checked A maximum of 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 2012 HP InfoTech S R L Page 476 CodeVisionAVR 6 14 Setting the Two Wire Interfaces The XMEGA Two Wire Interfaces TWI can be configured by clicking on the Two Wire Interfaces Tull nodes of the CodeWizardAVR selection tree The following General Settings are available TWIC Settings General Settings Enable SDA Hold Time Enable the External Driver Interface e Enable SDA Hold Time allows to add an internal hold time to the SDA signal with respect to the negative edge of SCL e Enable the External Driver Interface activates the usage of external TWI compliant tri state drivers for the SDA and SCL signals In this situation the internal TWI drivers with input filtering and slew rate control are bypassed The normal I O port pin function is used and the direction must be configured by the user software The following setti
157. 200 UCSROA 0 UCSROB 1 lt lt TXENO UCSROC 1 lt lt UCSZ01 1 lt lt UCSZ00 UBRROH BAUD_INIT gt gt 8 UBRROL BAUD_INIT amp 0xFF init the PCF8563 RTC rtc_init 0 RTC_CLKOUT_OFF RTC_TIMER OFF init the pointer to the RTC function used for reading time prtc_get_time void unsigned char unsigned char unsigned char rtc_get_time init the pointer to the RTC function used for reading date prtc_get_date void unsigned char unsigned char unsigned int rtc_get_ date globally enable interrupts asm sei mount logical drive 0 if res f mount 0 amp fat FR_OK printf Logical drive 0 mounted OK r n else an error occured display it and stop error res printf Ss r n path create a new file in the root of drive 0 and set write access mode if res f open amp file path FA CREATE ALWAYS FA WRITE FR_OK printf File s created OK r n path else an error occured display it and stop error res write some text to the file without the NULL string terminator sizeof data 1 if res f write amp file text sizeof text 1 amp nbytes FR_OK printf Su bytes written of Su r n nbytes sizeof text 1 else an error occured display it and stop error res 1998 2012 HP InfoTech S R L Page 330 CodeVisionAVR close the file if res f clo
158. 2119 VLCD63 5V62 0 VLCD63 5 62V D2119 VLCD63 5V80 1 VLCD63 5 80V D2119 VLCD63 6V00 2 VLCD63 6 00V ization values for the VcomL voltage DVO 4 from Power Control Reg 4 D2119 VCOML_0 60 0 VcomL VLCD63 0 D2119 VCOML 0 63 1 VcomL VLCD63 0 D2119 VCOML_0 66 2 VcomL VLCD63 0 D2119 VCOML_0 69 3 VcomL VLCD63 0 D2119 VCOML_0 72 4 VcomL VLCD63 0 D2119 VCOML_ 0 75 5 VcomL VLCD63 0 D2119 VCOML 0 78 6 VcomL VLCD63 0 D2119 VCOML_ 0 81 7 VcomL VLCD63 0 D2119 VCOML_0 84 8 VcomL VLCD63 0 D2119 VCOML 0 87 9 VcomL VLCD63 0 D2119 VCOML_0 90 10 VcomL VLCD63 D2119 VCOML 0 93 11 VcomL VLCD63 D2119 VCOML_0 96 12 VcomL VLCD63 D2119 VCOML_0 99 13 VcomL VLCD63 D2119 VCOML 1 02 14 VcomL VLCD63 D2119 VCOML EXT RES 15 Vcom D2119 VCOML 1 05 16 VcomL VLCD63 D2119 VCOML_1 08 17 VcomL VLCD63 D2119 VCOML 1 11 18 VcomL VLCD63 D2119 VCOML 1 14 19 VcomL VLCD63 D2119 VCOML 1 17 20 VcomL VLCD63 D2119 VCOML 1 20 21 VcomL VLCD63 D2119 VCOML 1 23 22 VcomL VLCD63 xy xJ a 7 f f ef ZA L is set by an external variable resistor 7 EJ i a 1998 2012 HP InfoTech S R L Page 252 CodeVisionAVR Initialization values for SS SS SS SS SS SS SS define define define define define define define D2119 F D2119 F D2119 F D2119 F D2119 F D2119 F D2119 F Default define
159. 25Fh Hardware Stack size 384 byte s Heap size 0 byte s EEPROM usage 0 bytefs 0 0 of EEPROM 1998 2012 HP InfoTech S R L Page 71 CodeVisionAVR 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 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 cvavr examples Copy The Project Go to Next Error respectively Project Go to Previous Error menu commands the F8 respectively Ctrl F8 keys or the B 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 J
160. 29 2 2 4 3 Jumping to a Symbol Definition or Declaration ececeeee ener eeeeenteeeeeeneeeeeeeaas 29 2 2 4 4 Jumping to a Specific Line Number in the Edited File cecsecceeeeeeeeeeeeeseees 30 2 2 4 5 Printing a Text Selecon 220 4 ee i ee ee ee ees 30 2 2 4 6 Indenting Unindenting a Text Selection eccceeeeeteeeeeeeneeeeeeeneeeeeeeceeeeeenaeeeeseaas 30 2 2 4 7 Commenting Uncommenting a Text Selection 2 eccceeeeeeeeeeeeeeeeeeeeneeeeeeeneeeeeeaas 30 2 2 4 8 Match Braces sic cvesdoscevetecaceevetiacaavhd daceevetledaavet adcevettitiavhl doasbeticiavet alae nile 30 2 2 4 9 Inserting Special Characters in the Text eeeeececeeeeeneeeeeseneeeeeeeeeeeeesnaeeeeeenaeeeeeeaas 31 2 2 4 10 Using the Auto Complete Functions 0 cccceeeccceeeeeeeeeee entree eeeeeieeeeeeneeeeeenaeeeeeeaas 32 2 2 4 11 Using Code Folding 0 ceccceececeeeeeetnee ee enne reese ene ee ee sees eeeaeeeeeeeeeeescaeeeenenaeeeeeeaas 32 22 0 SAVING a Flosi tes ae ee ed a ee ae 33 2 2 6 Renaming a File eee eee etter eee e eee ene ee erent ee erent ee ee eaae ee ee eeaeeeeeeaaeeeeeeaeeeeeeaeeeeeenaes 33 226 PUM se MN eects T A pu lave ae daa dak peagwasedavauseeesenadsoe pagers saci S 34 2 2 0 CIOSING a Fio rrena r vhidcievehitl caviticceaved ad E ave tutcaavd adtaeehaia whl avetaeeas 34 2 2 9 Closing Multiple FIGS 5 352 arccces arnar ENA NERT A ETEA ATEA 35 1998 2012 HP InfoTech S R L Page 2 CodeVisionAVR 2 2 10 Using the C
161. 3 5 7 Setting the Alphanumeric LCD Library Options ccceeeeeeeeeeneeeeeeeaeeeeeeteeeeeeaas 63 2 3 5 8 Setting the Graphic LCD Library Options 0 ccc eeeeeeeeeeneeeeeeeeeeeeeaeeeeeentaeeeeneaas 64 2 3 5 9 Executing an User Specified Program before Build 0 ccceeeteeeeeesteeeeeenteeeeeeeaes 65 2 3 5 10 Transferring the Compiled Program to the AVR Chip after Build eee 66 2 3 5 11 Executing an User Specified Program after Build 0 0 0 0 ecceeeeeeeeeeeeneeeeeenteeeeeeeaes 68 2 3 6 Obtaining an Executable Program ccccccceeeeeseteeeeeeeneeeeeenneeeeetnaeeeeeeeaeeeseenaeeeeeeneeeeeeaas 70 2 3 6 1 CHECKING SYNtAX eee ec eect eee enee ee eee e rannan ener EANAN ee ANANE AE ANENE ANNE KAANANE EENAA ERARE EEEa 70 2 3 6 2 Compiling the Projet 0 cc00 ade ie eed ened ie ee ae eee 71 2 3 6 3 Building the Projet esuriens AEE AN AEA 73 2 3 6 4 Cleaning Up the Project Output DirectorieS sssseeesrsesssrresesrnennssnnnneennaanannaatennaannanna 77 2 3 6 5 Using the Code Navigator nsnsi aaa E AAA 78 2 3 6 6 Using the Code Information 0 cecccccceceee etter ee etneee ee eaeeeeeeeeeeeeeeeeeeneeeeeenaeeeeneaas 79 2 3 6 7 Using the Function Call Tree w ccciisiccieieicecl ieacdd blanche ncaateeeeeddeecnddaseeaatveeeesiieeees 80 2 3 7 Closing a ud 0 0 Sere 81 1998 2012 HP InfoTech S R L Page 3 CodeVisionAVR 244 The AVR Debugger wiiiciscetee niet hie Wines laced A ee ee des 82 2 4 2 The AVR
162. 329 3290 649 6490 chips can be specified by clicking on the corresponding P node of the CodeWizardAVR selection tree a CodeWizardAVR test cwp File Help USI USART Analog Comparator ADC sp i2c 1 Wire LCD Bit Banged Project Information Chip Ports External IRQ Timers V LCD Enabled LCD Low Power Waveform LCD Frame Complete Interrupt Duty Cycle Static kd Bias Static z Clock Source System v Frame Rate 50 Hz Frame Rate Error 2 3 Used Segments SEG0 12 x Contrast Control 2 BOY 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 Ilcd_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 Fram
163. 451 CodeVisionAVR When SDRAM is used as external memory and a different clock source is used instead of the internal 2M oscillator it is necessary to execute the function that configures the system clocks before the EBI setup sequence which will ensure that correct timing is used for later SDRAM access by the startup code This can be achieved by using the __reset attribute applied to the clock initialization function _ reset void system clocks init void Initialization code The code generated by the CodeWizardAVR for XMEGA chips automatically handles such situations 1998 2012 HP InfoTech S R L Page 452 CodeVisionAVR 6 4 Setting the Event System The XMEGA Event System can be configured by clicking on the Event System ny node of the CodeWizardAVR selection tree The following options are available Event System Settings Event Channel 0 Event Channel 1 Event Channel 2 Event Chanr Source None v Digital Filter Coefficient 1 Sampe The Event Channel Source list box allow to select the events that will trigger the corresponding channel The Digital Filter Coefficient option allows to specify the length of digital filtering used Events will be passed through to the event channel only when the event source has been active and sampled with the same level for the specified number of peripheral clock cycles The Event Channel 0 Output list box allows to specify if the
164. 6 initialize the TWI in master mode with 100 kHz bit rate twi master init 100 enable interrupts so that TWI can be used asm sei initialize the DS1621 sensor with address 0 tlow 20 C thigh 25 C ds1621 init 0 20 25 0 1998 2012 HP InfoTech S R L Page 358 CodeVisionAVR 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 dsl621 temperature 10 1 prepare the displayed temperatures in the display buffer sprintf display buffer t0 i u ScC nt1l i u scC t0 10 abs t0 10 Oxdf t1 10 abs t1 10 Oxdf ole display the temperatures led_clear lcd _ puts display buffer The same example but the DS1621 chips are accessed using the TWI Functions for Master Mode Operation for XMEGA Devices The chips are connected to the TWI of PORTD TWID of an ATxmega128A1 include the DS1621 functions for TWI include lt ds1621_twi h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototype for abs i
165. 9 CodeVisionAVR 4 15 Two Wire Interface Functions for XMEGA Devices The TWI Functions for XMEGA Devices are intended for easy interfacing between C programs and various external peripherals using the C bus and SMBus These functions can operate the XMEGA AVR microcontroller as both bus master and slave The function prototypes along with helper structure and macro definitions are placed in the header file twix h located in the INC subdirectory This file must be include d before using the TWI functions Notes e The twix h header file automatically includes the io h header file that contains the I O modules definitions for the XMEGA device selected in the project configuration e The TWI Functions for XMEGA Devices operate using interrupts so the interrupt priority level s used by them must be activated Interrupts must be also globally enabled using the asm sei inline assembly code e For proper operation the TWI Functions require the presence of 3 3k 4 7k pull up resistors to 3 3V on the SCL and SDA signals General initialization of the TWI module associated with an XMEGA I O port is performed by the void twi_init TWI_t module bool ext_driver_intf unsigned char sda_hold function Parameters module represents a pointer to the TWI module associated with the I O port ext_driver enables the external driver interface In this situation the internal TWI drivers with input filtering and slew rate control are
166. 9 63 4V67 63 4v80 63 5Vv00 63 5v14 63 5V29 63 5V45 define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS define SS D1289_VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOM D1289 VCOML o uu cAn FWNHEHR O WO 1 1 1 1 1 1 ization values for L 0 60 L 0 63 L 0 66 L 69 L 0 72 L0 75 L 0 78 LO 81 L 0 84 L 0 87 L 0 90 L0 93 L 0 96 L 0 99 L 1 02 0 G Ui w e e CO PrRPRPRPR o BwWNE OO EXT_RE n L_1_05 L 1 08 L1 11 L1 14 LL t7 L 1 20 L1 23 Initial define SS define SS define SS define SS define SS define SS define SS D1289 FRAM D1289 F D1289 F D1289 F D1289 F D1289 F D1289 F M M BERR EBS E E E60 5 E65 8 16 17 18 19 20 21 22 ization values for E50 0 E55 2 E70 Ox0A E75 0x0 ME80 Ox0E C VI VLCD63 3 VLCD63 3 VLCD63 3 VLCD63 3 VLCD63 3 VLCD63 3 VLCD63 4 VLCD63 4 VLCD63 4 VLCD63 4 0O VLCD63 4 1 VLCD63 4 2 VLCD63 5 3
167. ADC Input Connected to GND for Offset Compensation ADC pin ADC Compare Register 0 h Channel 0 Channel 1 Channel 2 Channel 3 Input Mode Internal positive input signal v Positive Input Temp Reference x Negative Input GND Interrupt Low Level v Interrupt Mode Conversion Complete z ADC Enabled allows the activation of the selected ADC ADC Clock Frequency specifies the frequency of the clock signal used by the ADC ADC Resolution allows to select 8 Bit or 12 Bit analog to digital conversion resolution ADC Conversion Mode allows to select Signed or Unsigned analog to digital conversion ADC Reference allows to specify the voltage reference used by the ADC Temperature Measurement Reference Enabled activates the on chip temperature sensor Conversion Start Mode allows to select how an analog to digital conversion is started for each ADC channel Triggered by Software Free Running Triggered by the Event System and Triggered by the Event System Synchronized 1998 2012 HP InfoTech S R L Page 479 CodeVisionAVR e ADC Input Connected to GND for Offset Compensation allows to specify which ADC input is connected to GND in Unsigned conversion mode so that the ADC offset voltage can be measured at start up and substracted from subsequent conversion results For Signed conversion mode there is no need to connect one of the ADC inputs to GND because the offset is read using
168. AT function result FRESULT res will hold the information for logical drive 0 FATFS drive root directory path char path 256 0 1998 2012 HP InfoTech S R L Page 320 CodeVisionAVR initialize Timerl overflow interrupts in Mode 0 Normal TCCR1IA 0x00 clkio 1024 TCCRIB 1 lt lt CS12 1 lt lt CS10 timer overflow interrupts will occur with 100Hz frequency TCNTIH T1 INIT gt gt 8 TCNTIL T1_ INITS amp OxFF enable Timerl overflow interrupt TIMSK 1 lt lt TOIE1 initialize the USARTO TX 8N1 Baud rate 19200 UCSROA 0 UCSROB 1 lt lt TXENO UCSROC 1 lt lt UCSZ01 1 lt lt UCSZ0OO UBRROH BAUD_INIT gt gt 8 UBRROL BAUD_INIT amp OXxFF globally enable interrupts asm sei printf Directory listing for root of logical drive 0 r n mount logical drive 0 if res f mount 0 amp drive FR_OK printf Logical drive 0 mounted OK r n else an error occured display it and stop error res rvrepeateadly read directory entries and display them if res directory scan path FR_OK if an error occured display it and stop error res stop here while 1 Note When compiling the above example make sure that the s printf Features option in the Project Configure C Compiler Code Generation menu will be set to long width This will ensure that the unsigned long
169. ATA PA6 AND 5V 7 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 2012 HP InfoTech S R L Page 370 CodeVisionAVR char text J 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
170. BUS san tn eshceiaacc she cookin cln be esa hoc dba ia Danaea 416 5 13 1 Setting the LM75 G6VICES orcccccenicccareriiiiii iiin E E 417 5 13 2 Setting the DS1621 devices uaassseeesseessrresrerreerirrnsttenneatsnnnatinnaantnnadtannaadannaatannaannnnaaaa 418 5 13 3 Setting the PCF8563 deVICES cerrccccrnirorniiioni E EEE R 419 5 13 4 Setting the PCF8583 devices ssseesrseessrrnsrrrresrsrrsatinnetsssnnaatinnedrinnaatanneadanaaatannnaanannaa 420 9 13 9 Setting the DS130 deviC s sii ish cceveieccetsnececgetedeecedbnpencdessnecedgevsieeaevtiehsesteeedersneceeeenenenns 421 9 14 Setting the 1 Wire BUS wiestiesicnitenesindei tiered siesta elaine tibiae 423 5 15 Setting the Two Wire Bus Interface eccccccceeeee eens ee eene ee ee eeneee eee teeeeeteeeeeneeeeeeeeeereaa 425 5 16 Setting the Two Wire Bus Slave Interface for the ATtiny20 40 ChIDS eceeeeeeeeeeeeeeereee 427 5 17 Setting the CAN Controller ec ecee eee retire erties rene ee erties erties ee nieeeeetiieeeeeesneeenead 429 5 18 Setting the ATmega169 329 3290 649 6490 LCD Controller c cccccceeeceeeeeeeetteeeeeeees 431 5 19 Setting the Alphanumeric LCD 00 00 ccc eee ttre etree erties erties eee tieee ee teeeeetiieeeereiieeeene 432 9 20 Setting the Graphie LCD 4cccuvi ni cenit deni adie tine ieeniteanitei ecient 433 5 21 Setting the USB Controlar vice svvscacisvetexeatidecazecvdvcanay eh custan E AERA 434 5 22 Setting Bit Banged Peripherals c ccc
171. Buffer on AINO Disable Digital Input Buffer on AIN1 Checking the Analog Comparator Enabled check box enables the on chip analog comparator Checking the Bandgap Voltage Reference check box will connect an internal voltage reference to the analog comparator s positive input Checking the 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 2012 HP InfoTech S R L Page 406 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
172. C SD SD HC FLASH memory cards formated using the FAT12 FAT16 or FAT32 standards The FAT access functions are based on FATFS open source library by Mr ChaN from Electronic Lives Mfg http elm chan org The FAT access function prototypes helper type definitions and macros are placed in the header file ff h located in the INC subdirectory This file must be include d before using the functions The FAT access functions call the low level MMC SD SD HC Card Driver functions so the I O port signals employed for communication with the MMC SD SD HC card must be configured in the Project Configure C Compiler Libraries MMC SD SD HC Card menu Notes e The FAT access functions are not re entrant They must not be called from interrupt service routines e Currently the FAT access functions support only the DOS short 8 3 file name format Long file names are not supported e The file directory names are encoded using 8bit ASCII unicode characters are not supported e Before beeing accessed using the FAT functions the MMC SD SD HC card must be partitioned and formated to FAT12 FAT16 or FAT32 system on a PC The following helper data types are defined in ff h e The FRESULT type is used for returning the result of the FAT access functions typedef enum FR_OK 0 0 Succeeded FR_DISK_ERR 1 A hard error occured in the low level
173. CMD DISP_ NORMAL 0xA6 set normal display mode define UC1701 CMD DISP REVERSE O0xA7 set reversed display mode define UC1701 CMD PIXELS NORMAL 0xA4 display the graphic RAM contents define UC1701 CMD ALL PIXELS ON 0xA5 all display pixels are on define UC1701 CMD STATIC INDICATOR_OFF OxAC turn off static indicator define UC1701 CMD STATIC _INDICATOR_ON O0xAD turn on static indicator define UC1701 CMD DISP OFF OxAE turn display off define UC1701 CMD DISP ON OxAF turn display on define UC1701 CMD LCD BIAS LOW 0xA2 sets voltage ratio for LCD bias to 1 9 duty cycle 1 65 1 8 duty cycle 1 49 1 6 duty cycle 1 33 1 8 duty cycle 1 55 1 8 duty cycle 1 53 define UC1701 CMD LCD BIAS HIGH 0xA3 sets voltage ratio for LCD bias to 1 7 duty cycle 1 65 1 6 duty cycle 1 49 1 5 duty cycle 1 33 1 6 duty cycle 1 55 1 6 duty cycle 1 53 define UC1701 CMD COMO 63 O0xCO sets the COM output scan direction 0 gt 63 MY 0 define UC1701 CMD COM63 0 OxC8 sets the COM output scan direction 63 gt 0 MY 1 define UC1701 CMD POWER CTRL 0x28 turns on off the voltage follower bit 0 voltage regulator bit 1 voltage booster bit 2 define UC1701 VOLT FOLLOWER_ON 1 lt lt 0 enable voltage follower define UC1701 VOLT REGULATOR _ON 1 lt lt 1 enable voltage regula
174. CodeVisionAVR VERSION 2 60 HP InfoTech User Manual CodeVisionAVR CodeVisionAVR V2 60 User Manual Revision 36 6 2012 Copyright 1998 2012 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 2012 HP InfoTech S R L Page 1 CodeVisionAVR Table of Contents Table of Contents asec aaa EA EnaA aA ANERE Eaa AAAA ARKAA eaS 2 1 Introduction snnncneran aa ves 11 ED r e EA E E E E E IE I ere or I E E I 12 2 The CodeVisionAVR Integrated Development Environment ssssssssssnnssnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nn 13 2 1 Using the Integrated Development Environment Workspace ccceceeeeeeeeeeeeeetteeeeeetnneeeeeene 13 2 2 Working with PIlGS ciicgiecnecieesiacaekiintetdes nadie ea EE 26 2 21 Creatingra NEW Filise daeevvetieciavvt a vet hl aeeventinianunts 26 2 2 2 Opening an Existing File sis ccteiecictenieceiteiethngetedecdics ep AEEA KPA AA AE TAAT EEE eens 27 2 2 9 Files FISO sscicsieecisthwtncebdeneaneiethwliebineeihidetaiet ead thn eisai 27 2 2 4 Editing FIC seca asec dt cccceeesendeczvesscnied gandedanseaadaet ga dew scandent a aaa iai 28 2 2 4 1 Sarching Replacing Textil nceticuiiiseieet eared NANAREN AA NAANA NAA RARESA 29 2 2 4 2 Setting BookmarkS ssseesseeerseeerresirresttrnntttt ee erent eee eae eee ee eaaeeeeeeaaeeesesaeeeeeenaeeeeeeaas
175. D S S E Includes me amp E A Macros Ka G Typedefs kd E p Global Static Vari sae F Functions T 0 mainfvoid Ef fii pf Function Call Tree ES FO main g DSTACK Func 0 Gt printf amp amp DSTACK Func 5 B f _print E DSTACKF B f strlen amp DSTA H Messages B Eros B wamings An undocked toolbar can be hidden by clicking on its amp icon Alternatively the toolbars visible state can be changed by using the View Toolbars menu 1998 2012 HP InfoTech S R L Page 22 CodeVisionAVR 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 SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usart prj File Edit Search View Project Tools Settings Help beec HeaCSolmMARs HAHA i Add or Remove Buttons 7 Bee f RE Code Information Includes 0 Macros to test Joie apo E Typedefs E gt Global Static Variabl H Save yelopme B F Functions v E Save As fO main void ez B adder Gil Save All Close Close Multiple the VTi Close All s the ff Convert to Library af Function Call Tree mMm Page Setup apen EfG main Print Preview E DSTACK Func 0 T i 500 RS B f printf Print hfigure E DSTACK Func TOT Miel Tto 3600bps 8N1 B f _print Ila amp DSTACK Func 2 20 BF strlen 21 include lt stdio h gt Fa NSTACK Fun
176. D8544 DISPLAY INVERSE 0x0D Sets inverse video mode define PCD8544 SETX 0X80 Sets X address of display RAM define PCD8544 SETY 0X40 Sets Y address of display RAM Extended instruction set enabled by PCD8544_ FUNCTION SET PCD8544 EXT INST define PCD8544 TEMP CTRL 0x04 Sets temperature coefficient define PCD8544 BIAS SYSTEM 0x10 Sets bias system define PCD8544 VLCD 0x80 Sets VLCD value A detailed description of the above mentioned commands can be found in the PCD8544 datasheet void pcd8544_setvicd unsigned char vicd Controls the LCD contrast Parameter vicd value for the VLCD voltage allowed range is 0 127 1998 2012 HP InfoTech S R L Page 222 CodeVisionAVR The glcd_pcd8544 h header file also contains the definition of the GLCDINIT_t type specific for the PCD8544 controller used as parameter for the gled_init function typedef struct flash unsigned char font default font after initialization pointer to the function used for reading a byte from external memory unsigned char readxmem GLCDMEMADDR t addr pointer to the function used for writing a byte to external memory void writexmem GLCDMEMADDR t addr unsigned char data unsigned char temp _coef 2 temperature coefficient bits 0 3 unsigned char bias 3 bias system bits 0 7 unsigned char vlcd 7
177. DC1 Fosc 8 define IL19325 STEPUP1 FOSC16 4 FDCDC1 Fosc 16 define ILI9325 STEPUP1 FOSC32 5 FDCDC1 Fosc 32 define ILI9325 STEPUP1 FOSC64 6 FDCDC1 Fosc 64 define ILI9325 STEPUP1 HALT 7 Halt step up circuit 1 Initialization values for stepup freq2 define IL19325 STEPUP2_FOSC4 0 FDCDC2 Fosc 4 define IL19325 STEPUP2 FOSC8 1 FDCDC2 Fosc 8 define IL19325 STEPUP2 FOSC16 2 FDCDC2 Fosc 16 define IL19325 STEPUP2 FOSC32 3 FDCDC2 Fosc 32 define IL19325 STEPUP2_ FOSC64 4 FDCDC2 Fosc 64 define IL19325 STEPUP2 FOSC128 5 FDCDC2 Fosc 128 define ILI9325 STEPUP2 FOSC256 6 FDCDC2 Fosc 256 define ILI9325 STEPUP2 HALT 7 Halt step up circuit 2 1998 2012 HP InfoTech S R L Page 218 CodeVisionAVR Initialization values for frame freq 19325 REVX_NORM No horizontal reverse 119325 REVY NORM No vertical reverse define ILI9325 FRAME40 0 40Hz define ILI9325 FRAME43 1 43Hz define ILI9325 FRAME45 2 45Hz define ILI9325 FRAME48 3 48Hz define ILI9325 FRAME51 4 51Hz define ILI9325 FRAME55 5 55Hz define ILI9325 FRAME59 6 59Hz define ILI9325 FRAME64 7 64Hz define ILI9325 FRAME70 8 70Hz define ILI9325 FRAME77 9 77Hz define ILI9325 FRAME85 10 85Hz define ILI9325 FRAME96 11 96Hz define ILI9325 FRAME110 12 110Hz define
178. DCOL_t ssd1963_rddram void Reads color data for 1 pixel from the SSD1963 controller s display RAM Note Before calling this function a SSD1963_CMD_RD_MEM_START or SD1963_CMD_RD_MEM_CONT command must be issued to the controller using the ssd1963_wrcmd function void ssd1963_sleep bool on Puts the SSD1963 controller in sleep mode or exit from sleep mode Parameter on when true puts the controller in sleep mode when false exits the sleep mode Notes e The function automatically inserts a Sms delay after entering or exiting the sleep mode e A delay of minimum 120ms must be present after exiting the sleep mode and entering sleep mode again The glcd_ssd1963 h header file also contains the definition of the GLCDINIT_t type specific for the SSD1963 controller used as parameter for the gled_init function typedef struct flash unsigned char font default font after initialization pointer to the function used for reading a byte from external memory unsigned char readxmem GLCDMEMADDR t addr pointer to the function used for writing a byte to external memory void writexmem GLCDMEMADDR t addr unsigned char data unsigned short ctrl_clk SSD1963 controller external clock crystal frequency kHz unsigned short tft pixel clk TFT pixel clock frequency kHz unsigned char hpulse width TFT panel horizontal pulse width pixel clock cycles unsigned char hfront porch TFT panel horizontal fr
179. DY t yend arc end y coordinate GLCDARCCOORDS _t e GLCDINIT_t structure type used for specifying various parameters used for initializing the LCD controller typedef struct flash unsigned char font default font after initialization pointer to the function used for reading a byte from external memory unsigned char readxmem GLCDMEMADDR t addr pointer to the function used for writing a byte to external memory void writexmem GLCDMEMADDR t addr unsigned char data additional structure members which are specific to each LCD controller GLCDINIT t 1998 2012 HP InfoTech S R L Page 192 CodeVisionAVR e GLCDSTATE_t structure type used for specifying the graphic display state typedef struct iCDCOL t fgcolor foreground color iCDCOL t bkcolor background color GLC GLC GLCDCOL t tpcolor transparency color GLCDX_t cx current x horizontal coordinate GLCDY t cy current y vertical coordinate GLCDTEXT t text current text display settings GLCDLINE t line current line display settings GLCDARCCOORDS t arc coordinates of last displayed arc GLCDFILL t fill current fill display settings pointer to the function used for reading a byte from external memory unsigned char readxmem GLCDMEMADDR t addr pointer to the function used for writing
180. D_CL_LIME GLCD_CL_BLU E GLCD_CL_RED GLCD_CL_AQUA GLCD_CL_YELLOW GLCD_CL_MAGENTA GLCD_CL_CYAN GLCD_CL_DARK_CYAN GLCD_CL_ORANGE GLCD_CL_PINK GLCD_CL_BROWN GLCD_CL_VIOLET GLCD_CL_SILVER GLCD_CL_GOLD GLCD_CL_NAVY GLCD_CL_MAROON GLCD_CL_PURPLE GLCD_CL_OLIVE The SSD2119 library functions can operate the display in 256 or 64k color modes For 256 color mode the following color bit allocation in a data byte is used e Bits 0 2 Blue color bits 0 2 e Bits 3 5 Green color bits 0 2 e Bits 6 7 Red color bits 0 1 1998 2012 HP InfoTech S R L Page 254 CodeVisionAVR For 64k color mode the following color bit allocation in a 16bit data word is used e Bits 0 4 Blue color bits 0 4 e Bits 5 10 Green color bits 0 5 e Bits 11 15 Red color bits 0 4 Notes e In order to reduce image storage size and improve speed it is recommended to use the 256 color mode if possible e The gled_ssd2119 h header file is automatically included when the main glcd h header file is included Therefore there is no need to explicitly include glcd_ssd2119 h e The EXAMPLES Graphic LCD SSD2119 directory contains fully functional code samples that may be used as references for SSD2119 initialization and usage 1998 2012 HP InfoTech S R L Page 255 CodeVisionAVR 4 12 10 Graphic LCD Functions Specific to the ST7565 Controller In order to take full advantage of the ST7565 controller s features the fol
181. E enable the Low interrupt level PMIC CTRL PMIC_LOLVLEN_ bm set the DS1307 functions to use TWID ds1307 twi_init amp twid_ master enable interrupts so that TWI can be used fasm sei initialize the RTC square wave output is disabled SQW OUT has logic state 0 rte init 0 0 0 rtc_set_time 12 0 0 set time 12 00 00 rtc_set_date 2 1 2 11 set date Tuesday 1 02 2011 display the time and date continuously while 1 read the time from the RTC rtc_get_time amp hour min amp Sec read the date from the RTC rtc_get_ date amp week day day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec led_clear lcd _ puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month 2000 year lcd _ puts display buffer delay ms 500 0 5 second delay 1998 2012 HP InfoTech S R L Page 355 CodeVisionAVR DS1307 example using the Software Bit Banged I2C Bus Functions include the DS1307 functions for bit banged I2C The I2C bus connections and bit rate must be specified in the Project Configure C Compiler Libraries I2C menu include lt ds1307 h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanum
182. EEPROM define EEPROM TWI BUS ADDRESS 0xA0 gt gt 1 void main void struct struct unsigned char msb unsigned char lsb addr unsigned char data twi eeprom unsigned char eeprom rd data the TWI master for SCL bit rate of 100 kHz twi_master init 100 globally enable interrupts asm sei write the byte 0x55 to the AT24C16B EEPROM address 0x210 twi_eeprom addr msb 0x02 twi_eeprom addr 1lsb 0x10 twi_eeprom data 0x55 twi_master trans EEPROM TWI_BUS ADDRESS unsigned char amp twi_eeprom 3 0 0 10ms delay to complete the write operation delay ms 10 1998 2012 HP InfoTech S R L Page 275 CodeVisionAVR read the byte back into the eeprom rd data variable twi master trans EEPROM TWI BUS ADDRESS unsigned char amp twi_eeprom 2 amp eeprom rd data 1 stop here while 1 4 14 2 Two Wire Interface Functions for Slave Mode Operation The following function is used for operating the TWI in slave mode void twi_slave_init bool match_any_addr unsigned char addr unsigned char rx_buffer unsigned char rx_buffer_size unsigned char tx_buffer bool slave_rx_handler bool rx_complete unsigned char slave_tx_handler bool tx_complete enables and initializes the TWI hardware for operating in slave mode Parameters match_any_addr enables the TWI s
183. EG1OUT 0 88 define ILI9325 VCOM 0 90 10 Vcom VREGLOUT 0 90 define ILI9325 VCOM 0 92 11 Vcom VREG1OUT 0 92 define ILI9325 VCOM 0 94 12 Vcom VREGLOUT 0 94 define ILI9325 VCOM 0 96 13 Vcom VREG1OUT 0 96 define ILI9325 VCOM 0 98 14 Vcom VREG1OUT 0 98 define ILI9325 VCOM_1_00 15 Vcom VREG1OUT 1 00 define ILI9325 VCOM 1 02 0x14 Vcom VREG1OUT 1 02 define ILI9325 VCOM_1 04 0x15 Vcom VREGIOUT 1 04 define ILI9325 VCOM_1 06 0x16 Vcom VREG1OUT 1 06 define ILI9325 VCOM_1 08 0x17 Vcom VREG1OUT 1 08 define ILI9325 VCOM_1 10 0x18 Vcom VREGIOUT 1 10 define ILI9325 VCOM 1 12 0x19 Vcom VREGIOUT 1 12 define ILI9325 VCOM_1_ 14 Ox1A Vcom VREG1OUT 1 14 define ILI9325 VCOM 1 16 0x1B Vcom VREG1OUT 1 16 define ILI9325 VCOM 1 18 Ox1C Vcom VREG1OUT 1 18 define ILI9325 VCOM_1 20 Ox1D Vcom VREGIOUT 1 20 define ILI9325 VCOM 1 22 0x1E Vcom VREGIOUT 1 22 define ILI9325 VCOM_1 24 Ox1F Vcom VREG1OUT 1 24 Initialization value for VcomH VcomH VREG1OUT VREGLOUT_MULT1000 1000 VREGIOUT_MULT1000 685 1000 define ILI 9325 VCOMH VREGIOUT MULT1000 VREGIOUT MULT1000 685 5 Initialization values for stepup freql define ILI9325 STEPUP1 FOSC 0 FDCDC1 Fosc define IL19325 STEPUP1 FOSC2 1 FDCDC1 Fosc 2 define IL19325 STEPUP1 FOSC4 2 FDCDC1 Fosc 4 define ILI9325 STEPUP1 FOSC8 3 FDC
184. HP InfoTech S R L Page 315 CodeVisionAVR Return values FR_OK success FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_INVALID_ OBJECT the file was not opened with f_open FRESULT f_truncate FIL fp truncates the file s size to the current position of the file read write pointer If the read write pointer is already at the end of the file the function will have no effect Parameter fp points to the FIL type structure that contains the file parameters This structure must have been previously initialized by calling the f_open function Return values FR_OK success FR_DENIED file access was denied because it was opened in read only mode FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_INVALID OBJECT the file was not opened with f_open FRESULT f_close FIL fp closes a file previously opened using f_open If any data was written to the file the cached information is written to the disk After the function succeeded the FIL type structure pointed by fp is not valid anymore and the RAM memory allocated for
185. 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 2012 HP InfoTech S R L Page 419 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 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 i ps1307 4 gt 4 Enabled Address Mo The PCF8583 Address list box allows you to specify the low bit of the I C addresses of the PCF8583 devices connected to the bus Maximum 2 PCF8583 devices can be used The PCF8583 devices are accessed through the Philips PCF8583 Real Time Clock Functions 1998 2012 HP InfoTech S R L Page 420 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 2C _ LCD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator ADC SPI 2C 12C
186. I_ specifies which XMEGA chip SPI controller is used by the SPI Functions _ATXMEGA_SPI_PORT_ specifies which XMEGA 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 Example This will set _ LINE __ to 50 and __ FILE to file2 c line 50 file2 c This will set _ LINE to 100 line 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 2012 HP InfoTech S R L Page 103 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 2012 HP InfoTech S R L Page 104 CodeVisionAVR 3 3 Reserved Keywords Following is a list of keywords
187. K_FREQUENCY_ BAUD_RATE 16L 1 100Hz timer interrupt generated by ATmegal28 Timerl overflow interrupt TIM1_OVF void timer comp_isr void ve initialize Timerl TCNTIH T1_ INIT gt gt 8 TCNTIL T1_ INITS amp OxFF card access low level timing function disk timerproc error message list flash char flash error msg not used wE _ DISK ERR FR INT R F R F EADY F E F H F D NAME E D FR EXIST vE LID_OBJECT F E PROTECTED F LID_DRIVE FR_NOT_ENABLED F O FILESYSTEM mE KFS ABORTED E IMEOUT 3 aa ax H Z tH l AWE l l za l pa l Ooo to j D H WEI GI pal O l pa l T yo 4 2 Z lt il H D E l s l py A lt D l l v5 zZ lt DH l pol l za l pul l ys HES Z2ZQxHSHMUHEZ aAZeZ wD E a pal l 1998 2012 HP InfoTech S R L Page 323 CodeVisionAVR display error message and stop void error FRESULT res if res gt FR_DISK_ ERR amp amp res lt FR_TIMEOUT printf ERROR p r n error msg res stop here while 1 void main void FAT function result FRESULT res will hold the information for logical drive 0 FATFS fat pointer to the FATFS type s
188. LE Sherri sssesassnnosnesesnesnannnennoosnssnnonsnsennenssosossnsnsnsnenosnnsensnneaesnsnnsnnnsnnnesassnnonnsonnnsanonnnsansonessesnssssesnssnsnnannonesonnenesosnnannnssenonsnsnsossnsonsssnansassnsasesnonessssnssssessssnons Recent Places Computer A Network 4 File name Files of type MULTFILE Project files prj Ex O e gt Hy Size CodeVisionAVR Pr r Open 7 Cancel By pressing the Open button you will open the Project file and its source file s You can later configure the Project by using the Project Configure menu command or by pressing the N toolbar button 1998 2012 HP InfoTech S R L Page 40 CodeVisionAVR 2 3 3 Exporting a Project The settings of the currently opened project can be exported to a new one by using the Project Export menu command or the 3H toolbar button Upon execution of this command a Project Export dialog window will open 7 EX Export Project MULTFILE PRJ To Savein J New Project 602 ega T Name Date modified Type wp No items match your search Recent Places Desktop Libraries m w Eo m Computer Se Network wm SSS Save as type Project files pri 7 Cancel _ allowing to specify the name of the new project to which all the settings of the current project will be exported 1998 2012 HP InfoTech S R L Page 41 CodeVisionAVR 2 3 4 Adding Notes or Comments to the Proje
189. LL 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 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 2012 HP InfoTech S R L Page 126 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
190. LT PKN50 2 PRNOO PRNO2 negative gamma gradient adj define SSD1289 DEFAU iT PRNOO 2 PRN10 PRN12 negative gamma gradient adj define SSD1289 DEFAULT PRN10 5 VRNOO VRNO3 negative gamma amplification adj define SSD1289 DEFAU iT _VRNOO 2 VRN1O VRN14 negative gamma amplification adj define SSD1289 DEFAULT _VRN10 3 The following colors are predefined in the glcd_ssd1289 h header file GLCD_CL_BLACK GLCD_CL_WHITE GLCD_CL_GRAY GLCD_CL_LIGHT_GRAY GLCD_CL_GREEN GLCD_CL_LIME GLCD_CL_BLUE GLCD_CL_RED GLCD_CL_AQUA GLCD_CL_YELLOW GLCD_CL_MAGENTA GLCD_CL_CYAN GLCD_CL_DARK_CYAN GLCD_CL_ORANGE GLCD_CL_PINK GLCD_CL_BROWN GLCD_CL_VIOLET GLCD_CL_SILVER GLCD_CL_GOLD GLCD_CL_NAVY GLCD_CL_MAROON GLCD_CL_PURPLE GLCD_CL_OLIVE The SSD1289 library functions can operate the display in 256 or 64k color modes For 256 color mode the following color bit allocation in a data byte is used e Bits 0 2 Blue color bits 0 2 e Bits 3 5 Green color bits 0 2 e Bits 6 7 Red color bits 0 1 For 64k color mode the following color bit allocation in a 16bit data word is used e Bits 0 4 Blue color bits 0 4 e Bits 5 10 Green color bits 0 5 e Bits 11 15 Red color bits 0 4 Notes e In order to reduce image storage size and improve speed it is recommended to use the 256 color mode if possible e The gled_ssd1289 h header file is automatically included when the main glcd h header file is include
191. M registers The Two Wire Data Interrupt option enables the generation of an interrupt when a data byte has been successfully received in the TWSD register i e no bus errors or collisions have occurred during the operation The Two Wire Address Stop Interrupt option enables the generation of an interrupt when the slave detects that a valid address has been received a transmit collision or a STOP condition have been detected on the bus The Two Wire Stop Interrupt option enables the generation of an interrupt when a STOP condition has been detected on the bus The TWI Acknowledge Action list box specifies which action will be performed when a valid command has been written to TWCMDO and TWCMD71 bits of the TWSCRB register or when the TWSD data register has been read after a data byte has been received from the master More details about the TWI Slave Interface can be found in the ATtiny 20 datasheet 1998 2012 HP InfoTech S R L Page 428 CodeVisionAVR 5 17 Setting the CAN Controller The CAN Interface configuration can be specified by clicking on the corresponding CAN node of the CodeWizardAVR selection tree a CodeWizardAVR test cwp File Help External IRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C LCD Bit Banged Project Information Chip ExtemalSRAM Pots 1wire 2Wire 2c GAN J CAN Enabled Baud Rate 1000 000 kHz Interrupts CAN Timer Overrun En
192. Medium Level T Receive Buffer Size 128 pA Transmit Buffer Size 128 pA Default USART for getchar Default USART for putchar The SPI Mode can be e Mode 0 e Mode 1 e Mode 2 e Mode 3 The Data Order in the frame can be e MSB First e LSB First 1998 2012 HP InfoTech S R L Page 472 CodeVisionAVR For enabled USARTs the CodeWizardAVR generates the functions void usartmn_init void where m is the lowercase suffix of the I O port where the USART is implemented n is the number of the USART on the port starting with 0 An unused USART can be disabled by calling the function void usart_disable USART_t pu where pu is a pointer to the correspoding USART_t structure Example USARTC1 is not used so disable it usart disable amp USARTC1 For transmitting data the CodeWizardAVR generates the functions void putchar_usartmn char c where c is the character to be transmitted m is the lowercase suffix of the I O port where the USART is implemented n is the number of the USART on the port starting with 0 For receiving data the CodeWizardAVR generates the functions char getchar_usartmn void where m is the lowercase suffix of the I O port where the USART is implemented n is the number of the USART on the port starting with 0 1998 2012 HP InfoTech S R L Page 473 CodeVisionAVR 6 12 Setting the Serial Peripheral Interfaces The XMEGA Serial Peripher
193. Messages Globally ttdefine Paths include paths one per line C cvayrkinc Amy_header_files Library paths one per line C cvayrlib Amy_libraries yo Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2012 HP InfoTech S R L Page 58 CodeVisionAVR 2 3 5 4 Setting the 1 Wire Library Options The Libraries tab is used for configuring specific driver libraries used by the compiler The 1 Wire tab is used for configuring the I O port allocation for the 1 Wire Protocol Functions Configure Project DS18820 PRJ Files C Compiler Before Build After Build Code Generation Advanced Libraries Messages Global Hdefine Paths nable 1 Wire Bus Interface Support Data Connection 1 0 Port PORTA x Bit 6 X Cancel Hep The following settings are available e Enable 1 Wire Bus Interface Support allows the activation of the 1 Wire Protocol Functions e W O Port and Bit specify in Data Connection the port and bit used for 1 Wire bus communication 1998 2012 HP InfoTech S R L Page 59 CodeVisionAVR 2 3 5 5 Setting the I C Library Options The Libraries tab is used for configuring specific driver libraries used by the compiler The I2C tab is used for configuring the I O port allocation and bit rate of the software bit banged C Bus Functions a
194. NOO PRNO2 negative gamma gradient adj 1998 2012 HP InfoTech S R L Page 235 CodeVisionAVR unsigned char prnl10 3 unsigned char vrn00 4 unsigned char vrnl10 5 GLCDINIT t PRN10 PRN12 negative adj VRNOO VRNO3 negative adj VRN10 VRN14 negative amplification adj gamma gradient gamma amplification gamma The following macros are defined for initializing the members of the GLCDINIT_t structure Initialization val define SS es for reverse x D1289 REVX_NORM 0 No horizontal reverse 7 define SSD1289 REVX_REV 1 Horizontal reverse Initialization values for reverse y define SSD1289 REVY NORM 0 No vertical reverse define SSD1289 REVY REV 1 Vertical reverse Initialization values for cl_ bits order define SSD1289 CL BITS RGB 0 Write color bits to display RAM in RGB order define SSD1289 CL BITS BGR 1 Write color bits to display RAM in BGR order TInitilization values for dc30 step up circuit cycle define SSD1289 STEPUP_FLINE24 0 Fline 24 define SSD1289 STEPUP_FLINE16 1 Fline 16 define SSD1289 STEPUP_FLINE12 2 Fline 12 define SSD1289 STEPUP FLINE8 3 Fline 8 define SSD1289 STEPUP FLINE6 4 Fline 6 define SSD1289
195. O port The TWI_MASTER_INFO_t data type variable must have been first initialized by a call to twi_master_init slave_addr specifies the 7 bit bus address of the slave with which the transaction should be performed tx_data represents a pointer to the buffer that holds the data that must be transmitted to the slave during the transaction tx_count specifies the number of bytes to transmit during the transaction If no data must be transmitted to the slave the tx_data parameter should be a NULL pointer and tx_count must be 0 rx_data represents a pointer to the buffer that will hold the data received from the slave during the transaction rx_count specifies the number of bytes to be received from the slave during the transaction If no data must be received from the slave the rx_data parameter should be a NULL pointer and rx_count must be 0 Return values true on success false in case of error The nature of the error can be established by reading the value of the result member of the TWI_MASTER_INFO_t structure data type variable pointed by twi 1998 2012 HP InfoTech S R L Page 282 CodeVisionAVR TWI master operation example accessing an external AT24C16B EEPROM using the TWID module running in master mode TWI functions for XMEGA devices include lt twix h gt delay functions include lt delay h gt TWI clock rate Hz define TWI_CLK_RATE 100000 7 bit
196. O ports can be also accessed using the Virtual Ports I O register definitions for the XMEGA128A1 chip include lt io h gt void main void unsigned char a Map PORTA to virtual port VPORTO and PORTB to virtual port VPORT1L PORTCFG VPCTRLA PORTCFG VPIMAP PORTB gc PORTCFG VPOMAP PORTA gc Set all VPORTO PORTA pins as inputs VPORTO_DIR 0x00 Read VPORTO PORTA input pins a VPORTO_IN Set all VPORT1 PORTB pins as outputs VPORT1 DIR 0xFF Write data to VPORT1 PORTB outputs VPORT1 OUT 0x11 Set VPORT1 PORTB pin 2 to 1 VPORT1 OUT 1 lt lt 2 Set VPORT1 PORTB pin 4 to 0 VPORT1 OUT amp 1 lt lt 4 Toggle VPORT1 PORTB pin 0 VPORT1_ OUT 1 lt lt 0 More details about accessing I O ports for the XMEGA chips can be found in the following Atmel documents e AVR1000 Getting Started Writing C code for XMEGA e XMEGA A Manual e XMEGA AU Manual e XMEGA D Manual 1998 2012 HP InfoTech S R L Page 133 CodeVisionAVR 3 14 1 Bit level access to the I O Registers Bit level access to the I O registers can be performed by using the special macros that are defined in the iobits h header file located in the INC subdirectory The following macros are available SETBIT port b sets bit b of port to logic 1 state Example set bit 5 of I O Port A output to logic 1 for non XMEGA chips SETBIT PORTA 5
197. ODE t enumeration type used for specifying the read write modes for the glcd_block function typedef enum GLCD PUTCOPY copy a bitmap from memory to LCD overwriting previous display data GLCD PUTXOR copy a bitmap from memory to LCD performing a XOR with previous display data GLCD PUTOR copy a bitmap from memory to LCD performing an OR with previous display data GLCD PUTNOT copy a bitmap from memory to LCD performing a bit negation GLCD PUTAND copy a bitmap from memory to LCD performing an AND with previous display data TTP used for displaying image in tranparent mode used for storing a block of data from specified coordinates to memory GLCD PUTCHAR used internally by the glcd_putchar function GLCD PUTFILL used internally by the rectangular area fill function GLCD CLEARBLOCK used internally by the rectangular area clear function GLCD SETBLOCK used internally by the rectangular area set function t GLCD P GLCD GE TLE GLCDBLOCKMOD mal Notes e The GLCD_PUTXOR GLCD_PUTOR GLCD_PUTNOT GLCD_PUTAND modes are supported only for displays with 2 colors monochrome e The GLCD_PUTTP mode is supported only for displays with more than 2 colors e GLCDMEMADDR _t type used for specifying RAM EEPROM FLASH or external memory addresses for bitmap image storage e GLCDTE
198. Operation for XMEGA Devices The chip is connected to the TWI of PORTD TWID of an ATxmega128A1 include the PCF8563 functions for TWI include lt pcf8563 twi h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line structure that holds information used by the TWID master for performing a TWI bus transaction TWI_ MASTER INFO t twid master 1998 2012 HP InfoTech S R L Page 338 CodeVisionAVR interrupt service routine for TWID master interrupt TWID TWIM vect void twid_master isr void twi_master int handler amp twid_ master TWI clock rate Hz define TWI CLK RATE 100000 void main void unsigned char hour min sec day month unsigned int year initialize the LCD 2 rows by 16 columns led_init 16 general TWID initialization no external driver interface no SDA hold time twi_init amp TWID false false enable and initialize the TWID master interrupt level low twi master init amp twid_master amp TWID TWI_ MASTER INTLVL LO gc TWI BAUD REG _ MCU_CLOCK FREQUENCY TWI_CLK RATE en
199. Page 266 CodeVisionAVR define T6963 DATA WR_INC 0xC0 Write data and increment ADP define T6963 DATA RD INC 0xC1 Read data and increment ADP define T6963 DATA WR 0xC4 Write data without modifying ADP define T6963 DATA RD 0xC5 Read data without modifying ADP define T6963 SCREEN PEEK 0xE0 Transfers 1 byte of displayed data to the data stack define T6963 SCREEN COPY OxE8 Copies a single raster line of data to the graphic area A detailed description of the above mentioned commands can be found in the T6963C datasheet void t6963_wrdata unsigned char data Writes a data byte to the T6963C controller Parameter data byte to be sent to the controller unsigned char t6963_rddata void Reads a data byte from the T6963C controller void glcd_cleartext void Clears the text overlay area when the character generator is used and sets the text display position at row 0 and column 0 void glcd_cleargraphics void Clears the LCD graphics overlay area by setting it s color to the current background color void glced_definechar unsigned char c flash unsigned char data Defines a character in the LCD controller s character generator external RAM Parameters c specifies the defined character s code must be gt 0x80 data points to a byte array that contains the character s definition The array dimension depends on the height of the character generator font a
200. Port PORTA SDABit 0 SCLBit 1 o pcresea 081307 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 SQW OUT pin can be specified using the OUT list box 1998 2012 HP InfoTech S R L Page 421 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 V Enabled Freq 1 v Hz Project Information External SRAM Parts 12C 1998 2012 HP InfoTech S R L Page 422 CodeVisionAVR 5 14 Setting the 1 Wire Bus The 1 Wire bus configuration can be specified by clicking on the 1 Wire Bus Interface Et node of the CodeWizardAVR selection tree amp CodeWizardAVR test cwp File Help External IRQ Timers USARTO USART1 Bit Banged Project Information Chip External SRAM Ports Analog Comparator ADC SPI 12C T 2Wire 20 Leb 1 Wire Port POR
201. 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 1998 2012 HP InfoTech S R L Page 129 CodeVisionAVR The ANSI char to int operands promotion can be turned on or off using the pragma promotechar directive Example turn on the ANSI char to int promotion pragma promotechart turn off the ANSI char to int promotion pragma promotechar This option can also be specified in the Project Configure C Compiler Code Generation Promote char to int menu Treating char by default as an unsigned 8 bit can be turned on or off using the pragma uchar directive 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 Con
202. Q USART Baud rate define BAUD RATE 19200 define BAUD INIT MCU CLOCK FREQUENCY BAUD RATE 16L 1 FAT function result FRESULT res number of bytes written read to the file unsigned int nbytes will hold the information for logical drive 0 FATFS fat will hold the file information FIL file will hold file attributes time stamp information FILINFO finfo file path char path 0 file txt text to be written to the file char text I like CodeVisionAVR file read buffer char buffer 256 100Hz timer interrupt generated by ATmegal28 Timerl overflow interrupt TIM1_ OVF void timer _comp_isr void ve initialize Timerl TCNT1H T1 INIT gt gt 8 TCNTIL T1_ INITS amp OxFF card access low level timing function disk timerproc 1998 2012 HP InfoTech S R L Page 328 CodeVisionAVR error message list ta LID OBJECT l flash char flash error msg not used FR DISK_ERR FR INT ERR FR INT ERR FR NOT READY FR NO FILE FR NO PATH FR INVALID NAME FR DENIED FR EXIST VA l FR WRITE PROTECTED FR INVALID DRIVE FR NOT ENABLED l W w HS 2AaHS WOH 44 AHH O FILESYSTEM _MKFS ABORTED IMEOUT l AX
203. R L Page 341 CodeVisionAVR 4 22 2 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 using both the hardware TWI and software bit banged C bus functions One of the following header files located in the INC subdirectory must be include d before using these functions e pcf8583_twi h for hardware TWI e pcf8583 h for software bit banged C bus The appropriate header files for hardware TWI twi h or twix h or software bit banged C bus i2c h functions prototypes are automatically include d with the pcf8583_twi h or pcf8583 h The Project Configure C Compiler Libraries I2C menu must be used for specifying the I O port allocation of the SCL and SDA signals along the bit rate of the SCL clock for bit banged C bus not the hardware TWI communication Note For proper operation the PCF8583 Functions require the presence of 3 3k 4 7k pull up resistors to 5V 3 3V for XMEGA devices on the SCL and SDA signals 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 TWI hardware respectively C bus must be initialized by calling the twi_master_init twi_init twi_master_init and pcf8583_twi_init for XMEGA devices respectively i2c_init functions This is the first function that must be called prior to
204. 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 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
205. ROM eeprom struct my structure se Global pointer loca eeprom struct my struc ed in RAM to the EEPROM located structure ure ptrse amp se Global pointer loca eeprom struct my struc ed in FLASH to the EEPROM located structure ure flash ptrfse amp Se ct ct T Global pointer loca eeprom struct my struc ed in EEPROM to the EEPROM located structure ure eeprom ptrese amp se void main void Local structure struct my structure sl Local pointer to the RAM located global structure struct my structure ptrlsr amp sr Local pointer to the FLASH located global structure flash struct my structure ptrlisf amp sf Local pointer to the EEPROM located global structure eeprom struct my structure ptrlse amp se 1998 2012 HP InfoTech S R L Page 115 CodeVisionAVR Structures can be grouped in arrays Example how to initialize and access an global structure array stored in EEPROM Global structure array located in EEPROM eeprom struct eeprom structure char a int b char c 15 se 2 a 25 Hello b 50 world void 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
206. RPOO RPO2 positive gamma gradient adj char rpl0 3 RP10 RP12 positive gamma gradient adj char vrp00 4 VRPOO VRPO3 positive gamma amplification adj char vrpl0 5 VRP1O VRP14 positive gamma amplification adj negative gamma control registers bits char kn00 3 KNOO KNO2 negative gamma micro adj char kn10 3 KN10 KN12 negative gamma micro adj char kn20 3 KN20 KN22 positive gamma micro adj char kn30 3 KN30 KN32 positive gamma micro adj char kn40 3 KN40 KN42 negative gamma micro adj char kn50 3 KN50 KN52 negative gamma micro adj char rn00 3 RNOO RNO2 negative gamma gradient adj char rnl10 3 RN10O RN12 negative gamma gradient adj char vrn00 4 VRNOO VRNO3 negative gamma amplification adj char vrnl0 5 VRN1O VRN14 negative gamma amplification adj Tt re defined for initializing the members of the GLCDINIT_t structure define ILI9325 R define ILI9325 R Initialization values for reverse x EVX NORM 0 No horizontal reverse EVX REV 1 Horizontal reverse values for reverse y define ILI9325 R define ILI9325 R Initialization EVY NORM 0 No vertical reverse EVY REV 1 Vertical reverse values for cl bits order define ILI9325 C define ILI9325 C Initialization L BITS RGB 0 Write color bits to display RAM in RGB order L_BI
207. RTC The prototypes for these functions are placed in the file ds1302 h located in the INC subdirectory This file must be include d before using the functions The DS1302 RTC Functions functions do not yet support the XMEGA 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 Note For XMEGA chips a virtual port must be mapped to the I O port used for connecting to the DS1302 chip and the address of the virtual port VPORTn_OUT register must be specified The DS1302 Functions are void rtc_init unsigned char tc_on unsigned char diodes unsigned char res this function initializes the DS1302 chip This is the first function that must be called prior to using the other DS1302 Functions If the tc_on parameter is set to 1 then the DS1302 s trickle charge function is enabled The diodes parameter specifies the number of diodes used when the trickle charge function is enabled This parameter can take the value 1 or 2 The res parameter specifies the value of the trickle charge resistor e 0 for no resistor e 1 fora 2kQ resistor e
208. Requirements Period 10 000000 pA ms Obtained 10ms 0 00 error Duty Cycle Ch 4 0 00 MA Duty Cycle Ch B 25 00 pA Apply Duty Cycle Ch C 50 00 sj Duty Cycle Ch D 75 00 4 PER j2710 h CNT 10 h CCA 10 h Compare Ch 4 Output CCB 9C4 h E Compare Ch B Output CCC 1388 h Compare Ch C Output CCD 1D4C h Compare Ch D Output Timer Overflow Underflow Interrupt Disabled Timer Error Interrupt Disabled Z Compare Capture A Interrupt Disabled x Compare Capture B Interrupt Disabled Xx Compare Capture C Interrupt Disabled Zi Compare Capture D Interrupt Disabled z The Requirements group box allows the user to specify the desired timer Period in ms and the Duty Cycles for the Compare Capture Channels A B C and D Pressing the Apply button will perform automatic timer configuration Clock Source PER CCA CCB CCC and CCD register values so that the required timer period and duty cycles will be obtained for a given Peripheral Clock value If the Compare Ch A Output option is enabled the corresponding waveform generation WG output will be activated for compare matches between the CNT and CCA registers The same applies for the Compare Ch B Output Compare Ch C Output and Compare Ch D Output options and the corresponding CCB CCC and CCD registers 1998 2012 HP InfoTech S R L Page 460 CodeVisionAVR When operating in waveform ge
209. SB The special __ reset attribute can be applied to a function that must be executed immediately after the chip reset before that startup initialization sequence This may be useful for XMEGA chips when SDRAM is used as external memory and a different clock source is used instead of the internal 2MHz oscillator which will ensure that correct timing is used for later SDRAM access by the startup code Example _ reset void system clocks init void Initialization code 1998 2012 HP InfoTech S R L Page 124 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
210. SS Default define SS value D2119 value D2119 Default value Gate 2 on lef define SSD2119 D D D M M SSS gt SS E for EFA SERE E50 E55 E60 E65 E70 E75 E80 QO 2 5 f 8 Ox0A Ox0C 0x01 50 55 60 65 F E reverse xX U for EFA T_REVX SS reverse y U for T REVY SS firs t out t side of display EFAULT_FIRST_OUT_GAT frame_freq Hz Hz Hz Hz 70Hz 75Hz 80Hz ae x a D2119 R g D2119 R EVX_NORM No horizontal reverse EVY NORM No vertical reverse gate py T Gl SSD2119 FIRST OUT GAT Default value for cl_bits order color bits wri write in RGB order ting order to display RAM define SSD2119 DEFAULT CL BITS SSD2119 CL BITS RGB Power control 1 BTO BT2 step up factor of the step up circuit define SSD2119 DEFAULT STEPUP FACTOR 4 Power control 1 DCO DC3 step up circuit cycle define SSD2119 DEFAULT STEPUP CYCLE SSD2119 STEPUP_FOSC4 Power control 1 APO AP2 adjusts the amount of current from the constant current source in the internal operational amplififier circuit define SSD2119 DEFAULT CRT SOURCE 2 Default value for VCIX2 voltage
211. SS PKN4O define SS PKN50 P define SSD PRNOO P define SSD D D PRN10 F define SS VRNOO V define SSD2 define SSD2 R 2 R 2 R 2119 D K 2 K 2 K 2 PKN32 posit PKN42 PKN52 2 R 2119 D R 2 R VRN10 VRN14 P12 posit 119 DEFAU ive gamm T PRP1O P03 posit 119 DEFAU ive gamm T_VRPOO P14 posit EFAU ive gamm N02 negat 119_DEFAU T_VRP10 ive gamm T_PKNOO N12 nega 119 DEFAU tive gamm iT PKN10 N22 posit 119 DEFAU ive iT gamm PKN20 ive iT gamm PKN30 119_DEFAU negat 119_DEFAU ive iT gamm PKN40 negat 119_DEFAU ive gamm T_PKN50 N02 negat EFAU ive gamm iT PRNOO N12 negat 119 DEFAU ive gamm N10 NO3 negat 119 DEFAU ive NOO negat 119 DEFAU TV amm ive T_VRN10 R g iT PR gamm R g R x a gradient adj 5 a amplification adj 2 a amplification adj 3 a 7 a 5 am 4 am 2 am 4 am 2 a gradient adj 2 a gradient adj 5 a amplification 2 a amplification 3 micro adj micro adj icro adj icro adj icro adj icro adj xy adj ad xi xi f The following colors are predefined in the glcd_ssd2119 h header file GLCD_CL_BLACK GLCD_CL_WHI TE GLCD_CL_GRAY GLCD_CL_LIGHT_GRAY GLCD_CL_GREEN GLC
212. START LINE 0x81 Partial image 1 display start line define ILI9325 CMD PARTIAL IMG1 END LINE 0x82 Partial image 1 display end line define ILI9325 CMD PARTIAL IMG2 DISPLAY POS 0x83 Partial image 2 display position define ILI9325 CMD PARTIAL IMG2 START LINE 0x84 Partial image 2 display start line define ILI9325 CMD PARTIAL IMG2 END LINE 0x85 Partial image 2 display end line define ILI9325 CMD PANEL IF CONTROL1 0x90 Panel interface control 1 define ILI9325 CMD PANEL IF CONTROL2 0x92 Panel interface control 2 define ILI9325 CMD PANEL IF CONTROL4 0x95 Panel interface control 4 define ILI9325 CMD OTP VCM PROG CONTROL O0xAl OTP VCM programming control define ILI9325 CMD OTP_VCM STATUS ENABLE 0xA2 OTP VCM status and enable define ILI9325 CMD OTP PGM ID KEY OxA5 OTP programming ID key A detailed description of the above mentioned command registers can be found in the ILI9325 datasheet void ili9325_wrreg unsigned char index unsigned short data Writes data to a command register of the ILI9325 controller Parameters index command register index data to be written unsigned short ili9325_rdreg unsigned char index Reads the contents of a command register of the ILI9325 controller Parameters index command register index 1998 2012 HP InfoTech S R L
213. T z Data Bits is 7 Stop Bits 1 x Parity Disabled X Multi processor Comm Mode Baud Rate 1200 v Real Baud Rate 1200 1 Error 0 0 Receiver Enabled V Transmitter Enabled Receive Complete Interrupt Medium Level z Transmit Complete Interrupt Medium Level hd Data Register Empty Interrupt Medium Level hd Receive Buffer Size 128 pA Transmit Buffer Size 128 MA Default USART for getchar Default USART for putchar The Communication Mode list box allows to select one of the following operating modes Asynchronous USART Synchronous USART Infrared Module IRDA 1 4 1998 2012 HP InfoTech S R L Page 469 CodeVisionAVR For the Asynchronous Synchronous and Infrared Module the following specific options are available The Data Bits option specifies the number of data bits in a data frame 5 to 9 The Stop Bits option specifies the number of stop bits in a data frame 1 or 2 The Parity bit in a data frame can be e Disabled e Even e Odd If the Multi processor Comm Mode option is enabled a dedicated bit in the frame is used to indicate whether the frame is an address or data frame If the Receiver is set up to receive frames that contain 5 to 8 data bits the first stop bit is used to indicate the frame type If the Receiver is set up for frames with 9 data bits the ninth bit is used for this purpose The Baud Rate list box allows to select the comm
214. TAG Daisy chain settings Target device is not part of a JTAG daisy chain Daisy chain Devices before 0 Instruction bits before Memory Settings E Preserve EEPROM After these options are specified it is very important to save the changes to the project solution by using the File Save All menu command or by pressing the E toolbar button 1998 2012 HP InfoTech S R L Page 153 CodeVisionAVR A typical debugging session will consist of the following steps 1 2 oo N Launching the debugger from the CodeVisionAVR IDE the current project remaining opened in CodeVisionAVR Loading the debugger s project solution associated with the COFF object file produced by CodeVisionAVR using the File Open Project Solution or File Recent Projects and Solutions menus Starting the actual debugging using the Debug Start Debugging and Break menu or by pressing the PIL toolbar button Single stepping or running the debugged code watching variables or registers etc Making changes and recompiling the code in the CodeVisionAVR IDE without having to close the debugger leading to the creation of an updated COFF object file The debugger will detect that the COFF and source files have changed and will ask for confirmation in order to reload them AVR Studio File Modification Detected The object file loaded for debugging has been modified ouside the enviomment A Press Reload to load the updated object fil
215. 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 2012 HP InfoTech S R L Page 144 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 2012 HP InfoTech S R L Page 145 CodeVisionAVR 3 19 1 Calling Assembly Functions from C The following example shows how to access functions written in assembly language from a C program function in assembler declaration this function will return 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
216. TE Data Bit oy D51820 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 2012 HP InfoTech S R L Page 423 CodeVisionAVR If you use the DS1820 DS18S20 temperature sensors you must check the DS1820 DS18S20 Enabled check box amp CodeWizardAVR test cwp z File Help ExtemallRQ 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 2012 HP InfoTech S R L Page 424 CodeVisionAVR 5 15 Setting the Two Wire Bus Interface The Two Wire Interface configuration can be specified by clicking on the corresponding Til node of the CodeWizardAVR selection tree External IRQ Timers USARTO USARTI Analog Comparator ADC SPI 12C Bit Banged Project Information
217. TS BGR 1 Write color bits to display RAM in BGR order define ILI9325 V define ILI9325 V define ILI9325 V define ILI9325 V define ILI9325 V define ILI9325 V define ILI9325 V define ILI9325 V define ILI9325 V define ILI9325 V values for the VREGI1OUT voltage REGLOUT_4V000 8 4 000 V REGLOUT_4V125 9 4 125 V REGIOUT_4V250 10 4 250 V REGLOUT_4V375 11 4 375 V REGLOUT_4V500 12 4 500 V REGIOUT_4V625 13 4 625 V REGLOUT_4V750 14 4 750 V REGIOUT_4V875 15 4 875 V REGLOUT_5V000 1 5 000 V REGIOUT 5V125 2 5 125 V 1998 2012 HP InfoTech S R L Page 217 CodeVisionAVR define ILI9325 VREGIOUT 5V250 3 5 250 V define ILI9325 VREGIOUT _5V500 4 5 500 V define ILI9325 VREGIOUT 5V750 5 5 750 V define ILI9325 VREG1OUT_6V000 6 6 000 V Initialization values for the Vcom voltage define ILI9325 VCOM 0 70 0 Vcom VREG1OUT 0 70 define ILI9325 VCOM_0_72 1 Vcom VREGIOUT 0 72 define ILI9325 VCOM_0 74 2 Vcom VREG1OUT 0 74 define ILI9325 VCOM 0 76 3 Vcom VREGLOUT 0 76 define ILI9325 VCOM 0 78 4 Vcom VREG1OUT 0 78 define ILI9325 VCOM_0 80 5 Vcom VREG1OUT 0 80 define ILI9325 VCOM 0 82 6 Vcom VREGLOUT 0 82 define IL19325 VCOM 0 84 7 Vcom VREG1OUT 0 84 define ILI9325 VCOM 0 86 8 Vcom VREG1OUT 0 86 define ILI9325 VCOM 0 88 9 Vcom VR
218. TWI bus slave address of the AT24C16B 2kbyte define EEPROM TWI BUS ADDRESS OxAO gt gt 1 3 EPROM structure that holds information used by the TWID master for performing a TWI bus transaction TWI_ MASTER INFO t twid master T interrupt service routine for TWID master interrupt TWID_TWIM vect void twid master_isr void twi_master_int_ handler amp twid_ master void main void struct struct unsigned char msb unsigned char lsb addr unsigned char data twi_eeprom unsigned char eeprom rd data general TWID initialization no external driver interface no SDA hold time twi_init amp TWID false false enable and initialize the TWID master interrupt level low twi master init amp twid_master amp TWID TWI MASTER INTLVL_LO gc TWI BAUD REG MCU CLOCK FREQUENCY _ TWI_CLK_ RATE enable the Low interrupt level PMIC CTRL PMIC_LOLVLEN_ bm globally enable interrupts asm sei 1998 2012 HP InfoTech S R L Page 283 CodeVisionAVR T write the byte 0x55 to the AT24C16B twi_eeprom addr msb 0x02 twi_eeprom addr 1lsb 0x10 twi_eeprom data 0x55 twi_master trans amp twid_master E EPROM TWI BUS ADDRESS unsigned char amp twi_eeprom 3 0 0 EPROM address 0x210 10ms delay to complete the write operation delay ms 10
219. TWID slave operation If one or several switches SWO SW7 are pressed on the STK600 board their state is transmitted by the TWIC master to the TWID slave which displays the received data on the LEDO LED7 The slave sends to the master the contents of the test_data array Use a STK600 development board with STK600 TOFP100 and STK600 RC100X 13 addapters The STK600 programmer must be set in JTAG programming mode in the Tools Programmer menu Make sure that the VTARGET and VREF voltages are set to 3 6V using AVR Studio The VTARGET LED on the STK600 board must be lighted Make the following connections on the STK600 PCO PDO SDA pin 4 7K resistor to VTG PC1 PD1 SCL pin 4 7K resistor to VTG SWO SW7 PEO PE7 using a ribbon cable with 10 pin connectors LEDO LED7 PAO PA7 using a ribbon cable with 10 pin connectors ef TWI functions for XMEGA devices include lt twix h gt string functions include lt string h gt delay functions include lt delay h gt TWI clock rate Hz define TWI_CLK_RATE 100000 7 bit TWI slave address define SLAVE ADDR Ox5A 1998 2012 HP InfoTech S R L Page 287 CodeVisionAVR structure that holds information used by the TWIC master for performing a TWI bus transaction TWI MASTER INFO t twi master TWIC master interrupt service routine interrup
220. Tmega103 Clock 4 000000 t MHz Crystal Oscillator Divider Enabled Check Reset Source The chip type can be specified using the Chip list box The chip clock frequency in MHz can be specified using the Clock spinedit box For the AVR chips that contain a crystal oscillator divider a supplementary Crystal Oscillator Divider Enabled check box is visible This check box allows you to enable or disable the crystal oscillator divider If the crystal oscillator is enabled you can specify the division ratio using the Crystal Oscillator Divider spinedit box For the AVR chips that allow the identification of the reset source a supplementary Check Reset Source check box is visible If it s checked then the CodeWizardAVR will generate code that allows identification of the conditions that caused the chip reset 1998 2012 HP InfoTech S R L Page 386 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 xa 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
221. 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 files will be deleted except the asm and vec assembly source files e Linker Files directory all files will be deleted 1998 2012 HP InfoTech S R L Page 77 CodeVisionAVR 2 3 6 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 a Project LED S Notes led c B Errors L94 undefined symbol k Warnings B L51 local variable q was declared but not referenced fai Headers 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 fi
222. V4_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 Its 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 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 1998 2012 HP InfoTech S R L Page 294 CodeVisionAVR include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt SPI driver function include lt spi h gt 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
223. VLCD63 5 4 VLCD63 5 5 VLCD63 5 the VcomL vol VcoomL VLCD VcoomL VLCD VcoomL VLCD VcoomL VLCD VcomL VLCD VcoomL VLCD iC iC iC iC VcoomL VLCD VcoomL VLCD VcoomL VLCD VcoomL VLCD VcoomL VLC VcoomL V VcoomL V VcoomL V VcoomL V iC iC iC iC VcoomL VLC VcoomL VLC VcoomL VLC VcomL VLC VcoomL VLC VcocomL VLC VcocomL VLC frame freq 50Hz 55Hz 60Hz 65Hz 70Hz 75Hz 80Hz 08V 24V 40V 56V TOV 86V 04V 18Vv 33V 49V 67V 80V 00v 14V 29V 45V tage 6370 63 0 6370 63 03 63 0 63 0 63 0 G30 63 0 63 0 D63 1 D63 1 D63 0 D63 0 D63 0 D63 0 D63 1 15 VcomL is set by an external variable resistor D63 1 D63 1 D63 1 D63 1 D63 1 LCD63 voltage gt y xy E 60 63 66 69 72 15 78 81 84 87 90 93 96 99 02 05 08 11 14 17 20 23 ei s7 y af 7 if 7 xy i sy 7 ae 1998 2012 HP InfoTech S R L Page 237 CodeVisionAVR Default value for reverse x define SSD1289 DEFAULT _REVX SSD1289 REVX_ NORM No horizontal reverse Default value for reverse y define SSD1289 DEFAULT REVY SSD1289 RE
224. VR 5 23 Specifying the Project Information The information placed in the comment header located at the beginning of the C source file produced by CodeWizardAVR can be specified by clicking on the Project Information m node of the selection tree amp CodeWizardAVR test cwp File Help Extemnal IRQ Timers USARTO USART1 Analog Comparator ADC SPI 12C 1wire 2Wire 20 LCD Chip ExtemalSRAM Ports i eatin 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 2012 HP InfoTech S R L Page 436 CodeVisionAVR 6 CodeWizardAVR Automatic Program Generator for the XMEGA Chips The CodeWizardAVR Automatic Program Generator allows you to easily write all the code needed for initializing the XMEGA on chip peripherals The Automatic Program Generator is invoked using the Tools CodeWizardAVR menu command or by clicking on the toolbar button The following dialog box will open a amp CodeWizardAVR AVR Chip Type ATSO ATtiny ATmega FPSLIC MEGA ETTI allowing to select between the AVR chip families for which automatic code generation will be performed 1998 2012 HP InfoTech S R L Page 437 CodeVisionAVR The File New menu command or the D toolbar button allow creating a new CodeWizardAVR project This project will be named by d
225. VR Automatic Program Generator ccccsscceceseseneeeeeeneeeeseeneeeesseneeeneseeneeenseeneeenss 381 5 1 Setting the AVR Chip Options 00 ccececcecceeceeeeeeeeeeeneceeeeeeececeaaaecaeeeeeeeseseneeaeeeeeeeseseenaaeeeeeees 386 5 2 Setting the External SRAM ccciccesccseveseeeeas teeceesineneataneeeetsideactasiacecctaneeeetsideacetidizectnanaeeectaneees 388 5 3 Setting the Input Output Ports ccc cccccssceeeeesneeeeecsneeeeesseeeeeeseeeeeeseeeeesseeeesssieeeessseeeeneea 390 1998 2012 HP InfoTech S R L Page 7 CodeVisionAVR 2 5 setting the Timers COUNIENS i c 2520 ct ti candle edie ates ead eed ec enc ede E EREE 393 5 6 Setting the UART or USART cccccccseeceeeeeceeeeeeeaeeeeeeeceaeeeecaaeeeeneeseaeeesaeeseaeeeeeeeeseaeeeseaeeseaeeees 403 5 7 Setting the Analog Comparator 0 00 cece terest terre titre teenies erties ee teeeeetieeeeetieeeeeeieeeeeeaa 406 5 8 Setting the Analog to Digital Converter cece eter retire erties erties ee teeeeetieeeertieeeertad 408 5 9 Setting the ATmega406 Voltage Reference sseesssesssrreseernnenssnnnnennaannnnaattnnaanannaaaeennaanannaae 410 5 10 Setting the ATmega406 Coulomb Counter sssssesesssssssrnsseennannsnnnstennaannnnnaseennaanannannennaananna ae 411 S11 Setting the SPI Interiace i5 iccsiieoie erected apiece cited 413 5 12 Setting the Universal Serial Interface USI cece ener eeeneee ee eneeeeee teaser teeeeeeeeeere 414 5 13 Setting the IC
226. VY NORM No vertical reverse Default value for cl_bits order color bits writing order to display RAM write in RGB order define SSD1289 DEFAULT CL BITS SSD1289 CL BITS RGB Power control 1 BTO BT2 step up factor of the step up circuit define SSD1289 DEFAU iT STEPUP FACTOR 4 Power control 1 DCO DC3 step up circuit cycle define SSD1289 DEFAU iT STEPUP CYCLE SSD1289 STEPUP_FOSC4 Power control 1 APO AP2 adjusts the amount of current from the constant current source in the internal operational amplififier circuit define SSD1289 DEFAU iT CRT SOURCE 2 Default value for VCIX2 voltage define SSD1289 DEFAU iT VCIX2 SSD1289 VCIX2_ 5V1 Default value for VLCD63 voltage define SSD1289 DEFAULT VLCD63 SSD1289 VLCD63 4V80 Default value for VcomL alternating drive voltage define SSD1289 DEFAULT VCOML SSD1289 VCOML 0 72 Default value for VcomH VLCD63 0 35 0x1A 0 01 define SSD1289 DEFAU iT VCOMH Ox1lA Default value for driving waveform control FLD bit splits one frame into 3 fields to reduce flicker define SSD1289 DEFAULT FLD 1 Default value for LCD frame frequency define SSD1289 DEFAULT FRAME FREQ SSD1289 FRAME80 Default initialization values for the
227. VisionAVR For some devices like the ATmega3290 the following options may be present a CodeWizardAVR test cwp a File Help LUSI USART Analog Comparator ADC sp i2c 1 Wire LeD LCD Controller Bit Banged Project Information Chip Ports ExtemallRQ Timers J INTO Enabled Mode Lowlevel v v Any change on 1 0 pins PCINTO v Any change on 1 0 pins PCINT8 15 V Any change on 1 0 pins PCINT16 23 v Any change on 1 0 pins PEINT 24 30 PCINTO PCINTS 15 PCI 4 gt Ot 2S 4 3 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 2012 HP InfoTech S R L Page 392 CodeVisionAVR 5 5 Setting the Timers Counters The timers counters configuration can be specified by clicking on the Timers Counters node of the CodeWizardAVR selection tree 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 Timers Counters Settings Timer Status Requirements Period 0 255000 4 ms Duty Cycle A 25 00 pA B 50 00 zj Obtained Period 0 255 ms 0 00 error _ Apply Timer Timer Timer2 Timer3 Time l Cloc
228. Voltage Reference Internal 1 00 Left Adjust Value DAC Conversion Interval 1 500 us 7 DAC Channel Refresh Timing 8 000 us K e Channel 1 External Output Enabled check box allows to activate the output of DAC Channel 1 on the corresponding port pin e Channel 1 Triggered by the Event System check box allows to trigger a Digital To Analog conversion for Channel 1 too when an event occurs on the Event System Channel selected by the corresponding option e DAC Channel Refresh Timing allows to specify the time interval between each time a channel is updated This interval can t exceed 30 us 1998 2012 HP InfoTech S R L Page 488 CodeVisionAVR The following functions are generated by the CodeWizardAVR void dacn_init void This function will initialize the DACn peripheral where n is the name of the PORT where the DAC outputs are located void dacn_write unsigned char ch unsigned int data This function will write the data value to the output of DACn channel ch If triggering by the Event System is disabled for channel ch the Digital to Analog conversion is automatically started by calling this function If triggering is enabled the conversion will start only after the function is called and an event occurs on the corresponding Event System channel More details about DAC operation for the XMEGA chips can be found in the Atmel XMEGA A Manual 1998 2012 HP InfoTech S R L Page 489 CodeVisionAVR 6 17 S
229. 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 Wi toolbar button 1998 2012 HP InfoTech S R L Page 26 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 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 2012 HP InfoTech S R L Page 27 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
230. XT_t structure type used for specifying the text displaying parameters typedef struct flash unsigned char font current font unsigned char horiz horizontal justification in pixels unsigned char vert vertical justification in pixels unsigned char transparent 1 enable transparent text display mode GLCDTEXT t Note The transparent structure member is defined only for displays with more than 2 colors e GLCDLINE_t structure type used for specifying the line drawing parameters typedef struct unsigned char thick line thickness unsigned char pattern bit pattern GLCDLINE t xJ 1998 2012 HP InfoTech S R L Page 191 CodeVisionAVR e GLCDPOINT_t structure type used for specifying point coordinates typedef s G G truct LCDX t x LCDY t y GLCDPOINT t e GLCDFILL_t structure type used for specifying the fill style parameters typedef struct GLCDCOL_t color fill color bit pattern for filling a rectangular area unsigned char pattern GLCD FILL PATTERN WIDTH GLCDFILL t e GLCDARCCOORDS _t structure type used for specifying the arc coordinates typedef s AN ANA AQAS S truct LCDX t x arc x center coordinate LCDY t y arc y center coordinate LCDX t xstart arc start x coordinate LCDY t ystart arc start y coordinate LCDX t xend arc end x coordinate LC
231. _ DI s i ll a set bit 1 of Port A as input VPORTO DI W m ll S x set bit 0 of Port A output to logic 1 VPORTO OUT 0 1 test bit 1 input of Port A if VPORTO_IN 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 PPR cate a Lancs Z Note 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 2012 HP InfoTech S R L Page 136 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 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
232. _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 Note 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 The CodeWizardAVR features an automatic timer configurator which is invoked by selecting the Requirements tab Here the user can enter the required timer period in ms and the duty cycle s for the enabled timer s outputs for PWM modes By pressing the Apply button all the corresponding timer configuration registers are set accordingly in order to obtain the closest possible values for the required parameters using the timer operating mode specified by the Mode list box 1998 2012 HP InfoTech S R L Page 394 CodeVisionAVR Selecting the Timer 0 Status tab allows to see the obtained output pulse parameters for the currently set timer clock frequency operating mode and configuration registers values Timers Counters Settings Timer Status Requirements Timer Period 0 255 ms Output Pulse s OCOA Period 0 255 ms Width 0 064 ms OCOB Period 0 255 ms Width 0 128 ms TimerO Timert Timer2 Timer3 Time 4 gt Clock Source System Clock hd Clock Value 2000 000 kHz M 4 Mode Phase corect PWM top 0xFF Out amp Non Inverted Pw M hd Out B
233. a byte to external memory void writexmem GLCDMEMADDR t addr unsigned char data GLCDSTATE t Note The tpcolor transparency color member is available only for displays with more than 2 colors e GLCDMEM_t enumeration type used for specifying the kind of memory access typedef enum GLCD MEM RAM RAM access GLCD MEM FLASH FLASH access GLCD MEM EEPROM EEPROM access GLCD MEM EXT external memory accessed using special functions GLCDMEM t The following macros are defined in the header file glcd_types h GLCD_LINE_SOLID solid line pattern GLCD_LINE_DOT_SMALL small dots line pattern GLCD_LINE_DOT_LARGE large dots line pattern _GLCD_FILL_PATTERN_WIDTH_ width of the fill pattern measured in pixels _GLCD_MAXCOLOR_ highest color value for a pixel in ON state The following macros are predefined by the compiler based on the settings from the Project Configure C Compiler Libraries Graphic LCD menu e _GLCD_MAXX_ horizontal display resolution measured in pixels e _GLCD_MAXY_ vertical display resolution measured in pixels e _GLCD_BYTEY_ signals that the LCD controller uses vertical byte organization for accessing the display RAM e _GLCD_INTERNAL_FONT_WIDTH_ specifies the width of the internal character generator s font measured in pixels e _GLCD_INTERNAL_FONT_HEIGHT_ specifies the height of the internal character generator s font measured in
234. a char string placed in EEPROM eeprom char eeprom eeprom ptr _to_eeprom This string is placed in EEPROM 1998 2012 HP InfoTech S R L Page 125 CodeVisionAVR In order to improve the 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 SMA
235. a will fit in btr specifies the number of bytes to be read from the file br points to an unsigned int variable that will hold the number of bytes of data effectively read from the file On function success if the number of effectively read bytes is smaller than the btr value then the file read write pointer reached the end of the file 1998 2012 HP InfoTech S R L Page 314 CodeVisionAVR Return values FR_OK success FR_DENIED file access was denied because it was opened in write only mode FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_INVALID_ OBJECT the file was not opened with f_open FRESULT f_write FIL fp const void buff unsigned int btw unsigned int bw writes data to a file previously opened with f_open After the function is executed the file read write pointer advances with the number of bytes written to the file Parameters fp points to the FIL type structure that contains the file parameters This structure must have been previously initialized by calling the f_open function buff points to a byte buffer array located in RAM that holds the data to be written to the file btw specifies the number of bytes to be written to the file bw points to an unsigned int variable that will hold the nu
236. able MOb Reaisters E Mobo Enable MOb Interrupts iT Mobo Highest Interrupt Priority MOb MObO X CAN System Clock 8000 0 kHz Propagation Time Segment 0 625 us z Re Sync Jump Width 0 125 us v Phase Segment 1 0 125 us Z Phase Segment 2 0 125 us A Sample Points 1 CAN Timer Clock Period 1 000 us m 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 Overrun serviced by the can_isr function 1998 2012 HP InfoTech S R L Page 429 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 t
237. able in the pop up menu invoked by mouse right clicking in the Editor window 2 2 4 7 Commenting Uncommenting a Text Selection Portions of text can be selected by dragging with the mouse Selected 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 8 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 2012 HP InfoTech S R L Page 30 CodeVisionAVR 2 2 4 9 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
238. able the Low interrupt level PMIC CTRL PMIC_LOLVLEN_ bm set the PCF8563 functions to use TWID pcf8563 twi_init amp twid_master enable interrupts so that TWI can be used fasm sei initialize the RTC Timer interrupt enabled Alarm interrupt enabled CLKOUT frequency 1Hz Timer clock frequency 1Hz rtc_init RTC_TIE ON RTC_AIE ON RTC_CLKOUT_1 RTC_TIMER CLK 1 rtc_set_time 12 0 0 set time 12 00 00 rtc_set_date 1 2 2011 set date 1 02 2011 display the time and date continuously while 1 read the time from the RTC rtc_get_time amp hour min amp Sec read the date from the RTC rtc_get_ date amp day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec lced_clear lcd _ puts display buffer 1998 2012 HP InfoTech S R L Page 339 CodeVisionAVR display the date on the LCD sprintf display buffer Date 2d 02d d day month year lcd _ puts display buffer delay ms 500 0 5 second delay PCF8563 example using the Software Bit Banged I2C Bus Functions include the PCF8563 functions for bit banged I2C The I2C bus connections and bit rate must be specified in the Project Configure C Compiler Libraries I2C menu include lt pcf8563 h gt include the LCD Functions The connections must be specified in the P
239. ace Size 64k 7 Bytes SRAM Wait State 2x CikPer X conce 2 Her The Enable check box activates the usage of the corresponding CSn chip select signal The Base Address represents the starting address in hexadecimal of the Address Space for which the chip select signal becomes active The Address Space Size list box allows to specify the address range size for which the chip select signal is active The SRAM Wait State list box allows inserting additional wait states when accessing slow external memory 1998 2012 HP InfoTech S R L Page 53 CodeVisionAVR Specific options can be set if SDRAM chips are connected to the XMEGA chip a XN Configure Project sdcard4 prj Files C Compiler Before Build After Build Libraries Messages Globally define Paths Code Generation EBI Configuration Advanced Memory Type and Connection EBI Disabled OLPC 2P ALE1 mux amp 7 0 D7 0 D SRAM 3P ALE1 mux A7 0 415 3 LPC 2P ALE1 ALE2 mux SRAM 3P ALE1 ALE2 mus D LPC 3 P ALE1 mux 47 0 D7 0 SDRAM 3P SDRAM CS3 Row Bits 11 Bits Column Bits Bits CAS Latency 2 w 2x ClkPer Mode Register Delay 0 x 2x ClkPer Row Cycle Delay 0 x 2x ClkPer Row to Pre charge Delay 0 2x ClkPer Row to Column Delay 0 w 2x ClkPer Write Recovery Delay 0 x 2x ClkPer Exit Self Refresh Delay
240. 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 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 g
241. age will be written Return values image size or 0 if the coordinate values are not valid void glcd_setlinestyle unsigned char thickness unsigned char bit_pattern Sets the current line displaying style Parameters thickness specifies the thickness of the lines to be drawn on the display measured in pixels bit_pattern specifies the pattern of the eight successive pixels of the lines to be drawn There are the following predefined patterns e GLCD_LINE_SOLID solid line pattern e GLCD_LINE_DOT_SMALL small dots line pattern e GLCD_LINE_DOT_LARGE large dots line pattern 1998 2012 HP InfoTech S R L Page 207 CodeVisionAVR void glcd_setlinethick unsigned char thickness Sets the current line thickness Parameter thickness specifies the thickness of the lines to be drawn on the display measured in pixels unsigned char glcd_getlinethick void Returns current line thickness setting measured in pixels unsigned char glcd_getlinepattern void Returns current line bit pattern setting void gilcd_line GLCDX_t x0 GLCDY_t y0 GLCDX_t x1 GLCDY_t y1 Draws a line with the current foreground color thickness and bit pattern The current pixel plot position will be updated to the line s ending point coordinates Parameters x0 specifies the line s starting point horizontal coordinate y0 specifies the line s starting point vertical coordinate x1 specifies the line s ending point horizontal coordinate y1 specifies t
242. ain 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 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 2012 HP InfoTech S R L Page 374 CodeVisionAVR 4 22 10 National Semiconductor LM75 Temperature Sensor Functions These functions are intended for easy interfacing between C programs and the LM75 C bus temperature sensor using b
243. al TTY VT52 or VT100 type of handshaking used in communication None Hardware CTS or DTR or Software XON XOFF possibility to append LF characters after CR characters on reception and transmission 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 2012 HP InfoTech S R L Page 98 CodeVisionAVR 2 6 Accessing the Help The CodeVisionAVR help system is accessed by invoking the Help Help menu command or by pressing the ee toolbar button 2 7 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 8 Quitting the CodeVisionAVR IDE To quit working with the CodeVisionAVR IDE you must select the File Exit menu command If some source files were modified and were not saved yet you will be prompted if you want to do that 1998 2012 HP InfoTech S R L Page 99 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 l
244. al 1 00 Zz Temperature Measurement Reference Enabled Conversion Start Mode Channels Sweeped by the Event System Z Event Channel 0 Sweeps Channel s 0 1 2 3 ADC Input Connected to GND for Offset Compensation ADC pin z ADC Compare Register 0 h Channel 0 Channel 1 Channel 2 Channel 3 Input Mode Internal positive input signal z Positive Input Temp Reference Negative Input GND Interrupt Low Level z Interrupt Mode Conversion Complete z In the above example figure an event that occurs on event channel 0 will start the sweep of ADC channels 0 1 2 and 3 inputs 1998 2012 HP InfoTech S R L Page 483 CodeVisionAVR The following functions are generated by the CodeWizardAVR void adcn_init void This function will initialize the ADCn peripheral where n is the name of the PORT where the ADC inputs are located The function will also perform the ADC calibration in 12 Bit mode by reading the calibration value from the signature row the measurement of its offset voltage and will store the offset value in the adcn_offset variable This value will be later substracted for offset compensation when performing analog to digital conversions void adcn_conv_start unsigned char channel This function will start an analog to digital conversion for the specified channel of ADCn It is generated only in C
245. al Interfaces SPI can be configured by clicking on the Serial Peripheral Interfaces SPI nodes of the CodeWizardAVR selection tree The following options are available SPIC Settings v SPI Enabled SPI Mode Made 0 v Master v SCK Leading Edge Rising Sample Data SCK Trailing Edge Falling Data Setup Data Order MSB First SCK Rate 15 625 kHz SPI Interrupt Disabled z The SPI Enabled check box allows to activate the corresponding Serial Peripheral Interface The SPI Mode can be e Mode 0 e Mode 1 e Mode 2 e Mode 3 The SPI can operate as e Master e Slave The Data Order in the frame can be e MSB First e LSB First If the SPI operates as a Master it will generate the SCK clock signal for the slave s The frequency of this signal obtained by dividing the ClkPer peripheral clock can be selected using the SCK Rate list box The SPI Interrupt can be enabled and its priority set using the corresponding list box The initialization of each SPI peripheral is performed by the void spim_init void functions generated by the CodeWizardAVR where m is the lowercase suffix of the I O port where the SPI is implemented 1998 2012 HP InfoTech S R L Page 474 CodeVisionAVR If the SPI Interrupt is disabled the SPI will operate in polled mode The following transmit receive function will be generated by the CodeWizardAVR for this situation for Master mode uns
246. 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 memory 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 2012 HP InfoTech S R L Page 168 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 d before using the f
247. amming and verification Fuse and Lock Bits programming 1998 2012 HP InfoTech S R L Page 66 CodeVisionAVR The Merge data from a ROM File for FLASH Programming option if checked will merge in the FLASH programming buffer the contents of the ROM file created by the compiler after Make with the data from the ROM file specified in ROM File Path This is useful for example when adding a boot loader executable compiled in another project to an application program that will be programmed in the FLASH memory 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 prot
248. 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 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 2012 HP InfoTech S R L Page 171 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 d 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 ch
249. anguage 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 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 its expansion and the formal parameters with the real ones Example define SUM a b a b th
250. ar 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 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 2012 HP InfoTech S R L Page 172 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 str
251. ar value 1998 2012 HP InfoTech S R L Page 342 CodeVisionAVR unsigned char rtc_get_status unsigned char chip this function returns the value of the PCF8583 control status register By calling this function the global variables rtc_status and rtc_alarm are automatically updated The rtc_status variable holds the value of the PCF8583 control status register The rtc_alarm variable takes the value 1 if an RTC alarm occurred 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 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 day unsigned char month unsigned year this function returns the current date measured by the RTC The day 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 day unsigned char month unsigned year this function sets the current date of th
252. aracters option allows to turn on or off the displaying of non printable characters in the Editor window The 1 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 V Code Information v Function Call Tree
253. argument 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 1998 2012 HP InfoTech S R L Page 163 CodeVisionAVR The function returns the number of successful entries or 1 on error signed char sscanf char str char flash fmtstr arg1 address arg2 address this function is identical to scanf except that the formatted text is inputted from the null terminated character string str located in 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 sup
254. at holds the file information and has the time stamp to be set contained in the fdate and ftime members Return values FR_OK success FR_NO_FILE couldn t find the file or directory FR_NO_PATH couldn t find the path FR_INVALID_NAME the file or directory name is invalid FR_INVALID_DRIVE the drive number is invalid FR_NOT_READY no disk access was possible due to missing media or other reason FR_WRITE_PROTECTED the media in the drive is write protected FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTENM there is no valid FAT partition on the disk 1998 2012 HP InfoTech S R L Page 327 CodeVisionAVR Example ATmegal28 I O register definitions include lt megal28 h gt FAT on MMC SD SD HC card support include lt ff h gt printf include lt stdio h gt include the PCF8563 functions The I2C bus connections and bit rate must be specified in the Project Configure C Compiler Libraries I2C menu include lt PCF8563 h gt Timerl overflow interrupt frequency Hz define Tl_OVF_FREQ 100 Timerl clock prescaler value define T1 PRESC 10241 Timerl initialization value after overflow define Tl_INIT 0x10000L _MCU_CLOCK_FREQUENCY_ T1_PRESC T1_OVF_FRE
255. ated char string that represents the path name for the file or directory value specifies the new combination of attribute flags to be set mask specifies the combination of which attribute flags must be changed The attribute is obtained by combining the following predefined macros AM_RDO Read Only attribute flag AM_HID Hidden attribute flag AM_SYS System attribute flag AM_ARC Archive attribute flag using the binary OR operator 1998 2012 HP InfoTech S R L Page 326 CodeVisionAVR Return values FR_OK success FR_NO_FILE couldn t find the file or directory FR_NO_PATH couldn t find the path FR_INVALID_NAME the file or directory name is invalid FR_INVALID_DRIVE the drive number is invalid FR_NOT_READY no disk access was possible due to missing media or other reason FR_WRITE_PROTECTED the media in the drive is write protected FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTENM there is no valid FAT partition on the disk FRESULT f_utime const char path const FILINFO fno changes the time stamp of a file or directory Parameters path points to a RAM based NULL terminated char string that represents the path name for the file or directory fno points to the FILINFO type structure th
256. ates deallocates a work area of memory for a logical drive volume This function must be called first before any other FAT access function In order to deallocate a work area associated with a logical drive a NULL pointer must be passed as fs Note This function only initializes the work area no physical disk access is performed at this stage The effective volume mount is performed on first file access after the function was called or after a media change Parameters vol specifies the logical drive number 0 9 fs is a pointer to the FATFS type data structure associated with the logical drive that must be allocated deallocated Return Values FR_OK success FR_INVALID_DRIVE the drive number is invalid FRESULT f_open FIL fp const char path unsigned char mode creates a file object FIL structure which will be used for accessing the file The file read write pointer is set to the start of the file Parameters fp points to the FIL type structure to be created After the f_open function succeeds this structure can be used by the other functions to access the file path points to a RAM based NULL terminated char string that represents the path name for the file to be created or opened The path name has the following format logical_drive_number directory_name file_name Examples file txt a file located in the current directory specified previously by the f_chdir function on the current drive specified previously
257. ation General Settings iL System Clocks tl External Bus Interface ny Event System 105 Ports WE Virtual Ports CC Timers Counters CO Watchdog Timer Uy ATC f USARTs a Serial Peripheral Interfaces ol 1 Wire Bus Interface F08 Two Wire Interfaces Aue Analog to Digital Converters tt Digital to Analog Converters Alphanumeric LCD Graphic LCD If program code was already generated and is available for display in the Program Preview window clicking on a peripheral node will position the cursor at the beginning of the initialization code for that peripheral 1998 2012 HP InfoTech S R L Page 441 CodeVisionAVR 6 1 Setting the General Chip Options The general chip options can be specified by clicking on the General Settings node of the CodeWizardAVR selection tree General Settings Chip Type ATxmegal 2841 z Program Type Application Zi Check Reset Source Interrupts Enable Low Level Interrupts Enable Medium Level Interrupts Enable High Level Interrupts The Chip Type list box allows to select the XMEGA device for which code will be generated The Program Type list box allows to select the type of the generated code e Application e Boot Loader 1998 2012 HP InfoTech S R L Page 442 CodeVisionAVR The Check Reset Source check box enables the generation of code that allows the identification of the conditions that caused the XMEGA ch
258. ation list box allows selection of the splitting address for the two external SRAM pages The wait states that are inserted during external SRAM access can be specified for the lower respectively upper memory pages using the Lower wait states respectively Upper wait states list boxes The MCUCR EMCUCR XMCRA registers in the startup initialization code are configured automatically according to these settings 1998 2012 HP InfoTech S R L Page 389 CodeVisionAVR 5 3 Setting the Input Output Ports The input output Ports configuration can be specified by clicking on the Ports ios node of the CodeWizardAVR selection tree amp CodeWizardAVR test cwp x File Help Exteinal IRQ Timers USARTO USART1 Analog Comparator ADC SPI lac 1wire 2Wire 20 LCD Bit Banged Project Information Chip Extemal SRAM Port A Port B Port C PotD Pc ME Data Direction Pullup Output Value Bit 0 In T Bo Bit1 In T Bit1 Bit2 _In Ti Bit 2 Bit3 In T Bit3 Bit 4 _In T Bit4 Bit5 In Ti Bit5 Bit6 _In Ti Bit 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 inp
259. 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 to identify the ROM codes of the devices and to be able to address them ata later stage in the program Example include lt mega8515 h gt the ATmega8515 port and bit used for the 1 Wire bus must be specified in the Project Configure C Compiler Libraries 1 Wire menu 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 contr
260. by calling the function void tc1_disable TC1_t ptc where ptc is a pointer to the correspoding TC1_t structure 1998 2012 HP InfoTech S R L Page 463 CodeVisionAVR 6 8 Setting the Watchdog Timer The XMEGA Watchdog Timer WDT can be configured by clicking on the Watchdog Timer Gh node of the CodeWizardAVR selection tree The following options are available Watchdog Timer Settings v Watchdog Enabled Watchdog Timeout Period Sms X Watchdog Window Mode Timeout Period Oms v The Watchdog Enabled option allows to activate the WDT The Watchdog Timeout Period list box allows to specify the open window time period after which the WDT will issue a system reset in Normal and Window operating modes if the application code has not reset the WDT using the WDR instruction The Watchdog Window Mode Timeout Period allows to specify the length of the closed window time period in Window operating mode in which if the application code uses the WDR instruction to try to reset the WDT the WDT will issue a system reset If the application code resets the WDT after the closed window time elapses but during the open window no system reset will occur Note If the Watchdog Window Mode Timeout Period is set to 0 the WDT will operate in Normal mode The WDT initialization is performed by the void watchdog_init void function generated by the CodeWizardAVR 1998 2012 HP InfoTech S R L Page 464 CodeVisi
261. bytes contain the ROM code and CRC unsigned char rom_codes MAX DEVICES 9 1998 2012 HP InfoTech S R L Page 364 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
262. c As x Savein inc amp fv r Name 7 Date modified Type Size my 1WIRE 01 Mar 01 03 15 C compiler header s Recent Places 5 43U5B355 05 Mar 07 13 39 C compiler header w E 76C711 05 Mar 07 13 40 C compiler header L 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 lt 4 m p Network File name mylib bg Save Save as type lc Compiler header file h X Cancel 1998 2012 HP InfoTech S R L Page 147 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 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 Fi
263. c LCD Functions Specific to the SSD2119 Controller 0 cccceeeeeeeteeeeeeees 248 4 12 10 Graphic LCD Functions Specific to the ST7565 Controller ccceeeseeseeeeeeeeees 256 4 12 11 Graphic LCD Functions Specific to the ST7920 Controller 0 ccccseceeeeeeeeeeeeee 260 4 12 12 Graphic LCD Functions Specific to the T6963C Controller ee ceeeeeeeeeeeeeneees 266 4 12 13 Graphic LCD Functions Specific to the UC1701 Controller 0 ccceeetseeeceeeeeeees 268 1998 2012 HP InfoTech S R L Page 6 CodeVisionAVR BAe 1 Wire Protocol FUNGHONS m ianandtneniduninnsaiamnaienaaandinadianae eT 4 14 Two Wire Interface Functions for non XMEGA Devices 0 0000 cece eeeeeeeeeeeeeeeeenaeeeeeeenaeeeeeeaas 274 4 14 1 Two Wire Interface Functions for Master Mode Operation ccccceeeeeeeeereeeeeeees 274 4 14 2 Two Wire Interface Functions for Slave Mode Operation cccceeeeeeeeteeeeeeeeees 276 4 15 Two Wire Interface Functions for XMEGA DeVICES 0 0 0 cc ccceceeeeeeeeeeneeeeeenneeeeeetaeeeeeeenaeeeeeeaas 280 4 15 1 Two Wire Interface Functions for Master Mode Operation ccccceeeteeesteeeeeeeees 281 4 15 2 Two Wire Interface Functions for Slave Mode Operation ccceeeeeeeeenteeeeeeees 285 4 16 Software Bit Banged C Bus Um CHM Se sassceit sx atustadassiGaienuritannie tanundagaiaiiiomdaentiain 290 A A SPli FUNCIONS oeconomia e sda c
264. ce option allows to select the reference used by the DAC e 1 0 V internal reference e the AVCC pin e the AREF pin on PORTA e the AREF pin on PORTB The Left Adjust Value option if enabled allows to distribute the data bits 4 11 to the CHODATAH and data bits 0 3 to the bits 4 7 of the CHODATAL registers This also allows for 8 bit Digital to Analog conversions if only the CHODATAH register is written If the option is disabled the data bits 0 7 are distributed to the CHODATAL and data bits 8 11 to the bits 8 11 of the CHODATAH registers The DAC Conversion Interval specifies the time interval between a completed channel conversion until starting a new conversion Its minimal value depends of the Peripheral Clock value and can t be less than 1 us in Single Channel operating mode 1998 2012 HP InfoTech S R L Page 487 CodeVisionAVR In Dual Channel operating mode the DAC output is fed into two different pins using a sample and hold circuit In this operating mode the following additional options are available DACA Settings v DAC Enabled DAC Low Power Mode Internal Output Routed to the ADC and Analog Compator MUX es Operating Mode Dual Channel Sample Hold forChO amp Ch1 Channel 0 External Output Enabled Channel 1 External Output Enabled V Channel 0 Triggered by the Event System V Channel 1 Triggered by the Event System DAC Triggered by Event System Channel 0 w DAC
265. ced with the same file located in the INC directory of the CodeVisionAVR installation 3 24 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 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 vpri
266. cessary 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 d more than once the compiler will issue errors about variable redeclarations 1998 2012 HP InfoTech S R L Page 44 CodeVisionAVR 2 3 5 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 Fe Linker Files _ link ie C 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 created by the linker during the Build process will be placed in the Linker Files directory 1998 2012
267. cifies the font size used by the Editorl e Default Text 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 2012 HP InfoTech S R L Page 92 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 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 ong e 4 define MAX a b Language element Symbol x 5 i a gt b a b Text Color HM Window Text w 7 flash char pflash flash int 0 3 8 eeprom int peepro
268. control x ROL6 0x35 Gamma control L7 0x36 Gamma control xf L8 0x37 Gamma control 7 L9 0x3a Gamma control X7 ROL10 0x3b Gamma control 10 1 0x41 Vertical scroll control for screen 1 2 0x42 Vertical scroll control for screen 2 define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM l H nN U 1 O A O Kk td l l QHN z OvuoUO UU eee Ue U O z j W H G E A A g define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM define SSD1289 CM l E OO R Oo oO QOoQuvsaa O DD DD define SSD1289 CMD FRAME define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD GAMMA CO define SSD1289 CMD VERT SCRO tj ve BwwawaBeaeeeawewaeaee vo oooo ow EC ea OER ea Ea ee oe OWMOATIAN OB WN HAD O O 0 HHHHHHAHAAAHAHHHAO define SSD1289 CMD V GI RT_SCRO 1998 2012 HP InfoTech S R L Page 233 CodeVisionAVR define SSD1289
269. controller s Graphic Display RAM 1998 2012 HP InfoTech S R L Page 234 CodeVisionAVR The glcd_ssd1289 h header file also contains the definition of the GLCDINIT_t type specific for the SD1289 controller used as parameter for the gled_init function typedef struct flash unsigned char font default font after initialization pointer to the function used for reading a byte from external memory unsigned char memory readxmem a pointer to the function used for wri GLCDMEMADDR t addr ting a byte to external void writexmem GLCDMEMADDR t addr unsigned char data unsigned char reverse x 1 reverse display horizontally unsigned char reverse yil reverse display vertically unsigned char cl_ bits order 1 selects the color bits writing order to the display RAM 0 gt RGB 1 gt BGR power control registers bits unsigned char stepup factor 3 step up factor of the step up circuit see BTO BT2 bits in the datasheet unsigned char stepup_cycle 4 controls the cycle for the step up circuit unsigned char crt_source 3 adjusts the amount of current from the constant current source in the internal op amplififier circuit APO AP2 bits unsigned char vcix2 3 adjusts the VCIX2 voltage unsigned char vlcd63 4 adjusts the VLCD63 voltage unsigned
270. ct 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 menu command or the eA toolbar button PS Project Notes MULTFILE PRJ o 6 this is a note 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 2012 HP InfoTech S R L Page 42 CodeVisionAVR 2 3 5 Configuring the Project The Project can be configured using the Project Configure menu command or the N toolbar button 2 3 5 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 amp amp toolbar button A Configure Project tabbed dialog window will open You must select the Files and Input Files tabs XN Configure Project MULTFILE PRJ Fies C Compiler Before Build After Build Input Files Output Directories E A C cvavr2 EXSMPLES MULTFILESMULTFILE PR mainfile c a New filel c T fle2 c Ti ad file3 c p By pressing the New button you can create a new c source file and add it to the project The Add button allows adding an existing source file to the project 1998 2012 HP InfoTech S R L Page 43 CodeVisionAVR Multiple files can be added by holding
271. ction failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTEM there is no valid FAT partition on the disk 1998 2012 HP InfoTech S R L Page 325 CodeVisionAVR FRESULT f_unlink const char path deletes an existing file or directory Parameter path points to a RAM based NULL terminated char string that represents the path name for the file or directory to be deleted Return values FR_OK success FR_NO_FILE couldn t find the file or directory FR_NO_PATH couldn t find the path FR_INVALID_NAME the file or directory name is invalid FR_INVALID_ DRIVE the drive number is invalid FR_DENIED access was denied because one of the following reasons file or directory read only attribute is set the directory is not empty FR_NOT_READY no disk access was possible due to missing media or other reason FR_WRITE_PROTECTED the media in the drive is write protected FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTENM there is no valid FAT partition on the disk FRESULT f_chmod const char path unsigned char value unsigned char mask changes the attribute of a file or directory Parameters path points to a RAM based NULL termin
272. ctions like in the following example FAT on MMC SD SD HC card support include lt ff h gt include the PCF8563 functions The I2C bus connections and bit rate must be specified in the Project Configure C Compiler Libraries I2C menu include lt PCF8563 h gt void main void init the PCF8563 RTC rto init 0 RTC_CLKOUT_OFF RIC T IMER_OFF init the pointer to the RTC function used for reading time prtc_get_time void unsigned char unsigned char unsigned char rtc_get_time init the pointer to the RTC function used for reading time prtc_ get date void unsigned char unsigned char unsigned int rtc_get_ date follows the rest of the program PA ee FI Notes e Ifthe return type of the RTC functions is different from void like required by the prtc_get_time and prtc_get_date pointer declarations then casting to the appropriate type must be performed like in the above example e If the system doesn t have a Real Time Clock then these pointers must not be initialized at program startup In this situation they will be automatically initialized to NULL in the FAT access library and all files or directories created or modified by the FAT access functions will have the time stamp January 1 2009 00 00 00 1998 2012 HP InfoTech S R L Page 312 CodeVisionAVR The FAT access functions are FRESULT f_mount unsigned char vol FATFS fs alloc
273. d Therefore there is no need to explicitly include gled_ssd1289 h e The EXAMPLES Graphic LCD SSD1289 directory contains fully functional code samples that may be used as references for SSD1289 initialization and usage 1998 2012 HP InfoTech S R L Page 239 CodeVisionAVR 4 12 8 Graphic LCD Functions Specific to the SSD1963 Controller The SSD1963 library functions supplied with the CodeVisionAVR Advanced license can operate the controller in 8 and 16 bit interface modes To obtain higher display speed the 16 bit interface mode is recommended In order to take full advantage of the SSD1963 controller s features the following specific functions declared in the glcd_ssd1963 h header file were implemented void ssd1963_wrcmd unsigned char cmd Writes a command to the SSD1963 controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the gled_ssd1963 h header file define SSD1963 CMD NOP 0x00 No operation define SSD1963 CMD SOFT RESET 0x01 Software reset define SSD1963 CMD GET PWR MODE Ox0A Get the current power mode define SSD1963 CMD GET ADDR MODE 0x0B Get the frame buffer to the display panel read order define SSD1963 CMD GET DISPLAY MODE 0x0D Returns the display image mode status define SSD1963 CMD GET SIGNAL MODE 0
274. d dest void src unsigned char n for the TINY memory model void memcpy void dest void src unsigned int n for the SMALL memory model Copies n bytes from src to dest dest must not overlap src else use memmove Returns a pointer to dest void memcpyf void dest void flash src unsigned char n for the TINY memory model void memcpyf void dest void flash src unsigned int n for the SMALL memory model Copies n bytes from src located in FLASH to dest Returns a pointer to dest void memccpy void dest void src char c unsigned char n for the TINY memory model void memccpy void dest void src char c unsigned int n for the SMALL memory model Copies at most n bytes from src to dest until the character c is copied dest must not overlap src Returns a NULL pointer if the last copied character was c or a pointer to dest n 1 1998 2012 HP InfoTech S R L Page 175 CodeVisionAVR 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
275. d 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 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 prog
276. d to hold the information required by the TWI module when operating in master mode The ds1307_twi_init function must be called before rtc_init Refer to the supplied example at the end of this chapter for more details 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 2012 HP InfoTech S R L Page 352 CodeVisionAVR 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 week_day unsigned char day unsigned char month unsigned char year this function returns the current date measured by the RTC The week_day day month and year pointers must point to the variables that must receive the values of day of week day month and year void rtc_set_date unsigned char week_day unsigned char day unsigned char month unsigned char year this function sets the current date of the RTC DS1307 example using the hardware TWI Functions for Master Mode Operation for non XMEGA Devices include the DS1307 functions for TWI include lt ds1307 twi h gt include the LCD Functions The connections must be specified in
277. de 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 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 l1sb temp_msb temp high temp_ low resl res2 cnt_rem cnt_c ere __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 2012 HP InfoTech S R L Page 362 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 the ATmega8515 port and bit used for the 1 Wire bus must be specified in the Project Configure C Compiler Libraries 1 Wire menu include the DS1820 DS18S20 functions prototypes include
278. dinates will be used instead e GLCD_PUTXOR copy a bitmap from memory to LCD performing a XOR with previous display data e GLCD_PUTOR copy a bitmap from memory to LCD performing an OR with previous display data e GLCD_PUTNOT copy a bitmap from memory to LCD performing a bit negation e GLCD_PUTAND copy a bitmap from memory to LCD performing an AND with previous display data Return values image size or 0 if the coordinate values are not valid Notes e The GLCD_PUTXOR GLCD_PUTOR GLCD_PUTNOT GLCD_PUTAND modes are supported only for displays with 2 colors monochrome e The GLCD_PUTTP mode is supported only for displays with more than 2 colors 1998 2012 HP InfoTech S R L Page 203 CodeVisionAVR unsigned long glcd_putimagef GLCDX_t left GLCDY_t top flash unsigned char pimg GLCDBLOCKMODE_t mode Displays a bitmap image located in FLASH at specified coordinates Parameters left specifies the horizontal coordinate of the left top corner of the image top specifies the vertical coordinate of the left top corner of the image pimg pointer to the image data which is located in FLASH mode specifies how the display operation must be performed e GLCD_PUTCOPY copy a bitmap from memory to LCD overwriting previous display data e GLCD_PUTTP copy a bitmap from memory to LCD overwriting previous display data using transparent mode when an image pixel with the current transparency color must be displayed the background c
279. ding Atmel data sheet 1998 2012 HP InfoTech S R L Page 399 CodeVisionAVR By selecting the Timer 3 tab you can have the following options Timers Counters Settings Timer3 Status Requirements Period 1 000000 MA ms Duty Cycle A 10 00 pA B 20 00 yA c 30 00 4 x Obtained Period 1 ms 0 00 error Apply Clock Source System Clock Z Clock Value 16000 000kHz Mode Ph corect PWM top ICR3 Z Out A Noninv 7 Out B Non Inv x Out C Inverted Input Capture Noise Cancel Rising Edge Interrupt on Timer3 Overflow A T Input Capture Value 0 h inp Capture 1F40 h Comp 320 hB 640 hC 15E0 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 counte
280. direction 0 gt 63 define SPLC501 CMD _COM63 0 OxC8 sets the COM output scan direction 63 gt 0 define SPLC501 CMD POWER CTRL 0x28 turns on off the voltage follower bit 0 voltage regulator bit 1 voltage booster bit 2 define SPLC501 VOLT FOLLOWER_ON 1 lt lt 0 enable voltage follower define SPLC501 VOLT REGULATOR ON 1 lt lt 1 enable voltage regulator define SPLC501 VOLT BOOSTER _ON 1 lt lt 2 enable voltage booster define SPLC501 CMD VOLT REG V5 0x20 sets the V5 voltage regulator internal resistor ratio define SPLC501 CMD ELECTRONIC VOLUME 0x81 sets the electronic volume register in order to control the V5 LCD drive voltage define SPLC501 CMD SET DRIVING MODE 0xD2 used to set the LCD driving mode define SPLC501 CMD RESET 0xE2 resets the controller A detailed description of the above mentioned commands can be found in the SPLC501C datasheet 1998 2012 HP InfoTech S R L Page 230 CodeVisionAVR void splc501_setcontrast unsigned char contrast Controls the LCD contrast Parameter contrast sets the value of the V5 LCD drive voltage allowed range is 0 63 The gled_splc501 h header file also contains the definition of the GLCDINIT_t type specific for the SPLC501C controller used as parameter for the gled_init function typedef struct
281. disabled and the project rebuild This will allow to reduce the size of the program and increase its 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 supported only the l input size modifier is supported e float width precision the following conversion type characters are supported c
282. displayed character y specifies the vertical coordinate of the left top corner of the displayed character c specifies the code of the character that must be displayed void glcd_putchar char c Displays a character using the current font at the current pixel plot position Parameter c specifies the code of the character that must be displayed void glcd_outtextxy GLCDX_t x GLCDY_t y char str Displays a NULL terminated literal char string located in RAM at the specified coordinates The new display position will be located at the end of the displayed text Parameters x specifies the horizontal coordinate of the left top corner of the first displayed character y specifies the vertical coordinate of the left top corner of the first displayed character str pointer to the literal char string void glcd_outtextxyf GLCDX_t x GLCDY_t y flash char str Displays a NULL terminated literal char string located in FLASH at the specified coordinates The new display position will be located at the end of the displayed text Parameters x specifies the horizontal coordinate of the left top corner of the first displayed character y specifies the vertical coordinate of the left top corner of the first displayed character str pointer to the literal char string 1998 2012 HP InfoTech S R L Page 200 CodeVisionAVR void glcd_outtextxye GLCDX_t x GLCDY_t y eeprom char str Displays a NULL terminated literal char string located
283. dow 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 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 its 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 sou
284. e Ba oO Yellow 22 El 4 m p c i Z e File Load 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 2012 HP InfoTech S R L Page 90 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
285. e GLCD_PUTTP copy a bitmap from memory to LCD overwriting previous display data using transparent mode when an image pixel with the current transparency color must be displayed the background color at the pixel coordinates will be used instead e GLCD_PUTXOR copy a bitmap from memory to LCD performing a XOR with previous display data e GLCD_PUTOR copy a bitmap from memory to LCD performing an OR with previous display data e GLCD_PUTNOT copy a bitmap from memory to LCD performing a bit negation e GLCD_PUTAND copy a bitmap from memory to LCD performing an AND with previous display data Return values image size or 0 if the coordinate values are not valid Notes e The GLCD_PUTXOR GLCD_PUTOR GLCD_PUTNOT GLCD_PUTAND modes are supported only for displays with 2 colors monochrome e The GLCD_PUTTP mode is supported only for displays with more than 2 colors unsigned long glcd_getimage GLCDX_t left GLCDY_t top GLCDX_t width GLCDY_t height unsigned char pimg Saves a rectangular display area to RAM as a bitmapped image Parameters left specifies the horizontal coordinate of the left top corner of the rectangular display area top specifies the vertical coordinate of the left top corner of the rectangular display area width specifies the horizontal size of the rectangular display area height specifies the vertical size of the rectangular display area pimg points to the byte array that will hold the image data Return values i
286. e Gradient Adjustment TC JSC WE AT rE WJ Checking the Voltage Reference Enabled check box enables the precision voltage reference The 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 2012 HP InfoTech S R L Page 410 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 clicking on the Coulomb Counter Ly node of the CodeWizardAVR selection tree amp CodeWizardAVR test cwp x File Help lac 1 Wite 2 Wire 120 LCD Bit Banged Project Information Chip Ports External IRQ Timers ADC Voltage Reference Coulomb Counter V Coulomb Counter Enabled Accumulate Current Conversion Time 125 7 ms v Regular Current Detection Mode Sampling Interval 266 ms v Accumulate Current Interrupt v Regular Current Interrupt V Instantaneous Current Interrupt Regular Charge Current R s 5 mohm 53 5 v md Regular Discharge Current Rs 5 mohm
287. e I O port allocation for the LCD Functions for displays with up to 2x40 characters XN Configure Project sdcard4 prj Files C Compiler Before Build After Build Code Generation Advanced Libraries Messages Globally define Paths 1 Wire MMC SD SD HC Card Alphanumeric LCD aled h V Enable Alpnanumeric LCD Support Connections LCD Module AYR RS PORTA RD PORTA EN PORTA D4 PORTA D5 PORTA DG PORTA D7 PORTA X Cancel Help The Enable Alhanumeric LCD Support check box activates the configuration specified for the alcd h library functions The connections between the LCD module and the AVR I O ports can be specified individually for each signal in the Connections group box 1998 2012 HP InfoTech S R L Page 63 CodeVisionAVR 2 3 5 8 Setting the Graphic LCD Library Options The Libraries tab is used for configuring specific driver libraries used by the compiler The Graphic LCD tab is used for configuring the I O port allocation for the Graphic LCD Functions P NN Configure Project MULTFILE PRJ Files C Compiler Before Build After Build Code Generation Advanced Libraries Messages Globally define Paths 12C MMC SD SD HC Card Alphanumeric LCD alcd h Graphic LCD gt Display Type 5ED1335 32
288. e 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 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 1998 2012 HP InfoTech S R L Page 343 CodeVisionAVR void rtc_get_alarm_date unsigned char chip unsigned char day 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 day unsigned char month this function sets the alarm date of the RTC PCF8583 example using the hardware TWI Functions for Master Mode Operation for non XMEGA Devices include the PCF8583 functions for TWI include lt pcf8583 twi h gt include the LCD Functions The connections must be speci
289. e Rate spin edit allows specifying the LCD frame rate The LCD Frame Rate Register LCDFRR is initialized based on the frequency of the clock source and the obtainable frame rate that is as close as possible to the one that was specified 1998 2012 HP InfoTech S R L Page 431 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 19 Setting the Alphanumeric LCD The I O port allocation for the LCD Functions for displays with up to 2x40 characters can be configured by clicking on the Alphanumeric LCD 3 node of the CodeWizardAVR selection tree UARTO UARTI 12c 1wie Bit Banged Project Information Chip Ports External IRQ Timers Twi 12C Alphanumeric LCD Enable Alphanumeric LCD Support Characters Line fa v Connections LCD Module AYR RS PORTD Bit 0 v RD PORTD Bit 1 v EN PORTD Bit 2 D4 EORTD aur Bi 4 D5 PORTD Bit 5 v D6 PORTD Bit 6 v D7 PORTD Bit Z v The Enable Alhanumeric LCD Support check box activates the configuration specified for the alcd h library functions The Characters Line list box allow
290. e 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 2 2 4 3 Jumping to a Symbol Definition or Declaration When the editor cursor is located on a symbol name and the Edit Go to Definition Declaration menu command is performed the F12 key or the toolbar button are pressed a jump will be performed to the symbol definition or declaration located in any of the project s source files After a jump to the definition or declaration was performed the Edit Go Back menu command or the toolbar button allow to return to the previous position in the edited 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 m
291. e based on VcomH VR step up factor of circuit the datasheet controls step up circ controls step up circ adjusts the from the cons the internal APO the VREGIOUT voltage in Circuit CS B 1 gt BGR the step up see BTO BT2 bits in frequency for the uit 1 frequency for the uit 2 amount of current tant current source op amplififier AP2 bits the the ude of the Vcom OUT ts voltage the amplit voltage based on VREG1OUT voltage EGLOUT vcomh 0 005 0 685 LCD frame frequency ude of the VcomH V default font after initialization X 1998 2012 HP InfoTech S R L Page 216 CodeVisionAVR positi unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned GLCDINI The following macros a Initialization ve gamma control registers bits char kp00 3 KP00 KP02 positive gamma micro adj char kp10 3 KP10 KP12 positive gamma micro adj char kp20 3 KP20 KP22 positive gamma micro adj char kp30 3 KP30 KP32 positive gamma micro adj char kp40 3 KP40 KP42 positive gamma micro adj char kp50 3 KP50 KP52 positive gamma micro adj char rp00 3
292. e enabled and initialized for operation in master mode int_level specifies the interrupt priority level used by the TWI module when operating in master mode 1998 2012 HP InfoTech S R L Page 281 CodeVisionAVR baud_reg specifies the value used for initializing the TWI module s MASTER BAUD register Usually the value of this parameter is calculated using the TWI_BAUD_REG macro void twi_master_int_handler TWI_MASTER_INFO_t twi represents the interrupt handler used for processing the interrupts generated by a TWI module operating in master mode Parameters twi represents a pointer to the TWI_MASTER_INFO_t data type variable that is used to hold all the required information for master operation of a particular TWI module associated with an I O port The TWI_MASTER_INFO_t data type variable must have been first initialized by a call to twi_master_init The twi_master_int_handler function must be called inside the interrupt service routine associated with the master interrupt of a particular TWI module bool twi_master_trans TWI_MASTER_INFO_t twi unsigned char slave_addr unsigned char tx_data unsigned char tx_count unsigned char rx_data unsigned char rx_count performs a TWI transaction using the master module Parameters twi represents a pointer to the TWI_MASTER_INFO_t data type variable that is used to hold all the required information for master operation of a particular TWI module associated with an I
293. e following code sequence will be replaced with int i 2 3 int i SUM 2 3 1998 2012 HP InfoTech S R L Page 100 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 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
294. e from the disk Press Ignore to ignore the extemal changes The changes will be used the next time you open the project The Reload button must be pressed Continuing the debugging process by repeating steps 3 to 6 as needed Finishing the debugging session using the Debug Stop Debugging menu or by pressing the 4 toolbar button Closing the debugger using the File Exit menu Before closing the debugger will ask for confirmation about saving the updated project solution z AVRStudio Save changes to the following items SSD1963 Demo atsin i l 5SD1963 Demo Cancel The Yes button must be pressed to confirm 1998 2012 HP InfoTech S R L Page 154 CodeVisionAVR The following commands can be used when debugging Ga e Debug Step Into F11 key or toolbar button to execute one instruction e Debug Step Over F10 key or G toolbar button to execute one instruction If the instruction contains a function pall the function is executed as well e Debug Step Out ShifttF11 keys or toolbar button to continue execution until the current function has completed e Debug Run To Cursor Ctrl F10 keys or toolbar button to continue execution until the current cursor position in the source file or disassembly view is reached e Debug Reset Shift F5 keys or Ea toolbar button to restart program execution from the beginning e DebugjRestart or l toolbar button to restart the debugger and reload t
295. e of display define SSD2119 FIRST OUT GATE2 1 Gate 2 on left side of display Initialization values for cl bits order define SSD2119 CL BITS RGB 0 Write color bits to display RAM in RGB order define SSD2119 CL BITS BGR 1 Write color bits to display RAM in BGR order TInitilization values for dc30 step up circuit cycle define SSD2119 STEPUP_FLINE24 0 Fline 24 define SSD2119 STEPUP_FLINE16 1 Fline 16 define SSD2119 STEPUP FLINE12 2 Fline 12 define SSD2119 STEPUP_FLINE8 3 Fline 8 define SSD2119 STEPUP_FLINE6 4 Fline 6 define SSD2119 STEPUP_FLINES 5 Fline 5 define SSD2119 STEPUP_FLINE4 6 Fline 4 define SSD2119 STEPUP FLINE3 7 Fline 3 define SSD2119 STEPUP_FLINE2 8 Fline 2 define SSD2119 STEPUP_FLINE1 9 Fline 1 define SSD2119 STEPUP_FOSC4 10 Fosc 4 Fosc 510kHz define SSD2119 STEPUP_FOSC6 11 Fosc 6 define SSD2119 STEPUP_FOSC8 12 Fosc 8 define SSD2119 STEPUP_FOSC10 13 Fosc 10 define SSD2119 STEPUP_FOSC12 14 Fosc 12 define SSD2119 STEPUP_FOSC16 15 Fosc 16 1998 2012 HP InfoTech S R L Page 251 CodeVisionAVR Initialization values for the VCIX2 voltage Power Control Reg 2 define define define define define define SS SS SS SS SS SS al a Initi bits define define define define define define define define define define define
296. e sfrb and sfrw keywords to access the AVR microcontroller s I O registers located in the 0 3Fh address range using the IN and OUT assembly instructions Example Define the SFRs sfrb PINA 0x19 8 bit access to the SFR sfrw TCNT1 0x2c 16 bit access to the SFR void main void unsigned char a a PINA Read PORTA input pins TCNT1 0x1111 Write to TCNT1L amp TCNTI1H registers The io h header file located in the INC subdirectory contains the definitions of the I O registers for all the chips supported by the compiler The definitions are selected based on the AVR chip setting specified by the Project Configure C Compiler Code Generation Chip option This header must be include d at the beginning of the C source file For XMEGA chips the following syntax must be used for accessing I O registers I O register definitions for the XMEGA128Al1 chip include lt io h gt void main void unsigned char a Set all PORTA pins as inputs PORTA DIR 0x00 Read PORTA input pins a PORTA IN Set all PORTB pins as outputs PORTB DIR OxFF Write data to PORTB outputs PORTB OUT 0x11 Set PORTB pin 2 to 1 PORTB OUTSET 1 lt lt 2 Set PORTB pin 4 to 0 PORTB OUTCLR 1 lt lt 4 Toggle PORTB pin 0 PORTB OUTTGL 1 lt lt 0 1998 2012 HP InfoTech S R L Page 132 CodeVisionAVR The XMEGA I
297. e 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 the character in str1 where str2 begins If there is no match returns a NULL pointer char strtok char str1 char flash str2 scans the string str1 located in 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 1998 2012 HP InfoTech S R L Page 174 CodeVisionAVR 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 void memcpy voi
298. e using the hardware TWI Functions for Master Mode Operation for XMEGA Devices The chip is connected to the TWI of PORTD TWID of an ATxmega128A1 include the DS1307 functions for TWI include lt ds1307 twi h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line structure that holds information used by the TWID master for performing a TWI bus transaction TWI_ MASTER INFO t twid_master interrupt service routine for TWID master interrupt TWID_TWIM vect void twid master_isr void twi_master int handler amp twid_ master TWI clock rate Hz define TWI_CLK_RATE 1998 2012 HP InfoTech S R L Page 354 CodeVisionAVR void main void unsigned char hour min sec week day day month year initialize the LCD 2 rows by 16 columns led_init 16 general TWID initialization no external driver interface no SDA hold time twi_init amp TWID false false enable and initialize the TWID master interrupt level low twi master init amp twid_master amp TWID TWI_ MASTER INTLVL_LO gc TWI BAUD REG MCU CLOCK FREQUENCY TWI_CLK RAT
299. ebugging of the program Once debugging was finished this option can be also set to Optimize for Size The debugger is invoked using the Tools Debugger menu command or the toolbar button In order to be able to do this the debugger version and it s installation path must be first specified using the Settings Debugger menu 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 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
300. ecify the External RAM Size in case the microcontroller have external SRAM memory connected 1998 2012 HP InfoTech S R L Page 48 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 PRJ Files C Compiler Before Build After Build Code Generation Libraries Messages Globally define Paths f RAM Chip ATIAK z f Data Stack Size 1024 bytes Clock 8 000000 4 MH a 24 Heap Size 0 bytes Memory Model Program RAM Size 10 Kwords Small Z Data RAM Size 16288 bytes Optimize for Size Code Generation Optimization Level Bit Variables Size Maximal Promote char to int char is unsigned V 8 bit enums V Enhanced Par Passing J Smart Register Allocation V Automatic Global Register Allocation s printf Features F Store Global Constants in FLASH Memory int width Use an External Startup Initialization File s scanf Features V Clear Global Variables at Program Startup E Stack End Markers File Output Format s COF ROMHEXEEP int width Preprocessor E Create Preprocessor Output Files Z Include 1 0 Re
301. eclaring the structure variables used to hold the information required by each TWI module when operating in master mode These structure variables are updated automatically by the TWI functions during bus transactions The result of a TWI master transaction is returned in the result member of the TWI_LMASTER_INFO_t structure data type which may take the values defined by the following macros from twix h define TWIM define TWIM ES OK 1 define TWIM ES BUFFER OVERFLOW 2 RES UNKNOWN 0 RI RI define TWIM RES ARBITRATION LOST 3 RI RI R define TWIM RES BUS ERROR 4 define TWIM RES NACK RECEIVED 5 define TWIM RES FAIL 6 The macro TWI_BAUD_REG SYS_CLK TWI _CLK_RATE is used for calculating the value of the TWI MASTER BAUD register for the desired TWI clock rate TWI_CLK_RATE expressed in Hz based on the System Clock SYS_CLK value expressed in Hz The following functions are used for operating the TWI in master mode void twi_master_init TWI_MASTER_INFO_t twi TWI_t module TWI_MASTER_INTLVL_t int_level unsigned char baud_reg enables and initializes a TWI module for operating in master mode Parameters twi represents a pointer to the TWI_MASTER_INFO_t data type variable that will be used to hold all the required information for operating in master mode for a particular TWI module module represents a pointer to the TWI module associated with an XMEGA I O port that will b
302. ect Name Version Date Author Company Comments You can specify the Project Name Date Author Company and Comments 1998 2012 HP InfoTech S R L Page 492 CodeVisionAVR 7 Licensing System 7 1 Activating the License The CodeVisionAVR license is locked to the hardware of the PC on which it is installed If the license is not yet activated the following dialog will be displayed at program startup i Internet License Activation f Your license requires to be activated using the Internet connection Please enter the License ID received from HP InfoTech below License ID 1234567 8l Paste from Clipboard You must enter the License ID that was supplied by HP InfoTech when the license was initially purchased The License ID can be also pasted from the clipboard by pressing the Paste from Clipboard button After that the license can be activated by pressing the Activate button CodeVisionAVR will contact the Activation Server using the Internet After several seconds upon successful activation the following confirmation message will be displayed n Information i Your license was successfully activated CodeVisionAVR will be restarted please wait Important Note Always use the Help Transfer Deactivate License menu command before performing hardware changes mainboard BIOS CPU or HDD to your PC formating your HDD or re installing Windows After pressing t
303. ect your program from copying you must select the corresponding option using the FLASH Lock Bits radio box If you wish to check the chip s signature before programming you must use the Check Signature option To speed up the programming process you can uncheck the Check Erasure check box In this case there will be no verification of the correctness of the FLASH erasure The Preserve EEPROM checkbox allows preserving the contents of the EEPROM during chip erasure To speed up the programming process you can uncheck the Verify check box In this case there will be no verification of the correctness of the FLASH and EEPROM programming Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2012 HP InfoTech S R L Page 67 CodeVisionAVR 2 3 5 11 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 7 Hee 1998 2012 HP InfoTech S R L Page 68 CodeVisionAVR Using the Program Settings button you can modify the e Program Directory and File Name e Program Comma
304. ection of cursor movement to right define S1D13700 POWER SAVE 0X53 Enter standby mode define S1D13700 DISP_ON OFF 0X58 Enable disable display and display flashing define S 1D13700 HDOT SCR OX5A Set horizontal scroll position define S1D13700 OVLAY OX5B Set display overlay format define S1D13700 CGRAM ADDR OX5C Set start address of character generator RAM define S1D13700 CSRFORM OX5D Set cursor type define S1D13700 GRAYSCALE 0x60 Set grayscale depth A detailed description of the above mentioned commands can be found in the S1D13700 datasheet void s1d_wrdata unsigned char data Writes a data byte to the 1D13700 controller Parameter data byte to be sent to the controller unsigned char s1d_rddata void Reads a data byte from the 1D13700 controller Notes e The gled_s1d13700 h header file is automatically included when the main gled h header file is included Therefore there is no need to explicitly include gled_s1d13700 h e The EXAMPLES Graphic LCD S1D13700 directory contains fully functional code samples that may be used as references for S1D13700 initialization and usage 1998 2012 HP InfoTech S R L Page 224 CodeVisionAVR 4 12 4 Graphic LCD Functions Specific to the SED1335 Controller In order to take full advantage of the SED1335 controller s features the following specific functions declared
305. ects developed with CodeVisionAVR prior to V2 04 7 the 1 Wire functions can also be configured as outlined in the example below However in this case the Enable 1 Wire Bus Interface Support option must be disabled in the Project Configure C Compiler Libraries 1 Wire menu 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 include lt lwire h gt This method is not recommended for new projects and it also does not support the XMEGA chips 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 1998 2012 HP InfoTech S R L Page 271 CodeVisionAVR unsigned char w1_search unsigned char cmd void p this function returns the number of devices connected to the 1 Wire
306. ed DAC Low Power Mode Internal Output Routed to the ADC and Analog Compator MUX es Operating Mode Single Channel Ch0 v Channel 0 External Output Enabled V Channel 0 Triggered by the Event System DAC Triggered by Event System Channel v DAC Voltage Reference Internal 1 00 v Left Adjust Value DAC Conversion Interval 1 000 us aa e DAC Enabled allows the activation of the selected DAC e DAC Low Power Mode allows the operation of the DAC in low power consumption mode e Internal Output Routed to the ADC and Analog Comparator MUX es allows to internally connect the DAC s output to the corresponding ADC and or Analog Comparator multiplexers e Operating Mode allows to select one of the two DAC operating modes Single Channel Ch0 or Dual Channel Ch0 and Ch1 1998 2012 HP InfoTech S R L Page 486 CodeVisionAVR In Single Channel operating mode the DAC output is directly connected to the Channel 0 output without using a sample and hold circuit This output can be activated using the Channel 0 External Output Enabled check box A Digital to Analog conversion can be triggered by e writing a new value to the CHODATAL and CHODATAH registers e the Event System if the Channel 0 Triggered by the Event System option is enabled In this later case the DAC Triggered by Event System Channel option allows to select the channel on which an event will trigger a conversion The DAC Voltage referen
307. ed 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 2012 HP InfoTech S R L Page 70 CodeVisionAVR 2 3 6 2 Compiling the Project To compile the Project you must use the Project Compile menu command press the F9 key or the P 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 amp 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 bytefs 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
308. ed using the Software Bit Banged I2C Bus Functions include the LM75 functions The I2C bus connections and bit rate must be specified in the Project Configure C Compiler Libraries I2C menu include lt lm75 h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu inclu inc inclu inc inclu inc inclu de lt alcd h gt lude the proto de lt stdio h gt lude the proto de lt stdlib h gt lude the proto de lt delay h gt type for sprintf type for abs types for the delay functions char display buffer 33 void main void int to ini ini i2c_in ini ils it thyst 20 C tos 25 1m75_init 0 20 25 0 ini tialize the LCD 2 rows by 16 columns led_init 16 tialize the I C bus tialize the LM75 sensor with address 0 C tialize the LM75 sensor with address 1 thyst 30 C tos 35 1m75_init 1 30 35 0 PG 7 temperature display loop while 1 read the temperature of sensor 0 10 C tO lm75 temperature 10 0 300ms delay delay ms 300 X read the temperature of sensor 1 10 C tl lm75_ temperature 10 1 300ms delay delay ms 300 1998 2012 HP InfoTech S R L Page 379 CodeVisionAVR prepare the displayed temperatu
309. eeeaeeeeesiaeeeeeeeneeeeseaes 181 4 11 Alphanumeric LCD Functions cccccccececececccee cece ee ee seca aeae cece esses caaaaaeeeeeeeeesesenceeeeeeeeteess 182 4 11 1 LCD Functions for displays with up to 2x40 characters cececceceeceeeeeeeeeetetneeeeees 182 4 11 2 LCD Functions for displays with 4x40 characters 00 cccceececeeeceeeeeeeeeeeeneeeseeneeeeeeeenaees 185 4 11 3 LCD Functions for displays connected in 8 bit memory mapped mode 08 187 4 12 Graphic LCD Functions cis scceicciccedecisasceccetececcessaccucdatsacshcasbasnadacheesndsassanadahecenessbameaadeeteceadepasanes 190 4 12 1 Graphic LCD Functions Specific to the ILI9325 Controller ccceceeetseeseeeereeeees 214 4 12 2 Graphic LCD Functions Specific to the PCD8544 Controller cceceeeestseeeeeeees 222 4 12 3 Graphic LCD Functions Specific to the S1D13700 Conitroller 0 ccceceeseceeeeeeees 224 4 12 4 Graphic LCD Functions Specific to the SED1335 Controller cc eeeeeeeeeeereeeeneees 225 4 12 5 Graphic LCD Functions Specific to the SED1530 Controller cceeeesseeeceeeeeeees 227 4 12 6 Graphic LCD Functions Specific to the SPLC501C Controller 0 cccceeeseeeeeeees 230 4 12 7 Graphic LCD Functions Specific to the SSD1289 Controller a se 233 4 12 8 Graphic LCD Functions Specific to the SSD1963 Controller cceeseeeeteeteeeees 240 4 12 9 Graphi
310. 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 2012 HP InfoTech S R L Page 120 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 structure stored in EEPROM eeprom struct type struct3 1998 2012 HP InfoTech S R L Page 121 CodeVisionAVR 3 9 Type Conversions In an expression if the two operands of a binary operator are of different types then the compiler will con
311. efault untitled cwx The File Open menu command or the toolbar button allow loading an existing CodeWizardAVR project fone E Lookin i bin T Name Date modif Type ri y Recent Places _ test cwx test v CodeWizardAVRX project files cwx v 1998 2012 HP InfoTech S R L Page 438 CodeVisionAVR The File Save menu command or the 5 toolbar button allow saving the currently opened CodeWizardAVR project The File Save As menu command or the et toolbar button allow saving the currently opened CodeWizardAVR project under a new name SK Save C cvavr2 bin untitled cwx As Savein work pP iv Name Date modified Type 7 This folder is empty Recent Places 4 File name test Save as type CodeWizardAVRX project files cwx By selecting the Program Generate 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 Program 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 CWX file and return to the CodeVisionAVR IDE Eventual peripheral c
312. efine T6963 SET MODE OR 0x80 define T6963 SET MODE XOR 0x81 define T6963 SET MODE AND 0x83 aE gt I define T6963 SET MODE TXT ATTR 0x84 Set text attributes define T6963 SET MODE INTCG 0x80 Use internal character generator define T6963 SET MODE EXTCG 0x88 Use external character generator define T6963 DISPLAY OFF 0x90 Display off define T6963 CURSORON BLINKOFF 0x92 Cusror on blink off define T6963 CURSORON BLINKON 0x93 Cusror on blink on define T6963 TXTON GFXOFF 0x94 Text on graphics off define T6963 TXTOFF_GFXON 0x98 Text off graphics on define T6963 TXTON _GFXON 0x9C Text on graphics on define T6963 CURSOR 1LINE 0xA0O Selects 1 line cursor define T6963 CURSOR 2LINE 0xAl Selects 2 lines cursor define T6963 CURSOR _3LINE 0xA2 Selects 3 lines cursor define T6963 CURSOR ALINE 0xA3 Selects 4 lines cursor define T6963 CURSOR_5LINE 0xA4 Selects 5 lines cursor define T6963 CURSOR GLINE 0xA5 Selects 6 lines cursor define T6963 CURSOR_7LINE 0xA6 Selects 7 lines cursor define T6963 CURSOR 8LINE 0xA7 Selects 8 lines cursor define T6963 DATA AUTO WR 0xBO Data auto write define T6963 DATA AUTO RD 0xB1 Data auto read define T6963 AUTO RESET 0xB2 Use to exit from auto mode 1998 2012 HP InfoTech S R L
313. el llaa weno s aa 1998 2012 HP InfoTech S R L Page 23 CodeVisionAVR 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 SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usart prj File Edit Search View Project Tools Settings Hel J g p BeS HReAaACSS MRAS x Ef v File A es 48 oeAae ogol iN S j 7 i E f RE Code Information v 7 E Ap hl E Z Z o ojj E v View 9 z el a as Notes usartc EJ V TE Search f f HG Macros 1 z gt Typedefs 2 Sample progr Project ATxmegei 4p Global Static Variables Sse 2 STK600 Tools eed with F Functions 4 STK600 RC1 00 J 0 mainfvoid 5 V settings 6 The STK600 pi be set ir i in the Tools v Heip p 8 9 Make sure that the VTARGET and VREF 10 using AVR Studio 11 The VITARGET LED on the STK600 board 12 Make the following c cti ti ff Function Call Tree eX Ee ee ee EO All the workspace layout will be automatically saved at program exit and restored back on the next launch 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 W close the current editor tabbed window The current editor tabbed window can
314. enerates 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 2012 HP InfoTech S R L Page 146 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 a 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 function prototypes int sum int a int b int mul int a int b pragma used this pragma directive will tell the compiler to compile link the functions from the mylib lib library pragma library mylib lib Save the file under a new name in the INC directory using the File Save As menu command for example mylib h SK Save C cvavr work untitled
315. eprom 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 2012 HP InfoTech S R L Page 111 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 initialization 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 var
316. erature of two LM75 sensors with addresses 0 and 1 The chips are accessed using the TWI Functions for Master Mode Operation for non XMEGA Devices include the include lt lm75 __ include the LM75 functions for TWI twi h gt LCD Functions The connections must be specified in the Project Conf include lt stdio include lt delay char display bu void main void ant tOst igure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf h gt include the prototype for abs include lt stdlib h gt include the prototypes for the delay functions ah ffer 33 initialize the LCD 2 rows by 16 columns led_init 16 initialize the TWI in master mode with 100 kHz bit rate twi_master init 100 enable interrupts so that TWI can be used asm sei initialize the LM75 sensor with address 0 thyst 20 C tos 25 C 1m75_ init 0 20 25 0 initialize the LM75 sensor with address 1 thyst 30 C tos 35 C Im75_init 1 30 35 0 temperature display loop while 1 read the temperature of sensor 0 10 C tO lm75_ temperature 10 0 300ms delay delay ms 300 read the temperature of sensor 1 10 C tl lm75_ temperature 10 1 300ms delay delay ms 300 1998 2012 HP InfoTech S
317. eric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line void main void unsigned char hour min sec week day day month year initialize the LCD 2 rows by 16 columns led_init 16 initialize the bit banged I2C functions i2e init initialize the RTC square wave output is disabled SQW OUT has logic state 0 rtc_init 0 0 0 rtc_set_time 12 0 0 set time 12 00 00 rtc_set_date 2 1 2 11 set date Tuesday 1 02 2011 display the time and date continuously while 1 read the time from the RTC rtc_get_time amp hour amp min amp Sec read the date from the RTC rtc_get_date amp week day day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec lcd_clear lcd _ puts display buffer display the date on the LCD sprintf display _ buffer Date 2d 02d d day month 2000 year lcd _ puts display_buffer delay ms 500 0 5 second delay 1998 2012 HP InfoTech S R L Page 356 CodeVisionAVR 4 22 5 Maxim Dallas Semiconductor DS1621 Thermometer Thermostat Functions These functions are intended for easy interfacing between C program
318. erification 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 chip s FLASH respectively EEPROM you must use the Read FLASH respectively ReadJEEPROM 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 1998 2012 HP InfoTech S R L Page 85 CodeVisionAVR 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
319. ers 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 2012 HP InfoTech S R L Page 138 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 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 f
320. ersion result is compared with the value of the CMPL and CMPH registers an interrupt being generated if the specified condition is met 1998 2012 HP InfoTech S R L Page 480 CodeVisionAVR In the Free Running conversion start mode the ADC will continuously sweep the channels specified by the Sweeped Channel s list box ADCA Settings 7 ADC Enabled ADC Clock Frequency ADC Resolution ADC Conversion Mode ADC Reference Conversion Start Mode Sweeped Channel s 125 000 kHz x 12 Bits x Internal 1 00 V Temperature Measurement Reference Enabled Free Running Channels Sweeped Continuously Y Dale ADC Input Connected to GND for Offset Compensation ADC pin v ADC Compare Register 0 h Channel 0 Channel 1 Channel 2 Channel 3 Input Mode Internal positive input signal z Positive Input Temp Reference v Negative Input GND bA Interrupt Low Level d Interrupt Mode Conversion Complete In the above example figure the ADC will continuously sweep the inputs of channels 0 1 2 and 3 1998 2012 HP InfoTech S R L Page 481 CodeVisionAVR In the Channels Triggered by the Event System conversion start mode each Event Channel will trigger the analog to digital conversion for the ADC channels specified by the Trigger s Channels s list box
321. esecceeedeccteeeesteneeseeceeneeseeneeseecceeeeeseneeesedeceneeseeeceeeeeas 435 5 23 Specifying the Project Information cccceccceeee ee eeeeee eee Kean ANNAA KARAER RAEAN 436 6 CodeWizardAVR Automatic Program Generator for the XMEGA Chips ccsssseeeeesseeeeeees 437 6 1 Setting the General Chip Options ccccccecceeceeeeecece cece ee eeeeeeeaeaeceeeeesedneaneeeeeeeeseesnnieeeeeeeess 442 6 2 Setting the System CIOCKS 0 ccieeieee ete eee erent rene ee tieee ee eeee ee teeeeetiieeeeneneeeentaa 444 1998 2012 HP InfoTech S R L Page 8 CodeVisionAVR 6 3 Setting the External Bus Interface cccccccssssssssssssussssssssssssssssssesssssssseesssussnsssnseseessesnsen 449 6 4 Setting the Event Systa M tecaiit nt o ciel nied indeed 453 6 5 Setting the Input Output Ports ccc ccecsseceeecseeeeeeceneeeeesseeeeeeseeeeeecaeeeeesseeeesssieeeesssieeeeneea 454 6 6 Setting the Virtual POS cscri ie een ie ene see 456 6 7 Setting the Timers COUNHELS 0 eee cere etree ee tee etter erie ee eerie ee ee eee ee teeeee tenses sieeeetea 457 6 8 setting the Watchdog TIME serraria niren s e a AAE OAA eave vec 464 6 9 Setting the 16 Bit Real Time Counter esssesssrrereernansssnnnseennaansnnansennaanannnatennnaanannanennaananna ae 465 6 10 Setting the 32 Bit Real Time Counter and Battery Backup System 467 6 11 Setting th USART S aiicinnesi isinin a a eerie a aa 469 6 12 Setting the Serial Peri
322. etcolor void Returns the display s current foreground color GLCDCOL_t gilcd_getbkcolor void Returns the display s current background color GLCDCOL_t glcd_gettpcolor void Returns the current transparency color for image displaying in transparent mode When an image pixel with this color must be displayed in transparent mode GLCD_PUTTP the background color at the pixel coordinates will be used instead Note This function is available only for displays with more than 2 colors 1998 2012 HP InfoTech S R L Page 196 CodeVisionAVR GLCDCOL_t glcd_getmaxcolor void Returns the highest color value for a pixel in ON state GLCDX_t glcd_getmaxx void Returns the maximum X horizontal coordinate value GLCDY_t glcd_getmaxy void Returns the maximum Y horizontal coordinate value void glcd_clear void Clears the LCD by setting it s color to the current background color void glcd_putpixel GLCDX_t x GLCDY_t y GLCDCOL_t color Sets the color of the pixel at specified coordinates Note The current pixel plot coordinates are not affected by this function Parameters x specifies the horizontal pixel coordinate y specifies the vertical pixel coordinate color specifies the color that must be assigned to the pixel void glcd_setpixel GLCDX_t x GLCDY_t y Sets the color of the pixel at specified coordinates to the current foreground color Note The current pixel plot position coordinates are not affected by
323. eters e Program Working Directory 1998 2012 HP InfoTech S R L Page 65 CodeVisionAVR 2 3 5 10 Transferring the Compiled Program to the AVR Chip after Build This option is available if you select the After Build tab 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 Z Merge data from a ROM File for FLASH Programming ROM File Path cavrprojects bootloader bootloader rom 3 Chip Programming Options SCK Freq 230400 Hz 4 Program Fuse Bit s FLASH Lock Bits F CKSELO 0 7 No Protection CKSEL1 0 ne CKSEL2 0 Programming disabled O CKSEL3 0 Programming and Verification disabled z tae CKOUT 0 Boot Lock Bit 0 Boot Lock Bit 1 CKDIV8 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 0B12 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 aaa 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 progr
324. etting the Alphanumeric LCD The I O port allocation for the LCD Functions for displays with up to 2x40 characters can be configured by clicking on the Alphanumeric LCD node of the CodeWizardAVR selection tree Alphanumeric LCD Settings v Enable Alphanumeric LCD Support Characters Line a oy z Connections LCD Module AVR RS RD EN D4 D5 D6 D PORTA Bit 0 PORTA Bit 1 PORTA Bit 2 PORTA Bit 4 PORTA Bit 5 PORTA Bit 6 PORTA Bit 7 The Enable Alhanumeric LCD Support check box activates the configuration specified for the alcd h library functions The Characters Line list box allows to specify the number of characters per line supported by the LCD module The connections between the LCD module and the AVR I O ports can be specified individually for each signal in the Connections group box 1998 2012 HP InfoTech S R L Page 490 CodeVisionAVR 6 18 Setting the Graphic LCD The I O port allocation for the Graphic LCD Functions can be configured by clicking on the Graphic LCD node of the CodeWizardAVR selection tree Graphic LCD Settings Display Type ED1335 320x240 CS Active low v Use Image Storage in External Memory Use Internal Font Only Connections LCD Module AYR XMEGA DBO PORTA Bit 0 v DBI PORTA Bit in DB2 PORTA Bit
325. eturned in the result member of the TWI_SLAVE_INFO_t structure data type which may take the values defined by the following macros from twix h define TWIS define TWIS_ define TWIS ES ADDR MATCH 2 define TWIS RES BUFFER OVERFLOW 3 RES UNKNOWN 0 RI RI RI define TWIS RES TRANSMIT COLLISION 4 RI RI R ES OK 1 define TWIS RES BUS ERROR 5 define TWIS RES FAIL 6 define TWIS RES HALT 7 The following functions are used for operating the TWI in slave mode void twi_slave_init TWI_SLAVE_INFO_t twi TWI_t module TWI_SLAVE_INTLVL_t int_level bool match_any_addr unsigned char addr unsigned char addr_mask_reg unsigned char rx_buffer unsigned char rx_buffer_size unsigned char tx_buffer void twi_slave_trans void enables and initializes the TWI module for operating in slave mode 1998 2012 HP InfoTech S R L Page 285 CodeVisionAVR Parameters twi represents a pointer to the TWI_SLAVE_INFO_t data type variable that will be used to hold all the required information for operating in slave mode for a particular TWI module module represents a pointer to the TWI module associated with an XMEGA I O port that will be enabled and initialized for operation in slave mode int_level specifies the interrupt priority level used by the TWI module when operating in slave mode match_any_addr enables the TWI slave to respond to any slave address supplied by the master when start
326. everse x define SPLC501 DEFAULT REVX SPLC501 REVX_ NORM default value for rev1l32_x0 effective only when reverse x 1 SPLC501 REVX_REV define SPLC501 DEFAULT REV132 X0 SPLC501_REV132_XONC default value for reverse y define SPLC501 DEFAULT REVY SPLC501 REVY NORM default V5 voltage regulator internal resistor ratio define SPLC501 DEFAULT VOLT REG V5 6 al S 1 S The detailed description of the above mentioned initialization parameters can be found in the SPLC501C datasheet Notes e The glcd_splc501 h header file is automatically included when the main gled h header file is included Therefore there is no need to explicitly include glcd_splc501 h e The EXAMPLES Graphic LCD SPLC501C directory contains fully functional code samples that may be used as references for SPLC501C initialization and usage 1998 2012 HP InfoTech S R L Page 232 CodeVisionAVR 4 12 7 Graphic LCD Functions Specific to the SSD1289 Controller The SSD1289 library functions supplied with the CodeVisionAVR Advanced license operate the controller in 16 bit interface mode In order to take full advantage of the SSD1289 controller s features the following specific functions declared in the glcd_ssd1289 h header file were implemented void ssd1289_wrcmd unsigned char cmd Writes a command to the SSD1289 controller used to access a specific command register Parameter cmd command register index
327. 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 4 19 please consult its Help system 1998 2012 HP InfoTech S R L Page 150 CodeVisionAVR 3 22 Using the AVR Studio 5 1 and Atmel Studio 6 Debuggers CodeVisionAVR is designed to work in conjunction with the AVR Studio 5 1 and Atmel Studio 6 or later debuggers 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 Important Note It is highly reco
328. f day month and year void rtc_set_date unsigned char day unsigned char month unsigned year this function sets the current date of the RTC void rtc_alarm_off void this function disables the RTC alarm function 1998 2012 HP InfoTech S R L Page 336 CodeVisionAVR void rtc_alarm_on void this function enables the RTC alarm function void rtc_get_alarm unsigned char day unsigned char hour unsigned char min this function returns the alarm time and date of the RTC The day hour and min pointers must point to the variables that must receive the values of day hour and minutes void rtc_set_alarm unsigned char day unsigned char hour unsigned char min this function sets the alarm time and date of the RTC The day hour and min parameters represent the values of day hours and minutes If day 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 PCF8563 example using the hardware TWI Functions for Master Mode Operation for non XMEGA Devices include the PCF8563 functions for TWI include lt pcf8563 twi h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype f
329. fied in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line void main void unsigned char hour min sec hsec day month unsigned int year initialize the LCD 2 rows by 16 columns lcd_init 16 initialize the TWI in master mode with 100 kHz bit rate twi_master init 100 enable interrupts so that TWI can be used fasm sei initialize the RTC 0 no dated alarm rtc_init 0 0 rtc_set_time 0 12 0 0 0 set time 12 00 00 00 on RTC 0 rtc_set_date 0 1 2 2011 set date 1 02 2011 on RTC 0 1998 2012 HP InfoTech S R L Page 344 CodeVisionAVR display the time and date continuously while 1 read the time from the RTC 0 rtc_get_ time 0 amp hour min amp sec amp hsec read the date from the RTC 0 rtc_get_ date 0 amp day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec lcd_clear lcd puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month year lcd puts display buffer delay _ms 500 0 5 second delay PCF8583 example using
330. figure 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 code here The pragma vector preprocessor directive and the __interrupt keyword are used for compatibility with other C compilers for the Atmel AVR 1998 2012 HP InfoTech S R L Page 130 CodeVisionAVR 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 Example force the next function to be linked even if it s not used pragma keep 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 2012 HP InfoTech S R L Page 131 CodeVisionAVR 3 14 Accessing the I O Registers The compiler uses th
331. fine define define define define define define IL define I define I HHHHHHH ter definitions LI9325_ CMD OSC 0x00 Oscillator register LI9325 CMD DRIVER OUT 0x01 Driver output control LI9325 CMD DRIVING WAVEFORM 0x02 LCD driving waveform control LI9325 CMD ENTRY MODE 0x03 Entry mode control LI9325 RESIZE CONTROL 0x04 Resizing control register LI9325 CMD DISPLAY CONTROL1 0x07 Display control register 1 LI9325 CMD DISPLAY CONTROL2 0x08 Display control register 2 LI9325 CMD DISPLAY CONTROL3 0x09 Display control register 3 LI9325 CMD DISPLAY CONTROL4 0x0a Display control register 4 LI9325 CMD RGB IF CONTROL1 Ox0c RGB display interface control 1 LI9325 FRAME MARKER POS 0x0d Frame marker position LI9325 CMD RGB IF CONTROL2 Ox0f RGB display interface control Zs E7 LI9325 CMD POWER_CONTROL1 0x10 Power control 1 register LI9325 CMD POWER _CONTROL2 0x11 Power control 2 register LI9325 CMD POWER _CONTROL3 0x12 Power control 3 register LI9325 CMD POWER_CONTROL4 0x13 Power control 4 register LI9325 CMD GDDRAMX 0x20 Set GRAM X address counter register LI9325 CMD GDDRAMY 0x21 Set GRAM Y address counter register LI9325 CMD _GDDRAM DATA 0x22 GRAM read write data register LI9325 CMD POWER _CONTROL7 0x29 Power control 7 re
332. fine ST7565 REV132 XONC 0 driver 132 when ADC 1 display driver reversed ADC 1 lization ST7565 REVX_REV pixel with x 0 is not connected to column define ST7565 REV132 XOCON 1 pixel with x 0 is connected to column driver 132 when ADC 1 values used for reverse y initi define ST7565 REVY NORM 0 sets dire define ST7565 REVY REV 1 sets dire values used for driving mode ini define define define define ST7565 DRIVING MODE1 0 ST7565 DRIVING MODE2 1 ST7565 DRIVING MODE3 2 ST7565 DRIVING MODE4 3 alization the vertical COM output scan ction 0 gt 63 the vertical COM output scan ction 63 gt 0 tialization driving mode 1 driving mode 2 driving mode 3 driving mode 4 1998 2012 HP InfoTech S R L Page 258 CodeVisionAVR defaul initialization values default value for LCD bias define ST7565_ DEFAULT LCD BIAS ST7565 LCD BIAS LOW default value for reverse x define ST7565__ EFAULT REVX ST7565_REVX NORM default value for rev1l32_x0 e D e effective only when reverse x 1 ST7565 REVX_ REV D e D define ST7565_ EFAULT REV132 X0 ST7565 REV132 XONC default value for reverse y define ST7565_ EFAULT REVY ST7565_REVY NORM default V5 voltage regulator internal resistor ratio define ST7565 DEFAULT VOLT REG V5 6 default LCD drivi
333. finished transmitting data return false no more bytes to receive signal to the TWI master that the TWI slave is ready to accept more data as long as there is space in the receive buffer return twi_rx index lt sizeof rx_buffer unsigned char slave tx _handler bool tx_complete unsigned char i if tx_complete false transmission from slave to master is about to start copy the text to transmit to the TWI master in the transmission buffer strcpyf tx _buffer Data packet received OK n r ee of bytes to transmit from the TWI slave to the TWI master return strlen tx buffer transmission from slave to master has already started no more bytes to send in this transaction if received_ok no TWI receive error display the received data on the LCD lced_clear for i 0 i lt twi_rx index it lcd putchar rx buffer i return 0 void main void initialize the LCD led init 16 lcd_clear 1998 2012 HP InfoTech S R L Page 278 CodeVisionAVR initialize the TWI slave twi_slave init false TWI SLAVE ADDR rx buffer sizeof rx buffer tx buffer slave rx handler slave tx handler T lcd putsf TWI slave OK delay ms 2000 enable interrupts to start TWI communication asm sei all processing is performed by TWI interrupts inside twi lib while 1 1998 2012 HP InfoTech S R L Page 27
334. for non XMEGA devices The ptwim parameter must point to a TWI_LMASTER_INFO _t structure variable that is used to hold the information required by the TWI module when operating in master mode The pcf8563_twi_init function must be called before rtc_init Refer to the supplied example at the end of this chapter for more details 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 PCF8563 register at address unsigned char rtc_get_time unsigned char hour unsigned char min unsigned char sec this function returns the current time measured by the RTC The hour min and sec pointers must point to the variables that must receive the values of hour minutes and seconds The function return the value 1 if the read values are correct If the function returns 0 then the chip supply voltage has dropped below the Vlow value and the time values are incorrect 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 day unsigned char month unsigned year this function returns the current date measured by the RTC The day month and year pointers must point to the variables that must receive the values o
335. for the string display_eeprom Hello world while 1 1998 2012 HP InfoTech S R L Page 108 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 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
336. foreground respectively background text colors for the selected Language Element to the default ones specified in the Text Default Text Color respectively Text Default Background Color settings 1998 2012 HP InfoTech S R L Page 93 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 7 Text Color BB Window Text X 11 p 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 g while Number 4 19 peeprort t pflasht 20 Number 21 22 lr x 4 m p X Cancel
337. formed 1998 2012 HP InfoTech S R L Page 381 CodeVisionAVR The File New menu command or the 6 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 SK Open Project Ee Look in d bin T E F a flv I Name Date modified Type P test 17 Apr 08 15 01 CodeWizardAVR project file A Recent Places Desktop aj Pavel C ae Computer A Network 4 m p File name test X Open Files of type CodeWizardAVR project files cwp X Cancel 1998 2012 HP InfoTech S R L Page 382 CodeVisionAVR The File Save menu command or the 5 toolbar button allow saving the currently opened CodeWizardAVR project _ The File Save As menu command or the toolbar button allow saving the currently opened CodeWizardAVR project under a new name S Save C cvavr bin untitled cwp As rx Savein work 9 8 Pe E z Name Date modif Type Size wA This folder is empty Recent Places Pavel A E Computer A lt Network File name test ba Save as type CodeWizardAVR project files cwp X Cancel By selecting the Program Generate 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 c
338. fter the selection was made the Finish button must be pressed The new debugger project solution will be then created Based on the information present in the COFF object file the debugger will copy some of the C source files from the directory where the CodeVisionAVR project is located to the path specified in the Location edit box of the Open Object File For Debugging dialog window The list of these files is available in the Solution Explorer window Solution Explorer ax e ad Solution SSD1963 Demo 1 project s SSD1963 Demo Sa Output Files c arial_bold c c ariall4 c c bargraph c c courier_bold14 c c courier7x14 c ic image c c la_bambal7 c c main c ic meter c VA View amp VA Outline a Solution Ex 1998 2012 HP InfoTech S R L Page 152 CodeVisionAVR Important Note During a debugging session the debugger will detect if one or more of the C source files located in the CodeVisionAVR project directory has changed and will automatically update the corresponding file s in the Location directory Once the new debugger project solution was created the Project Properties menu command must be executed allowing to select the tool or simulator to be used for debugging and it s specific options PU Deon Ree ee eee General Device Tool Selected debugger programmer JTAGICE mkII 00A0000003F5 Interface JTAG Use external reset Use external reset J
339. full implementation would require a large amount of FLASH memory space The function returns the number of outputed characters 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 its field will be padded with spaces If the flag is used the result field will be padded on the right otherwise it will be padded on the left On at least n characters are outputted If the result has less than n characters it is padded on the left with zeros The optional precision specifier sets the maximal number of characters or minimal number of integer digits that may be outputted For the e E and f conversion type characters the precision s
340. g set The DRESULT enumeration data type is defined in sdcard h typedef enum RES _OK 0 0 Successful RES ERROR 1 R W Error RES WRPRT 2 Write Protected RES NOTRDY 3 Not Ready RES _PARERR 4 Invalid Parameter DRESULT It is used for returning the result of the following driver functions DRESULT disk_read unsigned char drv unsigned char buff unsigned long sector unsigned char count reads sectors from a physical drive Parameters drv represents the drive number Drive numbering starts with 0 buff points to the char array where read data will be stored sector represents the Logical Block Address number of the first sector to be read count represents the number of sectors to be read 1 255 1998 2012 HP InfoTech S R L Page 304 CodeVisionAVR Return value RES_OK success RES_ERROR awrite error occured RES_WRPRT the MMC SD SD HC card is write protected RES NOTRDY the disk drive has not been initialized RES_PARERR invalid parameters were passed to the function Note For the MMC SD SD HC card driver using the SPI interface the drv parameter must be always 0 otherwise the function will return with the STA_NOINIT flag set DRESULT disk_write unsigned char drv unsigned char buff unsigned long sector unsigned char count writes sectors to a physical drive Parameters drv represents the drive number Drive numbering starts w
341. g the File Page Setup menu command or the toolbar button which opens the Page Setup dialog window N Page Setup x Printing Options Margins Vi Fage Header left 25 Right 19 v Page Numbers e7 Top 19 Bottom 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 es 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 2012 HP InfoTech S R L Page 34 CodeVisionAVR 2 2 9 Closing Multiple Files Closing several files can be performed using the File Close Mul
342. g 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 the Coulomb Counter 1998 2012 HP InfoTech S R L Page 412 CodeVisionAVR 5 11 Setting the SPI Interface The SPI interface configuration can be specified by clicking on the Serial Peripheral Interface apr node of the CodeWizardAVR selection tree amp CodeWizardAVR test cwp l File Help Extemnal IRQ Timers USARTO USART1 USART2 USART3 Analog Comparator 2 Wire 12C LCD Bit Banged Project Information Chip ExtemalSRAM Ports ADC SPI 2c 1wie v SPI Enabled SPI Interrupt Clock Rate x2 SPI Mode Mode 0 v 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 Data Order 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 C
343. gamma control register bits PKPOO PKPO2 positive gamma micro adj define SSD1289 DEFAULT _PKPOO 7 PKP10 PKP12 positive gamma micro adj define SSD1289 DEFAULT PKP10 7 PKP20 PKP22 positive gamma micro adj define SSD1289 DEFAULT PKP20 4 PKP30 PKP32 positive gamma micro adj define SSD1289 DEFAULT _PKP30 2 PKP40 PKP42 positive gamma micro adj define SSD1289 DEFAULT _PKP40 4 PKP50 PKP52 positive gamma micro adj define SSD1289 DEFAULT _PKP50 2 PRPOO PRPO2 positive gamma gradient adj define SSD1289 DEFAULT PRPOO 2 PRP10 PRP12 positive gamma gradient adj define SSD1289 DEFAULT PRP10 5 VRPOO VRPO3 positive gamma amplification adj define SSD1289 DEFAULT _VRPOO 2 VRP10 VRP14 positive gamma amplification adj define SSD1289 DEFAULT VRP10 3 PKNOO PKNO2 negative gamma micro adj define SSD1289 DEFAULT _PKNOO 7 PKN10O PKN12 negative gamma micro adj define SSD1289 DEFAULT PKN10 5 PKN20 PKN22 positive gamma micro adj define SSD1289 DEFAULT PKN20 4 PKN30 PKN32 positive gamma micro adj 1998 2012 HP InfoTech S R L Page 238 CodeVisionAVR define SSD1289 DEFAU iT PKN30 2 PKN40 PKN42 negative gamma micro adj define SSD1289 DEFAULT PKN40 4 PKN50 PKN52 negative gamma micro adj define SSD1289 DEFAU
344. gister LI9325 CMD FRAME RATE 0x2b Frame rate frequency control LI9325 CMD GAMMA CONTROL1 0x30 Gamma control 1 LI9325 CMD GAMMA CONTROL2 0x31 Gamma control 2 LI9325 CMD GAMMA CONTROL3 0x32 Gamma control 3 LI9325 CMD GAMMA CONTROL4 0x35 Gamma control 4 LI9325 CMD GAMMA CONTROLS 0x36 Gamma control 5 LI9325 CMD GAMMA CONTROL6 0x37 Gamma control 6 LI9325 CMD GAMMA CONTROL7 0x38 Gamma control 7 19325 CMD GAMMA CONTROL8 0x39 Gamma control 8 LI9325 CMD GAMMA CONTROL9 0x3c Gamma control 9 LI9325 CMD GAMMA CONTROL10 0x3d Gamma control 10 1998 2012 HP InfoTech S R L Page 214 CodeVisionAVR define ILI9325 CMD HORIZ RAM ADDR START 0x50 Address of horizontal start window positions define ILI9325 CMD HORIZ RAM ADDR END 0x51 Address of horizontal end window positions define ILI9325 CMD window positions define ILI9325 CMD V D D lt ea ERT RAM ADDR START 0x52 Address of vertical start EA RT RAM ADDR END 0x53 Address of vertical end window positions define ILI9325 CMD DRIVER OUT _CONTROL2 0x60 Driver output control define ILI9325 CMD BASE IMG DISPLAY CONTROL 0x61 Base image display control define ILI9325 CMD VERT SCROLL CONTROL Ox6a Vertical scroll control define IL19325 CMD PARTIAL IMG1 DISPLAY POS 0x80 Partial image 1 display position define ILI9325 CMD PARTIAL IMG1
345. gisters Bits Definitions X cence 2 Her 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 2012 HP InfoTech S R L Page 49 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 other 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 defaul
346. gital conversion result for the input adc_input The input numbering starts from 0 If interrupts are enabled the above function will use an additional interrupt service routine adc_isr This routine will store the conversion result in the adc_data global variable 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 2012 HP InfoTech S R L Page 409 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 clicking on the Voltage Reference FEF node of the CodeWizardAVR selection tree amp CodeWizardAVR test cwp File Help 2c 1 Wire 2Wire 120 _ LCD Bit Banged Project Information Chip Ports External IRQ Timers ADC Voltage Reference Coulomb Counter v Voltage Reference Enabled Voltage Calibration io x mi Temperatur
347. hanges 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 Program 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 2012 HP InfoTech S R L Page 383 CodeVisionAVR In the course of program generation the user will be prompted for the name of the main C file SE Save C Compiler Source File Savein work PB o T Name Date modif Type Size ny No items match your search Recent Places Desktop T Pavel Me Computer A lt Network File name test v 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 rT Name Date modif Type Size wp No items match your search Recent Places Desktop Pavel LS Oa Computer A lt 2 Network File name test Save as type Project files pr v Cancel 1998 2012 HP InfoTech S R L Page 384 CodeVisionAVR Selecting the File Exit menu option allows the user to exit the CodeWizardAVR without genera
348. hannels Triggered by Software conversion start mode if interrupts are enabled for at least one of the ADCn channels After the conversion is complete its result can be read in the ADCn channel s interrupt service routine If software polling is used interrupts are disabled for the ADCn channel then the following functions can be used unsigned int adcn_read unsigned char channel for Unsigned ADC conversion mode int adcn_read unsigned char channel for Signed ADC conversion mode When called these functions will start an analog to digital conversion for the specified channel of ADCn will wait for the conversion to complete will compensate the ADC offset voltage and will return the conversion result Note The analog to digital conversion will be started by the adcn_read functions only for Channels Triggered by Software conversion start mode For the other start modes it will be automatically started by the ADC itself Free Running mode or by the Event System For the Channels Triggered by Software Channels Sweeped by the Event System and Channels Sweeped by the Event System Synchronized conversion start modes and if software polling is used interrupts being disabled for at least one of the ADCn channels the following functions are generated void adcn_sweep_read unsigned int pdata for Unsigned ADC conversion mode void adcn_sweep_read int pdata for Signed ADC conversion mode When called these functions will start analog t
349. hat will hold the number of free clusters fatfs points to a pointer to the FATFS type structure associated with the logical drive Return values FR_OK success FR_INVALID_DRIVE the drive number is invalid FR_NOT_READY no disk access was possible due to missing media or other reason FR_WRITE_PROTECTED opening in write mode or creating a file was not possible because the media is write protected FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTEM there is no valid FAT partition on the disk 1998 2012 HP InfoTech S R L Page 322 CodeVisionAVR The csize member of the FATFS structure represents the number of sectors cluster so the free size in bytes can be calculated using the example below ATmegal28 I O register definitions include lt megal28 h gt FAT on MMC SD SD HC card support include lt ff h gt printf include lt stdio h gt Timerl overflow interrupt frequency Hz define Tl_OVF_FREQ 100 Timerl clock prescaler value define T1 PRESC 10241 Timerl initialization value after overflow define Tl_INIT 0x10000L _MCU_CLOCK_FREQUENCY_ T1_PRESC T1_OVF_FREQ USART Baud rate define BAUD RATE 19200 define BAUD_ INIT _MCU_CLOC
350. he Address Space for which the chip select signal becomes active The Address Space Size list box allows to specify the address range size for which the chip select signal is active The SRAM Wait State list box allows inserting additional wait states when accessing slow external memory 1998 2012 HP InfoTech S R L Page 450 CodeVisionAVR Specific options can be set if SDRAM chips are connected to the XMEGA chip External Bus Interface Settings Memory Type and Connection EBI Disabled SDRAM 3P SRAM 3P ALE1 mus 47 0 415 8 SRAM 3P ALE1 ALE2 mux LPC 2 P ALE1 mux A 0 D 7 0 LPC 2 P ALE1 ALE2 mux LPC 3 P ALE1 mux A 0 D 7 0 SDRAM CS3 Row Bits ma Bits Column Bits a v Bits CAS Latency 0 063 gt us Mode Register Delay 0000 v us Row Cycle Delay 0 000 us Row to Pre charge Delay 0 000 g us Row to Column Delay 0 000 z us Write Recovery Delay 0 000 7 us Exit Self Refresh Delay 0 000 7 us Initialization Delay 0 000 4 us Refresh Period 1 000 vA us SDRAM Self Refresh These options are described in detail in Atmel s XMEGA A Manual in the EBI External Bus Interface chapter Note All the necessary code for EBI setup will be automatically added by the compiler in the startup initialization that is executed immediately after the chip reset There is no need for the programmer to write his own code for this purpose 1998 2012 HP InfoTech S R L Page
351. he 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 Phase Segment 1 and Phase Segment 2 parameters If the CAN Baud Rate value is correct its value is displayed in black color otherwise it is displayed in red and must be corrected by modifying the above mentioned parameters 1998 2012 HP InfoTech S R L Page 430 CodeVisionAVR 5 18 Setting the ATmega169 329 3290 649 6490 LCD Controller The configuration of the LCD Controller built in the ATmega169
352. he OK button CodeVisionAVR will be restarted and ready to use 1998 2012 HP InfoTech S R L Page 493 CodeVisionAVR If there was an error contacting the Activation Server the license needs to be activated manually by contacting HP InfoTech In this case the following message will be displayed with a Serial Number specific to the computer on which CodeVisionAVR is installed F CodeVisionAVR License Unable to contact the Activation Server In order to activate a legally acquired license please send the Serial Number to HP InfoTech 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 105A F25 7 16AB DC8E 9756 EDD6 B1CE 5FC2 Copy to Clipboard Close The Serial Number can be copied to the clipboard using the Copy to Clipboard button and then pasted from the clipboard in the e mail program Note If you experience problems contacting the Activation Server please make sure that no firewall or antivirus program are blocking CodeVisionAVR to access the Internet 1998 2012 HP InfoTech S R L Page 494 CodeVisionAVR 7 2 Transferring or Deactivating the License The CodeVisionAVR license is locked to the hardware of the PC on which the software is installed The Help Transfer Deactivate License menu command must be used in order to transfer the license to an
353. he XMEGA 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_msk must be set to LCD_EN1 respectively LCD_ENZ to select the upper respectively lower half LCD controller Example enables the displaying of the cursor on the upper half of the LCD _en1 msk LCD_EN1 _lcd_ready _lcd_write data 0xe 1998 2012 HP InfoTech S R L Page 185 CodeVis
354. he above mentioned functions 1998 2012 HP InfoTech S R L Page 28 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 or 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 b
355. he data transmitted by the slave this function is called with the tx_complete parameter set as false and should return the number of bytes from the transmit buffer that must be transmitted to the master during the ongoing transaction After the master has finished receiving the data bytes transmitted by the slave this function is called for the second time with the tx_complete parameter set as true signaling that the transaction on the bus has finished In this case the function should return the value 0 as there are no more bytes to be transmitted from the slave to the master After the transaction has finished the twi_tx_index global variable will be the index of the last byte in the transmission buffer that was transmitted by the slave to the master 1998 2012 HP InfoTech S R L Page 276 CodeVisionAVR After a transaction between the master and the slave has finished its status can be read from the twi_result global variable which may take one of the values specified by these macros defined in the twi h header file define TWI_LRES_OK 0 define TWI_LRES_BUFFER_OVERFLOW 1 define TWI_LRES_BUS_ ERROR 3 define TWI_LRES_NACK_RECEIVED 4 define TWILRES_UNKNOWN 7 Note Operating the TWI in slave mode requires the interrupts to be globally enabled This must be done by using the asm sei inline assembly code before attempting any communication through the I7C bus TWI slave operation example The slave will
356. he debugged program e Debug Toggle Breakpoint or F9 key to set a breakpoint at the current cursor position in the C source file or disassembly view e Debug New Breakpoint Break at Function to set a breakpoint at the beginning of a particular function e Debug Delete All Breakpoints or Ctrl Shift F9 keys to delete all the breakpoints that were set e Debug Disable All Breakpoints to temporarily disable all the breakpoints that were set e Debug jEnable All Breakpoints to re enable all the breakpoints that were set e Debug Continue F5 key or toolbar button to continue execution after a breakpoint e Debug Break All Ctrl F5 keys or 4 toolbar button to stop program execution e Debug Windows allow displaying specific windows for watching variables processor registers I O and peripheral registers memory contents code disassembly etc To obtain more information about using AVR Studio 5 1 and Atmel Studio 6 please consult their Help system 1998 2012 HP InfoTech S R L Page 155 CodeVisionAVR 3 23 Compiling the Sample Code of the XMEGA Application Notes from Atmel In order to support the new XMEGA chips Atmel has released 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 repla
357. he file name is invalid FR_INVALID_DRIVE the drive number is invalid FR_EXIST the file already exists FR_DENIED file access was denied because one of the following reasons trying to open a read only file in write mode file couldn t be created because a file with the same name or read only attribute already exists file couldn t be created because the directory table or disk are full FR_NOT_READY no disk access was possible due to missing media or other reason FR_WRITE_PROTECTED opening in write mode or creating a file was not possible because the media is write protected FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTEM there is no valid FAT partition on the disk FRESULT f_read FIL fp void buff unsigned int btr unsigned int br reads data from a file previously opened with f_open After the function is executed the file read write pointer advances with the number of bytes read from the file Parameters fp points to the FIL type structure that contains the file parameters This structure must have been previously initialized by calling the f_open function buff points to a byte buffer array located in RAM that will hold the data read from the file The size of the buffer must be large enough so that the dat
358. he generation of the non inverted Low Side LS and inverted High Side HS waveforms on the corresponding I O port pins Dead times are inserted between LS and HS switching These can be specified using the Low Side Dead Time and High Side Dead Time edit boxes Dead time insertion can be individually activated for each compare channel using the corresponding Enable Dead Time Insertion for Compare Channel Output option The Dead Time Insertion PORT Override group box allows to individually specify which LS or HS waveforms will be outputed on the I O port associated with the timer If the Common Waveform Channel Mode Enabled option is activated the Compare Channel A waveform will be used as input for all the dead time generators The waveforms of Compare Channels B C and D will be ignored 1998 2012 HP InfoTech S R L Page 461 CodeVisionAVR If the Enable Pattern Generation option is activated the pattern generator extension will be used to produce a synchronized bit pattern on the I O port associated with the timer The DTI unit is not activated in this case its registers will be used by the pattern generator The pattern can be specified using the Pattern Generation check boxes This value will be used to initialize the DTIHS register The Pattern Generation PORT Override check boxes allow to specify to which I O port pins the waveform generated by the Compare Channel A will be outputed when an UPDATE condition is set by the
359. he horizontal coordinate of the left top corner of the rectangular display area top specifies the vertical coordinate of the left top corner of the rectangular display area width specifies the horizontal size of the rectangular display area height specifies the vertical size of the rectangular display area memt specifies the memory type to from which the data will be written read It may take one of the following values GLCD_MEM_RAM GLCD_MEM_FLASH GLCD_MEM_EEPROM GLCD_MEM_EXT RAM access FLASH access EEPROM access external memory accessed using special functions addr specifies the memory address to from which the data will be written read mode specifies the operation to be performed Notes GLCD_PUTCOPY GLCD_PUTTP GLCD_PUTXOR GLCD_PUTOR GLCD_PUTNOT GLCD_PUTAND GLCD_GET copy a bitmap from memory to LCD overwriting previous display data copy a bitmap from memory to LCD overwriting previous display data using transparent mode when an image pixel with the current transparency color must be displayed the background color at the pixel coordinates will be used instead copy a bitmap from memory to LCD performing a XOR with previous display data copy a bitmap from memory to LCD performing an OR with previous display data copy a bitmap from memory to LCD performing a bit negation copy a bitmap from memory to LCD performing an AND with previous display data read a block of data from specified coordinates
360. he index of the character in str If there are no matching characters returns the length of str char strpbrk char str char set searches the string str for the first occurrence of a char from the string set If there is a match returns a pointer to the character in str If there are no matching characters returns a NULL pointer 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 th
361. he line s ending point vertical coordinate void glcd_lineto GLCDX_t x GLCDY_t y Draws a line from the current pixel plot position to a new position using the current foreground color thickness and bit pattern The current pixel plot position will be updated to the line s ending point coordinates Parameters x specifies the line s ending point horizontal coordinate y specifies the line s ending point vertical coordinate void glcd_linerel GLCDDX_t dx GLCDDY_t dy Draws a line from the current pixel plot position to a new relative position using the current foreground color thickness and bit pattern The current pixel plot position will be updated to the line s ending point coordinates Parameters dx specifies the horizontal displacement of the line s ending point relative to the current pixel plot position dy specifies the vertical displacement of the line s ending point relative to the current pixel plot position 1998 2012 HP InfoTech S R L Page 208 CodeVisionAVR void glcd_rectangle GLCDX_t left GLCDY_t top GLCDX_t right GLCDY_t bottom Draws a rectangle with the current foreground color line thickness and bit pattern using absolute coordinates The current pixel plot position will be updated to the left top corner of the rectangle Parameters left specifies the horizontal coordinate of the left top corner of the rectangle top specifies the vertical coordinate of the left top corner of the rectangle rig
362. he 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 e CodeVisionAVR Chip Programmer STK500 AVRISP File Edit Program Read Compare Help Chip ATmega2560 Da Program all C Reset Chip SCK Freq 57600 X Hz FLASH EEPROM Start 0 h End 1FFFF h Start 0 h End FFF h Checksum 0x0000 Checksum 0x0000 V Program Chip Programming Options FLASH Lock Bits V Program Fuse Bit s No Protection I CKSELO 0 _ CKSEL1 0 Programming disabled T CKSEL2 0 l CKSEL3 0 Programming and Verification disabled SUTO 0 C SUT1 0 Boot Lock Bit 0 Boot Lock Bit 1 m ON B01 1 B02 1 B11 1 812 1 BOOTRST 0 C BOOTSZ0 0 B01 0 BO2 1 B11 0B12 1 pootsz1 0 S a x a EESAVE 0 BO1 0 BO2 0 5 B11 0 B12 0 M WDTON 0 B01 1 BO2 0 5 B11 1 B12 0 JTAGEN 0 7 OCDEN 0 7 BODLEVELO 0 7 BODLEVEL1 0 BODLEVEL2 0 J Check Signature V Check Erasure Preserve EEPROM V Verify 1998 2012 HP InfoTech S R L Page 83 CodeVisionAVR 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 of the chip s clock frequency The EEPROM Program chec
363. he size of the src string unsigned char stricpyf char dest char flash src unsigned char n copies at most n 1 characters from the string src located in FLASH to the string dest located in SRAM ensuring that it will be always null terminated even if the src string was truncated to fit If n is less then the length of src then the remainder of dest after the null terminator will not be padded with nulls The function returns the size of the src string 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 1998 2012 HP InfoTech S R L Page 173 CodeVisionAVR 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 t
364. hort id File system mount ID unsigned short n_rootdir Number of root directory entries 0 on FAT32 unsigned char fsi_ flag fsinfo dirty flag l must be written back unsigned long last_clust Last allocated cluster unsigned long free clust Number of free clusters unsigned long fsi sector fsinfo sector unsigned long cdir Current directory 0 root unsigned long sects fat Sectors per fat unsigned long max clust Maximum cluster 1 Number of clusters is max_clust 2 unsigned long fatbase FAT start sector unsigned long dirbase Root directory start sector Cluster on FAT32 unsigned long database Data start sector unsigned long winsect Current sector appearing in the win unsigned char win 512 Disk access window for Directory FAT FATFS A FATES type object is allocated by the f_mount function for each logical drive e The FIL type structure is used to hold the state of an open file typedef struct FIL_ FATFS fs Pointer to the owner file system object unsigned short id Owner file system mount ID unsigned char flag File status flags unsigned char csect Sector address in the cluster unsigned long fptr File R W pointer unsigned long fsize File size unsigned long org clust File start cluster unsigned long curr clust Current cluster unsigned long dsect
365. ht specifies the horizontal coordinate of the right bottom corner of the rectangle bottom specifies the vertical coordinate of the right bottom corner of the rectangle void glcd_rectrel GLCDX_t left GLCDY_t top GLCDDX_t width GLCDDY_t height Draws a rectangle with the current foreground color line thickness and bit pattern using relative coordinates The current pixel plot position will be updated to the left top corner of the rectangle Parameters left specifies the horizontal coordinate of the left top corner of the rectangle top specifies the vertical coordinate of the left top corner of the rectangle width specifies the horizontal size of the rectangle height specifies the vertical size of the rectangle void glcd_rectround GLCDX_t left GLCDY_t top GLCDDX_t width GLCDDY_t height GLCDRAD t radius Draws a rectangle with rounded corners using the current foreground color and line thickness The current pixel plot position will be updated to the left top corner of the rectangle Parameters left specifies the horizontal coordinate of the left top corner of the rectangle top specifies the vertical coordinate of the left top corner of the rectangle width specifies the horizontal size of the rectangle height specifies the vertical size of the rectangle radius specifies the radius of each corner s circle arc void glcd_drawpoly unsigned char npoints flash GLCDPOINT_t polypoints Draws a polygon using the current foreground
366. iables 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 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 2012 HP InfoTech S R L Page 112 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 pr
367. ical COM output scan direction 63 gt 0 E T 1998 2012 HP InfoTech S R L Page 228 CodeVisionAVR default initialization values default value for LCD bias define SED1530 DEFAULT LCD BIAS SED1530 LCD BIAS 16 default value for reverse x define SED1530 DEFAULT REVX SED1530 REVX NORM default value for rev1l32_x0 effective only when reverse x 1 SED1530 REVX REV define SED1530 DEFAULT REV132_ X0 SED1530 REV132 XONC default value for reverse y define SED1530 DEFAULT REVY SED1530 REVY NORM default contrast define SED1530 DEFAULT CONTRAST 7 The detailed description of the above mentioned initialization parameters can be found in the SED1530 datasheet Notes e The gled_sed1530 h header file is automatically included when the main gled h header file is included Therefore there is no need to explicitly include glcd_sed1530 h e The EXAMPLES Graphic LCD SED1530 directory contains fully functional code samples that may be used as references for SED1530 initialization and usage 1998 2012 HP InfoTech S R L Page 229 CodeVisionAVR 4 12 6 Graphic LCD Functions Specific to the SPLC501C Controller In order to take full advantage of the SPLC501C controller s features the following specific functions declared in the glcd_splc501 h header file were imple
368. 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 unsigned char from 0 to 15 1998 2012 HP InfoTech S R L Page 158 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 Standard 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 d before using the functions The standard C language I O functions were adapted to work on embedded microcontrollers with limited resources The lowest level Inp
369. ight Text v 14 Fost Floathmbher 0 12312 Highlighted Backg Color E Highlight eos c CDs 16 jchar text Helle world Non Printable Text Color Silver 7 while Number 18 A 19 peeprort pflash 20 Number 21 he 22 L 4 m p X cancel 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 spe
370. igned char spim_master_tx_rx unsigned char c where m is the lowercase suffix of the I O port where the SPI is implemented c is the byte to be transmitted to the slave The function will return the byte received from the slave The SPI beeing operated in polled mode this function will be blocking as the state of the SPIF flag from the STATUS register will be tested in an endless loop until one byte will be transmitted received Note The spim_master_tx_rx function doesn t control the SS signal The SS line must be set low in order to select the slave before calling this function The SET_SPIM_SS_LOW macro is defined by the CodeWizardAVR for this purpose where M is the suffix of the I O port where the SPI is implemented After all communication is finished on the bus the SS line must be set high in order to deselect the slave This is accomplished using the SET_SPIM_SS_HIGH macro defined by the CodeWizardAVR for this purpose where M is the suffix of the I O port where the SPI is implemented Example for SPIC operating as a master Select the SPI slave SET SPIC_SS_ LOW Send two bytes of data to the slave spic_ master tx rx 0x12 spic master tx rx 0x34 Deselect the SPI slave SET SPIC_SS_ HIGH When operating as a Slave the CodeWizardAVR will generate the function unsigned char spim_slave_tx_rx unsigned char c where m is the lowercase suffix of the I O port where the SPI is implemented c i
371. ild After Build Code Generation Advanced Messages Globally define Paths Interrupt Vectors Table Number of Vectors 5 t 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 tees ae 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 2012 HP InfoTech S R L Page 55 CodeVisionAVR The Messages tab allows to individually enable or disable various compiler and linker warnings R Configure Project MULTFILE PRJ Se Files C Compiler Before Build After Build Code Generation Advanced Messages Globally Hdefine Paths 7 Enable Warnings Warnings I 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 memory 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 refere
372. ill be outlined SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usart prj of amp File Edit Search View Project Tools Settings Help BeS HRBACEE MARE o gt bea B 4 ae PPA DAR ARN BES AGG 27 KO R Code Information V FF CAcvavi2 examples atemega USARTCO usartc C cvavr2 inc xmegal28a1 h o ror9 S BB Ble E Code Templates Y 3 G9 R Clipboard Y Z E 5 j af 0 p B i des usart c EJ v B xmegal28a1 h EJ ON t MO Macros alli 1 CodeVisionAVR C Compiler V2 1 a ERA Typedefs Sample program to test the j 2 7 C 1998 2009 Pavel Haiduc I f Ap Global Static Variables Use a STK600 development boi f 3 i FO Functions STK600 RC100X 13 addapters 1 4 Peripheral Modules and Inter 4 main void 5 lo The STK600 programmer must i 6 ifndef _ XMEGA128A1_INCLUDED__ in the Tools Programmer ment 7 define _ XMEGA126A1_INCLUDED__ While 8 i hil E 9 include lt xmstruct h gt defini gt ai i Code Navigator 10 include lt xmbits_a1 h gt bit d SX CodeVisionaVR j LED on the STK6t 11 rox tisk T Sf Project usart 32 casera Pizrae I O Register i Sania Notes following connectie A E f Function Call Tree pe pa a 14 afrb eproi 0x01 Bhan of Headers 15 sfrb cPIo2 0x02 arses i Litt DSTACK Func 0 Total 0 3 16 s rb GPIO3 0x03 ra renee f stdio h e STK600
373. in EEPROM at the specified coordinates The new display position will be located at the end of the displayed text Parameters x specifies the horizontal coordinate of the left top corner of the first displayed character y specifies the vertical coordinate of the left top corner of the first displayed character str pointer to the literal char string void glcd_outtext char str Displays a NULL terminated literal char string located in RAM at the current display position The new display position will be located at the end of the displayed text Parameter str pointer to the literal char string void glcd_outtextf char str Displays a NULL terminated literal char string located in FLASH at the current display position The new display position will be located at the end of the displayed text Parameter str pointer to the literal char string void glcd_outtexte char str Displays a NULL terminated literal char string located in EEPROM at the current display position The new display position will be located at the end of the displayed text Parameter str pointer to the literal char string 1998 2012 HP InfoTech S R L Page 201 CodeVisionAVR void glcd_block GLCDX_t left GLCDY_t top GLCDX_t width GLCDY_t height GLCDMEM_t memt GLCDMEMADDR_t addr GLCDBLOCKMODE_t mode Writes reads a block of bytes to from a rectangular graphics display area at specified coordinates Parameters left specifies t
374. in the glcd_sed1335 h header file were implemented void sed1335_wrcemd unsigned char cmd Writes a command to the SED1335 controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the gled_sed1335 h header file ED1335 SYSTEM SET 0X40 Initialize device and display ED1335 MWRITE 0X42 Write to display memory ED1335 MREAD 0x43 Read from display memory ED1335 SCROLL 0X44 Set display start address and display regions D1335 CSRW 0X46 Set cursor address D1335 CSRR 0X47 Read cursor address D1335 CSRDIR_RIGHT OX4C Set direction of cursor movement to right D1335 SLEEP_IN 0X53 Enter standby mode D1335 DISP ON OFF 0X58 Enable disable display and display flashing D1335 HDOT SCR OX5A Set horizontal scroll position D1335 OVLAY OX5B Set display overlay format D1335 CGRAM ADDR OX5C Set start address of character generator RAM D1335 CSRFORM OX5D Set cursor type define define define define N U UN V Cl Gl Fl FI n Bi mi m define define S define S define S define S Bi mi define S define define S NUUN mi m m define S pi A detailed description of the above mentioned commands can be found in the SED1335 datasheet void sed1335_wrdata unsigned char data Writes a data byte to the SED1335
375. ing a transaction addr represents the 7 bit slave address to which the slave will respond if the match_any_addr parameter is false addr_mask_reg specfies the value used to initialize the TWI module s SLAVE ADDRMASK register If bit 0 of addr_mask_reg is 0 then bits 1 to 7 will represent the 7 bit slave address bit mask otherwise these bits will represent a second 7 bit slave address to which the slave will respond When address mask mode is used if a bit in the address mask is set to 1 the address match between the incoming address bit and the corresponding bit from the slave address is ignored i e masked bits will always match rx_buffer represents a pointer to the buffer that will hold the data received by the slave during the transaction rx_buffer_size represents the size of the receive buffer specified in bytes tx_buffer represents a pointer to the buffer that holds the data to be transmitted by the slave to the master during the transaction twi_slave_trans represents a pointer to the TWI slave transaction processing function This function is called each time a byte is received from the master It will handle the received data from the receive buffer using the value from the rx_index member of TWI_SLAVE_INFO_t Also on its first call when a transaction was started it must initialize the bytes_to_tx member to the number of bytes from the transmit buffer that must be send to the master during the ongoing transaction After the curre
376. ing dest located in RAM It returns 1 if successful 0 if not The DS2430 device is selected using its 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 its 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 its 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 its ROM code stored in an array of 8 bytes located at address romcode 1998 2012 HP InfoTech S R L Page 369 CodeVisionAVR unsigned char ds2430_read_appreg_block unsigned char romcode unsigned char dest unsigned char addr unsigned char size this function reads a
377. ing macros from the glcd_sed1530 h header file define SED1530 CMD START LINE 0x40 set display start line define SED1530 CMD SET PAGE 0xBO set display page address define SED1530 CMD SET ADDR LOW 0x00 set column address bits 0 3 define SED1530 CMD SET ADDR HIGH 0x10 set column address bits 4 7 define SED1530 CMD ADC SELECT NORM 0xA0 set relationship between RAM column address and display driver normal define SED1530 CMD ADC SELECT REV 0xA1 set relationship between RAM column address and display driver reversed define SED1530 CMD DISP_ NORMAL 0xA6 set normal display mode define SED1530 CMD DISP REVERSE 0xA7 set reversed display mode define SED1530 CMD PIXELS NORMAL 0xA4 display the graphic RAM contents define SED1530 CMD ALL PIXELS ON 0xA5 all display pixels are on define SED1530 CMD DISP OFF OxAE display off define SED1530 CMD DISP_ON OxAF display on define SED1530 CMD LCD BIAS 16 0xA2 sets voltage ratio for LCD bias to 1 6 define SED1530 CMD LCD BIAS 15 O0xA3 sets voltage ratio for LCD bias to 1 5 define SED1530 CMD COMO 63 0xCO sets the COM output scan direction 0 gt 63 define SED1530 CMD _COM63 0 OxC8 sets the COM output scan direction 63 gt 0 define SED1530 CMD POWER CTRL 0x28 turns on off the
378. ing 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 fo xe F2 edits value Tab saves edited value Arrow keys Tab Shift Tab PgUp PgDn moves selection Mouse right click fills memory black 1998 2012 HP InfoTech S R L Page 84 CodeVisionAVR 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 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 ETT This window lets you specify the Start Address End Address and Fill Value of the memory area to be filled If you wish to check the chip s signature before any operation you must use the Check Signature option To speed up the programming process you can uncheck the Check Erasure check box In this case there will be no verification of the correctness of the FLASH erasure The Preserve EEPROM checkbox allows preserving the contents of the EEPROM during chip erasure To speed up the programming process you also can uncheck the Verify check box In this case there will be no v
379. ing the Assembler tab will display assembly results li Information x Compiler Assembler Programmer AVRASM AVA macro assembler 2 1 9 build 90 Jul 5 2006 11 06 16 Copyright C 1995 2006 ATMEL Corporation ATmega8515 memory use summary bytes Segment Begin End Code Data Used Size Use cseg Ox000000 0x000106 252 10 262 8192 3 2 dseg Ox0000600x0000e1 OF 1 1 512 02 eseg 0x000000 Ox000001 OF 1 1 512 0 2 Assembly complete 0 errors Program the chip 1998 2012 HP InfoTech S R L Page 75 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 J 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 2012 HP InfoTech S R L Page 76 CodeVisionAVR 2 3 6 4 Cleaning Up the Project Output Directories The various files created during the Project Build process can be deleted using the Project Clean
380. int file sizes will be displayed correctly by the printf function 1998 2012 HP InfoTech S R L Page 321 CodeVisionAVR FRESULT f_stat const char path FILINFO fno gets the file or directory status in a FILINFO type structure Parameters path points to a RAM based NULL terminated char string that represents the path name for the file or directory fno points to the FILINFO type structure that will hold the status information Return values FR_OK success FR_NO_FILE couldn t find the file FR_NO_PATH couldn t find the path FR_INVALID_NAME the file name is invalid FR_INVALID_DRIVE the drive number is invalid FR_NOT_READY no disk access was possible due to missing media or other reason FR_WRITE_PROTECTED opening in write mode or creating a file was not possible because the media is write protected FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTENM there is no valid FAT partition on the disk FRESULT f_getfree const char path unsigned long nclst FATFS fatfs gets the number of free clusters on the drive Parameters path points to a RAM based NULL terminated char string that represents the path name of the root directory of the logical drive nclst points to an unsigned long int variable t
381. int to a FIL type structure defined in the ff h header file that was previously initialized using the f_open function On success the function returns a positive value an 8bit character in the LSB the MSB beeing 0 In case of error or if the end of file was reached the function returns the value of the predefined macro EOF 1 The ferror function must be used to establish if an error occured In order to check if the end of file was reached the feof function must be called 1998 2012 HP InfoTech S R L Page 164 CodeVisionAVR char fgets char str unsigned int len FIL fp reads from a file maximum len 1 characters to the char array pointed by str The read process stops if a new line n character is encountered or the end of file was reached The new line character is also saved in the char string The string is automatically NULL terminated after the read process is stopped The fp pointer must point to a FIL type structure defined in the ff h header file that was previously initialized using the f_open function On success the function returns the same pointer as str If the end of file was encountered and no characters were read a NULL pointer is returned The same happens in case of file access error The ferror function must be used to establish if an error occured In order to check if the end of file was reached the feof function must be called int fputc char k FIL fp writes the character k to a fi
382. ionAVR 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 ExtemalIRQ Timers USARTO USART1 _1Wire 2Wire 2C _ LCD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator apc SPI 12C 12C Port PORTA SDABit 0 SCLBit 1 7 Enabled Address V 0 Output Active High Temperature C Hyst 75 240 5 80 4 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 2012 HP InfoTech S R L Page 417 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 ExtemalIR Timers USARTO USART1 _1Wire 2Wire 2C _ LCD Bit Banged Project Information Chip ExtemalSRAM Ports Analog Comparator abc SPI 12C 12C Port PORTA SDABit 0 SCLBit 1 7 Enabled
383. ionAVR 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 in FLASH 1998 2012 HP InfoTech S R L Page 186 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
384. ip reset e Power On Reset External Reset Brown Out Reset Watchdog Reset Program and Debug Interface Reset Software Reset The Interrupts group box allows to specify the settings for Programmable Multi level Interrupt Controller initialization code generation The following groups of interrupts can be individually enabled or disabled e Low Level Interrupts e Medium Level Interrupts e High Level Interrupts 1998 2012 HP InfoTech S R L Page 443 CodeVisionAVR 6 2 Setting the System Clocks The various XMEGA clock source options can be specified by clicking on the System Clocks ii node of the CodeWizardAVR selection tree The System Clock Source list box allows to select between the following options 2MHz Internal RC Oscillator 32MHz Internal RC Oscillator 32 768kHz Internal RC Oscillator External Oscillator or Clock Phase Locked Loop If one of the internal RC oscillators is used as a system clock source the following options are available System Clocks Settings System Clock Source 2MHz Intemal RC Ose x v Calibrate the 2MHz internal oscillator Calibration Reference 32 768kHz Ext Crystal Osc v 32 768kHz Oscillator Low Power Mode Prescaler A mm CikPer4 2000 000kHz Prescalers B C B 1 C 1 v CikPer2 2000 000kHz ClkPer 2000 000kHz CIKCPU 2000 000kHz Lock Clock Configuration ClkPer Output Disabled z 1998 2012 HP InfoTech S R L Page 444 CodeVisionAVR
385. ips can be connected to the I C bus their chip address can be from 0 to 7 The LM75 is configured in comparator mode where it functions like a thermostat The O S output becomes active when the temperature exceeds the tos limit and leaves the active state when the temperature drops below the thyst limit Both thyst and tos are expressed in C pol represents the polarity of the LM75 O S output in active state If pol is 0 the output is active low and if pol is 1 the output is active high Refer to the LM75 data sheet for more information void Im75_twi_init TWI_MASTER_INFO_t ptwim this function is used to initialize the LM75 library s internal variables when using the TWI Functions for Master Mode Operation for XMEGA Devices It is not used for non XMEGA devices The ptwim parameter must point to a TWI_LMASTER_INFO _t structure variable that is used to hold the information required by the TWI module when operating in master mode The Im75_twi_init function must be called before Im75_init Refer to the supplied example at the end of this chapter for more details int lm75_temperature_10 unsigned char chip this function returns the temperature of the LM75 sensor with the address chip The temperature is in C and is multiplied by 10 A 300ms delay must be present between two successive calls to the Im75_temperature_10 function 1998 2012 HP InfoTech S R L Page 375 CodeVisionAVR Example how to display the temp
386. isabled IRCOM Transmitter Pulse Length 3 258 us x v Receiver Enabled IRCOM Receiver Input RX Pin x Transmitter Enabled Receive Complete Interrupt Medium Level Z Transmit Complete Interrupt Medium Level hd Data Register Empty Interrupt Medium Level hd Receive Buffer Size 128 4 Transmit Buffer Size 128 4 Default USART for getchar Default USART for putchar The IRCOM Receiver Pulse Length option sets the filter coefficient for the IRCOM Receiver If enabled it represent the number of samples required for pulse to be accepted The IRCOM Transmitter Pulse Length sets the pulse modulation scheme for the IRCOM Transmitter The IRCOM Receiver Input list box allows to select if the input of the IRCOM Receiver will be connected to the RX port pin or to one of the Event System Channels 0 to 7 1998 2012 HP InfoTech S R L Page 471 CodeVisionAVR If the Master SPI communication mode is used some specific options are available USARTCO Settings Communication Mode Master SPI m SPI Mode 0 X XEK Leading Edge Rising Sample Data XEK Trailing Edge Falling Data Setup Data Order MSB Fist v Baud Rate 100000 w RealBaud Rate 100000 0 Error 0 0 V Receiver Enabled J Transmitter Enabled Receive Complete Interrupt Medium Level 5 Transmit Complete Interrupt Medium Level Data Register Empty Interrupt
387. ith 0 buff points to the char array where the data to be written is stored sector represents the Logical Block Address number of the first sector to be written count represents the number of sectors to be written 1 255 Return value RES_OK success RES_ERROR awrite error occured RES_WRPRT the SD SD HC card is write protected RES_NOTRDY disk drive has not been initialized RES_PARERR invalid parameters were passed to the function Note For the MMC SD SD HC card driver using the SPI interface the drv parameter must be always 0 otherwise the function will return with the STA_NOINIT flag set DRESULT disk_ioctl unsigned char drv unsigned char ctrl void buff this function is used for controlling MMC SD SD HC card specific features and other disk functions Parameters drv represents the drive number Drive numbering starts with 0 ctrl specifies the command code buff points to the buffer that will hold function results depending on the command code When not used a NULL pointer must be passed as parameter Return value RES_OK success RES_ERROR an error occured RES NOTRDY the disk drive has not been initialized RES_PARERR invalid parameters were passed to the function Note For the MMC SD SD HC card driver using the SPI interface the drv parameter must be always 0 otherwise the function will return with the STA_NOINIT flag set 1998 2012 HP InfoTech S R L Page 305 CodeVisionAVR
388. itialization and usage 1998 2012 HP InfoTech S R L Page 247 CodeVisionAVR 4 12 9 Graphic LCD Functions Specific to the SSD2119 Controller The SSD2119 library functions supplied with the CodeVisionAVR Advanced license can operate the controller in 8bit and 16 bit interface modes In order to take full advantage of the SSD2119 controller s features the following specific functions declared in the glcd_ssd2119 h header file were implemented void ssd2119_wrcemd unsigned char cmd Writes a command to the SSD2119 controller used to access a specific command register Parameter cmd command register index to be sent to the controller This index may take one of the values defined in the following macros from the glcd_ssd2119 h header file SSD2119 command register definitions define SSD2119 CMD OSC 0x00 Oscillator register define SSD2119 CMD DRIVER_OUT 0x01 Driver output control define SSD2119 CMD DRIVING WAVEFORM 0x02 LCD driving waveform control define SSD2119 CMD POWER_CONTROL1 0x03 Power control 1 define SSD2119 CMD DISPLAY CONTROL 0x07 Display control register define SSD2119 CMD FRAME CYCLE 0x0b Frame cycle control register define SSD2119 CMD POWER _CONTROL2 0x0c Power control 2 register define SSD2119 CMD POWER _CONTROL3 0x0d Po
389. itialization is performed by the void system_clocks_init void function generated by the CodeWizardAVR 1998 2012 HP InfoTech S R L Page 448 CodeVisionAVR 6 3 Setting the External Bus Interface The External Bus Interface EBI program generation options can be specified by clicking on the External Bus Interface fel node of the CodeWizardAVR selection tree External Bus Interface Settings Memory Type and Connection EBI Disabled SDRAM 3P SRAM 3P ALE1 mus 4 7 0 415 8 SRAM 3P ALE1 ALE2 mux LPC 2 P ALE1 mux 47 0 D7 0 LPC 2 P ALE1 ALE2 mux LPC 3P ALE1 mux 47 0 D7 0 The check boxes from the Memory Type and Connection group allow to specify the EBI operating mode and kind of external RAM connected to the chip 1998 2012 HP InfoTech S R L Page 449 CodeVisionAVR Depending on the EBI operating mode additional tabs are displayed for the configuration of the CS0 CS3 chip select signals External Bus Interface Settings Memory Type and Connection EBI Disabled SDRAM 3P SRAM 3 P ALE1 mux 47 0 415 8 SRAM 3P ALE1 ALE2 mux LPC 2 P ALE1 mux amp 7 0 D7 0 LPC 2 P 4LE1 ALE2 mux LPC 3 P ALE1 mux 47 0 D7 0 cso csi_ cs2_ cs3 v Enabled Base Address 0 h Address Space Size 64k bA Bytes SRAM Wait State 0 000 v us The Enable check box activates the usage of the corresponding CSn chip select signal The Base Address represents the starting address in hexadecimal of t
390. k when the Enable Second Slave Address option is disabled represents the 7 bit slave address bit mask applied to the Slave Address Slave v Enable Interrupt Low Level z Match Any Slave Address Slave Address 20 h Enable Second Slave Address Slave Address Mask 0 h Receive Buffer Size 1 pA byte s Transmit Buffer Size 1 jA byte s If a bit in the Slave Address Mask is set to 1 the address match between the incoming address bit and the corresponding bit from the Slave Address is ignored i e masked bits will always match e Receive Buffer Size specifies the size of the receive buffer in bytes e Transmit Buffer Size specifies the size of the transmit buffer in bytes After the TWI is configured the CodeWizardAVR will generate code that uses the Two Wire Interface Functions for XMEGA Devices library 1998 2012 HP InfoTech S R L Page 478 CodeVisionAVR 6 15 Setting the Analog to Digital Converters The XMEGA Analog to Digital Converter s ADC can be configured by clicking on the Analog to Digital Converters Abe nodes of the CodeWizardAVR selection tree The following settings are available ADCA Settings ADC Enabled ADC Clock Frequency 125 000 kHz x ADC Resolution 12 Bits v ADC Conversion Made Unsigned Z ADC Reference Internal 1 00 Y Z Temperature Measurement Reference Enabled Conversion Start Mode Channels Triggered by Software X
391. k Source System Clock 7 Clock Value 2000 000 kHz 7 4 Mode Phase correct PM top 0xFF Out amp Non Inverted Pw M A Out B Non Inverted Pw z Overflow Interrupt Compare Match A Interrupt Compare Match B Interrupt Timer Value 0 h Compare A 40 Compare B 80 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 2012 HP InfoTech S R L Page 393 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
392. k box allows to enable or disable EEPROM programming when the Program All menu command is executed or when the Sy Program All button is pressed 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 Sy 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 memory buffer You can Load or Save the contents of these buffers using the File menu Supported file formats are e Atmel rom and eep e Intel HEX e Binary bin After loading a file in the corresponding buffer the Start and End addresses are updated accordingly You may also edit these addresses if you wish The contents of the FLASH respectively EEPROM buffers can be displayed and edited us
393. lave to respond to any slave address supplied by the master when starting a transaction addr represents the 7 bit slave address to which the slave will respond if the match_any_addr parameter is false rx_buffer represents a pointer to the buffer that will hold the data received by the slave during the transaction rx_buffer_size represents the size of the receive buffer specified in bytes tx_buffer represents a pointer to the buffer that holds the data to be transmitted by the slave to the master during the transaction slave_rx_handler represents a pointer to the TWI slave receive processing function This function is called each time a byte is received from the master It can handle the received data from the receive buffer using the value from the twi_rx_index global variable The TWI interrupt service routine embedded in twi lib when calling this function will pass the rx_complete argument as true when the master transmission to the slave has finished If the slave wishes to terminate the reception of bytes from the slave the function pointed by the slave_rx_handler must return the value false when it is called If the slave can accept more data bytes from the master this function should return the value true slave_tx_handler represents a pointer to the TWI slave transmission processing function This function is caled twice by the TWI interrupt service routine embedded in twi lib On its first call when the master is ready to receive t
394. lcd_barrel GLCDX_t left GLCDY_t top GLCDDX_t width GLCDDY_t height Draws a filled in rectangular bar using relative coordinates without drawing an outline The bar is filled using the current fill pattern and fill color Parameters left specifies the horizontal coordinate of the left top corner of the bar top specifies the vertical coordinate of the left top corner of the bar width specifies the horizontal size of the bar height specifies the vertical size of the bar 1998 2012 HP InfoTech S R L Page 212 CodeVisionAVR void glced_floodfill GLCDX_t x GLCDY_t y GLCDCOL_t border Fills a closed polygon or area with the current fill color Parameters x specifies the horizontal coordinate of a point inside the area to be filled y specifies the vertical coordinate of a point inside the area to be filled border specifies the color of the border of the area to be filled where the fill process must stop void gled_fillcircle GLCDX_t x GLCDY_t y GLCDRAD_t radius Draws and fills a circle at specified center coordinates using the current fill color Parameters x specifies the horizontal coordinate of the circle s center y specifies the vertical coordinate of the circle s center radius specifies the circle s radius void glcd_pieslice GLCDX_t x GLCDY_t y unsigned short start_angle unsigned short end_angle GLCDRAD _t radius Draws a pie slice at specified center coordinates using the current foreground color and
395. le The fp pointer must point to a FIL type structure defined in the ff h header file that was previously initialized using the f_open function On success the function returns a positive value which represents the same character as k the MSB beeing 0 In case of error the function returns the value of the predefined macro EOF 1 int fputs char str FIL fp writes to a file the NULL terminated char string stored in RAM pointed by str The terminating NULL character is not written to the file The fp pointer must point to a FIL type structure defined in the ff h header file that was previously initialized using the f_open function On success the function returns a positive value 1 In case of error the function returns the value of the predefined macro EOF 1 int fputsf char flash str FIL fp writes to a file the NULL terminated char string stored in FLASH memory pointed by str The terminating NULL character is not written to the file The fp pointer must point to a FIL type structure defined in the ff h header file that was previously initialized using the f_open function On success the function returns a positive value 1 In case of error the function returns the value of the predefined macro EOF 1 int fprintf FIL fp char flash fmtstr this function is identical to printf except that the formatted text is written to a file The fp pointer must point to a FIL type structure defined in the ff h header
396. le Save As menu command pd Save C cvavr inc untitled c As x Save in work O PE r Name Date modif Type Size wA No items match your search Recent Places Computer A lt Network File name mylib X Save as type C Compiler source file c v Cancel 1998 2012 HP InfoTech S R L Page 148 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 2012 HP InfoTech S R L Page 149 CodeVisionAVR 3 21 Using the AVR Studio 4 19 Debugger CodeVisionAVR is designed to work in conjunction with the Atmel AVR Studio 4 19 debugger 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 Important Note It is highly recommended to set the Optimize for Speed option in the Project Configure C Compiler Code Generation menu which will allow correct d
397. le 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 i node the corresponding source line is highlighted in the 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 2012 HP InfoTech S R L Page 78 CodeVisionAVR 2 3 6 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 E E led c fan Includes E mega8515 h 40 Macros mal fmove mi xtal be Typedefs b gt abc a b c 4p Global Static Variables X led_status gt RAM O0E0h X w EEPROM 0001h X xyz gt not used removed by the linker FQ Functions 0 mainfvoid fO timerl_overflow yvoid The Code Information win
398. led prior to any access using the va_arg macro type va_arg argptr type This macro is used to extract successive arguments from the variable length argument list referenced by argptr type specifies the data type of the argument to extract The va_arg macro can be called only once for each argument The order of the parameters in the argument list must be observed On the first call va_arg returns the first argument after the previous_par argument specified in the va_start macro Subsequent calls to va_arg return the remaining arguments in succession void va_end argptr This macro is used to terminate use of the variable length argument list pointer argptr initialized using the va_start macro Example include lt stdarg h gt declare a function with a variable number of arguments int sum_all int nsum va_list argptr int i result 0 initialize argptr va_start argptr nsum add all the function arguments after nsum for i 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 2012 HP InfoTech S R L Page 177 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 p
399. line thickness After that the pie slice is filled with the current fill color The angles are measured starting from from 3 o clock counter clockwise Parameters x specifies the horizontal coordinate of the circle s center y specifies the vertical coordinate of the circle s center start_angle specifies the arc s starting angle end_angle specifies the arc s ending angle radius specifies the circle s radius 1998 2012 HP InfoTech S R L Page 213 CodeVisionAVR 4 12 1 Graphic LCD Functions Specific to the ILI9325 Controller The ILI9325 library functions supplied with the CodeVisionAVR Advanced license can operate the controller in 16 bit interface mode with 256 or 64k colors In order to take full advantage of the ILI9325 controller s features the following specific functions declared in the glcd_ili9325 h header file were implemented void ili9325_wrcmd unsigned char cmd Writes a command to the ILI9325 controller used to access a specific command register Parameter cmd command register index to be sent to the controller This index may take one of the values defined in the following macros from the glcd_ili9325 h header file ILI9325 command regis define I define I define I define define define define define define define register define I define I register define I define I define I define I define I I I ag I HHHHHHH define define define define register define de
400. ling properties of LCD signal generator 2 define SSD1963 CMD GET LCD GEN2 0xC5 Get the rise fall period and toggling properties of LCD signal generator 2 define SSD1963 CMD SET LCD GEN3 0xC6 Set the rise fall period and toggling properties of LCD signal generator 3 define SSD1963 CMD GET LCD GEN3 0xC7 Get the rise fall period and toggling properties of LCD signal generato PIOO ROP 0xC8 Set GPIOO with respec signal generators using ROP3 operation PIOO ROP 0xC9 Get GPIOO properties with respect to LCD signal generators PIO1l ROP OxCA Set GPIO1 with respect to LCD signal generators using ROP3 operation PIO1l ROP OxCB Get GPIO1 properties with respect to LCD signal generators PIO2 ROP OxCC Set GPIO2 with respect to LCD signal generators using ROP3 operation PIO2 ROP OxCD Get GPIO2 properties with respect to LCD signal generators PIO3 ROP OxCE Set GPIO3 with respect to LCD signal generators using ROP3 operation GPIO3 ROP OxCF Get GPIO3 properties with respect to LCD signal generators DBC CONF 0xDO Set Dynamic Backlight Control configuration DBC CONF 0xD1 Get Dynamic Backlight Control configuration DBC THRES 0xD4 Set the threshold for each level of power saving nan Gl Gl FI HA define SSD1963 CMD Q Gl define SSD1963 C define SSD1963 C define SSD1963 CM C C H define SSD1963 define SSD1963 H
401. lock Rate x2 check box available for some AVR chips will double the SPI Clock Rate For communicating through the SPI interface with disabled SPI interrupt you must use the SPI Functions If the SPI interrupt is enabled you must use the spi_isr interrupt service routine declared by the CodeWizardAVR 1998 2012 HP InfoTech S R L Page 413 CodeVisionAVR 5 12 Setting the Universal Serial Interface USI The USI configuration can be specified by clicking on the corresponding node st of the CodeWizardAVR selection tree The USI operating mode can be selected using the Mode list box One of the USI operating modes is the Three Wire SPI mode a CodeWizardAVR test cwp File Help 1 Wire LCD Bit Banged Project Information Chip Ports External IRQ Timers USI Analog Comparator ADC 12C Mode Three Wire SPI zj Clock Register amp Counter USICLK USI Counter Overflow Interrupt 1998 2012 HP InfoTech S R L Page 414 CodeVisionAVR The USI can also operate in the Two Wire I2C mode amp CodeWizardAVR test cwp x File Help 1 Wite ln LCD Bit Banged Project Information Chip Ports External IRQ Timers USI Analog Comparator ADC Ea m Mode Two wire 12C z Clock Register amp Counter USICLK z USI Counter Overflow Interrupt USI Start Condition Interrupt The Shift Reg Clock list box sets the clock source for
402. lowing specific functions declared in the glcd_st7565 h header file were implemented void st7565_wrcmd unsigned char cmd Writes a command to the ST7565 controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the glcd_st7565 h header file define ST7565 CMD define ST7565 CM D START LINE 0x40 set display start line D define ST7565 CMD D D S SET PAGE 0xBO set display page address SET ADDR LOW 0x00 set column address bits 0 3 S A define ST7565 CM define ST7565_CM ET ADDR HIGH 0x10 set column address bits 4 7 DC_SELECT NORM 0xA0 set relationship between RAM column address and display driver normal define ST7565 CMD ADC SELECT REV OxAl set relationship between RAM column address and display driver reversed define ST7565 CMD DISP NORMAL 0xA6 set normal display mode define ST7565 CMD DISP REVERSE O0xA7 set reversed display mode define ST7565 CMD PIXELS NORMAL 0xA4 display the graphic RAM contents define ST7565 CMD ALL PIXELS ON 0xA5 all display pixels are on define ST7565 CMD STATIC INDICATOR OFF OxAC turn off static indicator define ST7565 CMD STATIC INDICATOR ON OxAD turn on static indicator define ST7565 CMD DISP OFF OxAE display off define ST7565 CMD DISP ON OxAF display on define ST7565 CMD LCD BIAS LOW 0xA2 sets voltage
403. ls along the bit rate of the SCL clock for bit banged I C bus not the hardware TWI communication Note For proper operation the DS1307 Functions require the presence of 3 3k 4 7k pull up resistors to 5V 3 3V for XMEGA devices on the SCL and SDA signals 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 TWI hardware respectively 1 C bus must be initialized by calling the twi_master_init twi_init twi_master_init and ds1307_twi_init for XMEGA devices respectively i2c_init functions 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 Ofor1 Hz e 1 for 4096 Hz e 2 for 8192 Hz e 3 for 32768 Hz If the sqwe parameter is set to 1 then the square wave output on the SQW OUT pin is enabled The out parameter specifies the logic level on the SQW OUT pin when the square wave output is disabled sqwe 0 Refer to the DS1307 data sheet for more information void ds1307_twi_init TWI_MASTER_INFO_t ptwim this function is used to initialize the DS1307 library s internal variables when using the TWI Functions for Master Mode Operation for XMEGA Devices It is not used for non XMEGA devices The ptwim parameter must point to a TWI_LMASTER_INFO _t structure variable that is use
404. lt ds1820 h gt include the printf function prototype include lt stdio h gt 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 2012 HP InfoTech S R L Page 363 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 prin
405. m eeprom int Background Color J window v 3 aii Text Attributes Use Editor Colors for 10 Elvoid main void J Bold Text 11 0 12 int Number 123 Italic 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 peepror pflasht t 20 Number 21 he z 22 11 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
406. mage size or 0 if the coordinate values are not valid 1998 2012 HP InfoTech S R L Page 206 CodeVisionAVR unsigned long glcd_getimagee GLCDX_t left GLCDY_t top GLCDX_t width GLCDY_t height eeprom unsigned char pimg Saves a rectangular display area to EEPROM as a bitmapped image Parameters left specifies the horizontal coordinate of the left top corner of the rectangular display area top specifies the vertical coordinate of the left top corner of the rectangular display area width specifies the horizontal size of the rectangular display area height specifies the vertical size of the rectangular display area pimg points to the byte array that will hold the image data Return values image size or 0 if the coordinate values are not valid unsigned long gicd_getimagex GLCDX_t left GLCDY_t top GLCDX_t width GLCDY_t height GLCDMEMADDR _t addr Saves a rectangular display area to external memory as a bitmapped image Note External memory write must be implemented through an user defined function specified during initialization by gled_init Parameters left specifies the horizontal coordinate of the left top corner of the rectangular display area top specifies the vertical coordinate of the left top corner of the rectangular display area width specifies the horizontal size of the rectangular display area height specifies the vertical size of the rectangular display area addr specifies the external memory address to which the im
407. main void int i Call the function sum using the pointer i sum ptr 1 2 1998 2012 HP InfoTech S R L Page 127 CodeVisionAVR 3 13 Compiler Directives Compiler specific directives are specified 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 default optimization for Size or Speed specified the Project Configure C Compiler Code Generation Optimization menu setting can be restored using the pragma optsize_defaul
408. mber of bytes of data effectively written to the file Return values FR_OK success FR_DENIED file access was denied because it was opened in read only mode FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_INVALID_ OBJECT the file was not opened with f_open FRESULT f_lseek FIL fp unsigned long ofs moves the file read write pointer of a file previously opened with f_open In write mode this function can be also used to extend the file size by moving the file read write pointer past the end of the file On success the value of the fptr member of the FIL structure pointed by fp must be checked to see if the file read write pointer effectively advanced to the correct position and the drive didn t get full In read mode trying to advance the file read write pointer past the end will limit its position to the end of the file In this case the fptr member of the FIL structure pointed by fp will hold the size of the file Parameters fp points to the FIL type structure that contains the file parameters This structure must have been previously initialized by calling the f_open function ofs represents the byte position where the file read write pointer must be placed starting with the begining of the file 1998 2012
409. me for the file or directory to be renamed path_new points to a RAM based NULL terminated char string that represents the new path name for the file or directory Return values FR_OK success FR_NO_FILE couldn t find the file or directory FR_NO_PATH couldn t find the path FR_INVALID_NAME the file or directory name is invalid FR_INVALID_DRIVE the drive number is invalid FR_NOT_READY no disk access was possible due to missing media or other reason FR_EXIST the file or directory already exists FR_DENIED the file or directory couldn t be created or moved from any reason FR_WRITE_PROTECTED the media in the drive is write protected FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTEM there is no valid FAT partition on the disk FRESULT f_chdir const char path changes the current directory of the current logical drive When the drive is mounted the current directory is the root directory Note After f_chdir is called all subsequent file access function operations will be performed by default in the new current directory if no other directory is specified when calling these functions Parameter path points to a RAM based NULL terminated char string that represents the path name for the directory to go
410. mented void splc501_wrcmd unsigned char cmd Writes a command to the SPLC501C controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the gled_spIc501 h header file define SPLC501 CMD START LINE 0x40 set display start line define SPLC501 CMD SET PAGE 0xBO set display page address define SPLC501 CMD SET ADDR LOW 0x00 set column address bits 0 3 define SPLC501 CMD SET ADDR HIGH 0x10 set column address bits 4 7 define SPLC501_ CMD ADC SELECT NORM 0xA0 set relationship between RAM column address and display driver normal define SPLC501 CMD ADC SELECT REV 0xAl set relationship between RAM column address and display driver reversed define SPLC501 CMD DISP_ NORMAL 0xA6 set normal display mode define SPLC501 CMD DISP REVERSE 0xA7 set reversed display mode define SPLC501 CMD PIXELS NORMAL 0xA4 display the graphic RAM contents define SPLC501 CMD ALL PIXELS ON 0xA5 all display pixels are on define SPLC501 CMD DISP OFF OxAE display off define SPLC501 CMD DISP ON OxAF display on define SPLC501 CMD LCD BIAS 19 0xA2 sets voltage ratio for LCD bias to 1 9 define SPLC501 CMD LCD BIAS 17 O0xA3 sets voltage ratio for LCD bias to 1 7 define SPLC501 CMD COMO 63 O0xCO sets the COM output scan
411. micro adj LI9325 DEFAULT KP50 2 RP02 positive gamma gradient adj LI9325 DEFAULT RPOO 2 RP12 positive gamma gradient adj LI9325 DEFAULT RP10 5 VRP03 positive gamma amplification adj LI9325 DEFAULT VRPOO 2 VRP14 positive gamma amplification adj LI9325 DEFAULT VRP10 3 KNO2 negative gamma micro adj LI9325 DEFAULT KNOO 7 KN12 negative gamma micro adj LI9325 DEFAULT KN10 5 KN22 positive gamma micro adj LI9325 DEFAULT KN20 4 KN32 positive gamma micro adj LI9325 DEFAULT KN30 2 KN42 negative gamma micro adj LI9325 DEFAULT KN40 4 KN52 negative gamma micro adj LI9325 DEFAULT KN50 2 RNO2 negative gamma gradient adj LI9325 DEFAULT RNOO 2 RN12 negative gamma gradient adj R VRNO3 negative gamma amplification adj iT _VRNOO 2 negative gamma amplification adj T_VRN1O 3 ae RJ xJ 1998 2012 HP InfoTech S R L Page 220 CodeVisionAVR The ILI9325 library functions can operate the display in 256 or 64k color modes For 256 color mode the following color bit allocation in a data byte is used e Bits 0 2 Blue color bits 0 2 e Bits 3 5 Green color bits 0 2 e Bits 6 7 Red color bits 0 1 For 64k color mode the following color bit allocation in a 16bit data word is used e Bits 0 4 Blue color bits 0 4 e Bits 5 10 Green color bits 0 5 e Bits 11 15 Red color bits 0 4 Notes e In order to reduce image storage size and im
412. mmended to set the Optimize for Speed option in the Project Configure C Compiler Code Generation menu which will allow correct debugging of the program Once debugging was finished this option can be also set to Optimize for Size The debugger is invoked using the Tools Debugger menu command or the toolbar button In order to be able to do this the debugger version and it s installation path must be first specified using the Settings Debugger menu After a new CodeVisionAVR project was compiled for the first time and the COFF object file was produced a corresponding Project Solution must be created in the debugger s IDE This is accomplished by launching the debugger and executing the File Open Open Object File For Debugging menu command The following dialog window will be displayed r Open Object File For Debugging Project Creation Wizard Object File Path and Project Name Selection Specify the object file path project name and project location Select the Object File To Debug C cvavr2 examples Graphic LCD SSD1963 demo_tft43 cof pm Specify Project Name and path AVR Studio will create a new project _objproj for the object file opened for debugging Specify a name for the project and the location where the project folder should be created Project Name 5501963 Demo Location C Users PaveliDocuments AVRStudio 5 1 sama V Maintain Folder heirarchy for source files Recommended The
413. n TOP v Requirements Frequency 10 000000 pA kHz Obtained 10kHz 0 00 error Apply PER 0 h CNT 0 h CCA 63 h E Compare Ch A Output CCB 0 h cce 0 h CCD O h Timer Overflow Underflow Interrupt Disabled X Timer Error Interrupt Disabled z Compare Capture 4 Interrupt Disabled v Compare Capture B Interrupt Disabled zi Compare Capture C Interrupt Disabled ne Compare Capture D Interrupt Disabled ha The Requirements group box allows the user to specify the desired timer Frequency in kHz Pressing the Apply button will perform automatic timer configuration Clock Source and CCA register values so that the required timer frequency will be obtained for a given Peripheral Clock value Note The PER register is not used in this operating mode If the Compare Ch A Output option is enabled the corresponding waveform generation WG output will be toggled on each compare match between the CNT and CCA registers The duty cycle of this signal will be 50 1998 2012 HP InfoTech S R L Page 459 CodeVisionAVR In Single Slope PWM Generation and Double Slope PWM Generation modes the following specific options are available Timer Counter TCEO Settings Basic Advanced Waveform Extension Clock Source Peripheral Clock 1 x Timer Clock 2000kHz Resolution 16Bit x Mode Dual Slope PWM Gen Overflow Int E vent on TOP X
414. n address and display driver normal ADC 0 define SPLC501 REVX_ REV 1 set relationship between RAM column address and display driver reversed ADC 1 values used for rev132_x0 initilization effective only when reverse x 1 SPLC501 REVX_REV define SPLC501 REV132 X0NC 0 pixel with x 0 is not connected to column driver 132 when ADC 1 define SPLC501 REV132 X0CON 1 pixel with x 0 is connected to column driver 132 when ADC 1 1998 2012 HP InfoTech S R L Page 231 CodeVisionAVR values used for reverse y initialization define SPLC501 REVY NORM 0 sets the vertical COM output scan direction O gt 63 define SPLC501 REVY REV 1 sets the vertical COM output scan direction 63 gt 0 values used for driving _mode initialization define SPLC501 DRIVING MODE1 0 driving mode 1 defau define defau define t LCD driving mode LC501 DEFAULT DRIVING MODE SPLC501 DRIVING MOD t contrast PLC501 DEFAULT CONTRAST 7 U T GI hb DP define SPLC501 DRIVING MODE2 1 driving mode 2 define SPLC501 DRIVING MODE3 2 driving mode 3 define SPLC501 DRIVING MODE4 3 driving mode 4 default initialization values default value for LCD bias define SPLC501 DEFAULT LCD BIAS SPLC501 LCD BIAS 19 default value for r
415. n aee a EAE dens E a 499 BO QING E E E A E E O E N E E E E aid 499 1998 2012 HP InfoTech S R L Page 9 CodeVisionAVR 8 7 Other Rights and Restrictions 0 cece eects teenie seer nE EEKEREN ANANEA NEARE NARE SAKERNA ANAE EAEEREN 499 9 Technical Support and Updates ececcceccceceeeeeeeee cece eeeeeseeeeee seen ene seseaeeeseeeseseeeseeeeeseeeseeeeeenenees 500 10 Contact IMPOrmMmationy i cisco ccececiesscsscncecteeees cccsantesevesseeaneancbeederdevsaneansunessvacuiandanchne deveneeanenoteecntnesd 501 Page 10 1998 2012 HP InfoTech S R L CodeVisionAVR 1 Introduction CodeVisionAVR is a C cross compiler Integrated Development Environment and Automatic Program Generator designed for the Atmel AVR family of microcontrollers It is designed to run under the 2000 XP Vista and Windows 7 32bit and 64bit 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 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 automatic transfer of the program to the microcontroller chip after successful compilation assembly The In System Programmer softwa
416. n generated by the CodeWizardAVR 1998 2012 HP InfoTech S R L Page 455 CodeVisionAVR 6 6 Setting the Virtual Ports The XMEGA Virtual Ports can be configured by clicking on the Virtual Ports ui node of the CodeWizardAVR selection tree The following options are available Virtual Ports Settings YPORTO Mapping PORTA x YPORT1 Mapping PORTE x YPORT2 Mapping PORTC x VPORT3 Mapping PORTD x The VPORTO Mapping VPORT1 Mapping VPORT2 Mapping and VPORT3 Mapping list boxes allow to select which I O port mapped in the extended I O memory space will be mapped virtually to the I O memory space allowing it to be accessed using more efficient IN and OUT instructions The Virtual Ports initialization is performed by the void vports_init void function generated by the CodeWizardAVR 1998 2012 HP InfoTech S R L Page 456 CodeVisionAVR 6 7 Setting the Timers Counters The XMEGA Timers Counters can be configured by clicking on the Timers Counters and TCn nodes of the CodeWizardAVR selection tree The Timer Counter can be activated by selecting a Clock Source Timer Counter TCEQ Settings Basic Clock Source Peripheral Clock 1 x Timer Clock 2000kHz Resolution 16Bit ha Mode Normal Operation Overflow Int E vent on TOP Capture Event Source Event Channel 0 Capture Event Action Input Capture x Requirements Pe
417. n 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 2012 HP InfoTech S R L Page 113 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 sf c 10 Global structure located in EEPROM eeprom struct eeprom structure char a int b char 15 7 se void main void Local s
418. n value after overflow define Tl INIT 0x10000L _MCU CLOCK FREQUENCY T1_PRESC T1 OVF_FREQ 100Hz timer interrupt generated by ATmegal28 Timerl overflow interrupt TIM1_OVF void timer comp_isr void ve initialize Timerl TCNTIH T1_ INIT gt gt 8 TCNT1L T1 INIT amp OxFF card access low level timing function disk timerproc the rest of the interrupt service routine E Seas RL 1998 2012 HP InfoTech S R L Page 306 CodeVisionAVR void main void char display buffer 64 buffer used by sprintf unsigned char status unsigned int sector size unsigned long int sector count initialize Timerl overflow interrupts in Mode 0 Normal TCCR1IA 0x00 clkio 1024 TCCRIB 1 lt lt CS12 1 lt lt CS10 timer overflow interrupts will occur with 100Hz frequency TCNT1H T1 INIT gt gt 8 TCNTIL T1_ INITS amp OxFF enable Timerl overflow interrupt TIMSK 1 lt lt TOIE1 initialize the LCD led_init 16 globally enable interrupts asm sei initialize SPI interface and card driver status disk initialize 0 clear the LCD lcd_clear display disk initialization result on the LCD if status amp STA _NOINIT lcd puts Disk init failed else if status amp STA _NODISK lcd puts Card not present else if status amp STA PROTECT lcd_puts Card write nprotected
419. nal is obtained by dividing the output of the 32 768 kHz external crystal oscillator which can be configured to operate in Low Power Mode by checking the appropriate option The RTC32 can be configured automatically by specifying the RTC32 Overflow and RTC32 Compare periods and clicking on the Apply button from the Requirements group box This will set the optimal values for the Clock Frequency list box PER period and COMP compare 32 bit registers The initial value for the CNT count 32 bit register can be specified in hexadecimal using the appropriate edit box The RTC32 can generate two types of interrupts e RTC32 Overflow Interrupt e RTC32 Compare Interrupt Each type of interrupt can be individually enabled and its priority set using the corresponding list boxes 1998 2012 HP InfoTech S R L Page 467 CodeVisionAVR When it is enabled the RTC32 initialization is performed by the void rtc32_battery_backup_init void function generated by the CodeWizardAVR If the RTC32 is disabled the initialization is performed by the void rtc32_battery_backup_disable void function 1998 2012 HP InfoTech S R L Page 468 CodeVisionAVR 6 11 Setting the USARTs The XMEGA USARTSs can be configured by clicking on the USARTs and USARTn H nodes of the CodeWizardAVR selection tree The following options are available for configuring each USART USARTCO Settings Communication Mode Asynchronous USAR
420. name C Program Files x86 Atmel Atmel Studio 6 0 AtmelStudio exe fg x Cancel Help The Debugger list box allows to select one of the three versions of debuggers compatible with CodeVisionAVR After selecting the debugger the IDE will detect automatically it s installation path and display it in the Directory and Filename edit box z path can be also manually edited and eventually other location can be selected by pressing the button Changes can be saved respectively canceled using the OK respectively Cancel buttons The debugger is executed by selecting the Tools Debugger menu command or by pressing the button on the toolbar Details about using the debuggers with CodeVisionAVR can be found in the following chapters 3 21 Using the AVR Studio 4 19 Debugger 3 22 Using the AVR Studio 5 1 and Atmel Studio 6 Debuggers 1998 2012 HP InfoTech S R L Page 82 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 MkIl JTAGICE 3 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 t
421. nate GLCDY_t glcd_gety void Returns the value of the current pixel plot position vertical coordinate void glcd_setfont flash unsigned char font_name Specifies the current font used for displaying text Parameters font_name points to an array located in FLASH memory that holds the font definition void glcd_settextjustify unsigned char horiz unsigned char vert Sets the horizontal and vertical text justification values Parameters horiz specifies the horizontal spacing between displayed characters measured in pixels vert specifies the vertical spacing between displayed characters measured in pixels 1998 2012 HP InfoTech S R L Page 198 CodeVisionAVR unsigned char glcd_charwidth char c Returns the width in pixels of a character for the current font including the horizontal justification Parameter c specifies the code of the character for which the width must be returned unsigned char gicd_textheight void Returns the text height in pixels for the current font including the vertical justification GLCDX_t gled_textwidth char str Returns the text width in pixels of a NULL terminated literal char string located in RAM for the current font including the horizontal justification Parameter str pointer to the literal char string GLCDX_t glcd_textwidthf flash char str Returns the text width in pixels of a NULL terminated literal char string located in FLASH for the current fon
422. nced 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 2012 HP InfoTech S R L Page 56 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 will be equivalent with placing the macro definition define ABC 1234 in each project s program module 1998 2012 HP InfoTech S R L Page 57 CodeVisionAVR The Paths tabs allows to specify additional paths for include and library files These paths must be entered one per line in the appropriate edit controls XM Configure Project MULTFILE PRI l Files C Compiler Before Build After Build Code Generation Advanced
423. nclude lt stdlib h gt char display buffer 33 structure that holds information used by the TWID master for performing a TWI bus transaction TWI_ MASTER INFO t twid master interrupt service routine for TWID master interrupt TWID_TWIM vect void twid_master isr void twi_master int handler amp twid master TWI clock rate Hz define TWI CLK RATE 100000 1998 2012 HP InfoTech S R L Page 359 CodeVisionAVR void main void int t0 t1 initialize the LCD 2 rows by 16 columns led_init 16 general TWID initialization no external driver interface no SDA hold time twi_init amp TWID false false enable and initialize the TWID master interrupt level low twi master init amp twid_master amp TWID TWI_ MASTER INTLVL_LO gc TWI BAUD REG MCU CLOCK FREQUENCY _ TWI_CLK_ RATE enable the Low interrupt level PMIC CTRL PMIC_LOLVLEN_ bm set the DS1621 functions to use TWID ds1621 twi_init amp twid_ master enable interrupts so that TWI can be used asm sei 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
424. nd 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 directory and file Changes can be saved respectively canceled using the OK respectively Cancel buttons 1998 2012 HP InfoTech S R L Page 69 CodeVisionAVR 2 3 6 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 6 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 modifi
425. nd is 8 Notes e The gled_t6963 h header file is automatically included when the main gled h header file is included Therefore there is no need to explicitly include glcd_t6963 h e The EXAMPLES Graphic LCD T6963C directory contains fully functional code samples that may be used as references for T6963C initialization and usage 1998 2012 HP InfoTech S R L Page 267 CodeVisionAVR 4 12 13 Graphic LCD Functions Specific to the UC1701 Controller In order to take full advantage of the UC1701 controller s features the following specific functions declared in the glcd_uc1701 h header file were implemented void uc1701_wrcemd unsigned char cmd Writes a command to the UC1701 controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the gled_uc1701 h header file define UC1701 CMD SET SCROLL LINE 0x40 set the scroll line number define UC1701 CMD SET PAGE 0xBO set display page address define UC1701 CMD SET ADDR LOW 0x00 set column address bits 0 3 define UC1701 CMD SET ADDR HIGH 0x10 set column address bits 4 7 define UC1701 CMD SEG DIR NORM 0xA0 set relationship between RAM column address and display driver normal MX 0 define UC1701 CMD SEG DIR REV OxAl set relationship between RAM column address and display driver reversed MX 1 define UC1701_
426. neration modes the Timer Counter can also use the Advanced Waveform Extension AWeX that provides some additional features It can be accessed by selecting the Advanced Waveform Extension tab Timer Counter TCEO Settings Basic Advanced Waveform Extension Enable Pattern Generation Lock Configuration Registers Dead Time Insertion Low Side Dead Time 0 vA ClkPer Cycles Duration 0 000 us High Side Dead Time 0 MA ClkPer Cycles Duration 0 000 us Enable Dead Time Insertion for Compare Channel 4 Output Enable Dead Time Insertion for Compare Channel B Output Enable Dead Time Insertion for Compare Channel C Output Enable Dead Time Insertion for Compare Channel D Output Dead Time Insertion PORTE Override Common Waveform Channel Mode Enabled CCA DTI Low Side gt OUT O CCC DTI Low Side gt OUT 4 CCA DTI High Side gt OUT 1 C CCC DTI High Side gt OUT 5 CCB DTI Low Side gt OUT 2 CCD DTI Low Side gt OUT 6 CCB DTI High Side gt QUT 3 CCD DTI High Side gt QUT 7 Fault Protection Input Sources Event Channel0 Event Channel 4 Event Channel Event Channel 5 Event Channel2 Event Channel 6 Event Channel 3 Event Channel 7 Action None Fault protection disabled om Restart Mode Latched Mode a V On Chip Debug Break Request Triggers a Fault Condition The Dead Time Insertion group box contains the settings for the Dead Time Insertion DTI unit that enables t
427. nfirm that the license was indeed deactivated Note If you experience problems contacting the Activation Server please make sure that no firewall or antivirus program are blocking CodeVisionAVR to access the Internet If you wish to perform hardware changes to your computer mainboard BIOS or HDD or format the HDD and reinstall Windows you need to temporary deactivate the license using the above mentioned procedure and once the changes are done activate the license again as described in Chapter 7 1 7 3 Upgrading the License The Help Upgrade License menu command must be used if you have purchased a license upgrade or update extension The following dialog will be displayed B Internet License Upgrade In order to upgrade your license please enter the License ID below License ID 1 2345678 Paste from Clipboard You must enter the License ID that was supplied by HP InfoTech when the license was initially purchased This is necessary in order to prevent accidental license upgrade by unauthorized persons The License ID can be also pasted from the clipboard by pressing the Paste from Clipboard button After that the license can be upgraded by pressing the Upgrade button CodeVisionAVR will contact the Activation Server using the Internet After several seconds upon successful upgrade the following confirmation message will be displayed E Information i License successfully upg
428. ng mode define ST7565 DEFAULT DRIVING MODE ST7565 DRIVING MODE1 default contrast define ST7565 DEFAULT CONTRAST 7 pe The detailed description of the above mentioned initialization parameters can be found in the ST7565 datasheet Notes e The glcd_st7565 h header file is automatically included when the main glcd h header file is included Therefore there is no need to explicitly include gled_st7565 h e The EXAMPLES Graphic LCD ST7565 directory contains fully functional code samples that may be used as references for ST 7565 initialization and usage 1998 2012 HP InfoTech S R L Page 259 CodeVisionAVR 4 12 11 Graphic LCD Functions Specific to the ST7920 Controller In order to take full advantage of the ST7920 controller s features the following specific functions declared in the gled_st7920 h header file were implemented void st7920_wrcmd unsigned char cmd Writes a command to the ST7920 controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the glcd_st7920 h header file Basic command set clear display define ST7920 DISPLAY CLEAR 0x01 return cursor to origin define ST7920 RETURN HOME 0x02 set cursor position amp display shift when doing write or read define ST7920 ENTRY MODE SET 0x04 entry mode bits
429. ngs are available for operating the TWI module in Master mode Master v Enable Interrupt Low Level x SCL Rate 100000 4 bps Real SCL Rate 100000 bps Error 0 0 e Enable activates the operation of the TWI module in master mode e Interrupt specifies the interrupt priority level used by the TWI module when operating in master mode e SCL Rate specifies the required TWI clock rate on the SCL pin The Real SCL Rate is calculated and displayed based on the System Clock value 1998 2012 HP InfoTech S R L Page 477 CodeVisionAVR The following settings are available for operating the TWI module in Slave mode Slave J Enable Interrupt Low Level Match Any Slave Address Slave Address 20 h v Enable Second Slave Address Second Slave Address 50 h Receive Buffer Size 1 pA bytefs Transmit Buffer Size 1 74 bytels e Enable activates the operation of the TWI module in slave mode e Interrupt specifies the interrupt priority level used by the TWI module when operating in slave mode e Match Any Slave Address enables the TWI slave to respond to any slave address supplied by the master when starting a transaction e Slave Address represents the 7 bit slave address to which the slave will respond if the Match Any Slave Address option is disabled e Enable Second Slave Address when enabled allows to specify a Second Slave Address to which the slave should respond e Slave Address Mas
430. nitialization values for the gamma control register bits KP00 KP02 positive gamma micro adj define IL19325 DEFAULT _KPO0O 7 KP10 KP12 positive gamma micro adj define ILI9325 DEFAULT KP10 7 KP20 KP22 positive gamma micro adj define ILI9325 DEFAULT KP20 4 KP30 KP32 positive gamma micro adj define IL19325 DEFAULT _KP30 2 KP40 KP42 positive gamma micro adj define ILI9325 DEFAULT KP40 4 1998 2012 HP InfoTech S R L Page 219 CodeVisionAVR KP50 define I RPOO define I RP10 define VRPOO define I VRP1O define I KNOO define KN10 define KN20 define KN30 define KN4O define KNS5O define RNOO define RN10 define I VRNOO define I VRNIO define I H H H H ti H H H The following colors are redefined in the glced_ili9325 h header file LI9325 DEFAULT RN10 L19325 DEFAU VRN14 L19325 DEFAU GLCD_CL_BLACK GLCD_CL_WHITE GLCD_CL_GRAY GLCD_CL_LIGHT_GRAY GLCD_CL_GREEN GLCD_CL_LIME GLCD_CL_BLUE GLCD_CL_RED GLCD_CL_AQUA GLCD_CL_YELLOW GLCD_CL_MAGENTA GLCD_CL_CYAN GLCD_CL_DARK_CYAN GLCD_CL_ORANGE GLCD_CL_PINK GLCD_CL_BROWN GLCD_CL_VIOLET GLCD_CL_SILVER GLCD_CL_GOLD GLCD_CL_NAVY GLCD_CL_MAROON GLCD_CL_PURPLE GLCD_CL_OLIVE 5 KP52 positive gamma
431. nnection schematic is provided below MICROCONTROLLER 5 or tO PORT OUTPUT WRITE PROT VO POR VO POR Note The drivers can be also used with hardware designs which set the WP signal to logic 0 when the MMC SD SD HC Card is write protected In this case the WP Active Low option must be enabled in the Project Configure C Compiler Libraries MMC SD SD HC Card menu The MMC SD SD HC card driver function prototypes helper type definitions and macros are placed in the header file sdcard h located in the INC subdirectory This file must be include d before using the functions 1998 2012 HP InfoTech S R L Page 300 CodeVisionAVR The MMC SD SD HC card driver functions are void disk_timerproc void is a low level timing function that must be called every 10ms by a Timer interrupt Note It is mandatory to ensure that this function is called every 10ms in your program Otherwise the MMC SD SD HC card driver functions will lock in an endless loop when testing for disk operations timeout Example ATmegal28 I O register definitions include lt megal28 h gt MMC SD SD HC card support include lt sdcard h gt Timerl overflow interrupt frequency Hz define Tl_OVF_FREQ 100 Timerl clock prescaler value define T1 PRESC 10241 Timerl initialization value after overflow define Tl_INIT 0x10000L _MCU_CLOCK_FREQUENCY_ T1_PRESC T
432. nnels in ascending order as can be seen from the above example picture Each Capture Channel can be enabled using the corresponding Capture Ch A Capture Ch B Capture Ch C or Capture Ch D check boxes The initial values of the CCA CCB CCC and CCD capture channel registers can be specified using the corresponding edit controls The Requirements group box allows the user to specify the desired timer Period in ms Pressing the Apply button will perform automatic timer configuration Clock Source and PER period register values so that the required timer period will be obtained for a given Peripheral Clock value The initial value for the Timer Counter CNT register can be specified using the corresponding edit control The Timer Counter can generate several types of interrupts Timer Overflow Underflow Interrupt Timer Error Interrupt Compare Capture A Interrupt Compare Capture B Interrupt Compare Capture C Interrupt Compare Capture D Interrupt Each type of interrupt can be individually enabled and its priority set using the corresponding list boxes 1998 2012 HP InfoTech S R L Page 458 CodeVisionAVR In Frequency Waveform Generation mode the following specific options are available Timer Counter TCEQ Settings Basic Advanced Waveform Extension Clock Source Peripheral Clock 1 x Timer Clock 2000kH2 Resolution 16Bit Mode Frequency Waveform Gen Overflow Int E vent o
433. noise canceler is to be used Interrupt on specifies if an interrupt is to be generated on timer counter 1 overflow input capture and compare match e Timer Value specifies the initial value of timer counter 1 at startup e Comp A B and C specifies the initial value of timer counter 1 output compare registers A B and C 1998 2012 HP InfoTech S R L Page 396 CodeVisionAVR 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 Note 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 2012 HP InfoTech S R L Page 397 CodeVisionAVR By selecting the Timer 2 tab you can have the following options Timers Counters Settings Timer Status Requirements Period 1 024000 4 ms Duty Cycle A 50 00 4 x B 60 00 4 x Obtained Period 1 024 ms 0 00 error Apply Timerd Timerl Timer2 Timer3 Time t gt Clock Source System Clock Z Clock Value 250 000 kHz 7 Mode Fast PM top 0xFF EA Dut amp Non Inverted PwiM Z Out B Non Inverted Pwd zi Overflow Interrupt Compare Match A Inter
434. nput Output Functions getchar gets scanf putchar puts and printf For interrupt driven serial communication CodeWizardAVR automatically redefines the basic getchar and putchar functions The receiver buffer is implemented using the global array rx_buffer The global variable rx_wr_index is the rx_buffer array index used for writing received characters in the buffer The global variable rx_rd_index is the rx_buffer array index used for reading received characters from the buffer by the getchar function The global variable rx_counter contains the number of characters received in rx_buffer and not yet read by the getchar function If the receiver buffers overflows the rx_buffer_overflow global bit variable will be set 1998 2012 HP InfoTech S R L Page 404 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
435. ns prototypes are automatically include d with the pcf8563_twi h or pcf8563 h The Project Configure C Compiler Libraries I2C menu must be used for specifying the I O port allocation of the SCL and SDA signals along the bit rate of the SCL clock for bit banged C bus not the hardware TWI communication Note For proper operation the PCF8563 Functions require the presence of 3 3k 4 7k pull up resistors to 5V 3 3V for XMEGA devices on the SCL and SDA signals 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 TWI hardware respectively 1 C bus must be initialized by calling the twi_master_init twi_init twi_master_init and pcf8563_twi_init for XMEGA devices respectively i2c_init functions This is the first function that must be called prior to using the other PCF8563 Functions Only one PCF8563 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
436. nt transaction is finished bytes_to_tx will be automatically reset to 0 along with rx_index by the TWI slave interrupt handler so it can be ready to be initialized when the next transaction will start void twi_slave_int_handler TWI_SLAVE_INFO_t twi represents the interrupt handler used for processing the interrupts generated by a TWI module operating in master mode Parameters twi represents a pointer to the TWI_SLAVE_INFO_t data type variable that is used to hold all the required information for slave operation of a particular TWI module associated with an I O port The TWI_SLAVE_INFO_t data type variable must have been first initialized by a call to twi_slave_init The twi_slave_int_handler function must be called inside the interrupt service routine associated with the slave interrupt of a particular TWI module 1998 2012 HP InfoTech S R L Page 286 CodeVisionAVR void twi_slave_halt_trans TWI_SLAVE_INFO_t twi is used by the slave to halt a TWI transaction Usually this function must be called from within the TWI slave transaction processing function specified by the twi_slave_trans parameter of twi_slave_init Parameters twi represents a pointer to the TWI_SLAVE_INFO_t data type variable that is used to hold all the required information for slave operation of a particular TWI module associated with an I O port TWI master and slave operation example Sample program to test the XMEGA TWIC master and
437. ntf vsprintf and vsnprintf Standard C Input Output Functions can t output strings longer than 255 characters for the s format specifier 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 XMEGA TWI functions and EBI support are not available in the Evaluation version e the libraries for color graphic LCDs ILI9325 SSD1289 SSD1963 SSD2119 and XG7100 are available and can be used only with Advanced or Professional licenses 1998 2012 HP InfoTech S R L Page 156 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 2012 HP InfoTech S R L Page 157 CodeVisionAVR 4 1 Character Type Functions The prototypes for these functions are placed in the file ctype h located in the INC subdirectory This file must be include d 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
438. ntroller is used for displaying text Note This option is available only for graphic LCD controllers that have a built in character generator The connections between the graphic LCD module and the AVR I O ports can be specified individually for each signal in the Data and Control tabs Note In order to obtain maximum performance it is advised to set the LCD controller s data bus bits to match the bits with the same numbers of the same AVR I O port 1998 2012 HP InfoTech S R L Page 433 CodeVisionAVR 5 21 Setting the USB Controller The configuration of the USB Controller for the AT90USB646 AT90USB647 AT90USB1286 and AT90USB1287 chips can be specified by clicking on the corresponding Q CodeWizardAVR selection tree node of the The USB controller can operate in two modes Device and Host specified using the Operating Mode list box File Help External IRQ a CodeWizardAVR test cwp Timers USART1 Bit Banged Chip Analog Comparator abc SPI 12C Project Information External S FAM Parts 1 Wire 2 Wire 12c LCD UID UYCON General Int SRP Method Low Speed Device Int Endpoint Endpoint Cfg Endpoint Size Operating Mode Device OTG am USB Pad Regulator UYCON Hardware Control O SRP Data line pulsing Mode O Suspend o Control OUT x Banks 1 yA 8 Endpoint Enable e The
439. nu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line void main void unsigned char hour min sec hsec day month unsigned int year initialize the LCD 2 rows by 16 columns led_init 16 initialize the bit banged I2C functions G26 ANTEC 7 initialize the RTC 0 no dated alarm rtc_init 0 0 rtc_set_time 0 12 0 0 0 set time 12 00 00 00 on RTC 0 rtc_set_date 0 1 2 2011 set date 1 02 2011 on RTC 0 display the time and date continuously while 1 read the time from the RTC 0 rtc_get_ time 0 amp hour min amp sec amp hsec read the date from the RTC 0 rtc_get_ date 0 amp day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec lcd_clear lcd _ puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month year lcd _ puts display buffer delay ms 500 0 5 second delay 1998 2012 HP InfoTech S R L Page 347 CodeVisionAVR 4 22 3 Maxim Dallas Semiconductor DS1302 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the DS1302 real time clock
440. nu must be used in order to make a hidden window visible again Clicking on the icon will make the docked window temporarily hidden its position will be displayed by a vertical bar located on the left or right of the docking site SX CodeVisionAvR C cvavr2 examples atxmega US File Edit Search View Project Tools Settings DSeS HUaEORGMNE Messages Ferrers A TEETER PAM DRRR fE be Code Information v zE olj a gn a z Includes Notes usar rs A Macros 1 El s Fat Typedefs 2 Sample S Xp Global Static Variables 3 Use a F Functions 4 sTK600 fo main void 5 6 The STI i in the 8 9 Make s 10 using i 11 The VI 12 ef Function Call Tree x g1 pinch SO main is 4 DSTACK Func 0 Total C Fell connect SFO printf a lcere a E DSTACK Func 10 Ti a i en FO _print l E DSTACK Func 21 A GE ft strlen A E DSTACK Fund 23 inciue 1998 2012 HP InfoTech S R L Page 18 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 SX CodeVisionAVR C cvavr2 examples atxmega USA File Edit Search View Project Tools Settings OGe H RE AlS MH APA BPWCROL fe fe Code Navigator V 44 9 E CAcvavr2 examp oj a sH Code ision VA gam E Bi Project usart Notes 1 B 6 usart c 2 Sample 3 Al Headers es 3
441. o definitions are placed in the header file twi h located in the INC subdirectory This file must be include d before using the TWI functions Notes e The twi h header file automatically includes the io h header file that contains the I O modules definitions for the AVR device selected in the project configuration e These functions operate using interrupts so the interrupts must be globally enabled using the asm sei inline assembly code before attempting any communication through the IC bus e For proper operation the TWI Functions require the presence of 3 3k 4 7k pull up resistors to 5V on the SCL and SDA signals 4 14 1 Two Wire Interface Functions for Master Mode Operation The following functions are used for operating the TWI in master mode void twi_master_init unsigned char bit_rate enables and initializes the TWI hardware for operating in master mode Parameters bit_rate specifies the SCL clock frequency in kHz bool twi_master_trans unsigned char slave_addr unsigned char tx_data unsigned char tx_count unsigned char rx_data unsigned char rx_count performs a TWI transaction using the master module Parameters slave_addr specifies the 7 bit bus address of the slave with which the transaction should be performed tx_data represents a pointer to the buffer that holds the data that must be transmitted to the slave during the transaction tx_count specifies the number of bytes to transmit during the
442. o digital conversions for all the ADCn channels specified in the Sweep listbox will wait for the conversions to complete will compensate the ADC offset voltage and will store the conversion results in the array pointed by pdata Note The analog to digital conversions will be started by the adcn_sweep functions only for Channels Triggered by Software conversion start mode For the other start modes they will be automatically started by the Event System 1998 2012 HP InfoTech S R L Page 484 CodeVisionAVR If interrupts are enabled for an ADC channel then the corresponding interrupt service routine will be generated for it void adcn_chm_isr void where n is the name of the PORT where the ADC inputs are located and m is the number of the ADCn channel The interrupt service routine will contain code to read the conversion result from the RESL and RESH registers of ADCn channel m and compensate the ADCn offset voltage More details about ADC operation for the XMEGA chips can be found in the following Atmel documents e AVR1300 Using the XMEGA ADC e XMEGA A Manual e XMEGA D Manual 1998 2012 HP InfoTech S R L Page 485 CodeVisionAVR 6 16 Setting the Digital to Analog Converters The XMEGA Digital fo Analog Converter s DAC can be configured by clicking on the Digital to Analog Converters DAC nodes of the CodeWizardAVR selection tree The following settings are available DACA Settings v DAC Enabl
443. ocumentation 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 8 6 Terms This license is effective until terminated You may terminate it by destroying the program the documentation and copies thereof This license will also terminate if you fail to comply with any terms or conditions of this agreement You agree upon such termination to destroy all copies of the program and of the documentation or return them to Pavel Haiduc or HP InfoTech S R L for disposal Note that by registering this product you give Pavel Haiduc and HP InfoTech S R L permission to reference your name in product advertisements 8 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 2012 HP InfoTech S R L Page 499 CodeVisionAVR 9 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 2012 HP InfoTech S R L Page 500 CodeVisionAVR 10 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
444. ode Templates 0 0 0 0 cicccicnee rennet etinnee erties eee eineee erties AANA KERA ATANAN NARESH KERNAN 36 2 2 11 Using the Clipboard History cai ccccccciceccctee ce eccece se cnceetesennad evened eseedeneestesenead E 37 2 3 Working with Project 0 cece nee nn nner eee eine erties ee neee eee neeeeeneeeenieeeeeiae 38 2 3 1 Creating a New Project ciiecen nde hiii nie EEEE EREEREER 38 2 3 2 Opening an Existing Project 0 cc eee ee eene eee etne ee erent ee ee tees settee eeeaeeeeetaeeeeeeenaeeeseeaas 40 2 3 9 EXPOMING a Pro o censa a aE A davase entice Blea lor adie ade 41 2 3 4 Adding Notes or Comments to the Project 0 eccceceeeeeeeeeeeeeeeeneeeeeeeneeeeeetaeeeeteneeeenenaes 42 2 3 0 Gontiguring the Project gceisieiteieeei cise eel neh ee A nineties Govinaii aides 43 2 3 5 1 Adding or Removing a File from the Project cc ce eeeeceeeeeeneeeeeeeneeeeeenaeeeeeentaeeeeneaas 43 2 3 5 2 Setting the Project Output Directories 0 eee eee etter ee eeteeeee eee eeeeenaaeeeeeenaeeeeeeaas 45 2 3 5 3 Setting the C Compiler Options ccccccccceeeceecceeeeeeeeeeeeaeeeeeeeeeeeeseceaeaeeeeeeetenennaees 46 2 3 5 4 Setting the 1 Wire Library Options ceceee sence ee eeneeeeeeeeeeeeeaeeeeeeeaeeeeeeaeeeeeeaas 59 2 3 5 5 Setting the FC Library Options siiiciccii atacand windinaei lacie andiedaa thesia 60 2 3 5 6 Setting the MMC SD SD HC Card Library Options c ccceeceeeeeeeeeeeeeeteeeeseeeeeees 61 2
445. ogic state of bit b of port Example tests bit 5 of PINA I O Port A input for non XMEGA chips if TSTBIT PINA 5 bit 5 of I O Port A input is logic 1 do something tests bit 5 of PORTA IN I O Port A input for XMEGA chips if TSTBIT PORTA IN 5 bit 5 of I O Port A input is logic 1 do something The bit level access to the I O registers can be also accomplished by 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 to logic 1 PORTA 0 1 1998 2012 HP InfoTech S R L Page 135 CodeVisionAVR test bit 1 input of Port A if PINA 1 place some code here The same program for XMEGA chips using the Virtual Port VPORTO I O register definitions for the ATxmegal28Al chip include lt xmegal28al h gt void main void Map PORTA to virtual port VPORTO and PORTB to virtual port VPORT1L PORTCFG VPCTRLA PORTCFG VPIMAP PORTB gc PORTCFG VPOMAP PORTA gc set bit 0 of Port A as output VPORTO
446. ogram 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 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 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 eve
447. ol 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 2012 HP InfoTech S R L Page 272 CodeVisionAVR display the ROM codes for each detected device printf S u DEVICE S DETECTED n r devices if devices for i 0 i lt devices itt printf DEVICE u ROM CODE IS itl for j 0 j3 lt 8 j printf s xX rom_codes i j printf n r y while 1 loop forever unsigned char w1_dow_crc8 void p unsigned char n this function checks the 8 bit DOW CRC for a block of bytes with the length n pointed by p It returns 1 if the DOW CRC of the first n 1 bytes from the block equals the value of the n th byte or 0 if it doesn t 1998 2012 HP InfoTech S R L Page 273 CodeVisionAVR 4 14 Two Wire Interface Functions for non XMEGA Devices The TWI Functions for non XMEGA Devices are intended for easy interfacing between C programs and various external peripherals using the IC bus These functions can operate the AVR microcontroller as bus master or slave The function prototypes along with helper variable and macr
448. olor at the pixel coordinates will be used instead e GLCD_PUTXOR copy a bitmap from memory to LCD performing a XOR with previous display data e GLCD_PUTOR copy a bitmap from memory to LCD performing an OR with previous display data e GLCD_PUTNOT copy a bitmap from memory to LCD performing a bit negation e GLCD_PUTAND copy a bitmap from memory to LCD performing an AND with previous display data Return values image size or 0 if the coordinate values are not valid Notes e The GLCD_PUTXOR GLCD_PUTOR GLCD_PUTNOT GLCD_PUTAND modes are supported only for displays with 2 colors monochrome e The GLCD_PUTTP mode is supported only for displays with more than 2 colors 1998 2012 HP InfoTech S R L Page 204 CodeVisionAVR unsigned long glcd_putimagee GLCDX_t left GLCDY_t top eeprom unsigned char pimg GLCDBLOCKMODE_t mode Displays a bitmap image located in EEPROM at specified coordinates Parameters left specifies the horizontal coordinate of the left top corner of the image top specifies the vertical coordinate of the left top corner of the image pimg pointer to the image data which is located in EEPROM mode specifies how the display operation must be performed e GLCD_PUTCOPY copy a bitmap from memory to LCD overwriting previous display data e GLCD_PUTTP copy a bitmap from memory to LCD overwriting previous display data using transparent mode when an image pixel with the current transparency color must be dis
449. om 0 to 99 4 9 Gray Code Conversion Functions The prototypes for these functions are placed in the file gray h located in the INC subdirectory This file must be include d before using the functions unsigned char gray2binc unsigned char n unsigned int gray2bin unsigned int n unsigned long gray2binl unsigned long n Convert the number n from Gray code representation to its binary equivalent unsigned char bin2grayc unsigned char n unsigned int bin2gray unsigned int n unsigned long bin2grayl unsigned long n Convert the number n from binary representation to its Gray code equivalent 1998 2012 HP InfoTech S R L Page 180 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 d 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 2012 HP InfoTech S R L Page 181 CodeVisionAVR 4 11 Alphanumeric LCD Functions 4
450. on is identical to vsprintf except that at most size including the null terminator characters are placed in the character string str The function returns the number of outputed characters 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
451. onAVR 6 9 Setting the 16 Bit Real Time Counter The XMEGA 16 Bit Real Time Counter RTC can be configured by clicking on the Real Time Counter a node of the CodeWizardAVR selection tree The following options are available Real Time Counter Settings Clock Source 1024 Hz from 32 768 kHz Crystal Osc on TOSC z 32 768 kHz External Oscillator Low Power Mode Requirements RTC Overflow Period 0 000 vA ms RTC Compare Period 0 000 BA ms Apply RTC Clock Prescaler ATC Clock 1 v PER O oh CNT 0 h COMPO h RTC Overflow Interrupt Disabled Z RTC Compare Interrupt Disabled Z The Clock Source list box allows to select the signal that will be used as RTC clock e 1024 Hz obtained from the 32 kHz internal Ultra Low Power oscillator e 1024 Hz obtained from the 32 768 kHz external crystal oscillator on the TOSC1 and TOSC2 pins e 1024 Hz obtained from the 32 kHz internal RC oscillator e 32 768 kHz obtained from the 32 768 kHz external crystal oscillator on the TOSC1 and TOSC2 pins If the 32 768 kHz external crystal oscillator is used it can be configured to operate in Low Power Mode by checking the appropriate option The RTC can be configured automatically by specifying the RTC Overflow and RTC Compare periods and clicking on the Apply button from the Requirements group box This will set the optimal values for the RTC Clock Prescaler list box PER period and COMP compare 16 bit regis
452. onAVR void ds1621_set_status unsigned char chip unsigned char data this function sets the contents of the configuration status register of the DS1621 with address 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 chips are accessed using the TWI Functions for Master Mode Operation for non XMEGA Devices include the DS1621 functions for TWI include lt ds1621 twi h gt include the LCD Functions The connections must be specified in the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd 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 ant 60 EL initialize the LCD 2 rows by 16 columns lcd init 1
453. onfiguration conflicts will be prompted to the user allowing him to correct the errors 1998 2012 HP InfoTech S R L Page 439 CodeVisionAVR In the course of program generation the user will be prompted for the name of the main C file SE Save C Compiler Source File Savein work PB o T Name Date modif Type Size ny No items match your search Recent Places Desktop T Pavel Me Computer A lt Network File name test v 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 rT Name Date modif Type Size wp No items match your search Recent Places Desktop Pavel LS Oa Computer A lt 2 Network File name test Save as type Project files pr v Cancel 1998 2012 HP InfoTech S R L Page 440 CodeVisionAVR Selecting the File Exit menu option allows the user to exit the CodeWizardAVR without generating any program files By selecting the Help Help Topics menu option by pressing the F1 key or by clicking on the 2 toolbar button the user can see the help topic that corresponds to the current CodeWizardAVR configuration menu The XMEGA peripheral that needs to be configured can be selected by clicking on the corresponding node of the CodeWizardAVR selection tree E CodeWizard4VR untitled cwx Project Inform
454. ont porch width pixel clock cycles unsigned char hback_ porch TFT panel horizontal back porch width pixel clock cycles unsigned char vpulse width TFT panel vertical pulse width line cycles unsigned char vfront_porch TFT panel vertical front porch width line cycles unsigned char vback porch TFT panel vertical back porch width line cycles unsigned char tft24bit 1 specify TFT panel data width 0 18bit 1 24bit unsigned char reverse x 1 reverse display horizontally unsigned char reverse yil reverse display vertically unsigned char cl bits _order 1 selects the color bits writing order to the display RAM 0 gt RGB 1 gt BGR GLCDINIT t 1998 2012 HP InfoTech S R L Page 244 CodeVisionAVR The following macros are defined for initializing the members of the GLCDINIT_t structure Initialization values for tft24bit define SS define SS D1963 TFT DATA WIDTH18 D1963 TFT DATA WIDTH24 Initial define SS define SS ization values for rev D1963_ REVX_NORM 0 N D1963 REVX_REV 1 Ho ization 0 TFT panel data width 18 bit 1 TFT panel data width 24 bit erse x o horizontal reverse rizontal reverse Initial define SSD1963 R define SSD1963 R Initialization values for reverse y EVY REV 1 Vertical reverse Write colo
455. 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 cvavrhexamplesSLED 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 Vled c 32 lobal variable xyz declared but not referenced Warming Copy 1998 2012 HP InfoTech S R L Page 73 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
456. or compatibility with versions of the compiler prior to V1 24 1 This directive is not recommended for new projects 1998 2012 HP InfoTech S R L Page 139 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 2012 HP InfoTech S R L Page 140 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 global 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 an
457. or 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 ds18b20 scratch pad struct unsigned char temp l1sb temp_msb temp high temp_ low conf register resl res2 res3 CHC __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 2012 HP InfoTech S R L Page 366 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
458. or sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line void main void unsigned char hour min sec day month unsigned int year initialize the LCD 2 rows by 16 columns lcd_init 16 initialize the TWI in master mode with 100 kHz bit rate twi_master init 100 enable interrupts so that TWI can be used fasm sei 1998 2012 HP InfoTech S R L Page 337 CodeVisionAVR initialize the RTC Timer interrupt enabled Alarm interrupt enabled CLKOUT frequency 1Hz Timer clock frequency 1Hz rtc_init RTC_TIE ON RTC_AIE ON RTC_CLKOUT_1 RTC_TIMER CLK 1 rtc_set_time 12 0 0 set time 12 00 00 rtc_set_date 1 2 2011 set date 1 02 2011 display the time and date continuously while 1 read the time from the RTC rtc_get_time amp hour amp min amp Sec read the date from the RTC rtc_get_ date amp day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec lced_clear lcd _ puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month year lcd puts display_buffer delay ms 500 0 5 second delay PCF8563 example using the hardware TWI Functions for Master Mode
459. or the step up circuit unsigned char crt_source 3 adjusts the amount of current from the constant current source in the internal op amplififier circuit APO AP2 bits unsigned char vcix2 3 adjusts the VCIX2 voltage unsigned char vlcd63 4 adjusts the VLCD63 voltage unsigned char vcoml 5 adjusts the amplitude of the VcomL alternating drive voltage unsigned char vcomh 5 adjusts the amplitude of the VcomH voltage VcomH VLCD63 0 35 vcomh 0 01 V unsigned char frame freq 4 LCD frame frequency positive gamma control registers bits unsigned char pkp00 3 PKPOO PKPO2 positive gamma micro adj unsigned char pkpl0 3 PKP10 PKP12 positive gamma micro adj unsigned char pkp20 3 PKP20 PKP22 positive gamma micro adj unsigned char pkp30 3 PKP30 PKP32 positive gamma micro adj unsigned char pkp40 3 PKP40 PKP42 positive gamma micro adj unsigned char pkp50 3 PKP50 PKP52 positive gamma micro adj unsigned char prp00 3 PRPOO PRPO2 positive gamma gradient adj unsigned char prpl10 3 PRP10 PRP12 positive gamma gradient adj unsigned char vrp00 4 VRPOO VRPO3 positive gamma amplification adj unsigned char vrpl0 5 VRP10O VRP14 positive gamma amplification adj 1998 2012 HP InfoTech S R L Page 250 CodeVisionAVR negative gamma control registers bits
460. otal E DSTACK Func 24 Sample program Use a STK600 ds STK600 RC100X 1 The STK600 prog in the Tools Pr Code Navigator B S CodeVisionavR E Bi Project usart S Notes usart c B Fal Headers stdio h stdara h A ioh xmegal 28a1 h xmstruct h xmbits_al h stdint h stdbool h B Errors I 1998 2012 HP InfoTech S R L Page 16 CodeVisionAVR Once docked the window will become a tabbed page SX CodeVisionAVR C cvavr2 examples atxmega USARTCO usart File Edit Search View Project Tools Settings Help bBeEeS HP ECHEOMRAS gh H gp MM u i M y Code Navigator v 2 amp 9 eN S S CodeVisionAVR a G Bi Project usart Notes 1 07 usart c 2 S B Al Headers 3 U stdio h 4jjjS stdara h 5 A ioh 6j T xmegal28a1 h 7 2 BA xmstruct h Si 8 B xmbits_al h 9 B stdint h lt 10 2 11 T ee Code Information fe Code Navigator 12 ef F 7 13 M unction Call Tree 7E 14 E B f main 15 E DSTACK Func 0 Total 0 To undock a single tabbed page the bottom tab must be dragged with the mouse 1998 2012 HP InfoTech S R L Page 17 CodeVisionAVR A workspace window can be hidden by left clicking on its icon by pressing its 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 me
461. oth the hardware TWI and software bit banged C bus functions One of the following header files located in the INC subdirectory must be include d before using these functions e Im75_twi h for hardware TWI e 1m75 h for software bit banged C bus The appropriate header files for hardware TWI twi h or twix h or software bit banged C bus i2c h functions prototypes are automatically include d with the Im75_twi h or Im75 h The Project Configure C Compiler Libraries I2C menu must be used for specifying the I O port allocation of the SCL and SDA signals along the bit rate of the SCL clock for bit banged IC bus not the hardware TWI communication Note For proper operation the LM75 Functions require the presence of 3 3k 4 7k pull up resistors to 5V 3 3V for XMEGA devices on the SCL and SDA signals 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 TWI hardware respectively I C bus must be initialized by calling the twi_master_init twi_init twi_master_init and Im75_twi_init for XMEGA devices respectively i2c_init functions 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 IC bus then the function must be called for each one specifying accordingly the function parameter chip Maximum 8 LM75 ch
462. other computer The following dialog will be displayed Internet License Deactivation Transfer In order to deactivate or transfer your license please enter the License ID below License ID 1 2345678 Paste from Clipboard You must enter the License ID that was supplied by HP InfoTech when the license was initially purchased This is necessary in order to prevent accidental license deactivation by unauthorized persons The License ID can be also pasted from the clipboard by pressing the Paste from Clipboard button After that the license can be deactivated by pressing the Deactivate button CodeVisionAVR will contact the Activation Server using the Internet After several seconds upon successful deactivation the following confirmation message will be displayed Information The license was successfully deactivated You may now activate it on any PC using your License ID If the Activation Server could not be contacted the following message will be displayed Information The license was deactivated but the Activation Server couldn t be contacted This may happen if a firewall is blocking CodeVisionAVR You will need to modify the firewall settings to fix this Please send the Removal Code WASEC7251 to HP InfoTech for confirmation 1998 2012 HP InfoTech S R L Page 495 CodeVisionAVR The Removal Code must be sent by e mail to HP InfoTech in order to co
463. ouse right clicking in the Editor window 1998 2012 HP InfoTech S R L Page 29 CodeVisionAVR 2 2 4 4 Jumping to a Specific Line Number in the Edited File You can go to a specific line number in the edited file by using the Edit Go to 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 edited 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 5 Printing a Text Selection Portions of text can be selected by dragging with the mouse The Edit Print Selection menu command or the g 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 6 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 avail
464. pe E femme ee hbo ea see lao AeA e e e e e al e e ll e Interrupt Level Disabled Interrupt Level Disabled OUT Register E GTD A ge Oo m enoa a a The Direction list box specifies if the pin associated with the I O port bit will be an input or output The input output data on the port pin can be Inverted by enabling this option The Limit Output Slew Rate option will enable slew rate limiting on the corresponding output pin The Output Pull Configuration list box allows to specify the corresponding configurations for the port pin Output configurations can be Totempole Wired OR Wired AND 1998 2012 HP InfoTech S R L Page 454 CodeVisionAVR Pull configurations can be e None e Bus keeper e Pull down if the pin is an input e Pull up if the pin is an input The Input Sense Configuration list box allows to specify how the pin configured as input can trigger port interrupts and events The Interrupt 0 respectively Interrupt 1 group boxes allow to individually enable disable port interrupt 0 respectively port interrupt 1 triggering by each pin For both Interrupt 0 and Interrupt 1 the enabled state and priority can be specified by the corresponding Interrupt Level list boxes The OUT group box allows to individually set the values of each bit of the port output register written during initialization The Input Output Ports initialization is performed by the void ports_init void functio
465. pecifier 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 long int for the i d u x X conversion type characters 1998 2012 HP InfoTech S R L Page 161 CodeVisionAVR The type_char conversion type character is used to specify the way the function argument will be treated The following conversion
466. pheral Interfaces sseessesineeeersseerreseerrssetrrnsttrrnnsttnnnntennnstennnneennnnnt 474 6 13 Setting the 1 Wire BUS encanta can eae 476 6 14 Setting the Two Wire Interfaces 0 00 0 eee eter reenter teeter erties ee teee ee teeeee teaser nanten rnant 477 6 15 Setting the Analog to Digital Converters ccceecieeeeeetteee erties ee eneeeeetiieeeeeetieeeeetneeeer 479 6 16 Setting the Digital to Analog Converters 0 ccceeieeeeeeeeeneeeeeeeneeeeetiieeeeetiieeeeeetieeeeetieeeee 486 6 17 Setting the Alphanumeric LCD 0 oe eee ree nee eran etna eeennee etna ee naaeenneeeea 490 6 18 Setting the Graphic UCD sessin an irena seiest bee OAA ATANA 491 6 19 Specifying the Project Information 0 cccececeeee ee eeteee erence ee tnneeeeeeieeeeetieeeeeteeeeseneeeereaa 492 T LICENSING System ssrin EAEE 493 7 1 Activating the LICENSE 0 00 eee tir eee tne eee ene ee ete ee ee teee ee tieee eee teeeeeteeessieeeeneaa 493 7 2 Transferring or Deactivating the LICENSE cece eeteee cette eter tenets ee teieeeeetieeeeetiieeeeeetieeeee 495 7 3 Upgrading the LICENSE 0 ei eee etter enter eerie ee eet e ee eet eee ee tieee ee teeeeenieeeeeenieeeertaa 496 8 License Agreement ernerik aaan an EAE A AREARE AAEE 498 8 1 S0iware LICENSE soiis A E AT T A 498 8 2 Liability Disclaino arenas aaa a E TEE TT 498 8 3 RESUICUONS e a E a E ened acer neared 498 8 4 Operating LICGNSC zesiran anana EEEE A eee de 498 8 5 Back Uprand Transfer caero
467. phics h where the high level graphic LCD functions are declared The following high level graphic LCD functions are available bool glcd_init GLCDINIT_t init_data initializes the graphic LCD controller and performs the following initializations of the graphic system e clears the LCD e sets the current plot coordinates to 0 0 e sets the current font used for displaying text as specified by the font member of the structure pointed by init_data sets the current background color to 0 sets the current foreground color to GLCD_MAXCOLOR_ sets the current transparency color to O for displays with more than 2 colors sets the current text horizontal justification to 1 pixel sets the current text vertical justification to 1 pixel sets the current line width to 1 pixel sets the transparent text mode display to OFF for LCDs with more than 2 colors sets the current line pattern to solid line sets the current line color to GLCD_MAXCOLOR_ sets the current fill pattern to solid sets the current fill color to GLCD_MAXCOLOR_ sets the pointers to the external memory read and write functions Parameter init_data points to a GLCDINIT_t structure that specifies various parameters used for initializing the LCD controller including the font used for displaying text If the font member of the structure pointed by init_data is NULL then the internal character generator if present of the LCD controller will be used for displaying text In this situation the
468. pixels e _GLCD_CTRL_ILI9325_ signals that the LCD controller type is llitek ILI9325 e _GLCD_CTRL_KS0108_ signals that the LCD controller type is Samsung KS0108 e _GLCD_CTRL_SED1335_ signals that the LCD controller type is Epson SED1335 e _GLCD_CTRL_SED1520_ signals that the LCD controller type is S MOS Systems SED1520 1998 2012 HP InfoTech S R L Page 193 CodeVisionAVR _GLCD_CTRL_SED1530_ signals that the LCD controller type is EPSON SED1520 _GLCD_CTRL_S1D13700_ signals that the LCD controller type is Epson S1D13700 _GLCD_CTRL_ST7565_ signals that the LCD controller type is Sitronix ST7565 _GLCD_CTRL_ST7920_ signals that the LCD controller type is Sitronix ST7920 _GLCD_CTRL_SPLC501_ signals that the LCD controller type is Sunplus SPLC501C _GLCD_CTRL_SSD1289_ signals that the LCD controller type is Solomon Systech SSD1289 _GLCD_CTRL_SSD1963_ signals that the LCD controller type is Solomon Systech SSD1963 _GLCD_CTRL_SSD2119_ signals that the LCD controller type is Solomon Systech SSD2119 _GLCD_CTRL_T6963_ signals that the LCD controller type is Toshiba T6963C _GLCD_CTRL_UC1701_ signals that the LCD controller type is UltraChip UC1701 _GLCD_CTRL_PCD8544_ signals that the LCD controller type is Philips PCD8544 _GLCD_CTRL_XG7100_ signals that the LCD controller type is Delcomp XG7100 Note The header file glcd_types h is automatically include d by gled h so there is no need to include it directly The same applies to the header file gra
469. played the background color at the pixel coordinates will be used instead e GLCD_PUTXOR copy a bitmap from memory to LCD performing a XOR with previous display data e GLCD_PUTOR copy a bitmap from memory to LCD performing an OR with previous display data e GLCD_PUTNOT copy a bitmap from memory to LCD performing a bit negation e GLCD_PUTAND copy a bitmap from memory to LCD performing an AND with previous display data Return values image size or 0 if the coordinate values are not valid Notes e The GLCD_PUTXOR GLCD_PUTOR GLCD_PUTNOT GLCD_PUTAND modes are supported only for displays with 2 colors monochrome e The GLCD_PUTTP mode is supported only for displays with more than 2 colors 1998 2012 HP InfoTech S R L Page 205 CodeVisionAVR unsigned long glcd_putimagex GLCDX_t left GLCDY_t top GL CDMEMADDR_t addr GLCDBLOCKMODE_t mode Displays a bitmap image located in external memory at specified coordinates Note External memory read must be implemented through an user defined function specified during initialization by gled_init Parameters left specifies the horizontal coordinate of the left top corner of the image top specifies the vertical coordinate of the left top corner of the image addr specifies the external memory address from which the image will be read mode specifies how the display operation must be performed e GLCD_PUTCOPY copy a bitmap from memory to LCD overwriting previous display data
470. ported 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 following Standard C Input Output functions are used for file access on MMC SD SD HC FLASH memory cards Before using any of these functions the logical drive that needs to be accessed must be mounted using the f_mount function and the appropriate file must be opened using the f_open function int feof FIL fp establishes if the end of file was reached during the last file access The fp pointer must point to a FIL type structure defined in the ff h header file that was previously initialized using the f_open function If the end of file was reached a non zero value 1 will be returned Otherwise the function will return 0 int ferror FIL fp establishes if an error occurred during the last file access The fp pointer must point to a FIL type structure defined in the ff h header file that was previously initialized using the f_open function If an error occurred a non zero value 1 will be returned Otherwise the function will return 0 int fgetc FIL fp reads a character from a file The fp pointer must po
471. py 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 8 4 Operating License You have the non exclusive right to use the program only by a single person on a single computer at a time You may physically transfer the program from one computer to another provided that the program is used only by a single person on a single computer at a time In group projects where multiple persons will use the program you must purchase an individual license for each member of the group Use over a local area network within the same locale is permitted provided that only a single person on a single computer uses the program at a time Use over a wide area network outside the same locale is strictly prohibited under any and all circumstances 1998 2012 HP InfoTech S R L Page 498 CodeVisionAVR 8 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 d
472. r bit 1 voltage booster bit 2 define ST7565 VOLT FOLLOWER_ON 1 lt lt 0 enable voltage follower define ST7565 VOLT REGULATOR _ON 1 lt lt 1 enable voltage regulator define ST7565 VOLT BOOSTER ON 1 lt lt 2 enable voltage booster E define ST7565 CMD VOLT REG V5 0x20 sets the V5 voltage regulator internal resistor ratio define ST7565 CMD ELECTRONIC VOLUME 0x81 sets the electronic volume register in order to control the V5 LCD drive voltage define ST7565 CMD SET DRIVING MODE 0xD2 used to set the LCD driving mode define ST7565 CMD RESET OxE2 resets the controller A detailed description of the above mentioned commands can be found in the ST7565 datasheet void st7565_setcontrast unsigned char contrast Controls the LCD contrast Parameter contrast sets the value of the V5 LCD drive voltage allowed range is 0 63 1998 2012 HP InfoTech S R L Page 257 CodeVisionAVR The glcd_st7565 h header file also contains the definition of the GLCDINIT_t type specific for the ST7565 controller used as parameter for the gled_init function typedef struct flash unsigned char font pointer to the function from external memory unsigned char readxmem pointer to the function to external memory void writexmem unsigned char lcd_bias 1 char char unsigned unsigned reve
473. r 20 Frequency 40 000000MHz Prescaler A is CikPer4 40000 000kHz2 Prescalers B C B 4 C 1 ClkPer2 10000 000kHz CikPer 10000 000kHz CIKCPU 10000 000kHz Lock Clock Configuration ClkPer Output Disabled z The Clock Source list box allows to select one of the following clocks for the PLL e 2MHz Internal RC Oscillator e 32MHz Internal RC Oscillator divided by 4 e External Oscillator or Clock For the the two internal RC oscillators we can find the specific calibration options that were explained previously The Multiplication Factor list box allows to select a factor between 1 and 31 by which the PLL will multiply its clock source frequency 1998 2012 HP InfoTech S R L Page 447 CodeVisionAVR If an External Oscillator or Clock is selected as PLL clock source we can find the specific options that were explained previously System Clocks Settings System Clock Source Phase Locked Loop v External Clock 8000 000 yA kHz External Clock Source Start up Time External Clock on XTAL1 6 CLK ka Phase Locked Loop Clock Source External Osc or Clock Z Multiplication Factor 4 X Frequency 32 000000MHz Prescaler 1 7 ClkPer4 32000 000kHz Prescalers B C B 4 Gal ClkPer2 8000 000kHz ClkPer 8000 000kHz CIkCPU 8000 000kHz2 External Clock Source Failure Monitor Lock Clock Configuration ClkPer Output Disabled A The System Clocks in
474. r 2 bytes_cluster specifies the number of bytes allocated for one cluster Return values FR_OK success FR_INVALID_DRIVE the drive number is invalid FR_INVALID_ PARAMETER the number_fats or bytes_cluster parameters are not valid FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_WRITE_PROTECTED the media in the drive is write protected FR_MKFS_ABORTED the formatted disk size is too small or the bytes_cluster parameter is not correct for the disk size 1998 2012 HP InfoTech S R L Page 334 CodeVisionAVR 4 22 Peripheral Chips Functions The CodeVisionAVR C Compiler has a rich set of library functions for accessing a large variety of peripheral chips using the C TWI 1 Wire and SPI buses 4 22 1 Philips PCF8563 Real Time Clock Functions These functions are intended for easy interfacing between C programs and the PCF8563 IC bus real time clock RTC using both the hardware TWI and software bit banged IC bus functions One of the following header files located in the INC subdirectory must be include d before using these functions e pcf8563_twi h for hardware TWI e pcf8563 h for software bit banged C bus The appropriate header files for hardware TWI twi h or twix h or software bit banged C bus i2c h functio
475. r 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 2012 HP InfoTech S R L Page 400 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 Notes e Depending of the used AVR chip some of these options may not be present e Some AVR chips may have additional timers which can be configured the same way as described above By selecting the Watchdog tab you can configure the watchdog timer Timers Counters Settings Timer3 Timer4 Timer Watchdog 4 v Watchdog Timer Enabled Oscillator Prescaler OSC 2k OSC 64k OSC 4k OSC 128k OSC 8k OSC 256k OSC 1Ek OSC 512k OSC 32k OSC 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 1998 2012 HP InfoTech S R L Page 401 CodeVisionAVR In case the watchdog timer is enabled you must include
476. r bi define SSD1963 C Write color bi define SSD1963 C Default initia values for cl bits order ts to display RAM in RGB order L BITS RGB 0 ts to display RAM in BGR order L BITS BGR 1 lization values for GLCDINIT t define SSD1963 D EFAULT_CTRL_C EVY NORM 0 No vertical reverse K 10000 external clock frequency kHz if _GLC TET LCD define SS SS SS SS define define define SS SS SS define define define default define SS elif G 4 3 48 TFT LCD define SS SS SS SS define define define SS SS SS define define define default define SS D MAXX 32 pixel cloc 0 amp amp _GLCD MAXY_ 3 5 320x240 display k frequency kHz 240 a D1963 DEFAULT TFT PIXE L CLK FREQ 6500 D1963 DEFAULT TFT HOR PULSE WIDTH 20 TFT HOR D1963 DEFAULT FRONT PORCH 20 D1963 DEFAULT TFT HOR BACK PORCH 48 al D1963 DEFAULT TFT R PULSE WIDTH 2 R D1963 DEFAULT FRONT PORCH 4 V TFT V TFT V mi m D1963 DEFAULT R BACK PORCH 16 tft24bit to 18 bit TF D1963 DEFAU T_TFT_DATA LCD MAXX 480 0x272 display pixel clock frequency D1963 DEFAULT TFT PIXE amp amp G ef _WIDTH SSD1963 TFT DATA WIDTH18 LCD MAXY 272 FREQ 9000 kHz 1 CLK D1963
477. raded CodeVisionAVR will be restarted 1998 2012 HP InfoTech S R L Page 496 CodeVisionAVR If there was an error contacting the Activation Server the following error message will be displayed x Failed to access the Activation Server This may happen if a firewall is blocking CodeVisionAVR You will need to modify the firewall settings to fix this Please contact HP InfoTech for technical support In this situation you will need to contact HP InfoTech in order to manually upgrade your license Note If you experience problems contacting the Activation Server please make sure that no firewall or antivirus program are blocking CodeVisionAVR to access the Internet 1998 2012 HP InfoTech S R L Page 497 CodeVisionAVR 8 License Agreement 8 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 2012 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 prod
478. ram 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 2012 HP InfoTech S R L Page 141 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 is 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 2012 HP InfoTech S R L Page 142 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 immedia
479. rce 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 Code Information tree branches can be expanded respectively collapsed by clicking on the respectively buttons 1998 2012 HP InfoTech S R L Page 79 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 6 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 f main E DSTACK Func 0 Total 0 3 f i 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 to
480. re is designed to work in conjunction with the Atmel STK500 STK600 AVRISP AVRISP MkII AVR Dragon JTAGICE MkII JTAGICE 3 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 and Graphic LCD modules e Philips IC bus e National Semiconductor LM75 Temperature Sensor e Philips PCF8563 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 TWI for both XMEGA and non XMEGA chips Power management Delays Gray code conversion MMC SD SD HC FLASH memory cards low level access FAT acces on MMC SD SD HC FLASH memory cards 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 functions e External memory access setup e Chip reset source identification e Input Output Port initialization e External Interrupts initialization e Timers Counte
481. reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_INVALID_ OBJECT the file was not opened with f_open FRESULT f_opendir DIR dj const char path opens an existing directory and initializes the DIR type structure that holds directory information which may be used by other FAT access functions The memory allocated for the DIR type structure may be de allocated at any time Parameters dj points to the DIR type structure that must be initialized path points to a RAM based NULL terminated char string that represents the path name for the directory to be opened Return values FR_OK success FR_NO_PATH couldn t find the path FR_INVALID_ NAME the directory name is invalid FR_INVALID_DRIVE the drive number is invalid FR_NOT_READY no disk access was possible due to missing media or other reason FR_DISK_ERR the function failed because of a physical disk access function failure FR_INT_ERR the function failed due to a wrong FAT structure or an internal error FR_NOT_ENABLED the logical drive was not mounted with f_mount FR_NO_FILESYSTENM there is no valid FAT partition on the disk 1998 2012 HP InfoTech S R L Page 317 CodeVisionAVR FRESULT f_readdir DIR dj FILINFO fno sequentially reads directory entries In order to read all the items in a directory this function
482. rent background color The ST7920 controller has a built in alphanumeric character font generator which can be used for displaying text over the graphics In order to take advantage of this capability the following high level functions compatible with the Alphanumeric LCDs were implemented void Icd_clear void Clears the text on the LCD and sets the text display position at row 0 and column 0 Note This function is equivalent to glcd_cleartext and was defined for compatibility void Icd_gotoxy unsigned char x unsigned char y Sets the current text 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 For displaying ASCII set characters c may take the values 0x02 0x7F These characters are displayed in a 8x16 pixel matrix For displaying a Chinese BIG5 character the function must be called twice first with the MSB of the character code then with the LSB Example display the Chinese BIG5 character with code 0xA140 lcd_putchar 0xA1 lcd putchar 0x40 The Chinese BIG5 characters may take the values 0xA140 0xD75F For displaying an user defined character the Icd_putchar function must be also called twice first with the parameter 0 then with the character code which may be 0 2 4 or 6 Example lcd putchar 0 lcd putchar 4 display the user defined character with code 4 Note
483. res in the display buffer sprintf display buffer t0 i uScC nt1 1 uscC t0 10 abs t0 10 Oxdf t1 10 abs t1 10 Oxdf display the temperatures led_clear lcd puts display buffer 1998 2012 HP InfoTech S R L Page 380 CodeVisionAVR 5 CodeWizardAVR Automatic Program Generator The CodeWizardAVR Automatic Program Generator allows you to easily write all the code needed for implementing the following functions e External memory access setup e Chip reset source identification e Input Output Port initialization e External Interrupts initialization e Timers Counters initialization e Watchdog Timer initialization e UART initialization and interrupt driven buffered serial communication e Analog Comparator initialization e ADC initialization e SPI Interface initialization e C Bus LM75 Temperature Sensor DS1621 Thermometer Thermostat 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 gt toolbar button The following dialog box will open amp CodeWizardAVR AVR Chip Type ATIO ATtiny ATmega FPSLIC xMEGA ET allowing to select between the AVR chip families for which automatic code generation will be per
484. ring sleep If we wish to use this feature we need to enter in sleep mode in maximum 4 clocks after the BODS bit is set in the MCUCR register But calling and executing the powersave function requires a longer time than than this so this example code will not function correctly unsigned char tmp sleep enable Disable brown out detection in sleep tmp MCUCR 1 lt lt BODS 1 lt lt BODSE MCUCR tmp MCUCR tmp amp 1 lt lt BODSE powersave Takes too long until the sleep instruction is executed This is the correct code unsigned char tmp Prepare the sleep in power save mode SMCR 1 lt lt SE 1 lt lt SM1 1 lt lt SMO Disable brown out detection in sleep tmp MCUCR 1 lt lt BODS 1 lt lt BODSE MCUCR tmp MCUCR tmp amp 1 lt lt BODSE Enter sleep mode asm Sleep 1998 2012 HP InfoTech S R L Page 298 CodeVisionAVR 4 19 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 d 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
485. riod 10 000000 4 ms Obtained 10ms 0 00 error Apply PER 4E1F h CNT 0 h CCA 10 h E Capture Ch amp Event Ch 0 gt Capture Ch A CCB h Capture Ch B Event Ch 1 gt Capture Ch B 0 CEC 10 h Capture Ch C Event Ch 2 gt Capture Ch C 0 CCD h E Capture Ch D Event Ch 3 gt Capture Ch D Timer Overflow Underflow Interrupt Disabled Timer Error Interrupt Disabled z Compare Capture 4 Interrupt Disabled Compare Capture B Interrupt Disabled T Compare Capture C Interrupt Disabled z Compare Capture D Interrupt Disabled Z The clock source can be the Peripheral Clock divided by a factor between 1 and 1024 or an event from Event Channels 0 to 7 The Resolution list box allows to select one of the following options e 16Bit e 16Bit with High Resolution Extension enabled e 8BBit 1998 2012 HP InfoTech S R L Page 457 CodeVisionAVR The Mode list box allows to select one of the following Timer Counter operating modes e Normal Operation Frequency Waveform Generation Single Slope Pulse Width Modulation PWM Generation Dual Slope PWM Generation In Normal operating mode the timer can capture an event specified by the Capture Event Action option The Capture Event Source option specifies the capture source for Capture Channel A CCA The event sources for the rest of the capture channels CCB CCC and CCD are the next Event Cha
486. rite data i2c_stop 10ms delay to complete the write operation delay ms 10 void main void unsigned char i initialize the I C bus 2G ini t 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 2012 HP InfoTech S R L Page 292 CodeVisionAVR 4 17 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 d 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 XMEGA 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
487. roject Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line void main void unsigned char hour min sec day month unsigned int year initialize the LCD 2 rows by 16 columns led_init 16 initialize the bit banged I2C functions i2c_init initialize the RTC Timer interrupt enabled Alarm interrupt enabled CLKOUT frequency 1Hz Timer clock frequency 1Hz rtc_ini t RTC_TIE ON RTC_ATE ON RTC_CLKOUT_1 RTC_TIMER CLK 1 rtc_set_time 12 0 0 set time 12 00 00 rtc_set_date 1 2 2011 set date 1 02 2011 display the time and date continuously while 1 read the time from the RTC rtc_get_time amp hour amp min amp Sec read the date from the RTC rtc_get_ date amp day amp month amp year 1998 2012 HP InfoTech S R L Page 340 CodeVisionAVR display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec led_clear lcd puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month year lcd puts display buffer delay_ms 500 0 5 second delay 1998 2012 HP InfoTech S
488. rototypes for the non local jump functions are placed in the file setjmp h located in the INC subdirectory This file must be include d 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
489. rove speed it is recommended to use the 256 color mode if possible e The gled_ili9325 h header file is automatically included when the main gled h header file is included Therefore there is no need to explicitly include gled_ili9325 h e The EXAMPLES Graphic LCD ILI9325 directory contains fully functional code samples that may be used as references for ILI9325 initialization and usage 1998 2012 HP InfoTech S R L Page 221 CodeVisionAVR 4 12 2 Graphic LCD Functions Specific to the PCD8544 Controller In order to take full advantage of the PCD8544 controller s features the following specific functions declared in the glcd_pcd8544 h header file were implemented void pcd8544_wrcemd unsigned char cmd Writes a command to the PCD8544 controller Parameter cmd command to be sent to the controller This command may take one of the values defined in the following macros from the glcd_pcd8544 h header file define PCD8544 FUNCTION SET 0x20 Function set horizontal addressing Puts controller in power down mode must be combined with PCD8544 FUNCTION SET define PC D8544 POWER DOWN 0x04 Use extended instruction set must be combined with PCD8544 FUNCTION SET define PCD8544 EXT_INST 0x01 define PCD8544 DISPLAY BLANK 0x08 Sets display blank define PCD8544 DISPLAY NORMAL 0x0C Sets display normal mode define PCD8544 DISPLAY ALL ON 0x09 Sets all display segments on define PC
490. rs A pop up hint with the members list will show like in the example below structl al bi ci The user can select the member to be inserted in the text at the cursor position by using the arrow keys respectively 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 11 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
491. rs initialization e Watchdog Timer initialization e UART USART initialization and interrupt driven buffered serial communication e Analog Comparator initialization e ADC and DAC initialization e SPI Interface initialization e Two Wire Interface initialization e CAN Interface initialization e C Bus LM75 Temperature Sensor DS1621 Thermometer Thermostat and PCF8563 PCF8583 DS1302 DS1307 Real Time Clocks initialization e 1 Wire Bus and DS1820 DS18S20 Temperature Sensors initialization e Alphanumeric and graphic LCD module initialization 1998 2012 HP InfoTech S R L Page 11 CodeVisionAVR This product is Copyright 1998 2012 Pavel Haiduc and HP InfoTech S R L all rights reserved The MMC SD SD HC and FAT File System libraries are based on the FatFS open source project from http elm chan org Copyright 2006 2009 ChaN all rights reserved 1 1 Credits The HP InfoTech team wishes to thank e Mr Jack Tidwell for his great help in the implementation of the floating point routines e Mr Yuri G Salov for his excellent work in improving the Mathematical Functions Library e Mr Olivier Wuillemin and Mr Franc Marx for their help in beta testing e Mr Lee H Theusch for his support in improving the compiler e Mr ChaN from Electronic Lives Mfg http elm chan org for the open source MMC SD SD HC FLASH Memory Card Driver and FAT File System functions 1998 2012 HP InfoTech S R L Page 12 CodeVisionAVR
492. rsave 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 2012 HP InfoTech S R L Page 297 CodeVisionAVR void extended_standby void this function puts the AVR chip in the extended standby mode Prior to using this function the sleep_enable function must be invoked to allow entering the low power consumption modes This mode is similar to the powersave mode with the exception that the external clock oscillator keeps on running Consult the Atmel Data Sheet for the particular chip that you use in order to see if the standby mode is available for it Note There are specific situations where the power management functions can t be used because of the timing limitations For example the ATmega168P chip has a feature which is not available in ATmega168 Brown Out Detection disable du
493. rse x 1 rev132_x0 1 char char nsigned nsigned reverse y l volt_reg v5 nsigned char driving_mode nsigned char GLCDINIT t lcd_contrast default font after initialization used for reading a byte GLCDMEMADDR t addr used for writing a byte GLCDMEMADDR t addr unsigned char data The following macros are defined for initializing the members of the GLCDINIT_t structure values used for led bias initia define ST7565 LCD BIAS 19 0 se define ST7565 LCD BIAS 17 1 se values used for reverse x ini ti define ST7565 RI t EVX_NORM 0 set and se and R 1 EV define ST7565_REVX_R values used for rev132_x0 initi 0 LCD bias ratio low 1 LCD bias ratio high reverse display horizontally ADC set to 1 for displays that use reversed RAM column address reverse_x 1 driver and the pixel with x 0 is connected to column driver 132 reverse display vertically COM 3 set V5 voltage regulator internal resistor ratio 0 7 2 2 set LCD driving mode 0O mode 1 1 mode 2 2 mode 3 3 mode 4 5 LCD contrast voltage 0 63 lization ts LCD bias drive ratio 1 9 1 8 1 7 ts LCD bias drive ratio 1 7 1 6 1 5 alization relationship between RAM column address display driver normal ADC 0 relationship between RAM column address effective only when reverse x 1 de
494. rupt Compare Match B Interrupt Timer Value O h Compare 4 80 h CompareB 99 h Clock Source specifies the timer counter 2 clock pulse source Clock Value specifies the timer counter 2 clock frequency Mode specifies if the timer counter 2 functioning mode 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 1998 2012 HP InfoTech S R L Page 398 CodeVisionAVR 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 Note Depending of the used AVR chip some of these options may not be present For more information you must consult the correspon
495. s rae ac 1998 2012 HP InfoTech S R L Page 319 CodeVisionAVR if res f opendir amp directory path FR_OK whil res f _readdir amp directory amp file info FR_OK amp amp file info fname 0 display file directory name and associated information printf Sc cSc c c S02u S02u Su 02u 02u 02u 91u s s r n file info fattrib amp AM DIR D file info fattrib amp AM RDO R file info fattrib amp AM HID H file info fattrib amp AM SYS S file info fattrib amp AM ARC A file info fdate amp 0x1F file info fdate gt gt 5 amp OXF file info fdate gt gt 9 1980 file info ftime gt gt 11 file_info ftime gt gt 5 amp Ox3F file info ftime amp OxF lt lt 1 file info fsize path file info fname if file info fattrib amp AM DIR it s a subdirectory make sure to skip past and when recursing if file info fname 0 i strlen path append the subdirectory name to the path if path i 1 strceatf path strcat path file info fname scan subdirectory res directory_scan path restore the old path name path i 0 remove any eventual from the end of the path i gt if path i path i 0 stop if an error occured if res FR_OK break return res void main void F
496. s use the parallel printer port The following choices are available through the Printer Port radio group box e LPT1 at base address 378h e LPT2 at base address 278h e LPT3 at base address 3BCh amp Programmer Settings AVA Chip Programmer Type Kanda Systems STK200 300 Printer Port LPT1 378h v Delay Multiplier 1 4 v ATmegal69 CKDIV8 Fuse Warning X Cancel Help 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 2012 HP InfoTech S R L Page 96 CodeVisionAVR The STK500 AVRISP and AVRProg programmers use the RS232C serial communication port which can be specified using the Communication Port list box amp amp Programmer Settings Ez AVR Chip Programmer Type Atmel STK500 4VRISP Communication Port COM2 v ATmegal69 CKDIVS Fuse Warning x Cancel The Atmel AVRISP MkII AVR Dragon JTAGICE MkII and JTAGICE 3 use the USB connection for communication with the PC Usage of these programmers requires the Atmel s AVR Studio 5 1 or la
497. s an user defined 8x8 pixel fill pattern from FLASH used by the glcd_bar and gicd_barrel functions and the fill color Parameters pattern points to an 8 byte array that holds the fill pattern color specifies the current color used by the filling functions 1998 2012 HP InfoTech S R L Page 211 CodeVisionAVR void glcd_setfille eeprom unsigned char pattern GLCDCOL_t color Sets an user defined 8x8 pixel fill pattern from EEPROM used by the glcd_bar and gicd_barrel functions and the fill color Parameters pattern points to an 8 byte array that holds the fill pattern color specifies the current color used by the filling functions void glicd_setfillcolor GLCDCOL_t color Sets the fill color Parameters color specifies the current color used by the filling functions GLCDCOL_t glicd_getfillcolor void Returns the current fill color used by the filling functions void glcd_bar GLCDX_t left GLCDY_t top GLCDX_t right GLCDY_t bottom Draws a filled in rectangular bar using absolute coordinates without drawing an outline The bar is filled using the current fill pattern and fill color Parameters left specifies the horizontal coordinate of the left top corner of the bar top specifies the vertical coordinate of the left top corner of the bar right specifies the horizontal coordinate of the right bottom corner of the bar bottom specifies the vertical coordinate of the right bottom corner of the bar void g
498. s and the DS1621 C bus thermometer thermostat using both the hardware TWI and software bit banged C bus functions One of the following header files located in the INC subdirectory must be include d before using these functions e ds1621_twi h for hardware TWI e ds1621 h for software bit banged C bus The appropriate header files for hardware TWI twi h or twix h or software bit banged C bus i2c h functions prototypes are automatically include d with the ds1621_twi h or ds1621 h The Project Configure C Compiler Libraries I2C menu must be used for specifying the I O port allocation of the SCL and SDA signals along the bit rate of the SCL clock for bit banged I C bus not the hardware TWI communication Note For proper operation the DS1621 Functions require the presence of 3 3k 4 7k pull up resistors to 5V 3 3V for XMEGA devices on the SCL and SDA signals The DS1621 Functions are void ds1621_init unsigned char chip signed char tlow signed char thigh unsigned char pol this function initializes the DS1621 chip Before calling this function the TWI hardware respectively C bus must be initialized by calling the twi_master_init twi_init twi_master_init and ds1621_twi_init for XMEGA devices respectively i2c_init functions 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 re bus then the function must be called for each one
499. s the byte to be transmitted to the master The function will return the byte received from the master The SPI beeing operated in polled mode this function will be blocking as the state of the SPIF flag from the STATUS register will be tested in an endless loop until one byte will be transmitted received In order to prevent such situations it is recommended to enable the SPI Interrupt The CodeWizardAVR will then generate the spim_isr SPI interrupt service routine where m is the lowercase suffix of the I O port where the SPI is implemented Inside this function the received data will be processed only when its received and new data will be prepared to be transmitted without blocking the execution of the rest of the application 1998 2012 HP InfoTech S R L Page 475 CodeVisionAVR 6 13 Setting the 1 Wire Bus The 1 Wire Protocol Functions for the XMEGA chips can be configured by clicking on the 1 Wire te node of the CodeWizardAVR selection tree The following settings are available 1 Wire Bus Interface Settings V Enable 1 Wire Bus Interface Support Data Connection 1 0 Port PORTA Bit 6 D51820 D518520 Enabled e Enable 1 Wire Bus Interface Support allows the activation of the 1 Wire Protocol Functions e I O Port and Bit specify in Data Connection the port and bit used for 1 Wire bus communication e DS1820 DS18S20 Enabled check box activates the generation of support code for accessing the DS18
500. s to specify the number of characters per line supported by the LCD module The connections between the LCD module and the AVR I O ports can be specified individually for each signal in the Connections group box 1998 2012 HP InfoTech S R L Page 432 CodeVisionAVR 5 20 Setting the Graphic LCD The I O port allocation for the Graphic LCD Functions can be configured by clicking on the Graphic LCD node of the CodeWizardAVR selection tree ExtemalIRQ Timers USARTO USART1 Analog Comparator ADC SPI 2c 1 wire TWI 2C Alphanumeric LCD Bit Banged Project Information Chip EstemalSRAM Ports Graphic LCD Display Type SED1335 320x240 CS Active low Z Use Image Storage in External Memory Use Internal Font Only Data Control LCD Module AVR DBO PORTA Bit 0 v DBI PORTA Bit l v DB2 PORTA Bit 2 v DB3 PORTA Bit 3 v DB4 PORTA Bit 4 v DB5 PORTA v Bit 5 DBE PORTA Bit 6 v DB PORTA vy Bit The Display Type list box allows to select the graphic controller type and LCD resolution The Use Image Storage in External Memory check box specifies if additional code will be generated for functions needed to read or write data from external memory used for graphic image storage The Use Internal Font Only check box specifies for the gled_init function that only the internal character generator of the co
501. s 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 Code 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 2012 HP InfoTech S R L Page 36 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 2012 HP InfoTech S R L Page 37 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 button on the toolbar A dialog box appears in which yo
502. se amp file FR_OK printf File s closed OK r n path else an error occured display it and stop error res open the file in read mode if res f open amp file path FA READ FR_OK printf File s opened OK r n path else an error occured display it and stop error res read and display the file s content make sure to leave space for a NULL terminator in the buffer so maximum sizeof buffer 1 bytes can be read if res f read amp file buffer sizeof buffer 1 amp nbytes FR_OK printf u bytes read r n nbytes NULL terminate the char string in the buffer buffer nbytes 1 NULL display the buffer contents printf Read text Ss r n buffer else an error occured display it and stop error res close the file if res f close amp file FR_OK printf File s closed OK r n path else an error occured display it and stop error res display file s attribute size and time stamp display status path change file s attributes set the file to be Read Only LE res f_chmod path AM_RDO AM_RDO FR_OK printf Read Only attribute set OK r n path else an error occured display it and stop error res 1998 2012 HP InfoTech S R L Page 331 CodeVisionAVR change file s time stamp define DAY 6 define MONTH define YEAR define SECOND 0
503. 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 7 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 2012 HP InfoTech S R L Page 116 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 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
504. sed this option must signal to the compiler if the variable initialization with 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 1998 2012 HP InfoTech S R L Page 50 CodeVisionAVR When your program runs correctly you may disable the placement of these strings in order to reduce code size 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 1998 20
505. ses in the situation when the usage of the CD card detect signal is disabled in the in the Project Configure C Compiler Libraries MMC SD SD HC Card menu e If the function is called before disk_initialize it will automatically first perform the initialization including the SPI bus interface and I O ports of the physical drive 1998 2012 HP InfoTech S R L Page 303 CodeVisionAVR unsigned char disk_status unsigned char drv returns the current disk status of a physical drive located on a MMC SD or SD HC card Parameters drv represents the drive number Drive numbering starts with 0 Return value The function returns 1 byte containing the disk status flags specified by the following macros defined in sdeard h e STA_NOINIT 0x01 bit 0 of function result Disk drive not initialized This flag is set after microcontroller reset card removal or when the disk_initialize function has failed e STA_NODISK 0x02 bit 1 of function result This flag is set if no card is inserted in the socket Note the STA_NOINIT flag is also set in this situation e STA_PROTECT 0x04 bit 2 of function result Card is write protected If the STA_NODISK flag is also set the STA_PROTECT flag is not valid On success the function returns 0 which means all status flags are reset Note For the MMC SD SD HC card driver using the SPI interface the drv parameter must be always 0 otherwise the function will return with the STA_NOINIT fla
506. signal triggered by Event Channel 0 will be fed to the bit 7 of PORTC PORTD or PORTE Additional Event System specific options are present in the CodeWizardAVR configuration pages for each XMEGA peripheral The Event System initialization is performed by the void event_system_init void function generated by the CodeWizardAVR 1998 2012 HP InfoTech S R L Page 453 CodeVisionAVR 6 5 Setting the Input Output Ports The XMEGA Input Output Ports can be configured by clicking on the Ports and PORTn ios nodes of the CodeWizardAVR selection tree The following options are available for configuring each bit of an I O port PORTA Settings Bits 0 3 Bits 4 7 Bit 0 Direction Input X Output Pull Configuration Input Sense Configuration Bit 1 Output Pull Configuration Input Sense Configuration Direction Input C inverted Limit Output Slew Rate Z Totempole No z 3 Sense both edges Inverted Limit Output Slew Rate 5 Totempole No 5 Sense both edges Bit 2 Direction Input linverted Limit Output Slew Rate Output Pull Configuration Totempole No z Input Sense Configuration Sense both edges 7 Bit 3 a Direction Input Inverted Limit Dutput Slew Rate Output Pull Configuration Totempole No 5 Input Sense Configuration Sense both edges 7 Interrupt 0 Interrupt 1 E s
507. sing the other C Functions unsigned char i2c_start void issues a START condition Returns 1 if bus is free or 0 if the 1 C bus is busy void i2c_stop void issues a STOP condition unsigned char i2c_read unsigned char ack reads a byte from the bus The ack parameter specifies if an acknowledgement is to be issued after the byte was read Set ack to 0 for no acknowledgement or 1 for acknowledgement 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 include the I2C bus functions The I2C bus connections and bit rate must be specified in the Project Configure C Compiler Libraries I2C menu include lt i2c h gt function declaration for delay ms include lt delay h gt define EEPROM BUS ADDRESS 0xa0 read a byte from the EEPROM unsigned char eeprom read unsigned char address unsigned char data i2c_start i2c_ write EEPROM BUS ADDRESS i2c_write address i2c_start i2c_ write EEPROM BUS ADDRESS 1 data i2c read 0 i2c_stop return data 1998 2012 HP InfoTech S R L Page 291 CodeVisionAVR 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 w
508. sistor ratio define UC1701 DEFAULT VLCD RES 6 H c ast EFAULT CONTRAST 7 mperature compensation coefficient EFAULT LCD TEMP COMP UC1701 LCD TEMP COMP 011 D default contr define UC1701 D D default LCD define UC1701_ The detailed description of the above mentioned initialization parameters can be found in the UC1701 datasheet Notes e The gled_uc1701 h header file is automatically included when the main gled h header file is included Therefore there is no need to explicitly include gled_uc1701 h 1998 2012 HP InfoTech S R L Page 270 CodeVisionAVR 4 13 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 d before using the functions The 1 Wire functions must be configured by specifying the I O port and bit used for communication through the 1 Wire protocol This is accomplished in the Project Configure C Compiler Libraries 1 Wire menu e the Enable 1 Wire Bus Interface Support option must be activated e the I O Port and Bit must be specified in Data Connection Note For compatibility with proj
509. ster index void ssd2119_wrdata unsigned short data Writes data to the SSD2119 controller s Graphic Display RAM Parameters data to be written unsigned short ssd2119_rddata void Reads data from the SSD2119 controller s Graphic Display RAM 1998 2012 HP InfoTech S R L Page 249 CodeVisionAVR The gled_ssd2119 h header file also contains the definition of the GLCDINIT_t type specific for the SSD2119 controller used as parameter for the gled_init function typedef struct flash unsigned char font default font after initialization pointer to the function used for reading a byte from external memory unsigned char readxmem GLCDMEMADDR t addr pointer to the function used for writing a byte to external memory void writexmem GLCDMEMADDR t addr unsigned char data unsigned char reverse x 1 reverse display horizontally unsigned char reverse y 1 reverse display vertically unsigned char first_out_gate 1 selects the first output gate GD bit of Driver Output Control register 0 Gate 1 on left side of display 1 Gate 2 on left side of display unsigned char cl bits order 1 selects the color bits writing order to the display RAM 0 gt RGB 1 gt BGR power control registers bits unsigned char stepup factor 3 step up factor of the step up Circuit see BTO BT2 bits in the datasheet unsigned char stepup_cycle 4 controls the cycle f
510. t typedef unsigned char byte 1998 2012 HP InfoTech S R L Page 187 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 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
511. t RIOD OxB5 Get RIOD OxB6 Set bet and RIOD OxB7 Get bet and SSD1963 minimal revision C u C u D panel mode and tion D panel mode and tion front porch settings front porch settings the vert blanking interval ween last scan line next LFRAME pulse the vert blanking interval ween last scan line next LFRAME pulse 1998 2012 HP InfoTech S R L Page 241 CodeVisionAVR define SSD1963 CMD S define SSD1963 CMD define SSD1963 CMD S GPIO CONF 0xB8 Set GPIO configuration GPIO CONF 0xB9 Get GPIO configuration GPIO VAL OxBA Write data to the GPIOs configured as outputs GPIO STATUS 0xBB Read data from the GPIOs configured as inputs POST PROC OxBC Set the image post processor POST PROC OxBD Get the image post processor PWM CONF OxBE Set PWM configuration PWM CONF OxBF Get PWM configuration CD GENO OxCO Set the rise fall period and toggling properties of LCD signal generator 0 define SSD1963 CMD GET LCD GENO OxCl Get the rise fall period and toggling properties of LCD signal generator 0 define SSD1963 CMD SET LCD GEN1 0xC2 Set the rise fall period and toggling properties of LCD signal generator 1 define SSD1963 CMD GET LCD GEN1 0xC3 Get the rise fall period and toggling properties of LCD signal generator 1 define SSD1963 CMD SET LCD GEN2 0xC4 Set the rise fall period and togg
512. t TWIC_TWIM vect void twic_master_ isr void twi_master int handler amp twi_master TWID slave receive and transmit buffers unsigned char twi_slave rx buffer 16 data to be transmitted to the master unsigned char test _data TWI test structure that holds information used by the TWID slave for performing a TWI bus transaction TWI SLAVE INFO t twi slave TWID slave interrupt service routine interrupt TWID _TWIS vect void twic_slave_isr void twi_slave int handler amp twi_slave TWID slave transaction processing function void twi_slave_trans void read the received data from the buffer and output it to the LEDs on PORTA PORTA OUT twi_slave rx buffer twi_slave rx_ index prepare to transmit the contents of the test _data array to the master initialize the number of bytes to transmit only once at the beginning of the transmission if twi_slave bytes to _tx 0 twi_slave bytes to_tx sizeof test data if needed the function twi_slave halt amp twi_slave can be called here in order to halt the transaction by the slave void main void unsigned char switches received data from the slave unsigned char rx data sizeof test_ data initialize PORTA as inverted outputs used for driving LEDs PORTA OUT 0x00 all LEDs are initially off PORTA DIR OxXFF 1998 2012 HP
513. t directive Example The program will be optimized for maximum speed pragma optsize Place your program functions here Now the program will be optimized for the setting specified in the project configuration pragma optsize default Place your program functions here 1998 2012 HP InfoTech S R L Page 128 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_irqg 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 SR push r30 endasm Fl Q place the C code here gt sses now restore SREG R31 and R30 asm pop r30 out SREG r30 pop r31 pop r30 endasm poe 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
514. t including the horizontal justification Parameter str pointer to the literal char string GLCDX_t glcd_textwidthe eeprom char str Returns the text width in pixels of a NULL terminated literal char string located in EEPROM for the current font including the horizontal justification Parameter str pointer to the literal char string void glcd_transparent bool on Controls displaying text in transparent mode If this mode is enabled the background color of the area where the character is displayed is preserved otherwise the color specified by glcd_setbkcolor is used Parameter on enables or disables displaying text in transparent mode Note The glcd_transparent function is defined only for displays with more than 2 colors 1998 2012 HP InfoTech S R L Page 199 CodeVisionAVR void glcd_putcharxy GLCDX_t x GLCDY_t y char c Displays a character using the current font at the specified coordinates After the character is displayed the current horizontal pixel plot coordinate is increased to the next display position by the width of the character horizontal text justification If the new horizontal pixel plot coordinate will result outside the right display margin then the new horizontal coordinate will be set to 0 and the vertical pixel plot coordinate will be increased by the height of the font vertical text justification Parameters x specifies the horizontal coordinate of the left top corner of the
515. t 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 Par Passing check box allows enabling or disabling the generation of specific code for passing the last function parameter with a size of up to 4 bytes in the registers R26 R27 R24 and R25 Enabling this option allows a code size reduction of 3 4 for large projects It can be disabled in case of incompatibility with functions written fully in assembler for older version of the compiler 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
516. tal level of the Data Stack when the program is executed inside the function 1998 2012 HP InfoTech S R L Page 80 CodeVisionAVR 2 3 7 Closing a Project You can quit working with the current Project by using the File Close 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 2012 HP InfoTech S R L Page 81 CodeVisionAVR 2 4 Tools Using the Tools menu you can execute other programs without exiting the CodeVisionAVR IDE 2 4 1 The AVR Debugger The CodeVisionAVR C Compiler is designed to work along with the following debuggers from Atmel e AVR Studio 4 19 e AVR Studio 5 1 or later version e Atmel Studio 6 0 or later version The compiler will generate a COF object file that can be opened with the above mentioned programs allowing C source and assembly debbuging Before you can invoke the debugger you must first specify its location and file name using the Settings Debugger menu command r S Debugger Settings Debugger Atmel Studio 6 0 Directory and File
517. tely 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 supplied 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
518. ter software to be installed on the PC The Atmel AVR Dragon JTAGICE MkII and JTAGICE 3 can use two programming modes e JTAG e ISP Help These can be selected using the Programming Mode list box amp Programmer Settings 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 2012 HP InfoTech S R L Page 97 CodeVisionAVR 2 5 6 Serial Communication Terminal Setup The serial communication Terminal is configured using the Settings Terminal menu command co Terminal Settings Ex Handshaking Appearance Port COMI v Catt A None howe 25 A Baud rate 9600 x xon off m BpSels Columns 80 Data bits 9 DTR DSR LH e Append LF Stop bits 1 v On Reception Font a Parity re v On Transmission Emulation TTY X v Echo X cence 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 termin
519. ters The initial value for the CNT count 16 bit register can be specified in hexadecimal using the appropriate edit box The RTC can generate two types of interrupts e RTC Overflow Interrupt e RTC Compare Interrupt Each type of interrupt can be individually enabled and its priority set using the corresponding list boxes 1998 2012 HP InfoTech S R L Page 465 CodeVisionAVR The RTC initialization is performed by the void rtcxm_init void function generated by the CodeWizardAVR 1998 2012 HP InfoTech S R L Page 466 CodeVisionAVR 6 10 Setting the 32 Bit Real Time Counter and Battery Backup System The XMEGA 32 Bit Real Time Counter RTC32 and Battery Backup System can be configured by clicking on the RTC32 and Battery Backup D node of the CodeWizardAVR selection tree The following options are available 32 Bit Real Time Counter and Battery Backup System Settings v RTC32 Enabled 32 768 kHz External Oscillator Low Power Mode Requirements ATC32 Overflow Per 0 000 tjs RTC32 Compare Per 0 000 Al s Apply Clock Frequency 1 Hz X PER 0 h CNT 0 h COMP 0 h RTC32 Overflow Interrupt Disabled Z RTC32 Compare Interrupt Disabled z The RTC32 Enabled option allows to activate the operation the 32 Bit Real Time Counter and associated Battery Backup System The RTC32 can be clocked by a 1 Hz or 1024 Hz signal selected using the Clock Frequency list box This sig
520. tf t u i u xf8C n r i temp 10 abs temp s10 unsigned char ds1820_set_alarm unsigned char addr signed char temp_low signed char temp_high this function sets the low temp_low and high temp_high temperature alarms of the DS1820 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 the ATmega8515 port and bit used for the 1 Wire bus must be specified in the Project Configure C Compiler Libraries 1 Wire menu 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
521. the Project Configure C Compiler Libraries Alphanumeric LCD menu include lt alcd h gt include the prototype for sprintf include lt stdio h gt include the prototypes for the delay functions include lt delay h gt char display buffer 17 LCD display buffer for 1 line void main void unsigned char hour min sec week day day month year initialize the LCD 2 rows by 16 columns lcd_init 16 initialize the TWI in master mode with 100 kHz bit rate twi_master init 100 enable interrupts so that TWI can be used fasm sei initialize the RTC square wave output is disabled SQW OUT has logic state 0 rtc_init 0 0 0 rtc_set_time 12 0 0 set time 12 00 00 rtc_set_date 2 1 2 11 set date Tuesday 1 02 2011 1998 2012 HP InfoTech S R L Page 353 CodeVisionAVR display the time and date continuously while 1 read the time from the RTC rtc_get_time amp hour amp min amp Sec read the date from the RTC rtc_get_ date amp week day day amp month amp year display the time on the LCD sprintf display buffer Time 2d 02d 02d n hour min sec lcd_clear lcd puts display buffer display the date on the LCD sprintf display buffer Date 2d 02d d day month 2000 year lcd puts display buffer delay _ms 500 0 5 second delay DS1307 exampl
522. the Ctrl key when selecting in the Add File to Project dialog SK Add File To Project x Look in J MULTFILE emn I Name Date modified Type Size ne J exe 17 04 2008 12 19 File Folder Recent Places O link 17 04 2008 12 19 File Folder a i list 17 04 2008 12 19 File Folder dJ obj 17 04 2008 12 19 File Folder Desktop E FILE1 14 03 2001 03 15 C compiler source g 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 v Open Files of type C Compiler files c v 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 definitions and function declarations must be placed in header H files that will be include d as ne
523. the same as described above The UARTO USARTO will use the normal putchar and getchar functions In case of interrupt driven buffered communication VARTO USARTO will use the following variables rx_buffer0 rx_wr_index0 rx_rd_index0 rx_counter0 rx_buffer_overflow0 tx_buffer0 tx_wr_index0 tx_rd_index0 tx_counter0 The UART1 USART1 will use the putchar1 and getchar1 functions In case of interrupt driven buffered communication VART1 USART1 will use the following variables rx_buffer1 rx_wr_index1 rx_rd_index1 rx_counter1 rx_buffer_overflow1 tx_buffer1 tx_wr_index1 tx_rd_index1 tx_counter 1 All serial I O using functions declared in stdio h will be done using UARTO USARTO 1998 2012 HP InfoTech S R L Page 405 CodeVisionAVR 5 7 Setting the Analog Comparator The configuration of the Analog Comparator can be specified by clicking on the corresponding node gt of the CodeWizardAVR selection tree amp CodeWizardAVR test cwp x File Help 1 Wire LCD Bit Banged Project Information Chip Ports External IRQ Timers US Analog Comparator ADC 12c Analog Comparator Enabled Inputs AINO JAINIE gt Bandgap Voltage Reference Negative Input Multiplexer Inputs Hysterezis Gis 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
524. the smallest integer value of the floating point number x float ceil float x returns the largest integer value of the floating point number x float fmod float x float y returns the remainder of x divided by y float modf float x float ipart splits the floating point number x into integer and fractional components The fractional part of x is returned as a signed floating point number The integer part is stored as floating point number at ipart float Idexp float x int expn returns x 2 float frexp float x int expn returns the 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 2012 HP InfoTech S R L Page 170 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
525. the state of the folded blocks of lines for each edited source file 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 2012 HP InfoTech S R L Page 91 CodeVisionAVR 2 5 3 2 Editor Text Settings The following Editor settings can be established by clicking on the Text tab Editor Settings a General Test 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 MA Block Indent Size 4 WA 7 flesh char pflash flash int 0 9 8 jeeprom int peeprom eeprom int Fon Ip Courier New v Font Size 8 x m Default Text Color HB Window Text X 10 F void main void E 11 i Default Background Color C Window X 12 int Number 123 Br o 13 jint HexNumber 0x1FA7 Highlighted Text Color C Highl
526. ther 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 The function returns the number of outputed characters In order to reduce program code size there is the Project Configure C Compiler Code Generation s printf Features option It allows linking different versions of the printf and sprintf functions with only the features that are really required by the program The following s printf features are available e int the following conversion type characters are supported c s p i d u x X no width or precision specifiers are supported only the and flags are supported no input size modifiers are supported e int width the following conversion type characters are supported c s p i d u x X the width specifier is supported the precision specifier is not supported only the 0 and flags are supported no input size modifiers are supported e long width the following conversion type characters are supported c s p i d u x X the width specifier is supported the precision specifier is not supported only the 0 and flags are supported only the I input size modifier is supported e long width precision the following conversion type characters are supported c s p i d
527. thus reducing the power consumption of the chip The corresponding bits in the PIN registers will always read 0 in this case Some of this check boxes may not be present on all the AVR chips If the analog comparator interrupt is enabled the CodeWizardAVR will define the ana_comp_isr interrupt service routine 1998 2012 HP InfoTech S R L Page 407 CodeVisionAVR 5 8 Setting the Analog to Digital Converter Some AVR chips contain an Analog to Digital Converter ADC The ADC configuration can be specified by clicking on the Analog to Digital Converter Abe node of the CodeWizardAVR selection tree amp CodeWizardAVR test cwp File Help 1Wire LCD Bit Banged Project Information Chip Ports External IRQ Timers USI Analog Comparator ADC 12C v ADC Enabled Vv Use bits v Interrupt Noise Canceler vV Bipolar Input Volt Ref AVCC pin Clock 125 000 kHz Auto Trigger Source Free Running Automatically Scan Inputs v Enabled First 0 pA Last 7 2j Disable Digital Input Buffers 0 1 2 Aef3 456 Disable Digital Input Buffers 7 8 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 de
528. timing function disk timerproc the rest of the interrupt service routine VE aaa E 1998 2012 HP InfoTech S R L Page 302 CodeVisionAVR void main void unsigned char status initialize Timerl overflow interrupts in Mode 0 Normal TCCR1IA 0x00 clkio 1024 TCCRIB 1 lt lt CS12 1 lt lt CS10 timer overflow interrupts will occur with 100Hz frequency TCNTIH T1 INIT gt gt 8 TCNTIL T1_ INITS amp OXxFF enable Timerl overflow interrupt TIMSK 1 lt lt TOIE1 initialize the LCD 16 characters line led_init 16 globally enable interrupts fasm sei initialize SPI interface and card driver status disk initialize 0 clear the LCD lced_clear display disk initialization result on the LCD if status amp STA _NODISK lcd puts Card not present else if status amp STA _NOINIT lcd puts Disk init failed else if status amp STA PROTECT lcd puts Card write nprotected all status flags are 0 disk initialization OK else lcd puts Init OK wait 2 seconds delay ms 2000 the rest of the program IE saws RY while 1 E sega bool sdcard_present void is used for detecting the presence of a FLASH memory card inserted in the socket It returns true in this case Notes e This function must be called before performing memory card acces
529. ting any program files By selecting the Help Help Topics menu option by pressing the F1 key or by clicking on the 2 toolbar button the user can see the help topic that corresponds to the current CodeWizardAVR configuration menu The AVR peripheral that needs to be configured can be selected by clicking on the corresponding node of the CodeWizardAVR selection tree J CodeWizardAVR untitled cwp Project Information Chip fa External SRAM 10 Ports ny External Interrupts CL Timers Counters CO Watchdog Timer f USARTO f USART1 f USART2 f USART3 gt Analog Comparator Ane Analog to Digital Converter 238 Serial Peripheral Interface Iof Two Wire Interface F Bit Banged 12C Bus Interface Ast 1 Wire Bus Interface oa Bit Banged Peripherals CD Alphanumeric LCD Graphic LCD If program code was already generated and is available for display in the Program Preview window clicking on a peripheral node will position the cursor at the beginning of the initialization code for that peripheral 1998 2012 HP InfoTech S R L Page 385 CodeVisionAVR 5 1 Setting the AVR Chip Options The AVR chip options can be specified by clicking on the Chip node of the CodeWizardAVR selection tree a CodeWizardAVR test cwp File Help External IRQ Timers UART Analog Comparator ADC Spi 12C 1 Wire LCD Bit Banged Project Information External SRAM Ports Chip A
530. tiple 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 T usart c Select All a Invert Clear eec g K 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 2012 HP InfoTech S R L Page 35 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 Template
531. tor define UC1701 VOLT BOOSTER ON 1 lt lt 2 enable voltage booster 1998 2012 HP InfoTech S R L Page 268 CodeVisionAVR define UC1701 CMD VLCD RES 0x20 sets the VLCD voltage regulator internal resistor ratio define UC1701 CMD ELECTRONIC VOLUME 0x81 sets the electronic volume register in order to control the VLCD drive voltage T define UC1701 CMD ADV PGM CTRLO OxFA advanced program control 0 used to set LCD temperature compensation coefficient TC define UC1701 CMD RESET OxE2 resets the controller set cursor update mode when writing to display RAM reading from display RAM doesn t affect the column address register CA define UC1701 CMD CURSOR_UPDATE ON 0xE0 the column address CA will be incremented when writing to display RAM define UC1701 CMD CURSOR_UPDATE OFF OxEE the column address CA will not be incremented when writing to display RAM T A detailed description of the above mentioned commands can be found in the UC1701 datasheet void uc1701_setcontrast unsigned char contrast Controls the LCD contrast Parameter contrast sets the value of the VLCD drive voltage allowed range is 0 63 The gled_uc1701 h header file also contains the definition of the GLCDINIT_t type specific for the UC1701 controller used as parameter for the gled_init function typedef
532. tructure FATFS pfat number of free clusters on logical drive 0 unsigned long free clusters number of free kbytes on logical drive 0 unsigned long free kbytes root directory path for logical drive 0 char root _path 0 initialize Timerl overflow interrupts in Mode 0 Normal TCCR1IA 0x00 clkio 1024 TCCRIB 1 lt lt CS12 1 lt lt CS10 timer overflow interrupts will occur with 100Hz frequency TCNTIH T1 INIT gt gt 8 TCNTIL T1_ INITS amp OxFF enable Timerl overflow interrupt TIMSK 1 lt lt TOIE1 initialize the USARTO TX 8N1 Baud rate 19200 UCSROA 0 UCSROB 1 lt lt TXENO UCSROC 1 lt lt UCSZ01 1 lt lt UCSZ00 UBRROH BAUD_INIT gt gt 8 UBRROL BAUD_INIT amp 0xFF globally enable interrupts asm sei point to the FATFS structure that holds information for the logical drive 0 pfat amp fat mount logical drive 0 if res f mount 0 pfat FR_OK printf Logical drive 0 mounted OK r n else an error occured display it and stop error res 1998 2012 HP InfoTech S R L Page 324 CodeVisionAVR get the number of free clusters if res f_getfree root_path amp free clusters amp pfat FR_OK calculate the number of free bytes free kbytes free clusters cluster size in sectors pfat gt csize divide by 2 to obtain the sector size in
533. tructure struct local structure char a int b long c sl lt width gt el diz The space allocated to the structure in memory is equal to sum of the sizes of all the members 1998 2012 HP InfoTech S R L Page 114 CodeVisionAVR The same generic structure type can be declared in any memory type RAM FLASH or EEPROM Generic structure type struct my structure char a b inte O7 char d 30 e 10 char pp Global struc struct my struc ure located in RAM ure sr ct ct pointer located in RAM to the RAM located structure structure ptrsr amp sr Global pointer located in FLASH to the RAM located structure truct my structure flash ptrfsr amp sr Global pointer located in EEPROM to the RAM located structure truct my structure eeprom ptresr amp sr Global constant structure located in FLASH flash struct my structure sf 0 0 0 0 0 0 Global pointer located in RAM to the FLASH located structure flash struct my structure ptrsf amp sf Global pointer located in FLASH to the FLASH located structure flash struct my structure flash ptrfsf amp sf T Global pointer located in EEPROM to the FLASH located structure flash struct my_structure eeprom ptresf amp sf Global constant structure located in EEP
534. ttribute AM_ARC Archive attribute AM_MASK Mask of all defined attributes e The DIR type structure is used for holding directory information returned by the f_opendir and f_readdir functions typedef struct _DIR_ FATFS fs Pointer to the owner file system object Af unsigned short id Owner file system mount ID unsigned short index Current read write index number unsigned long sclust Table start cluster 0 Static table unsigned long clust Current cluster unsigned long sect Current sector unsigned char dir Pointer to the current SFN entry in the win unsigned char fn Pointer to the SFN in out file 8 ext 3 status 1 DIR 1998 2012 HP InfoTech S R L Page 311 CodeVisionAVR The FAT access functions require the presence of a Real Time Clock in the system in order to be able to set the time stamp of files or directories The following pointers to functions that allow reading the time and date from the Real Time Clock are declared in the ff h header file void prtc_get_time unsigned char hour unsigned char min unsigned char sec pointer to a Real Time Clock function used for reading time void prtc_get_date unsigned char date unsigned char month unsigned int year pointer to a Real Time Clock function used for reading date On program startup these pointers need to be initialized to point to the appropriate RTC fun
535. 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 int sprintf char str char flash fmtstr arg1 arg2 this function is identical to printf except that the formatted text is placed in the null terminated character string str The function returns the number of outputed characters int snprintf char str unsigned char size char flash fmtstr arg1 arg2 for the TINY memory model int snprintf char str unsigned int size char flash fmtstr arg1 arg2 for the o
536. u S i u xf8C n r i temp 10 abs temp 10 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 DS1820 DS18S20 data sheet for more information 1998 2012 HP InfoTech S R L Page 365 CodeVisionAVR 4 22 7 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 d before using the functions The 1 Wire bus functions prototypes are automatically include d with the ds18b20 h The 1 Wire functions must be configured by specifying the I O port and bit used for communication through the 1 Wire protocol This is accomplished in the Project Configure C Compiler Libraries 1 Wire menu e the Enable 1 Wire Bus Interface Support option must be activated e the I O Port and Bit must be specified in Data Connection 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 sens
537. u must select File Type Project and press the OK button B 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 new 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 2012 HP InfoTech S R L Page 38 CodeVisionAVR You must specify the new Project file name and its location SK Create New Project x Save in d examples v E F a flv P Name Date modified Type Size FZ Ji 2USART_LCD Recent Places M ADC8535 a Jy AVR134 Jb C_ASM Desktop 018820 S D B Ds1820 J D51990 Pavel JJ EEPROM 7 J KEYPAD Hki 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 2012 HP InfoTech S R L Page 39 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 Fi Open You must select the file name of the Project you wish to open Lookin J MULTFILE wy I MULTFI
538. ua A E venceeseunecereeedee 293 4 18 Power Management FUN ctions cccceeeeeeeeeneeeeeeeeeeeeeeaeeeeeeaeeeeeeaeeeeeeaeeeeeeiaaeeeseedaeeeeneaas 297 4 19 Delay FUNCUONS 22 icennieet aie vaiediabe citi eee ea en ee ie 299 4 20 MMC SD SD HC FLASH Memory Card Driver Functions ccccccceseeeeseeeecteeeeeeeeseeeeees 300 4 21 FAT ACCESS FUNCUONS i ieis cite nn nnn nA E EE EO E 309 4 22 Peripheral Chips Functions 2 c ccccccceeeeeeeecee cece eeeeeeeseccaeaeeeeeeeeeseccaeaeeeeeeeeeeeecsnceeeeeeeeeteees 335 4 22 1 Philips PCF8563 Real Time Clock Functions ccccceceeeeeeeeeceeceeeeeeeseceeaeeeeeeeeetees 335 4 22 2 Philips PCF8583 Real Time Clock FUNCtIONS ecceceececeeeeeeeeeeeeneeeeeeeteseteenenaeeeeees 342 4 22 3 Maxim Dallas Semiconductor DS1302 Real Time Clock Functions 348 4 22 4 Maxim Dallas Semiconductor DS1307 Real Time Clock Functions 352 4 22 5 Maxim Dallas Semiconductor DS1621 Thermometer Thermostat Functions 357 4 22 6 Maxim Dallas Semiconductor DS1820 DS18S20 Temperature Sensors Functions 362 4 22 7 Maxim Dallas Semiconductor DS18B20 Temperature Sensor Functions 006 366 4 22 8 Maxim Dallas Semiconductor DS2430 EEPROM Functions c cceeccesseeeeeeeeetes 369 4 22 9 Maxim Dallas Semiconductor DS2433 EEPROM Functions 372 4 22 10 National Semiconductor LM75 Temperature Sensor Functions ceceeeeeeees 375 5 CodeWizardA
539. uct This software product and documentation may not in whole or in part be copied photocopied translated or reduced to any electronic medium or machine readable form without prior consent in writing from HP InfoTech S R L and according to all applicable laws The sole owners of this product are Pavel Haiduc and HP InfoTech S R L 8 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 8 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 co
540. ump 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 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 2012 HP InfoTech S R L Page 72 CodeVisionAVR 2 3 6 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 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
541. unctions signed char cmax signed char a signed char b returns the maximum value of bytes a and b int max int a int b returns the maximum value of integers a and b long int Imax long int a long int b returns the maximum value of long integers a and b float fmax float a float b returns the maximum value of floating point numbers a and b signed char cmin signed char a signed char b returns the minimum value of bytes a and b int min int a int b returns the minimum value of integers a and b long int Imin long int a long int b returns the minimum value of long integers a and b float fmin float a float b returns the minimum value of floating point numbers a and b signed char csign signed char x returns 1 0 or 1 if the byte x is negative zero or positive signed char sign int x returns 1 0 or 1 if the integer x is negative zero or positive 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 2012 HP InfoTech S R L Page 169 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
542. unication data rate The CodeWizardAVR automatically calculates the values for the BSEL and SCALE for the current Baud Rate and Peripheral Clock values The Real Baud Rate and Error are displayed The Receiver respectively Transmitter can be activated using the Receiver Enabled respectively Transmitter Enabled check boxes The USART can generate several types of interrupts e Receive Complete Interrupt e Transmit Complete Interrupt e Data Register Empty Interrupt Each type of interrupt can be individually enabled and its priority set using the corresponding list boxes If buffered interrupt driven serial communication will be used the sizes of the Receiver respectively Transmitter buffers can be specified using the Receiver Buffer Size respectively Transmitter Buffer Size edit boxes In order to allow receiving respectively transmitting data using the USART the CodeWizardAVR will define the getchar_usartpn respectively putchar_usartpn functions where p is the I O port letter and n is the USART number in the port One of the USARTs can be chosen as the default communication device to be used by the getchar respectively putchar Standard C Input Output Functions by enabling the Default USART for getchar respectively the Default USART for putchar options In this situation the standard getchar and putchar functions are redefined in the generated program For interrupt driven serial communication some additional global
543. using the other PCF8583 Functions If more then one chip is connected to the IC 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 void pcf8583_twi_init TWI_MASTER_INFO_t ptwim this function is used to initialize the PCF8583 library s internal variable swhen using the TWI Functions for Master Mode Operation for XMEGA Devices It is not used for non XMEGA devices The ptwim parameter must point to a TWI_LMASTER_INFO _t structure variable that is used to hold the information required by the TWI module when operating in master mode The pcf8583_twi_init function must be called before rtc_init Refer to the supplied example at the end of this chapter for more details 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 ye
544. ut it can be tri stated T or have an internal pull up P resistor connected to the positive power supply e ifthe pin is an output its value can be initially set to 0 or 1 The PORTX register will be initialized according to these settings 1998 2012 HP InfoTech S R L Page 390 CodeVisionAVR 5 4 Setting the External Interrupts The external interrupt configuration can be specified by clicking on the External IRQ ny node of the CodeWizardAVR selection tree a CodeWizardAVR test cwp Ex File Help Analog Comparator ADC SPI 12C 1Wire 2Wie 2c Lco Bit Banged Project Information Chip EstemalSRAM Ports Timers USARTO USARTI INTO Enabled Mode Lowlevel gt INT1 Enabled Mode Low level z INT2 Enabled Mode Low level z VIINT3 Enabled Mode Low level v INT5 Enabled Mode Low level v v v v v V INT4 Enabled Mode Low level z v Vi INTE Enabled Mode Lowlevel v INTZ Enabled Mode Low level v 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 2012 HP InfoTech S R L Page 391 Code
545. ut 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 2012 HP InfoTech S R L Page 159 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 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_
546. vert 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 warnings in these situations Example void main void unsigned char a 30 unsigned char b 128 unsigned int c This will generate an incorrect result because the multiplication is done on 8 bits producing an 8 bit result which overflows Only after
547. verts the integer n to characters in string str void Itoa long int n char str converts the long integer n to characters in string str void ftoa float n unsigned char decimals char str converts the floating point number n to characters in string str The number is represented with a specified number of decimals void ftoe float n unsigned char decimals char str converts the floating point number n to characters in string str The number is represented as a mantissa with a specified number of decimals and an integer power of 10 exponent e g 12 35e 5 float atof char str converts the characters from string str to floating point int rand void generates a pseudo random number between 0 and 32767 void srand int seed sets the starting value seed used by the pseudo random number generator in the rand function 1998 2012 HP InfoTech S R L Page 167 CodeVisionAVR 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
548. vices allow the ADC to use a high speed conversion mode but with lower precision This feature is enabled by checking the High Speed check box if 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 2012 HP InfoTech S R L Page 408 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 di
549. waveform generation mode This value will be used to initialize the DTILS register Timer Counter TCEO Settings Basic Advanced Waveform Extension J Enable Pattern Generation Lock Configuration Registers Pattern Generation 7654321 0 Pattern Generation PORTE Override CCA WG Out gt OUT O CCA WG Out gt OUT 4 CCA WG Out gt OUT 1 CCA WG Out gt OUT 5 CCA WG Out gt OUT 2 CCA WG Out gt OUT 6 CCA WG Out gt OUT 3 CCA WG Out gt OUT Fault Protection Input Sources Event Channel 0 Event Channel 4 Event Channel 1 Event Channel 5 Event Channel2 T Event Channel 6 Event Channel 3 Event Channel 7 Action None Fault protection disabled z Restart Mode Latched Mode z V On Chip Debug Break Request Triggers a Fault Condition The Fault Protection group box allows to specify the Input Sources and Action to be performed when a fault is detected The fault protection beeing event controlled any event from the Event System can be used to trigger a fault action 1998 2012 HP InfoTech S R L Page 462 CodeVisionAVR The following event Actions are possible e None e Clear all Override Enable Bits in the OUTOVEN register disabling the output override on all Timer Counter outputs e Clear all Direction Bits in the I O port DIR register setting all port pins as tri stated inputs The Restart Mode list box allows to specify how the AWeX and Timer Counter can return from the
550. wer control 3 register define SSD2119 CMD POWER _CONTROL4 0x0e Power control 4 register define SSD2119 CMD GATE SCAN POS 0x0f Gate scan position register define SSD2119 CMD SLEEP MODE 0x10 Sleep mode register define SSD2119 CMD ENTRY MODE 0x11 Entry mode register define SSD2119 CMD DEEP SLEEP MODE 0x12 Deep sleep mode register define SSD2119 CMD GENERIC IF CTRL 0x15 Generic interface control register define SSD2119 CMD HORIZ PORCH 0x16 Horizontal porch register define SSD2119 CMD VERT PORCH 0x17 Vertical porch register define SSD2119 CMD POWER CONTROLS Oxle Power control 5 register define SSD2119 CMD GDDRAM DATA 0x22 GDDRAM read write data register define SSD2119 CMD FRAME FREQ 0x25 Frame frequency control register define SSD2119 CMD GAMMA CONTROL1 0x30 Gamma control 1 define SSD2119 CMD GAMMA CONTROL2 0x31 Gamma control 2 define SSD2119 CMD GAMMA CONTROL3 0x32 Gamma control 3 define SSD2119 CMD GAMMA CONTROL4 0x33 Gamma control 4 define SSD2119 CMD GAMMA CONTROLS 0x34 Gamma control 5 define SSD2119 CMD GAMMA CONTROL6 0x35 Gamma control 6 define SSD2119 CMD GAMMA CONTROL7 0x36 Gamma control 7 define SSD2119 CMD GAMMA CONTROL8 0x37 Gamma control 8 define SSD2119 CMD GAMMA CONTROL9 0x3a Gamma control 9 define SSD2119 CMD GAMMA CONTROL10 0x3b Gamma control 10 define SSD2119 CMD VERT _SCROLL1 0x41 Vertical
551. ww aes dite ese gah Dade E EE OAT OTE T decade ends 118 3 6 Enumero a dda Actas ate eee 120 3 6 Defining Data TY GOS esiaren rrn A EAN NETE E 121 3 9 Type Convenis oerien a A AAA A 122 3 T0 OPEratOrS iiai a aa n AKE a a cada Ea r ere a e a EE iaa ER E a 123 3 11 FUNCONS 3 cc cree i E O TEE REE EE 124 3 12 PONET S iire a OE EEEE EEEREN ence nee A ge ei 125 3 13 Compiler Directives sirane eiaaeeelncccienaceade te lacadee EA E ARA a N 128 3 14 Accessing the I O Registers 00 0 0 cee tree etire rennet tt tttn tnnt tn unatu uant Ennn attuna nten nnat enunt tennant 132 3 14 1 Bit level access to the I O RegisterS n esssesesrnssssrresaternanrnnnantenndanannaaeennaannannaneenndanannaae 134 3 15 Accessing the EEPROM essione aAA 137 216 Using IMETUPIS zerera a IR AAT O OTE T 138 3 17 RAM Memory Organization and Register Allocation eeeeeesseeeessirreseerreserrnesrrresrrrrssrernsne 140 3 18 Using an External Startup Assembly File ssseesseeenseernesesrreserrssttrrnsttrrsssttrnnnttnnsstenrnsten nne 143 3 19 Including Assembly Language in Your Program sssessessessrissesrisstrrrsstirrssttrrssttnnnnstrnnstennnne 145 3 19 1 Calling Assembly Functions from C ssssssssssesrrsseerrsserrrsrtrrssttnrnssttnnnsttnnnntennnstennnnten nnt 146 3 20 Creating Librari s wi nceeien ead Meni EEEE EO E ETE 147 3 21 Using the AVR Studio 4 19 Debugger seciirruisnsnrieiniirrnnnrddnnk kainu inkan nn Hanani KEEA AR KAANANE aAA 150 3 22 Using the
552. x buffer twi_slave_ trans interrupt level interrupts C_LOLVLEN_bm globaly enable interrupts asm sei while 1 read the SWO 7 switches the switches value is inverted becaus the connection is established to GND when a switch is pressed switches PORTE IN check if at least one switch was pressed if switches ye s transmit the switches state to the slave and receive the contents of the test_data array sent by the slave in rx data twi_master trans amp twi_master SLAVE ADDR amp switches sizeof switches rx _data sizeof rx_data 1998 2012 HP InfoTech S R L Page 289 CodeVisionAVR check that correct data was received from the slave if strncmp rx data test data sizeof test data if rx data doesn t match test_data while 1 flash all LEDs to signal the mismatch PORTA OUT O0xFF delay ms 200 PORTA OUT 0x00 delay ms 200 4 16 Software Bit Banged I C Bus Functions The 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 I C Functions are implemented in software using the bit banging method The hardware TWI is not used Notes e For proper operation the IC Functions require the presence of 3 3k 4 7k pull up resistors
553. x0E Get the current display signal mode from the peripheral define SSD1963 CMD ENT SLEEP 0x10 Enter sleep mode define SSD1963 CMD EXIT SLEEP 0x11 Exit from sleep mode define SSD1963 CMD ENT PARTIAL MODE 0x12 Enter partial display mode define SSD1963 CMD ENT NORMAL MODE 0x13 Enter normal display mode define SSD1963 CMD EXIT INVERT MODE 0x20 Exit from inverted display mode define SSD1963 CMD ENT INVERT MODE 0x21 Enter inverted display mode define SSD1963 CMD SET GAMMA 0x26 Selects the gamma curve used by the display device define SSD1963 CMD BLANK DISPLAY 0x28 Set display off without clearing the frame buffer ON DISPLAY 0x29 Set display on SET COLUMN ADDR 0x2A Set the column extent of the frame buffer accessed with the SSD1963 CMD RD MEM CONT and SSD1963 CMD WR MEM CONT commands define SSD1963 CMD SET PAGE ADDR 0x2B Set the pag xtent of the frame buffer accessed with the SSD1963 CMD RD MEM CONT and SSD1963 CMD WR MEM CONT commands define SSD1963 CMD WR MEM START 0x2C Transfer image information from uC to SSD1963 starting with the location specified by SSD1963 CMD SET COLUMN ADDR and SSD1963 CMD SET PAGE ADDR define SSD1963 CMD_ define SSD1963 CMD_ 1998 2012 HP InfoTech S R L Page 240 CodeVisionAVR define define define define
554. x3A S D1963 PIXEL 3BIT 0x10 3 bit pixel D1963 PIXEL 8BIT 0x20 8 bit pixel D1963 PIXEL 12BIT 0x30 12 bit pix D1963 PIXEL 16BIT 0x50 16 bit pix D1963 PIXEL 18BIT 0x60 18 bit pix D1963 PIXEL 24BIT 0x70 24 bit pix D1963 CMD WR M SSD1963 CMD RD MEM CON SSD1963 CMD S SS SS SS SS SS SS SS SS SS SS SS ET FAR S D1963 CMD G ET T FAR S D1963_S D1963 P D1963 CM D1963 CMD R UPPLIER ID 0x _PRODUCT_ID 0x61 SSD1963 prod D1963 REVISION 0x01 SE CD MO D1963 CM CD MO D1963 CM HO D1963 CM HO go D1963 CM B el m VE D1963 CM ar D DDB 0xAl Read th SSD196 last sS SSD196 Transf uC con last SSD196 0x44 T 0x3E GI CANLINE CANLINE 0x45 i EM CONT 0x3C Transfer image data from uC to 3 continuing from the SD1963 CMD WR MEM START or 3 CMD WR MEM CONT er image data from SSD1963 to tinuing from the SD1963 CMD RD MEM START or 3 CMD RD MEM CONT Enable sending the TE to the uC when the display refresh reaches th provided scanline Get the current scanline signal D of SSD1963 5701 Solomon vice Descriptor Block Systech supplier ID uct ID DE OxBO Set L resol DE 0xB1 Get L resol RIOD 0xB4 Se
555. y and sets the printing character position at row 0 and column 0 The numbers of columns of the LCD must be specified e g 16 No cursor is displayed This is the first function that must be called before using the other high level LCD Functions 1998 2012 HP InfoTech S R L Page 183 CodeVisionAVR 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 void Icd_putse char eeprom str displays at the current display position the string str located in EEPROM 1998 2012 HP InfoTech S R L Page 184 CodeVisionAVR 4 11 2 LCD Functions for displays with 4x40 characters The LCD Functions are intended for easy interfacing between C programs and alphanumeric LCD modules with 4x40 characters built with the Hitachi HD44780 chip or equivalent The prototypes for these functions are placed in the file lcd4x40 h located in the INC subdirectory This file must be include d before using the functions The LCD functions do not yet support t
556. zation no external driver interface no SDA hold time twi_init amp TWID false false 1998 2012 HP InfoTech S R L Page 377 CodeVisionAVR enable and initialize the TWID master interrupt level low twi master init amp twid_ master amp TWID TWI_ MASTER INTLVL_LO gc TWI BAUD REG MCU CLOCK FREQUENCY _ TWI_CLK_ RATE enable the Low interrupt level PMIC CTRL PMIC_LOLVLEN_ bm set the LM75 functions to use TWID Im75_twi_init amp twid_ master enable interrupts so that TWI can be used fasm sei initialize the LM75 sensor with address 0 thyst 20 C tos 25 C 1m75_ init 0 20 25 0 initialize the LM75 sensor with address 1 thyst 30 C tos 35 C Im75_init 1 30 35 0 temperature display loop while 1 read the temperature of sensor 0 10 C tO lm75 temperature 10 0 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 tC0O S i uScC nt1l S i uScc t0 10 abs t0 10 Oxdf t1 10 abs t1 10 Oxdf display the temperatures lced_clear lcd _ puts display buffer 1998 2012 HP InfoTech S R L Page 378 CodeVisionAVR The same example but the LM75 chips are access
Download Pdf Manuals
Related Search
Related Contents
JVC DR-MV150B User Manual 9450/52 English PDF 379 KB Enrutador inalámbrico N para uso doméstico Guida di installazione My Book Thunderbolt Duo User Manual コンパクト&多機能デジタル複合機、誕生。 - OFFICE 110 『OA機器販売 Sentry 1200 lit-fauteuil manuel - Matelas Anti Copyright © All rights reserved.
Failed to retrieve file