CodeVisionAVR User Manual PDF
CodeVisionAVR User Manual PDF
VERSION 3.32
User Manual
CodeVisionAVR
Table of Contents
1. Introduction...................................................................................................................................... 13
2.1.6.4 Transferring the Compiled Program to the AVR Chip after Build ............................... 31
3.3.6.12 Transferring the Compiled Program to the AVR Chip after Build ........................... 101
4.7.1 Specifying the RAM and EEPROM Storage Address for Global Variables...................... 167
4.23 Compiling the Sample Code of the XMEGA Application Notes from Atmel........................... 215
5.11.1 LCD Functions for displays with up to 2x40 characters ................................................. 250
5.11.2 LCD Functions for displays with 4x40 characters .......................................................... 253
5.11.3 LCD Functions for displays connected in 8 bit memory mapped mode ......................... 256
5.11.4 LCD Functions for displays with I²C bus connection ...................................................... 259
5.12.2 Graphic LCD Functions Specific to the ILI9325 and RM68090 Controllers ................... 298
5.12.7 Graphic LCD Functions Specific to the PCD8544 Controller ......................................... 338
5.12.12 Graphic LCD Functions Specific to the SED1335 Controller ....................................... 359
5.12.13 Graphic LCD Functions Specific to the SED1530 Controller ....................................... 361
5.12.15 Graphic LCD Functions Specific to the SSD1289 Controller ....................................... 367
5.12.16 Graphic OLED Display Functions Specific to the SSD1303 and SH1101A Controllers
5.12.17 Graphic OLED Display Functions Specific to the SSD1306 Controller........................ 377
5.12.18 Graphic OLED Display Functions Specific to the SSD1309 Controller........................ 380
5.12.19 Graphic OLED Display Functions Specific to the SSD1322 Controller........................ 383
5.12.20 Graphic OLED Display Functions Specific to the SSD1331 Controller........................ 389
5.12.21 Graphic OLED Display Functions Specific to the SSD1332 Controller........................ 394
5.12.22 Graphic OLED Display Functions Specific to the SSD1351 Controller........................ 399
5.12.23 Graphic LCD Functions Specific to the SSD1963 Controller ....................................... 405
5.12.24 Graphic LCD Functions Specific to the SSD2119 Controller ....................................... 413
5.12.25 Graphic LCD Functions Specific to the ST7565 Controller .......................................... 421
5.12.26 Graphic LCD Functions Specific to the ST7567 Controller .......................................... 424
5.12.27 Graphic LCD Functions Specific to the ST7781 Controller .......................................... 427
5.12.28 Graphic LCD Functions Specific to the ST7789 Controller .......................................... 434
5.12.29 Graphic LCD Functions Specific to the ST7920 Controller .......................................... 441
5.12.30 Graphic LCD Functions Specific to the T6963C Controller .......................................... 447
5.12.31 Graphic LCD Functions Specific to the UC1608 Controller ......................................... 449
5.12.32 Graphic LCD Functions Specific to the UC1610 Controller ......................................... 453
5.12.33 Graphic LCD Functions Specific to the UC1701 Controller ......................................... 457
5.16 Two Wire Interface Functions for non-XMEGA Devices ........................................................ 489
5.16.1 Two Wire Interface Functions for Master Mode Operation............................................. 489
5.16.2 Two Wire Interface Functions for Slave Mode Operation............................................... 491
5.17.1 Two Wire Interface Functions for Master Mode Operation............................................. 496
5.17.2 Two Wire Interface Functions for Slave Mode Operation............................................... 500
5.18.2 Two Wire Interface Functions for Slave Mode Operation............................................... 511
5.26.16 Bosch Sensortec BME280 Digital Pressure and Humidity Sensor Functions.............. 692
5.26.17 Measurement Specialties MS5611-01BA Digital Pressure Sensor Functions ............. 701
6.16 Setting the Two Wire Bus Slave Interface for the ATtiny20/40 chips..................................... 751
7.10 Setting the 32-Bit Real Time Counter and Battery Backup System ....................................... 795
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 Windows XP, Vista, 7, 8 and 10, 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 Studio and AVR Studio debuggers.
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 software is designed to work in conjunction with
the Atmel STK500, STK600, AVRISP, AVRISP MkII, AVR Dragon, JTAGICE MkII, JTAGICE 3,
Atmel-ICE, Atmel mEDBG, AVRProg (AVR910 application note), USBASP, Kanda Systems STK200+,
STK300, Arduino, 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.
CodeVisionAVR can be also used as an extension in Atmel Studio 6.2 or 7.0, allowing seamless
editing, compiling and debugging projects in this IDE.
Besides the standard C libraries, the CodeVisionAVR C compiler has dedicated libraries for:
• Alphanumeric and Graphic LCD/OLED displays
• Philips I2C bus
• Texas Instruments LM75 Temperature Sensor
• Philips PCF8563, PCF8583, Maxim DS1302, DS1307, DS3231 Real Time Clocks
• Philips PCF8574(A) I/O expander
• Maxim/Dallas Semiconductor 1 Wire protocol
• Maxim DS1820, DS18S20 and DS18B20 Temperature Sensors
• Maxim DS1621 Thermometer/Thermostat
• Maxim DS2430 and DS2433 EEPROMs
• SPI
• TWI for both XMEGA and non-XMEGA chips
• USB 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
• ADS7843 and ADS7846 Resistive touchscreen controllers
• FT5206, FT5306 and FT5406 Capacitive touchscreen controllers
• BMP085, BMP180 and MS5611-01BA Digital Pressure sensors.
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:
• External memory access setup
• Chip reset source identification
• Input/Output Port initialization
• External Interrupts initialization
• Timers/Counters initialization
• Watchdog Timer initialization
• UART (USART) initialization and interrupt driven buffered serial communication
• Analog Comparator initialization
• ADC and DAC initialization
• SPI Interface initialization
• Two Wire Interface initialization
• USB Initialization
• CAN Interface initialization
• I2C Bus, LM75 Temperature Sensor, DS1621 Thermometer/Thermostat, PCF8563, PCF8583,
DS1302, DS1307, DS3231 Real Time Clocks and PCF8574(A) I/O expander initialization
• 1 Wire Bus and DS1820/DS18S20 Temperature Sensors initialization
• Alphanumeric and graphic displays initialization
• Touchscreen controllers initialization.
CodeVisionAVR is © Copyright 1998-2017 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.
The CodeVisionAVR IDE uses the freeware TDiff Delphi component © Copyright 2001-2008 by Angus
Johnson.
For C source style formatting the CodeVisionAVR IDE calls the Artistic Style program © Copyright
2014 by Jim Pattee.
The AVRISP mKII, AVR Dragon, JTAGICE MkII, JTAGICE3, Atmel-ICE, STK600 and USBASP
programmers are supported by calling the AVR Dude program © Copyright 2000-2005 by Brian S.
Dean, © Copyright 2007-2016 by Joerg Wunsch.
1.1 Credits
The HP InfoTech team wishes to thank:
• Mr. Jack Tidwell for his great help in the implementation of the floating point routines
• Mr. Yuri G. Salov for his excellent work in improving the Mathematical Functions Library
• Mr. Olivier Wuillemin and Mr. Franc Marx for their help in beta testing
• Mr. Lee H. Theusch for his support in improving the compiler
• 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.
The following chapters cover only the specific aspects of CodeVisionAVR integrated in Atmel Studio.
For more details about using Atmel Studio, please refer to its documentation.
allowing to select between the AVR chip families for which automatic code generation will be
performed.
the Program|Generate, Save and Exit menu option must be selected or the toolbar button must
be clicked in CodeWizardAVR.
It will generate the main .c source, Atmel Studio project .cproj and it's own .cwp (for non-XMEGA
chips) or .cwx (for XMEGA chips) project files.
Eventual peripheral configuration conflicts will be prompted to the user, allowing him to correct the
errors.
In the course of program generation the user will be prompted for the name of the first .c source file of
the project:
and for the name of the CodeVisionAVR project for Atmel Studio file:
The user will be also prompted to save the current chip configuration in a CodeWizardAVR .cwp or
.cwx project file:
Once all these files were created, the user will be prompted for creating an Atmel Studio solution
which will incorporate the new CodeVisionAVR project:
If the answer is affirmative, the user will be prompted for the Atmel Studio solution name:
If a solution is already opened, the user will be prompted for the inclusion of the new project in that
solution, without creating a new one.
Note: When an Atmel Studio .cproj project is created, a corresponding .prj project file for the
CodeVisionAVR IDE will be created too.
This allows editing/compiling the same project in both Atmel Studio and CodeVisionAVR IDE.
After the project file name was specified, the user will be prompted to select the target chip type
and the name of the first .c source file of the project:
Once these are specified, a configuration window for the newly created project will be displayed:
More details can be found in the chapter: 3.3.6 Configuring the Project.
After the project configuration was specified, the user will be prompted for the name of the Atmel
Studio solution that will hold the new project:
If a solution is already opened, the user will be prompted for the inclusion of the new project in that
solution, without creating a new one.
Note: When an Atmel Studio .cproj project is created, a corresponding .prj project file for the
CodeVisionAVR IDE will be created too.
This allows editing/compiling the same project in both Atmel Studio and CodeVisionAVR IDE.
If the answer is affirmative, the user will be prompted to specify the name of the new solution that will
hold the imported project:
If a solution is already opened, the user will be prompted for the inclusion of the imported project in
that solution, without creating a new one.
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.
The resulting .rom, .hex, .eep and .elf files will be placed in the Executable Files directory.
If the Project|Configure|After Build|Action:Program the Chip option is enabled, then the .elf
production file will also contain, besides the FLASH and EEPROM data, the settings for programming
the lock and fuse bits.
Alternatively the lock, respectively fuse bits, can be specified in the program source using the
#pragma lock_bits, respectively #pragma fuses compiler directives.
The object files, including the .cof COFF object file used for debugging, will be placed in the Object
Files directory.
The .asm, .lst and .map files 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.
The Executable Files, Object Files, List Files and Linker Files directories are specified in the
Project|Configure|Files|Output menu.
To build the Project you must use the Build|Build project name menu command or the 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 Build|Rebuild project
name menu command 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 |File Output Formats.
Eventual compilation errors and/or warnings will be listed in Atmel Studio's Output window.
After the build process is completed, an Information window will open showing the build results.
Pressing the Compiler tab will display compilation results.
Pressing the Programmer tab will display the Chip Programming Counter, which shows how many
times was the AVR chip programmed so far.
Pressing the Set Counter button will open the Set Programming Counter window:
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.
The Information window for the last build, can be always displayed using the Project|Build
Information for project name menu.
The Function Call Tree window is accessed using the Project|Function Call Tree menu command
and appears after the first 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:
• Function nodes. Clicking on a function name moves the cursor to the corresponding definition
in the source file.
• DSTACK nodes display the data stack used by the parent function and the total level of the
Data Stack when the program is executed inside the function.
If the Action|Program the Chip option is selected, then after successful compilation/assembly your
program will be automatically transferred to the AVR chip using the built-in Programmer software.
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 MkII
can be specified using the SCK Freq. listbox. This frequency must not exceed ¼ of the chip's clock
frequency.
If the chip you have selected has Fuse Bit(s) that may be programmed, then a supplementary
Program Fuse Bit(s) check box will appear.
If it is checked, than the chip's Fuse Bit(s) will be programmed after Build.
The Fuse Bit(s) can set various chip options, which are described in the Atmel data sheets.
If a Fuse Bit(s) check box is checked, then the corresponding fuse bit will be set to 0, the fuse being
considered as programmed (as per the convention from the Atmel data sheets).
If a Fuse Bits(s) check box is not checked, then the corresponding fuse bit will be set to 1, the fuse
being considered as not programmed.
If you wish to protect your program from copying, you must select the corresponding option using the
FLASH Lock Bits radio box.
If you wish to check the chip's signature before programming you must use the Check Signature
option.
To speed up the 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.
The above dialog window allows selecting the Arduino Board Type and the serial COM Port used for
communication with the development board.
If the Arduino Board Type is selected as Custom, then you can also specify the Communication
Protocol and Baud Rate to be used with the boot loader.
Changes can be saved, respectively canceled, using the OK, respectively Cancel buttons.
Atmel Studio uses the .cof object file produced by CodeVisionAVR for debugging.
Therefore it is important that this file is created, by selecting in the Project|Configure|C
Compiler|Code generation|File Output Formats list box the following formats for the files generated
by the compiler: COFF, ROM, Intel HEX and EEP.
To obtain more information about using the debugger, please consult the Atmel Studio Help.
Note: The compiler applies some optimization techniques that may prevent correct debugging of the
executable program.
Therefore it is recommended to select the Project|Configure|C Compiler|Code generation|
Optimize for: Speed option for code debugging.
If the program fits in the chip's FLASH, this option must be left enabled for Release too, as the
program will execute faster this way.
The Automatic Program Generator is invoked using the Tools|CodeWizardAVR menu command or
by clicking on the Tools toolbar button.
More details about using CodeWizardAVR can be found in Chapter 6 of the User Manual.
The uploader is executed by selecting the Tools|Upload to Arduino menu command or by pressing
the button on the Atmel Studio Tools toolbar.
The Settings group box allows selecting the Arduino Board Type and the serial COM Port used for
communication with the development board.
If the Arduino Board Type is selected as Custom, then any Chip Type with a boot area can be
selected, along with the Communication Protocol and Baud Rate to be used with the boot loader.
The Files group box allows specifying the .hex FLASH and .eep, EEPROM contents files to be
uploaded to the AVR microcontroller.
Pressing the button will open a dialog window, allowing to select the appropriate file.
Note: The boot loaders from some Arduino boards don't support EEPROM programming, therefore
the Files|EEPROM option is disabled in such cases.
LCD Vision is invoked using the Atmel Studio Tools|LCD Vision menu command or the button on
the Tools toolbar.
Note: The LCD Vision editor/converter can be used only with an Advanced CodeVisionAVR license.
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.
The window can be resized by dragging its margins and corners with the left mouse button pressed.
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:
When the mouse cursor arrives on one of the docking markers, the future docking position will be
outlined:
After the mouse button will be released, the window will become docked.
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:
To undock a single tabbed page, the bottom tab must be dragged with the mouse.
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 menu 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:
If the user will place the mouse cursor on the vertical bar, the hidden window will be displayed for a
short amount of time
Clicking with the mouse on the window icon will open a specific drop down menu:
Alternatively this menu can be also invoked by right clicking with the mouse inside the window.
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:
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:
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:
All the workspace layout will be automatically saved at program exit and restored back on the next
launch.
The current editor tabbed window can be also closed by clicking on the icon located on the top
right of the tabbed control.
Tabbed editor windows can be also undocked, dragged and then docked in any desired position, like it
was exemplified above, allowing to create a fully customized workspace layout, that suits the user's
specific needs.
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.
Pressing the Home key moves the cursor to the start of the current text line.
Pressing the End key moves the cursor to the end of the current text line.
Pressing the Ctrl+Home keys moves the cursor to the start of the file.
Pressing the Ctrl+End keys moves the cursor to the end of the file.
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 toolbar button.
Dragging and dropping with the mouse can move portions of text.
Pressing the Ctrl+Y keys deletes the text line where the cursor is currently positioned.
Changes in the edited text can be undone, respectively redone, by using the Edit|Undo, respectively
Edit|Redo, menu commands, by pressing the Ctrl+Z, respectively Shift+Ctrl+Z keys, or by pressing
the , respectively buttons on the toolbar.
Clicking with the mouse right button in the Editor window, opens a pop-up menu that gives access to
the above mentioned functions.
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.
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 mouse right clicking in the Editor
window.
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 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.
A pop-up window containing a character map grid will be displayed, allowing the user to select the
appropriate character to be inserted:
This function is also available in the pop-up menu, invoked by mouse right clicking in the Editor
window.
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:
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 '->' auto completion triggering
characters.
A pop-up hint with the members list will show like in the example below:
The user can select the member to be inserted in the text at the cursor position, by using the up/down
arrow keys, respectively the mouse, and then pressing Enter or Space keys, respectively the left
mouse button.
Pressing the Esc key will close the pop-up hint window, without inserting the member.
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.
C code auto complete displays a pop-up hint window with C keywords, library functions, data types,
predefined macros, based on the first characters of a word typed in the Editor:
The user can select the auto completed word to be inserted in the text at the cursor position, by using
the up/down arrow keys, respectively the mouse, and then pressing Enter or Space keys, respectively
the left mouse button.
Pressing the Esc key will close the pop-up hint window, without inserting the auto completed word.
C source code formatting can be also applied to several files at the same time using the Edit|Format
Source Code for Multiple Files menu command or by pressing the button on the Edit toolbar.
A file selection window will be displayed:
Initially the file list will contain all the .C and .H files of the currently opened project.
More files can be added by pressing the Add button.
By clicking in the file list, one or more files can be selected.
Note: Multiple files can be selected by holding the Ctrl key and clicking on the corresponding files in
the list. Alternatively a range of files can be selected by pressing the Shift key and clicking on the first
file, then pressing Shift and clicking on the last file.
Pressing the Remove button will remove the selected file(s) from the list.
The C source file formatting style can be customized by pressing the Settings button (see chapter
3.5.4 for a detailed description).
Pressing the OK button will apply the formatting to all the files in the list.
Pressing the Cancel button will exit, without applying source code formatting.
The View|Toggle Fold menu and the toolbar button allow to collapse/expand the block of code
where the cursor is located.
The View|Expand All Folds menu and the toolbar button allow to expand all folded blocks of
code.
The View|Collapse All Folds menu and the 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.
You will have the possibility to specify the new name and type of the file, and eventually its new
location.
You can print the current file using the File|Print menu command or by pressing the button on the
toolbar.
The contents of the file will be printed to the Windows default printer.
The paper margins used when printing can be set using the File|Page Setup menu command or the
toolbar button, which opens the Page Setup dialog window.
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.
Closing several files can be performed using the File|Close Multiple menu command or the
toolbar button.
A dialog window, which lists all the opened files, will open for this purpose:
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.
A dialog window will open, allowing the user to select the second file to be compared with:
The second file can be one of the already opened in the Editor or the user has the option to open a file
by pressing the Another File button.
The file selection must be confirmed by pressing the Ok button.
The comparison action can be canceled by clicking on the Cancel button.
Once the two files to be compared were selected, their contents is displayed in a new window, the
differences being highlighted with special colors.
If a file is changed in the editor, a * character is appended to its path, displayed in the Compare Files
window.
The user has then the possibility to repeat the comparison process by pressing the button.
This process can be always aborted by pressing the button.
Pressing the , respectively, toolbar buttons allows to position the cursor to the next, respectively
previous, text difference.
The toolbar button also allows to select the colors used for highlighting the text differences.
This is achieved by clicking on the desired code sequence in the Code Templates window and then
dragging and dropping it to the appropriate position in the Editor window.
New code templates can be added to the list by dragging and dropping a text selection from the Editor
window to the Code Templates window.
By right clicking in the Code Templates window you can open a pop-up menu with the following
choices:
• Copy to the Edit Window the currently selected code template
• Paste a text fragment from the clipboard to the 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.
By right clicking in the Clipboard History window you can open a pop-up menu with the following
choices:
• Copy to the Edit Window the currently selected text fragment from the Clipboard History
window
• Delete the currently selected text fragment from the list
• Delete All the text fragments from the list.
You can create a new project file using the File|New|Project menu command, by pressing the and
buttons on the toolbar.
A dialog will open asking you to confirm if you would like to use the CodeWizardAVR to create the new
project.
If you select No then the Create New Project dialog window will open.
You must specify the new Project file name and its location.
After the name and location of the project file was specified, a device selection dialog will open:
The dialog also allows to specify the name of the first C source file of the project.
Once the OK button is pressed the project and the C source file are created and the project
configuration window is displayed:
The Project configuration can be later modified by using the Project|Configure menu command or by
pressing the toolbar button.
Note: When a .prj project for the CodeVisionAVR IDE is created, a corresponding .cproj project file
for Atmel Studio will be created too.
This allows editing/compiling the same project in both Atmel Studio and CodeVisionAVR IDE.
An existing Project file can be opened using the File|Open menu command or by pressing the
button on the toolbar.
An Open dialog window appears.
You must select the file name of the Project you wish to open.
By pressing the Open button you will open the Project file and its source file(s).
You can later configure the Project by using the Project|Configure menu command or by pressing
the toolbar button.
Upon execution of this command a Project Export dialog window will open:
allowing to specify the name of the new project to which all the settings of the current project will be
exported.
The Project can be configured using the Project|Configure menu command or the toolbar button.
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.
Multiple files can be added by holding the Ctrl key when selecting in the Add File to Project dialog.
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:
• only .C files must be added to the project's Files list
• there's no need to #include the .C files from the Files list as they will be automatically linked
• data type definitions and function declarations must be placed in header .H files, that will be
#include -d as necessary in the .C files
• global variables declarations must be placed in the .C files where necessary
• 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.
The .rom, .hex and .eep 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 .cof 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.
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 DS1820/DS18S20/DS18B20 Temperature Sensors Functions.
The required memory model can be selected by using the Memory Model list box.
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:
• Application
• Boot Loader
If the Boot Loader program type was selected, a supplementary Boot Loader Debugging in AVR
Studio option is available.
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.
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 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:
• 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
• 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
• long, width - the following conversion type characters are supported: 'c', 's', 'p', 'i', 'd', 'u', 'x', 'X',
'%' the width specifier is supported, the precision specifier is not supported, only the '+', '-', '0' and ' '
flags are supported, only the 'l' input size modifier is supported
• 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
• float, width, precision - the following conversion type characters are supported: 'c', 's', 'p', 'i', 'd',
'u', 'e', 'E', 'f', 'x', 'X', '%', the width and precision specifiers are supported, only the '+', '-', '0' and ' ' flags
are supported, only the 'l' input size modifier is supported.
The more features are selected, the larger is the code size generated for the printf and sprintf
functions.
The (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:
• 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
• 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
• long, float, width - the following conversion type characters are supported: 'c', 's', 'i', 'd', 'u', 'x', 'f',
'e', 'E', 'g', 'G', '%', the width specifier is supported, the 'l' input size modifier is supported only for
integer types.
The more features are selected, the larger is the code size generated for the scanf and sscanf
functions.
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:
n
heap _ size = ( n + 1) ⋅ 4 + ∑ block _ sizei
i =1
where: n is the number of memory blocks that will be allocated in the heap
block _ sizei 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 specify the External RAM Size (in case the microcontroller have external
SRAM memory connected).
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.
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 >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 >31 option not checked if the number of global
bit variables is small enough and no additional registers are needed for their storage.
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 default the char data type as an
unsigned 8 bit in the range 0…255.
If the check box is not checked the char data type is by default a signed 8 bit in the range –128…127.
This option can also be specified using the #pragma uchar compiler directive.
Treating char as unsigned leads to better code size and speed.
If the 8 bit enums check box is checked, the compiler treats the enumerations as being of 8 bit char
data type, leading to improved code size and execution speed of the compiled program. If the check
box is not checked the enumerations are considered as 16 bit int data type as required by ANSI.
The following modes, specified in the Project|Configure|C Compiler|Code Generation menu, are
used for function parameter passing and storage:
• Enhanced Parameter: No - all function parameters are passed using the Data Stack and
accessed using the LDD Rn, Y+d and STD Y+d,Rn instructions
• Enhanced Parameter: Mode 1 - all function parameters, except the last one, are passed using
the Data Stack.
The last parameter is passed in registers R26 for 1 byte, R26, R27 for 2 byte and R26, R27, R24, R25
for 4 byte parameters.
However in the function prologue this last parameter is pushed in the Data Stack too.
So in this mode all function parameters are also accessed using the LDD Rn, Y+d and STD Y+d,Rn
instructions.
Better code size is obtained, because register accessing instructions are used when passing the last
function parameter during function call.
• Enhanced Parameter: Mode 2 - all function parameters, except the last one, are passed using
the Data Stack.
The last parameter is passed in registers R26 for 1 byte, R26, R27 for 2 byte and R26, R27, R24, R25
for 4 byte parameters.
In the function prologue the function parameters are copied from the Data Stack or registers R26,
R27, R24, R25 to the registers R16..R21, that were not allocated for local variables.
In this mode function parameters that could be allocated/copied to registers R16..R21 are accessed
using more efficient instructions.
The rest of the parameters are still accessed using the LDD Rn, Y+d and STD Y+d,Rn instructions.
Even better code size is obtained, because register accessing instructions are used when passing the
last parameter and for accessing the parameters stored in registers inside the function.
Note: If this mode is used for programs which contain functions that use inline assembly code to
access function parameters, then such functions must be enclosed between #pragma dstack+ and
#pragma dstack- like in the following example:
The Smart Register Allocation check box enables allocation of registers R2 to R14 (not used for bit
variables) and R16 to R21 in such a way that 16bit variables will be preferably located in even register
pairs, thus favouring the usage of the enhanced core MOVW instruction for their access. This option is
effective only if the Enhanced Instructions check box is also checked.
If Smart Register Allocation is not enabled, the registers will be allocated in the order of variable
declaration.
The Smart Register Allocation option 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 used, 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.
When your program runs correctly you may disable the placement of these strings in order to reduce
code size.
Using the File Output Formats list box you can select the following formats for the files generated by
the compiler:
• COFF (required by the Atmel AVR Studio debugger), ROM, Intel HEX and EEP (required by the
In-System Programmer) ;
• Atmel generic OBJ, ROM, Intel HEX and EEP (required by the In-System Programmer).
For the XMEGA chips that feature an External Bus Interface (EBI) an additional EBI Configuration
tab is present:
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.
Depending on the EBI operating mode, additional tabs are displayed for the configuration of the
CS0...CS3 chip select signals:
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.
Specific options can be set if SDRAM chips are connected to the XMEGA chip:
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.
This can be achieved by using the __reset attribute applied to the clock initialization function:
The code generated by the CodeWizardAVR for XMEGA chips, automatically handles such situations.
The Advanced tab, which is present only in the Advanced version of the compiler, enables more
detailed custom configuration like the number and jump type of the interrupt vectors and memory
usage:
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.
The On-Chip RAM Start and End fields allow to specify the RAM area to be used by the compiler.
Checking the Startup Initialization - Disable the Watchdog Timer option allows generation of code
that ensures that the watchdog timer is disabled after a software reset.
The Reserved Registers option allows to prevent the automatic allocation of some of the registers R2
to R14 to global variables, if the Automatic Global Registers Allocation option is enabled in the
Project|Configure|C Compiler|Code Generation menu.
The reserved registers can in this case be used for inline assembly code or be allocated manually for
a specific global variable.
Example:
register unsigned char abc @14; /* the global variable abc is allocated
to the reserved register R14 */
register unsigned char abc=123; /* the variable abc, allocated to R14,
is also initialized with the value 123
during definition */
The option Use "Mangled" Names for Watching "static" Variables in the debugger, is useful when
several static global variables with the same name were declared in different C program modules.
It allows to distinguish between them in the debugger's watch window.
If it's enabled, the .map file will display the mangled name of the static variable, which must be used
with the debugger.
The Messages tab allows to individually enable or disable various compiler and linker warnings:
The generation of warning messages during compilation can be globally enabled or disabled by using
the Enable Warnings check box.
The Globally #define tab allows to #define macros that will be visible in all the project files.
For example:
The Paths tab allows to specify additional search paths for #include and Library files.
Changes can be saved, respectively canceled, using the OK, respectively Cancel buttons.
The 1 Wire tab is used for configuring the I/O port allocation for the 1 Wire Protocol Functions.
• Enable 1 Wire Bus Interface Support allows the activation of the 1 Wire Protocol Functions
• I/O Port and Bit specify in Data Connection, the port and bit used for 1 Wire bus communication.
The I2C tab is used for configuring the I/O port allocation and bit rate of the software bit-banged I2C
Bus Functions.
• Enable Bit-Banged I2C Support allows the activation of the I2C Bus Functions library.
• I/O Port, SDA and SCL specify in Data Connection, the port and bits used for I2C bus
communication
• Bit Rate specifies the frequency of the clock pulses on the SCL line.
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.
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.
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.
The Alphanumeric LCD tab is used for configuring the I/O port allocation for the LCD Functions for
displays with up to 2x40 characters.
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.
The Graphic Display tab is used for configuring the I/O port allocation for the Graphic Display
Functions.
The Display Type list box allows to select the graphic controller type and LCD resolution.
The connections between the graphic display 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 display controller's data bus
bits to match the bits with the same numbers of the same AVR I/O port.
The Resistive Touchscreen tab is used for configuring the I/O port allocation for the Resistive
Touchscreen Functions.
The Enable Resistive Touchscreen Support option must be checked in order to enable the usage of
the touchscreen library.
The Controller list box allows selecting the resistive touchscreen controller type.
The connections between the touchscreen controller and the AVR I/O ports can be specified
individually for each signal in the Connections group box.
The USB tab is used for configuring specific features of the CodeVisionAVR USB library.
The Use Power Management option allows reducing the power consumption, when the USB bus is in
the suspended state, by stopping the clock of the PLL used by the USB controller.
Enabling this option however increases the program's code size.
Some of the USB library functions require specific features to be enabled in order to support certain
USB device classes.
This is accomplished by checking the corresponding option in the Enable Specific USB Library
Functions list.
There is also the option to wait for the user's program to finish it's execution before staring the Build
process.
Pressing the button allows to select a directory and file.
If the Action|Program the Chip option is selected, then after successful compilation/assembly your
program will be automatically transferred to the AVR chip using the built-in Programmer software.
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 MkII
can be specified using the SCK Freq. listbox. This frequency must not exceed ¼ of the chip's clock
frequency.
If the chip you have selected has Fuse Bit(s) that may be programmed, then a supplementary
Program Fuse Bit(s) check box will appear.
If it is checked, than the chip's Fuse Bit(s) will be programmed after Build.
The Fuse Bit(s) can set various chip options, which are described in the Atmel data sheets.
If a Fuse Bit(s) check box is checked, then the corresponding fuse bit will be set to 0, the fuse being
considered as programmed (as per the convention from the Atmel data sheets).
If a Fuse Bits(s) check box is not checked, then the corresponding fuse bit will be set to 1, the fuse
being considered as not programmed.
If you wish to protect your program from copying, you must select the corresponding option using the
FLASH Lock Bits radio box.
If you wish to check the chip's signature before programming you must use the Check Signature
option.
To speed up the 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.
The above dialog window allows selecting the Arduino Board Type and the serial COM Port used for
communication with the development board.
If the Arduino Board Type is selected as Custom, then you can also specify the Communication
Protocol and Baud Rate to be used with the boot loader.
The Upload to EEPROM checkbox allows to enable or disable automatic programming of the chip's
EEPROM, if the compiler has generated an .EEP file during project build.
Changes can be saved, respectively canceled, using the OK, respectively Cancel buttons.
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.
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.
The resulting .rom, .hex, .eep and .elf files will be placed in the Executable Files directory.
If the Project|Configure|After Build|Action:Program the Chip option is enabled, then the .elf
production file will also contain, besides the FLASH and EEPROM data, the settings for programming
the lock and fuse bits.
Alternatively the lock, respectively fuse bits, can be specified in the program source using the
#pragma lock_bits, respectively #pragma fuses compiler directives.
The object files, including the .cof COFF object file used for debugging, will be placed in the Object
Files directory.
The .asm, .lst and .map files 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.
The Executable Files, Object Files, List Files and Linker Files directories are specified in the
Project|Configure|Files|Output menu.
Eventual compilation errors and/or warnings will be listed in the Message window located under the
Editor window, or in the Code Navigator window.
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:
The Project|Go to Next Error, respectively Project|Go to Previous Error menu commands, the F8,
respectively Ctrl+F8 keys or the , respectively 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 , respectively toolbar buttons, allow moving to the next,
respectively previous warning message.
If the message refers also to a previous declaration or definition from a file that is different than the
one where the error was signaled, right clicking with the mouse opens a pop-up menu with the Jump
to Previous Declaration or Definition option:
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.
After successful compilation the object files will be linked and an assembly .asm file will be produced.
If no compilation or linking errors were encountered, then the Atmel AVR assembler AVRASM2 will be
executed, obtaining the output file types specified in Project|Configure|C Compiler|Code
Generation.
The build process can be stopped using the Project|Stop Compilation menu command or by
pressing the 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.
The Project|Go to Next Error, respectively Project|Go to Previous Error menu commands, the F8,
respectively Ctrl+F8 keys or the , respectively 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 , respectively 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:
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:
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.
Pressing the Programmer tab will display the Chip Programming Counter, which shows how many
times was the AVR chip programmed so far.
Pressing the Set Counter button will open the Set Programming Counter window:
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.
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 node.
By clicking on a closed file node, the appropriate file is opened in the editor.
If the file is already opened, clicking on its node, will make it active in the editor.
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 closed header file node, the appropriate file is opened in the editor.
If the header file is already opened, clicking on its node, will make it active in the editor.
The List Files node contains the assembly, list and map files generated by the compiler after the
Compile or Build process.
By clicking on a closed list file node, the appropriate file is opened in the editor.
If the list file is already opened, clicking on its node, will make it active in the editor.
If during compilation there are errors or warnings, these are also displayed in the Code Navigator
window.
By clicking on the error or warning node, the corresponding source line is highlighted in 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.
The Code Information window is accessed using the tab with the same name and appears after the
first Compile or Build process of the currently opened project.
The information is displayed in the form of a tree with several types of nodes:
• Includes node which displays all the header .h files #included in the currently edited source
file. Clicking on a header node moves the cursor to the corresponding #include directive in the
edited source file.
• 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.
• 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/items are displayed as additional or nodes.
• Global/Static Variables 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.
• Global Constants node which displays all the global constants declared in the currently edited
source file. Clicking on a constant node moves the cursor to the corresponding declaration in the
edited source file.
• 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.
By right clicking in the Code Information window you can open a pop-up menu with the following
choices:
• Toggle on or off alphabetically sorting the items in the Code Information tree
• Toggle on or off expanding the Code Information tree branches.
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:
• Function nodes. Clicking on a function name moves the cursor to the corresponding definition
in the source file.
• DSTACK nodes display the data stack used by the parent function and the total level of the
Data Stack when the program is executed inside the function.
You can quit working with the current Project by using the File|Close All 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.
When saving, the IDE will create a backup file with a .prj~ extension.
3.4 Tools
Using the Tools menu you can execute other programs without exiting the CodeVisionAVR IDE.
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.
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.
This 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:
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 MkII
can be specified using the SCK Freq. listbox. This frequency must not exceed ¼ of the chip's clock
frequency.
The EEPROM|Program check box allows to enable or disable EEPROM programming when the
Program|All menu command is executed or when the 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 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:
• The FLASH memory buffer
• The EEPROM memory buffer.
You can Load or Save the contents of these buffers using the File menu.
Supported file formats are:
• Atmel ELF production files
• Atmel .rom and .eep
• Intel HEX
• Binary .bin
After loading a file in the corresponding buffer, the Start and End addresses are updated accordingly.
You may also edit these addresses if you wish.
The contents of the FLASH, respectively EEPROM, buffers can be displayed and edited using the
Edit|FLASH , respectively Edit|EEPROM menu commands.
When one of these commands is invoked, an Edit window displaying the corresponding buffer
contents will open:
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:
This window lets you specify the Start Address, End Address and Fill Value of the memory area to
be filled.
If you wish to check the chip's signature before any operation you must use the Check Signature
option.
To speed up the programming process you can uncheck the Check Erasure check box.
In this case there will be no verification of the correctness of the FLASH erasure.
The Preserve EEPROM checkbox allows preserving the contents of the EEPROM during chip
erasure.
To speed up the programming process you also can uncheck the Verify check box.
In this case there will be no verification of the correctness of the FLASH and EEPROM programming.
For erasing a chip's FLASH and EEPROM you must select the Program|Erase menu command.
After erasure the chip's FLASH and EEPROM are automatically blank checked.
For simple blank checking you must use the Program|Blank Check menu command.
If you wish to program the FLASH with the contents of the FLASH buffer you must use the
Program|FLASH menu command.
For programming the EEPROM you must use the Program|EEPROM menu command.
After programming the FLASH and EEPROM are automatically verified.
To program the Lock, respectively the Fuse Bit(s) you must use the Program|Fuse Bit(s),
respectively Program|Lock Bits menu commands.
If you wish to read the contents of the chip's FLASH, respectively EEPROM, you must use the
Read|FLASH, respectively Read|EEPROM menu commands.
For reading the chip's signature you must use the Read|Chip Signature menu command.
To read the Lock, respectively the Fuse Bits you must use the Read|Lock Bits,
respectively Read|Fuse Bits menu commands.
For some devices there's also the Read|Calibration Byte(s) option available.
It allows reading the value of the calibration bytes of the chip's internal RC oscillator.
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.
The uploader is executed by selecting the Tools|Upload to Arduino menu command or by pressing
the button on the toolbar.
The Settings group box allows selecting the Arduino Board Type and the serial COM Port used for
communication with the development board.
If the Arduino Board Type is selected as Custom, then any Chip Type with a boot area can be
selected, along with the Communication Protocol and Baud Rate to be used with the boot loader.
The Files group box allows specifying the .hex FLASH and .eep, EEPROM contents files to be
uploaded to the AVR microcontroller.
Pressing the button will open a dialog window, allowing to select the appropriate file.
Note: The boot loaders from some Arduino boards don't support EEPROM programming, therefore
the Files|EEPROM option is disabled in such cases.
Connection to the serial port can be toggled on/off by pressing the Connect/Disconnect /
button.
The characters can be displayed in ASCII or hexadecimal format. The display mode can be toggled
using the ASCII/Hex / 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 on the toolbar.
By pressing the Tx File button, the contents of a file can be transmitted through the serial port.
By pressing the Reset button, the AVR chip on the STK200+/300, STK500, STK600, 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.
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.
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.
Changes can be saved, respectively canceled, using the OK, respectively Cancel buttons.
• The View|Visible Non-Printable Characters option allows to turn on or off the displaying of non-
printable characters in the Editor window. The toolbar button can be also used for this purpose.
• The View|Toolbar option allows to turn on or off the displaying of the various toolbars containing
the IDE command buttons;
• 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;
• 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;
• 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.
The settings can be enabled or disabled by checking or un-checking the appropriate check boxes:
Changes can be saved, respectively canceled, using the OK, respectively Cancel buttons.
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.
The File Load/Save settings allow for the following options to be set:
• 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.
• 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.
• Auto Save Interval specifies at which time interval all the modified source files will be
automatically saved by the Editor.
The Visual Aids settings allow for the following options to be set:
• Show Line Numbers enables or disables the displaying of line numbers on the gutter located on
the left side of the Editor windows;
• Save Bookmarks enables or disables saving the bookmarks set in each edited source file;
• 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.
• Save Folded Lines enables or disables saving the state of the folded blocks of lines for each
edited source file;
• Collapse Mark Text specifies the text foreground color of the collapse marks;
• Collapse Mark Bg. specifies the text background color of the collapse marks;
• 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.
• 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;
• Matching Brace Bg. specifies the text background color of the highlighted matching braces.
• Auto Indent enables or disables text auto indenting during file editing;
• 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.
• 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;
• 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;
• Discard Trailing Spaces enables or disables the automatic deletion from the end of each line, of
spaces that are not followed by text,
• Tab Size specifies the number of spaces the Editor cursor is moved when the user presses the
Tab key;
• Block Indent Size specifies the number of spaces the Editor indents a marked block of text;
• Font specifies the font type used by the Editorl;
• Font Size specifies the font size used by the Editorl;
• Default Text Color specifies the foreground color of the default (normal) text in the Editor and
Terminal windows;
• Default Background Color specifies the background color of the default (normal) text in the Editor
and Terminal windows;
• Highlighted Text Color specifies the foreground color of the text highlighted by the user in the
Editor window;
• Highlighted Background Color specifies the background color of the text highlighted by the user
in the Editor window;
• 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.
The Text, respectively Background, check boxes from the Use Editor Colors group box, when
checked will set the foreground, respectively background, text colors for the selected Language
Element to the default ones specified in the Text|Default Text Color, respectively Text|Default
Background Color settings.
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.
• 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.
• 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 '->' 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.
• Auto Complete C Code enables or disables displaying a pop-up hint window with C keywords,
library functions, data types, predefined macros, based on the first characters of a word typed in the
Editor. The user may select the word to be inserted in the text using the mouse, up/down arrow keys
and validate the selection by pressing the Enter or Space keys.
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.
These colors will be also applied to the character grid pop-up hint window that is invoked using the
Edit|Insert Special Characters menu, the Insert Special Characters right-click pop-up menu or by
pressing the Ctrl+. keys.
The selected source code formatting options can be visualized in the Sample Text window.
• Default Artistic Style - the opening brackets are not changed and the closing brackets will be
broken from the preceding line:
• Kernighan & Ritchie - opening brackets are broken from function definitions.
Brackets are attached to everything else, including statements within a function, arrays, structures,
and enumerations.
• One True Brace – is similar to the Kernighan & Ritchie style, adding brackets to unbracketed one-
line conditional statements.
• Visualization Toolkit – uses broken, indented brackets, except for the opening bracket.
Switch blocks are indented to prevent a 'hanging indent' with following case statements.
The One Line Brackets option allows to insert or remove brackets arround sinle line conditional
statements:
• No change – leaves the text unchanged
• Add – adds brackets:
if (alfa)
alfa = alfa * 2;
becomes:
if (alfa)
{
alfa = alfa * 2;
}
if (alfa)
{
alfa = alfa * 2;
}
becomes:
if (alfa)
alfa = alfa * 2;
The Indent Spaces option specifies the number of spaces per indent, to be applied during text
formatting.
The Indent 'case' in 'switch' Blocks option, if enabled, will add additional indents for case
statements.
switch (alfa)
{
case 1:
alfa = alfa + 20;
break;
case 2:
alfa = alfa + 30;
++alfa;
break;
}
becomes:
switch (alfa)
{
case 1:
alfa = alfa + 20;
break;
case 2:
alfa = alfa * 30;
++alfa;
break;
}
The Indent Code in 'case' Blocks option, if enabled, will indent case blocks from case headers.
Case statements not enclosed in blocks will not be indented.
switch (alfa)
{
case 1:
alfa = alfa + 20;
break;
case 2:
{
alfa = alfa * 30;
++alfa;
break;
}
}
becomes:
switch (alfa)
{
case 1:
alfa = alfa + 20;
break;
case 2:
{
alfa = alfa * 30;
++alfa;
break;
}
}
The Indent Labels option, if enabled, will add extra indentation to labels so they appear one indent
less than the current indentation, rather than being flushed to the left by default.
switch (alfa)
{
case 1:
alfa = alfa + 20;
goto label;
case 2:
label:
alfa = alfa * 30;
++alfa;
break;
}
becomes:
switch (alfa)
{
case 1:
alfa = alfa + 20;
goto label;
case 2:
label:
alfa = alfa * 30;
++alfa;
break;
}
The Indent Preprocessor Blocks option, if enabled, will indent preprocessor blocks located at
bracket level zero.
Note: Blocks within arrays, structures, enumerations and those containing brackets or multi-line
#define statements will not be indented.
#ifdef DEBUG
#include <stdio.h>
#endif
becomes:
#ifdef DEBUG
#include <stdio.h>
#endif
The Indent Preprocessor Conditionals option, if enabled, will indent preprocessor conditional
statements to the same level as the source code.
becomes:
The Indent Multi-Line #defines option, if enabled, will indent multi-line preprocessor definitions
ending with a backslash.
#define TEST_FOO(arg,a,b) \
(foo(arg,a) || \
(foo(arg,b))
becomes:
#define TEST_FOO(arg,a,b) \
(foo(arg,a) || \
(foo(arg,b))
The Indent C++ Style Comments option, if enabled, will indent C++ comments beginning at column
one. By default such comments are assumed to be commented-out code and not indented.
becomes:
The Remove Comment Prefix/Suffix option, if enabled, will remove the preceding/trailing '*'
character that begins/ends a comment line.
/*
* Comment line 1 *
* Comment line 2 *
*/
becomes:
/*
Comment line 1
Comment line 2
*/
The Optimal Fill option, if enabled, will use an optimal mix of tabs and space characters during
indenting. If disabled, indenting will be performed only by inserting spaces.
The Break at Max. Line Length option, if enabled, will insert a line break if the number of
characters/line exceeds the specified value.
The Break Blocks option, if enabled, will insert padding empty lines around header blocks (e.g. 'if',
'for', 'while', etc.).
becomes:
if (alfa)
printf("alfa = %d\r\n",alfa);
else
printf("alfa is zero\r\n");
return alfa*2;
}
The Break 'else if' option, if enabled, will break else if header combinations into separate lines.
becomes:
The Pad Operators with Spaces option, if enabled, will insert padding spaces around operators.
becomes:
The Delete Empty Lines Inside Functions option, if enabled, will remove empty the empty lines
inside a function body.
if (alfa>=0)
printf("alfa is zero or positive\r\n");
else if (alfa<0)
printf("alfa is negative\r\n");
return alfa*2+a;
becomes:
The configuration changes can be saved, respectively canceled, using the OK, respectively Cancel
buttons.
By pressing the Default button the default source code formatting settings are restored.
Before you can invoke the debugger, you must first specify its location and file name using the
Settings|Debugger menu command.
Pressing the 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.
The STK200+, STK300, DT006, VTEC-ISP, JRAVR, ATCPU and Mega2000 in-system programmers
use the parallel printer port.
The following choices are available through the Printer Port radio group box:
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.
The STK500, AVRISP and AVRProg programmers use the RS232C serial communication port, which
can be specified using the Communication Port list box.
The Atmel AVRISP MkII, AVR Dragon, JTAGICE MkII, JTAGICE 3 and Atmel-ICE use the USB
connection for communication with the PC.
Usage of these programmers requires the Atmel Studio 6.2 or later software to be installed on the PC.
The Atmel AVR Dragon, JTAGICE MkII, JTAGICE 3 and Atmel-ICE can use the following
programming modes:
• JTAG
• ISP/PDI
Changes can be saved, respectively canceled, using the OK, respectively Cancel buttons.
The serial communication Terminal is configured using the Settings|Terminal menu command.
The Reset Development Board at Startup option, if enabled, allows to issue a chip reset when the
Terminal is started, if a chip programmer is connected to the AVR microcontroller.
Changes can be saved, respectively canceled, using the OK, respectively Cancel buttons.
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://www.hpinfotech.com
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:
or
Macros can also have parameters. The preprocessor will replace the macro with its expansion and the
formal parameters with the real ones.
Example:
When defining macros you can use the # operator to convert the macro parameter to a character
string.
Example:
/* ...... */
/* the following code sequence will be replaced with printf("Hello"); */
PRINT_MESSAGE(Hello);
#define ALFA(a,b) a ## b
#undef ALFA
The #ifdef, #ifndef, #else and #endif directives may be used for conditional compilation.
The syntax is:
#ifdef macro_name
[set of statements 1]
#else
[set of statements 2]
#endif
If 'alfa' is a defined macro name, then the #ifdef expression evaluates to true and the set of
statements 1 will be compiled.
Otherwise the set of statements 2 will be compiled.
The #else and set of statements 2 are optional.
If 'alfa' is not defined, the #ifndef expression evaluates to true.
The rest of the syntax is the same as that for #ifdef.
The #if, #elif, #else and #endif directives may be also used for conditional compilation.
#if expression1
[set of statements 1]
#elif expression2
[set of statements 2]
#else
[set of statements 3]
#endif
The #line directive can be used to modify the predefined __LINE__ and __FILE__ macros.
The syntax is:
Example:
The #error directive can be used to stop compilation and display an error message.
The syntax is:
#error error_message
Example:
#warning warning_message
Example:
The #message directive can be used to display a message dialog window in the CodeVisionAVR IDE.
The syntax is:
#message general_message
Example:
4.2 Comments
The character string "/*" marks the beginning of a comment.
The end of the comment is marked with "*/".
Example:
/* This is a comment */
/* This is a
multiple line comment */
__eeprom
__flash
__interrupt
__task
_Bool
_Bit
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
4.4 Identifiers
An identifier is the name you give to a variable, function, label or other object.
An identifier can contain letters (A...Z, a...z) and digits (0...9), as well as the underscore character (_).
However an identifier can only start with a letter or an underscore.
Case is significant; i.e. variable1 is not the same as Variable1.
Identifiers can have up to 64 characters.
The bit or _Bit data types are not allowed as the type of an array element, structure/union member,
function parameter or return value.
In order to use the bool data type, the stdbool.h header file must be #included in the source files
where this data type is referenced.
Note: The long64_t, respectively ulong64_t, data types, defined in the math64.h header of the 64-bit
Integer Mathematical Functions, can be used instead of the not supported long long, respectively
unsigned long long, types.
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:
Example:
void main(void) {
/* Local constants declaration */
const long f=22222222;
const float x=1.5;
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:
Example:
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:
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 code efficiency is low, because both FLASH and
RAM memories are used for the string storage. */
display_ram("Hello world");
while(1);
}
For compatibility with AVR GCC programs the pgmspace.h header file is supplied with
CodeVisionAVR.
If contains the following macros:
For the TINY and SMALL memory models (16 bit FLASH address):
pgm_read_byte_near(address_short)
pgm_read_word_near(address_short)
pgm_read_dword_near(address_short)
pgm_read_float_near(address_short)
pgm_read_ptr_near(address_short)
For the MEDIUM and LARGE memory models (32 bit FLASH address):
pgm_read_byte_far(address_long)
pgm_read_word_far(address_long)
pgm_read_dword_far(address_long)
pgm_read_float_far(address_long)
pgm_read_ptr_far(address_long)
pgm_read_byte(address)
pgm_read_word(address)
pgm_read_dword(address)
pgm_read_float(address)
pgm_read_ptr(address)
4.7 Variables
CodeVisionAVR uses the little-endian convention for storing variables: the LSB is always stored at the
lower address or register, the MSB(s) at the consecutive address(es) or register(s).
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:
Example:
void main(void) {
/* Local variables declaration */
char d;
int e;
/* and initialization */
long f=22222222;
}
/* Multidimensional array */
int multidim_array[2][3]={{1,2,3},{4,5,6}};
void main(void) {
/* local array declaration */
int local_array1[10];
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 n++;
}
void main(void) {
int i;
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:
To instruct the compiler to allocate a variable to registers, the register modifier must be used.
Example:
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:
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:
The initialization data for the EEPROM is stored in an .EEP file in Intel hex format.
The contents of this file must programmed to the chip's EEPROM.
4.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 following procedure must be used if a global variable, placed at a specific address using the @
operator, must be initialized during declaration:
bit <identifier>;
Example:
void main(void)
{
if (alfa) beta=!beta;
/* ........ */
}
Memory allocation for the global bit variables is done, in the order of declaration, starting with bit 0 of
GPIOR0, then bit 1 of GPIOR0 and so on, in ascending order.
After all the GPIOR registers are allocated, further bit variables are allocated in R2 up to R14.
If the chip does not have GPIOR registers, the allocation begins directly from register R2.
The size of the global bit variables allocated to the program can be specified in the
Project|Configure|C Compiler|Code Generation|Bit Variables Size list box.
This size should be as low as possible, in order to free registers for allocation to other global variables.
If not specifically initialized, the global bit variables are automatically set to 0 at program startup.
The compiler allows also to declare up to 8 local bit variables which will be allocated in register R15.
Example:
void main(void)
{
bit alfa; /* bit 0 of R15 */
bit beta; /* bit 1 of R15 */
/* ........ */
}
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.
You may specify how many registers in the R2 to R14 range are allocated for global bit variables
using the Project|Configure|C Compiler|Code Generation|Bit Variables Size list box. This value
must be as low as required by the program.
If the Project|Configure|C Compiler|Code Generation|Automatic Global Register Allocation
option is checked or the #pragma regalloc+ compiler directive is used, the rest of registers in the R2
to R14 range, that aren't used for global bit variables, are allocated to char and int global variables
and global pointers.
register unsigned char abc @14; /* the global variable abc is allocated
to the reserved register R14 */
register unsigned char abc=123; /* the variable abc, allocated to R14,
is also initialized with the value 123
during definition */
CodeVisionAVR uses the little-endian convention for storing variables: the LSB is always stored in the
lower register, the MSB in the consecutive register.
If the automatic register allocation is disabled, you can use the register keyword to specify which
global variable to be allocated to registers.
Example:
Local char, int and pointer local variables are allocated to registers R16 to R21.
If the Project|Configure|C Compiler|Code Generation|Smart Register Allocation option is
checked, the allocation of these registers for local variables is performed in such a way that 16bit
variables will be preferably located in even register pairs, thus favouring the usage of the enhanced
core MOVW instruction for their access.
Otherwise the local variables are automatically allocated to registers in the order of declaration.
4.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:
Example:
void main(void) {
/* Local structure */
struct local_structure {
char a;
int b;
long c;
} sl;
/* ............. */
The space allocated to the structure in memory is equal to sum of the sizes of all the members.
The same generic structure type can be declared in any memory type: RAM, FLASH or EEPROM:
void main(void) {
/* Local structure */
struct my_structure sl;
/* Local pointer to the RAM located global structure */
struct my_structure *ptrlsr = &sr;
/* Local pointer to the FLASH located global structure */
flash struct my_structure *ptrlsf = &sf;
/* Local pointer to the EEPROM located global structure */
eeprom struct my_structure *ptrlse = &se;
/* ............. */
void main(void) {
char k1,k2,k3,k4;
int i1, i2;
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, c;
} s={2,3};
/* define the function */
struct alpha *sum_struct(struct alpha *sp) {
/* member c=member a + member b */
sp->c=sp->a + sp->b;
/* return a pointer to the structure */
return sp;
}
void main(void) {
int i;
/* s->c=s->a + s->b */
/* i=s->c */
i=sum_struct(&s)->c;
}
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:
4.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:
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;
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:
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:
4.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:
Example:
void main {
/* the variable days_of_week is initialized with
the integer value 6 */
days_of_week=saturday;
}
The flash or __flash memory attributes must be used to specify enumeration storage in FLASH
memory.
Example:
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.
/* type definitions */
typedef unsigned char byte;
typedef struct {
int a;
char b[5];
} struct_type;
/* variable declarations */
byte alfa;
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.
void main(void) {
int a, c;
long b;
/* The long integer variable b will be treated here as an integer */
c=a+(int) b;
}
void main(void) {
unsigned char a=30;
unsigned char b=128;
unsigned int c;
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.
4.10 Operators
The compiler supports the following operators:
+ -
* /
% ++
-- =
== ~
! !=
< >
<= >=
& &&
| ||
^ ? :
<< >>
-= +=
/= %=
&= *=
^= |=
>>= <<=
sizeof
4.11 Functions
You may use function prototypes to declare a function.
These declarations include information about the function parameters.
Example:
The old Kernighan & Ritchie style of writing function definitions is not supported.
Function parameters are passed through the Data Stack.
Function values are returned in registers R30, R31, R22 and R23 (from LSB to MSB).
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:
4.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:
or
Although the pointers may point to different memory areas, they are by default stored in RAM.
Example:
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:
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 SMALL memory model, except it uses pointers to the
FLASH memory area that are 32 bits wide.
The LARGE memory model can be used for chips with 256kbytes or more of FLASH.
In all memory models pointers to the EEPROM memory area are 16 bit wide.
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];
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 a+b;
}
void main(void) {
int i;
Warnings can also be enabled or disabled individually using the following #pragma format:
#pragma <warn_xxxx><+/->
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:
or
/* Turn optimization on */
#pragma opt+
If the code optimization is enabled, you can optimize some portions or all the program for size or
speed using the #pragma optsize directive.
The default state is determined by the Project|Configure|C Compiler|Code
Generation|Optimization menu setting.
Example:
The default optimization for Size or Speed specified the Project|Configure|C Compiler|Code
Generation|Optimization menu setting can be restored using the #pragma optsize_default
directive.
Example:
The automatic saving and restoring of registers affected by the interrupt handler, can be turned on or
off using the #pragma savereg directive.
Example:
/* 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
The automatic allocation of global variables to registers can be turned on or off using the #pragma
regalloc directive.
The default state is determined by the Project|Configure|C Compiler|Code Generation|Automatic
Global Register Allocation check box.
Example:
The ANSI char to int operands promotion can be turned on or off using the #pragma promotechar
directive.
Example:
Treating char by default as an unsigned 8 bit can be turned on or off using the #pragma uchar
directive.
Example:
The #pragma library directive is used for specifying the necessity to compile/link a specific library file.
Example:
The #pragma glbdef+ directive is used for compatibility with projects, created with versions of
CodeVisionAVR prior to V1.0.2.2, where the Project|Configure|C Compiler|Global #define option
was enabled.
It signals the compiler that macros are globally visible in all the program modules of a project.
This directive must be placed in beginning of the first source file of the project.
By default this directive is not active, so macros are visible only in the program module where they are
defined.
The #pragma vector directive is used for specifying that the next declared function is an interrupt
service routine.
Example:
The #pragma vector directive and the __interrupt keyword are used for compatibility with other C
compilers for the Atmel AVR.
The #pragma keep+ directive forces a function, global variable or global constant to be linked even if
it wasn't used anywhere in the program.
Example:
The #pragma data_alignment=value directive is used to align variables located in RAM at addresses
which are multiples of value.
Example:
#pragma data_alignment=2
The #pragma dstack_par+ directive is used to force passing function parameters using the Data
Stack, even if the Enhanced Parameter Mode 2 is selected in the Project|Configure|C
Compiler|Code Generation menu.
This ensures compatibility with C functions containing inline assembly code, that references the
function's parameters.
The directive remains valid until #pragma dstack_par- or the end of the current C program module is
encountered.
Example:
/* This will force passing the function parameters using the data stack */
#pragma dstack_par+
The pragma lock_bits directive allows embedding lock bits programming data into the production .elf
file created after a successful project build.
This directive can be used only once in the whole program.
The syntax is:
#pragma lock_bits=n
#pragma lock_bits=0x3F
will disable further FLASH and EEPROM programming and reading for an ATmega328P chip.
The pragma fuses directive allows embedding fuse byte(s) programming data into the production .elf
file created after a successful project build.
This directive can be used only once in the whole program.
The syntax is:
where low_byte, high_byte, extended_byte are the values to be used for fuse byte(s) programming.
Example:
#pragma fuses=0xFF,0xDE,0xFD
void main(void)
{
unsigned char a;
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:
void main(void)
{
unsigned char a;
The XMEGA I/O ports can be also accessed using the Virtual Ports:
void main(void)
{
unsigned char a;
More details about accessing I/O ports for the XMEGA chips can be found in the following Atmel
documents:
• AVR1000: Getting Started Writing C-code for XMEGA
• XMEGA A Manual
• XMEGA AU Manual
• XMEGA B Manual
• XMEGA C Manual
• XMEGA D Manual
• XMEGA E Manual
SETBIT(port,b)
Example:
CLRBIT(port,b)
Example:
TGLBIT(port,b)
Example:
EQUBIT(port,b,value)
Example:
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)
Example:
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;
/* ....... */
The same program for XMEGA chips using the Virtual Port VPORT0:
void main(void) {
/* Map PORTA to virtual port VPORT0 and
PORTB to virtual port VPORT1 */
PORTCFG.VPCTRLA=PORTCFG_VP1MAP_PORTB_gc | PORTCFG_VP0MAP_PORTA_gc;
/* ....... */
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 */ };
/* ....... */
}
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.
void main(void) {
int i;
/* Pointer to EEPROM */
int eeprom *ptr_to_eeprom;
For compatibility with AVR GCC programs, the eeprom.h header file is supplied with CodeVisionAVR.
It contains the following macros and functions:
eeprom_read_byte(addr)
eeprom_read_word(addr)
eeprom_read_dword(addr)
eeprom_read_float(addr)
Reads a block of n bytes, pointed by src, from EEPROM to RAM, pointed by dst.
eeprom_write_byte(addr, value)
eeprom_write_word(addr, value)
Writes the unsigned short value starting with EEPROM address addr.
eeprom_write_dword(addr, value)
Writes the unsigned long value starting with EEPROM address addr.
eeprom_write_float(addr, value)
Writes the unsigned short value starting with EEPROM address addr.
Writes a block of n bytes, pointed by src, from RAM to EEPROM, pointed by dst.
eeprom_update_byte(addr, value)
eeprom_update_word(addr, value)
Writes the unsigned short value starting with EEPROM address addr.
eeprom_update_dword(addr, value)
Writes the unsigned long value starting with EEPROM address addr.
eeprom_update_float(addr, value)
Writes the unsigned short value starting with EEPROM address addr.
Writes a block of n bytes, pointed by src, from RAM to EEPROM, pointed by dst.
Note: For CodeVisionAVR both the EEPROM write and update macros/functions are equivalent.
They check if the EEPROM location contains the same data as the value to be written to.
In this case no write is performed in order to not wear out the EEPROM.
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:
The #pragma vector preprocessor directive and the __interrupt keyword are used for compatibility
with other C compilers for the Atmel AVR.
The automatic saving and restoring of registers affected by the interrupt handler, can be turned on or
off using the #pragma savereg directive.
Example:
/* 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
The Working Registers area contains 32x8 bit general purpose working registers.
The register usage depends on the type of the AVR core for which code is generated:
• standard core: the compiler uses the following registers: R0, 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.
If Enhanced Parameter: Mode 2 is selected in the Project|Configure|C Compiler|Code
Generation menu, then the remaining registers R16 to R21, that were not allocated for local
variables, are used for storing char and int function parameters.
• reduced core (ATtiny10): the compiler uses the following registers: R16, R17, R22, R23, R24,
R25, R26, R27, R28, R29, R30 and R31.
No registers may be allocated by the compiler for global and local bit variables.
Registers R18 to R21 are allocated for local char and int variables.
If Enhanced Parameter: Mode 2 is selected in the Project|Configure|C Compiler|Code
Generation menu, then the remaining registers R18 to R21, that were not allocated for local
variables, are used for storing char and int function parameters.
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:
• standard core: R0, R1, R15, R22, R23, R24, R25, R26, R27, R30, R31 and SREG
• reduced core: R16, R17, R22, R23, R24, R25, R26, R27, R30, R31 and SREG.
The following modes, specified in the Project|Configure|C Compiler|Code Generation menu, are
used for function parameter passing and storage:
• Enhanced Parameter: No - all function parameters are passed using the Data Stack and
accessed using the LDD Rn, Y+d and STD Y+d,Rn instructions
• Enhanced Parameter: Mode 1 - all function parameters, except the last one, are passed using
the Data Stack.
The last parameter is passed in registers R26 for 1 byte, R26, R27 for 2 byte and R26, R27, R24, R25
for 4 byte parameters.
However in the function prologue this last parameter is pushed in the Data Stack too.
So in this mode all function parameters are also accessed using the LDD Rn, Y+d and STD Y+d,Rn
instructions.
Better code size is obtained, because register accessing instructions are used when passing the last
function parameter during function call.
• Enhanced Parameter: Mode 2 - all function parameters, except the last one, are passed using
the Data Stack.
The last parameter is passed in registers R26 for 1 byte, R26, R27 for 2 byte and R26, R27, R24, R25
for 4 byte parameters.
In the function prologue the function parameters are copied from the Data Stack or registers R26,
R27, R24, R25 to the registers R16..R21, that were not allocated for local variables.
In this mode function parameters that could be allocated/copied to registers R16..R21 are accessed
using more efficient instructions.
The rest of the parameters are still accessed using the LDD Rn, Y+d and STD Y+d,Rn instructions.
Even better code size is obtained, because register accessing instructions are used when passing the
last parameter and for accessing the parameters stored in registers inside the function.
Note: If this mode is used for programs which contain functions that use inline assembly code to
access function parameters, then such functions must be enclosed between #pragma dstack+ and
#pragma dstack- like in the following example:
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 program execution the Hardware Stack grows downwards to the Global Variables area.
When configuring the compiler you have the option to place the strings DSTACKEND, respectively
HSTACKEND, at the end of the Data Stack, respectively Hardware Stack areas.
When you debug the program with AVR Studio you may see if these strings are overwritten, and
consequently modify the Data Stack Size using the Project|Configure|C Compiler|Code
Generation menu command.
When your program runs correctly, you may disable the placement of the strings in order to reduce
code size.
The Heap is a memory area located between the Hardware Stack and the RAM end.
It is used by the memory allocation functions from the Standard Library (stdlib.h): malloc, calloc,
realloc and free.
The Heap size must be specified in the Project|Configure|C Compiler|Code Generation menu.
It can be calculated using the following formulae:
n
heap _ size = ( n + 1) ⋅ 4 + ∑ block _ sizei
i =1
where: n is the number of memory blocks that will be allocated in the Heap
block _ sizei 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.
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-2013 Pavel Haiduc, HP InfoTech s.r.l.
;CLEAR R2-R14
LDI R24,13
LDI R26,2
CLR R27
__CLEAR_REG:
ST X+,R30
DEC R24
BRNE __CLEAR_REG
;CLEAR RAM
LDI R24,LOW(__CLEAR_SIZE)
LDI R25,HIGH(__CLEAR_SIZE)
LDI R26,LOW(__CLEAR_START)
LDI R27,HIGH(__CLEAR_START)
__CLEAR_RAM:
ST X+,R30
SBIW R24,1
BRNE __CLEAR_RAM
#endif
The __CLEAR_START and __CLEAR_SIZE constants can be changed to specify which area of RAM
to clear at program initialization.
The __GLOBAL_INI_TBL label must be located at the start of a table containing the information
necessary to initialize the global variables located in RAM. This table is automatically generated by the
compiler.
The registers R0, 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.
/* This will force passing the function parameters using the data stack */
#pragma dstack_par+
/* Re-enable warnings */
#pragma warn+
void main(void) {
int r;
The functions return their values in the registers (from LSB to MSB):
• R30 for char and unsigned char
• R30, R31 for int and unsigned int
• R30, R31, R22, R23 for long and unsigned long.
So our function must return its result in the R30, R31 registers.
After the return from the function the compiler automatically generates code to reclaim the Data Stack
space used by the function parameters.
The #pragma warn- compiler directive will prevent the compiler from generating a warning that the
function does not return a value.
This is needed because the compiler does not know what it is done in the assembler portion of the
function.
1. Create a header .h file with the prototypes of the library functions using the File|New|Source File
menu command, by pressing the Ctrl+N keys or the and buttons on the toolbar.
A new editor window will be opened for the untitled.c source file.
Type in the prototype for your function. Example:
Save the file, using the File|Save As menu command or the toolbar button, in the .\INC directory
using the File|Save As menu command, for example mylib.h :
Create the library file using the File|New|Source File menu command, by pressing the Ctrl+N keys or
the and buttons on the toolbar.
A new editor window will be opened for the untitled.c source file.
Type in the definitions for your functions.
Example:
Save the file, under a new name, for example mylib.c , in any directory using the File|Save As menu
command or the toolbar button:
Finally use the File|Convert to Library menu command or the toolbar button, to save the currently
opened .c file under the name mylib.lib in the .\LIB directory:
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 <mylib.h>
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.
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 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 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 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.
The following syntax is used when invoking the compiler from the command line:
where project_file is the full path of the project .prj file created/modified using the CodeVisionAVR
IDE. The path must be enclosed between " " if it contains long file names.
-b [options] [-m <message_out_file>] Build project - only the modified source files
are re-compiled
-ba [options] [-m <message_out_file>] Build All project files – all source files are
re-compiled
-s <source_file> [-m <message_out_file>] Check Syntax for source_file
-cl Cleanup project directory.
If the –m argument is used, the output of the command line compiler is written to the
message_out_file, otherwise it is directed to the console.
Examples:
Re-compiles all source files in the ds1820.prj project and outputs the results to the console.
Re-compiles all source files in the ds1820.prj project, outputs the build results to the GUI and
automatically programs the chip using the AVRISP MKII programmer with a SCK frequency of 115200
Hz.
All messages will be also written to the messages.txt file, that will be located in the directory where
the ds1820.prj project file is located.
Re-compiles all source files in the ds1820.prj project, defining the additional global preprocessor
macro BAUD_RATE with the value 9600.
Checks the syntax for the ds1820.c file from the ds1820.prj project and writes the results to the
messages.txt file.
The sample code for these Application Notes can be easily compiled with CodeVisionAVR.
For this purpose the header file avr_compiler.h supplied for each Application Note must be replaced
with the same file located in the ..\INC directory of the CodeVisionAVR installation.
4.24 Hints
In order to decrease code size and improve the execution speed, you must apply the following rules:
• If possible use unsigned variables;
• Use the smallest data type possible, i.e. bit and unsigned char;
• 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;
• If possible use the smallest possible memory model (TINY or SMALL);
• Always store constant strings in FLASH by using the flash or __flash memory models;
• After finishing debugging your program, compile it again with the Stack End Markers option
disabled.
4.25 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
• date and time functions (time.h) are not implemented
• extended multibyte/wide character utilities (wchar.h) are not implemented
• wide character classification and mapping utilities (wctype.h) are not implemented
• the printf, sprintf, snprintf, vprintf, vsprintf and vsnprintf Standard C Input/Output Functions
can't output strings longer than 255 characters for the %s format specifier
• the size of the compiled code is limited for the Evaluation version
• XMEGA TWI EBI, RTC and RTC32 support are not available in the Evaluation version
• the libraries for color graphic displays are available and can be used only with Advanced licenses.
Note: The long64_t, respectively ulong64_t, data types, defined in the math64.h header of the 64-bit
Integer Mathematical Functions, can be used instead of the not supported long long, respectively
unsigned long long, types.
You must #include the appropriate header files for the library functions that you use in your program.
Example:
void main(void) {
int a,b;
a=-99;
/* Here you actually use the functions */
b=abs(a);
putsf("Hello world");
}
returns 1 if c is alphanumeric.
returns 1 if c is alphabetic.
char toascii(char c)
char tolower(char c)
char toupper(char c)
The standard C language I/O functions were adapted to work on embedded microcontrollers with
limited resources.
char getchar(void)
void putchar(char c)
Example:
#include <mega8515.h>
#include <stdio.h>
/* Baud rate */
#define baud 9600
void main(void) {
char k;
while (1) {
/* receive the character */
k=getchar();
/* and echo it back */
putchar(k);
};
}
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 <stdio.h>
For the XMEGA chips the getchar and putchar functions use by default the USARTC0.
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:
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.
outputs, using putchar, the null terminated character string str, located in RAM, followed by a new
line character.
outputs, using putchar, the null terminated character string str, located in FLASH, followed by a
new line character.
outputs formatted text, using putchar, according to the format specifiers in the fmtstr string.
The format specifier string fmtstr is constant and must be located in FLASH memory.
The implementation of printf is a reduced version of the standard C function.
This was necessary due to the specific needs of an embedded system and because the full
implementation would require a large amount of FLASH memory space.
The function returns the number of outputed characters.
%[flags][width][.precision][l]type_char
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 optional precision specifier sets the maximal number of characters or minimal number of integer
digits that may be outputted.
For the 'e', 'E' and 'f' conversion type characters the precision specifier sets the number of digits that
will be outputted to the right of the decimal point.
The precision specifier always begins with a '.' character in order to separate it from the width
specifier.
The following precision specifiers are supported:
none - the precision is set to 1 for the 'i', 'd', 'u', 'x', 'X' conversion type characters. For the 's' and
'p' conversion type characters, the char string will be outputted up to the first null character;
.0 - the precision is set to 1 for the 'i', 'd', 'u', 'x', 'X' type characters;
.n - n characters or n decimal places are outputted.
For the 'i', 'd', 'u', 'x', 'X' conversion type characters, if the value has less than n digits, then it will be
padded on the left with zeros. If it has more than n digits then it will not be truncated.
For the 's' and 'p' conversion type characters, no more than n characters from the char string will be
outputted.
For the 'e', 'E' and 'f' conversion type characters, n digits will be outputted to the right of the decimal
point.
The precision specifier has no effect on the 'c' conversion type character.
The optional 'l' input size modifier specifies that the function argument must be treated as a long int for
the 'i', 'd', 'u', 'x', 'X' conversion type characters.
The type_char conversion type character is used to specify the way the function argument will be
treated.
The following conversion type characters are supported:
'i' - the function argument is a signed decimal integer;
'd' - the function argument is a signed decimal integer;
'u' - the function argument is an unsigned decimal integer;
'e' - the function argument is a float, that will be outputted using the [-]d.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.
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 other memory models.
this function is identical to sprintf except that at most size (including the null terminator)
characters are placed in the character string str.
The function returns the number of outputed characters.
The more features are selected, the larger is the code size generated for the printf and sprintf
functions.
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.
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 function 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.
inputs, using getchar, the character string str terminated by the new line character.
The new line character will be replaced with 0.
The maximum length of the string is len. If len characters were read without encountering the new line
character, then the string is terminated with 0 and the function ends.
The function returns a pointer to str.
signed char scanf(char flash *fmtstr [ , arg1 address, arg2 address, ...])
formatted text input by scanning, using getchar, a series of input fields according to the format
specifiers in the fmtstr string.
The format specifier string fmtstr is constant and must be located in FLASH memory.
The implementation of scanf is a reduced version of the standard C function.
This was necessary due to the specific needs of an embedded system and because the full
implementation would require a large amount of FLASH memory space.
The format specifier string has the following structure:
%[width][l]type_char
The optional width specifier sets the maximal number of characters to read. If the function encounters
a whitespace character or one that cannot be converted, then it will continue with the next input field, if
present.
The optional 'l' input size modifier specifies that the function argument 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.
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.
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.
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.
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.
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 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).
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.
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.
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 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).
this function is identical to vprintf 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 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).
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).
float fabs(float x)
sets the starting value seed used by the pseudo-random number generator in the rand function.
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.
Notes:
• The allocated memory block occupies size+4 bytes in the heap.
• An additional 4 bytes of heap are also used by the dynamic memory allocation functions.
This must be taken into account when specifying the Heap size in the Project|Configure|C
Compiler|Code Generation menu (total size of allocated blocks + 4 bytes).
If there wasn't enough contiguous free memory in the heap to allocate, the function returns a null
pointer.
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.
frees a memory block allocated in the heap by the malloc, calloc or realloc functions and pointed
by the ptr pointer.
After being freed, the memory block is available for new allocation.
If ptr is null then it is ignored.
float sqrt(float x)
float floor(float x)
float ceil(float x)
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.
returns x * 2expn.
float exp(float x)
returns ex .
float log(float x)
float log10(float x)
returns xy .
float sin(float x)
returns the sine of the floating point number x, where the angle is expressed in radians.
float cos(float x)
returns the cosine of the floating point number x, where the angle is expressed in radians.
float tan(float x)
returns the tangent of the floating point number x, where the angle is expressed in radians.
float sinh(float x)
returns the hyperbolic sine of the floating point number x, where the angle is expressed in radians.
float cosh(float x)
returns the hyperbolic cosine of the floating point number x, where the angle is expressed in
radians.
float tanh(float x)
returns the hyperbolic tangent of the floating point number x, where the angle is expressed in
radians.
float asin(float x)
returns the arc sine of the floating point number x (in the range -PI/2 to PI/2).
x must be in the range -1 to 1.
float acos(float x)
returns the arc cosine of the floating point number x (in the range 0 to 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).
returns the arc tangent of the floating point numbers y/x (in the range -PI to PI).
The 64-bit integers are stored in the following structure data types, defined in the math64.h header
file:
The long64_t, respectively ulong64_t, data types should be used instead of the standard C long
long, respectively unsigned long long types.
The value ranges are:
• -9223372036854775808 to 9223372036854775807 for the long64_t type
• 0 to 18446744073709551615 for the ulong64_t type.
The __INIT64(n) macro is defined in math64.h, in order to be able to initialize during declaration a
long64_t or ulong64_t variable, with a numeral n.
Example:
Note: the LL, respectively ULL, sufixes are used to specify that the numerals must be considered as
64-bit signed, respectively unsigned, integers.
#include <math64.h>
void main(void)
{
/* Assign the numeral -100000000000000000 to a */
__EQU64(a,-100000000000000000LL);
Assigning long64_t or ulong64_t variables between them, follows the standard C syntax.
Example:
#include <math64.h>
void main(void)
{
/* Declare the 64-bit local variables */
long64_t a=__INIT64(100000000000000000LL);
long64_t b;
b=a;
}
Assigning a 8-bit, 16-bit or 32-bit value to a long64_t, respectively ulong64_t, variable must be
performed using the tolong64, respectively tolong64u, functions defined in math64.h:
long64_t tolong64(long x)
returns the 32-bit unsigned long integer x promoted to an unsigned 64-bit integer.
Example:
#include <math64.h>
void main(void)
{
long64_t a;
ulong64_t b;
long c=-12345678L;
unsigned long d=12345678UL;
a=tolong64(c); /* a=-12345678 */
b=tolong64u(d); /* b=12345678 */
}
Truncating a long64_t or ulong64_t to a 8-bit, 16-bit or 32-bit value can be performed by simply
accessing the lo member of the structure.
Example:
#include <math64.h>
void main(void)
{
long64_t a=__INIT64(-12345678LL);
ulong64_t b=__INIT64(12345678ULL);
long64_t c=__INIT64(0xABCD00000000LL);
long d;
unsigned long e;
long f;
d=a.lo; /* c=-12345678 */
e=b.lo; /* d=12345678 */
f=c.lo; /* f=0 */
}
Example:
#include <math64.h>
void main(void)
{
long64_t a=__INIT64(-10000000000000000LL);
long64_t b=__INIT64(8);
long64_t c;
c=add64(a,b); /* c= -9999999999999992 */
}
long64_t neg64(long64_t x)
ulong64_t abs64(long64_t x)
returns -1, 0 or 1 if the value of the 64-bit signed integer x is negative, zero or positive.
ulong64_t com64(ulong64_t x)
ulong64_t not64(ulong64_t x)
performs an arithmetic shift right by n bits, on the 64-bit signed integer pointed by x.
Example:
#include <math64.h>
void main(void)
{
long64_t a=__INIT64(-8000000000000000LL);
performs a logic shift right by n bits, on the 64-bit unsigned integer pointed by x.
performs a logic shift left by n bits, on the 64-bit unsigned integer pointed by x.
Example:
#include <math64.h>
void main(void)
{
ulong64_t a=__INIT64(8000000000000000LL);
Example:
#include <math64.h>
void main(void)
{
long64_t a=__INIT64(-8000000000000000LL);
converts the NULL terminated char string pointed by str, containing the decimal
representation of a signed number, to a 64-bit signed integer.
Note: The function skips past preceding white space characters and converts the numeral as long as
decimal digits are present.
Example:
#include <math64.h>
void main(void)
{
long64_t a;
a=atol64(buffer); /* a=-8000000000000000 */
}
converts the NULL terminated char string pointed by str, containing the hexadecimal
representation of an unsigned number, to a 64-bit unsigned integer.
Note: The function skips past preceding white space characters and converts the numeral as long as
hexadecimal digits are present.
Example:
#include <math64.h>
void main(void)
{
long64_t a;
a=xtol64(buffer); /* a=0xABCD1234567890 */
}
converts the 64-bit signed integer x to characters in the NULL terminated char string str, in
decimal representation.
Note: The char buffer pointed by str must have at least 21 characters, so that it can hold the largest
converted decimal 64-bit value, including the '-' sign and the NULL string terminator.
Example:
#include <io.h>
#include <stdio.h>
#include <math64.h>
char buffer[32];
void main(void)
{
long64_t a=__INIT64(-8000000000000000LL);
long64_t b=__INIT64(8);
converts the 64-bit unsigned integer x to characters in the NULL terminated char string str, in
hexadecimal representation.
Note: The char buffer pointed by str must have at least 17 characters, so that it can hold the largest
converted hexadecimal 64-bit value, including the NULL string terminator.
void printl64(long64_t x)
outputs the 64-bit signed integer x in decimal format, using the putchar Standard C
Input/Output function.
Example:
#include <io.h>
#include <stdio.h>
#include <math64.h>
void main(void)
{
long64_t a=__INIT64(-8000000000000000LL);
long64_t b=__INIT64(8);
printf("a + b = ");
printf("\r\n");
}
void printx64(ulong64_t x)
outputs the 64-bit unsigned integer x in hexadecimal format, using the putchar Standard C
Input/Output function.
Note: Additional information on the usage of the 64-bit Integer Mathematical Functions can be
found in the example program supplied with the compiler and located in the \Examples\AVR\64-Bit
Math subdirectory of the CodeVisionAVR installation.
The string manipulation functions were extended to handle strings located both in RAM and FLASH
memories.
concatenate the string str2, located in FLASH, to the end of the string str1.
concatenate maximum n characters of the string str2 to the end of the string str1.
Returns a pointer to the string str1.
concatenate maximum n characters of the string str2, located in FLASH, to the end of the string
str1.
Returns a pointer to the string str1.
returns a pointer to the first occurrence of the character c in the string str, else a NULL pointer.
returns a pointer to the first occurrence of the character c in the string str, else a NULL pointer.
returns a pointer to the last occurrence of the character c in the string str located in FLASH
memory, else a NULL pointer.
returns a pointer to the last occurrence of the character c in the string str located in FLASH
memory, else a NULL pointer.
returns the index to first occurrence of the character c in the string str, else -1.
returns the index to the last occurrence of the character c in the string str, else -1.
compares the string str1, located in RAM, with the string str2, located in FLASH.
Returns <0, 0, >0 according to str1<str2, str1=str2, str1>str2.
compares at most n characters of the string str1 with the string str2.
Returns <0, 0, >0 according to str1<str2, str1=str2, str1>str2.
compares at most n characters of the string str1, located in RAM, with the string str2, located in
FLASH.
Returns <0, 0, >0 according to str1<str2, str1=str2, str1>str2.
copies the string src, located in FLASH, to the string dest, located in RAM.
Returns a pointer to the string dest.
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.
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.
copies at most n 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 the size of the src string.
copies at most n 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.
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.
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.
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.
searches the string str for the first occurrence of a character from the string set, located in FLASH.
If there is a match, returns the index of the character in str.
If there are no matching characters, returns the length of str.
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.
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.
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.
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.
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.
searches the string str1, located in RAM, for the first occurrence of the string str2, located in
FLASH.
If there is a match, returns a pointer to the character in str1 where str2 begins.
If there is no match, returns a NULL pointer.
scans the string str1, located in RAM, for the first token not contained in the string str2, located in
FLASH.
The function considers the string str1 as consisting of a sequence of text tokens, separated by spans
of one or more characters from the string str2.
The first call to strtok, with the pointer to str1 being different from NULL, returns a pointer to the first
character of the first token in str1. Also a NULL character will be written in str1, immediately after the
returned token.
Subsequent calls to strtok, with NULL as the first parameter, will work through the string str1 until no
more tokens remain. When there are no more tokens, strtok will return a NULL pointer.
returns the length of the string str located in FLASH, excluding the null terminator.
Copies n bytes from src to dest. dest must not overlap src, else use memmove.
Returns a pointer to dest.
Copies n bytes from src, located in FLASH, to dest. Returns a pointer to dest.
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.
Compares at most n bytes of buf1, located in RAM, with buf2, located in FLASH.
Returns <0, 0, >0 according to buf1<buf2, buf1=buf2, buf1>buf2.
This macro, when used in a function with a variable length argument list, initializes the argptr pointer
of va_list type, for subsequent use by the va_arg and va_end macros.
The previous_par argument must be the name of the function argument immediately preceding the
optional arguments.
The va_start macro must be called prior to any access using the va_arg macro.
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 <stdarg.h>
/* initialize argptr */
va_start(argptr,nsum);
return result;
}
void main(void)
{
int s;
/* calculate the sum of 5 arguments */
s=sum_all(5,10,20,30,40,50);
}
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 0 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.
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 <mega8515.h>
#include <stdio.h>
#include <setjmp.h>
void foo(void)
{
printf("Now we will make a long jump to main()\n\r");
longjmp(cpu_state,1);
}
/* 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 j;
if (setjmp(cpu_state)==0)
{
printf("First call to setjmp\n\r");
foo();
}
else
printf("We jumped here from foo()\n\r");
}
Convert the number n from Gray code representation to its binary equivalent.
Convert the number n from binary representation to its Gray code equivalent.
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.
The appropriate header file must be #include -d before using the functions.
The LCD functions do support both the XMEGA and non-XMEGA chips.
The following LCD formats are supported in alcd.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.
Example:
13 D6 - 7 PC6
14 D7 - 8 PC7
void main(void)
{
/* initialize the LCD for 2 lines & 16 columns */
lcd_init(16);
initializes the LCD module, clears the display and sets the printing character position at row 0 and
column 0. The numbers of columns of the LCD must be specified (e.g. 16). No cursor is displayed.
This is the first function that must be called before using the other high level LCD Functions.
void lcd_clear(void)
clears the LCD and sets the printing character position at row 0 and column 0.
sets the current display position at column x and row y. The row and column numbering starts
from 0.
void lcd_putchar(char c)
displays at the current display position the string str, located in RAM.
displays at the current display position the string str, located in FLASH.
displays at the current display position the string str, located in EEPROM.
int lcd_printfxy(unsigned char x, unsigned char y, char flash *fmtstr [ , arg1, arg2, ...])
outputs formatted text, at specified screen coordinates, according to the format specifiers in the
fmtstr string.
Parameters:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
outputs formatted text, at current display position, according to the format specifiers in the fmtstr
string.
Parameters:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
Prior to #include -ing the lcd4x40.h file, you must declare which microcontroller port is used for
communication with the LCD module.
Example:
You must also connect the LCD power supply and contrast control voltage, according to the data
sheet.
void _lcd_ready(void)
Prior calling the low level functions _lcd_ready and _lcd_write_data, the global variable _en1_msk
must be set to LCD_EN1, respectively LCD_EN2, to select the upper, respectively lower half, LCD
controller.
Example:
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 lcd_clear(void)
clears the LCD and sets the printing character position at row 0 and column 0.
sets the current display position at column x and row y. The row and column numbering starts
from 0.
void lcd_putchar(char c)
displays at the current display position the string str, located in RAM.
displays at the current display position the string str, located in FLASH.
int lcd_printfxy(unsigned char x, unsigned char y, char flash *fmtstr [ , arg1, arg2, ...])
outputs formatted text, at specified screen coordinates, according to the format specifiers in the
fmtstr string.
Parameters:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
outputs formatted text, at current display position, according to the format specifiers in the fmtstr
string.
Parameters:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
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 lcdstk.h: 1x8, 2x12, 3x12, 1x16, 2x16, 2x20, 4x20, 2x24
and 2x40 characters.
void _lcd_ready(void)
The _LCD_RS0, respectively _LCD_RS1, macros are used for accessing the LCD Instruction Register
with RS=0, respectively RS=1.
Example:
Chip: ATmegaS8515
Memory Model: SMALL
Data Stack Size: 128 bytes
void main(void)
{
/* initialize the LCD for 2 lines & 16 columns */
lcd_init(16);
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 lcd_clear(void)
clears the LCD and sets the printing character position at row 0 and column 0.
sets the current display position at column x and row y. The row and column numbering starts
from 0.
void lcd_putchar(char c)
displays at the current display position the string str, located in RAM.
displays at the current display position the string str, located in FLASH.
int lcd_printfxy(unsigned char x, unsigned char y, char flash *fmtstr [ , arg1, arg2, ...])
outputs formatted text, at specified screen coordinates, according to the format specifiers in the
fmtstr string.
Parameters:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
outputs formatted text, at current display position, according to the format specifiers in the fmtstr
string.
Parameters:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
The appropriate header file must be #include -d before using the functions.
The libraries for the XMEGA and AVR8X chips support only hardware TWI.
The following LCD formats are supported: 1x8, 2x12, 3x12, 1x16, 2x16, 2x20, 4x20, 2x24 and 2x40
characters.
The library supports two types of Arduino I²C interface shields using the PCF8754 expander with the
following signal connections:
• "YwRobot Arduino LCM1602 IIC V1" or "LCM1602 IIC"
[PCF8574] [LCD]
P0 RS
P1 R/W
P2 EN
P3 Backlight On control, active for logic 1
P4 DATA4
P5 DATA5
P6 DATA6
P7 DATA7
• "Arduino-IIC-LCD GY-LCD-V1"
[PCF8574] [LCD]
P0 DATA4
P1 DATA5
P2 DATA6
P3 DATA7
P4 EN
P5 R/W
P6 RS
P7 Backlight On control, active for logic 0
Notes:
• The LCD power supply and contrast control voltage must also be connected according to the
module data sheet.
• If the "Arduino-IIC-LCD GY-LCD-V1" Arduino shield is used, the following global macro must be
defined in the Project|Configure|C Compiler|Global #define menu:
GY_LCD_V1 1
Example:
Example:
void main(void)
{
/* initialize the LCD for 2 lines & 16 columns */
lcd_i2c_init(PCF8574_ADDR,16);
initializes the LCD module for communication using the bit-banged I²C library, clears the display
and sets the printing character position at row 0 and column 0.
No cursor is displayed.
Parameters:
pcf8574_addr specifies the PCF8574 7-bit I2C slave address set by the logic state of the A0, A1
and A2 pins: 0x20..0x27 for PCF8574 and 0x38..0x3F for PCF8574A.
columns specifies the number of columns of the LCD (e.g. 16).
Notes:
• The alcd_i2c.h header file must be #included.
• This is the first function that must be called before using the other LCD Functions with the bit-
banged I²C interface. Please see above example for usage.
initializes the LCD module for communication using the hardware TWI, clears the display and sets
the printing character position at row 0 and column 0.
No cursor is displayed.
Parameters:
pcf8574_addr specifies the PCF8574 7-bit I2C slave address set by the logic state of the A0,
A1 and A2 pins: 0x20..0x27 for PCF8574 and 0x38..0x3F for PCF8574A.
columns specifies the number of columns of the LCD (e.g. 16).
Notes:
• The alcd_twi.h header file must be #included.
• Before calling this function, the TWI interface must be properly initialized, using the appropriate
functions and the interrupts must be enabled using the #asm("sei") inline assembly code.
• This is the first function that must be called before using the other LCD Functions.
Example:
void main(void)
{
/* initialize the TWI in master mode with 100 kHz bit rate */
twi_master_init(100);
lcd_putsf("Hello World");
initializes the LCD module for communication using the hardware TWI, clears the display and sets
the printing character position at row 0 and column 0.
No cursor is displayed.
Parameters:
twi_master is a pointer to the structure that holds information used by the TWI master
XMEGA or AVR8X module for performing a TWI bus transaction
pcf8574_addr specifies the PCF8574 7-bit I2C slave address set by the logic state of the A0,
A1 and A2 pins: 0x20..0x27 for PCF8574 and 0x38..0x3F for PCF8574A.
columns specifies the number of columns of the LCD (e.g. 16).
Notes:
• The alcd_twi.h header file must be #included.
• Before calling this function, the TWI interface must be properly initialized, using the appropriate
functions and the interrupts must be enabled using the #asm("sei") inline assembly code.
• This is the first function that must be called before using the other LCD Functions.
void main(void)
{
/* general TWID initialization
no external driver interface
no SDA hold time */
twi_init(&TWID,false,false);
lcd_putsf("Hello World");
void main(void)
{
/* general TWI0 initialization
SDA setup time 4 clock cycles
no SDA hold time
no Fast Plus mode */
twi_init(&TWI0,TWI_SDASETUP_4CYC_gc,TWI_SDAHOLD_OFF_gc,false);
lcd_putsf("Hello World");
void lcd_clear(void)
clears the LCD and sets the printing character position at row 0 and column 0.
sets the current display position at column x and row y. The row and column numbering starts
from 0.
void lcd_putchar(char c)
displays at the current display position the string str, located in RAM.
displays at the current display position the string str, located in FLASH.
displays at the current display position the string str, located in EEPROM.
int lcd_printfxy(unsigned char x, unsigned char y, char flash *fmtstr [ , arg1, arg2, ...])
outputs formatted text, at specified screen coordinates, according to the format specifiers in the
fmtstr string.
Parameters:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
outputs formatted text, at current display position, according to the format specifiers in the fmtstr
string.
Parameter:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
Note: The ..\EXAMPLES\AVR\I2C LCD directory contains fully functional code samples that may be
used as references.
Before using these functions, the type of the graphic display 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 Display menu.
The following graphic display controllers are supported:
Note: The library functions for color TFT displays are supported only for the Advanced or Professional
CodeVisionAVR licenses.
The Graphic Display 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:
• GLCDBLOCKMODE_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 display
overwriting previous display data */
GLCD_PUTXOR, /* copy a bitmap from memory to display
performing a XOR with previous display data */
GLCD_PUTOR, /* copy a bitmap from memory to display
performing an OR with previous display data */
GLCD_PUTNOT, /* copy a bitmap from memory to display
performing a bit negation */
GLCD_PUTAND, /* copy a bitmap from memory to display
performing an AND with previous display data */
GLCD_PUTTP, /* used for displaying image in tranparent mode */
GLCD_GET /* 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 */
} GLCDBLOCKMODE_t;
Notes:
• The GLCD_PUTXOR, GLCD_PUTOR, GLCD_PUTNOT, GLCD_PUTAND modes are supported
only for displays with 2 colors (monochrome).
• The GLCD_PUTTP mode is supported only for displays with more than 2 colors.
• GLCDMEMADDR_t type used for specifying RAM, EEPROM, FLASH or external memory
addresses for bitmap image storage
• GLCDTEXT_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.
• 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;
typedef struct
{
GLCDX_t x;
GLCDY_t y;
} GLCDPOINT_t;
• GLCDFILL_t structure type used for specifying the fill style parameters:
typedef struct
{
GLCDCOL_t color; /* fill color */
typedef struct
{
GLCDX_t x; /* arc x center coordinate */
GLCDY_t y; /* arc y center coordinate */
GLCDX_t xstart; /* arc start x coordinate */
GLCDY_t ystart; /* arc start y coordinate */
GLCDX_t xend; /* arc end x coordinate */
GLCDY_t yend; /* arc end y coordinate */
} GLCDARCCOORDS_t;
• GLCDINIT_t structure type used for specifying various parameters used for initializing the display
controller:
typedef struct
{
flash unsigned char *font; /* default font after initialization */
} GLCDINIT_t;
• GLCDSTATE_t structure type used for specifying the graphic display state:
typedef struct
{
GLCDCOL_t fgcolor; /* foreground color */
GLCDCOL_t bkcolor; /* background color */
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 */
Note: The tpcolor transparency color member is available only for displays with more than 2 colors.
• 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 predefined by the compiler based on the settings from the
Project|Configure|C Compiler|Libraries|Graphic Display menu:
initializes the graphic display controller and performs the following initializations of the
graphic system:
• clears the display
• sets the current plot coordinates to (0,0)
• 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 0 (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 display 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 display controller will be used for displaying text.
In this situation the 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 display controller will be used, including
the internal character generator, if present.
Return values:
Example:
return data;
}
void main(void)
{
GLCDINIT_t init;
/* Specify the function used for reading data from external memory.
If not used, set value to NULL */
init.readxmem=read_ext_memory;
Parameter:
Sets the current foreground color that will be used for displaying text and graphics.
Parameter:
Sets the current background color that will be used for displaying text and graphics.
Parameter:
Parameter:
Note: This function is available only for displays with more than 2 colors.
GLCDCOL_t glcd_getcolor(void)
GLCDCOL_t glcd_getbkcolor(void)
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.
GLCDCOL_t glcd_getmaxcolor(void)
GLCDX_t glcd_getmaxx(void)
GLCDY_t glcd_getmaxy(void)
void glcd_clear(void)
Clears the display by setting it's color to the current background color.
Parameters:
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 this function.
Parameters:
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:
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:
Parameters:
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 coordinate.
GLCDY_t glcd_gety(void)
Returns the value of the current pixel plot position vertical coordinate.
Parameters:
font_name points to an array located in FLASH memory, that holds the font definition.
Parameters:
horiz specifies the horizontal spacing between displayed characters, measured in pixels
vert specifies the vertical spacing between displayed characters, measured in pixels.
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.
Returns the text height (in pixels) for the current font, including the vertical justification.
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:
Returns the text width (in pixels) of a NULL terminated literal char string located in FLASH
for the current font, including the horizontal justification.
Parameter:
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:
Returns the width and height (in pixels) of the rectangular screen area needed to display a
NULL terminated literal char string, containing multiple lines of text terminated with the '\n' character,
for the current font including the horizontal and vertical justifications.
The width of the area will be the displayed size of the longest line of text.
Parameters:
Returns the width and height (in pixels) of the rectangular screen area needed to display a
NULL terminated literal char string located in FLASH memory, containing multiple lines of text
terminated with the '\n' character, for the current font including the horizontal and vertical justifications.
The width of the area will be the displayed size of the longest line of text.
Parameters:
Returns the width and height (in pixels) of the rectangular screen area needed to display a
NULL terminated literal char string located in EEPROM, containing multiple lines of text terminated
with the '\n' character, for the current font including the horizontal and vertical justifications.
The width of the area will be the displayed size of the longest line of text.
Parameters:
Parameter:
Note: The glcd_transparent function is defined only for displays with more than 2 colors.
Parameters:
x specifies the horizontal coordinate of the left top corner of the 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:
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.
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.
Displays a NULL terminated literal char string located 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.
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:
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:
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:
Displays a NULL terminated character string located in RAM, containing multiple lines of text
terminated with the '\n' character, starting from the specified x, y coordinates.
The start of the text lines will have an offset of x pixels from the left edge of the screen.
Parameters:
x specifies the horizontal coordinate of the left top corner of the first displayed character in a
line of text
y specifies the vertical coordinate of the left top corner of the first displayed character
str pointer to the literal char string.
Displays a NULL terminated character string located in FLASH memory, containing multiple
lines of text terminated with the '\n' character, starting from the specified x, y coordinates.
The start of the text lines will have an offset of x pixels from the left edge of the screen.
Parameters:
x specifies the horizontal coordinate of the left top corner of the first displayed character in a
line of text
y specifies the vertical coordinate of the left top corner of the first displayed character
str pointer to the literal char string.
Displays a NULL terminated character string located in EEPROM, containing multiple lines of
text terminated with the '\n' character, starting from the specified x, y coordinates.
The start of the text lines will have an offset of x pixels from the left edge of the screen.
Parameters:
x specifies the horizontal coordinate of the left top corner of the first displayed character in a
line of text
y specifies the vertical coordinate of the left top corner of the first displayed character
str pointer to the literal char string.
outputs formatted text, at specified screen coordinates, according to the format specifiers in the
fmtstr string.
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
fmtstr pointer to the format specifier string, located in FLASH memory.
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
outputs formatted text, at current display position, according to the format specifiers in the fmtstr
string.
Parameters:
The supported format specifiers are identical to those of the printf Standard C Input/Output Function.
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
memt specifies the memory type to/from which the data will be written/read.
It may take one of the following values:
addr specifies the memory address to/from which the data will be written/read
mode specifies the operation to be performed:
Notes:
• The glcd_block function doesn't access the text overlay display, if present.
• The GLCD_PUTXOR, GLCD_PUTOR, GLCD_PUTNOT, GLCD_PUTAND modes are supported
only for displays with 2 colors (monochrome).
• The GLCD_PUTTP mode is supported only for displays with more than 2 colors.
Returns the memory size in bytes needed to store a rectangular bitmap image.
Parameters:
Return values:
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:
Return values:
Notes:
• The GLCD_PUTXOR, GLCD_PUTOR, GLCD_PUTNOT, GLCD_PUTAND modes are supported
only for displays with 2 colors (monochrome).
• The GLCD_PUTTP mode is supported only for displays with more than 2 colors.
unsigned long glcd_putimagef(GLCDX_t left, GLCDY_t top, flash unsigned char *pimg,
GLCDBLOCKMODE_t mode)
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:
Return values:
Notes:
• The GLCD_PUTXOR, GLCD_PUTOR, GLCD_PUTNOT, GLCD_PUTAND modes are supported
only for displays with 2 colors (monochrome).
• The GLCD_PUTTP mode is supported only for displays with more than 2 colors.
unsigned long glcd_putimagee(GLCDX_t left, GLCDY_t top, eeprom unsigned char *pimg,
GLCDBLOCKMODE_t mode)
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:
Return values:
Notes:
• The GLCD_PUTXOR, GLCD_PUTOR, GLCD_PUTNOT, GLCD_PUTAND modes are supported
only for displays with 2 colors (monochrome).
• The GLCD_PUTTP mode is supported only for displays with more than 2 colors.
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:
Return values:
Notes:
• The GLCD_PUTXOR, GLCD_PUTOR, GLCD_PUTNOT, GLCD_PUTAND modes are supported
only for displays with 2 colors (monochrome).
• 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)
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:
unsigned long glcd_getimagee(GLCDX_t left, GLCDY_t top, GLCDX_t width, GLCDY_t height,
eeprom unsigned char *pimg)
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:
unsigned long glcd_getimagex(GLCDX_t left, GLCDY_t top, GLCDX_t width, GLCDY_t height,
GLCDMEMADDR_t addr)
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 image will be written.
Return values:
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:
Parameter:
thickness specifies the thickness of the lines to be drawn on the display, measured in
pixels.
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:
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:
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.
Draws a triangle with the current foreground color, line thickness and bit pattern.
The current pixel plot position will be updated to the third point of the triangle.
Parameters:
Parameters:
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
right 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.
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.
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.
Draws a rectangle with rounded corners, filled using the current fill color.
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.
Draws a polygon using the current foreground 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:
Example:
void main(void)
{
GLCDINIT_t init;
/* Stop here */
while (1);
}
Draws a circle at specified center coordinates using the current foreground color and line
thickness.
Parameters:
Parameters:
Fills a GLCDARCCOORDS_t type structure with information about the last call to the
glcd_arc function.
Parameter:
Draws an ellipse at specified center coordinates using the current line color and thickness.
Parameters:
Draws an ellipse at specified center coordinates using the current fill color.
Parameters:
Sets an user defined 8x8 pixel fill pattern from RAM, used by the glcd_bar and glcd_barrel
functions, and the fill color.
Parameters:
Sets an user defined 8x8 pixel fill pattern from FLASH, used by the glcd_bar and
glcd_barrel functions, and the fill color.
Parameters:
Sets an user defined 8x8 pixel fill pattern from EEPROM, used by the glcd_bar and
glcd_barrel functions, and the fill color.
Parameters:
Parameters:
GLCDCOL_t glcd_getfillcolor(void)
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.
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.
Parameters:
Draws and fills a circle at specified center coordinates using the current fill color.
Parameters:
Draws a pie slice at specified center coordinates using the current foreground color and 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:
In order to take full advantage of the ILI9225 controller's features, the following specific functions,
declared in the glcd_ili9225.h header file, were implemented:
Writes a command to the ILI9225 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_ili9225.h header
file:
A detailed description of the above mentioned command registers can be found in the ILI9225
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_ili9225.h header file also contains the definition of the GLCDINIT_t type specific for the
ILI9225 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM */
/* =0 -> RGB, =1 ->BGR */
unsigned char lcd_type:1; /* LCD type =0 normally black, =1
normally white */
unsigned char vci1:4; /* VCI1 voltage */
unsigned char vcoml:7; /* VCOML=GVDD*(0.534+0.006*(vcoml-15)) [V]
*/
unsigned char vcomh:7; /* VCOMH=GVDD*(0.4015+0.0055*vcomh) [V] */
unsigned char gamma_voltage:7; /* GVDD=2.50+gamma_voltage*0.02 [V]
*/
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 ILI9225 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ili9225.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ili9225.h.
• The ..\EXAMPLES\Graphic Displays\ILI9225 directory contains fully functional code samples that
may be used as references for ILI9225 initialization and usage.
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:
Writes a command to the ILI9325 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_ili9325.h header
file:
A detailed description of the above mentioned command registers can be found in the ILI9325
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_ili9325.h header file also contains the definition of the GLCDINIT_t type specific for the
ILI9325 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
/* power control registers bits */
unsigned char stepup_factor:3; /* step-up factor of the step-up
circuit, see BT0..BT2 bits in
the datasheet */
unsigned char stepup_freq1:3; /* controls the frequency for the
step-up circuit 1 */
unsigned char stepup_freq2:3; /* controls the frequency for the
step-up circuit 2 */
unsigned char crt_source:3; /* adjusts the amount of current
from the constant current source
in the internal op. amplififier
circuit (AP0..AP2 bits) */
unsigned char vreg1out:4; /* adjusts the VREG1OUT voltage */
unsigned char vcom:5; /* adjusts the amplitude of the Vcom
alternating drive voltage based on
VREG1OUT voltage */
unsigned char vcomh:6; /* adjusts the amplitude of the VcomH
voltage based on VREG1OUT voltage
VcomH=VREG1OUT*(vcomh*0.005+0.685) [V] */
unsigned char frame_freq:4; /* LCD frame frequency */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ili9325.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ili9325.h.
• The ..\EXAMPLES\Graphic Displays\ILI9325 directory contains fully functional code samples that
may be used as references for ILI9325 initialization and usage.
In order to take full advantage of the ILI9328 controller's features, the following specific functions,
declared in the glcd_ili9328.h header file, were implemented:
Writes a command to the ILI9328 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_ili9328.h header
file:
A detailed description of the above mentioned command registers can be found in the ILI9328
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_ili9328.h header file also contains the definition of the GLCDINIT_t type specific for the
ILI9328 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
/* power control registers bits */
unsigned char stepup_factor:3; /* step-up factor of the step-up
circuit, see BT0..BT2 bits in
the datasheet */
unsigned char stepup_freq1:3; /* controls the frequency for the
step-up circuit 1 */
unsigned char stepup_freq2:3; /* controls the frequency for the
step-up circuit 2 */
unsigned char crt_source:3; /* adjusts the amount of current
from the constant current source
in the internal op. amplififier
circuit (AP0..AP2 bits) */
unsigned char vreg1out:4; /* adjusts the VREG1OUT voltage */
unsigned char vcom:5; /* adjusts the amplitude of the Vcom
alternating drive voltage based on
VREG1OUT voltage */
unsigned char vcomh:6; /* adjusts the amplitude of the VcomH
voltage based on VREG1OUT voltage
VcomH=VREG1OUT*(vcomh*0.005+0.685) [V] */
unsigned char frame_freq:4; /* LCD frame frequency */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 ILI9328 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ili9328.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ili9328.h.
• The ..\EXAMPLES\Graphic Displays\ILI9328 directory contains fully functional code samples that
may be used as references for ILI9328 initialization and usage.
In order to take full advantage of the ILI9331 controller's features, the following specific functions,
declared in the glcd_ili9331.h header file, were implemented:
Writes a command to the ILI9331 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_ili9331.h header
file:
A detailed description of the above mentioned command registers can be found in the ILI9331
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_ili9331.h header file also contains the definition of the GLCDINIT_t type specific for the
ILI9331 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
/* power control registers bits */
unsigned char stepup_factor:3; /* step-up factor of the step-up
circuit, see BT0..BT2 bits in
the datasheet */
unsigned char stepup_freq1:3; /* controls the frequency for the
step-up circuit 1 */
unsigned char stepup_freq2:3; /* controls the frequency for the
step-up circuit 2 */
unsigned char crt_source:3; /* adjusts the amount of current
from the constant current source
in the internal op. amplififier
circuit (AP0..AP2 bits) */
unsigned char vreg1out:4; /* adjusts the VREG1OUT voltage */
unsigned char vcom:5; /* adjusts the amplitude of the Vcom
alternating drive voltage based on
VREG1OUT voltage */
unsigned char vcomh:6; /* adjusts the amplitude of the VcomH
voltage based on VREG1OUT voltage
VcomH=VREG1OUT*(vcomh*0.005+0.685) [V] */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 ILI9331 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ili9331.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ili9331.h.
• The ..\EXAMPLES\Graphic Displays\ILI9331 directory contains fully functional code samples that
may be used as references for ILI9331 initialization and usage.
In order to take full advantage of the ILI9340 controller's features, the following specific functions,
declared in the glcd_ili9340.h header file, were implemented:
Parameter:
This command may take one of the values defined in the following macros from the glcd_ili9340.h
header file:
Writes data byte(s) to the ILI9340 controller after a command was issued using the
ili9340_wrcmd function.
Parameter:
Reads result data byte(s) from the ILI9340 controller after a command was issued using the
ili9340_wrcmd function.
Note: When used immediately after ili9340_wrcmd, this function must be called twice.
The result of the first call is a dummy read and it is not valid.
Writes color data for 1 pixel to the ILI9340 controller's display RAM.
Parameter:
GLCDCOL_t ili9340_rddram(void)
Reads color data for 1 pixel from the ILI9340 controller's display RAM.
Puts the ILI9340 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:
• A delay of minimum 120ms must be present after exiting the sleep mode and entering sleep mode
again.
The glcd_ili9340.h header file also contains the definition of the GLCDINIT_t type specific for the
ILI9340 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
unsigned char vrh:6; /* set VRH=3.0+(vrh-3)*0.05 [V] */
unsigned char vci1:4; /* set VCI1=2.30+vci1*0.05 [V] */
unsigned char vcoml:7; /* set VCOML=-2.5+vcoml*0.025 [V] */
unsigned char vcomh:7; /* set VCOMH=2.7+vcomh*0.025 [V] */
unsigned char vcom_offset:7; /* set VCOM offset=VM+vcom_offset-64
*/
unsigned char lcd_type:1; /* LCD type =0 normally black,
=1 normally white */
unsigned char scan_mode:1; /* set vertical scan mode
=0 interlaced,
=1 non-interlaced */
unsigned char frame_rate:5; /* set vertical frame rate 61..119Hz */
unsigned char gamma_curve:2; /* selects the gamma curve used by
the device */
} GLCDINIT_t;
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 ILI9340 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ili9340.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ili9340.h.
• The ..\EXAMPLES\Graphic Displays\ILI9340 directory contains fully functional code samples that
may be used as references for ILI9340 initialization and usage.
In order to take full advantage of the ILI9341 controller's features, the following specific functions,
declared in the glcd_ili9341.h header file, were implemented:
Parameter:
This command may take one of the values defined in the following macros from the glcd_ili9341.h
header file:
Writes data byte(s) to the ILI9341 controller after a command was issued using the
ili9341_wrcmd function.
Parameter:
Reads result data byte(s) from the ILI9341 controller after a command was issued using the
ili9341_wrcmd function.
Note: When used immediately after ili9341_wrcmd, this function must be called twice.
The result of the first call is a dummy read and it is not valid.
Writes color data for 1 pixel to the ILI9341 controller's display RAM.
Parameter:
GLCDCOL_t ili9341_rddram(void)
Reads color data for 1 pixel from the ILI9341 controller's display RAM.
Puts the ILI9341 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:
• A delay of minimum 120ms must be present after exiting the sleep mode and entering sleep mode
again.
The glcd_ili9341.h header file also contains the definition of the GLCDINIT_t type specific for the
ILI9341 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
unsigned char pump_ratio:1; /* =0 -> DDVDH=2xVCI,
=1 -> DDVDH=3xVCI */
unsigned char ddvdh_enh_mode:1; /* DDVDH enhanced mode
=0 -> disable,
=1 -> enable */
unsigned char cr_timing:1;
unsigned char eq_timing:1;
unsigned char precharge_timing:2;
unsigned char vrh:6; /* set VRH=3.0+(vrh-3)*0.05 [V] */
unsigned char vcoml:7; /* set VCOML=-2.5+vcoml*0.025 [V] */
unsigned char vcomh:7; /* set VCOMH=2.7+vcomh*0.025 [V] */
unsigned char vcom_offset:7; /* set VCOM offset=VM+vcom_offset-64
*/
unsigned char lcd_type:1; /* LCD type =0 normally black,
=1 normally white */
unsigned char scan_mode:1; /* set vertical scan mode
=0 interlaced,
=1 non-interlaced */
unsigned char frame_rate:5; /* set vertical frame rate 61..119Hz */
} GLCDINIT_t;
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 ILI9341 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ili9341.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ili9341.h.
• The ..\EXAMPLES\Graphic Displays\ILI9341 directory contains fully functional code samples that
may be used as references for ILI9341 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_pcd8544.h
header file:
A detailed description of the above mentioned commands can be found in the PCD8544 datasheet.
Parameter:
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 glcd_init function:
typedef struct
{
flash unsigned char *font; /* default font after initialization */
The detailed description of the above mentioned initialization parameters can be found in the
PCD8544 datasheet.
Notes:
• 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.
• The ..\EXAMPLES\Graphic Displays\PCD8544 directory contains fully functional code samples
that may be used as references for PCD8544 initialization and usage.
In order to take full advantage of the RA8875 controller's features, the following specific functions,
declared in the glcd_ra8875.h header file, were implemented:
Parameters:
The register may take one of the values defined in the following macros from the glcd_ra8875.h
header file:
Parameter:
The returned status byte will contain the following status bits set/reset, as defined in the
glcd_ra8875.h header file:
void ra8875_membusy(void)
Waits until the RA8875 controller completes the current memory read/write operation.
void ra8875_btebusy(void)
Waits until the RA8875 controller completes the current BTE operation.
void ra8875_dmabusy(void)
Waits until the RA8875 controller completes the current DMA operation.
void ra8875_memwr(void)
Writes color data to the graphic display memory after the ra8875_memwr function was
executed.
Parameter:
Note: The ra8875_wrdata function can be executed multiple times, without the need for a new
ra8875_memwr function call, until a new command will be issued to one of the RA8875 registers.
void ra8875_memrd(void)
GLCDCOL_t ra8875_rddata(void)
Reads color data from the graphic display memory after the ra8875_memrd function was
executed.
Note: The ra8875_rddata function can be executed multiple times, without the need for a new
ra8875_memrd function call, until a new command will be issued to one of the RA8875 registers.
Parameters:
Parameter:
Sets the foreground color for graphic memory fill and drawing operations.
Parameter:
ra8875_settpcolor(GLCDCOL_t color)
Sets the background transparent color for graphic memory fill and drawing operations.
Parameter:
color to be used as transparent background, for graphic memory fill and drawing operations.
Puts the RA8875 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.
Note: The function automatically inserts a 10ms delay after exiting the sleep mode in order to allow
the controller's PLL to stabilize itself.
The glcd_ra8875.h header file also contains the definition of the GLCDINIT_t type specific for the
RA8875 controller, used as parameter for the glcd_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 short osc_clk; /* external crystal oscillator frequency
15000..30000 [kHz] */
unsigned short pixel_clk; /* TFT LCD pixel clock frequency [kHz]
*/
} GLCDINIT_t;
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 RA8875 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:
• Bits 0..1 - Blue color bits 0..1
• Bits 2..4 - Green color bits 0..2
• Bits 5..7 - Red color bits 0..2.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ra8875.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ra8875.h.
• The ..\EXAMPLES\Graphic Displays\RA8875 directory contains fully functional code samples
that may be used as references for RA8875 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_s1d13700.h
header file:
A detailed description of the above mentioned commands can be found in the S1D13700 datasheet.
Parameter:
Notes:
• The glcd_s1d13700.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_s1d13700.h.
• The ..\EXAMPLES\Graphic Displays\S1D13700 directory contains fully functional code samples
that may be used as references for S1D13700 initialization and usage.
In order to take full advantage of the S6D0164 controller's features, the following specific functions,
declared in the glcd_s6d0164.h header file, were implemented:
Writes a command to the S6D0164 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_s6d0164.h
header file:
A detailed description of the above mentioned command registers can be found in the S6D0164
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_s6d0164.h header file also contains the definition of the GLCDINIT_t type specific for the
S6D0164 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
unsigned char lcd_type:1; /* LCD type =0 normally black,
=1 normally white */
unsigned char vci1:4; /* VCI1 voltage */
unsigned char vcoml:7; /* VCOML=GVDD*(0.534+0.006*(vcoml-15))
[V] */
unsigned char vcomh:7; /* VCOMH=GVDD*(0.4015+0.0055*vcomh) [V] */
unsigned char gamma_voltage:7; /* GVDD=2.50+gamma_voltage*0.02
[V] */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 S6D0164 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_s6d0164.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_s6d0164.h.
• The ..\EXAMPLES\Graphic Displays\S6D0164 directory contains fully functional code samples
that may be used as references for S6D0164 initialization and usage.
In order to take full advantage of the S6D1121 controller's features, the following specific functions,
declared in the glcd_s6d1121.h header file, were implemented:
Writes a command to the S6D1121 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_s6d1121.h
header file:
A detailed description of the above mentioned command registers can be found in the S6D1121
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_s6d1121.h header file also contains the definition of the GLCDINIT_t type specific for the
S6D1121 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
unsigned char lcd_type:1; /* LCD type =0 normally black,
=1 normally white */
unsigned char vci1:3; /* VCI1 voltage */
unsigned char vcoml:6; /* VCOML=2.52+vcoml*0.04 [V] */
unsigned char vcomh:6; /* VCOMH=3.52+(vcomh-10)*0.033 [V] */
unsigned char vcomdc:6; /* VCOMDC=2.40+vcomdc*0.03125 [V] */
unsigned char gamma_voltage:6; /* GVDD=3+gamma_voltage*0.03 [V] */
/* pointer to an array located in FLASH memory
which contains gamma control adjustment
values for registers 1..14 */
flash unsigned short *gamma_control;
} GLCDINIT_t;
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 S6D1121 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_s6d1121.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_s6d1121.h.
• The ..\EXAMPLES\Graphic Displays\S6D1121 directory contains fully functional code samples
that may be used as references for S6D1121 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_sed1335.h
header file:
A detailed description of the above mentioned commands can be found in the SED1335 datasheet.
Parameter:
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:
• When the glcd_init function is called, it enables BUSY flag testing, so that the display will not
flicker.
• The glcd_sed1335.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_sed1335.h.
• The ..\EXAMPLES\Graphic Displays\SED1335 directory contains fully functional code samples
that may be used as references for SED1335 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_sed1530.h
header file:
A detailed description of the above mentioned commands can be found in the SED1530 datasheet.
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 glcd_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 display horizontally (ADC) */
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 (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:
The detailed description of the above mentioned initialization parameters can be found in the
SED1530 datasheet.
Notes:
• The glcd_sed1530.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_sed1530.h.
• The ..\EXAMPLES\Graphic Displays\SED1530 directory contains fully functional code samples
that may be used as references for SED1530 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_splc501.h
header file:
A detailed description of the above mentioned commands can be found in the SPLC501C datasheet.
Parameter:
contrast sets the value of the V5 LCD drive voltage, allowed range is 0..63.
The glcd_splc501.h header file also contains the definition of the GLCDINIT_t type specific for the
SPLC501C controller, used as parameter for the glcd_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);
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the
SPLC501C datasheet.
Notes:
• The glcd_splc501.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_splc501.h.
• The ..\EXAMPLES\Graphic Displays\SPLC501C directory contains fully functional code samples
that may be used as references for SPLC501C initialization and usage.
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:
Writes a command to the SSD1289 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_ssd1289.h
header file:
A detailed description of the above mentioned command registers can be found in the SSD1289
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_ssd1289.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD1289 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
/* power control registers bits */
unsigned char stepup_factor:3; /* step-up factor of the step-up
circuit, see BT0..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 (AP0..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; /* PKP00..PKP02 positive gamma micro adj. */
unsigned char pkp10: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; /* PRP00..PRP02 positive gamma gradient
adj. */
unsigned char prp10:3; /* PRP10..PRP12 positive gamma gradient
adj. */
unsigned char vrp00:4; /* VRP00..VRP03 positive gamma amplification
adj. */
unsigned char vrp10:5; /* VRP10..VRP14 positive gamma amplification
adj. */
/* negative gamma control registers bits */
unsigned char pkn00:3; /* PKN00..PKN02 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; /* PRN00..PRN02 negative gamma gradient
adj. */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
#define SSD1289_DEFAULT_PKN30 2
/* PKN40..PKN42 negative gamma micro adj. */
#define SSD1289_DEFAULT_PKN40 4
/* PKN50..PKN52 negative gamma micro adj. */
#define SSD1289_DEFAULT_PKN50 2
/* PRN00..PRN02 negative gamma gradient adj. */
#define SSD1289_DEFAULT_PRN00 2
/* PRN10..PRN12 negative gamma gradient adj. */
#define SSD1289_DEFAULT_PRN10 5
/* VRN00..VRN03 negative gamma amplification adj. */
#define SSD1289_DEFAULT_VRN00 2
/* VRN10..VRN14 negative gamma amplification adj. */
#define SSD1289_DEFAULT_VRN10 3
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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ssd1289.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1289.h.
• The ..\EXAMPLES\Graphic Displays\SSD1289 directory contains fully functional code samples
that may be used as references for SSD1289 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_ssd1303.h
header file:
#define SSD1303_CMD_COM0_63 0xC0 /* sets the COM output scan direction 0->63 */
#define SSD1303_CMD_COM63_0 0xC8 /* sets the COM output scan direction 63->0 */
A detailed description of the above mentioned commands can be found in the SSD1303 datasheet.
Parameter:
contrast sets the contrast value, the allowed range being 0..255.
The glcd_ssd1303.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD1303 controller, used as parameter for the glcd_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);
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the
SSD1303 datasheet.
Notes:
• The glcd_ssd1303.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1303.h.
• The ..\EXAMPLES\Graphic Displays\SSD1303 directory contains fully functional code samples
that may be used as references for SSD1303, SH1101A initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_ssd1306.h
header file:
#define SSD1306_CMD_COM0_63 0xC0 /* sets the COM output scan direction 0->63 */
#define SSD1306_CMD_COM63_0 0xC8 /* sets the COM output scan direction 63->0 */
A detailed description of the above mentioned commands can be found in the SSD1306 datasheet.
Parameter:
contrast sets the contrast value, the allowed range being 0..255.
The glcd_ssd1306.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD1306 controller, used as parameter for the glcd_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 (ADC) */
unsigned char
reverse_y:1; /* reverse display vertically (COM) */
unsigned char
interlaced:1; /* use vertically interlaced display */
unsigned char
external_vcc:1; /* =0 Vcc is generated by the
internal DC/DC converter
=1 Vcc is applied from an external
source */
unsigned char contrast; /* OLED display contrast */
} GLCDINIT_t;
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the
SSD1306 datasheet.
Notes:
• The glcd_ssd1306.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1306.h.
• The ..\EXAMPLES\Graphic Displays\SSD1306 directory contains fully functional code samples
that may be used as references for SSD1306 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_ssd1309.h
header file:
#define SSD1309_CMD_COM0_63 0xC0 /* sets the COM output scan direction 0->63 */
#define SSD1309_CMD_COM63_0 0xC8 /* sets the COM output scan direction 63->0 */
A detailed description of the above mentioned commands can be found in the SSD1309 datasheet.
Parameter:
contrast sets the contrast value, the allowed range being 0..255.
The glcd_ssd1309.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD1309 controller, used as parameter for the glcd_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 (ADC) */
unsigned char
reverse_y:1; /* reverse display vertically (COM) */
unsigned char
interlaced:1; /* use vertically interlaced display */
unsigned char
external_vcc:1; /* =0 Vcc is generated by the
internal DC/DC converter
=1 Vcc is applied from an external
source */
unsigned char contrast; /* OLED display contrast */
} GLCDINIT_t;
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the
SSD1309 datasheet.
Notes:
• The glcd_ssd1309.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1309.h.
• The ..\EXAMPLES\Graphic Displays\SSD1309 directory contains fully functional code samples
that may be used as references for SSD1309 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_ssd1322.h
header file:
A detailed description of the above mentioned commands can be found in the SSD1322 datasheet.
Parameter:
Parameter:
contrast sets the contrast value, the allowed range being 0..127.
The glcd_ssd1322.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD1322 controller, used as parameter for the glcd_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 divset:4; /* Front clock divider */
unsigned char osc_freq:4; /* Oscillator frequency */
unsigned char phase1:4; /* Phase 1 period */
unsigned char phase2:4; /* Phase 2 period */
/* Pre-charge voltage= Vcc*(0.2+precharge_v*0.01275) */
unsigned char precharge_v:5;
unsigned char vcomh:3; /* VCOMH voltage= Vcc*(0.72+vcomh*0.02) */
/* horizontal segment offset of pixel with x=0 */
unsigned char offset_x0;
unsigned char reverse_x:1; /* reverse display horizontally */
unsigned char reverse_y:1; /* reverse display vertically */
unsigned char com_split:1; /* enable odd/even split of COM pins */
unsigned char dual_com:1; /* =0 - disable dual COM mode
=1 - enable dual COM mode */
Note: The offset_x0 configuration parameter, representing the OLED display's segment number
which corresponds to the pixel with the horizontal coordinate x=0 is usually 0.
However the DD-12864 and DD-25664 displays, manufactured by Densitron, have the segment 112
connected to the pixel with x=0.
So for these displays offset_x0=112.
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the
SSD1322 datasheet.
The following example shows how to initialize the SSD1322 controller with an user defined gray scale
table:
#include <io.h>
#include <stdio.h>
#include <glcd.h>
void main()
{
GLCDINIT_t glcd_init_data;
while (1)
}
Notes:
• The glcd_ssd1322.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1322.h.
• The ..\EXAMPLES\Graphic Displays\SSD1322 directory contains fully functional code samples
that may be used as references for SSD1322 initialization and usage.
• lines
• rectangles
• filled rectangles
• filled circles
• filled ellipses.
The following functions, declared in the glcd_ssd1331.h header file, were implemented:
Parameter:
This command may take one of the values defined in the following macros from the glcd_ssd1331.h
header file:
A detailed description of the above mentioned commands can be found in the SSD1331 datasheet.
void ssd1331_busy(void)
Waits until the controller has finished executing a hardware accelerated drawing command.
Parameter:
Parameter:
contrast sets the contrast value, the allowed range being 0..15.
The glcd_ssd1331.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD1331 controller, used as parameter for the glcd_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 divset:4; /* Front clock divider */
unsigned char osc_freq:4; /* Oscillator frequency */
unsigned char phase1:4; /* Phase 1 period: 1..15 [DCLK cycles] */
unsigned char phase2:4; /* Phase 2 period: 1..15 [DCLK cycles] */
unsigned char precharge_v:5; /* Pre-charge voltage=
Vcc*(0.1+precharge_v*0.0125) */
unsigned char vcomh:5; /* VCOMH voltage= Vcc*(0.44+vcomh*0.0122) */
unsigned char reverse_x:1; /* reverse display horizontally */
unsigned char reverse_y:1; /* reverse display vertically */
unsigned char color_bgr:1; /* =0 - color order: R, G, B
=1 - color order: B, G, R */
unsigned char com_split:1; /* enable odd/even split of COM pins
(interlaced display) */
unsigned char precharge_t2_red; /* Second pre-charge period
[DCLK cycles] for red color */
unsigned char precharge_t2_green; /* Second pre-charge period
[DCLK cycles] for green
color */
unsigned char precharge_t2_blue; /* Second pre-charge period
[DCLK cycles] for blue
color */
unsigned char contrast_red; /* Contrast current= ISEG*contrast
for red color */
unsigned char contrast_green; /* Contrast current= ISEG*contrast
for green color */
unsigned char contrast_blue; /* Contrast current= ISEG*contrast
for blue color */
unsigned char master_current:4; /* Reduce the output current for
all colors to
(master_current+1)/16 */
flash unsigned char *gray_scale_table; /* pointer to gray scale
table for gamma correction
(array located in FLASH
with 32 byte values
A NULL pointer specifies
to use the default
table */
} GLCDINIT_t;
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the
SSD1331 datasheet.
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 SSD1331 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:
• Bits 0..1 - Blue color bits 0..1
• Bits 2..4 - Green color bits 0..2
• Bits 5..7 - Red color bits 0..2.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ssd1331.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1331.h.
• The ..\EXAMPLES\Graphic Displays\SSD1331 directory contains a fully functional code example
that may be used as references for SSD1331 initialization and usage.
• lines
• rectangles
• filled rectangles
• filled circles
• filled ellipses.
The following functions, declared in the glcd_ssd1332.h header file, were implemented:
Parameter:
This command may take one of the values defined in the following macros from the glcd_ssd1332.h
header file:
A detailed description of the above mentioned commands can be found in the SSD1332 datasheet.
void ssd1332_busy(void)
Waits until the controller has finished executing a hardware accelerated drawing command.
Parameter:
Parameter:
contrast sets the contrast value, the allowed range being 0..15.
The glcd_ssd1332.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD1332 controller, used as parameter for the glcd_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 divset:4; /* Front clock divider */
unsigned char osc_freq:4; /* Oscillator frequency */
unsigned char phase1:4; /* Phase 1 period: 1..15 [DCLK cycles] */
unsigned char phase2:4; /* Phase 2 period: 1..15 [DCLK cycles] */
unsigned char vcomh:5; /* VCOMH voltage= Vcc*(0.44+vcomh*0.0122) */
unsigned char reverse_x:1; /* reverse display horizontally */
unsigned char reverse_y:1; /* reverse display vertically */
unsigned char com_split:1; /* enable odd/even split of COM pins
(interlaced display) */
unsigned char vp_red; /* Precharge Voltage for red color
(0.43+vp_red*0.00445)*Vref [V] */
unsigned char vp_green; /* Precharge Voltage for green color
(0.43+vp_green*0.00445)*Vref [V] */
unsigned char vp_blue; /* Precharge Voltage for blue color
(0.43+vp_blue*0.00445)*Vref [V] */
unsigned char contrast_red; /* Contrast current= ISEG*contrast
for red color */
unsigned char contrast_green; /* Contrast current= ISEG*contrast
for green color */
unsigned char contrast_blue; /* Contrast current= ISEG*contrast
for blue color */
unsigned char master_current:4; /* Reduce the output current for
all colors to
(master_current+1)/16 */
flash unsigned char *gray_scale_table; /* pointer to gray scale
table for gamma correction
(array located in FLASH
with 32 byte values)
A NULL pointer specifies
to use the default
table */
} GLCDINIT_t;
Note: The SSD1332 controller doesn't allow changing the color scan order: RGB or BGR by
hardware.
This function is accomplished by software in the library.
In order to specify the desired color order, select one of the following options in the
Project|Configure|Libraries|Graphic Displays menu:
• SSD1332 96x64 OLED 256 (or 64k) Colors RGB 8Bit Bus
• SSD1332 96x64 OLED 256 (or 64k) Colors BGR 8Bit Bus.
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the
SSD1332 datasheet.
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 SSD1332 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:
• Bits 0..1 - Blue color bits 0..1
• Bits 2..4 - Green color bits 0..2
• Bits 5..7 - Red color bits 0..2.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ssd1332.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1332.h.
• The ..\EXAMPLES\Graphic Displays\SSD1332 directory contains a fully functional code example
that may be used as references for SSD1332 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_ssd1351.h
header file:
A detailed description of the above mentioned commands can be found in the SSD1351 datasheet.
Parameter:
Parameter:
contrast sets the contrast value, the allowed range being 0..15.
The glcd_ssd1351.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD1351 controller, used as parameter for the glcd_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 divset:4; /* Front clock divider */
unsigned char osc_freq:4; /* Oscillator frequency */
unsigned char phase1:4; /* Phase 1 period */
unsigned char phase2:4; /* Phase 2 period */
unsigned char precharge_v:5; /* Pre-charge voltage=
Vcc*(0.2+precharge_v*0.01275) */
unsigned char vcomh:3; /* VCOMH voltage= Vcc*(0.72+vcomh*0.02) */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the
SSD1351 datasheet.
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 SSD1351 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:
• Bits 0..1 - Blue color bits 0..1
• Bits 2..4 - Green color bits 0..2
• Bits 5..7 - Red color bits 0..2.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ssd1351.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1351.h.
• The ..\EXAMPLES\Graphic Displays\SSD1351 directory contains a fully functional code example
that may be used as references for SSD1351 initialization and usage.
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:
Parameter:
This command may take one of the values defined in the following macros from the glcd_ssd1963.h
header file:
Writes data byte(s) to the SSD1963 controller after a command was issued using the
ssd1963_wrcmd function.
Parameter:
Reads result data byte(s) from the SSD1963 controller after a command was issued using
the ssd1963_wrcmd function.
Writes color data for 1 pixel to the SSD1963 controller's display RAM.
Parameter:
GLCDCOL_t ssd1963_rddram(void)
Reads color data for 1 pixel from the SSD1963 controller's display RAM.
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:
• The function automatically inserts a 5ms delay after entering or exiting the sleep mode.
• 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 glcd_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 front 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] */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
#define SSD1963_DEFAULT_TFT_HOR_PULSE_WIDTH 20
#define SSD1963_DEFAULT_TFT_HOR_FRONT_PORCH 20
#define SSD1963_DEFAULT_TFT_HOR_BACK_PORCH 48
#define SSD1963_DEFAULT_TFT_VER_PULSE_WIDTH 2
#define SSD1963_DEFAULT_TFT_VER_FRONT_PORCH 4
#define SSD1963_DEFAULT_TFT_VER_BACK_PORCH 16
#define SSD1963_DEFAULT_TFT_HOR_PULSE_WIDTH 41
#define SSD1963_DEFAULT_TFT_HOR_FRONT_PORCH 2
#define SSD1963_DEFAULT_TFT_HOR_BACK_PORCH 2
#define SSD1963_DEFAULT_TFT_VER_PULSE_WIDTH 10
#define SSD1963_DEFAULT_TFT_VER_FRONT_PORCH 2
#define SSD1963_DEFAULT_TFT_VER_BACK_PORCH 2
#define SSD1963_DEFAULT_TFT_HOR_PULSE_WIDTH 40
#define SSD1963_DEFAULT_TFT_HOR_FRONT_PORCH 82
#define SSD1963_DEFAULT_TFT_HOR_BACK_PORCH 7
#define SSD1963_DEFAULT_TFT_VER_PULSE_WIDTH 17
#define SSD1963_DEFAULT_TFT_VER_FRONT_PORCH 29
#define SSD1963_DEFAULT_TFT_VER_BACK_PORCH 22
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 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_ssd1963.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_ssd1963.h.
• The ..\EXAMPLES\Graphic Displays\SSD1963 directory contains fully functional code samples
that may be used as references for SSD1963 initialization and usage.
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:
Writes a command to the SSD2119 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_ssd2119.h
header file:
A detailed description of the above mentioned command registers can be found in the SSD2119
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_ssd2119.h header file also contains the definition of the GLCDINIT_t type specific for the
SSD2119 controller, used as parameter for the glcd_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 -> RGB, =1 ->BGR */
/* power control registers bits */
unsigned char stepup_factor:3; /* step-up factor of the step-up
circuit, see BT0..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 (AP0..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; /* PKP00..PKP02 positive gamma micro adj. */
unsigned char pkp10: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; /* PRP00..PRP02 positive gamma gradient
adj. */
unsigned char prp10:3; /* PRP10..PRP12 positive gamma gradient
adj. */
unsigned char vrp00:4; /* VRP00..VRP03 positive gamma amplification
adj. */
unsigned char vrp10:5; /* VRP10..VRP14 positive gamma amplification
adj. */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_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.
• The ..\EXAMPLES\Graphic Displays\SSD2119 directory contains fully functional code samples
that may be used as references for SSD2119 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_st7565.h
header file:
A detailed description of the above mentioned commands can be found in the ST7565 datasheet.
Parameter:
contrast sets the value of the V5 LCD drive voltage, allowed range is 0..63.
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 glcd_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);
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the ST7565
datasheet.
Notes:
• 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 glcd_st7565.h.
• The ..\EXAMPLES\Graphic Displays\ST7565 directory contains fully functional code samples
that may be used as references for ST7565 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_st7567.h
header file:
A detailed description of the above mentioned commands can be found in the ST7567 datasheet.
Parameter:
contrast sets the value of the V0 LCD drive voltage, allowed range is 0..63.
The glcd_st7567.h header file also contains the definition of the GLCDINIT_t type specific for the
ST7567 controller, used as parameter for the glcd_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);
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the ST7567
datasheet.
Notes:
• The glcd_st7567.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_st7567.h.
• The ..\EXAMPLES\Graphic Displays\ST7567 directory contains fully functional code samples
that may be used as references for ST7567 initialization and usage.
In order to take full advantage of the ST7781 controller's features, the following specific functions,
declared in the glcd_st7781.h header file, were implemented:
Writes a command to the ST7781 controller, used to access a specific command register.
Parameter:
This index may take one of the values defined in the following macros from the glcd_st7781.h header
file:
A detailed description of the above mentioned command registers can be found in the ST7781
datasheet.
Parameters:
Parameters:
Parameters:
data to be written.
The glcd_st7781.h header file also contains the definition of the GLCDINIT_t type specific for the
ST7781 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
/* power control registers bits */
unsigned char stepup_factor:3; /* step-up factor of the step-up
circuit, see BT0..BT2 bits in
the datasheet */
unsigned char stepup_freq1:3; /* controls the frequency for the
step-up circuit 1 */
unsigned char stepup_freq2:3; /* controls the frequency for the
step-up circuit 2 */
unsigned char crt_source:3; /* adjusts the amount of current
from the constant current source
in the internal op. amplififier
circuit (AP0..AP2 bits) */
unsigned char vreg1out:4; /* adjusts the VREG1OUT voltage */
unsigned char vcom:5; /* adjusts the amplitude of the Vcom
alternating drive voltage based on
VREG1OUT voltage */
unsigned char vcomh:6; /* adjusts the amplitude of the VcomH
voltage based on VREG1OUT voltage
VcomH=VREG1OUT*(vcomh*0.005+0.685) [V] */
unsigned char frame_freq:4; /* LCD frame frequency */
/* positive gamma control registers bits */
unsigned char kp00:3; /* KP00..KP02 positive gamma micro adj. */
unsigned char kp10:3; /* KP10..KP12 positive gamma micro adj. */
unsigned char kp20:3; /* KP20..KP22 positive gamma micro adj. */
unsigned char kp30:3; /* KP30..KP32 positive gamma micro adj. */
unsigned char kp40:3; /* KP40..KP42 positive gamma micro adj. */
unsigned char kp50:3; /* KP50..KP52 positive gamma micro adj. */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 ST7781 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_st7781.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_st7781.h.
• The ..\EXAMPLES\Graphic Displays\ST7781 directory contains fully functional code samples
that may be used as references for ST7781 initialization and usage.
In order to take full advantage of the ST7789 controller's features, the following specific functions,
declared in the glcd_st7789.h header file, were implemented:
Parameter:
This command may take one of the values defined in the following macros from the glcd_st7789.h
header file:
Writes data byte(s) to the ST7789 controller after a command was issued using the
st7789_wrcmd function.
Parameter:
Reads result data byte(s) from the ST7789 controller after a command was issued using the
st7789_wrcmd function.
Note: When used immediately after st7789_wrcmd, this function must be called twice.
The result of the first call is a dummy read and it is not valid.
Writes color data for 1 pixel to the ST7789 controller's display RAM.
Parameter:
GLCDCOL_t st7789_rddram(void)
Reads color data for 1 pixel from the ST7789 controller's display RAM.
Puts the ST7789 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:
• A delay of minimum 120ms must be present after exiting the sleep mode and entering sleep mode
again.
The glcd_st7789.h header file also contains the definition of the GLCDINIT_t type specific for the
ST7789 controller, used as parameter for the glcd_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 cl_bits_order:1; /* selects the color bits writing
order to the display RAM
=0 -> RGB, =1 ->BGR */
unsigned char vgl:3; /* set VGL (see the datasheet) */
unsigned char vgh:3; /* set VGH (see the datasheet) */
unsigned char vrh:6; /* set VRH (see the datasheet) */
unsigned char vdv:6; /* set VDV (see the datasheet) */
unsigned char vcom:6; /* set VCOM (see the datasheet) */
unsigned char frame_rate:5; /* set vertical frame rate
39..119Hz */
} GLCDINIT_t;
The following macros are defined for initializing the members of the GLCDINIT_t structure:
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 ST7789 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:
• Bits 0..2 - Blue color bits 0..2
• Bits 3..5 - Green color bits 0..2
• Bits 6..7 - Red color bits 0..1.
For 64k color mode the following color bit allocation in a 16bit data word is used:
• Bits 0..4 - Blue color bits 0..4
• Bits 5..10 - Green color bits 0..5
• Bits 11..15 - Red color bits 0..4.
Notes:
• In order to reduce image storage size and improve speed, it is recommended to use the 256 color
mode, if possible.
• The glcd_st7789.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_st7789.h.
• The ..\EXAMPLES\Graphic Displays\ST7789 directory contains fully functional code samples
that may be used as references for ST7789 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_st7920.h
header file:
/* set cursor position & display shift when doing write or read */
#define ST7920_ENTRY_MODE_SET 0x04
/* entry mode bits: */
/* 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
/* function set */
#define ST7920_FUNC_SET 0x20
/* function set control bits:
must not be applied at the same time!
change ST7920_8BIT or ST7920_GRAPHICS_ON first, then ST7920_EXTENDED */
/* 8 bit interface */
#define ST7920_8BIT 0x10
/* select the extended command set */
#define ST7920_EXTENDED 0x04
/* turn graphics display on */
#define ST7920_GRAPHICS_ON 0x02
A detailed description of the above mentioned commands can be found in the ST7920 datasheet.
Parameter:
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.
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 lcd_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.
Sets the current text display position at column x and row y. The row and column numbering
starts from 0.
void lcd_putchar(char c)
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:
For displaying an user defined character the lcd_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: Chinese BIG 5 and user defined characters use a 16x16 pixel matrix, therefore may be
displayed only on even horizontal text x coordinates.
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 -> pixel 7, on row 0
byte 0, bit 1 -> pixel 6, on row 0
..
byte 0, bit 7 -> pixel 0, on row 0
byte 1, bit 0 -> pixel 15, on row 0
byte 1, bit 1 -> pixel 14, on row 0
..
byte 1, bit 7 -> pixel 8, on row 0
Example:
#include <glcd.h>
#include <delay.h>
void main()
{
unsigned char c;
GLCDINIT_t init;
/* No font is used */
init.font=NULL;
/* 2 seconds delay */
delay_ms(2000);
lcd_clear();
lcd_putsf("User defined\n"
"characters:\n");
Displays at the current display position the string str, located in RAM.
Displays at the current display position the string str, located in FLASH.
Displays at the current display position the string str, located in EEPROM.
Notes:
• The glcd_st7920.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_st7920.h.
• The ..\EXAMPLES\Graphic Displays\ST7920 directory contains fully functional code samples
that may be used as references for ST7920 initialization and usage.
void t6963_busy(void)
Waits for the T6963 controller to become ready for reading or writing data by polling the
STA0 and STA1 flags. Also sets C /D=1.
Parameter:
This command may take one of the values defined in the following macros from the glcd_t6963.h
header file:
A detailed description of the above mentioned commands can be found in the T6963C datasheet.
Parameter:
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.
Parameters:
Notes:
• The glcd_t6963.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_t6963.h.
• The ..\EXAMPLES\Graphic Displays\T6963C directory contains fully functional code samples
that may be used as references for T6963C initialization and usage.
In order to take full advantage of the UC1608 controller's features, the following specific functions,
declared in the glcd_uc1608.h header file, were implemented:
Parameter:
This command may take one of the values defined in the following macros from the glcd_uc1608.h
header file:
A detailed description of the above mentioned commands can be found in the UC1608 datasheet.
Parameter:
contrast sets the value of the LCD bias voltage, allowed range is 0..63.
The glcd_uc1608.h header file also contains the definition of the GLCDINIT_t type specific for the
UC1608 controller, used as parameter for the glcd_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);
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the UC1608
datasheet.
Notes:
• The glcd_uc1608.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_uc1608.h.
• The ..\EXAMPLES\Graphic Displays\UC1608 directory contains fully functional code samples
that may be used as references for UC1608 initialization and usage.
The UC1610 hardware configuration for the 4-wire serial mode is obtained by connecting the following
signals:
• BM0 - GND
• BM1 - GND
• WR0 - +3.3V
• WR1 - +3.3V
• D0 (SCK) - microcontroller I/O port, specified in the Project|Configure|C
Compiler|Libraries|Graphic Displays menu
• D3 (SDA) - microcontroller I/O port, specified in the Project|Configure|C
Compiler|Libraries|Graphic Displays menu
• D6 - GND
• D7 - +3.3V
• CD - microcontroller I/O port, specified in the Project|Configure|C Compiler|Libraries|Graphic
Displays menu
• /CS0 - microcontroller I/O port, specified in the Project|Configure|C Compiler|Libraries|Graphic
Displays menu
• CS1 - +3.3V
• /RST - microcontroller I/O port, specified in the Project|Configure|C Compiler|Libraries|Graphic
Displays menu.
In order to take full advantage of the UC1610 controller's features, the following specific functions,
declared in the glcd_uc1610.h header file, were implemented:
Parameter:
This command may take one of the values defined in the following macros from the glcd_uc1610.h
header file:
A detailed description of the above mentioned commands can be found in the UC1610 datasheet.
Parameter:
contrast sets the value of the LCD bias voltage, allowed range is 0..255.
The glcd_uc1610.h header file also contains the definition of the GLCDINIT_t type specific for the
UC1610 controller, used as parameter for the glcd_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);
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the UC1610
datasheet.
Notes:
• The glcd_uc1610.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_uc1610.h.
• The ..\EXAMPLES\Graphic Displays\UC1610 EA DOGXL160-7 directory contains fully functional
code samples that may be used as references for UC1610 initialization and usage.
Parameter:
This command may take one of the values defined in the following macros from the glcd_uc1701.h
header file:
A detailed description of the above mentioned commands can be found in the UC1701 datasheet.
Parameter:
contrast sets the value of the VLCD drive voltage, allowed range is 0..63.
The glcd_uc1701.h header file also contains the definition of the GLCDINIT_t type specific for the
UC1701 controller, used as parameter for the glcd_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 LCD bias voltage ratio low,
=1 LCD bias voltage ratio high */
unsigned char reverse_x:1; /* 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) */
The following macros are defined for initializing the members of the GLCDINIT_t structure:
The detailed description of the above mentioned initialization parameters can be found in the UC1701
datasheet.
Note:
• The glcd_uc1701.h header file is automatically #included when the main glcd.h header file is
#included. Therefore there is no need to explicitly #include glcd_uc1701.h.
Before using these functions, the I/O port signals employed for communication with the touchscreen
controller must be specified in the Project|Configure|C Compiler|Libraries|Resistive Touchscreen
menu.
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.
The following helper data types and variables are defined in the header file rtouch.h:
/* Signal that the screen was touched and the point's coordinates
can be read using the rt_getxy function */
extern bit rt_touched;
void rt_timerproc(void)
This function needs to be called every 10ms by a timer interrupt service routine in order to
sense the state of the /PENIRQ output of the touch screen controller.
Example:
Note:
• If the screen was touched, rt_timerproc will set the global variable rt_touched to 1.
The variable will be reset to 0 when reading the point's coordinates using the rt_readctrl and rt_getxy
functions.
Waits for the screen to be touched and returns the xt, yt touchscreen coordinate values read
from the controller.
Parameters:
xt - pointer to the variable that will hold the 12-bit noise filtered value read from the
controller's ADC for the horizontal coordinate
yt - pointer to the variable that will hold the 12-bit noise filtered value read from the
controller's ADC for the vertical coordinate.
Note:
• xt and yt don't represent graphic display coordinates.
Parameter:
Return values:
true if the touchscreen calibration data, stored in the chip's EEPROM is valid;
false if not.
Notes:
• After calling rt_init, please make sure that the timer that is used for generating the 10ms interrupt
which calls rt_timerproc, is also initialized and that global interrupts are enabled using #asm("sei").
• In order to simplify the usage of the rt_init function, the following macros are defined in the
rtouch.h header file:
Calibrates the resistive touchscreen controller and stores the calibration data in the chip's
EEPROM.
Parameters:
touchscreen - points to the RTCALP_t structure that holds the ADC values read by the
touchscreen controller, corresponding to the display coordinates of the calibration points
display - points to the RTCALP_t structure, stored in FLASH memory, that holds the
coordinates of the calibration points to be displayed.
Return values:
Note:
• rt_calibrate stores the calibration data redundantly in the chip's EEPROM, special routines are
also used in rt_init in order to prevent this data to be corrupted and eventually correct it in such cases.
Example:
#include <io.h>
#include <glcd.h>
#include <font5x7.h>
#include <stdio.h>
#include <delay.h>
#include <rtouch.h>
/* Display buffer */
char display_buf[];
/* Display calibration points and read the touchscreen result for each of
them */
delay_ms(1000);
delay_ms(1000);
void main()
{
GLCDINIT_t glcd_init_data;
unsigned char n;
glcd_init(&glcd_init_data);
if (calibrate_touchscreen())
glcd_outtextxyf(0,20,"Touchscreen controller calibrated OK");
else
glcd_outtextxyf(0,20,"Touchscreen controller calibration\n"
"failed");
}
/* Stop here */
while (1);
}
Waits for the screen to be touched and returns the xd, yd display coordinates calculated
using the calibration data stored in the chip's EEPROM.
Parameters:
xd - pointer to the variable that will hold the read horizontal X display coordinate
yd - pointer to the variable that will hold the read vertical Y display coordinate.
Return values:
Example:
#include <io.h>
#include <glcd.h>
#include <font5x7.h>
#include <stdio.h>
#include <delay.h>
#include <rtouch.h>
/* Display buffer */
char display_buf[];
/* Display calibration points and read the touchscreen result for each of
them */
delay_ms(1000);
delay_ms(1000);
void main()
{
GLCDINIT_t glcd_init_data;
unsigned char n;
short x,y;
glcd_init(&glcd_init_data);
if (calibrate_touchscreen())
glcd_outtextxyf(0,20,"Touchscreen controller calibrated OK");
else
{
glcd_outtextxyf(0,20,"Touchscreen controller calibration\n"
"failed");
/* Stop here */
while (1);
}
}
delay_ms(2000);
glcd_clear();
glcd_outtextf("Touch the screen to draw...");
while (1)
{
if (rt_getxy(&x,&y))
{
glcd_setpixel(x,y);
delay_ms(10);
}
}
}
short rt_readtemp(void)
Note:
• Due to the ADS7846 operating mode, the temperature measurement accuracy is only 2 °C.
Reads the battery voltage in mV on the Vbat input of the ADS7846 controller.
The communication between the touchscreen controller and the AVR chip is performed using the
hardware TWI, so before using these functions, this interface must be properly configured for
operation in Master Mode, as described in the 5.15 Two Wire Interface Functions for non-XMEGA
Devices and 5.16 Two Wire Interface Functions for XMEGA Devices chapters.
The following connections must be performed for the touchscreen controller's signals:
• SDA signal must be connected to the AVR's TWI SDA signal. A 3.3k..10k pull-up resistor to +3.3V
must be present on the SDA line.
• SCL signal must be connected to the AVR's TWI SCL signal. A 3.3k..10k pull-up resistor to +3.3V
must be present on the SCL line.
• /RES signal must be connected to the corresponding /RES (/RESET) reset signal of the graphic
display controller
• /INT signal must be connected to an I/O port input pin of the AVR chip that can sense a high to
low transition and generate the corresponding External Interrupt
• WAKE signal must be connected to a logic high level. Alternatively, it can be connected to an I/O
port output pin and set to low level by the user's program, forcing the controller to enter low power
consumption mode.
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.
The following helper data types and variables are defined in the header file ft5x06.h:
/* Structure that holds the touched point data read from the controller */
typedef struct
{
unsigned char touched_points:3; /* number of simultaneously touched points
stored in the point buffer */
unsigned char new_touch:1; /* signal that a new touch occured
since the last read from the point buffer */
CTPOINT_t point[5]; /* buffer with touched point display coordinates */
} CTSTATUS_t;
Note: The FT5206, FT5306 and FT5406 controllers can detect up to 5 simultaneous touch points, the
coordinates of which are stored in the point member of the CTSTATUS_t structure.
The number of detected points is stored in the touched_points member.
The following low level functions are available for interfacing with the capacitive touchscreen
controller:
Parameters:
reg – controller's register where the data must be written
data – byte to be written.
The registers available for the FT5206, FT5306 and FT5406 controllers are defined in the ft5x06.h
header file:
Parameter:
reg – controller's register from which the data must be read.
Returns:
data byte read from reg.
void ct_inthandler(void)
Function to be called in the I/O port External Interrupt Service Routine when the capacitive
touchscreen controller's /INT signal becomes active (high to low transition).
Example:
#include <io.h>
#include <glcd.h>
#include <ft5x06.h>
bool ct_init(void)
Parameter:
twi_master - pointer to a structure that holds the information required by the TWI module
used for communication with the touchscreen controller in master mode.
Notes:
• The ct_init function must be called after the interrupt system, TWI and graphic display controllers
were properly initialized.
• Interrupts must be globally enabled before calling the ct_init function.
• The FT5206, FT5306 and FT5406 touchscreen controllers come precalibrated along with the
display, so further calibration by the user is not necessary.
#include <io.h>
#include <iobits.h>
#include <glcd.h>
#include <ft5x06.h>
void main(void)
{
/* Initialization code for the graphic display controller */
/* … */
#include <io.h>
#include <iobits.h>
#include <glcd.h>
#include <ft5x06.h>
void main(void)
{
unsigned char n;
Waits for the display screen to be touched and returns the coordinates of the first point.
Parameters:
xd – pointer to an unsigned short variable that will hold the horizontal display coordinate of
the first touched point
yd – pointer to an unsigned short variable that will hold the vertical display coordinate of the
first touched point.
Returns:
#include <io.h>
#include <iobits.h>
#include <stdio.h>
#include <glcd.h>
#include <ft5x06.h>
void main(void)
{
signed char n;
/* Display buffer */
char display_buf[32];
while (1)
{
/* Wait for the display screen to be touched */
n=ct_getxy(&x,&y);
if (n>0)
{
/* Touched point(s) detected,
clear the screen */
glcd_clear();
Checks, without waiting, if the display screen is touched and returns the coordinates of the
first point.
Parameters:
xd – pointer to an unsigned short variable that will hold the horizontal display coordinate of
the first touched point
yd – pointer to an unsigned short variable that will hold the vertical display coordinate of the
first touched point.
Returns:
Waits for the display screen to be touched and returns the coordinates of all the touched
points.
Parameters:
points – pointer to an array of CTPOINT_t types that will hold the horizontal display
coordinate of the 5 touched points.
Returns:
#include <io.h>
#include <iobits.h>
#include <stdio.h>
#include <glcd.h>
#include <ft5x06.h>
void main(void)
{
signed char i,n;
/* Display buffer */
char display_buf[32];
while (1)
{
/* Wait for the display screen to be touched */
n=ct_getpoints(points);
if (n>0)
{
/* Touched point(s) detected,
clear the screen */
glcd_clear();
Checks, without waiting, if the display screen is touched and returns the coordinates of all
the touched points.
Parameters:
points – pointer to an array of CTPOINT_t types that will hold the horizontal display
coordinate of the 5 touched points.
Returns:
A fully functional code example for the FT5206 chip is provided in the \Examples\Graphic
Displays\Capacitive Touchscreen\FT5206 directory of the CodeVisionAVR installation.
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:
Note: For compatibility with projects 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:
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.
this function returns the number of devices connected to the 1 Wire bus.
If no devices were detected then it returns 0.
The byte cmd represents the Search ROM (F0h), 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 at a
later stage in the program.
Example:
#include <mega8515.h>
/* the ATmega8515 port and bit used for the 1 Wire bus must be specified in
the Project|Configure|C Compiler|Libraries 1 Wire menu */
/* allocate RAM space for the ROM codes & status bit */
unsigned char rom_codes[MAX_DEVICES][9];
/* Baud rate */
#define baud 9600
void main(void) {
unsigned char i,j,devices;
this function checks the 8 bit DOW CRC for a block of bytes with the length n, pointed by p.
It returns 0 if the DOW CRC of the first n-1 bytes from the block equals the value of the n-th byte, or 1
if it doesn't.
Notes:
• 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.
• 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 I2C bus.
• 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.
enables and initializes the TWI hardware for operating in master mode.
Parameters:
bool twi_master_trans(
unsigned char slave_addr,
unsigned char *tx_data,
unsigned char tx_count,
unsigned char *rx_data,
unsigned char rx_count)
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 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 twi_result global variable,
which can take the values defined in the following macros:
#define TWI_RES_OK 0
#define TWI_RES_BUFFER_OVERFLOW 1
#define TWI_RES_ARBITRATION_LOST 2
#define TWI_RES_BUS_ERROR 3
#define TWI_RES_NACK_RECEIVED 4
#define TWI_RES_BUS_TIMEOUT 5
#define TWI_RES_FAIL 6
#define TWI_RES_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 I2C bus.
/* TWI functions */
#include <twi.h>
/* delay functions */
#include <delay.h>
void main(void)
{
struct
{
struct
{
unsigned char msb;
unsigned char lsb;
} addr;
unsigned char data;
} twi_eeprom;
/* stop here */
while (1);
}
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 slave 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 the 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.
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_RES_OK 0
#define TWI_RES_BUFFER_OVERFLOW 1
#define TWI_RES_BUS_ERROR 3
#define TWI_RES_NACK_RECEIVED 4
#define TWI_RES_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 I2C bus.
/* The slave will 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 slave
will transmit the char string "Data packet received OK\n\r"
back to the master.
#include <io.h>
#include <stdio.h>
#include <twi.h>
#include <delay.h>
#include <alcd.h>
#include <string.h>
/* status messages */
flash char * flash status_msg[8]=
{
"OK",
"Buffer overflow",
"Arbitration lost",
"Bus error",
"NACK received",
"Bus timeout",
"Fail",
"Unknown error"
};
if (rx_complete)
/* the TWI master has finished transmitting data */
return false; /* no more bytes to receive */
void main(void)
{
/* initialize the LCD */
lcd_init(16);
lcd_clear();
The TWI Functions for XMEGA Devices are intended for easy interfacing between C programs and
various external peripherals using the I2C 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:
• 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.
• 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.
• 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
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 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:
For the rest of XMEGA chips sda_hold can take one of the following values:
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
*/
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 declaring 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_MASTER_INFO_t
structure data type, which may take the values defined by the following macros from twix.h:
#define TWIM_RES_UNKNOWN 0
#define TWIM_RES_OK 1
#define TWIM_RES_BUFFER_OVERFLOW 2
#define TWIM_RES_ARBITRATION_LOST 3
#define TWIM_RES_BUS_ERROR 4
#define TWIM_RES_NACK_RECEIVED 5
#define TWIM_RES_FAIL 6
The macro:
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)
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
be 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.
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.
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)
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.
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.
/* delay functions */
#include <delay.h>
void main(void)
{
struct
{
struct
{
unsigned char msb;
unsigned char lsb;
} addr;
unsigned char data;
} twi_eeprom;
/* stop here */
while (1);
}
typedef struct
{
TWI_t *module; /* pointer to the used TWI interface module
*/
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
*/
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 returned 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_RES_UNKNOWN 0
#define TWIS_RES_OK 1
#define TWIS_RES_ADDR_MATCH 2
#define TWIS_RES_BUFFER_OVERFLOW 3
#define TWIS_RES_TRANSMIT_COLLISION 4
#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.
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 starting 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 current 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.
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.
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.
/*
Sample program to test the XMEGA TWIC master and
TWID slave operation.
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.
/* string functions */
#include <string.h>
/* delay functions */
#include <delay.h>
twi_slave_halt(&twi_slave);
void main(void)
{
unsigned char switches;
/* received data from the slave */
unsigned char rx_data[sizeof(test_data)];
PORTA.PIN0CTRL=PORT_INVEN_bm | PORT_OPC_TOTEM_gc;
PORTA.PIN1CTRL=PORT_INVEN_bm | PORT_OPC_TOTEM_gc;
PORTA.PIN2CTRL=PORT_INVEN_bm | PORT_OPC_TOTEM_gc;
PORTA.PIN3CTRL=PORT_INVEN_bm | PORT_OPC_TOTEM_gc;
PORTA.PIN4CTRL=PORT_INVEN_bm | PORT_OPC_TOTEM_gc;
PORTA.PIN5CTRL=PORT_INVEN_bm | PORT_OPC_TOTEM_gc;
PORTA.PIN6CTRL=PORT_INVEN_bm | PORT_OPC_TOTEM_gc;
PORTA.PIN7CTRL=PORT_INVEN_bm | PORT_OPC_TOTEM_gc;
while (1)
{
/* read the SW0..7 switches
the switches value is inverted because
the connection is established to GND
when a switch is pressed */
switches= ~PORTE.IN;
Notes:
• The twi.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.
• The TWI Functions for AVR8X Devices operate using interrupts, so the interrupts must be also
globally enabled using the #asm("sei") inline assembly code
• For proper operation, the TWI Functions require the presence of 3.3k - 4.7k pull-up
resistors to Vcc on the SCL and SDA signals.
General initialization of the TWI module associated with an AVR8X I/O port is performed by the
function.
Parameters:
module represents a pointer to the TWI module associated with the I/O port.
sda_setup specifies the SDA setup time:
TWI_SDASETUP_4CYC_gc - 4 cycles
TWI_SDASETUP_8CYC_gc - 8 cycles.
sda_hold specifies the internal hold time on SDA with respect to the SCL negative edge:
fast_mode - enables using the Fast Mode Plus 1MHz bus speed.
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
*/
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 declaring 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_MASTER_INFO_t
structure data type, which may take the values defined by the following macros from twi.h:
#define TWIM_RES_UNKNOWN 0
#define TWIM_RES_OK 1
#define TWIM_RES_BUFFER_OVERFLOW 2
#define TWIM_RES_ARBITRATION_LOST 3
#define TWIM_RES_BUS_ERROR 4
#define TWIM_RES_NACK_RECEIVED 5
#define TWIM_RES_FAIL 6
The macro:
is used for calculating the value of the TWI MBAUD register for the desired TWI clock rate
TWI_CLK_RATE, expressed in bps, 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,
unsigned char baud_reg)
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 AVR8X I/O port, that will
be enabled and initialized for operation in master mode.
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.
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)
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.
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.
/* delay functions */
#include <delay.h>
void main(void)
{
struct
{
struct
{
unsigned char msb;
unsigned char lsb;
} addr;
unsigned char data;
} twi_eeprom;
/* stop here */
while (1);
}
typedef struct
{
TWI_t *module; /* pointer to the used TWI interface module
*/
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
*/
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 returned 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_RES_UNKNOWN 0
#define TWIS_RES_OK 1
#define TWIS_RES_ADDR_MATCH 2
#define TWIS_RES_BUFFER_OVERFLOW 3
#define TWIS_RES_TRANSMIT_COLLISION 4
#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,
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.
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 AVR8X I/O port, that will
be enabled and initialized for operation in slave mode.
match_any_addr enables the TWI slave 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.
addr_mask_reg specfies the value used to initialize the TWI module's SADDRMASK
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 current 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.
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.
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.
/*
Sample program to test the AVR8X TWI0 slave operation.
twi_slave_halt(&twi_slave);
void main(void)
{
/* received data from the slave */
unsigned char rx_data[sizeof(test_data)];
while (1)
{
/* all is handled by the twi_slave_trans function
called by the TWI0 interrupt handler */
}
}
Notes:
• For proper operation, the I2C Functions require the presence of 3.3k - 4.7k pull-up resistors
to +5V on the SCL and SDA signals.
• The bit-banged I2C Functions functions do not support the AVR8X and 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 I2C bus and the bit rate of the SCL clock.
This is accomplished in the Project|Configure|C Compiler|Libraries|I2C menu:
Note: For compatibility with projects developed with CodeVisionAVR prior to V2.05.1, the I2C
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
void i2c_init(void)
void i2c_stop(void)
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.
void main(void)
{
unsigned char i;
/* initialize the I2C bus */
i2c_init();
/* write the byte 55h at address AAh */
eeprom_write(0xaa,0x55);
/* read the byte from address AAh */
i=eeprom_read(0xaa);
while (1); /* loop forever */
}
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:
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:
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 lsb_first parameter is true, the data byte sent/received on the bus will start with bit 0,
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:
If the clk2x parameter is true, the SPI master will function in double speed mode.
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:
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.
/*
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
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)<<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.0 input from AD7896 BUSY
PB.1 output to AD7896 /CONVST
PB.2 & 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;
The prototypes for these functions are placed in the file usb_device.h, located in the .\INC
subdirectory. This file must be #include -d before using the functions.
For non-Xmega chips the USB Device Functions can implement up to two interfaces: 0 and 1, thus
allowing the creation of composite USB devices using the same controller, for example: mouse and
keyboard.
For Xmega chips up to four interfaces: 0 to 3 are supported.
Five endpoints are supported. Endpoint 0 is always used for control and endpoints 1 to 4 are used for
data transfer. The maximum size of an endpoint is 64 bytes.
The following data types are defined in usb_device.h and are used by the USB Device Functions:
/* Endpoint configuration */
typedef struct
{
unsigned char ep:4; /* Endpoint number */
unsigned char type:2; /* Endpoint type:
0 - Control, 1 - Isochronous,
2 - Bulk, 3 – Interrupt */
unsigned char size; /* Endpoint size: 8..64 [bytes],
set 0 if endpoint is not used */
} USB_ENDPOINT_t;
The following global variables are defined by the USB Device Functions library:
Stores the number of the USB configuration used by the USB device.
It takes the value 0 if the device was not enumerated by the host.
bit usb_current_interface
Stores the number of the currently active Interface which is used by the USB Device
Functions.
After device initialization the current interface is 0.
USB_TIMEOUT_t usb_timeout
The USB Device Functions may return one of the following result codes, defined in usb_device.h:
The following functions are implemented by the USB device mode library:
Notes:
• The usb_current_interface variable is initialized with the value 0.
• The usb_timeout structure is initialized with the transmission and reception timeout values,
specified in the USB_CONFIG_t structure. Later these values can be modified as needed during
program execution.
• For Xmega devices, the system clock must be properly initialized before the usb_init_device
function is called. The function will read the USB PAD calibration values from the signature row,
perform the appropriate calibration and configure the USB registers.
• The USB Device Functions require interrupts to be globally enabled, after the usb_init_device
function is called.
For non-Xmega devices, the USB Device Configuration used by the usb_init_device function is
defined as:
typedef struct
{
USB_INTERFACE_t interface[MAX_INTERFACES]; /* Interfaces configuration */
flash USB_DESCRIPTOR_LIST_t *pdescriptor_list; /* Pointer to the
USB_DESCRIPTOR_LIST_t
array */
unsigned char descriptor_list_items; /* # of elements in the
USB_DESCRIPTOR_LIST_t array */
USB_TIMEOUT_t timeout; /* Timeout periods */
} USB_CONFIG_t;
For Xmega devices, the USB Device Configuration used by the usb_init_device function is defined
as:
typedef struct
{
USB_INTERFACE_t interface[MAX_INTERFACES]; /* Interfaces configuration */
flash USB_DESCRIPTOR_LIST_t *pdescriptor_list; /* Pointer to the
USB_DESCRIPTOR_LIST_t
array */
unsigned char descriptor_list_items; /* # of elements in the
USB_DESCRIPTOR_LIST_t array */
USB_TIMEOUT_t timeout; /* Timeout periods */
USB_CLOCK_SOURCE_t usb_clock; /* USB controller's clock source:
USB_CLOCK_RC32M_SOF - 32 MHz RC
oscillator adjusted
and calibrated to 48 MHz using
the DFLL and USB Start Of Frame
USB_CLOCK_PLL_48M - PLL running
at 48 MHz
USB_CLOCK_PLL_96M - PLL running
at 96 MHz */
USB_INTLVL_t int_level; /* Interrupt priority for the USB
controller:
USB_INTLVL_LO_gc - Low level
USB_INTLVL_MED_gc - Medium level
USB_INTLVL_HI_gc - High level */
void (*usb_suspend_handler) (void); /* Pointer to the power management
function to be called when the
device on the USB bus is
suspended */
void (*usb_resume_handler) (void); /* Pointer to the power management
function to be called when the
device on the USB bus exits the
suspended state */
} USB_CONFIG_t;
Example:
/* Delay functions */
#include <delay.h>
};
void main(void)
{
/* Initialization code for other chip peripherals */
/* … */
Transmits a byte c to the host, using the currently active USB interface.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a buffer, located in RAM, using the currently active USB
interface. The length parameter specifies the number of bytes to transmit.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a buffer, located in FLASH memory, using the currently
active USB interface. The length parameter specifies the number of bytes to transmit.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a buffer, located in EEPROM, using the currently active
USB interface. The length parameter specifies the number of bytes to transmit.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a NULL terminated literal char string, located in RAM,
using the currently active USB interface.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a NULL terminated literal char string, located in FLASH
memory, using the currently active USB interface.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Immediately transmit to the host any buffered output for the currently active USB interface.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Clears the receive buffer for the currently active USB interface.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Receives a byte from the OUT endpoint of the currently active USB interface.
If the wait parameter is true, then the function will wait until data will be available in the OUT endpoint
buffer.
If the wait parameter is false, then the function will not wait for data to be available in the buffer.
Returns:
• in MSB: USB_RES_OK (=0) – no error.
The LSB contains the received byte.
• in MSB: USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured.
The LSB value is not defined.
• in MSB: USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host.
The LSB value is not defined.
• in MSB: USB_RES_NO_DATA – wait was set to false and there was no data available in the
buffer. The LSB value is not defined.
• in MSB: USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
The LSB value is not defined.
short usb_getchar(void)
Waits to receive a byte from the OUT endpoint of the currently active USB interface.
Returns:
• in MSB: USB_RES_OK (=0) – no error.
The LSB contains the received byte.
• in MSB: USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured.
The LSB value is not defined.
• in MSB: USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host.
The LSB value is not defined.
• in MSB: USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
The LSB value is not defined.
short usb_getcharnw(void)
Receives, without waiting, a byte from the OUT endpoint of the currently active USB interface.
Returns:
• in MSB: USB_RES_OK (=0) – no error.
The LSB contains the received byte.
• in MSB: USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured.
The LSB value is not defined.
• in MSB: USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host.
The LSB value is not defined.
• in MSB: USB_RES_NO_DATA – there was no data available in the buffer.
The LSB value is not defined.
• in MSB: USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
The LSB value is not defined.
Returns the number of bytes available in the receive buffer of the OUT endpoint for the
currently active USB interface.
Returns:
• USB_RES_OK – no error.
The variable pointed by length will hold the number of bytes that were effectively received from the
host.
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured.
The value of the variable pointed by length will remain unchanged.
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host.
The value of the variable pointed by length will remain unchanged.
• USB_RES_TIMEOUT – the device didn't receive the required number of bytes, in the time interval
specified in usb_timeout.rx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
The variable pointed by length will hold the number of bytes that were effectively received from the
host, before the receive timeout occurred.
Example:
/* Delay functions */
#include <delay.h>
};
/* Receive buffer */
unsigned char rx_buffer[32];
void main(void)
{
/* Variable that holds the number of bytes to receive */
unsigned short nbytes;
case USB_RES_CONFIG_ERROR:
printf("Error: Device not configured.\r\n");
break;
case USB_RES_DEVICE_NOT_ENUM:
printf("Error: Device not enumerated by the host.\r\n");
break;
case USB_RES_TIMEOUT:
printf("Error: Receive timeout occurred,"
" only %u bytes received.\r\n",nbytes);
break;
}
/* Stop here */
while (1);
}
The prototypes for these functions are placed in the file usb_cdc.h, located in the .\INC subdirectory.
This file must be #include -d before using the functions.
The file usb_cdc.h does automatically #include the usb_device.h header.
For the non-Xmega AVR devices, one CDC Virtual Serial Port is implemented, using the following
interfaces:
• Interface 0 implements the Communication Device Control class and uses the IN endpoint 1 for
RS-232 handshaking with the host, with Interrupt type transfers
• Interface 1 implements the Communication Device Data class and uses the IN endpoint 3 and
OUT endpoint 4 for data exchange with the host, with Bulk type transfers.
For the Xmega AVR devices, a maximal number of two CDC Virtual Serial Ports are implemented,
using the following interfaces:
• Interface 0 implements the Communication Device Control class for Port 0 and uses the IN
endpoint 1 for RS-232 handshaking with the host, with Interrupt type transfers
• Interface 1 implements the Communication Device Data class for Port 0 and uses the IN and OUT
endpoint 2 for data exchange with the host, with Bulk type transfers
• Interface 2 implements the Communication Device Control class for Port 1 and uses the IN
endpoint 3 for RS-232 handshaking with the host, with Interrupt type transfers
• Interface 3 implements the Communication Device Data class for Port 1 and uses the IN and OUT
endpoint 4 for data exchange with the host, with Bulk type transfers.
Before calling the CDC Virtual Serial Port functions, the USB controller must be properly initialized for
operation in device mode, using the usb_device_init function.
After this function is called, all input/output is directed by default to the Virtual Serial Port 0.
For the Xmega AVR devices this port can be changed during program execution, by calling the
usb_serial_select function.
All configuration structures required for these functions can be easily created using the
CodeWizardAVR.
Note: In order to use the CDC Virtual Serial Port functions, the corresponding option must be enabled
in the Project|Configure|C Compiler|Libraries|USB menu:
The following data types are defined in usb_cdc.h and are used by the CDC Virtual Serial Port
functions:
typedef union
{
struct
{
unsigned char dcd:1; /* DCD signal state */
unsigned char dsr:1; /* DSR signal state */
unsigned char break:1; /* Break detected */
unsigned char ri:1; /* RI signal state */
unsigned char frame_error:1; /* Frame error detected */
unsigned char parity_error:1; /* Parity error detected */
unsigned char overrun_error:1; /* Overrun error detected */
};
unsigned char signals;
} USB_CDC_SERIAL_STATUS_t; /* RS-232 signals and error status */
/* bcdCDC value */
#define USB_CDC_SPEC 0x0110 /* CDC 1.10 specification supported */
/* bDescriptorType values */
#define USB_DESCRIPTOR_TYPE_CS_INTERFACE 0x24 /* CS interface */
#define USB_DESCRIPTOR_TYPE_CS_ENDPOINT 0x25 /* CS endpoint */
/* bInterfaceProtocol */
#define USB_PROTOCOL_CDC_AT 0x01 /* AT command protocol */
/* bDescriptorSubType values */
#define CDC_DST_HEADER 0x00 /* Header functional descriptor */
#define CDC_DST_CALL_MANAGEMENT 0x01 /* Call Management functional
descriptor */
#define CDC_DST_ACM 0x02 /* Abstract Control Model
functional descriptor */
#define CDC_DST_DIRECT_LINE 0x03 /* Direct Line functional
descriptor */
#define CDC_DST_TEL_RINGER 0x04 /* Telephone Ringer functional
descriptor */
#define CDC_DST_TEL_CALL 0x05 /* Telephone Call functional
descriptor */
#define CDC_DST_UNION 0x06 /* Union functional descriptor */
#define CDC_DST_COUNTRY_SEL 0x07 /* Country Selection functional
descriptor */
#define CDC_DST_TEL_OP_MODES 0x08 /* Telephone Operation Modes
functional descriptor */
/* Stop_bits values */
#define CDC_SERIAL_STOP_BITS1 0 /* 1 stop bit */
#define CDC_SERIAL_STOP_BITS1_5 1 /* 1.5 stop bits */
#define CDC_SERIAL_STOP_BITS2 2 /* 2 stop bits */
/* Parity values */
#define CDC_SERIAL_PARITY_NONE 0 /* No parity bit */
#define CDC_SERIAL_PARITY_ODD 1 /* Odd parity bit */
#define CDC_SERIAL_PARITY_EVEN 2 /* Even parity bit */
#define CDC_SERIAL_PARITY_MARK 3 /* Mark parity bit */
#define CDC_SERIAL_PARITY_SPACE 4 /* Space parity bit */
The following global variable is defined by the CDC Virtual Serial Port library for non-Xmega AVR
devices:
USB_CDC_SERIAL_CONFIG_t usb_cdc_serial
Stores the CDC Virtual Serial Port communication parameters and control signals.
As the Xmega AVR devices support two Virtual Serial Ports 0 and 1, the communication parameters
and control signals are stored in an array:
USB_CDC_SERIAL_CONFIG_t usb_cdc_serial[2]
The CDC Virtual Serial Port functions may return one of the following result codes, defined in
usb_device.h:
The following functions are implemented by the CDC Virtual Serial Port library:
Selects, for the Xmega AVR devices, the current Virtual Serial Port 0 or 1 to which all the
input/output will be directed.
Transmits a byte c to the host using the currently selected CDC Virtual Serial Port.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a NULL terminated literal char string, located in RAM,
using the currently selected CDC Virtual Serial Port.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a buffer, located in RAM, using the currently selected
CDC Virtual Serial Port. The length parameter specifies the number of bytes to transmit.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a buffer, located in FLASH memory, using the currently
selected CDC Virtual Serial Port. The length parameter specifies the number of bytes to transmit.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a buffer, located in EEPROM, using the currently
selected CDC Virtual Serial Port. The length parameter specifies the number of bytes to transmit.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Transmits to the host the contents of a NULL terminated literal char string, located in FLASH
memory, using the currently selected CDC Virtual Serial Port.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Immediately transmit to the host any buffered output of the currently selected CDC Virtual
Serial Port.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Clears the receive buffer for the currently selected CDC Virtual Serial Port.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
short usb_serial_getchar(void)
Waits to receive a byte from the currently selected CDC Virtual Serial Port.
Returns:
• in MSB: USB_RES_OK (=0) – no error.
The LSB contains the received byte.
• in MSB: USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured.
The LSB value is not defined.
• in MSB: USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host.
The LSB value is not defined
• in MSB: USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
The LSB value is not defined.
short usb_serial_getcharnw(void)
Receives, without waiting, a byte from the CDC Virtual Serial Port.
Returns:
• in MSB: USB_RES_OK (=0) – no error.
The LSB contains the received byte.
• in MSB: USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured.
The LSB value is not defined.
• in MSB: USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host.
The LSB value is not defined.
Receives data from the from the currently selected CDC Virtual Serial Port and stores it into a
buffer.
The buffer pointer, points to the RAM area that will hold the received data.
The length pointer, points to an unsigned short variable that holds the number of bytes that must be
received.
Returns:
• USB_RES_OK – no error.
The variable pointed by length will hold the number of bytes that were effectively received from the
host.
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured.
The value of the variable pointed by length will remain unchanged.
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host.
The value of the variable pointed by length will remain unchanged.
• USB_RES_TIMEOUT – the device didn't receive the required number of bytes, in the time interval
specified in usb_timeout.rx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
The variable pointed by length will hold the number of bytes that were effectively received from the
host, before the receive timeout occurred.
Example:
/* Delay functions */
#include <delay.h>
};
/* Receive buffer */
unsigned char rx_buffer[32];
void main(void)
{
/* Variable that holds the number of bytes to receive */
unsigned short nbytes;
case USB_RES_CONFIG_ERROR:
printf("Error: Device not configured.\r\n");
break;
case USB_RES_DEVICE_NOT_ENUM:
printf("Error: Device not enumerated by the host.\r\n");
break;
case USB_RES_TIMEOUT:
printf("Error: Receive timeout occurred,"
" only %u bytes received.\r\n",nbytes);
break;
}
/* Stop here */
while (1);
}
Returns the number of bytes available in the currently selected CDC Virtual Serial Port's
receive buffer.
Sends RS-232 signals and error status of the currently selected CDC Virtual Serial Port to the
host.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the status, stored in the device's IN endpoint 1, in the
time interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Detailed examples on CDC Virtual Serial Port functions usage are available in the
\EXAMPLES\USB\CDC Virtual Serial Port and \EXAMPLES ATxmega\USB\CDC Virtual Serial
Port subdirectories of the CodeVisionAVR installation.
The CDC Virtual Serial Port uses the Windows serial driver.
Please follow the installation procedures below:
- The new CDC Virtual Serial Port will be now listed in the Device Manager window under Ports (COM
& LPT) as CodeVisionAVR CDC Virtual Serial Port (COMn)
- Retain the COMn number of the serial port for future use.
• Windows XP
- After connecting the USB device to the computer's USB port, the Found New Hardware Wizard
window will open
- Select Install from a List or Specific Location (Advanced)
- Click on the Next button
- Select the Search for the best driver in these locations and Include this location in search
options
- Browse to the directory where the file CVAVR CDC Virtual Serial Port.inf is located:
\Examples\USB\CDC Virtual Serial Port
- Click on the Next button
- Windows starts the driver installation, but displays a warning window with the message:
CodeVisionAVR CDC Virtual Serial Port has not passed Windows Logo testing to verify its
compatibility with Windows XP
- Click on the Continue Anyway button
- Windows finally installs the driver
- The new CDC Virtual Serial Port will be now listed in the Device Manager window under Ports
(COM & LPT) as CodeVisionAVR CDC Virtual Serial Port (COMn)
- The new CDC Virtual Serial Port will be now listed in the Device Manager window under Ports
(COM & LPT) as CodeVisionAVR CDC Virtual Serial Port (COMn)
- Retain the COMn number of the serial port for future use.
The required data type and macro definitions are placed in the file usb_hid.h, located in the .\INC
subdirectory. This file must be #include -d before using the functions.
The file usb_hid.h does automatically #include the usb_device.h header.
The Generic HID requires one interface, with the IN and OUT endpoints using Interrupt type transfers.
Before accessing a Generic HID, the USB controller must be properly initialized, using the
usb_device_init function.
All configuration structures required for a Generic HID can be easily created using the
CodeWizardAVR.
Note: In order to use a Generic HID, the corresponding option must be enabled in the
Project|Configure|C Compiler|Libraries|USB menu:
The following data type is defined in usb_hid.h and is used by a Generic HID:
/* bcdHID value */
#define USB_HID_SPEC 0x0111 /* HID 1.11 specification is supported */
After the USB controller is initialized, using the code generated by the CodeWizardAVR, all the USB
Device Mode Functions (chapter 5.19), can be used for communicating with the host.
Example:
/* Delay functions */
#include <delay.h>
};
/* Reception buffer */
unsigned char rx_buffer[64];
/* Transmission buffer */
unsigned char tx_buffer[64]={0};
void main(void)
{
unsigned short nbytes;
while (1)
{
/* Check if we have received some data */
nbytes=sizeof(rx_buffer); /* Number of bytes to receive */
if (usb_getbuf(rx_buffer,&nbytes)==USB_RES_OK)
{
/* Output the received data byte 0 to PORTD bits 4..7 and
light the corresponding LEDs */
PORTD=rx_buffer[0]<<4;
}
}
}
No special Windows driver is required, the Generic HID will be detected by the operating system when
the device is connected to the PC.
The prototypes for these functions are placed in the file usb_hid.h, located in the .\INC subdirectory.
This file must be #include -d before using the functions.
The file usb_hid.h does automatically #include the usb_device.h header.
The HID Keyboard device requires one interface, with one IN endpoint using Interrupt type transfers.
Before accessing a HID Keyboard device, the USB controller must be properly initialized, using the
usb_device_init function.
All configuration structures required for a HID Keyboard can be easily created using the
CodeWizardAVR.
Note: In order to use the HID Keyboard functions, the corresponding option must be enabled in the
Project|Configure|C Compiler|Libraries|USB menu:
The following data types are defined in usb_hid.h and used by the HID Keyboard functions:
/* bcdHID value */
#define USB_HID_SPEC 0x0111 /* HID 1.11 specification is supported */
The following global variables are defined by the HID Keyboard library:
USB_KEYBOARD_t usb_keyboard
USB_KEYBOARD_LEDS_t usb_keyboard_leds
The HID Keyboard functions may return one of the following result codes, defined in usb_device.h:
Sends the state of the currently pressed keys from usb_keyboard variable to the host, using
the currently active interface.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Sends a single keypress to the host, using the currently active interface.
key_scan contains the key scan code and modifier the key modifier values (both defined in
usb_hid.h).
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Example:
/* Delay functions */
#include <delay.h>
void main(void)
{
/* Initialization code for other chip peripherals */
/* … */
/* Stop here */
while (1);
}
The prototypes for these functions are placed in the file usb_hid.h, located in the .\INC subdirectory.
This file must be #include -d before using the functions.
The file usb_hid.h does automatically #include the usb_device.h header.
The HID Mouse requires one interface, with one IN endpoint using Interrupt type transfers.
Before accessing a HID Mouse, the USB controller must be properly initialized, using the
usb_device_init function.
All configuration structures required for a HID Mouse can be easily created using the
CodeWizardAVR.
Note: In order to use the HID Mouse functions, the corresponding option must be enabled in the
Project|Configure|C Compiler|Libraries|USB menu:
The following data types are defined in usb_hid.h and used by the HID Mouse functions:
/* bcdHID value */
#define USB_HID_SPEC 0x0111 /* HID 1.11 specification is supported */
USB_MOUSE_t usb_mouse
The HID Mouse functions may return one of the following result codes, defined in usb_device.h:
Sends mouse movement information to the host, using the currently active interface.
x, y and wheel range is -127 to 127. A value of 0 specifies no movement.
Note: The values of the x, y and wheel members of the usb_mouse global structure are updated
accordingly.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Sends the mouse buttons state to the host, using the currently active interface.
Note: The value of the buttons member in the usb_mouse global structure is updated with the new
state of the buttons.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Sends a mouse click to the host, using the currently active interface.
Note: The value of the buttons member in the usb_mouse global structure will be 0 after function
execution.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Example:
/* Delay functions */
#include <delay.h>
};
void main(void)
{
/* Initialization code for other chip peripherals */
/* … */
/* Stop here */
while (1);
}
No special Windows driver is required, the HID Mouse will be detected by the operating system when
the device is connected to the PC.
The prototypes for these functions are placed in the file usb_hid.h, located in the .\INC subdirectory.
This file must be #include -d before using the functions.
The file usb_hid.h does automatically #include the usb_device.h header.
The HID Joystick requires one interface, with one IN endpoint using Interrupt type transfers.
Before accessing a HID Joystick, the USB controller must be properly initialized, using the
usb_device_init function.
All configuration structures required for a HID Joystick can be easily created using the
CodeWizardAVR.
Note: In order to use the HID Joystick functions, the corresponding option must be enabled in the
Project|Configure|C Compiler|Libraries|USB menu:
The following data types are defined in usb_hid.h and used by the HID Joystick functions:
/* bcdHID value */
#define USB_HID_SPEC 0x0111 /* HID 1.11 specification is supported */
USB_JOYSTICK_t usb_joystick
The HID Joystick functions may return one of the following result codes, defined in usb_device.h:
Sends joystick movement and button state to the host, using the currently active interface. The
joystick_state parameter points to an USB_JOYSTICK_t structure that holds the movement values
for the X, Y, Z axis and the state of the two buttons.
Note: The usb_joystick global structure is updated with the new values, after the function is
executed.
Returns:
• USB_RES_OK – no error
• USB_RES_CONFIG_ERROR – the USB controller was not (correctly) configured
• USB_RES_DEVICE_NOT_ENUM – the device was not yet enumerated by the host
• USB_RES_TIMEOUT – the host didn't get the data, stored in the device's IN endpoint, in the time
interval specified in usb_timeout.tx
• USB_RES_DEVICE_SUSPENDED – the device is currently in suspended state.
Example:
/* Delay functions */
#include <delay.h>
/* memcmp function */
#include <string.h>
};
void main(void)
{
/* New new_joystick movement and button state */
USB_JOYSTICK_t new_joystick;
while (1)
{
/* Read new joystick movement data */
read_joystick(&new_joystick);
No special Windows driver is required, the HID Joystick will be detected by the operating system when
the device is connected to the PC.
void sleep_enable(void)
void sleep_disable(void)
void idle(void)
void powerdown(void)
void powersave(void)
void standby(void)
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 during 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:
sleep_enable();
/* Disable brown out detection in sleep */
tmp = MCUCR | (1<<BODS) | (1<<BODSE);
MCUCR = tmp;
MCUCR = tmp & (~(1<<BODSE));
powersave(); /* Takes too long until the sleep instruction is executed */
Example:
void main(void) {
/* disable interrupts */
#asm("cli")
/* 100µs delay */
delay_us(100);
/* ............. */
/* 10ms delay */
delay_ms(10);
/* enable interrupts */
#asm("sei")
/* ............. */
}
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 connection schematic is provided below:
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.
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:
void main(void)
{
/* initialize Timer1 overflow interrupts in Mode 0 (Normal) */
TCCR1A=0x00;
/* clkio/1024 */
TCCR1B=(1<<CS12)|(1<<CS10);
/* timer overflow interrupts will occur with 100Hz frequency */
TCNT1H=T1_INIT>>8;
TCNT1L=T1_INIT&0xFF;
/* enable Timer1 overflow interrupt */
TIMSK=1<<TOIE1;
/* globally enable interrupts */
#asm("sei")
while(1)
{
/* .... */
}
}
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:
Return value:
The function returns 1 byte containing the disk status flags, specified by the following macros
defined in sdcard.h:
• 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.
• 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.
• 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.
• The disk_initialize function will always configure the I/O port pin, where the SPI /SS signal is
present, as an output. This is required for the correct operation of the SPI in master mode.
The /SS signal can be used as a general purpose output, without affecting the MMC/SD/SD HC card
driver operation.
Example:
void main(void)
{
unsigned char status;
while(1)
{
/* .... */
}
}
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:
• This function must be called before performing memory card accesses, 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.
• 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.
returns the current disk status of a physical drive located on a MMC, SD or SD HC card.
Parameters:
Return value:
The function returns 1 byte containing the disk status flags, specified by the following macros
defined in sdcard.h:
• 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.
• 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.
• 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.
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;
DRESULT disk_read (unsigned char drv, unsigned char* buff, unsigned long sector, unsigned
char count)
Parameters:
Return value:
RES_OK - success
RES_ERROR - a write 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)
Parameters:
Return value:
RES_OK - success
RES_ERROR - a write 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
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.
The following ctrl command codes, specified by the macros defined in the sdcard.h header file, can
be issued to the disk_ioctl function:
• CTRL_SYNC - wait until the disk drive has finished the write process. The buff pointer must be
NULL.
• 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.
• 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.
• 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:
void main(void)
{
char display_buffer[64]; /* buffer used by sprintf */
unsigned char status;
unsigned int sector_size;
unsigned long int sector_count;
/* wait 2 seconds */
delay_ms(2000);
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 sector_count variable will be displayed correctly by the
sprintf function.
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:
• The FAT access functions are not re-entrant. They must not be called from interrupt service
routines.
• Currently the FAT access functions support only the DOS short 8.3 file name format. Long file
names are not supported.
• The file/directory names are encoded using 8bit ASCII, unicode characters are not supported.
• 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 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
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;
• The FATFS type structure is used for holding the work area associated with each logical drive
volume:
A FATFS type object is allocated by the f_mount function for each logical drive.
• The FIL type structure is used to hold the state of an open file:
This structure is initialized by the f_open and discarded by the f_close functions.
• The FILINFO type structure is used to hold the information returned by the f_stat and f_readdir
functions:
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:
• The DIR type structure is used for holding directory information returned by the f_opendir and
f_readdir functions:
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)
void (*prtc_get_date) (unsigned char *date, unsigned char *month, unsigned int *year)
On program startup these pointers need to be initialized to point to the appropriate RTC functions, like
in the following example:
void main(void)
{
/* 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 time */
prtc_get_date=
(void (*)(unsigned char *,unsigned char *,unsigned int *))
rtc_get_date;
Notes:
• If the 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.
• 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.
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:
Return Values:
FR_OK - success
FR_INVALID_DRIVE - the drive number is invalid.
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 by the f_chdrive function).
0:file.txt - a file located in the current directory (specified previously by the f_chdir function) on the
logical drive 0.
. - current directory.
The file_name must have the DOS 8.3 short file name format.
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 - the 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)
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 data 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.
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)
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 number 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.
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.
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.
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.
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.
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 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.
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:
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_FILESYSTEM - there is no valid FAT partition on the disk.
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_FILESYSTEM - there is no valid FAT partition on the disk.
Example:
if ((res=f_opendir(&directory,path))==FR_OK)
{
while (((res=f_readdir(&directory,&file_info))==FR_OK) &&
file_info.fname[0])
{
/* display file/directory name and associated information */
printf("%c%c%c%c%c %02u/%02u/%u %02u:%02u:%02u %9lu"
" %s/%s\r\n",
(file_info.fattrib & AM_DIR) ? 'D' : '-',
(file_info.fattrib & AM_RDO) ? 'R' : '-',
(file_info.fattrib & AM_HID) ? 'H' : '-',
(file_info.fattrib & AM_SYS) ? 'S' : '-',
(file_info.fattrib & AM_ARC) ? 'A' : '-',
file_info.fdate & 0x1F,(file_info.fdate >> 5) & 0xF,
(file_info.fdate >> 9)+1980,
file_info.ftime >> 11,(file_info.ftime >> 5) & 0x3F,
(file_info.ftime & 0x1F) << 1,
file_info.fsize,path,file_info.fname);
if (file_info.fattrib & 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]!='/') strcatf(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;
if (path[i]=='/') path[i]=0;
/* stop if an error occured */
if (res!=FR_OK) break;
}
}
}
}
return res;
}
void main(void)
{
/* FAT function result */
FRESULT res;
/* will hold the information for logical drive 0: */
FATFS drive;
/* root directory path */
char path[256]="0:/";
/* 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.
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_FILESYSTEM - there is no valid FAT partition on the disk.
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 that 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.
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:
void main(void)
{
/* FAT function result */
FRESULT res;
/* will hold the information for logical drive 0: */
FATFS fat;
/* pointer to the FATFS type structure */
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:/";
/* 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.
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 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.
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_FILESYSTEM - there is no valid FAT partition on the disk.
FRESULT f_chmod (const char* path, unsigned char value, unsigned char mask)
Parameters:
path points to a RAM based NULL terminated 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.
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_FILESYSTEM - there is no valid FAT partition on the disk.
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 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_FILESYSTEM - there is no valid FAT partition on the disk.
Example:
/* printf */
#include <stdio.h>
void main(void)
{
/* initialize Timer1 overflow interrupts in Mode 0 (Normal) */
TCCR1A=0x00;
/* clkio/1024 */
TCCR1B=(1<<CS12)|(1<<CS10);
/* timer overflow interrupts will occur with 100Hz frequency */
TCNT1H=T1_INIT>>8;
TCNT1L=T1_INIT&0xFF;
/* enable Timer1 overflow interrupt */
TIMSK=1<<TOIE1;
/* 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;
printf("%s \r\n",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.
Parameters:
path_old points to a RAM based NULL terminated char string that represents the path name
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.
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.
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_FILESYSTEM - there is no valid FAT partition on the disk.
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.
Parameter:
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.
The appropriate header files for hardware TWI (twi.h or twix.h) or software bit-banged I2C bus (i2c.h)
functions prototypes are automatically #include -d with the pcf8750_twi.h or pcf8750.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 I2C bus (not
the hardware TWI) communication.
Note: For proper operation, the PCF8574 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.
writes the data byte to the I/O expander, selected by the 7-bit I2C slave address, specified by the
logic state of the A0, A1 and A2 pins: 0x20..0x27 for PCF8574 and 0x38..0x3F for PCF8574A.
returns the data byte read from the I/O expander, selected by the 7-bit I2C slave address,
specified by the logic state of the A0, A1 and A2 pins: 0x20..0x27 for PCF8574 and 0x38..0x3F for
PCF8574A.
Note: In order to configure an I/O expander pin as an input (so it can be read using the pcf8574_read
function), a value of 1 must be first written to the corresponding bit using the pcf8574_write function.
which selects the TWI module used for communication with the I/O expander.
The twi_master parameter must point to a TWI_MASTER_INFO_t structure variable, that is used to
hold the information required by the TWI module when operating in master mode.
The pcf8574_twi_select function must be called first before any other PCF8574 functions.
Refer to the supplied example at the end of this topic for more details.
Note: Before calling any of the I/O expander functions, the TWI or software bit-banged I2C interface
must be properly initialized, using the appropriate functions.
For TWI operation, the interrupts must be also enabled using the #asm("sei") inline assembly code.
PCF8574 example using the hardware TWI Functions for Master Mode Operation for non-XMEGA
Devices:
/* delay functions */
#include <delay.h>
void main(void)
{
unsigned char n=0;
/* initialize the TWI in master mode with 100 kHz bit rate */
twi_master_init(100);
while (1)
{
/* toggle the output P0 */
pcf8574_write(n);
n^=1;
/* 0.5 second delay */
delay_ms(500);
}
}
PCF8574 example 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.
/* delay functions */
#include <delay.h>
void main(void)
{
unsigned char n=0;
while (1)
{
/* toggle the output P0 */
pcf8574_write(n);
n^=1;
/* 0.5 second delay */
delay_ms(500);
}
}
PCF8574 example using the hardware TWI Functions for Master Mode Operation for AVR8X
Devices.
The chip is connected to the TWI0 of an ATtiny817.
/* delay functions */
#include <delay.h>
void main(void)
{
unsigned char n=0;
while (1)
{
/* toggle the output P0 */
pcf8574_write(n);
n^=1;
/* 0.5 second delay */
delay_ms(500);
}
}
/* delay functions */
#include <delay.h>
void main(void)
{
unsigned char n=0;
while (1)
{
/* toggle the output P0 */
pcf8574_write(n);
n^=1;
/* 0.5 second delay */
delay_ms(500);
}
}
The appropriate header files for hardware TWI (twi.h or twix.h) or software bit-banged I2C bus (i2c.h)
functions 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 I2C 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.
void rtc_init(unsigned char ctrl2, unsigned char clkout, unsigned char timer_ctrl)
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:
• RTC_TIE_ON sets the Control/Status 2 register bit TIE to 1
• RTC_AIE_ON sets the Control/Status 2 register bit AIE to 1
• RTC_TP_ON sets the Control/Status 2 register bit TI/TP to 1
These macros can be combined using the | operator in order to set more bits to 1.
The clkout parameter specifies the initialization value for the PCF8563 CLKOUT Frequency register.
The pcf8563.h header file defines the following macros which allow the easy setting of the clkout
parameter:
• RTC_CLKOUT_OFF disables the generation of pulses on the PCF8563 CLKOUT output
• RTC_CLKOUT_1 generates 1Hz pulses on the PCF8563 CLKOUT output
• RTC_CLKOUT_32 generates 32Hz pulses on the PCF8563 CLKOUT output
• RTC_CLKOUT_1024 generates 1024Hz pulses on the PCF8563 CLKOUT output
• RTC_CLKOUT_32768 generates 32768Hz pulses on the PCF8563 CLKOUT output.
The timer_ctrl parameter specifies the initialization value for the PCF8563 Timer Control register.
The pcf8563.h header file defines the following macros which allow the easy setting of the timer_ctrl
parameter:
• RTC_TIMER_OFF disables the PCF8563 Timer countdown
• RTC_TIMER_CLK_1_60 sets the PCF8563 Timer countdown clock frequency to 1/60Hz
• RTC_TIMER_CLK_1 sets the PCF8563 Timer countdown clock frequency to 1Hz
• RTC_TIMER_CLK_64 sets the PCF8563 Timer countdown clock frequency to 64Hz
• RTC_TIMER_CLK_4096 sets the PCF8563 Timer countdown clock frequency to 4096Hz.
this function is used to initialize the PCF8563 library's internal variables when using the TWI
Functions for Master Mode Operation for XMEGA Devices and TWI Functions for Master Mode
Operation for AVR8X Devices.
It is not used for AVR8 devices.
The ptwim parameter must point to a TWI_MASTER_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.
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)
void rtc_set_time(unsigned char hour, unsigned char min, unsigned char sec)
void rtc_alarm_off(void)
void rtc_alarm_on(void)
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.
PCF8563 example using the hardware TWI Functions for Master Mode Operation for non-XMEGA
Devices:
void main(void)
{
unsigned char hour,min,sec,day,month;
unsigned int year;
/* initialize the TWI in master mode with 100 kHz bit rate */
twi_master_init(100);
PCF8563 example 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.
void main(void)
{
unsigned char hour,min,sec,day,month;
unsigned int year;
PCF8563 example using the hardware TWI Functions for Master Mode Operation for AVR8X
Devices.
The chip is connected to the TWI0 of an ATtiny817.
void main(void)
{
unsigned char hour,min,sec,day,month;
unsigned int year;
void main(void)
{
unsigned char hour,min,sec,day,month;
unsigned int year;
The appropriate header files for hardware TWI (twi.h or twix.h) or software bit-banged I2C 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 I2C 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.
If more then one chip is connected to the I2C 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 I2C 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.
this function is used to initialize the PCF8583 library's internal variables when using the TWI
Functions for Master Mode Operation for XMEGA Devices and TWI Functions for Master Mode
Operation for AVR8X Devices. It is not used for AVR8 devices.
The ptwim parameter must point to a TWI_MASTER_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.
void rtc_write(unsigned char chip, unsigned char address, unsigned char data)
void rtc_get_time(unsigned char chip, unsigned char *hour, unsigned char *min,
unsigned char *sec, unsigned char *hsec)
void rtc_set_time(unsigned char chip, unsigned char hour, unsigned char min, unsigned char
sec, unsigned char hsec)
void rtc_get_date(unsigned char chip, unsigned char *day, unsigned char *month, unsigned
*year)
void rtc_set_date(unsigned char chip, unsigned char day, unsigned char month,
unsigned year)
void rtc_get_alarm_time(unsigned char chip, unsigned char *hour, unsigned char *min,
unsigned char *sec, unsigned char *hsec)
void rtc_set_alarm_time(unsigned char chip, unsigned char hour, unsigned char min, unsigned
char sec, unsigned char hsec)
void rtc_get_alarm_date(unsigned char chip, unsigned char *day, unsigned char *month)
void rtc_set_alarm_date(unsigned char chip, unsigned char day, unsigned char month)
PCF8583 example using the hardware TWI Functions for Master Mode Operation for non-XMEGA
Devices:
void main(void)
{
unsigned char hour,min,sec,hsec,day,month;
unsigned int year;
/* initialize the TWI in master mode with 100 kHz bit rate */
twi_master_init(100);
PCF8583 example using the hardware TWI Functions for for Master Mode Operation XMEGA
Devices.
The chip is connected to the TWI of PORTD (TWID) of an ATxmega128A1.
void main(void)
{
unsigned char hour,min,sec,hsec,day,month;
unsigned int year;
PCF8583 example using the hardware TWI Functions for Master Mode Operation for AVR8X
Devices.
The chip is connected to the TWI0 of an ATtiny817.
void main(void)
{
unsigned char hour,min,sec,hsec,day,month;
unsigned int year;
void main(void)
{
unsigned char hour,min,sec,hsec,day,month;
unsigned int year;
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:
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.
void rtc_init(unsigned char tc_on, unsigned char diodes, unsigned char res)
this function reads a byte stored at address addr in the DS1302 registers or SRAM.
this function stores the byte data at address addr in the DS1302 registers or SRAM.
void rtc_get_time(unsigned char *hour, unsigned char *min, unsigned char *sec)
void rtc_set_time(unsigned char hour, unsigned char min, unsigned char sec)
void rtc_get_date(unsigned char *day, unsigned char *month, unsigned char *year)
void rtc_set_date(unsigned char day, unsigned char month, unsigned char year)
void main(void)
{
unsigned char hour,min,sec,day,month,year;
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 VPORT0.
void main(void)
{
unsigned char hour,min,sec,day,month,year;
The appropriate header files for hardware TWI (twi.h or twix.h) or software bit-banged I2C 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 signals, along the bit rate of the SCL clock, for bit-banged I2C 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.
void rtc_init(unsigned char rs, unsigned char sqwe, unsigned char out)
The rs parameter specifies the value of the square wave output frequency on the SQW/OUT pin:
• 0 for 1 Hz
• 1 for 4096 Hz
• 2 for 8192 Hz
• 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.
this function is used to initialize the DS1307 library's internal variables when using the TWI
Functions for Master Mode Operation for XMEGA Devices and TWI Functions for Master Mode
Operation for AVR8X Devices.
It is not used for AVR8 devices.
The ptwim parameter must point to a TWI_MASTER_INFO_t structure variable, that is used 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)
void rtc_set_time(unsigned char hour, unsigned char min, unsigned char sec)
void rtc_get_date(unsigned char *week_day, unsigned char *day, unsigned char *month,
unsigned char *year)
void rtc_set_date(unsigned char week_day, unsigned char day, unsigned char month,
unsigned char year)
DS1307 example using the hardware TWI Functions for Master Mode Operation for non-XMEGA
Devices:
void main(void)
{
unsigned char hour,min,sec,week_day,day,month,year;
/* initialize the TWI in master mode with 100 kHz bit rate */
twi_master_init(100);
DS1307 example 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.
void main(void)
{
unsigned char hour,min,sec,week_day,day,month,year;
DS1307 example using the hardware TWI Functions for Master Mode Operation for AVR8X
Devices.
The chip is connected to the TWI0 of an ATtiny817.
void main(void)
{
unsigned char hour,min,sec,week_day,day,month,year;
void main(void)
{
unsigned char hour,min,sec,week_day,day,month,year;
The appropriate header files for hardware TWI (twi.h or twix.h) or software bit-banged I2C bus (i2c.h)
functions prototypes are automatically #include -d with the ds3231_twi.h or ds3231.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 I2C bus (not
the hardware TWI) communication.
Note: For proper operation, the DS3231 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.
returns the data byte read from the specified address of a DS3231 register.
The address values for the DS3231 registers are defined in the ds3231_twi.h and ds3231.h header
files:
returns the data byte read from the DS3231 status register.
Parameters:
int_sqw_mode - specifies the operating modes of the ~INT/SQW output, as defined in the
ds3231_twi.h and ds3231.h header files:
en32khz - enables/disables the output of a square wave on the DS3231 32kHz pin.
this function is used to initialize the DS3231 library's internal variables when using the TWI
Functions for Master Mode Operation for XMEGA Devices and TWI Functions for Master Mode
Operation for AVR8X Devices. It is not used for AVR8 devices.
The ptwim parameter must point to a TWI_MASTER_INFO_t structure variable, that is used to hold
the information required by the TWI module when operating in master mode.
The ds3231_twi_init function must be called before rtc_init.
Refer to the supplied example at the end of this topic for more details.
float ds3231_get_temp(void)
void rtc_get_time(unsigned char *hour, unsigned char *min, unsigned char *sec)
void rtc_set_time(unsigned char hour, unsigned char min, unsigned char sec)
void rtc_get_date(unsigned char *week_day, unsigned char *day, unsigned char *month,
unsigned char *year)
void rtc_set_date(unsigned char week_day, unsigned char day, unsigned char month,
unsigned char year)
this function sets the configuration for the DS3231 RTC alarm 1.
The alarm parameter points to a structure, defined in the ds3231_twi.h and ds3231.h headers, that
holds the settings:
typedef struct {
unsigned char sec; /* Alarm seconds value [0..59] */
unsigned char min; /* Alarm minutes value [0..59] */
unsigned char hour; /* Alarm hour value [0..23] */
unsigned char day; /* Date day value [1..31] */
unsigned char use_sec:1; /* Trigger alarm when seconds match */
unsigned char use_min:1; /* Trigger alarm when minutes match */
unsigned char use_hour:1; /* Trigger alarm when hour match */
unsigned char use_day:1; /* Trigger alarm when date day match */
unsigned char enabled:1; /* Alarm interrupt is enabled */
} DS3231_ALARM_t;
this function reads the configuration for the DS3231 RTC alarm 1 into the DS3231_ALARM_t type
structure pointed by the alarm pointer.
Note: In order to sense the alarm triggering, the ~INT/SQW output must be enabled:
rtc_init(DS3231_INT_ON,false);
Alternatively, the status of the DS3231_STS_A1F alarm 1 interrupt flag bit, defined in the
ds3231_twi.h and ds3231.h headers, can be tested periodically:
this function sets the configuration for the DS3231 RTC alarm 2.
The alarm parameter points to a DS3231_ALARM_t type structure, defined in the ds3231_twi.h and
ds3231.h headers, that holds the settings.
Note: For the DS3231 alarm 2, the seconds trigger value is not implemented, therefore the sec and
use_sec members of the DS3231_ALARM_t structure must be set to 0.
this function reads the configuration for the DS3231 RTC alarm 2 into the DS3231_ALARM_t type
structure pointed by the alarm pointer.
Note: In order to sense the alarm triggering, the ~INT/SQW output must be enabled:
rtc_init(DS3231_INT_ON,false);
Alternatively, the status of the DS3231_STS_A2F alarm 2 interrupt flag bit, defined in the
ds3231_twi.h and ds3231.h headers, can be tested periodically:
DS3231 example using the hardware TWI Functions for Master Mode Operation for non-XMEGA
Devices:
void main(void)
{
unsigned char hour,min,sec,week_day,day,month,year;
/* initialize the TWI in master mode with 100 kHz bit rate */
twi_master_init(100);
DS3231 example 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.
void main(void)
{
unsigned char hour,min,sec,week_day,day,month,year;
DS3231 example using the hardware TWI Functions for Master Mode Operation for AVR8X
Devices.
The chip is connected to the TWI0 of an ATtiny817.
void main(void)
{
unsigned char hour,min,sec,week_day,day,month,year;
void main(void)
{
unsigned char hour,min,sec,week_day,day,month,year;
Additional examples with alarm triggering can be found in the \Examples\AVR\DS3231 RTC\TWI and
\Examples\AVR\DS3231 RTC\Bit Banged I2C subdirectories of the CodeVisionAVR installation.
The appropriate header files for hardware TWI (twi.h or twix.h) or software bit-banged I2C 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 I2C 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.
void ds1621_init(unsigned char chip,signed char tlow,signed char thigh, unsigned char pol)
If more then one chip is connected to the I2C bus, then the function must be called for each one,
specifying accordingly the function parameter chip.
Maximum 8 DS1621 chips can be connected to the I2C 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.
this function is used to initialize the LM75 library's internal variables when using the AVR8X and
XMEGA devices.
The ptwim parameter must point to a TWI_MASTER_INFO_t structure variable, that is used to hold
the information required by the TWI module when operating in master mode.
Note: Before calling this function, the TWI interface must be properly initialized, by calling the twi_init
and twi_master_init functions from the TWI Functions for Master Mode Operation for XMEGA
Devices, TWI Functions for Master Mode Operation for AVR8X Devices and the interrupts must
be enabled by executing the #asm("sei") inline assembly instruction.
Refer to the supplied example at the end of this topic for more details.
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.
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.
this functions exits the DS1621, with address chip, from the power-down mode and starts the
temperature measurements and the thermostat.
this functions enters the DS1621, with address chip, in power-down mode and stops the
temperature measurements and the thermostat.
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.
char display_buffer[33];
void main(void)
{
int t0,t1;
/* initialize the TWI in master mode with 100 kHz bit rate */
twi_master_init(100);
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.
char display_buffer[33];
void main(void)
{
int t0,t1;
The same example, but the DS1621 chips are accessed using the Software Bit-Banged I2C Bus
Functions.
char display_buffer[33];
void main(void)
{
int t0,t1;
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:
• the Enable 1 Wire Bus Interface Support option must be activated
• the I/O Port and Bit must be specified in Data Connection.
Note: Because the 1 Wire Functions require precision time delays for correct operation, the interrupts
must be disabled during their execution.
this function reads the contents of the SPD for the DS1820/DS18S20 sensor with the ROM code
stored in an array of 8 bytes located at address addr.
The functions 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_lsb,temp_msb,
temp_high,temp_low,
res1,res2,
cnt_rem,cnt_c,
crc;
} __ds1820_scratch_pad;
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).
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 <mega8515.h>
/* the ATmega8515 port and bit used for the 1 Wire bus must be specified in
the Project|Configure|C Compiler|Libraries 1 Wire menu */
/* Baud rate */
#define baud 9600
main()
{
unsigned char i,devices;
int temp;
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 <mega8515.h>
/* the ATmega8515 port and bit used for the 1 Wire bus must be specified in
the Project|Configure|C Compiler|Libraries 1 Wire menu */
main()
{
unsigned char i,devices;
int temp;
while (1)
{
/* measure and display the temperature(s) */
for (i=0;i<devices;)
{
temp=ds1820_temperature_10(&rom_codes[i][0]);
printf("t%-u=%-i.%-u\xf8" "C\n\r",++i,temp/10,
abs(temp%10));
};
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:
• the Enable 1 Wire Bus Interface Support option must be activated
• the I/O Port and Bit must be specified in Data Connection.
Note: Because the 1 Wire Functions require precision time delays for correct operation, the interrupts
must be disabled during their execution.
this function reads the contents of the SPD for the DS18B20 sensor with the ROM code stored in
an array of 8 bytes located at address addr.
The functions returns the value 1 on succes and 0 in case of error.
If only one DS18B20 sensor is used, no ROM code array is necessary and the pointer addr must be
NULL (0).
The contents of the SPD will be stored in the structure:
struct __ds18b20_scratch_pad_struct
{
unsigned char temp_lsb,temp_msb,
temp_high,temp_low,
conf_register,
res1,
res2,
res3,
crc;
} __ds18b20_scratch_pad;
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:
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 <mega8515.h>
/* the ATmega8515 port and bit used for the 1 Wire bus must be specified in
the Project|Configure|C Compiler|Libraries 1 Wire menu */
/* Baud rate */
#define baud 9600
main()
{
unsigned char i,devices;
while (1)
{
/* measure and display the temperature(s) */
for (i=0;i<devices;)
printf("t%u=%+.3f\xf8" "C\n\r",i+1,
ds18b20_temperature(&rom_codes[i++][0]));
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:
• the Enable 1 Wire Bus Interface Support option must be activated
• the I/O Port and Bit must be specified in Data Connection.
Note: Because the 1 Wire Functions require precision time delays for correct operation, the interrupts
must be disabled during their execution.
this function reads a block of size bytes starting from the DS2430 EEPROM memory address
addr and stores it in the string dest located in 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.
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.
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.
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.
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.
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
/* Baud rate */
#define baud 9600
main() {
unsigned char i,devices;
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:
• the Enable 1 Wire Bus Interface Support option must be activated
• the I/O Port and Bit must be specified in Data Connection.
Note: Because the 1 Wire Functions require precision time delays for correct operation, the interrupts
must be disabled during their execution.
this function reads a block of size bytes starting from the DS2433 EEPROM memory address
addr and stores it in the string dest located in 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.
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.
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.
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.
If only one DS2433 EEPROM is used, no ROM code array is necessary and the pointer romcode
must be NULL (0).
If several 1 Wire device are used, then the program must first identify the ROM codes for all the
devices. Only after that the DS2433 functions may be used, with the romcode pointer pointing to the
array which holds the ROM code for the needed device.
Example:
/* The ATmega8515 port and bit used for the 1 Wire bus must be specified
in the Project|Configure|C Compiler|Libraries 1 Wire menu
char buffer[100];
#define START_ADDR 2
/* Baud rate */
#define baud 9600
main() {
unsigned char i,devices;
for (i=0;i<devices;i++)
/* 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(&rom_code[i][0],
text,START_ADDR,sizeof(text)))
{
printf("Data written OK in DS2433 #%-u!\n\r",i+1);
/* display the text written in each DS2433 */
if (ds2433_read_block(&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",i+1);
}
else printf("Error writing data to DS2433 #%-u!\n\r",i+1);
};
/* stop */
while (1);
}
The appropriate header files for hardware TWI (twi.h or twix.h) or software bit-banged I2C bus (i2c.h)
functions prototypes are automatically #include -d with the lm75_twi.h or lm75.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 I2C 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.
void lm75_init(unsigned char chip,signed char thyst,signed char tos, unsigned char pol)
If more then one chip is connected to the I2C bus, then the function must be called for each one,
specifying accordingly the function parameter chip.
Maximum 8 LM75 chips can be connected to the I2C 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.
this function is used to initialize the LM75 library's internal variables when using the AVR8X and
XMEGA devices.
The ptwim parameter must point to a TWI_MASTER_INFO_t structure variable, that is used to hold
the information required by the TWI module when operating in master mode.
Note: Before calling this function, the TWI interface must be properly initialized, by calling the twi_init
and twi_master_init functions from the TWI Functions for Master Mode Operation for XMEGA
Devices, TWI Functions for Master Mode Operation for AVR8X Devices and the interrupts must
be enabled by executing the #asm("sei") inline assembly instruction.
Refer to the supplied example at the end of this topic for more details.
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 lm75_temperature_10 function.
Example how to display the temperature 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.
char display_buffer[33];
void main(void) {
int t0,t1;
/* initialize the TWI in master mode with 100 kHz bit rate */
twi_master_init(100);
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 ATxmega128A1 chip.
char display_buffer[33];
void main(void) {
int t0,t1;
The same example, but the LM75 chips are accessed using the Software Bit-Banged I2C Bus
Functions.
char display_buffer[33];
void main(void) {
int t0,t1;
Notes:
• The appropriate header files for hardware TWI (twi.h or twix.h) are automatically #include -d with
bmp085_twi.h
• For proper operation, the BMP085 functions require the presence of 4.7k pull-up resistors to +3.3V
on the SCL and SDA signals
• Before calling the BMP085 functions, the TWI interface must be properly initialized and the
interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Returns:
• In case of success, a positive value in the range 0..255, representing the read byte of data
• In case of error, the negative value defined in bmp085_twi.h:
The bmp085_twi.h header contains the definitions of the BMP085 registers and commands that are
accessible using the above mentioned functions:
reads the calibration parameters from the device's EEPROM and sets the pressure sensor's
measurement mode.
The BMP085 measurement modes are defined in bmp085_twi.h:
Note: Before calling this function, the TWI interface must be properly initialized, by calling the
twi_master_init function from the TWI Functions for Master Mode Operation for non-XMEGA
Devices and the interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
reads the calibration parameters from the device's EEPROM and sets the pressure sensor's
measurement mode.
The twi_master parameter points to the structure that holds the information used by the TWI master
Xmega module, used for communication with the pressure sensor, for performing a TWI bus
transaction.
Note: Before calling this function, the TWI interface must be properly initialized, by calling the twi_init
and twi_master_init functions from the TWI Functions for Master Mode Operation for XMEGA
Devices, TWI Functions for Master Mode Operation for AVR8X Devices and the interrupts must
be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* General TWID initialization
no external driver interface
no SDA hold time */
twi_init(&TWID,false,false);
Note: The calibration parameters read from the device's EEPROM are stored in the
bmp085_calib_param structure variable, declared in bmp085_twi.h:
typedef struct
{
short ac1; /* AC1 parameter */
short ac2; /* AC2 parameter */
short ac3; /* AC3 parameter */
unsigned short ac4; /* AC4 parameter */
unsigned short ac5; /* AC5 parameter */
unsigned short ac6; /* AC6 parameter */
short b1; /* B1 parameter */
short b2; /* B2 parameter */
short mb; /* MB parameter */
short mc; /* MC parameter */
short md; /* MD parameter */
} BMP085_CALIB_PARAM_t;
float bmp085_temperature(void)
reads the ambient temperature in °C, performing all necessary compensation based on calibration
parameters.
In case of error it returns the values defined in bmp085_twi.h:
long bmp085_pressure(void)
reads the absolute pressure in Pa, performing all necessary compensation based on calibration
parameters.
In case of error it returns the values defined in bmp085_twi.h:
void main(void)
{
float temperature,pressure;
/* USART initialization
Communication Parameters: 8 Data, 1 Stop, No Parity
USART Receiver: Off
USART Transmitter: On
USART0 Mode: Asynchronous
USART Baud Rate: 9600 (Double Speed Mode) @ 16MHz */
UCSR0A=(0<<RXC0) | (0<<TXC0) | (0<<UDRE0) | (0<<FE0) | (0<<DOR0) |
(0<<UPE0) | (1<<U2X0) | (0<<MPCM0);
UCSR0B=(0<<RXCIE0) | (0<<TXCIE0) | (0<<UDRIE0) | (0<<RXEN0) | (1<<TXEN0) |
(0<<UCSZ02) | (0<<RXB80) | (0<<TXB80);
UCSR0C=(0<<UMSEL01) | (0<<UMSEL00) | (0<<UPM01) | (0<<UPM00) | (0<<USBS0) |
(1<<UCSZ01) | (1<<UCSZ00) | (0<<UCPOL0);
UBRR0H=0x00;
UBRR0L=0xCF;
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
case BMP085_COMM_ERROR:
twi_comm_error:
printf("TWI communication error\r\n");
goto halt;
case BMP085_INIT_ERROR:
printf("Initialization parameters are not correct\r\n");
goto halt;
case BMP085_CALIB_ERROR:
printf("BMP085 calibration parameters read from EEPROM"
" are not valid\r\n");
halt:
while(1);
}
while (1)
{
/* Measure the temperature in [°C] */
temperature=bmp085_temperature();
/* Check for TWI communication error */
if (temperature==BMP085_COMM_ERROR) goto twi_comm_error;
/* Measure the absolute pressure in [Pa] */
pressure=bmp085_pressure();
/* Check for TWI communication error */
if (pressure==BMP085_COMM_ERROR) goto twi_comm_error;
/* Display the results in [°C] and [hPa] */
printf("t=%5.1fC P=%7.2fhPa\r\n",temperature,pressure/100.0);
/* 1 second delay between measurements */
delay_ms(1000);
}
}
CodeVisionAVR is also supplied with additional functions for calculating the altitude above sea level,
defined in the altitude.h header file:
returns the absolute altitude above sea level in [m], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
p0 - pressure at sea level [Pa]
Note: The standard value for the pressure [Pa] at sea level is defined in the altitude.h header:
returns the pressure at sea level in [Pa], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
abs_alt - measured absolute altitude above sea level [m].
Notes:
• The appropriate header files for hardware TWI (twi.h or twix.h) are automatically #include -d with
bmp180_twi.h
• For proper operation, the BMP180 functions require the presence of 4.7k pull-up resistors to +3.3V
on the SCL and SDA signals
• Before calling the BMP180 functions, the TWI interface must be properly initialized and the
interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Returns:
• In case of success, a positive value in the range 0..255, representing the read byte of data
• In case of error, the negative value defined in bmp180_twi.h:
The bmp180_twi.h header contains the definitions of the BMP180 registers and commands that are
accessible using the above mentioned functions:
reads the calibration parameters from the device's EEPROM and sets the pressure sensor's
measurement mode.
The BMP180 measurement modes are defined in bmp180_twi.h:
Note: Before calling this function, the TWI interface must be properly initialized, by calling the
twi_master_init function from the TWI Functions for Master Mode Operation for non-XMEGA
Devices and the interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
reads the calibration parameters from the device's EEPROM and sets the pressure sensor's
measurement mode.
The twi_master parameter points to the structure that holds the information used by the TWI master
Xmega module, used for communication with the pressure sensor, for performing a TWI bus
transaction.
Note: Before calling this function, the TWI interface must be properly initialized, by calling the twi_init
and twi_master_init functions from the TWI Functions for Master Mode Operation for XMEGA
Devices, TWI Functions for Master Mode Operation for AVR8X Devices and the interrupts must
be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* General TWID initialization
no external driver interface
no SDA hold time */
twi_init(&TWID,false,false);
Note: The calibration parameters read from the device's EEPROM are stored in the
bmp180_calib_param structure variable, declared in bmp180_twi.h:
typedef struct
{
short ac1; /* AC1 parameter */
short ac2; /* AC2 parameter */
short ac3; /* AC3 parameter */
unsigned short ac4; /* AC4 parameter */
unsigned short ac5; /* AC5 parameter */
unsigned short ac6; /* AC6 parameter */
short b1; /* B1 parameter */
short b2; /* B2 parameter */
short mb; /* MB parameter */
short mc; /* MC parameter */
short md; /* MD parameter */
} BMP180_CALIB_PARAM_t;
float bmp180_temperature(void)
reads the ambient temperature in °C, performing all necessary compensation based on calibration
parameters.
In case of error it returns the values defined in bmp180_twi.h:
long bmp180_pressure(void)
reads the absolute pressure in Pa, performing all necessary compensation based on calibration
parameters.
In case of error it returns the values defined in bmp180_twi.h:
void main(void)
{
float temperature,pressure;
/* USART initialization
Communication Parameters: 8 Data, 1 Stop, No Parity
USART Receiver: Off
USART Transmitter: On
USART0 Mode: Asynchronous
USART Baud Rate: 9600 (Double Speed Mode) @ 16MHz */
UCSR0A=(0<<RXC0) | (0<<TXC0) | (0<<UDRE0) | (0<<FE0) | (0<<DOR0) |
(0<<UPE0) | (1<<U2X0) | (0<<MPCM0);
UCSR0B=(0<<RXCIE0) | (0<<TXCIE0) | (0<<UDRIE0) | (0<<RXEN0) | (1<<TXEN0) |
(0<<UCSZ02) | (0<<RXB80) | (0<<TXB80);
UCSR0C=(0<<UMSEL01) | (0<<UMSEL00) | (0<<UPM01) | (0<<UPM00) | (0<<USBS0) |
(1<<UCSZ01) | (1<<UCSZ00) | (0<<UCPOL0);
UBRR0H=0x00;
UBRR0L=0xCF;
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
case BMP180_COMM_ERROR:
twi_comm_error:
printf("TWI communication error\r\n");
goto halt;
case BMP180_INIT_ERROR:
printf("Initialization parameters are not correct\r\n");
goto halt;
case BMP180_CALIB_ERROR:
printf("BMP180 calibration parameters read from EEPROM"
" are not valid\r\n");
halt:
while(1);
}
while (1)
{
/* Measure the temperature in [°C] */
temperature=bmp180_temperature();
/* Check for TWI communication error */
if (temperature==BMP180_COMM_ERROR) goto twi_comm_error;
/* Measure the absolute pressure in [Pa] */
pressure=bmp180_pressure();
/* Check for TWI communication error */
if (pressure==BMP180_COMM_ERROR) goto twi_comm_error;
/* Display the results in [°C] and [hPa] */
printf("t=%5.1fC P=%7.2fhPa\r\n",temperature,pressure/100.0);
/* 1 second delay between measurements */
delay_ms(1000);
}
}
CodeVisionAVR is also supplied with additional functions for calculating the altitude above sea level,
defined in the altitude.h header file:
returns the absolute altitude above sea level in [m], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
p0 - pressure at sea level [Pa]
Note: The standard value for the pressure [Pa] at sea level is defined in the altitude.h header:
returns the pressure at sea level in [Pa], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
abs_alt - measured absolute altitude above sea level [m].
Notes:
• The appropriate header files for hardware TWI (twi.h or twix.h) are automatically #include -d with
bmp280_twi.h
• For proper operation, the BMP280 functions require the presence of 4.7k pull-up resistors to +3.3V
on the SCL and SDA signals
• Before calling the BMP280 functions, the TWI interface must be properly initialized and the
interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Returns:
• In case of success, a positive value in the range 0..255, representing the read byte of data
• In case of error, the negative value defined in bmp280_twi.h:
The bmp280_twi.h header contains the definitions of the BMP280 registers and commands that are
accessible using the above mentioned functions:
/* BMP280 Registers: */
#define BMP280_CHIP_ID_REG 0xD0 /* Chip ID register */
#define BMP280_SOFT_RESET_REG 0xE0 /* Software Reset register */
reads the calibration parameters from the device's EEPROM and initializes the device.
Parameters:
Note: Before calling this function, the TWI interface must be properly initialized, by calling the
twi_master_init function from the TWI Functions for Master Mode Operation for non-XMEGA
Devices and the interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
reads the calibration parameters from the device's EEPROM and and initializes the device.
Parameters:
twi_master - points to the structure that holds the information used by the TWI master Xmega
module, used for communication with the pressure sensor, for performing a TWI bus transaction
Note: Before calling this function, the TWI interface must be properly initialized, by calling the twi_init
and twi_master_init functions from the TWI Functions for Master Mode Operation for XMEGA
Devices, TWI Functions for Master Mode Operation for AVR8X Devices and the interrupts must
be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* General TWID initialization
no external driver interface
no SDA hold time */
twi_init(&TWID,false,false);
Note: The calibration parameters read from the device's EEPROM are stored in the
bmp280_calib_param structure variable, declared in bmp280_twi.h:
typedef struct
{
unsigned short dig_T1;
signed short dig_T2;
signed short dig_T3;
unsigned short dig_P1;
signed short dig_P2;
signed short dig_P3;
signed short dig_P4;
signed short dig_P5;
signed short dig_P6;
signed short dig_P7;
signed short dig_P8;
signed short dig_P9;
} BMP280_CALIB_PARAM_t;
float bmp280_temperature(void)
reads the ambient temperature in °C, performing all necessary compensation based on calibration
parameters.
float bmp280_pressure(void)
reads the absolute pressure in Pa, with 0.1 Pa resolution, performing all necessary compensation
based on calibration parameters.
Note: calculations are performed on 64-bits with high precision.
void check_result(short n)
{
switch (n)
{
case BMP280_COMM_ERROR:
printf("TWI communication error\r\n");
goto halt;
case BMP280_INIT_ERROR:
printf("Initialization parameters are not correct\r\n");
goto halt;
case BMP280_MEAS_ERROR:
printf("Measurement error\r\n");
halt:
while(1);
}
}
void main(void)
{
float temperature,pressure;
/* USART initialization
Communication Parameters: 8 Data, 1 Stop, No Parity
USART Receiver: Off
USART Transmitter: On
USART0 Mode: Asynchronous
USART Baud Rate: 9600 (Double Speed Mode) @ 16MHz */
UCSR0A=(0<<RXC0) | (0<<TXC0) | (0<<UDRE0) | (0<<FE0) | (0<<DOR0) |
(0<<UPE0) | (1<<U2X0) | (0<<MPCM0);
UCSR0B=(0<<RXCIE0) | (0<<TXCIE0) | (0<<UDRIE0) | (0<<RXEN0) | (1<<TXEN0) |
(0<<UCSZ02) | (0<<RXB80) | (0<<TXB80);
UCSR0C=(0<<UMSEL01) | (0<<UMSEL00) | (0<<UPM01) | (0<<UPM00) | (0<<USBS0) |
(1<<UCSZ01) | (1<<UCSZ00) | (0<<UCPOL0);
UBRR0H=0x00;
UBRR0L=0xCF;
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
while (1)
{
/* Measure the temperature in degrees [C] */
temperature=bmp280_temperature();
/* Check for errors */
check_result(temperature);
/* Measure the absolute pressure in [Pa] */
pressure=bmp280_pressure();
/* Check for errors */
check_result(pressure);
/* Calculate the absolute altitude above sea level [m] */
altitude=abs_altitude(pressure,PRESSURE_SEA_LEVEL_STD);
/* Display the results */
printf("t=%5.1fC P=%7.2fhPa
Alt=%6.1fm\r\n",temperature,pressure/100.0,altitude);
/* 1 second delay between measurements */
delay_ms(1000);
}
}
long bmp280_pressure_low_res(void)
reads the absolute pressure in Pa, with 1 Pa resolution, performing all necessary compensation
based on calibration parameters.
Note: calculations are performed on 32-bits with lower precision.
This function can be used when lower code size and higher execution speed are required.
CodeVisionAVR is also supplied with additional functions for calculating the altitude above sea level,
defined in the altitude.h header file:
returns the absolute altitude above sea level in [m], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
p0 - pressure at sea level [Pa]
Note: The standard value for the pressure [Pa] at sea level is defined in the altitude.h header:
returns the pressure at sea level in [Pa], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
abs_alt - measured absolute altitude above sea level [m].
Notes:
• The appropriate header files for hardware TWI (twi.h or twix.h) are automatically #include -d with
bme280_twi.h
• For proper operation, the BME280 functions require the presence of 4.7k pull-up resistors to +3.3V
on the SCL and SDA signals
• Before calling the BME280 functions, the TWI interface must be properly initialized and the
interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Returns:
• In case of success, a positive value in the range 0..255, representing the read byte of data
• In case of error, the negative value defined in bme280_twi.h:
The bme280_twi.h header contains the definitions of the BME280 registers and commands that are
accessible using the above mentioned functions:
/* BME280 Registers: */
#define BME280_CHIP_ID_REG 0xD0 /* Chip ID register */
#define BME280_SOFT_RESET_REG 0xE0 /* Software Reset register */
reads the calibration parameters from the device's EEPROM and initializes the device.
Parameters:
Note: Before calling this function, the TWI interface must be properly initialized, by calling the
twi_master_init function from the TWI Functions for Master Mode Operation for non-XMEGA
Devices and the interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
reads the calibration parameters from the device's EEPROM and and initializes the device.
Parameters:
twi_master - points to the structure that holds the information used by the TWI master Xmega
module, used for communication with the pressure sensor, for performing a TWI bus transaction
Note: Before calling this function, the TWI interface must be properly initialized, by calling the twi_init
and twi_master_init functions from the TWI Functions for Master Mode Operation for XMEGA
Devices, TWI Functions for Master Mode Operation for AVR8X Devices and the interrupts must
be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* General TWID initialization
no external driver interface
no SDA hold time */
twi_init(&TWID,false,false);
Note: The calibration parameters read from the device's EEPROM are stored in the
bme280_calib_param structure variable, declared in bme280_twi.h:
typedef struct
{
unsigned short dig_T1;
signed short dig_T2;
signed short dig_T3;
unsigned short dig_P1;
signed short dig_P2;
signed short dig_P3;
signed short dig_P4;
signed short dig_P5;
signed short dig_P6;
signed short dig_P7;
signed short dig_P8;
signed short dig_P9;
unsigned char dig_H1;
signed short dig_H2;
unsigned char dig_H3;
signed short dig_H4;
signed short dig_H5;
signed char dig_H6;
} BME280_CALIB_PARAM_t;
float bme280_temperature(void)
reads the ambient temperature in °C, performing all necessary compensation based on calibration
parameters.
In case of error it returns the values defined in bme280_twi.h:
float bme280_pressure(void)
reads the absolute pressure in Pa, with 0.1 Pa resolution, performing all necessary compensation
based on calibration parameters.
Note: calculations are performed on 64-bits with high precision.
void check_result(short n)
{
switch (n)
{
case BME280_COMM_ERROR:
printf("TWI communication error\r\n");
goto halt;
case BME280_INIT_ERROR:
printf("Initialization parameters are not correct\r\n");
goto halt;
case BME280_MEAS_ERROR:
printf("Measurement error\r\n");
halt:
while(1);
}
}
void main(void)
{
float temperature,humidity,pressure,altitude;
/* USART initialization
Communication Parameters: 8 Data, 1 Stop, No Parity
USART Receiver: Off
USART Transmitter: On
USART0 Mode: Asynchronous
USART Baud Rate: 9600 (Double Speed Mode) @ 16MHz */
UCSR0A=(0<<RXC0) | (0<<TXC0) | (0<<UDRE0) | (0<<FE0) | (0<<DOR0) |
(0<<UPE0) | (1<<U2X0) | (0<<MPCM0);
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
while (1)
{
/* Measure the temperature in degrees [C] */
temperature=bme280_temperature();
/* Check for errors */
check_result(temperature);
/* Measure the relative humidity in [%] */
humidity=bme280_humidity();
/* Check for errors */
check_result(humidity);
/* Measure the absolute pressure in [Pa] */
pressure=bme280_pressure();
/* Check for errors */
check_result(pressure);
/* Calculate the absolute altitude above sea level [m] */
altitude=abs_altitude(pressure,PRESSURE_SEA_LEVEL_STD);
/* Display the results */
printf("t=%5.1fC RH=%3.0f%% P=%7.2fhPa
Alt=%6.1fm\r\n",temperature,humidity,pressure/100.0,altitude);
/* 1 second delay between measurements */
delay_ms(1000);
}
}
long bme280_pressure_low_res(void)
reads the absolute pressure in Pa, with 1 Pa resolution, performing all necessary compensation
based on calibration parameters.
Note: calculations are performed on 32-bits with lower precision.
This function can be used when lower code size and higher execution speed are required.
float bme280_humidity(void);
CodeVisionAVR is also supplied with additional functions for calculating the altitude above sea level,
defined in the altitude.h header file:
returns the absolute altitude above sea level in [m], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
p0 - pressure at sea level [Pa]
Note: The standard value for the pressure [Pa] at sea level is defined in the altitude.h header:
returns the pressure at sea level in [Pa], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
abs_alt - measured absolute altitude above sea level [m].
Notes:
• The appropriate header files for hardware TWI (twi.h or twix.h) are automatically #include -d with
ms5611_twi.h
• For proper operation, the MS5611-01BA functions require the presence of 4.7k pull-up resistors to
+3.3V on the SCL and SDA signals
• Before calling the MS5611-01BA functions, the TWI interface must be properly initialized and the
interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
reads the calibration parameters from the device's PROM and sets the pressure sensor's I2C bus
device_address and ADC Over-Sampling Ratio osr.
The values for these function parameters are defined in ms5611_twi.h:
Note: Before calling this function, the TWI interface must be properly initialized, by calling the
twi_master_init function from the TWI Functions for Master Mode Operation for non-XMEGA
Devices and the interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
reads the calibration parameters from the device's PROM and sets the pressure sensor's I2C bus
device_address and ADC Over-Sampling Ratio osr.
The twi parameter points to the structure that holds the information used by the TWI master Xmega
module, used for communication with the pressure sensor, for performing a TWI bus transaction.
Note: Before calling this function, the TWI interface must be properly initialized, by calling the twi_init
and twi_master_init functions from the TWI Functions for Master Mode Operation for XMEGA
Devices, TWI Functions for Master Mode Operation for AVR8X Devices and the interrupts must
be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* General TWID initialization
no external driver interface
no SDA hold time */
twi_init(&TWID,false,false);
float ms5611_temperature(void)
reads the ambient temperature in °C, with 0.01°C resolution, performing all necessary
compensation based on calibration parameters.
In case of error it returns the values defined in ms5611_twi.h:
long ms5611_pressure(void)
reads the absolute pressure in Pa, performing all necessary compensation based on calibration
parameters.
In case of error it returns the values defined in ms5611_twi.h:
void main(void)
{
float temperature,pressure;
/* USART initialization
Communication Parameters: 8 Data, 1 Stop, No Parity
USART Receiver: Off
USART Transmitter: On
USART0 Mode: Asynchronous
USART Baud Rate: 9600 (Double Speed Mode) @ 16MHz */
UCSR0A=(0<<RXC0) | (0<<TXC0) | (0<<UDRE0) | (0<<FE0) | (0<<DOR0) |
(0<<UPE0) | (1<<U2X0) | (0<<MPCM0);
UCSR0B=(0<<RXCIE0) | (0<<TXCIE0) | (0<<UDRIE0) | (0<<RXEN0) | (1<<TXEN0) |
(0<<UCSZ02) | (0<<RXB80) | (0<<TXB80);
UCSR0C=(0<<UMSEL01) | (0<<UMSEL00) | (0<<UPM01) | (0<<UPM00) | (0<<USBS0) |
(1<<UCSZ01) | (1<<UCSZ00) | (0<<UCPOL0);
UBRR0H=0x00;
UBRR0L=0xCF;
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
case MS5611_COMM_ERROR:
twi_comm_error:
printf("TWI communication error\r\n");
goto halt;
case MS5611_INIT_ERROR:
printf("Initialization parameters are not correct\r\n");
goto halt;
case MS5611_CRC_ERROR:
printf("The CRC of MS5611-01BA calibration parameters read"
"from PROM is not valid\r\n");
halt:
while(1);
}
while (1)
{
/* Measure the temperature in [°C] */
temperature=ms5611_temperature();
/* Check for TWI communication error */
if (temperature==MS5611_COMM_ERROR) goto twi_comm_error;
/* Measure the absolute pressure in [Pa] */
pressure=ms5611_pressure();
/* Check for TWI communication error */
if (pressure==MS5611_COMM_ERROR) goto twi_comm_error;
/* Display the results in [°C] and [hPa] */
printf("t=%6.2fC P=%7.2fhPa\r\n",temperature,pressure/100.0);
/* 1 second delay between measurements */
delay_ms(1000);
}
}
CodeVisionAVR is also supplied with additional functions for calculating the altitude above sea level,
defined in the altitude.h header file:
returns the absolute altitude above sea level in [m], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
p0 - pressure at sea level [Pa]
Note: The standard value for the pressure [Pa] at sea level is defined in the altitude.h header:
returns the pressure at sea level in [Pa], using the International Barometric Formula.
Parameters:
p - measured pressure in [Pa]
abs_alt - measured absolute altitude above sea level [m].
Notes:
• The appropriate header files for hardware TWI (twi.h or twix.h) are automatically #include -d with
bh1750_twi.h
• For proper operation, the BH1750FVI functions require the presence of 4.7k pull-up resistors to
+3.3V on the SCL and SDA signals
• Before calling the BH1750FVI functions, the TWI interface must be properly initialized and the
interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Parameters:
device_address - BH1750FVI 7-bit I2C bus address, defined in the bh1750_twi.h header file:
mt_reg - initialization value for the measurement time register, valid values are: 31..254.
The default value for mt_reg is defined in the bh1750_twi.h header file:
The function returns one the following values, defined in the bh1750_twi.h header file:
Note: Before calling this function, the TWI interface must be properly initialized, by calling the
twi_master_init function from the TWI Functions for Master Mode Operation for non-XMEGA
Devices and the interrupts must be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* TWI initialization
Mode: TWI Master, Bit Rate: 100 kbps */
twi_master_init(TWI_CLK_RATE);
Parameters:
twi_master - points to the structure that holds the information used by the TWI master Xmega
module, used for communication with the light sensor, for performing a TWI bus transaction
device_address - BH1750FVI 7-bit I2C bus address, defined in the bh1750_twi.h header file:
mt_reg - initialization value for the measurement time register, valid values are: 31..254.
The default value for mt_reg is defined in the bh1750_twi.h header file:
The function returns one the following values, defined in the bh1750_twi.h header file:
Note: Before calling this function, the TWI interface must be properly initialized, by calling the twi_init
and twi_master_init functions from the TWI Functions for Master Mode Operation for XMEGA
Devices, TWI Functions for Master Mode Operation for AVR8X Devices and the interrupts must
be enabled by executing the #asm("sei") inline assembly instruction.
Example:
void main(void)
{
/* General TWID initialization
no external driver interface
no SDA hold time */
twi_init(&TWID,false,false);
Parameters:
device_address - BH1750FVI 7-bit I2C bus address, defined in the bh1750_twi.h header file:
Parameters:
device_address - BH1750FVI 7-bit I2C bus address, defined in the bh1750_twi.h header file:
The function returns one the following values, defined in the bh1750_twi.h header file:
reads the result in [lx] of an illuminance measurement, previously initiated using the bh1750_start
function.
Parameter:
device_address - BH1750FVI 7-bit I2C bus address, defined in the bh1750_twi.h header file:
case BH1750_INIT_ERROR:
printf("Device not properly initialized\r\n");
halt:
while(1);
}
}
void main(void)
{
float illuminance;
/* USART initialization
Communication Parameters: 8 Data, 1 Stop, No Parity
USART Receiver: Off
USART Transmitter: On */
/* USART0 Mode: Asynchronous
USART Baud Rate: 9600 (Double Speed Mode) @ 16MHz */
UCSR0A=(0<<RXC0) | (0<<TXC0) | (0<<UDRE0) | (0<<FE0) | (0<<DOR0) |
(0<<UPE0) | (1<<U2X0) | (0<<MPCM0);
UCSR0B=(0<<RXCIE0) | (0<<TXCIE0) | (0<<UDRIE0) | (0<<RXEN0) | (1<<TXEN0) |
(0<<UCSZ02) | (0<<RXB80) | (0<<TXB80);
UCSR0C=(0<<UMSEL01) | (0<<UMSEL00) | (0<<UPM01) | (0<<UPM00) | (0<<USBS0) |
(1<<UCSZ01) | (1<<UCSZ00) | (0<<UCPOL0);
UBRR0H=0x00;
UBRR0L=0xCF;
/* TWI initialization
Mode: TWI Master
Bit Rate: 100 kHz */
twi_master_init(100);
#asm("sei")
while (1)
{
/* Start a single measurement for device with ADDR pin=0
and high resolution mode */
check_result(bh1750_start(BH1750_I2C_ADDR0,
BH1750_SINGLE_CONV_HIGH_RES));
The Automatic Program Generator is invoked using the Tools|CodeWizardAVR menu command or
by clicking on the toolbar button.
allowing to select between the AVR chip families for which automatic code generation will be
performed.
The File|New menu command or the 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:
The File|Save menu command or the 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:
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.
Note: By default the CodeWizardAVR generates initialization code even for peripherals that are not in
use (disabled).
This is a safety measure to configure correctly the chip if a software reset occurred by jumping to
address 0.
In order to reduce generated program size, this can be disabled by un-checking the
Program|Generate Code for Disabled Peripherals menu option.
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.
In the course of program generation the user will be prompted for the name of the main C file:
Note: When a .prj project for the CodeVisionAVR IDE is created, a corresponding .cproj project file
for Atmel Studio will be created too.
This allows editing/compiling the same project in both Atmel Studio and CodeVisionAVR IDE.
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
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.
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.
The AVR chip options can be specified by clicking on the Chip node of the CodeWizardAVR
selection tree.
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.
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:
• Application
• Boot Loader
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.
For devices, like the ATmega1280, that allow splitting the external SRAM in two pages, the External
SRAM configuration window will look like this:
The External SRAM page configuration list box allows selection of the splitting address for the two
external SRAM pages .
The wait states that are inserted during external SRAM access, can be specified for the lower,
respectively upper, memory pages using the Lower wait states, respectively Upper wait states list
boxes.
The MCUCR, EMCUCR, XMCRA registers in the startup initialization code are configured
automatically according to these settings.
The input/output Ports configuration can be specified by clicking on the Ports node of the
CodeWizardAVR selection tree.
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:
• if the pin is an input, it can be tri-stated (T) or have an internal pull-up (P) resistor connected to the
positive power supply.
• if the pin is an output, its value can be initially set to 0 or 1.
The PORTx register will be initialized according to these settings.
The external interrupt configuration can be specified by clicking on the External IRQ node
of the CodeWizardAVR selection tree.
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.
For some devices, like the ATmega3290, the following options may be present:
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 PCINT0-7,
pin_change_isr1 for PCINT8-15, pin_change_isr2 for PCINT16-23 and pin_change_isr3 for
PCINT24-30.
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:
If timer/counter 0 interrupts are used the following interrupt service routines may be defined by the
CodeWizardAVR:
• timer0_ovf_isr for timer/counter overflow
• timer0_compa_isr for timer/counter output compare A match
• 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.
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:
By selecting the Timer 1 tab you can have the following options:
If timer/counter 1 interrupts are used, the following interrupt service routines may be defined by the
CodeWizardAVR:
• timer1_ovf_isr for timer/counter overflow
• timer1_comp_isr or timer1_compa_isr, timer1_compb_isr and timer1_copmc_isr for
timer/counter output compare match
• 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.
By selecting the Timer 2 tab you can have the following options:
If timer/counter 2 interrupts are used, the following interrupt service routines may be defined by the
CodeWizardAVR:
• timer2_ovf_isr for timer/counter overflow
• 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 corresponding Atmel data sheet.
By selecting the Timer 3 tab you can have the following options:
If timer/counter 3 interrupts are used, the following interrupt service routines may be defined by the
CodeWizardAVR:
• timer3_ovf_isr for timer/counter overflow
• timer3_comp_isr or timer3_compa_isr, timer3_compb_isr and timer3_compc_isr for
timer/counter output compare match
• timer3_capt_isr for timer/counter input capture
Notes:
• Depending of the used AVR chip some of these options may not be present.
• 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.
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.
The Timeout Action list box allows to specify what action will be performed on watchdog timer
overflow:
• hardware Reset
• Interrupt only
• Interrupt and then hardware Reset.
If interrupt generation is enabled, the wdt_timeout_isr interrupt service function will be created.
In case the watchdog timer is enabled, you must include yourself the appropriate code sequences to
reset it periodically. Example:
#asm("wdr")
For more information about the watchdog timer you must consult the Atmel data sheet for the chip that
you use.
The UART or USART configuration can be specified by clicking on the USART node(s) of the
CodeWizardAVR selection tree.
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.
For devices featuring an USART there will be an additional Mode list box.
The serial communication is realized using the Standard Input/Output Functions getchar, gets, scanf,
putchar, puts and printf.
For interrupt driven serial communication, CodeWizardAVR automatically redefines the basic getchar
and putchar functions.
For devices with 2 UARTs, respectively 2 USARTs, there will be two tabs present: UART0 and
UART1, respectively USART0 and USART1.
The functions of configuration check and list boxes will be the same as described above.
The UART0 (USART0) will use the normal putchar and getchar functions.
In case of interrupt driven buffered communication, UART0 (USART0) 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, UART1 (USART1) will use the following variables:
rx_buffer1, rx_wr_index1, rx_rd_index1, rx_counter1, rx_buffer_overflow1,
tx_buffer1, tx_wr_index1, tx_rd_index1, tx_counter1.
All serial I/O using functions declared in stdio.h, will be done using UART0 (USART0).
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.
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 AIN0, respectively Disable Digital Input Buffer on AIN1 check
boxes, if checked, will deactivate the digital input buffers on the AIN0, respectively AIN1 pins, thus
reducing the power consumption of the chip.
The corresponding bits in the PIN registers will always read 0 in this case.
Some of this check boxes may not be present on all the AVR chips.
If the analog comparator interrupt is enabled, the CodeWizardAVR will define the ana_comp_isr
interrupt service routine.
Checking the ADC Enabled check box enables the on-chip ADC.
On some AVR devices only the 8 most significant bits of the AD conversion result can be used. This
feature is enabled by checking the Use 8 bits check box.
The ADC may be operated in bipolar mode if the Bipolar Input check box is checked.
Some AVR devices allow the ADC to use a high speed conversion mode, but with lower precision.
This feature is enabled by checking the High 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.
If ADC interrupts are used you have the possibility to enable the following functions:
• 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
• 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:
This function will return the analog-digital conversion result for the input adc_input. The input
numbering starts from 0.
If interrupts are enabled the above function will use an additional interrupt service routine adc_isr.
This routine will store the conversion result in the adc_data global variable.
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.
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 VREF 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.
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.
The Instantaneous Current Interrupt check box enables the generation of an interrupt when an
instantaneous current conversion has completed. This interrupt is serviced by the ccadc_conv_isr
ISR.
The Regular Charge Current, respectively Regular Discharge Current, list boxes determine the
threshold levels for the regular charge, respectively regular discharge currents, setting the values for
the CADRCC, respectively CADRDC, registers used for generating the Regular Current Interrupt.
The Atmega406 datasheet may be consulted for more details about the Coulomb Counter.
The SPI interface configuration can be specified by clicking on the Serial Peripheral Interface
node of the CodeWizardAVR selection tree.
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.
Checking the Clock Rate x2 check box, available for some AVR chips, will double the SPI Clock
Rate.
For communicating through the SPI interface, with disabled SPI interrupt, you must use the SPI
Functions.
If the SPI interrupt is enabled, you must use the spi_isr interrupt service routine, declared by the
CodeWizardAVR.
The USI configuration can be specified by clicking on the corresponding node 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:
The USI can also operate in the Two Wire (I2C) mode:
The Shift Reg. Clock list box sets the clock source for the USI Shift Register and Counter.
As both the USI Shift Register and Counter are clocked from the same clock source, the USI Counter
may be used to count the number of received or transmitted bits and generate an overflow interrupt
when the data transfer is complete.
Checking the USI Counter Overflow Interrupt check box will generate code for an interrupt service
routine that will be executed upon the overflow of the USI Counter.
If the USI Start Condition Interrupt check box is checked then the CodeWizardAVR will generate
code for an interrupt service routine that will be executed when a Start Condition is detected on the
I2C bus in USI Two Wire operating mode.
The I2C bus configuration can be specified by clicking on the Bit-Banged I2C Bus Interface node
of the CodeWizardAVR selection tree.
Using the I2C Port list box you can specify which port is used for the implementation of the I2C bus.
The SDA Bit and SCL Bit list boxes allow you to specify which port bits the I2C bus uses.
The LM75 Address list box allows you to specify the 3 lower bits of the I2C 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.
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 DS1621 Thermometer/Thermostat functions.
The CLKOUT list box specifies the frequency of the pulses on the CLKOUT output.
The Alarm Interrupt check box enables the generation of interrupts, on the INT pin, when the alarm
conditions are met.
The Timer|Clock list box specifies the countdown frequency of the PCF8563 Timer.
If the Int. Enabled check box is checked, an interrupt will be generated when the Timer countdown
value will be 0.
If the INT Pulses check box is checked, the INT pin will issue short pulses when the Timer countdown
value reaches 0.
The Timer|Value spinedit box specifies the Timer reload value when the countdown reaches 0.
The PCF8563 devices are accessed through the Philips PCF8563 Real Time Clock Functions.
The PCF8583 Address list box allows you to specify the low bit of the I2C 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.
The DS1307 device is accessed through the Maxim 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.
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:
The DS3231 device is accessed through the Maxim DS3231 Real Time Clock Functions.
The ~INT/SQW Output option allows selecting the function of the DS3231's output pin with the same
name:
• Disabled - the ~INT/SQW output is disabled
• Interrupt - a match between the timekeeping registers and either of the alarm registers activates
the ~INT/SQW output (if the alarm is also enabled)
• 1 Hz - SQW outputs a 1Hz square wave
• 1024 Hz - SQW outputs a 1024Hz square wave
• 4096 Hz - SQW outputs a 4096Hz square wave
• 8192 HZ - SQW outputs a 8192Hz square wave.
Activating the Enable 32kHz Output generates a 32kHz square wave signal on the DS3231's 32kHz
pin.
The 1 Wire bus configuration can be specified by clicking on the 1 Wire Bus Interface node of the
CodeWizardAVR selection tree.
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.
If you use the DS1820/DS18S20 temperature sensors, you must check the DS1820/DS18S20
Enabled check box.
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 DS1820/DS18S20 Temperature
Sensors Functions.
The Two Wire Interface configuration can be specified by clicking on the corresponding node of
the CodeWizardAVR selection tree.
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:
• TWI Master
• 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.
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.
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.
6.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 node of the CodeWizardAVR selection tree.
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 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.
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 TWSAM 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 TWCMD0 and TWCMD1 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.
The CAN Interface configuration can be specified by clicking on the corresponding node of the
CodeWizardAVR selection tree.
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:
• CAN Timer Overrun interrupt, serviced by the can_timer_isr function
• 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
The Enable MOb Registers list box allows for individual enabling/disabling of the CAN Message
Object registers.
The Enable MOb Interrupts list box allows for enabling/disabling the interrupts generated by
individual Message Object registers.
The Highest Interrupt Priority MOb list box allows selecting the Message Object register that has the
highest interrupt priority.
The CAN System Clock list box allows selecting the frequency of the CAN controller system clock.
The Propagation Time Segment list box allows for compensation of physical delay times within the
network. The duration of the propagation time segment must be twice the sum of the signal
propagation time on the bus line, the input comparator delay and the output driver delay.
The Re-Sync Jump Width list box allows for compensation of phase shifts between clock oscillators
of different bus controllers, by controller re-synchronization on any relevant signal edge of the current
transmission.
The Phase Segment 1 and Phase Segment 2 list boxes allow for compensation of phase edge
errors.
The Sample Point(s) list box allows selecting the number of times (1 or 3) the bus is sampled.
The CAN Timer Clock Period list box allows selecting the period of the CAN timer clock pulses.
The CAN Baud Rate is calculated based on the durations of the CAN System Clock, Propagation
Time Segment, 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.
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 lcd_sof_isr function.
The LCD Duty Cycle list box selects one of the following duty cycles: Static, 1/2, 1/3 or 1/4.
The LCD Bias list box selects the 1/3 or 1/2 bias. Please refer to the documentation of the LCD
manufacturer for bias selection.
The Clock Source list box selects the system clock or an external asynchronous clock as the LCD
controller clock source.
The Frame Rate spin edit allows specifying the LCD frame rate.
The LCD Frame Rate Register (LCDFRR) is initialized based on the frequency of the clock source and
the obtainable frame rate, that is as close as possible to the one that was specified.
The Frame Rate Error is calculated based on the specified Frame Rate and the real one obtained
from LCDFRR.
The Used Segments list box setting determine the number of port pins used as LCD segment drivers.
The Contrast Control list box specifies the maximum voltage on LCD segment and common pins
VLCD. The VLCD range is between 2.60 and 3.35 Vcc.
The Enable Alphanumeric LCD Support check box activates the configuration specified for the
alcd.h library functions.
The Controller Type option selects the alphanumeric LCD controller to be used:
• Hitachi HD44780 or compatible
• Samsung KS0073
• Solomon Systech SSD1803, used in Electronic Assembly's www.lcd-module.de DIP203 display
modules.
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.
The Display Type list box allows to select the graphic controller type and display 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 glcd_init function, that only the internal
character generator of the controller is used for displaying text.
Note: This option is available only for graphic display controllers that have a built-in character
generator.
The connections between the graphic display 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 display controller's data bus
bits to match the bits with the same numbers of the same AVR I/O port.
The Enable Resistive Touchscreen Support check box activates the configuration specified for the
rtouch.h library functions.
The Controller list box selects the type of the resistive touchscreen controller.
The Connections between the controller and the AVR I/O ports can be specified individually for each
signal.
One of the two connection modes for the touchscreen controller's voltage reference can be selected
using the Vref Connection list box:
• Single-ended
• Differential.
In order to sense the state of the /PENIRQ output of the touchscreen controller, the rt_timerproc
function (rtouch.h) needs to be called every 10ms by a timer overflow or compare match interrupt
service routine, which can be selected using the Timer Interrupt Service Routine list box.
This list box is automatically updated by the CodeWizardAVR when the user enables or disables a
timer interrupt.
If no interrupt service routine is selected, an error will be issued during code generation.
The user will be then prompted to go to the Timer Settings and configure one of the timers to
generate an interrupt every 10 ms.
The Enable Capacitive Touchscreen Support check box activates the generation of code for the
ft5x06.h library functions.
The Controller list box selects the type of the capacitive touchscreen controller.
The Connections between the controller and the AVR I/O ports can be specified individually for each
signal.
Communication with the capacitive touchscreen controller is performed using the hardware TWI.
When detecting a touch, the controller produces a high to low transition of the /INT signal, which must
be sensed by one of the I/O port input pins and produce an external interrupt.
This will be processed by the microcontroller, the corresponding interrupt service routine performing a
call to the ct_inthandler function from the Capacitive Touchscreen Functions library, described in
chapter 5.14.
The WAKE signal must be connected to a logic high level. Alternatively, it can be connected to an I/O
port output pin and set to low level by the user's program, forcing the controller to enter low power
consumption mode.
The /RES signal must be connected to the corresponding /RES (/RESET) reset signal of the graphic
display controller.
The configuration of the USB Controller can be specified by clicking on the corresponding node of
the CodeWizardAVR selection tree.
The USB library currently supports the Device, Full Speed operating mode of the USB controller.
In order to use the USB controller, the Enabled option must be checked.
The user must specify the following parameters, that need to be sent to the host:
• Manufacturer name
• Product name
• Serial Number of the product
• Vendor ID of the manufacturer, in hexadecimal format
• Product ID, in hexadecimal format
• Device Release Number, in BCD format.
Notes:
• In order to reduce FLASH memory usage, the Serial Number field may be left blank
• The Vendor ID and Product ID values must match the ones from the Windows .inf file used when
installing the driver for the USB device.
The Timeouts Tx, respectively RX, fields allow to specify the transmission, respectively reception,
timeouts used when communicating with the host. The values are expressed in ms.
The USB device mode library functions for non-Xmega devices, support operating a maximal number
of two interfaces.
This allows for the implementation of composite USB devices, for example mouse and keyboard,
using a single USB controller.
The configuration for each interface is selected by clicking on the corresponding tab:
• Interface 0
• Interface 1.
The Class option allows selecting the USB device class to be implemented by the Interface.
The following device classes are currently supported by the USB library:
• CDC Virtual Serial Port
• HID Generic
• HID Keyboard
• HID Mouse
• HID Joystick.
Notes:
• The CDC Virtual Serial Port requires the usage of both interfaces.
Interface 0 is used for RS232 control signals and Interface 1 for data communication.
• The HID Generic class allows additionally specifying the Vendor Page and Usage, used in HID
reports.
Each interface can have two endpoints (buffers) used for data storage in communication with the host:
• IN Endpoint stores the data to be transmitted by the device to the host
• OUT Endpoint stores the data received by the device from the host.
Notes:
• For some device classes (HID Mouse for example), there may be only one endpoint (IN), as the
device may only send data to the host.
• Endpoint 0 is always used for Control type transfers.
The Type selection allows specifying how the data transfer with the host will be performed:
• Isochronous transfers have a guaranteed rate, where the host can request a specific number of
bytes to transfer at defined intervals, without error correction
• Interrupt transfers have error correction and guaranteed maximum latency, specified by the
device. When a driver has requested a data transfer, the host allows no more than the specified
maximum latency, to elapse between transfer attempts
• Bulk transfers are the fastest, but have no guaranteed timing.
After the Program|Generate menu command is executed, the wizard will create three source files:
• main program file
• usb_init.h
• usb_init.c.
The contents of each file can be viewed in the Program Preview window, by selecting the appropriate
tab:
When creating the new CodeVisionAVR project, the wizard will automatically set the correct options
for USB library functions in the Project|Configure|Libraries|USB menu.
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 DS1302 Real Time Clock Functions.
You can specify the Project Name, Date, Author, Company and Comments.
The Automatic Program Generator is invoked using the Tools|CodeWizardAVR menu command or
by clicking on the toolbar button.
allowing to select between the AVR chip families for which automatic code generation will be
performed.
The File|New menu command or the toolbar button allow creating a new CodeWizardAVR project.
This project will be named by default untitled.cwx .
The File|Open menu command or the toolbar button allow loading an existing CodeWizardAVR
project:
The File|Save menu command or the 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:
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.
Note: By default the CodeWizardAVR generates initialization code even for peripherals that are not in
use (disabled).
This is a safety measure to configure correctly the chip if a software reset occurred by jumping to
address 0.
In order to reduce generated program size, this can be disabled by un-checking the
Program|Generate Code for Disabled Peripherals menu option.
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 configuration conflicts will be prompted to the user, allowing him to correct the
errors.
In the course of program generation the user will be prompted for the name of the main C file:
Note: When a .prj project for the CodeVisionAVR IDE is created, a corresponding .cproj project file
for Atmel Studio will be created too.
This allows editing/compiling the same project in both Atmel Studio and CodeVisionAVR IDE.
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
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.
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.
The general chip options can be specified by clicking on the General Settings node of the
CodeWizardAVR selection tree.
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:
• Application
• Boot Loader
The Check Reset Source check box enables the generation of code that allows the identification of
the conditions that caused the XMEGA chip reset:
• 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:
• Low Level Interrupts
• Medium Level Interrupts
• High Level Interrupts.
The various XMEGA clock source options can be specified by clicking on the System Clocks 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:
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:
• 32.768kHz Internal RC Oscillator
• 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 ClkCPU 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.
If an External Oscillator or Clock is used as System Clock Source, the following specific
configuration options are available:
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:
• switch to the 2MHz internal oscillator, independently of any clock system lock setting, by reseting
the System Clock Selection Register to its default value
• reset the Oscillator Control Register Register to its default value
• Set the External Clock Source Failure Detection Interrupt Flag in the XOSC Failure Detection
Register
• Issue a Non-Maskable Interrupt (NMI).
If a Phase Locked Loop (PLL) is used as System Clock Source, the following specific configuration
options are available:
The Clock Source list box allows to select one of the following clocks for the PLL:
• 2MHz Internal RC Oscillator
• 32MHz Internal RC Oscillator divided by 4
• 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.
If an External Oscillator or Clock is selected as PLL clock source, we can find the specific options,
that were explained previously:
void system_clocks_init(void)
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.
Depending on the EBI operating mode, additional tabs are displayed for the configuration of the
CS0...CS3 chip select signals:
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.
Specific options can be set if SDRAM chips are connected to the XMEGA chip:
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.
This can be achieved by using the __reset attribute applied to the clock initialization function:
The code generated by the CodeWizardAVR for XMEGA chips, automatically handles such situations.
The XMEGA Event System can be configured by clicking on the Event System node of the
CodeWizardAVR selection tree.
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 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.
void event_system_init(void)
The XMEGA Input/Output Ports can be configured by clicking on the Ports and PORTn nodes of
the CodeWizardAVR selection tree.
The following options are available for configuring each bit of an I/O port:
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.
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.
void ports_init(void)
The XMEGA Virtual Ports can be configured by clicking on the Virtual Ports node of the
CodeWizardAVR selection tree.
The VPORT0 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.
void vports_init(void)
The XMEGA Timers/Counters can be configured by clicking on the Timers/Counters and TCn
nodes of the CodeWizardAVR selection tree.
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:
• 16Bit
• 16Bit, with High Resolution Extension enabled
• 8Bit.
The Mode list box allows to select one of the following Timer/Counter operating modes:
• 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
Channels 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.
Each type of interrupt can be individually enabled and its priority set, using the corresponding list
boxes.
In Frequency Waveform Generation mode the following specific options are available:
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%.
In Single Slope PWM Generation and Double Slope PWM Generation modes the following specific
options are available:
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.
When operating in waveform generation 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:
The Dead Time Insertion group box contains the settings for the Dead Time Insertion (DTI) unit, that
enables the 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.
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 waveform generation mode.
This value will be used to initialize the DTILS register.
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.
The Restart Mode list box allows to specify how the AWeX and Timer/Counter can return from the
fault state and restore normal operation, when the fault condition is no longer active:
• 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.
• 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.
void tcmn_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.
The XMEGA Watchdog Timer (WDT) can be configured by clicking on the Watchdog Timer node
of the CodeWizardAVR selection tree.
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.
void watchdog_init(void)
The Clock Source list box allows to select the signal that will be used as RTC clock:
• 1024 Hz obtained from the 32 kHz internal Ultra Low Power oscillator
• 1024 Hz obtained from the 32.768 kHz external crystal oscillator on the TOSC1 and TOSC2 pins
• 1024 Hz obtained from the 32 kHz internal RC oscillator
• 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 registers.
The initial value for the CNT (count) 16-bit register can be specified in hexadecimal, using the
appropriate edit box.
Each type of interrupt can be individually enabled and its priority set, using the corresponding list
boxes.
void rtcxm_init(void)
7.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 node of the CodeWizardAVR selection tree.
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 signal 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.
Each type of interrupt can be individually enabled and its priority set, using the corresponding list
boxes.
void rtc32_battery_backup_init(void)
void rtc32_battery_backup_disable(void)
function.
The XMEGA USARTs can be configured by clicking on the USARTs and USARTn nodes of the
CodeWizardAVR selection tree.
The Communication Mode list box allows to select one of the following operating modes:
• Asynchronous USART
• Synchronous USART
• Infrared Module (IRDA 1.4)
• Master SPI.
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:
• Disabled
• Even
• 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 communication 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.
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 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.
If the Infrared Module communication mode is used, some specific options are available:
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.
If the Master SPI communication mode is used, some specific options are available:
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.
void putchar_usartmn(char c)
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.
The SPI Enabled check box allows to activate the corresponding Serial Peripheral Interface.
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.
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.
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:
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:
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 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.
The configuration of the USB Interface controller can be specified by clicking on the corresponding
node of the CodeWizardAVR selection tree.
The USB library currently supports the Device, Full Speed operating mode of the USB controller.
In order to use the USB controller, the USB Enabled option must be checked.
The USB Clock option allows to select the clock source used by the USB controller:
• Internal 32 MHz RC oscillator, calibrated and adjusted to 48 MHz using the DFLL and USB Start
Of Frame
• PLL running at 48 or 96 MHz.
If the PLL is used as USB controller clock source, then its reference Clock can be selected as:
• Internal 2 MHz RC Oscillator
• Internal 32 MHz RC Oscillator output divided by 4
• External Oscillator or Clock.
The Interrupt option specifies the interrupt priority level used by the USB controller.
By enabling the Use Suspend/Resume Handlers option, special code can be generated for functions
to be called when the device enters or exits the suspended state.
The user must specify the following parameters, that need to be sent to the host:
• Manufacturer name
• Product name
• Serial Number of the product
• Vendor ID of the manufacturer, in hexadecimal format
• Product ID, in hexadecimal format
• Device Release Number, in BCD format.
Notes:
• In order to reduce FLASH memory usage, the Serial Number field may be left blank
• The Vendor ID and Product ID values must match the ones from the Windows .inf file used when
installing the driver for the USB device.
The Timeouts Tx, respectively RX, fields allow specifying the transmission, respectively reception,
timeouts used when communicating with the host. The values are expressed in ms.
The USB device mode library functions for Xmega devices, support operating a maximal number of
four interfaces.
This allows for the implementation of composite USB devices, for example virtual serial port, mouse
and keyboard, using a single USB controller.
The configuration for each interface is selected by clicking on the corresponding tab:
• Interface 0
• Interface 1
• Interface 2
• Interface 3.
The Class option allows selecting the USB device class to be implemented by the Interface.
The following device classes are currently supported by the USB library:
• CDC Virtual Serial Port
• HID Generic
• HID Keyboard
• HID Mouse
• HID Joystick.
Notes:
• Up to two CDC Virtual Serial Ports: 0 and 1 are supported. Each port requires the usage of two
interfaces. Interface 0, respectively Interface 2, is used for RS232 control signals and Interface 1,
respectively Interface 3, for data communication.
• The HID Generic class allows additionally specifying the Vendor Page and Usage, used in HID
reports.
Each interface can have two endpoints (buffers) used for data storage in communication with the host:
• IN Endpoint stores the data to be transmitted by the device to the host
• OUT Endpoint stores the data received by the device from the host.
Notes:
• For some device classes (HID Mouse for example), there may be only one endpoint (IN), as the
device may only send data to the host.
• Endpoint 0 is always used for Control type transfers.
The Type selection allows to specify how the data transfer with the host will be performed:
• Isochronous transfers have a guaranteed rate, where the host can request a specific number of
bytes to transfer at defined intervals, without error correction
• Interrupt transfers have error correction and guaranteed maximum latency, specified by the
device. When a driver has requested a data transfer, the host allows no more than the specified
maximum latency, to elapse between transfer attempts
• Bulk transfers are the fastest, but have no guaranteed timing.
After the Program|Generate menu command is executed, the wizard will create three source files:
• main program file
• usb_init.h
• usb_init.c.
The contents of each file can be viewed in the Program Preview window, by selecting the appropriate
tab:
When creating the new CodeVisionAVR project, the wizard will automatically set the correct options
for USB library functions in the Project|Configure|Libraries|USB menu.
The 1 Wire Protocol Functions for the XMEGA chips can be configured by clicking on the 1 Wire
node of the CodeWizardAVR selection tree.
• Enable 1 Wire Bus Interface Support allows the activation of the 1 Wire Protocol Functions.
• I/O Port and Bit specify in Data Connection, the port and bit used for 1 Wire bus communication
• DS1820/DS18S20 Enabled check box activates the generation of support code for accessing the
DS1820/DS18S20 temperature sensor 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 DS1820/DS18S20 Temperature
Sensors Functions.
The XMEGA Two Wire Interfaces (TWI) can be configured by clicking on the Two Wire Interfaces
nodes of the CodeWizardAVR selection tree.
• Enable SDA Hold Time allows to add an internal hold time to the SDA signal with respect to the
negative edge of SCL.
• 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 settings are available for operating the TWI module in Master mode:
The following settings are available for operating the TWI module in Slave mode:
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.
• Receive Buffer Size specifies the size of the receive buffer in bytes.
• 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.
• 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 channel 0 in
differential mode, with both + and - inputs connected internally together.
• 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:
• 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:
Note: Differential input modes are available only for Signed ADC conversion mode.
• Positive Input allows to select which ADC pin will be used as channel's positive input for modes
that use external input signals
• Negative Input allows to select which ADC pin will be used as channel's negative input for
Differential input modes
• 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 conversion result is compared with the value of
the CMPL and CMPH registers, an interrupt being generated if the specified condition is met.
In the Free Running conversion start mode, the ADC will continuously sweep the channels specified
by the Sweeped Channel(s) list box:
In the above example figure, the ADC will continuously sweep the inputs of channels 0, 1, 2 and 3.
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:
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.
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:
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.
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.
This function will start an analog to digital conversion for the specified channel of ADCn.
It is generated only in Channels 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:
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:
When called, these functions will start analog to 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.
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:
• AVR1300: Using the XMEGA ADC
• XMEGA A Manual
• XMEGA D Manual.
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.
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 reference option allows to select the reference used by the DAC:
• 1.0 V internal reference
• the AVCC pin
• the AREF pin on PORTA
• the AREF pin on PORTB.
The Left Adjust Value option, if enabled, allows to distribute the data bits 4..11 to the CH0DATAH,
and data bits 0..3 to the bits 4..7 of the CH0DATAL registers.
This also allows for 8-bit Digital to Analog conversions if only the CH0DATAH register is written.
If the option is disabled, the data bits 0..7 are distributed to the CH0DATAL, and data bits 8..11 to the
bits 8..11 of the CH0DATAH 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.
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:
• Channel 1 External Output Enabled check box allows to activate the output of DAC Channel 1
on the corresponding port pin
• 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
• DAC Channel Refresh Timing allows to specify the time interval between each time a channel is
updated. This interval can't exceed 30 us.
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.
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.
The Enable Alphanumeric LCD Support check box activates the configuration specified for the
alcd.h library functions.
The Controller Type option selects the alphanumeric LCD controller to be used:
• Hitachi HD44780 or compatible
• Samsung KS0073
• Solomon Systech SSD1803, used in Electronic Assembly's (www.lcd-module.de) DIP203 display
modules.
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.
The I/O port allocation for the Graphic Display Functions can be configured by clicking on the
Graphic Display node of the CodeWizardAVR selection tree.
The Display Type list box allows to select the graphic controller type and display 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 glcd_init function, that only the internal
character generator of the controller is used for displaying text.
Note: This option is available only for graphic display 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 display controller's data bus
bits to match the bits with the same numbers of the same AVR I/O port.
The Enable Resistive Touchscreen Support check box activates the configuration specified for the
rtouch.h library functions.
The Controller list box selects the type of the resistive touchscreen controller.
The Connections between the controller and the AVR I/O ports can be specified individually for each
signal.
One of the two connection modes for the touchscreen controller's voltage reference can be selected
using the Vref Connection list box:
• Single-ended
• Differential.
In order to sense the state of the /PENIRQ output of the touchscreen controller, the rt_timerproc
(rtouch.h) function needs to be called every 10ms by a timer overflow or compare match interrupt
service routine, which can be selected using the Timer Interrupt Service Routine list box.
This list box is automatically updated by the CodeWizardAVR when the user enables or disables a
timer interrupt.
If no interrupt service routine is selected, an error will be issued during code generation.
The user will be then prompted to go to the Timer Settings and configure one of the timers to
generate an interrupt every 10 ms.
The Enable Capacitive Touchscreen Support check box activates the generation of code for the
ft5x06.h library functions.
The Controller list box selects the type of the capacitive touchscreen controller.
The Connections between the controller and the AVR I/O ports can be specified individually for each
signal.
Communication with the capacitive touchscreen controller is performed using the hardware TWI.
The user has the choice of selecting the TWI peripheral to be used.
When detecting a touch, the controller produces a high to low transition of the /INT signal, which must
be sensed by one of the I/O port input pins and produce an external interrupt.
This will be processed by the microcontroller, the corresponding interrupt service routine performing a
call to the ct_inthandler function from the Capacitive Touchscreen Functions library, described in
chapter 5.14.
The WAKE signal must be connected to a logic high level. Alternatively, it can be connected to an I/O
port output pin and set to low level by the user's program, forcing the controller to enter low power
consumption mode.
The /RES signal must be connected to the corresponding /RES (/RESET) reset signal of the graphic
display controller.
You can specify the Project Name, Date, Author, Company and Comments.
8. Licensing System
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.
After pressing the OK button, CodeVisionAVR will be restarted and ready to use.
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:
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.
The Help|Transfer/Deactivate License menu command must be used in order to transfer the license
to another computer.
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.
If the Activation Server could not be contacted, the following message will be displayed:
The Removal Code must be sent by e-mail to HP InfoTech in order to confirm 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.
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.
If there was an error contacting the Activation Server, the following error message will be displayed:
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.
9. License Agreement
This product is © Copyright 1998-2016 by Pavel Haiduc and HP InfoTech S.R.L., all rights reserved.
International copyright laws, international treaties and all other applicable national or international laws
protect this product. This software product and documentation may not, in whole or in part, be copied,
photocopied, translated, or reduced to any electronic medium or machine readable form, without prior
consent in writing, from HP InfoTech S.R.L. and according to all applicable laws.
The sole owners of this product are Pavel Haiduc and HP InfoTech S.R.L.
9.3 Restrictions
You may not use, copy, modify, translate, or transfer the programs, documentation, or any copy
except as expressly defined in this agreement. You may not attempt to unlock or bypass any "copy-
protection" or authentication algorithm utilized by the program. You may not remove or modify any
copyright notice or the method by which it may be invoked.
9.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.
HP INFOTECH S.R.L.
BD. DECEBAL NR. 3
BL. S12B, SC. 2, AP. 29
SECTOR 3
BUCHAREST
ROMANIA
Phone: +(40)-723469754
Fax: +(40)-213261876
e-mail: office@hpinfotech.com
Internet: http://www.hpinfotech.com
http://www.hpinfotech.biz
http://www.hpinfotech.ro