mikroC PRO for AVR Develop your applications quickly and easily with the world's most intuitive mikroC PRO for AVR Microcontrollers. Highly sophisticated IDE provides the power you need with the simplicity of a Windows based point-and-click environment. With useful implemented tools, many practical code examples, broad set of built-in routines, and a comprehensive Help, mikroC PRO for AVR makes a fast and reliable tool, which can satisfy needs of experienced engineers and beginners alike.
mikroC PRO for AVR December 2008. Reader’s note DISCLAIMER: mikroC PRO for AVR and this manual are owned by mikroElektronika and are protected Reader’s Note by copyright law and international copyright treaty. Therefore, you should treat this manual like any other copyrighted material (e.g., a book). The manual and the compiler may not be copied, partially or as a whole without the written consent from the mikroEelktronika.
USER MANUAL Table of Contents CHAPTER 1 Introduction CHAPTER 2 mikroC PRO for AVR Environment CHAPTER 3 mikroC PRO for AVR Specifics CHAPTER 4 AVR Specifics CHAPTER 5 mikroC PRO for AVR Language Reference CHAPTER 6 mikroC PRO for AVR Libraries
Table of Contents mikroC PRO for AVR CHAPTER 1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Where to Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 mikroElektronika Associates License Statement and Limited Warranty . . . . . 4 IMPORTANT - READ CAREFULLY . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 LIMITED WARRANTY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents Run Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Tools Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Help Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 mikroc pro for avr ide . .
Table of Contents mikroC PRO for AVR ROM Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Procedures Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Procedures Size Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Procedures Locations Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 HTML Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents Customizing Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Edit Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Managing Project Group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Add/Remove Files from Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Project Level Defines: . . . . . . . . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR CHAPTER 3 Notes: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 ANSI Standard Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Divergence from the ANI C Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Predefined Globals and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Predefined project level defines . . . .
mikroC PRO for AVR Table of Contents Local vars optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Better code generation and local optimization . . . . . . . . . . . . . . . . . . . 111 CHAPTER 4 Types Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Nested Calls Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Important notes: . . . . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR Floating Point Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Character Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Escape Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Disambiguation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 String Constants . . . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents Type Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Fundamental Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Arithmetic Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Integral Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Floating-point Types . . . . . . .
Table of Contents mikroC PRO for AVR Structure Uniqueness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Union Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Size of Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Union Member Access . . . . . . . . . .
mikroC PRO for AVR Table of Contents Function Calls and Argument Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 Argument Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 Operators Precedence and Associativity . . . . .
Table of Contents mikroC PRO for AVR Expression Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Selection Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Nested If statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Note . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents CHAPTER 6 Hardware AVR-specific Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 Standard ANSI C Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Miscellaneous Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Library Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 ADC Library . . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR Cf_Read_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 Cf_Read_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 Cf_Write_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Cf_Write_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Cf_Read_Sector . . . . . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents Glcd_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 Glcd_Set_Side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Glcd_Set_X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Glcd_Set_Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 Glcd_Read_Data . . . . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR Lcd_Cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Available Lcd Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 Manchester Code Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 External dependencies of Manchester Code Library . . .
mikroC PRO for AVR Table of Contents Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 OneWire Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 External dependencies of OneWire Library . . . . . . . . . . . . . . . . . . . . . . 347 Library Routines . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR Ps2_Key_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 Special Function Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 PWM Library . . . . . . . . . . . . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 Message format and CRC calculations . . . . . . . . . . . . . . . . . . . . . . . . . 401 Software I˛C Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 External dependecies of Soft_I2C Library . . . . . . . . . . . . . . . . . . . . . . . 402 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR SPI1_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 SPI1_Init_Advanced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 SPI1_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 SPI1_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 Library Example . . . . . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents SPI_Glcd_V_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 SPI_Glcd_H_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 SPI_Glcd_Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 SPI_Glcd_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 SPI_Glcd_Circle . . . . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR External dependencies of SPI T6963C Graphic Lcd Library . . . . . . . . 483 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484 SPI_T6963C_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 SPI_T6963C_WriteData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 SPI_T6963C_WriteCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents External dependencies of T6963C Graphic LCD Library . . . . . . . . . . . 507 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508 T6963C_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509 T6963C_WriteData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510 T6963C_WriteCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530 TWI_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530 TWI_Busy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 TWI_Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 TWI_Read . . . . . . . . . . . . . . . .
mikroC PRO for AVR Table of Contents ANSI C Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545 Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545 acos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 asin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 atan . . . . . . . . . . . .
Table of Contents mikroC PRO for AVR rand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552 srand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552 xtoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553 Div Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553 ANSI C String Library . .
mikroC PRO for AVR Table of Contents FloatToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565 Dec2Bcd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566 Bcd2Dec16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566 Dec2Bcd16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567 Sprint Library . . . . . . . . . . . . . . .
Table of Contents XXX mikroC PRO for AVR MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 1 Introduction to mikroC PRO for AVR The mikroC PRO for AVR is a powerful, feature-rich development tool for AVR microcontrollers. It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems, without compromising performance or control.
CHAPTER 1 mikroC PRO for AVR Introduction mikroC PRO for AVR IDE Features mikroC PRO for AVR allows you to quickly develop and deploy complex applications: - Write your C source code using the built-in Code Editor (Code and Parameter Assistants, Code Folding, Syntax Highlighting, Auto Correct, Code Templates, and more.) - Use included mikroC PRO for AVR libraries to dramatically speed up the development: data acquisition, memory, displays, conversions, communication etc.
mikroC PRO for AVR CHAPTER 1 Introduction - Get detailed reports and graphs: RAM and ROM map, code statistics, assembly listing, calling tree, and more. - mikroC PRO for AVR provides plenty of examples to expand, develop, and use as building bricks in your projects. Copy them entirely if you deem fit – that’s why we included them with the compiler. Where to Start - In case that you’re a beginner in programming AVR microcontrollers, read carefully the AVR Specifics chapter.
CHAPTER 1 mikroC PRO for AVR Introduction MIKROELEKTRONIKA ASSOCIATES LICENSE STATEMENT AND LIMITED WARRANTY IMPORTANT - READ CAREFULLY This license statement and limited warranty constitute a legal agreement (“License Agreement”) between you (either as an individual or a single entity) and mikroElektronika (“mikroElektronika Associates”) for software product (“Software”) identified above, including any software, media, and accompanying on-line or printed documentation.
mikroC PRO for AVR CHAPTER 1 Introduction LIMITED WARRANTY Respectfully excepting the Redistributables, which are provided “as is”, without warranty of any kind, mikroElektronika Associates warrants that Software, once updated and properly used, will perform substantially in accordance with the accompanying documentation, and Software media will be free from defects in materials and workmanship, for a period of ninety (90) days from the date of receipt.
CHAPTER 1 mikroC PRO for AVR Introduction HIGH RISK ACTIVITIES Software is not fault-tolerant and is not designed, manufactured or intended for use or resale as on-line control equipment in hazardous environments requiring fail-safe performance, such as in the operation of nuclear facilities, aircraft navigation or communication systems, air traffic control, direct life support machines, or weapons systems, in which the failure of Software could lead directly to death, personal injury, or severe physical
mikroC PRO for AVR CHAPTER 1 Introduction TECHNICAL SUPPORT In case you encounter any problem, you are welcome to our support forums at www.mikroe.com/forum/. Here, you may also find helpful information, hardware tips, and practical code snippets. Your comments and suggestions on future development of the mikroC PRO for AVR are always appreciated — feel free to drop a note or two on our Wishlist. In our Knowledge Base www.mikroe.
CHAPTER 1 mikroC PRO for AVR Introduction HOW TO REGISTER The latest version of the mikroC PRO for AVR is always available for downloading from our website. It is a fully functional software libraries, examples, and comprehensive help included. The only limitation of the free version is that it cannot generate hex output over 2 KB. Although it might sound restrictive, this margin allows you to develop practical, working applications with no thinking of demo limit.
mikroC PRO for AVR CHAPTER 1 Introduction This will start your e-mail client with message ready for sending. Review the information you have entered, and add the comment if you deem it necessary. Please, do not modify the subject line. Upon receiving and verifying your request, we will send the license key to the e-mail address you specified in the form.
CHAPTER 1 mikroC PRO for AVR Introduction After Receving the License Key The license key comes as a small autoextracting file – just start it anywhere on your computer in order to activate your copy of compiler and remove the demo limit. You do not need to restart your computer or install any additional components. Also, there is no need to run the mikroC PRO for AVR at the time of activation. Notes: - The license key is valid until you format your hard disk.
mikroC PRO for AVR USER MANUAL CHAPTER 2 mikroC PRO for AVR Environment The mikroC PRO for AVR is an user-friendly and intuitive environment: 11
CHAPTER 2 mikroC PRO for AVR Environment IDE OVERVIEW The mikroC PRO for AVR is an user-friendly and intuitive environment: - The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Auto Correct for common typos and Code Templates (Auto Complete). - The Code Explorer (with Keyboard shortcut browser and Quick Help browser) is at your disposal for easier project management.
mikroC PRO for AVR CHAPTER 2 Environment - Like in any modern Windows application, you may customize the layout of mikroC PRO for AVR to suit your needs best. - Spell checker underlines identifiers which are unknown to the project. In this way it helps the programmer to spot potential problems early, much before the project is compiled. Spell checker can be disabled by choosing the option in the Preferences dialog (F12).
CHAPTER 2 mikroC PRO for AVR Environment FILE MENU OPTIONS The File menu is the main entry point for manipulation with the source files. File Description Open a new editor window. Open source file for editing or image file for viewing. Reopen recently used file. Save changes for active editor. Save the active source file with the different name or change the file type. Close active source file. Print Preview. Exit IDE.
CHAPTER 2 mikroC PRO for AVR Environment EDIT MENU OPTIONS Edit Description Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard. Paste text from clipboard. Delete selected text. Select all text in active editor. Find text in active editor.
CHAPTER 2 mikroC PRO for AVR Environment Find next occurence of text in active editor. Find previous occurence of text in active editor. Replace text in active editor. Find text in current file, in all opened files, or in files from desired folder. Goto to the desired line in active editor. Advanced Code Editor options Advanced>> Description Comment selected code or put single line comment if there is no selection. Uncomment selected code or remove single line comment if there is no selection.
mikroC PRO for AVR CHAPTER 2 Environment Find Text Dialog box for searching the document for the specified text. The search is performed in the direction specified. If the string is not found a message is displayed. Replace Text Dialog box for searching for a text string in file and replacing it with another text string.
CHAPTER 2 mikroC PRO for AVR Environment Find In Files Dialog box for searching for a text string in current file, all opened files, or in files on a disk. The string to search for is specified in the Text to find field. If Search in directories option is selected, The files to search are specified in the Files mask and Path fields. Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned.
mikroC PRO for AVR CHAPTER 2 Environment Regular expressions By checking this box, you will be able to advance your search, through Regular expressions.
CHAPTER 2 mikroC PRO for AVR Environment VIEW MENU OPTIONS View Description Show/Hide toolbars. Show/Hide debug windows. Show/Hide Routine List in active editor. Show/Hide Project Settings window. Show/Hide Code Explorer window. Show/Hide Project Manager window. Show/Hide Library Manager window. Show/Hide Bookmarks window. Show/Hide Error Messages window. Show/Hide Macro Editor window. Show Window List window.
CHAPTER 2 mikroC PRO for AVR Environment TOOLBARS File Toolbar File Toolbar is a standard toolbar with following options: Icon Description Opens a new editor window. Open source file for editing or image file for viewing. Save changes for active window. Save changes in all opened windows. Close current editor. Close all editors. Print Preview. Edit Toolbar Edit Toolbar is a standard toolbar with following options: Icon Description Undo last change. Redo last change. Cut selected text to clipboard.
CHAPTER 2 mikroC PRO for AVR Environment Advanced Edit Toolbar Advanced Edit Toolbar comes with following options: Icon Description Comment selected code or put single line comment if there is no selection Uncomment selected code or remove single line comment if there is no selection. Select text from starting delimiter to ending delimiter. Go to ending delimiter. Go to line. Indent selected code lines. Outdent selected code lines.
CHAPTER 2 mikroC PRO for AVR Environment Project Toolbar Project Toolbar comes with following options: Icon Description Open new project wizard. wizard. Open Project. Save Project. Add existing project to project group. Remove existing project from project group. Add File To Project. Remove File From Project. Close current project. Build Toolbar Build Toolbar comes with following options: Icon Description Build current project. Build all opened projects. Build and program active project.
CHAPTER 2 mikroC PRO for AVR Environment Debugger Debugger Toolbar comes with following options: Icon Description Start Software Simulator. Run/Pause debugger. Stop debugger. Step into. Step over. Step out. Run to cursor. Toggle breakpoint. Toggle breakpoints. Clear breakpoints.
CHAPTER 2 mikroC PRO for AVR Environment Styles Toolbar Styles toolbar allows you to easily customize your workspace. Tools Toolbar Tools Toolbar comes with following default options: Icon Description Run USART Terminal EEPROM ASCII Chart Seven segment decoder tool. The Tools toolbar can easily be customized by adding new tools in Options(F12) window.
CHAPTER 2 mikroC PRO for AVR Environment PROJECT MENU OPTIONS 26 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 2 mikroC PRO for AVR Environment Project Description Build active project. Build all projects. Build and program active project. View Assembly. Edit search paths. Clean Project Folder Add file to project. Remove file from project. Open New Project Wizard Open existing project. Save current project. Open project group. Close project group. Save active project file with the different name. Open recently used project. Close active project.
CHAPTER 2 mikroC PRO for AVR Environment RUN MENU OPTIONS 28 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 2 mikroC PRO for AVR Environment Run Description Start Software Simulator. Stop debugger. Pause Debugger. Step Into. Step Over. Step Out. Jump to interrupt in current project. Toggle Breakpoint. Breakpoints. Clear Breakpoints. Show/Hide Watch Window Show/Hide Stopwatch Window Toggle between C source and disassembly.
CHAPTER 2 mikroC PRO for AVR Environment TOOLS MENU OPTIONS Tools Description Run mikroElektronika Programmer Run USART Terminal Run EEPROM Editor Run ASCII Chart Run 7 Segment Display Decoder Generate HTML code suitable for publishing source code on the web. Generate your own custom LCD characters Generate bitmap pictures for GLCD UDP communication terminal.
CHAPTER 2 mikroC PRO for AVR Environment HELP MENU OPTIONS Help Description Îpen Help File. Quick Help. Check if new compiler version is available. Open mikroElektronika Support Forums in a default browser. Open mikroElektronika Web Page in a default browser. Information on how to register. Open About window.
CHAPTER 2 mikroC PRO for AVR Environment KEYBOARD SHORTCUTS Below is a complete list of keyboard shortcuts available in mikroC PRO for AVR IDE. You can also view keyboard shortcuts in the Code Explorer window, tab Keyboard.
CHAPTER 2 mikroC PRO for AVR Environment Ctrl+X Cut Ctrl+Y Delete entire line Ctrl+Z Undo Ctrl+Shift+Z Redo Advanced Editor Shortcuts Ctrl+Space Code Assistant Ctrl+Shift+Space Parameters Assistant Ctrl+D Find declaration Ctrl+E Incremental Search Ctrl+L Routine List Ctrl+G Goto line Ctrl+J Insert Code Template Ctrl+Shift+.
CHAPTER 2 mikroC PRO for AVR Environment Software Simulator Shortcuts 34 F2 Jump To Interrupt F4 Run to Cursor F5 Toggle Breakpoint F6 Run/Pause Debugger F7 Step into F8 Step over F9 Debug Ctrl+F2 Reset Ctrl+F5 Add to Watch List Ctrl+F8 Step out Alt+D Dissasembly view Shift+F5 Open Watch Window MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
mikroC PRO for AVR CHAPTER 2 Environment MIKROC PRO FOR AVR IDE IDE Overview The mikroC PRO for AVR is an user-friendly and intuitive environment: - The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Auto Correct for common typos and Code Templates (Auto Complete). - The Code Explorer (with Keyboard shortcut browser and Quick Help browser) is at your disposal for easier project management. - The Project Manager alows multiple project management.
CHAPTER 2 Environment mikroC PRO for AVR - The New Project Wizard is a fast, reliable, and easy way to create a project. - Help files are syntax and context sensitive. - Like in any modern Windows application, you may customize the layout of mikroC PRO for AVR to suit your needs best. - Spell checker underlines identifiers which are unknown to the project. In this way it helps the programmer to spot potential problems early, much before the project is compiled.
mikroC PRO for AVR CHAPTER 2 Environment CUSTOMIZING IDE LAYOUT Docking Windows You can increase the viewing and editing space for code, depending on how you arrange the windows in the IDE. Step 1: Click the window you want to dock, to give it focus. Step 2: Drag the tool window from its current location. A guide diamond appears. The four arrows of the diamond point towards the four edges of the IDE.
CHAPTER 2 mikroC PRO for AVR Environment Step 3: Move the pointer over the corresponding portion of the guide diamond. An outline of the window appears in the designated area. Step 4: To dock the window in the position indicated, release the mouse button. Tip: To move a dockable window without snapping it into place, press CTRL while dragging it. Saving Layout Once you have a window layout that you like, you can save the layout by typing the name for the layout and pressing the Save Layout Icon .
CHAPTER 2 mikroC PRO for AVR Environment Auto Hide Auto Hide enables you to see more of your code at one time by minimizing tool windows along the edges of the IDE when not in use. -Click the window you want to keep visible to give it focus. -Click the Pushpin Icon on the title bar of the window. When an auto-hidden window loses focus, it automatically slides back to its tab on the edge of the IDE. While a window is auto-hidden, its name and icon are visible on a tab at the edge of the IDE.
CHAPTER 2 mikroC PRO for AVR Environment ADVANCED CODE EDITOR The Code Editor is advanced text editor fashioned to satisfy needs of professionals. General code editing is the same as working with any standard text-editor, including familiar Copy, Paste and Undo actions, common for Windows environment.
mikroC PRO for AVR CHAPTER 2 Environment Code Assistant If you type the first few letters of a word and then press Ctrl+Space, all valid identifiers matching the letters you have typed will be prompted in a floating panel (see the image below). Now you can keep typing to narrow the choice, or you can select one from the list using the keyboard arrows and Enter.
CHAPTER 2 mikroC PRO for AVR Environment Code Folding Code folding is IDE feature which allows users to selectively hide and display sections of a source file. In this way it is easier to manage large regions of code within one window, while still viewing only those subsections of the code that are relevant during a particular editing session. While typing, the code folding symbols ( and ) appear automatically. Use the folding symbols to hide/unhide the code subsections.
CHAPTER 2 mikroC PRO for AVR Environment Parameter Assistant The Parameter Assistant will be automatically invoked when you open parenthesis “(” or press Shift+Ctrl+Space. If the name of a valid function precedes the parenthesis, then the expected parameters will be displayed in a floating panel. As you type the actual parameter, the next expected parameter will become bold.
CHAPTER 2 mikroC PRO for AVR Environment Also, the Code Editor has a feature to comment or uncomment the selected code by simple click of a mouse, using the Comment Icon and Uncomment Icon from the Code Toolbar. Spell Checker The Spell Checker underlines unknown objects in the code, so they can be easily noticed and corrected before compiling your project. Select Tools › Options from the drop-down menu, or click the Show Options Icon and then select the Spell Checker Tab.
CHAPTER 2 mikroC PRO for AVR Environment CODE EXPLORER The Code Explorer gives clear view of each item declared inside the source code. You can jump to a declaration of any item by right clicking it. Also, besides the list of defined and declared objects, code explorer displays message about first error and it's location in code. Following options are available in the Code Explorer: Icon Description Expand/Collapse all nodes in tree. Locate declaration in code.
CHAPTER 2 mikroC PRO for AVR Environment ROUTINE LIST Routine list diplays list of routines, and enables filtering routines by name. Routine list window can be accessed by pressing Ctrl+L. You can jump to a desired routine by double clicking on it.
mikroC PRO for AVR CHAPTER 2 Environment PROJECT MANAGER Project Manager is IDE feature which allows users to manage multiple projects. Several projects which together make project group may be open at the same time. Only one of them may be active at the moment. Setting project in active mode is performed by double click on the desired project in the Project Manager.
CHAPTER 2 mikroC PRO for AVR Environment Icon Description Save project Group. Open project group. Close the active project. Close project group. Add project to the project group. Remove project from the project group. Add file to the active project. Remove selected file from the project. Build the active project. Run mikroElektronika's Flash programmer. For details about adding and removing files from project see Add/Remove Files from Project.
CHAPTER 2 mikroC PRO for AVR Environment PROJECT SETTINGS WINDOW Following options are available in the Project Settings Window: - Device - select the appropriate device from the device drop-down list. - Oscillator - enter the oscillator frequency value.
CHAPTER 2 mikroC PRO for AVR Environment LIBRARY MANAGER Library Manager enables simple handling libraries being used in a project. Library Manager window lists all libraries (extencion .mcl) which are instantly stored in the compiler Uses folder. The desirable library is added to the project by selecting check box next to the library name. In order to have all library functions accessible, simply press the button Check All and all libraries will be selected.
CHAPTER 2 mikroC PRO for AVR Icon Environment Description Refresh Library by scanning files in "Uses" folder.Useful when new libraries are added by copying files to "Uses" folder. Rebuild all available libraries. Useful when library sources are available and need refreshing. Include all available libraries in current project. No libraries from the list will be included in current project. Restore library to the state just before last project saving.
CHAPTER 2 mikroC PRO for AVR Environment ERROR WINDOW In case that errors were encountered during compiling, the compiler will report them and won’t generate a hex file. The Error Window will be prompted at the bottom of the main window by default. The Error Window is located under message tab, and displays location and type of errors the compiler has encountered. The compiler also reports warnings, but these do not affect the output; only errors can interefere with the generation of hex.
CHAPTER 2 mikroC PRO for AVR Environment STATISTICS After successful compilation, you can review statistics of your code. Click the Statistics Icon . Memory Usage Windows Provides overview of RAM and ROM usage in the form of histogram. RAM Memory Rx Memory Space Displays Rx memory space usage in form of histogram.
CHAPTER 2 mikroC PRO for AVR Environment Data Memory Space Displays Data memory space usage in form of histogram. Special Function Registers Summarizes all Special Function Registers and their addresses.
mikroC PRO for AVR CHAPTER 2 Environment General Purpose Registers Summarizes all General Purpose Registers and their addresses. Also displays symbolic names of variables and their addresses. ROM Memory ROM Memory Usage Displays ROM memory usage in form of histogram.
CHAPTER 2 mikroC PRO for AVR Environment ROM Memory Allocation Displays ROM memory allocation. Procedures Windows Provides overview procedures locations and sizes.
mikroC PRO for AVR CHAPTER 2 Environment Procedures Size Window Displays size of each procedure. Procedures Locations Window Displays how functions are distributed in microcontroller’s memory.
CHAPTER 2 mikroC PRO for AVR Environment HTML Window Display statistics in default web browser.
CHAPTER 2 mikroC PRO for AVR Environment MACRO EDITOR A macro is a series of keystrokes that have been 'recorded' in the order performed. A macro allows you to 'record' a series of keystrokes and then 'playback', or repeat, the recorded keystrokes. The Macro offers the following commands: Icon Description Starts 'recording' keystrokes for later playback. Stops capturing keystrokesthat was started when the Start Recordig command was selected. Allows a macro that has been recorded to be replayed.
CHAPTER 2 mikroC PRO for AVR Environment INTEGRATED TOOLS USART Terminal The mikroC PRO for AVR includes the USART communication terminal for RS232 communication. You can launch it from the drop-down menu Tools › USART Terminal or by clicking the USART Terminal Icon 60 from Tools toolbar.
CHAPTER 2 mikroC PRO for AVR Environment ASCII Chart The ASCII Chart is a handy tool, particularly useful when working with LCD display. You can launch it from the drop-down menu Tools › ASCII chart or by clicking the View ASCII Chart Icon from Tools toolbar.
CHAPTER 2 mikroC PRO for AVR Environment EEPROM Editor The EEPROM Editor is used for manipulating MCU's EEPROM memory. You can launch it from the drop-down menu Tools › EEPROM Editor. When Use this EEPROM definition is checked compiler will generate Intel hex file project_name.ihex that contains data from EEPROM editor. When you run mikroElektronika programmer software from mikroC PRO for AVR IDE - project_name.hex file will be loaded automatically while ihex file must be loaded manually.
CHAPTER 2 mikroC PRO for AVR Environment 7 Segment Display Decoder The 7 Segment Display Decoder is a convenient visual panel which returns decimal/hex value for any viable combination you would like to display on 7seg. Click on the parts of 7 segment image to get the requested value in the edit boxes. You can launch it from the drop-down menu Tools › 7 Segment Decoderor by clicking the Seven Segment Icon from Tools toolbar.
CHAPTER 2 mikroC PRO for AVR Environment UDP Terminal The mikroC PRO for AVR includes the UDP Terminal. You can launch it from the drop-down menu Tools › UDP Terminal.
mikroC PRO for AVR CHAPTER 2 Environment Graphic LCD Bitmap Editor The mikroC PRO for AVR includes the Graphic LCD Bitmap Editor. Output is the mikroC PRO for AVR compatible code. You can launch it from the drop-down menu Tools › GLCD Bitmap Editor.
CHAPTER 2 mikroC PRO for AVR Environment LCD Custom Character mikroC PRO for AVR includes the LCD Custom Character. Output is mikroC PRO for AVR compatible code. You can launch it from the drop-down menu Tools › LCD Custom Character.
mikroC PRO for AVR CHAPTER 2 Environment OPTIONS Options menu consists of three tabs: Code Editor, Tools and Output settings Code editor The Code Editor is advanced text editor fashioned to satisfy needs of professionals. Tools The mikroC PRO for AVR includes the Tools tab, which enables the use of shortcuts to external programs, like Calculator or Notepad. You can set up to 10 different shortcuts, by editing Tool0 - Tool9.
CHAPTER 2 mikroC PRO for AVR Environment Output settings By modifying Output Settings, user can configure the content of the output files. You can enable or disable, for example, generation of ASM and List file. Also, user can choose optimization level, and compiler specific settings, which include case sensitivity, dynamic link for string literals setting (described in mikroC PRO for AVR specifics). Build all files as library enables user to use compiled library (*.mcl) on any AVR MCU.
CHAPTER 2 mikroC PRO for AVR Environment REGULAR EXPRESSIONS Introduction Regular Expressions are a widely-used method of specifying patterns of text to search for. Special metacharacters allow you to specify, for instance, that a particular string you are looking for, occurs at the beginning, or end of a line, or contains n recurrences of a certain character. Simple matches Any single character matches itself, unless it is a metacharacter with a special meaning described below.
CHAPTER 2 mikroC PRO for AVR Environment Examples: unsigned\x20int matches 'unsigned int' (note space in the middle) \tunsigned matches 'unsigned' (predecessed by tab) Character classes You can specify a character class, by enclosing a list of characters in [], which will match any of the characters from the list. If the first character after the "[" is "^", the class matches any character not in the list. Examples: count[aeiou]r finds strings 'countar', 'counter', etc.
CHAPTER 2 mikroC PRO for AVR Environment Metacharacters - Line separators ^ - start of line $ - end of line \A - start of text \Z - end of text . - any character in line Examples: ^PORTA - matches string ' PORTA ' only if it's at the beginning of line PORTA$ - matches string ' PORTA ' only if it's at the end of line ^PORTA$ - matches string ' PORTA ' only if it's the only string in line PORT.
CHAPTER 2 mikroC PRO for AVR Environment Metacharacters - Word boundaries A word boundary ("\b") is a spot between two characters that has a "\w" on one side of it and a "\W" on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a "\W". \b - match a word boundary) \B - match a non-(word boundary) Metacharacters - Iterators Any item of a regular expression may be followed by another type of metacharacters - iterators.
CHAPTER 2 mikroC PRO for AVR Environment counte{2}r - matches string 'counteer' counte{2,}r - matches strings like 'counteer', 'counteeer', 'counteeer' etc. counte{2,3}r - matches strings like 'counteer', or 'counteeer' but not 'counteeeer' A little explanation about "greediness". "Greedy" takes as many as possible, "nongreedy" takes as few as possible.
CHAPTER 2 mikroC PRO for AVR Environment Metacharacters - Subexpressions The bracketing construct ( ... ) may also be used for define regular subexpressions. Subexpressions are numbered based on the left to right order of their opening parenthesis. First subexpression has number '1' Examples: (int){8,10} matches strings which contain 8, 9 or 10 instances of the 'int' routi([0-9]|a+)e matches 'routi0e', 'routi1e' , 'routine', 'routinne', 'routinnne' etc.
CHAPTER 2 mikroC PRO for AVR Environment MIKROC PRO FOR AVR COMMAND LINE OPTIONS Usage: mikroCAvr.exe [- [-]] ]] Infile can be of *.c and *.pld type. [ [-]] [- The following parameters and some more (see manual) are valid: -P : MCU for which compilation will be done. -FO : Set oscillator [in MHz]. -SP : Add directory to the search path list. -IP : Add directory to the #include search list. -N : Output files generated to file path specified by filename.
CHAPTER 2 mikroC PRO for AVR Environment TUTORIALS Projects The mikroC PRO for AVR organizes applications into projects, consisting of a single project file (extension .mcpav) and one or more source files (extension ). mikroC PRO for AVR IDE allows you to manage multiple projects (see Project Manager). Source files can be compiled only if they are part of a project.
mikroC PRO for AVR CHAPTER 2 Environment New Project Wizard Steps Start creating your New project, by clicking Next button: Step One - Select the device from the device drop-down list.
CHAPTER 2 mikroC PRO for AVR Environment Step Two - Enter the oscillator frequency value. Step Three - Specify the location where your project will be saved.
mikroC PRO for AVR CHAPTER 2 Environment Step Four - Add project file to the project if they are avaiable at this point. You can always add project files later using Project Manager.
CHAPTER 2 mikroC PRO for AVR Environment CUSTOMIZING PROJECTS Edit Project You can change basic project settings in the Project Settings window. You can change chip, and oscillator frequency. Any change in the Project Setting Window affects currently active project only, so in case more than one project is open, you have to ensure that exactly the desired project is set as active one in the Project Manager.
mikroC PRO for AVR CHAPTER 2 Environment The list of relevant source files is stored in the project file (extension .mcpav). To add source file to the project, click the Add File to Project Icon . Each added source file must be self-contained, i.e. it must have all necessary definitions after preprocessing. To remove file(s) from the project, click the Remove File from Project Icon MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD .
CHAPTER 2 mikroC PRO for AVR Environment Project Level Defines: Project Level Defines(.pld) files can also be added to project. Project level define files enable you to have defines that are visible in all source files in the project. A file must contain one definition per line in the following form: [=[]] [=[]] Define a macro named symbol. To specify a value, use =. If = is omitted, 1 is assumed.
CHAPTER 2 mikroC PRO for AVR Environment SOURCE FILES Source files containing C code should have the extension . The list of source files relevant to the application is stored in project file with extension .mcpav, along with other project information. You can compile source files only if they are part of the project. Use the preprocessor directive #include to include header files with the extension .h.
CHAPTER 2 mikroC PRO for AVR Environment Printing an open file 1. Make sure that the window containing the file that you want to print is the active window. 2. Select File › Print from the drop-down menu, or press Ctrl+P. 3. In the Print Preview Window, set a desired layout of the document and click the OK button. The file will be printed on the selected printer. Saving file 1. Make sure that the window containing the file that you want to save is the active window. 2.
mikroC PRO for AVR CHAPTER 2 Environment CLEAN PROJECT FOLDER Clean Project Folder This menu gives you option to choose which files from your current project you want to delete.
CHAPTER 2 mikroC PRO for AVR Environment COMPILATION When you have created the project and written the source code, it's time to compile it. Select Project › Build from the drop-down menu, or click the Build Icon from the Project Toolbar. If more more than one project is open you can compile all open projects by selecting Project › Build All from the drop-down menu, or click the Build All Icon from the Project Toolbar. Progress bar will appear to inform you about the status of compiling.
CHAPTER 2 mikroC PRO for AVR Environment ERROR MESSAGES Compiler Error Messages - Syntax Error: [%s] expected, but [%s] found - Array element cannot be function - Function cannot return array - Inconsistent storage class - Inconsistent type - [%s] tag redefined [%s] - Illegal typecast [%s] [%s] - [%s] is not valid identifier - Invalid statement - Constant expression required - Internal error [%s] - Too many actual parameters - Not enough parameters - Invalid expression - Identifier expected, but [%s] fou
CHAPTER 2 mikroC PRO for AVR Environment - Division by zero - Incompatible types: [%s] [%s] - Too many characters. - Assembler instruction [%s] was not found. - project name must be specified - Unknown command line Option: [%s] - File extension missing: [%s] - Bad FO argument: [%s] - Preprocessor exited with error code [%s] - Bad absolute address [%s] - Recursion or cross-calling of [%s] - no files specified - Device parameter missing (for example -PATMEGA...
mikroC PRO for AVR CHAPTER 2 Environment - [%s] already used - ILevel can be used only with interrupt service routines - ; expected, but [%s] found - Expected ''{'' - [%s] Identifier redefined - '(' expected, but [%s] found - ')' expected, but [%s] found - 'case' out of switch - ':' expected, but [%s] found - 'default' label out of switch - switch expression must evaluate to integral type - while expected, but [%s] found - void func cannot return values - 'continue' outside of loop - Unreachable code - La
CHAPTER 2 mikroC PRO for AVR Environment Compiler Warning Messages - Bad or missing fosc parameter.
CHAPTER 2 mikroC PRO for AVR Environment SOFTWARE SIMULATOR OVERVIEW The Source-level Software Simulator is an integral component of the mikroC PRO for AVR environment. It is designed to simulate operations of the AVR MCUs and assist the users in debugging C code written for these devices. After you have successfully compiled your project, you can run the Software Simulator by selecting Run › Start Debugger from the drop-down menu, or by clicking the Start Debugger Icon from the Debugger Toolbar.
CHAPTER 2 mikroC PRO for AVR Environment Add All Button Remove All Button adds all variables. removes all variables. You can also expand/collapse complex variables, i.e. struct type variables, strings... Values are updated as you go through the simulation. Recently changed items are colored red.
mikroC PRO for AVR CHAPTER 2 Environment Double clicking a variable or clicking the Properties Button opens the Edit Value window in which you can assign a new value to the selected variable/register. Also, you can choose the format of variable/register representation between decimal, hexadecimal, binary, float or character. All representations except float are unsigned by default. For signed representation click the check box next to the Signed label.
CHAPTER 2 mikroC PRO for AVR Environment RAM Window The Software Simulator RAM Window is available from the drop-down menu, View › Debug Windows › RAM. The RAM Window displays a map of MCU’s RAM, with recently changed items colored red. You can change value of any field by double-clicking it.
CHAPTER 2 mikroC PRO for AVR Environment SOFTWARE SIMULATOR OPTIONS Name Description Function Key Start Debugger Start Software Simulator. [F9] Run/Pause Debugger Run or pause Software Simulator. [F6] Stop Debugger Stop Software Simulator. Toggle Breakpoints Toggle breakpoint at the current cursor position. To view all breakpoints, select Run > View Breakpoints from the drop–down menu. Double clicking an item in the Breakpoints Window List locates the breakpoint.
CHAPTER 2 mikroC PRO for AVR Environment CREATING NEW LIBRARY mikroC PRO for AVR allows you to create your own libraries. In order to create a library in mikroC PRO for AVR follow the steps bellow: 1. Create a new C source file, see Managing Source Files 2. Save the file in the compiler's Uses folder: DriveName:\ProgramFiles\Mikroelektronika\mikroC PRO for AVR\Uses\__Lib_Example 3. Write a code for your library and save it. 4. Add __Lib_Example file in some project, see Project Manager.
CHAPTER mikroC PRO for AVR Specifics 3 The following topics cover the specifics of mikroC PRO for AVR compiler: - ANSI Standard Issues - Predefined Globals and Constants - Accessing Individual Bits - Interrupts - AVR Pointers - Linker Directives - Built-in Routines - Code Optimization - Memory Type Specifiers 97
CHAPTER 3 mikroC PRO for AVR Specifics Notes: - Directive absolute in Rx memory space guarantees only that defined variable will be overlapped with the given memory address. - Addresses of all registers are RAM Space addresses. RAM Space is continuous region of RAM memory including all AVR RAM memory spaces (RAM space = Rx Space + IO Space + SRAM Space). When using instructions dedicated to IO Space in asm blocks, IO registers should be accessed by their RAM Space addresses.
CHAPTER 3 mikroC PRO for AVR Specifics PREDEFINED GLOBALS AND CONSTANTS To facilitate programming of AVR compliant MCUs, the mikroC PRO for AVR implements a number of predefined globals and constants. All AVR SFR registers and their bits are implicitly declared as global variables. These identifiers have an external linkage, and are visible in the entire project.
CHAPTER 3 mikroC PRO for AVR Specifics ACCESSING INDIVIDUAL BITS The mikroC PRO for AVR allows you to access individual bits of 8-bit variables. It also supports sbit and bit data types Accessing Individual Bits Of Variables If you are familiar with a particular MCU, you can access bits by name: // Clear bit 0 on PORTA PORTA0_bit = 0; Also, you can simply use the direct member selector (.
CHAPTER 3 mikroC PRO for AVR Specifics bit type The mikroC PRO Compiler provides a bit data type that may be used for variable declarations. It can not be used for argument lists, and function-return values. bit bf; // bit variable There are no pointers to bit variables: bit *ptr; // invalid An array of type bit is not valid: bit arr [5]; // invalid Note : - Bit variables can not be initialized. - Bit variables can not be members of structures and unions.
CHAPTER 3 mikroC PRO for AVR Specifics INTERRUPTS AVR derivates acknowledges an interrupt request by executing a hardware generated CALL to the appropriate servicing routine ISRs. ISRs are organized in IVT. ISR is defined as a standard function but with the org directive afterwards which connects the function with specific interrupt vector. For example org 0x000B is IVT address of Timer/Counter 2 Overflow interrupt source of the ATMEGA16.
mikroC PRO for AVR CHAPTER 3 Specifics Direct accessing interrupt service routine and accessing interrupt service routine via Goto table.
CHAPTER 3 mikroC PRO for AVR Specifics LINKER DIRECTIVES The mikroC PRO uses an internal algorithm to distribute objects within memory. If you need to have a variable or routine at specific predefined address, use the linker directives absolute and org. Directive absolute Directive absolute specifies the starting address in RAM for a variable. If the variable is multi-byte, higher bytes will be stored at the consecutive locations.
mikroC PRO for AVR CHAPTER 3 Specifics Directive orgal If the user wants to place its routines, constants, etc, above a specified address in ROM, #pragma orgall directive should be used: #pragma orgall 0x200 This doesn't apply to IVT, Handler table and Goto table.
CHAPTER 3 mikroC PRO for AVR Specifics BUILT-IN ROUTINES The mikroC PRO for AVR compiler provides a set of useful built-in utility functions. The Lo, Hi, Higher, Highest routines are implemented as macros. If you want to use these functions you must include built_in.h header file (located in the inlclude folder of the compiler) into your project. The Delay_us and Delay_ms routines are implemented as “inline”; i.e.
CHAPTER 3 mikroC PRO for AVR Specifics Hi Prototype unsigned short Hi(long number); Returns Returns next to the lowest byte of number, bits 8..15. Function returns next to the lowest byte of number. Function does not interpret bit patterns of number – it merely returns 8 bits as found in register. Description This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Requires Arguments must be variable of scalar type (i.e.
CHAPTER 3 mikroC PRO for AVR Specifics Delay_us Prototype void Delay_us(const unsigned long time_in_us); Returns Nothing. Creates a software delay in duration of time_in_us microseconds (a constant). Range of applicable constants depends on the oscillator frequency. Description This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Requires Nothing.
CHAPTER 3 mikroC PRO for AVR Specifics Delay_Cyc Prototype void Delay_Cyc(char Cycles_div_by_10); Returns Nothing. Creates a delay based on MCU clock. Delay lasts for 10 times the input parameter in MCU cycles. Description Note that Delay_Cyc is library function rather than a built-in routine; it is presented in this topic for the sake of convenience. There are limitations for Cycles_div_by_10 value. Value Cycles_div_by_10 must be between 2 and 257 Requires Nothing.
CHAPTER 3 mikroC PRO for AVR Specifics Get_Fosc_kHz Prototype unsigned long Get_Fosc_kHz(void); Returns Device clock in kHz, rounded to the nearest integer. Function returns device clock in kHz, rounded to the nearest integer. Description Note that Get_Fosc_kHz is library function rather than a built-in routine; it is presented in this topic for the sake of convenience. Requires Nothing.
mikroC PRO for AVR CHAPTER 3 Specifics Stack allocation Temporary registers ("Stacks") are being used more rationally, allowing VERY complex expressions to be evaluated with a minimum stack consumption. Local vars optimization No local variables are being used if their result does not affect some of the global or volatile variables.
CHAPTER 3 Specifics 112 mikroC PRO for AVR MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 4 AVR Specifics Types Efficiency First of all, you should know that AVR ALU, which performs arithmetic operations, is optimized for working with bytes. Although mikroC PRO is capable of handling very complex data types, AVR may choke on them, especially if you are working on some of the older models. This can dramatically increase the time needed for performing even simple operations. Universal advice is to use the smallest possible type in every situation.
CHAPTER 4 mikroC PRO for AVR AVR Specifics Nested Calls Limitations There are no Nested Calls Limitations, except by RAM size. A Nested call represents a function call to another function within the function body. With each function call, the stack increases for the size of the returned address. Number of nested calls is equel to the capacity of RAM which is left out after allocation of all variables.
mikroC PRO for AVR CHAPTER 4 AVR Specifics AVR MEMORY ORGANIZATION The AVR microcontroller's memory is divided into Program Memory and Data Memory. Program Memory (ROM) is used for permanent saving program being executed, while Data Memory (RAM) is used for temporarily storing and keeping intermediate results and variables.
CHAPTER 4 mikroC PRO for AVR AVR Specifics Data Memory Data memory consists of : - Rx space I/O Memory Extended I/O Memory (MCU dependent) Internal SRAM Rx space consists of 32 general purpose working 8-bit registers (R0-R31). These registers have the shortest (fastest) access time, which allows single-cycle Arithmetic Logic Unit (ALU) operation. I/O Memory space contains addresses for CPU peripheral function, such as Control registers, SPI, and other I/O functions.
mikroC PRO for AVR CHAPTER 4 AVR Specifics MEMORY TYPE SPECIFIERS The mikroC PRO for AVR supports usage of all memory areas. Each variable may be explicitly assigned to a specific memory space by including a memory type specifier in the declaration, or implicitly assigned. The following memory type specifiers can be used: - code data rx io sfr Memory type specifiers can be included in variable declaration.
CHAPTER 4 mikroC PRO for AVR AVR Specifics rx This memory specifier allows variable to be stored in the Rx space (Register file). Description Note: In most of the cases, there will be enough space left for the user variables in the Rx space. However, since compiler uses Rx space for storing temporary variables, it might happen that user variables will be stored in the internal data SRAM, when writing complex programs.
CHAPTER 5 mikroC PRO for AVR Language Reference The mikroC PRO for AVR Language Reference describes the syntax, semantics and implementation of the mikroC PRO for AVR language. The aim of this reference guide is to provide a more understandable description of the mikroC PRO for AVR language to the user.
CHAPTER 5 mikroC PRO for AVR Language Reference MIKROC PRO FOR AVR LANGUAGE REFERENCE Lexical Elements Whitespace Comments Tokens Constants Constants Overview Integer Constants Floating Point Constants Character Constants String Constants Enumeration Constants Pointer Constants Constant Expressions Keywords Identifiers Punctuators Concepts Objects and Lvalues Scope and Visibility Name Spaces Duration Types Fundamental Types Arithmetic Types Enumerations Void Type Derived Types Arrays Pointers Introduction
CHAPTER 5 mikroC PRO for AVR Language Reference Linkage Storage Classes Type Qualifiers Typedef Specifier ASM Declaration Initialization Functions Introduction to Functions Function Calls and Argument Conversion Operators Introduction to Operators Operators Precedence and Associativity Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Conditional Operator Assignment Operators Sizeof Operator Expressions Introduction to Expressions Comma Expressions Statements Introduction Label
CHAPTER 5 Language Reference mikroC PRO for AVR LEXICAL ELEMENTS OVERVIEW The following topics provide a formal definition of the mikroC PRO for AVR lexical elements. They describe different categories of word-like units (tokens) recognized by the mikroC PRO for AVR. In the tokenizing phase of compilation, the source code file is parsed (that is, broken down) into tokens and whitespace.
CHAPTER 5 mikroC PRO for AVR char name [ ] = "mikro foo" ; Language Reference /* just one token here! */ Line Splicing with Backslash (\) A special case occurs if a line ends with a backslash (\). Both backslash and new line character are discarded, allowing two physical lines of a text to be treated as one unit. So, the following code "mikroC PRO \ Compiler" parses into "mikroC PRO Compiler". Refer to String Constants for more information.
CHAPTER 5 mikroC PRO for AVR Language Reference Note that the mikroC PRO for AVR does not support a nonportable token pasting strategy using /**/. For more information on token pasting, refer to the Preprocessor Operators. C++ comments The mikroC PRO for AVR allows single-line comments using two adjacent slashes (//). The comment can start in any position and extends until the next new line.
CHAPTER 5 mikroC PRO for AVR Language Reference TOKENS Token is the smallest element of a C program that compiler can recognize. The parser separates tokens from the input stream by creating the longest token possible using the input characters in a left–to–right scan. The mikroC PRO for AVR recognizes the following kinds of tokens: - keywords identifiers constants operators punctuators (also known as separators) Tokens can be concatenated (pasted) by means of the preprocessor operator ##.
CHAPTER 5 mikroC PRO for AVR Language Reference CONSTANTS Constants or literals are tokens representing fixed numeric or character values. The mikroC PRO for AVR supports: - integer constants floating point constants character constants string constants (strings literals) enumeration constants The data type of a constant is deduced by the compiler using such clues as a numeric value and format used in the source code.
CHAPTER 5 mikroC PRO for AVR Language Reference INTEGER CONSTANTS Integer constants can be decimal (base 10), hexadecimal (base 16), binary (base 2), or octal (base 8). In the absence of any overriding suffixes, the data type of an integer constant is derived from its value. Long and Unsigned Suffixes The suffix L (orl) attached to any constant forces that constant to be represented as a long. Similarly, the suffix U (or u) forces a constant to be unsigned.
CHAPTER 5 mikroC PRO for AVR Language Reference Value Assigned to Constant Assumed Type < -2147483648 Error: Out of range! -2147483648 – -32769 long -32768 – -129 int -128 – 127 short 128 – 255 unsigned short 256 – 32767 int 32768 – 65535 unsigned int 65536 – 2147483647 long 2147483648 – 4294967295 unsigned long > 4294967295 Error: Out of range! Hexadecimal All constants starting with 0x (or 0X) are taken to be hexadecimal.
CHAPTER 5 mikroC PRO for AVR Language Reference FLOATING POINT CONSTANTS A floating-point constant consists of: - Decimal integer - Decimal point - Decimal fraction - e or E and a signed integer exponent (optional) - Type suffix: f or F or l or L (optional) Either decimal integer or decimal fraction (but not both) can be omitted. Either decimal point or letter e (or E) with a signed integer exponent (but not both) can be omitted. These rules allow conventional and scientific (exponent) notations.
CHAPTER 5 Language Reference mikroC PRO for AVR CHARACTER CONSTANTS A character constant is one or more characters enclosed in single quotes, such as 'A', '+', or '\n'. In the mikroC PRO for AVR, single-character constants are of the unsigned int type. Multi-character constants are referred to as string constants or string literals. For more information refer to String Constants.
CHAPTER 5 mikroC PRO for AVR Language Reference Sequence Value Char What it does \a 0x07 BEL Audible bell \b 0x08 BS Backspace \f 0x0C FF Formfeed \n 0x0A LF Newline (Linefeed) \r 0x0D CR Carriage Return \t 0x09 HT Tab (horizontal) \v 0x0B VT Vertical Tab \\ 0x5C / Backslash \' 0x27 ' Single quote (Apostrophe) \" 0x22 " Double quote \? 0x3F ? Question mark \O any O = string of up to 3 octal digits \xH any H = string of hex digits \XH any H = string
CHAPTER 5 mikroC PRO for AVR Language Reference STRING CONSTANTS String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: "This is a string." The null string, or empty string, is written like "". A literal string is stored internally as a given sequence of characters plus a final null character. A null string is stored as a single null character.
mikroC PRO for AVR CHAPTER 5 Language Reference ENUMERATION CONSTANTS Enumeration constants are identifiers defined in enum type declarations. The identifiers are usually chosen as mnemonics to contribute to legibility. Enumeration constants are of int type. They can be used in any expression where integer constants are valid. For example: enum weekdays { SUN = 0, MON, TUE, WED, THU, FRI, SAT }; The identifiers (enumerators) used must be unique within the scope of the enum declaration.
CHAPTER 5 mikroC PRO for AVR Language Reference Pointer Constants A pointer or pointed-at object can be declared with the const modifier. Anything declared as const cannot change its value. It is also illegal to create a pointer that might violate a non-assignability of the constant object.
CHAPTER 5 mikroC PRO for AVR Language Reference CONSTANT EXPRESSIONS A constant expressions can be evaluated during translation rather that runtime and accordingly may be used in any place that a constant may be. Constant expressions can consist only of the following: - literals, enumeration constants, simple constants (no constant arrays or structures), sizeof operators.
CHAPTER 5 mikroC PRO for AVR Language Reference KEYWORDS Keywords are words reserved for special purposes and must not be used as normal identifier names. Beside standard C keywords, all relevant SFR are defined as global variables and represent reserved words that cannot be redefined (for example: TMR0, PCL, etc). Probe the Code Assistant for specific letters (Ctrl+Space in Editor) or refer to Predefined Globals and Constants.
CHAPTER 5 mikroC PRO for AVR Language Reference IDENTIFIERS Identifiers are arbitrary names of any length given to functions, variables, symbolic constants, user-defined data types, and labels. All these program elements will be referred to as objects throughout the help (don't get confused with the meaning of object in object-oriented programming). Identifiers can contain the letters a to z and A to Z, underscore character “_”, and digits 0 to 9.
CHAPTER 5 mikroC PRO for AVR Language Reference PUNCTUATORS The mikroC PRO for AVR punctuators (also known as separators) are: [ ] – Brackets ( ) – Parentheses { } – Braces , – Comma ; – Semicolon : – Colon * – Asterisk = – Equal sign # – Pound sign Most of these punctuators also function as operators.
CHAPTER 5 mikroC PRO for AVR Language Reference Braces Braces { } indicate the start and end of a compound statement: if (d == z) { ++x; func(); } Closing brace serves as a terminator for the compound statement, so a semicolon is not required after }, except in structure declarations. Sometimes, the semicolon can be illegal, as in if (statement) { ... }; else { ... }; /* illegal semicolon! */ For more information, refer to the Compound Statements.
CHAPTER 5 mikroC PRO for AVR Language Reference Semicolons are sometimes used to create an empty statement: for (i = 0; i < n; i++) ; For more information, see the Statements. Colon Use colon (:) to indicate the labeled statement: start: x = 0; ... goto start; Labels are discussed in the Labeled Statements.
mikroC PRO for AVR CHAPTER 5 Language Reference int a, b, c; a = b + c; For more information, see Assignment Operators. Pound Sign (Preprocessor Directive) Pound sign (#) indicates a preprocessor directive when it occurs as the first nonwhitespace character on a line. It signifies a compiler action, not necessarily associated with a code generation. See the Preprocessor Directives for more information.
CHAPTER 5 mikroC PRO for AVR Language Reference CONCEPTS This section covers some basic concepts of language, essential for understanding of how C programs work. First, we need to establish the following terms that will be used throughout the help: - Objects and lvalues Scope and Visibility Name Spaces Duration OBJECTS An object is a specific region of memory that can hold a fixed or variable value (or set of values).
CHAPTER 5 mikroC PRO for AVR Language Reference - Variables - Functions - Types - Arrays of other types - Structure, union, and enumeration tags - Structure members - Union members - Enumeration constants - Statement labels - Preprocessor macros The recursive nature of the declarator syntax allows complex declarators. You’ll probably want to use typedefs to improve legibility if constructing complex objects. Lvalues Lvalue is an object locator: an expression that designates an object.
CHAPTER 5 mikroC PRO for AVR Language Reference SCOPE AND VISIBILITY Scope The scope of an identifier is a part of the program in which the identifier can be used to access its object. There are different categories of scope: block (or local), function, function prototype, and file. These categories depend on how and where identifiers are declared.
CHAPTER 5 mikroC PRO for AVR Language Reference void f (int i) { int j; j = 3; { double j; j = 0.
CHAPTER 5 mikroC PRO for AVR Language Reference NAME SPACES Name space is a scope within which an identifier must be unique. The mikroC PRO for AVR uses four distinct categories of identifiers: 1. goto label names - must be unique within the function in which they are declared. 2. Structure, union, and enumeration tags - must be unique within the block in which they are defined. Tags declared outside of any function must be unique. 3.
mikroC PRO for AVR CHAPTER 5 Language Reference DURATION Duration, closely related to a storage class, defines a period during which the declared identifiers have real, physical objects allocated in memory. We also distinguish between compile-time and run-time objects. Variables, for instance, unlike typedefs and types, have real memory allocated during run time. There are two kinds of duration: static and local.
CHAPTER 5 mikroC PRO for AVR Language Reference void f() { /* local duration variable; init a upon every call to f */ int a = 1; /* static duration variable; init b only upon first call to f */ static int b = 1; /* checkpoint! */ a++; b++; } void main() { /* At checkpoint, f(); // a=1, b=1, f(); // a=1, b=2, f(); // a=1, b=3, // etc.
CHAPTER 5 mikroC PRO for AVR Language Reference TYPES The mikroC PRO for AVR is a strictly typed language, which means that every object, function, and expression must have a strictly defined type, known in the time of compilation. Note that the mikroC PRO for AVR works exclusively with numeric types. The type serves: - to determine the correct memory allocation required initially. - to interpret the bit patterns found in the object during subsequent access.
CHAPTER 5 mikroC PRO for AVR Language Reference FUNDAMENTAL TYPES The fudamental types represent types that cannot be divided into more basic elements, and are the model for representing elementary data on machine level. The fudamental types are sometimes referred to as unstructured types, and are used as elements in creating more complex derived or user-defined types.
CHAPTER 5 mikroC PRO for AVR Language Reference Type Size in bytes Range (unsigned) char 1 0 .. 255 signed char 1 - 128 .. 127 (signed) short (int) 1 - 128 .. 127 unsigned short (int) 1 0 .. 255 (signed) int 2 -32768 .. 32767 unsigned (int) 2 0 .. 65535 (signed) long (int) 4 -2147483648 .. 2147483647 unsigned long (int) 4 0 .. 4294967295 Floating-point Types The types float and double, together with the long double variant, are considered to be floating-point types.
CHAPTER 5 mikroC PRO for AVR Language Reference ENUMERATIONS An enumeration data type is used for representing an abstract, discreet set of values with appropriate symbolic names. Enumeration Declaration Enumeration is declared like this: enum tag {enumeration-list}; Here, tag is an optional name of the enumeration; enumeration-list is a commadelimited list of discreet values, enumerators (or enumeration constants). Each enumerator is assigned a fixed integral value.
CHAPTER 5 mikroC PRO for AVR Language Reference Initializer expression can include previously declared enumerators. For example, in the following declaration: enum memory_sizes { bit = 1, nibble = 4 * bit, byte = 2 * nibble, kilobyte = 1024 * byte }; nibble would acquire the value 4, byte the value 8, and kilobyte the value 8192.
CHAPTER 5 Language Reference mikroC PRO for AVR VOID TYPE void is a special type indicating the absence of any value. There are no objects of void; instead, void is used for deriving more complex types. Void Functions Use the void keyword as a function return type if the function does not return a value.
CHAPTER 5 mikroC PRO for AVR Language Reference DERIVED TYPES The derived types are also known as structured types. They are used as elements in creating more complex user-defined types. The derived types include: - arrays pointers structures unions ARRAYS Array is the simplest and most commonly used structured type. A variable of array type is actually an array of objects of the same type. These objects represent elements of an array and are identified by their position in array.
CHAPTER 5 mikroC PRO for AVR Language Reference Array Initialization An array can be initialized in declaration by assigning it a comma-delimited sequence of values within braces. When initializing an array in declaration, you can omit the number of elements – it will be automatically determined according to the number of elements assigned.
CHAPTER 5 mikroC PRO for AVR Language Reference A variable m is an array of 50 elements, which in turn are arrays of 20 floats each. Thus, we have a matrix of 50x20 elements: the first element is m[0][0], the last one is m[49][19]. The first element of the 5th row would be m[4][0]. If you don't initialize the array in the declaration, you can omit the first dimension of multi-dimensional array. In that case, array is located elsewhere, e.g. in another file.
CHAPTER 5 mikroC PRO for AVR Language Reference POINTERS Pointers are special objects for holding (or “pointing to”) memory addresses. In the mikroC PRO for AVR, address of an object in memory can be obtained by means of an unary operator &. To reach the pointed object, we use an indirection operator (*) on a pointer. A pointer of type “pointer to object of type” holds the address of (that is, points to) an object of type.
CHAPTER 5 mikroC PRO for AVR Language Reference int *pa, *pb, *pc; /* is same as: */ int *pa; int *pb; int *pc; Once declared, though, a pointer can usually be reassigned so that it points to an object of another type. The mikroC PRO for AVR lets you reassign pointers without typecasting, but the compiler will warn you unless the pointer was originally declared to be pointing to void. You can assign the void* pointer to the non-void* pointer – refer to void for details.
CHAPTER 5 Language Reference mikroC PRO for AVR FUNCTION POINTERS Function Pointers are pointers, i.e. variables, which point to the address of a function. // Define a function pointer int (*pt2Function) (float, char, char); Note: Thus functions and function pointers with different calling convention (argument order, arguments type or return type is different) are incompatible with each other.
CHAPTER 5 mikroC PRO for AVR Language Reference int modC(char x,char y){ return x%y; } //array of pointer to functions that receive two chars and returns int int (*arrpf[])(char,char) = { addC ,subC,mulC,divC,modC}; int res; char i; void main() { for (i=0;i<5;i++){ res = arrpf[i](10,20); } } POINTER ARITHMETIC Pointer arithmetic in the mikroC PRO for AVR is limited to: - assigning one pointer to another, comparing two pointers, comparing pointer to zero, adding/subtracting pointer and an integer valu
CHAPTER 5 mikroC PRO for AVR Language Reference is defined as *((id) + (exp)) where either: - id is a pointer and exp is an integer, or - id is an integer and exp is a pointer. The following statements are true: &a[i] a[i] = = a + i *(a + i) According to these guidelines, it can be written: pa = &a[4]; x = *(pa + 3); // pa points to a[4] // x = a[7] /* ..
CHAPTER 5 mikroC PRO for AVR Language Reference Two pointers pointing to the same array may be compared by using relational operators ==, !=, <, <=, >, and >=. Results of these operations are the same as if they were used on subscript values of array elements in question: int *pa = &a[4], *pb = &a[2]; if (pa == pb) {... /* won't be executed as 4 is not equal to 2 */ } if (pa > pb) {...
CHAPTER 5 mikroC PRO for AVR Language Reference This allows you to write loops which access the array elements in a sequence by means of incrementing pointer — in the last iteration you will have the pointer pointing to one element past the array, which is legal. However, applying an indirection operator (*) to a “pointer to one past the last element” leads to undefined behavior.
mikroC PRO for AVR CHAPTER 5 Language Reference STRUCTURES A structure is a derived type usually representing a user-defined collection of named members (or components). These members can be of any type, either fundamental or derived (with some restrictions to be discussed later), in any sequence. In addition, a structure member can be a bit field. Unlike arrays, structures are considered to be single objects.
CHAPTER 5 Language Reference mikroC PRO for AVR Note that the structure tag can be omitted, but then additional objects of this type cannot be declared elsewhere. For more information, see the Untagged Structures below. Structure is initialized by assigning it a comma-delimited sequence of values within braces, similar to array. For example: /* Referring to declarations from the example above: */ /* Declare and initialize dots p and q: */ struct Dot p = {1., 1.}, q = {3.7, -0.
CHAPTER 5 mikroC PRO for AVR Language Reference Usually, there is no need to use both tag and typedef: either can be used in structure type declarations. Untagged structure and union members are ignored during initialization. Note: See also Working with structures. WORKING WITH STRUCTURES Structures represent user-defined types. A set of rules regarding the application of structures is strictly defined.
CHAPTER 5 mikroC PRO for AVR Language Reference STRUCTURE MEMBER ACCESS Structure and union members are accessed using the following two selection operators: . (period) -> (right arrow) The operator . is called the direct member selector and it is used to directly access one of the structure’s members. Suppose that the object s is of the struct type S and m is a member identifier of the type M declared in s, then the expression s.
CHAPTER 5 mikroC PRO for AVR Language Reference Accessing Nested Structures If the structure B contains a field whose type is the structure A, the members of A can be accessed by two applications of the member selectors: struct A { int j; double x; }; struct B { int i; struct A aa; double d; } s, *sptr; ... s.i = 3; s.aa.j = 2; sptr->d = 1.23; sptr->aa.x = 3.14; // assign 3 to the i member of B // assign 2 to the j member of A // assign 1.23 to the d member of B // assign 3.
CHAPTER 5 mikroC PRO for AVR Language Reference UNIONS Union types are derived types sharing many of syntactic and functional features of structure types. The key difference is that a union members share the same memory space. Note: The mikroC PRO for AVR does not support anonymous unions (ANSI divergence).
CHAPTER 5 mikroC PRO for AVR Language Reference /* Referring to declarations from the example above: */ pm = μ mu.d = 4.016; tmp = mu.d; // OK: mu.d = 4.016 tmp = mu.i; // peculiar result pm->i = 3; tmp = mu.i; // OK: mu.i = 3 The third line is legal, since mu.i is an integral type. However, the bit pattern in mu.i corresponds to parts of the previously assigned double. As such, it probably won’t provide an useful integer interpretation.
CHAPTER 5 mikroC PRO for AVR Language Reference BIT FIELDS Bit fields are specified numbers of bits that may or may not have an associated identifier. Bit fields offer a way of subdividing structures into named parts of user-defined sizes. Structures and unions can contain bit fields that can be up to 16 bits. You cannot take the address of a bit field. Note: If you need to handle specific bits of 8-bit variables (char and unsigned short) or registers, you don’t need to declare bit fields.
CHAPTER 5 mikroC PRO for AVR typedef struct lo_nibble : hi_nibble : high_byte : Language Reference { 4; 4; 8;} myunsigned; which declares the structured type myunsigned containing three components: lo_nibble (bits 3..0), hi_nibble (bits 7..4) and high_byte (bits 15..8). Bit Fields Access Bit fields can be accessed in the same way as the structure members. Use direct and indirect member selector (. and ->).
CHAPTER 5 mikroC PRO for AVR Language Reference TYPES CONVERSIONS The mikroC PRO for AVR is a strictly typed language, with each operator, statement and function demanding appropriately typed operands/arguments. However, we often have to use objects of “mismatching” types in expressions. In that case, type conversion is needed. Conversion of object of one type means that object's type is changed into another type.
CHAPTER 5 mikroC PRO for AVR Language Reference STANDARD CONVERSIONS Standard conversions are built in the mikroC PRO for AVR. These conversions are performed automatically, whenever required in the program. They can also be explicitly required by means of the typecast operator (refer to the Explicit Typecasting). The basic rule of automatic (implicit) conversion is that the operand of simpler type is converted (promoted) to the type of more complex operand.
CHAPTER 5 mikroC PRO for AVR Language Reference After this, any two values associated with an operator are either int (including the long and unsigned modifiers) or float (equivalent with double and long double in the mikroC PRO for AVR). 1. If either operand is float, the other operand is converted to float. 2. Otherwise, if either operand is unsigned long, the other operand is converted to unsigned long. 3. Otherwise, if either operand is long, then the other operand is converted to long. 4.
mikroC PRO for AVR CHAPTER 5 Language Reference EXPLICIT TYPES CONVERSIONS (TYPECASTING) In most situations, compiler will provide an automatic implicit conversion of types where needed, without any user's interference. Also, the user can explicitly convert an operand to another type using the prefix unary typecast operator: (type) object This will convert object to a specified type. Parentheses are mandatory.
CHAPTER 5 mikroC PRO for AVR Language Reference DECLARATIONS A declaration introduces one or several names to a program – it informs the compiler what the name represents, what its type is, what operations are allowed with it, etc. This section reviews concepts related to declarations: declarations, definitions, declaration specifiers, and initialization.
mikroC PRO for AVR CHAPTER 5 Language Reference /* Definition of variable i: */ int i; /* Following line is an error, i is already defined! */ int i; Declarations and Declarators The declaration contains specifier(s) followed by one or more identifiers (declarators). The declaration begins with optional storage class specifiers, type specifiers, and other modifiers. The identifiers are separated by commas and the list is terminated by a semicolon.
CHAPTER 5 mikroC PRO for AVR Language Reference LINKAGE An executable program is usually created by compiling several independent translation units, then linking the resulting object files with preexisting libraries. A term translation unit refers to a source code file together with any included files, but without the source lines omitted by conditional preprocessor directives.
CHAPTER 5 mikroC PRO for AVR Language Reference The storage class specifiers auto and register cannot appear in an external declaration. No more than one external definition can be given for each identifier in a translation unit declared with internal linkage. An external definition is an external declaration that defines an object or a function and also allocates a storage.
CHAPTER 5 Language Reference mikroC PRO for AVR Static A global name declared with the static specifier has internal linkage, meaning that it is local for a given file. See Linkage for more information. A local name declared with the static specifier has static duration. Use static with a local variable to preserve the last value between successive calls to that function. See Duration for more information.
mikroC PRO for AVR CHAPTER 5 Language Reference TYPE QUALIFIERS The type qualifiers const and volatile are optional in declarations and do not actually affect the type of declared object. Qualifier const The qualifier const implies that a declared object will not change its value during runtime. In declarations with the const qualifier all objects need to be initialized. The mikroC PRO for AVR treats objects declared with the const qualifier the same as literals or preprocessor constants.
CHAPTER 5 mikroC PRO for AVR Language Reference TYPEDEF SPECIFIER The specifier typedef introduces a synonym for a specified type. The typedef declarations are used to construct shorter or more convenient names for types already defined by the language or declared by the user. The specifier typedef stands first in the declaration: typedef synonym; The typedef keyword assigns synonym to . The synonym needs to be a valid identifier.
CHAPTER 5 mikroC PRO for AVR Language Reference ASM DECLARATION The mikroC PRO for AVR allows embedding assembly in the source code by means of the asm declaration. The declarations _asm and __asm are also allowed in the mikroC PRO for AVR and have the same meaning. Note that numerals cannnot be used as absolute addresses for SFR or GPR variables in assembly instructions. Symbolic names may be used instead (listing will display these names as well as addresses).
CHAPTER 5 mikroC PRO for AVR Language Reference Initialization The initial value of a declared object can be set at the time of declaration (initialization). A part of the declaration which specifies the initialization is called initializer. Initializers for globals and static objects must be constants or constant expressions. The initializer for an automatic object can be any legal expression that evaluates to an assignment-compatible value for the type of the variable involved.
mikroC PRO for AVR CHAPTER 5 Language Reference FUNCTIONS Functions are central to C programming. Functions are usually defined as subprograms which return a value based on a number of input parameters. Return value of the function can be used in expressions – technically, function call is considered to be an expression like any other. C allows a function to create results other than its return value, referred to as side effects.
CHAPTER 5 mikroC PRO for AVR Language Reference Within parentheses, parameter-declarator-list is a list of formal arguments that function takes. These declarators specify the type of each function parameter. The compiler uses this information to check validity of function calls. If the list is empty, a function does not take any arguments. Also, if the list is void, a function also does not take any arguments; note that this is the only case when void can be used as an argument’s type.
mikroC PRO for AVR CHAPTER 5 Language Reference The function itself can be defined only within the file scope, which means that function declarations cannot be nested. To return the function result, use the return statement. The statement return in functions of the void type cannot have a parameter – in fact, the return statement can be omitted altogether if it is the last statement in the function body.
CHAPTER 5 Language Reference mikroC PRO for AVR FUNCTION CALLS AND ARGUMENT CONVERSIONS Function Calls A function is called with actual arguments placed in the same sequence as their matching formal parameters. Use the function-call operator (): function_name(expression_1, ... , expression_n) Each expression in the function call is an actual argument. Number and types of actual arguments should match those of formal function parameters.
CHAPTER 5 mikroC PRO for AVR Language Reference Argument Conversions If a function prototype has not been previously declared, the mikroC PRO for AVR converts integral arguments to a function call according to the integral widening (expansion) rules described in Standard Conversions. If a function prototype is in scope, the mikroC PRO for AVR converts the passed argument to the type of the declared parameter according to the same conversion rules as in assignment statements.
CHAPTER 5 Language Reference mikroC PRO for AVR Ellipsis ('...') Operator The ellipsis ('...') consists of three successive periods with no whitespace intervening. An ellipsis can be used in the formal argument lists of function prototypes to indicate a variable number of arguments, or arguments with varying types. For example: void func (int n, char ch, ...
CHAPTER 5 mikroC PRO for AVR Language Reference OPERATORS Operators are tokens that trigger some computation when applied to variables and other objects in an expression.
CHAPTER 5 mikroC PRO for AVR Language Reference OPERATORS PRECEDENCE AND ASSOCIATIVITY There are 15 precedence categories, some of them contain only one operator. Operators in the same category have equal precedence. If duplicates of operators appear in the table, the first occurrence is unary and the second binary. Each category has an associativity rule: left-to-right ( ), or right-toleft ( ).
CHAPTER 5 mikroC PRO for AVR Language Reference ARITHMETIC OPERATORS Arithmetic operators are used to perform mathematical computations. They have numerical operands and return numerical results. The type char technically represents small integers, so the char variables can be used as operands in arithmetic operations. All arithmetic operators associate from left to right.
CHAPTER 5 mikroC PRO for AVR Language Reference /* for example: */ 7 / 4; /* equals 1 */ 7 * 3 / 4; /* equals 5 */ /* but: */ 7. * 3. / 4.; /* equals 5.
CHAPTER 5 mikroC PRO for AVR Language Reference RELATIONAL OPERATORS Use relational operators to test equality or inequality of expressions. If an expression evaluates to be true, it returns 1; otherwise it returns 0. All relational operators associate from left to right.
CHAPTER 5 mikroC PRO for AVR Language Reference BITWISE OPERATORS Use the bitwise operators to modify individual bits of numerical operands. Bitwise operators associate from left to right. The only exception is the bitwise complement operator ~ which associates from right to left.
CHAPTER 5 mikroC PRO for AVR Language Reference ---------------------------& : 0001 0010 0011 0000 .. that is, 0x1230 */ /* Similarly: */ 0x1234 | 0x5678; 0x1234 ^ 0x5678; ~ 0x1234; /* equals 0x567C */ /* equals 0x444C */ /* equals 0xEDCB */ Note: Operator & can also be a pointer reference operator. Refer to Pointers for more information.
CHAPTER 5 mikroC PRO for AVR Language Reference LOGICAL OPERATORS Operands of logical operations are considered true or false, that is non-zero or zero. Logical operators always return 1 or 0. Operands in a logical expression must be of scalar type. Logical operators && and || associate from left to right. Logical negation operator ! associates from right to left.
CHAPTER 5 mikroC PRO for AVR Language Reference LOGICAL EXPRESSIONS AND SIDE EFFECTS General rule regarding complex logical expressions is that the evaluation of consecutive logical operands stops at the very moment the final result is known. For example, if we have an expression a && b && c where a is false (0), then operands b and c will not be evaluated. This is very important if b and c are expressions, as their possible side effects will not take place! LOGICAL VS.
CHAPTER 5 mikroC PRO for AVR Language Reference CONDITIONAL OPERATOR ? : The conditional operator ? : is the only ternary operator in C. Syntax of the conditional operator is: expression1 ? expression2 : expression3 The expression1 is evaluated first. If its value is true, then expression2 evaluates and expression3 is ignored. If expression1 evaluates to false, then expression3 evaluates and expression2 is ignored.
mikroC PRO for AVR CHAPTER 5 Language Reference ASSIGNMENT OPERATORS Unlike many other programming languages, C treats value assignment as operation (represented by an operator) rather than instruction. Simple Assignment Operator For a common value assignment, a simple assignment operator (=) is used: expression1 = expression2 The expression1 is an object (memory location) to which the value of expression2 is assigned. Operand expression1 has to be lvalue and expression2 can be any expression.
CHAPTER 5 mikroC PRO for AVR Language Reference Assignment Rules For both simple and compound assignment, the operands expression1 and expression2 must obey one of the following rules: 1. expression1 is of qualified or unqualified arithmetic type and expression2 is of arithmetic type. 2. expression1 has a qualified or unqualified version of structure or union type compatible with the type of expression2. 3.
CHAPTER 5 mikroC PRO for AVR Language Reference SIZEOF OPERATOR The prefix unary operator sizeof returns an integer constant that represents the size of memory space (in bytes) used by its operand (determined by its type, with some exceptions). The operator sizeof can take either a type identifier or an unary expression as an operand. You cannot use sizeof with expressions of function type, incomplete types, parenthesized names of such types, or with lvalue that designates a bit field object.
CHAPTER 5 Language Reference mikroC PRO for AVR Expressions Expression is a sequence of operators, operands, and punctuators that specifies a computation. Formally, expressions are defined recursively: subexpressions can be nested without formal limit. However, the compiler will report an out-of-memory error if it can’t compile an expression that is too complex. In ANSI C, the primary expressions are: constant (also referred to as literal), identifier, and (expression), defined recursively.
mikroC PRO for AVR CHAPTER 5 Language Reference COMMA EXPRESSIONS One of the specifics of C is that it allows using of comma as a sequence operator to form so-called comma expressions or sequences. Comma expression is a commadelimited list of expressions – it is formally treated as a single expression so it can be used in places where an expression is expected.
CHAPTER 5 mikroC PRO for AVR Language Reference STATEMENTS Statements specify a flow of control as the program executes. In the absence of specific jump and selection statements, statements are executed sequentially in the order of appearance in the source code. Statements can be roughly divided into: - Labeled Statements Expression Statements Selection Statements Iteration Statements (Loops) Jump Statements Compound Statements (Blocks) Labeled Statements Each statement in a program can be labeled.
CHAPTER 5 mikroC PRO for AVR Language Reference EXPRESSION STATEMENTS Any expression followed by a semicolon forms an expression statement: expression; The mikroC PRO for AVR executes an expression statement by evaluating the expression. All side effects from this evaluation are completed before the next statement starts executing. Most of expression statements are assignment statements or function calls. A null statement is a special case, consisting of a single semicolon (;).
CHAPTER 5 Language Reference mikroC PRO for AVR IF STATEMENT The if statement is used to implement a conditional statement. The syntax of the if statement is: if (expression) statement1 [else statement2] If expression evaluates to true, statement1 executes. If expression is false, statement2 executes. The expression must evaluate to an integral value; otherwise, the condition is ill-formed. Parentheses around the expression are mandatory.
CHAPTER 5 mikroC PRO for AVR Language Reference SWITCH STATEMENT The switch statement is used to pass control to a specific program branch, based on a certain condition. The syntax of the switch statement is: switch (expression) { case constant-expression_1 : statement_1; . . . case constant-expression_n : statement_n; [default : statement;] } First, the expression (condition) is evaluated. The switch statement then compares it to all available constant-expressions following the keyword case.
CHAPTER 5 mikroC PRO for AVR Language Reference switch (phase) { case 0: Lo(); break; case 1: Mid(); break; case 2: Hi(); break; default: Message("Invalid state!"); } Nested switch Conditional switch statements can be nested – labels case and default are then assigned to the innermost enclosing switch statement. ITERATION STATEMENTS (LOOPS) Iteration statements allows to loop a set of statements.
mikroC PRO for AVR CHAPTER 5 Language Reference DO STATEMENT The do statement executes until the condition becomes false. The syntax of the do statement is: do statement while (expression); The statement is executed repeatedly as long as the value of expression remains non-zero. The expression is evaluated after each iteration, so the loop will execute statement at least once. Parentheses around expression are mandatory.
CHAPTER 5 mikroC PRO for AVR Language Reference FOR STATEMENT The for statement implements an iterative loop. The syntax of the for statement is: for ([init-expression]; sion]) statement [condition-expression]; [increment-expres- Before the first iteration of the loop, init-expression sets the starting variables for the loop. You cannot pass declarations in init-expression.
CHAPTER 5 mikroC PRO for AVR Language Reference JUMP STATEMENTS The jump statement, when executed, transfers control unconditionally. There are four such statements in the mikroC PRO for AVR: - break continue goto return BREAK AND CONTINUE STATEMENTS Break Statement Sometimes it is necessary to stop the loop within its body. Use the break statement within loops to pass control to the first statement following the innermost switch, for, while, or do block.
CHAPTER 5 Language Reference mikroC PRO for AVR for (..;..;..) { ... if (val>0) continue; ... // continue jumps here } GOTO STATEMENT The goto statement is used for unconditional jump to a local label — for more information on labels, refer to Labeled Statements. The syntax of the goto statement is: goto label_identifier ; This will transfer control to the location of a local label specified by label_identifier.
mikroC PRO for AVR CHAPTER 5 Language Reference RETURN STATEMENT The return statement is used to exit from the current function back to the calling routine, optionally returning a value. The syntax is: return [expression]; This will evaluate expression and return the result. Returned value will be automatically converted to the expected function type, if needed. The expression is optional; if omitted, the function will return a random value from memory.
CHAPTER 5 mikroC PRO for AVR Language Reference PREPROCESSOR Preprocessor is an integrated text processor which prepares the source code for compiling. Preprocessor allows: - inserting text from a specifed file to a certain point in the code (see File Inclusion), - replacing specific lexical symbols with other symbols (see Macros), - conditional compiling which conditionally includes or omits parts of the code (see Conditional Compilation).
CHAPTER 5 mikroC PRO for AVR Language Reference PREPROCESSOR DIRECTIVES Any line in the source code with a leading # is taken as a preprocessing directive (or control line), unless # is within a string literal, in a character constant, or embedded in a comment. The initial # can be preceded or followed by a whitespace (excluding new lines). A null directive consists of a line containing the single character #. This line is always ignored.
CHAPTER 5 Language Reference mikroC PRO for AVR MACROS Macros provide a mechanism for a token replacement, prior to compilation, with or without a set of formal, function-like parameters.
mikroC PRO for AVR CHAPTER 5 Language Reference Attempting to redefine an already defined macro identifier will result in a warning unless a new definition is exactly the same token-by-token definition as the existing one. The preferred strategy when definitions might exist in other header files is as follows: #ifndef BLOCK_SIZE #define BLOCK_SIZE 512 #endif The middle line is bypassed if BLOCK_SIZE is currently defined; if BLOCK_SIZE is not currently defined, the middle line is invoked to define it.
CHAPTER 5 Language Reference mikroC PRO for AVR /* A simple macro which returns greater of its 2 arguments: */ #define _MAX(A, B) ((A) > (B)) ? (A) : (B) /* Let's call it: */ x = _MAX(a + b, c + d); /* Preprocessor will transform the previous line into: x = ((a + b) > (c + d)) ? (a + b) : (c + d) */ It is highly recommended to put parentheses around each argument in the macro body in order to avoid possible problems with operator precedence.
CHAPTER 5 mikroC PRO for AVR Language Reference FILE INCLUSION The preprocessor directive #include pulls in header files (extension .h) into the source code. Do not rely on preprocessor to include source files (extension ) — see Add/Remove Files from Project for more information.
CHAPTER 5 Language Reference mikroC PRO for AVR PREPROCESSOR OPERATORS The # (pound sign) is a preprocessor directive when it occurs as the first non-whitespace character on a line. Also, # and ## perform operator replacement and merging during the preprocessor scanning phase. Operator # In C preprocessor, a character sequence enclosed by quotes is considered a token and its content is not analyzed. This means that macro names within quotes are not expanded.
mikroC PRO for AVR CHAPTER 5 Language Reference CONDITIONAL COMPILATION Conditional compilation directives are typically used to make source programs easy to change and easy to compile in different execution environments. The mikroC PRO for AVR supports conditional compilation by replacing the appropriate sourcecode lines with a blank line. All conditional compilation directives must be completed in the source or include file in which they have begun.
CHAPTER 5 Language Reference mikroC PRO for AVR If all occurrences of constant-expression are false, or if no #elif directives appear, the preprocessor selects the text block after the #else clause. If the #else clause is omitted and all instances of constant_expression in the #if block are false, no section is selected for further processing. Any processed section can contain further conditional clauses, nested to any depth.
CHAPTER mikroC PRO for AVR Libraries 6 mikroC PRO for AVR provides a set of libraries which simplify the initialization and use of AVR compliant MCUs and their modules: Use Library manager to include mikroC PRO for AVR Libraries in you project.
CHAPTER 6 mikroC PRO for AVR Libraries Hardware AVR-specific Libraries - ADC Library - CANSPI Library - Compact Flash Library - EEPROM Library - Flash Memory Library - Graphic LCD Library - Keypad Library - LCD Library - Manchester Code Library - Multi Media Card library - OneWire Library - Port Expander Library - PS/2 Library - PWM Library - PWM 16 bit Library - RS-485 Library - Software I2C Library - Software SPI Library - Software UART Library - Sound Library - SPI Library - SPI Ethernet Library - SPI
CHAPTER 6 mikroC PRO for AVR Libraries Standard ANSI C Libraries - ANSI - ANSI - ANSI - ANSI C C C C Ctype Library Math Library Stdlib Library String Library Miscellaneous Libraries - Button Library - Conversions Library - Sprint Library - Time Library - Trigonometry Library - See also Built-in Routines. LIBRARY DEPENDENCIES Certain libraries use (depend on) function and/or variables, constants defined in other libraries. Image below shows clear representation about these dependencies.
CHAPTER 6 mikroC PRO for AVR Libraries Related topics: Library manager, AVR Libraries 230 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries ADC LIBRARY ADC (Analog to Digital Converter) module is available with a number of AVR micros. Library function ADC_Read is included to provide you comfortable work with the module in single-ended mode. ADC_Read Prototype unsigned ADC_Read(char channel); Returns 10-bit or 12-bit (MCU dependent) unsigned value from the specified channel. Description Initializes AVR ’s internal ADC module to work with XTAL frequency prescaled by 128.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example This example code reads analog value from channel 2 and displays it on PORTB and PORTC. #include unsigned int adc_rd; void main() { DDRB = 0xFF; DDRC = 0xFF; while (1) { adc_rd = ADC_Read(2); PORTB = adc_rd; PORTC = Hi(adc_rd); } // Set PORTB as output // Set PORTC as output // get ADC value from 2nd channel // display adc_rd[7..0] // display adc_rd[9..
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection ADC HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 233
CHAPTER 6 mikroC PRO for AVR Libraries CANSPI LIBRARY The SPI module is available with a number of the AVR compliant MCUs. The mikroC PRO for AVR provides a library (driver) for working with mikroElektronika's CANSPI Add-on boards (with MCP2515 or MCP2510) via SPI interface. The CAN is a very robust protocol that has error detection and signalization, self–checking and fault confinement. Faulty CAN data and remote frames are retransmitted automatically, similar to the Ethernet.
CHAPTER 6 mikroC PRO for AVR Libraries External dependecies of CANSPI Library The following variables must be defined in all projects using CANSPI Library: Description : Example : extern sfr sbit CanSpi_CS; Chip Select line. sbit CanSpi_CS at PORTB.B0; extern sfr sbit CanSpi_Rst; Reset line. sbit CanSpi_Rst at PORTB.B2; extern sfr sbit CanSpi_CS_Bit_Direction; Direction of the Chip Select pin. sbit CanSpi_CS_Bit_Direction at DDRB.B0; extern sfr sbit Direction of the Reset pin.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPISetOperationMode Prototype void CANSPISetOperationMode(char mode, char WAIT); Returns Nothing. Sets the CANSPI module to requested mode. Parameters : - mode: CANSPI module operation mode. Valid values: CANSPI_OP_MODE conDescription stants (see CANSPI constants). - WAIT: CANSPI mode switching verification request. If WAIT == 0, the call is non-blocking. The function does not verify if the CANSPI module is switched to requested mode or not.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPIInitialize Prototype void CANSPIInitialize( char SJW, char BRP, char PHSEG1, char PHSEG2, char PROPSEG, char CAN_CONFIG_FLAGS); Returns Nothing. Initializes the CANSPI module.
CHAPTER 6 mikroC PRO for AVR Libraries // CANSPI module connections sbit CanSpi_CS at PORTB.B0; sbit CanSpi_CS_Direction at DDRB.B0; sbit CanSpi_Rst at PORTB.B2; sbit CanSpi_Rst_Direction at DDRB.B2; // End CANSPI module connections Example // initialize the CANSPI module with the appropriate baud rate and message acceptance flags along with the sampling rules char Can_Init_Flags; ...
CHAPTER 6 mikroC PRO for AVR Libraries CANSPISetBaudRate Prototype void CANSPISetBaudRate( char SJW, char BRP, char PHSEG1, char PHSEG2, char PROPSEG, char CAN_CONFIG_FLAGS); Returns Nothing. Sets the CANSPI module baud rate. Due to complexity of the CAN protocol, you can not simply force a bps value. Instead, use this function when the CANSPI module is in Config mode. SAM, SEG2PHTS and WAKFIL bits are set according to CAN_CONFIG_FLAGS value. Refer to datasheet for details.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPISetMask Prototype void CANSPISetMask(char CAN_MASK, long val, char CAN_CONFIG_FLAGS); Returns Nothing. Configures mask for advanced filtering of messages. The parameter value is bitadjusted to the appropriate mask registers. Parameters: - CAN_MASK: CANSPI module mask number. Valid values: CANSPI_MASK constants (see CANSPI constants) Description - val: mask register value - CAN_CONFIG_FLAGS: selects type of message to filter.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPISetFilter Prototype void CANSPISetFilter(char CAN_FILTER, long val, char CAN_CONFIG_FLAGS); Returns Nothing. Configures message filter. The parameter value is bit-adjusted to the appropriate filter registers. Parameters: - CAN_FILTER: CANSPI module filter number. Valid values: CANSPI_FILTER constants (see CANSPI constants) Description - val: filter register value - CAN_CONFIG_FLAGS: selects type of message to filter.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPIRead Prototype char CANSPIRead(long *id, char *rd_data, char *data_len, char *CAN_RX_MSG_FLAGS); - 0 if nothing is received - 0xFF if one of the Receive Buffers is full (message received) Returns If at least one full Receive Buffer is found, it will be processed in the following way: - Message ID is retrieved and stored to location provided by the id parameter - Message data is retrieved and stored to a buffer provided by the rd_data parameter - Message len
CHAPTER 6 mikroC PRO for AVR Libraries CANSPIWrite Prototype Returns char CANSPIWrite(long id, char *wr_data, char data_len, char CAN_TX_MSG_FLAGS); - 0 if all Transmit Buffers are busy - 0xFF if at least one Transmit Buffer is available If at least one empty Transmit Buffer is found, the function sends message in the queue for transmission. Parameters: Description - id:CAN message identifier.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPI Constants There is a number of constants predefined in the CANSPI library. You need to be familiar with them in order to be able to use the library effectively. Check the example at the end of the chapter. CANSPI_OP_MODE The CANSPI_OP_MODE constants define CANSPI operation mode.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPI_CONFIG_DBL_BUFFER_BIT CANSPI_CONFIG_DBL_BUFFER_ON CANSPI_CONFIG_DBL_BUFFER_OFF = 0x10, = 0xFF, = 0xEF, // XXX1XXXX // XXX0XXXX CANSPI_CONFIG_MSG_BITS CANSPI_CONFIG_ALL_MSG CANSPI_CONFIG_VALID_XTD_MSG CANSPI_CONFIG_VALID_STD_MSG CANSPI_CONFIG_ALL_VALID_MSG = 0x60, = 0xFF, = 0xDF, = 0xBF, = 0x9F; // X11XXXXX // X10XXXXX // X01XXXXX // X00XXXXX You may use bitwise AND (&) to form config byte out of these values.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPI_RX_MSG_FLAGS CANSPI_RX_MSG_FLAGS are flags related to reception of CAN message. If a particular bit is set then corresponding meaning is TRUE or else it will be FALSE.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPI_FILTER The CANSPI_FILTER constants define filter codes. Functions CANSPISetFilter expects one of these as it's argument: const char CANSPI_FILTER_B1_F1 CANSPI_FILTER_B1_F2 CANSPI_FILTER_B2_F1 CANSPI_FILTER_B2_F2 CANSPI_FILTER_B2_F3 CANSPI_FILTER_B2_F4 = = = = = = 0, 1, 2, 3, 4, 5; Library Example This is a simple demonstration of CANSPI Library routines usage. First node initiates the communication with the second node by sending some data to its address.
CHAPTER 6 Libraries mikroC PRO for AVR Can_Send_Flags = _CANSPI_TX_PRIORITY_0 & // form value to be used _CANSPI_TX_XTD_FRAME & // with CANSPIWrite _CANSPI_TX_NO_RTR_FRAME; Can_Init_Flags = _CANSPI_CONFIG_SAMPLE_THRICE & // form value to be used _CANSPI_CONFIG_PHSEG2_PRG_ON &// with CANSPIInit _CANSPI_CONFIG_XTD_MSG & _CANSPI_CONFIG_DBL_BUFFER_ON & _CANSPI_CONFIG_VALID_XTD_MSG; SPI1_Init(); Spi_Rd_Ptr = SPI1_Read; // pass pointer to SPI Read function of used SPI module SPI1_Init(); // initialize SPI1 modu
mikroC PRO for AVR CHAPTER 6 Libraries Code for the second CANSPI node: unsigned char Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags; // can flags unsigned char Rx_Data_Len; // received data length in bytes char RxTx_Data[8]; // can rx/tx data buffer char Msg_Rcvd; // reception flag long Tx_ID, Rx_ID; // can rx and tx ID // CANSPI module connections sbit CanSpi_CS at PORTB.B0; sbit CanSpi_CS_Direction at DDRB.B0; sbit CanSpi_Rst at PORTB.B2; sbit CanSpi_Rst_Direction at DDRB.
CHAPTER 6 mikroC PRO for AVR Libraries CANSPISetFilter(_CANSPI_FILTER_B2_F3,12111,_CANSPI_CONFIG_XTD_MSG); // set id of filter B1_F1 to 3 CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF); // set NORMAL mode Tx_ID = 3; // set tx ID while (1) { // endless loop Msg_Rcvd = CANSPIRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // receive message if ((Rx_ID == 12111u) && Msg_Rcvd) { // if message received check id PORTC = RxTx_Data[0]; // id correct, output data at PORTC RxTx_Data[0]++ ; // increment
mikroC PRO for AVR CHAPTER 6 Libraries COMPACT FLASH LIBRARY The Compact Flash Library provides routines for accessing data on Compact Flash card (abbr. CF further in text). CF cards are widely used memory elements, commonly used with digital cameras. Great capacity and excellent access time of only a few microseconds make them very attractive for microcontroller applications. In CF card, data is divided into sectors. One sector usually comprises 512 bytes.
CHAPTER 6 mikroC PRO for AVR Libraries External dependencies of Compact Flash Library The following variables must be defined in all projects using Compact Flash Library: 252 Description: Example : extern sfr char CF_Data_Port; Compact Flash Data Port. sfr char CF_Data_Port at PORTD; extern sfr char CF_Data_Port_Direction; Direction of the Compact Flash Data Port. sfr char CF_Data_Port_Direc tion at DDRD; extern sfr sbit CF_RDY; Ready signal line. sbit CF_RDY at PINB.
CHAPTER 6 mikroC PRO for AVR Libraries extern sfr sbit CF_A1_direction; extern sfr sbit CF_A0_direction; Direction of the Address 1 pin. Direction of the Address 0 pin. sbit CF_A1_direction at DDRB.B1; sbit CF_A0_direction at DDRB.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Init Prototype void Cf_Init(); Returns Nothing. Description Initializes ports appropriately for communication with CF card.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Detect Prototype Returns unsigned short Cf_Detect(void); - 1 - if CF card was detected - 0 - otherwise Description Checks for presence of CF card by reading the chip detect pin. Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init. Example // Wait until CF card is inserted: do asm nop; while (!Cf_Detect()); Cf_Enable Prototype void Cf_Enable(void); Returns Nothing. Enables the device.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Read_Init Prototype void Cf_Read_Init(unsigned long address, unsigned short sector_count); Returns Nothing. Initializes CF card for reading. Description Parameters : - address: the first sector to be prepared for reading operation. - sector_count: number of sectors to be prepared for reading operation. Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Write_Init Prototype void Cf_Write_Init(unsigned long address, unsigned short sectcnt); Returns Nothing. Initializes CF card for writing. Description Parameters : - address: the first sector to be prepared for writing operation. - sectcnt: number of sectors to be prepared for writing operation. Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Read_Sector Prototype void Cf_Read_Sector(unsigned long sector_number, unsigned short *buffer); Returns Nothing. Reads one sector (512 bytes). Read data is stored into buffer provided by the buffer parameter. Description Parameters : - sector_number: sector to be read. - buffer: data buffer of at least 512 bytes in length. Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Init Prototype Returns unsigned short Cf_Fat_Init(); - 0 - if CF card was detected and successfully initialized - 1 - if FAT16 boot sector was not found - 255 - if card was not detected Description Initializes CF card, reads CF FAT16 boot sector and extracts necessary data needed by the library. Requires Nothing. Example // Init the FAT library if (!Cf_Fat_Init()) { // Init the FAT library ...
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Assign Prototype unsigned short Cf_Fat_Assign(char *filename, char file_cre_attr); - 0 if file does not exist and no new file is created. - 1 if file already exists or file does not exist but a new file is created. Returns Assigns file for file operations (read, write, delete...). All subsequent file operations will be applied over the assigned file. Parameters : - filename: name of the file that should be assigned for file operations.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Reset Prototype void Cf_Fat_Reset(unsigned long *size); Returns Nothing. Opens currently assigned file for reading. Description Parameters : size: buffer to store file size to. After file has been open for reading its size is returned through this parameter. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. Example unsigned long size; ...
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Rewrite Prototype void Cf_Fat_Rewrite(); Returns Nothing. Description Opens currently assigned file for writing. If the file is not empty its content will be erased. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires The file must be previously assigned. See Cf_Fat_Assign. Example // open file for writing Cf_Fat_Rewrite(); Cf_Fat_Append Prototype void Cf_Fat_Append(); Returns Nothing.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Write Prototype void Cf_Fat_Write(char *fdata, unsigned data_len); Returns Nothing. Writes requested number of bytes to currently assigned file opened for writing. Description Parameters : - fdata: data to be written. - data_len: number of bytes to be written. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. File must be open for writing.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Set_File_Date Prototype void Cf_Fat_Set_File_Date(unsigned int year, unsigned short month, unsigned short day, unsigned short hours, unsigned short mins, unsigned short seconds); Returns Nothing. Sets the date/time stamp. Any subsequent file writing operation will write this stamp to currently assigned file's time/date attributs. Parameters : Description - year: year attribute. Valid values: 1980-2107 month: month attribute.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Get_File_Date Prototype void Cf_Fat_Get_File_Date(unsigned int *year, unsigned short *month, unsigned short *day, unsigned short *hours, unsigned short *mins); Returns Nothing. Reads time/date attributes of currently assigned file. Parameters : Description - year: buffer to store year attribute to. Upon function execution year attribute is returned through this parameter. - month: buffer to store month attribute to.
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Get_File_Size Prototype unsigned long Cf_Fat_Get_File_Size(); Returns Size of the currently assigned file in bytes. Description This function reads size of currently assigned file in bytes. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. Example 266 unsigned long my_file_size; ...
CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Get_Swap_File Prototype Returns unsigned long Cf_Fat_Get_Swap_File(unsigned long sectors_cnt, char *filename, char file_attr); - Number of the start sector for the newly created swap file, if there was enough free space on CF card to create file of required size. - 0 - otherwise. This function is used to create a swap file of predefined name and size on the CF media.
CHAPTER 6 mikroC PRO for AVR Libraries Description Bit Mask Description 0 0x01 Read Only 1 0x02 Hidden 2 0x04 System 3 0x08 Volume Label 4 0x10 Subdirectory 5 0x20 Archive 6 0x40 Device (internal use only, never found on disk) 7 0x80 Not used Note: Long File Names (LFN) are not supported. 268 Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The following example is a simple demonstration of CF(Compact Flash) Library which shows how to use CF card data accessing routines. #include "built_in.h" // set compact flash pinout sfr char Cf_Data_Port at PORTD; sfr char Cf_Data_Port_Direction at DDRD; sfr sfr sfr sfr sfr sfr sfr sfr CF_RDY CF_WE CF_OE CF_CD1 CF_CE1 CF_A2 CF_A1 CF_A0 at at at at at at at at PINB.B7; PORTB.B6; PORTB.B5; PINB.B4; PORTB.B3; PORTB.B2; PORTB.B1; PORTB.
CHAPTER 6 mikroC PRO for AVR Libraries i = 0; while (ostr[i]) { UART1_Write(ostr[i++]); } UART1_Write(0x0A); } //-------------- Creates new file and writes some data to it void M_Create_New_File() { filename[7] = 'A'; Cf_Fat_Assign(&filename, 0x80); // Will not find file and then create file Cf_Fat_Rewrite(); // To clear file and start with new data for(loop = 1; loop <= 99; loop++) { // We want 5 files on the MMC card file_contents[0] = loop / 10 + 48; file_contents[1] = loop % 10 + 48; Cf_Fat_Write(fil
CHAPTER 6 mikroC PRO for AVR Libraries filename[7] = 'C'; Cf_Fat_Assign(&filename, 0); Cf_Fat_Rewrite(); for(loop = 1; loop <= 55; loop++) { file_contents[0] = loop / 10 + 64; file_contents[1] = loop % 10 + 64; Cf_Fat_Write(file_contents, 38); // write data to the assigned file } } //-------------- Opens an existing file and appends data to it // (and alters the date/time stamp) void M_Open_File_Append() { filename[7] = 'B'; Cf_Fat_Assign(&filename, 0); Cf_Fat_Set_File_Date(2005,6,21,10,35,0); Cf_Fat_App
CHAPTER 6 mikroC PRO for AVR Libraries //-------------- Tests whether file exists, and if so sends its creation date // and file size via USART void M_Test_File_Exist() { unsigned long fsize; unsigned int year; unsigned short month, day, hour, minute; unsigned char outstr[12]; filename[7] = 'B'; //uncomment this line to search for file that DOES exists // filename[7] = 'F'; //uncomment this line to search for file that DOES NOT exist if (Cf_Fat_Assign(filename, 0)) { //--- file has been found - get its d
CHAPTER 6 mikroC PRO for AVR Libraries size = Cf_Fat_Get_Swap_File(5000, "mikroE.txt", 0x20); on this function for details if // see help (size) { LongToStr((signed long)size, fat_txt); I_Write_Str(fat_txt); for(i=0; i<5000; i++) { Cf_Write_Sector(size++, Buffer); UART1_Write('.'); } } } //-------------- Main.
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection Pin diagram of CF memory card 274 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries EEPROM LIBRARY EEPROM data memory is available with a number of AVR family. The mikroC PRO for AVR includes a library for comfortable work with MCU's internal EEPROM. Note: EEPROM Library functions implementation is MCU dependent, consult the appropriate MCU datasheet for details about available EEPROM size and constrains.
CHAPTER 6 mikroC PRO for AVR Libraries EEPROM_Write Prototype void EEPROM_Write(unsigned address, unsigned short dData); Returns Nothing. Writes wrdata to specified address. Parameters : Description - address: address of the EEPROM memory location to be written. - wrdata: data to be written. Note: Specified memory location will be erased before writing starts. 276 Requires Nothing. Example unsigned address = 0x732; unsigned short dData = 0x55; ...
CHAPTER 6 mikroC PRO for AVR Libraries Library Example This example demonstrates using the EEPROM Library with ATMEGA16 MCU. First, some data is written to EEPROM in byte and block mode; then the data is read from the same locations and displayed on PORTA, PORTB and PORTC.
CHAPTER 6 mikroC PRO for AVR Libraries FLASH MEMORY LIBRARY This library provides routines for accessing microcontroller Flash memory. Note that prototypes differ for MCU to MCU due to the amount of Flash memory. Note: Due to the AVR family flash specifics, flash library is MCU dependent. Since some AVR MCU's have more or less than 64kb of Flash memory, prototypes may be different from chip to chip. Please refer to datasheet before using flash library. Note: Currently, Write operations are not supported.
mikroC PRO for AVR CHAPTER 6 Libraries FLASH_Read_Bytes // for MCUs with 64kb of Flash memory or less void FLASH_Read_Bytes(unsigned int address, char *buffer, unsigned NoBytes); Prototype // for MCUs with Flash memory larger than 64kb void FLASH_Read_Bytes(unsigned long address, char *buffer, unsigned NoBytes); Returns Nothing. Description Reads number of data bytes defined by NoBytes parameter from the specified address in Flash memory to varibale pointed by buffer. Requires Nothing.
CHAPTER 6 mikroC PRO for AVR Libraries FLASH_Read_Words // for MCUs with 64kb of Flash memory or less void FLASH_Read_wWrds(unsigned int address, char *buffer, unsigned NoWords); Prototype // for MCUs with Flash memory larger than 64kb void FLASH_Read_Words(unsigned long address, char *buffer, unsigned NoWords); Returns Nothing. Description Reads number of data words defined by NoWords parameter from the specified address in Flash memory to varibale pointed by buffer. Requires Nothing.
CHAPTER 6 mikroC PRO for AVR Libraries for (i = 0; i<64 ; i+=2) // reading 32 words in loop { word = FLASH_Read_Word(F_ADDRESS + i); // demonstration of reading single word PORTD = word; // output low byte to PORTD PORTB = word >> 8; // output higher byte to PORTB Delay_ms(200); } i = 0; while ( i < 64 ) // reading 64 bytes in loop { PORTD = FLASH_Read_Byte(F_ADDRESS + i++); // demonstration of reading single byte PORTB = FLASH_Read_Byte(F_ADDRESS + i++); // demonstration of reading single byte Delay_ms(
CHAPTER 6 mikroC PRO for AVR Libraries GRAPHIC LCD LIBRARY The mikroC PRO for AVR provides a library for operating Graphic LCD 128x64 (with commonly used Samsung KS108/KS107 controller). For creating a custom set of Glcd images use Glcd Bitmap Editor Tool. External dependencies of Graphic LCD Library The following variables must be defined in all projects using Graphic LCD Library: Description : extern sfr char GLCD_DataPort; Glcd Data Port.
CHAPTER 6 mikroC PRO for AVR Libraries Library Routines Basic routines: - Glcd_Init Glcd_Set_Side Glcd_Set_X Glcd_Set_Page Glcd_Read_Data Glcd_Write_Data Advanced routines: - Glcd_Fill Glcd_Dot Glcd_Line Glcd_V_Line Glcd_H_Line Glcd_Rectangle Glcd_Box Glcd_Circle Glcd_Set_Font Glcd_Write_Char Glcd_Write_Text Glcd_Image MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 283
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Init Prototype void Glcd_Init(); Returns Nothing. Description Initializes the Glcd module. Each of the control lines is both port and pin configurable, while data lines must be on a single port (pins <0:7>).
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Set_Side Prototype void Glcd_Set_Side(unsigned short x_pos); Returns Nothing. Selects Glcd side. Refer to the Glcd datasheet for detailed explaination. Parameters : - x_pos: position on x-axis. Valid values: 0..127 Description The parameter x_pos specifies the Glcd side: values from 0 to 63 specify the left side, values from 64 to 127 specify the right side. Note: For side, x axis and page layout explanation see schematic at the bottom of this page.
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Set_Page Prototype void Glcd_Set_Page(unsigned short page); Returns Nothing. Selects page of the Glcd. Parameters : Description - page: page number. Valid values: 0..7 Note: For side, x axis and page layout explanation see schematic at the bottom of this page. Requires Glcd needs to be initialized, see Glcd_Init routine. Example Glcd_Set_Page(5); Glcd_Read_Data Prototype unsigned short Glcd_Read_Data(); Returns One byte from Glcd memory.
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Write_Data Prototype void Glcd_Write_Data(unsigned short ddata); Returns Nothing. Writes one byte to the current location in Glcd memory and moves to the next location. Description Parameters : - ddata: data to be written Glcd needs to be initialized, see Glcd_Init routine. Requires Example Glcd side, x-axis position and page should be set first. See functions Glcd_Set_Side, Glcd_Set_X, and Glcd_Set_Page. unsigned short data; ...
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Dot Prototype void Glcd_Dot(unsigned short x_pos, unsigned short y_pos, unsigned short color); Returns Nothing. Draws a dot on Glcd at coordinates (x_pos, y_pos). Parameters : Description - x_pos: x position. Valid values: 0..127 - y_pos: y position. Valid values: 0..63 - color: color parameter. Valid values: 0..2 The parameter color determines a dot state: 0 clears dot, 1 puts a dot, and 2 inverts dot state.
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Line Prototype void Glcd_Line(int x_start, int y_start, int x_end, int y_end, unsigned short color); Returns Nothing. Draws a line on Glcd. Parameters : - Description x_start: x coordinate of the line start. Valid values: 0..127 y_start: y coordinate of the line start. Valid values: 0..63 x_end: x coordinate of the line end. Valid values: 0..127 y_end: y coordinate of the line end. Valid values: 0..63 color: color parameter. Valid values: 0..
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_H_Line Prototype void Glcd_H_Line(unsigned short x_start, unsigned short x_end, unsigned short y_pos, unsigned short color); Returns Nothing. Draws a horizontal line on Glcd. Parameters : - Description x_start: x coordinate of the line start. Valid values: 0..127 x_end: x coordinate of the line end. Valid values: 0..127 y_pos: y coordinate of horizontal line. Valid values: 0..63 color: color parameter. Valid values: 0..
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Box Prototype void Glcd_Box(unsigned short x_upper_left, unsigned short y_upper_left, unsigned short x_bottom_right, unsigned short y_bottom_right, unsigned short color); Returns Nothing. Draws a box on Glcd. Parameters : Description - x_upper_left: x coordinate of the upper left box corner. Valid values: 0..127 y_upper_left: y coordinate of the upper left box corner. Valid values: 0..63 x_bottom_right: x coordinate of the lower right box corner.
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Set_Font Prototype void Glcd_Set_Font(const char *activeFont, unsigned short aFontWidth, unsigned short aFontHeight, unsigned int aFontOffs); Returns Nothing. Sets font that will be used with Glcd_Write_Char and Glcd_Write_Text routines. Parameters : Description - activeFont: font to be set. Needs to be formatted as an array of char aFontWidth: width of the font characters in dots. aFontHeight: height of the font characters in dots.
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Write_Char Prototype void Glcd_Write_Char(unsigned short chr, unsigned short x_pos, unsigned short page_num, unsigned short color); Returns Nothing. Prints character on the Glcd. Parameters : Description - chr: character to be written - x_pos: character starting position on x-axis. Valid values: 0..(127-FontWidth) - page_num: the number of the page on which character will be written. Valid values: 0..7 - color: color parameter. Valid values: 0..
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Write_Text Prototype void Glcd_Write_Text(char *text, unsigned short x_pos, unsigned short page_num, unsigned short color); Returns Nothing. Prints text on Glcd. Parameters : Description - text: text to be written - x_pos: text starting position on x-axis. - page_num: the number of the page on which text will be written. Valid values: 0..7 - color: color parameter. Valid values: 0..
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Image Prototype void Glcd_Image(code const unsigned short *image); Returns Nothing. Displays bitmap on Glcd. Parameters : Description - image: image to be displayed. Bitmap array must be located in code memory. Use the mikroC PRO for AVR integrated Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd. Requires Glcd needs to be initialized, see Glcd_Init routine.
CHAPTER 6 mikroC PRO for AVR Libraries void delay2S(){ Delay_ms(2000); } // 2 seconds delay function void main() { unsigned short ii; char *someText; Glcd_Init(); Glcd_Fill(0x00); while(1) { Glcd_Image(truck_bmp); delay2S(); delay2S(); Glcd_Fill(0x00); Glcd_Box(62,40,124,56,1); Glcd_Rectangle(5,5,84,35,1); Glcd_Line(0, 0, 127, 63, 1); delay2S(); for(ii = 5; ii < 60; ii+=5 ){ vertical lines Delay_ms(250); Glcd_V_Line(2, 54, ii, 1); Glcd_H_Line(2, 120, ii, 1); } // Initialize Glcd // Clear Glcd // Draw
CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Set_Font(Character8x7, 8, 7, 32); someText = "8x7 Font"; Glcd_Write_Text(someText, 5, 0, 2); Glcd_Write_Text(someText, 5, 1, 2); delay2S(); // Change font Glcd_Set_Font(System3x5, 3, 5, 32); someText = "3X5 CAPITALS ONLY"; Glcd_Write_Text(someText, 60, 5, 2); Glcd_Write_Text(someText, 60, 6, 2); delay2S(); // Change font Glcd_Set_Font(font5x7, 5, 7, 32); someText = "5x7 Font"; Glcd_Write_Text(someText, 5, 5, 2); Glcd_Write_Text(someText, 5, 6, 2); delay2S();
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection Glcd HW connection 298 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries KEYPAD LIBRARY The mikroC PRO for AVR provides a library for working with 4x4 keypad. The library routines can also be used with 4x1, 4x2, or 4x3 keypad. For connections explanation see schematic at the bottom of this page. Note: Since sampling lines for AVR MCUs are activated by logical zero Keypad Library can not be used with hardwares that have protective diodes connected with anode to MCU side, such as mikroElektronika's Keypad extra board HW.Rev v1.
CHAPTER 6 mikroC PRO for AVR Libraries Keypad_Init Prototype void Keypad_Init(void); Returns Nothing. Description Initializes port for working with keypad. Requires Global variables : keypadPort - Keypad port keypadPort_Direction - Direction of the Keypad port must be defined before using this function. // Initialize PORTB for communication with keypad sfr char keypadPort at PORTB; // Port direction sfr char keypadPort_Direction at DDRB; Example // LCD module connections sbit LCD_RS at PORTD.
mikroC PRO for AVR CHAPTER 6 Libraries Keypad_Key_Press Prototype char Keypad_Key_Press(void); The code of a pressed key (1..16). Returns If no key is pressed, returns 0. Description Reads the key from keypad when key gets pressed. Requires Port needs to be initialized for working with the Keypad library, see Keypad_Init. Example char kp; ... kp = Keypad_Key_Press(); Keypad_Key_Click Prototype char Keypad_Key_Click(void); The code of a clicked key (1..16). Returns If no key is clicked, returns 0.
CHAPTER 6 mikroC PRO for AVR Libraries unsigned short kp, cnt, oldstate = 0; char txt[6]; // Keypad module connections sfr char keypadPort at PORTB; sfr char keypadPort_Direction at DDRB; // End Keypad module connections // LCD module connections sbit LCD_RS at PORTD.B2; sbit LCD_EN at PORTD.B3; sbit LCD_D4 at PORTD.B4; sbit LCD_D5 at PORTD.B5; sbit LCD_D6 at PORTD.B6; sbit LCD_D7 at PORTD.B7; sbit LCD_RS_Direction at DDRD.B2; sbit LCD_EN_Direction at DDRD.B3; sbit LCD_D4_Direction at DDRD.
CHAPTER 6 mikroC PRO for AVR Libraries case 1: for keypad4x4 case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: kp = 49; break; // 1 kp kp kp kp kp kp kp kp kp kp kp kp kp kp kp = = = = = = = = = = = = = = = 50; 51; 65; 52; 53; 54; 66; 55; 56; 57; 67; 42; 48; 35; 68; break; break; break; break; break; break; break; break; break; break; break; break; break; break; break; // // // // // // // // // // // // // // // // Uncomm
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection 4x4 Keypad connection scheme 304 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries LCD LIBRARY The mikroC PRO for AVR provides a library for communication with Lcds (with HD44780 compliant controllers) through the 4-bit interface. An example of Lcd connections is given on the schematic at the bottom of this page. For creating a set of custom Lcd characters use Lcd Custom Character Tool. External dependencies of Lcd Library The following variables must be defined in all projects using Lcd Library : Description : Example : sbit LCD_RS at PORTD.
CHAPTER 6 mikroC PRO for AVR Libraries Library Routines - 306 Lcd_Init Lcd_Out Lcd_Out_Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries Lcd_Init Prototype void Lcd_Init(); Returns Nothing. Description Initializes Lcd module.
CHAPTER 6 mikroC PRO for AVR Libraries Lcd_Out Prototype void Lcd_Out(char row, char column, char *text); Returns Nothing. Prints text on Lcd starting from specified position. Both string variables and literals can be passed as a text. Description Parameters : - row: starting position row number - column: starting position column number - text: text to be written Requires The Lcd module needs to be initialized. See Lcd_Init routine.
CHAPTER 6 mikroC PRO for AVR Libraries Lcd_Chr Prototype void Lcd_Chr(char row, char column, char out_char); Returns Nothing. Prints character on Lcd at specified position. Both variables and literals can be passed as a character. Description Parameters : - row: writing position row number - column: writing position column number - out_char: character to be written Requires The Lcd module needs to be initialized. See Lcd_Init routine.
CHAPTER 6 mikroC PRO for AVR Libraries Lcd_Cmd Prototype void Lcd_Cmd(char out_char); Returns Nothing. Sends command to Lcd. Parameters : Description - out_char: command to be sent Note: Predefined constants can be passed to the function, see Available Lcd Commands. Requires The Lcd module needs to be initialized. See Lcd_Init table.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The following code demonstrates usage of the Lcd Library routines: // Lcd module connections sbit LCD_RS at PORTD.B2; sbit LCD_EN at PORTD.B3; sbit LCD_D4 at PORTD.B4; sbit LCD_D5 at PORTD.B5; sbit LCD_D6 at PORTD.B6; sbit LCD_D7 at PORTD.B7; sbit LCD_RS_Direction at DDRD.B2; sbit LCD_EN_Direction at DDRD.B3; sbit LCD_D4_Direction at DDRD.B4; sbit LCD_D5_Direction at DDRD.B5; sbit LCD_D6_Direction at DDRD.B6; sbit LCD_D7_Direction at DDRD.
CHAPTER 6 mikroC PRO for AVR Libraries while(1) { for(i=0; i<7; i++) { Lcd_Cmd(LCD_SHIFT_LEFT); Move_Delay(); } for(i=0; i<7; i++) { Lcd_Cmd(LCD_SHIFT_RIGHT); Move_Delay(); } // Endless loop // Move text to the left 7 times // Move text to the right 7 times } } Lcd HW connection 312 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
mikroC PRO for AVR CHAPTER 6 Libraries MANCHESTER CODE LIBRARY The mikroC PRO for AVR provides a library for handling Manchester coded signals.
CHAPTER 6 mikroC PRO for AVR Libraries External dependencies of Manchester Code Library The following variables must be defined in all projects using Manchester Code Library: Description: Example: extern sfr sbit MANRXPIN; Receive line. sbit MANRXPIN at PINB.B0; extern sfr sbit MANTXPIN; Transmit line. sbit MANTXPIN at PORTB.B1; extern sfr sbit MANRXPIN_Direction; Direction of the Receive pin. extern sfr sbit MANTXPIN_Direction; Direction of the Transmit pin. sbit MANRXPIN_Direction at DDRB.
CHAPTER 6 mikroC PRO for AVR Libraries Man_Receive_Init Prototype Returns unsigned int Man_Receive_Init(); - 0 - if initialization and synchronization were successful. - 1 - upon unsuccessful synchronization. - 255 - upon user abort. The function configures Receiver pin and performs synchronization procedure in order to retrieve baud rate out of the incoming signal.
CHAPTER 6 mikroC PRO for AVR Libraries Man_Receive Prototype unsigned char Man_Receive(unsigned char *error); Returns A byte read from the incoming signal. The function extracts one byte from incoming signal. Description Parameters : - error: error flag. If signal format does not match the expected, the error flag will be set to non-zero. Requires To use this function, the user must prepare the MCU for receiving. See Man_Receive_Init. Example unsigned char data = 0, error = 0; ...
CHAPTER 6 mikroC PRO for AVR Libraries Man_Send Prototype void Man_Send(unsigned char tr_data); Returns Nothing. Sends one byte. Parameters : Description - tr_data: data to be sent Note: Baud rate used is 500 bps. Requires To use this function, the user must prepare the MCU for sending. See Man_Send_Init. Example unsigned char msg; ... Man_Send(msg); Man_Synchro Prototype Returns unsigned char Man_Synchro(); - 255 - if synchronization was not successful.
CHAPTER 6 mikroC PRO for AVR Libraries Man_Break Prototype void Man_Break(); Returns Nothing. Description Man_Receive is blocking routine and it can block the program flow. Call this routine from interrupt to unblock the program execution. This mechanism is similar to WDT. Note: Interrupts should be disabled before using Manchester routines again (see note at the top of this page). Requires Nothing.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The following code is code for the Manchester receiver, it shows how to use the Manchester Library for receiving data: // LCD module connections sbit LCD_RS at PORTD.B2; sbit LCD_EN at PORTD.B3; sbit LCD_D4 at PORTD.B4; sbit LCD_D5 at PORTD.B5; sbit LCD_D6 at PORTD.B6; sbit LCD_D7 at PORTD.B7; sbit LCD_RS_Direction at DDRD.B2; sbit LCD_EN_Direction at DDRD.B3; sbit LCD_D4_Direction at DDRD.B4; sbit LCD_D5_Direction at DDRD.
CHAPTER 6 mikroC PRO for AVR Libraries do { temp = Man_Receive(&error); // Attempt byte receive if (error) { // If error occured Lcd_Chr_CP('?'); // Write question mark on LCD ErrorCount++; // Update error counter if (ErrorCount > 20) { // In case of multiple errors temp = Man_Synchro(); // Try to synchronize again //Man_Receive_Init(); // Alternative, try to Initialize Receiver again ErrorCount = 0; // Reset error counter } } else { // No error occured if (temp != 0x0E) // If "End" byte was received(see
CHAPTER 6 mikroC PRO for AVR Libraries character = s1[0]; index = 0; while (character) { Man_Send(character); Delay_ms(90); index++; character = s1[index]; } Man_Send(0x0E); Delay_ms(1000); // Take first char from string // Initialize index variable // String ends with zero // Send character // Wait for a while // Increment index variable // Take next char from string // Send "end" byte } } Connection Example Simple Transmitter connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDE
CHAPTER 6 mikroC PRO for AVR Libraries Simple Receiver connection 322 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries MULTI MEDIA CARD LIBRARY The Multi Media Card (MMC) is a flash memory card standard. MMC cards are currently available in sizes up to and including 1 GB, and are used in cell phones, mp3 players, digital cameras, and PDA’s. mikroC PRO for AVR provides a library for accessing data on Multi Media Card via SPI communication.This library also supports SD(Secure Digital) memory cards.
CHAPTER 6 mikroC PRO for AVR Libraries Library Routines - Mmc_Init Mmc_Read_Sector Mmc_Write_Sector Mmc_Read_Cid Mmc_Read_Csd Routines for file handling: - 324 Mmc_Fat_Init Mmc_Fat_QuickFormat Mmc_Fat_Assign Mmc_Fat_Reset Mmc_Fat_Read Mmc_Fat_Rewrite Mmc_Fat_Append Mmc_Fat_Delete Mmc_Fat_Write Mmc_Fat_Set_File_Date Mmc_Fat_Get_File_Date Mmc_Fat_Get_File_Size Mmc_Fat_Get_Swap_File MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Init Prototype unsigned char Mmc_Init(); - 1 - if MMC/SD card was detected and successfully initialized - 0 - otherwise Returns Description Initializes hardware SPI communication; The function returns 1 if MMC card is present and successfully initialized, otherwise returns 0. Mmc_Init needs to be called before using other functions of this library.
CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Write_Sector Prototype unsigned char Mmc_Write_Sector(unsigned long sector, char *dbuff); Returns Returns 0 if write was successful; returns 1 if there was an error in sending write command; returns 2 if there was an error in writing. Function writes 512 bytes of data to MMC card at sector address sector. FuncDescription tion returns 0 if write was successful, or 1 if there was an error in sending write command, or 2 if there was an error in writing.
CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Fat_Init Prototype Returns Description unsigned short Mmc_Fat_Init(); - 0 - if MMC/SD card was detected and successfully initialized - 1 - if FAT16 boot sector was not found - 255 - if MMC/SD card was not detected Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by the library. Note: MMC/SD card has to be formatted to FAT16 file system.
CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Fat_QuickFormat Prototype Returns unsigned char Mmc_Fat_QuickFormat(unsigned char *port, unsigned char pin, char * mmc_fat_label) - 0 - if MMC/SD card was detected, successfully formated and initialized - 1 - if FAT16 format was unseccessful - 255 - if MMC/SD card was not detected Formats to FAT16 and initializes MMC/SD card. Parameters: Description - port: chip select signal port address. - pin: chip select pin.
CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Fat_Assign Prototype unsigned short Mmc_Fat_Assign(char * filename, char file_cre_attr); - 1 - if file already exists or file does not exist but new file is created. - 0 - if file does not exist and no new file is created. Returns Assigns file for file operations (read, write, delete...). All subsequent file operations will be applied over the assigned file. Parameters: - filename: name of the file that should be assigned for file operations.
CHAPTER 6 mikroC PRO for AVR Libraries Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. Example //Create file with archive attribut if it does not already exists Mmc_Fat_Assign('MIKROELE.TXT',0xA0); Mmc_Fat_Reset Prototype void Mmc_Fat_Reset(unsigned long * size); Returns Nothing. Description Procedure resets the file pointer (moves it to the start of the file) of the assigned file, so that the file can be read.
mikroC PRO for AVR CHAPTER 6 Libraries Mmc_Fat_Read Prototype void Mmc_Fat_Read(unsigned short * bdata); Returns Nothing. Procedure reads the byte at which the file pointer points to and stores data into Description parameter data. The file pointer automatically increments with each call of Mmc_Fat_Read. Requires The file must be assigned, see Mmc_Fat_Assign. Also, file pointer must be initialized; see Mmc_Fat_Reset.
CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Fat_Set_File_Date Prototype void Mmc_Fat_Set_File_Date(unsigned int year, unsigned short month, unsigned short day, unsigned short hours, unsigned short mins, unsigned short seconds); Returns Nothing. Description Writes system timestamp to a file. Use this routine before each writing to file; otherwise, the file will be appended an unknown timestamp. Requires The file must be assigned, see Mmc_Fat_Assign.
mikroC PRO for AVR CHAPTER 6 Libraries Mmc_Fat_Get_File_Size Prototype unsigned long Mmc_Fat_Get_File_Size(); Returns This function returns size of active file (in bytes). Description Retrieves size for currently selected file. Requires The file must be assigned, see Mmc_Fat_Assign. Example // get Date/time of file unsigned yr; char mnth, dat, hrs, mins; ...
CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Fat_Get_Swap_File Prototype Returns unsigned long Mmc_Fat_Get_Swap_File(unsigned long sectors_cnt, char* filename, char file_attr); - Number of the start sector for the newly created swap file, if there was enough free space on the MMC/SD card to create file of required size. - 0 - otherwise. This function is used to create a swap file of predefined name and size on the MMC/SD media.
CHAPTER 6 mikroC PRO for AVR Description Libraries Bit Mask Description 0 0x01 Read Only 1 0x02 Hidden 2 0x04 System 3 0x08 Volume Label 4 0x10 Subdirectory 5 0x20 Archive 6 0x40 Device (internal use only, never found on disk) 7 0x80 Not used Note: Long File Names (LFN) are not supported. Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
CHAPTER 6 mikroC PRO for AVR Libraries // if defined, we have a debug messages on PC terminal #define RS232_debug 1 sbit Mmc_Chip_Select at PORTG.B1; sbit Mmc_Chip_Select_Direction at DDRG.
mikroC PRO for AVR CHAPTER 6 Libraries #ifdef RS232_debug UART1_Write_Text("PIC-Started"); // If PIC present report UART1_Write(13); UART1_Write(10); #endif // Before all, we must initialize a MMC card SPI1_Init_Advanced(_SPI_MASTER, _SPI_FCY_DIV2, _SPI_CLK_LO_LEADING); Spi_Rd_Ptr = SPI1_Read; i = Mmc_Init(); #ifdef RS232_debug if(i == 0) { UART1_Write_Text("MMC Init-OK"); // If MMC present report UART1_Write(13); UART1_Write(10); } if(i) { UART1_Write_Text("MMC Init-error"); // If error report UART1_Wri
CHAPTER 6 mikroC PRO for AVR Libraries UART1_Write(13); } else { UART1_Write_Text("CID-error"); } i == Mmc_Read_Csd(data_for_registers); if(i == 0) { for(k=0; k<=15; k++) { printhex(data_for_registers[k]); if(k!=15) UART1_Write('-'); } UART1_Write(13); UART1_Write(10); } else { UART1_Write_Text("CSD-error"); } #endif // Variables initialisation serial_pointer = 0; // MAIN loop while(1) { if (UART1_Data_Ready()) { serial_buffer[serial_pointer] = UART1_Read(); // Get the received character serial_pointer++
CHAPTER 6 mikroC PRO for AVR Libraries { for(k=0; k<512; k++) { //UART1_Write(dData[k]); // send 512 bytes from MMC card via usart printhex(dData[k]); UART1_Write(' '); if(((k+1) % 16)==0) { UART1_Write(' '); //printhex(k); for(px=(k-15); px<=k; px++) { if((dData[px]>33) && (dData[px]<126)) { UART1_Write(dData[px]); } else { UART1_Write('.
CHAPTER 6 mikroC PRO for AVR Libraries { UART1_Write_Text("Write-error"); UART1_Write(13); UART1_Write(10); } else { UART1_Write_Text("Write-Ok"); UART1_Write(13); UART1_Write(10); } } } if(serial_buffer[0] == 'C') { received_character = serial_buffer[1]; } } } } } 340 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries The next program tests MMC FAT routines. First, we create 5 different files in the root of MMC card, and fill with some information. Then, we read the files and send them via UART for a check. #include sbit Mmc_Chip_Select at PORTG.B1; sbit Mmc_Chip_Select_Direction at DDRG.
CHAPTER 6 Libraries mikroC PRO for AVR //M-M-M--------- Creates many new files and writes data to them void M_Create_Multiple_Files() { for(loop2 = 'B'; loop2 <= 'Z'; loop2++) { UART1_Write(loop2); // signal the progress filename[7] = loop2; // set filename Mmc_Fat_Assign(&filename, 0xA0); // find existing file or create a new one Mmc_Fat_Rewrite(); // To clear file and start with new data for(loop = 1; loop <= 44; loop++) { file_contents[0] = loop / 10 + 48; file_contents[1] = loop % 10 + 48; Mmc_Fat_Wr
CHAPTER 6 mikroC PRO for AVR for (i = 1; i <= size; i++) { Mmc_Fat_Read(&caracter); UART1_Write(caracter); } Libraries // Write data to USART } //M-M-M--------- Deletes a file. If file doesn't exist, it will first be created // and then deleted.
CHAPTER 6 mikroC PRO for AVR Libraries else { //--- file was not found - signal it UART1_Write(0x55); Delay_ms(1000); UART1_Write(0x55); } } //-------------- Tries to create a swap file, whose size will be at least 100 // sectors (see Help for details) void M_Create_Swap_File() { unsigned int i; for(i=0; i<512; i++) Buffer[i] = i; size = Mmc_Fat_Get_Swap_File(5000, "mikroE.
CHAPTER 6 mikroC PRO for AVR Libraries M_Create_New_File(); M_Create_Multiple_Files(); M_Open_File_Rewrite(); M_Open_File_Append(); M_Open_File_Read(); M_Delete_File(); M_Test_File_Exist(); M_Create_Swap_File(); UART1_Write('e'); } else { I_Write_Str(fat_txt); } //--- Test termination PORTC = 0x0F; } MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 345
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection MMC interface MMC back view 346 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries ONEWIRE LIBRARY The OneWire library provides routines for communication via the Dallas OneWire protocol, e.g. with DS18x20 digital thermometer. OneWire is a Master/Slave protocol, and all communication cabling required is a single wire. OneWire enabled devices should have open collector drivers (with single pull-up resistor) on the shared data line. Slave devices on the OneWire bus can even get their power supply from data line.
CHAPTER 6 mikroC PRO for AVR Libraries Library Routines - Ow_Reset - Ow_Read - Ow_Write Ow_Reset Prototype Returns unsigned short Ow_Reset(); - 0 if the device is present - 1 if the device is not present Issues OneWire reset signal for DS18x20. Description Parameters : - None. Devices compliant with the Dallas OneWire protocol. Global variables : Requires - OW_Bit_Read: OneWire read line - OW_Bit_Write: OneWire write line.
CHAPTER 6 mikroC PRO for AVR Libraries Ow_Read Prototype unsigned short Ow_Read(); Returns Data read from an external device over the OneWire bus. Description Reads one byte of data via the OneWire bus. Devices compliant with the Dallas OneWire protocol. Global variables : Requires - OW_Bit_Read: OneWire read line - OW_Bit_Write: OneWire write line. - OW_Bit_Direction: Direction of the OneWire pin must be defined before using this function.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example This example reads the temperature using DS18x20 connected to pin PORTB.2. After reset, MCU obtains temperature from the sensor and prints it on the LCD. Make sure to pull-up PORTB.2 line and to turn off the PORTB leds. // LCD module connections sbit LCD_RS at PORTD.B2; sbit LCD_EN at PORTD.B3; sbit sbit sbit sbit LCD_D4 LCD_D5 LCD_D6 LCD_D7 at at at at PORTD.B4; PORTD.B5; PORTD.B6; PORTD.B7; sbit LCD_RS_Direction at DDRD.
CHAPTER 6 mikroC PRO for AVR Libraries // extract temp_whole temp_whole = temp2write >> RES_SHIFT ; // convert temp_whole to characters if (temp_whole/100) text[0] = temp_whole/100 + 48; text[1] = (temp_whole/10)%10 + 48; text[2] = temp_whole%10 + 48; // Extract tens digit // Extract ones digit // extract temp_fraction and convert it to unsigned int temp_fraction = temp2write << (4-RES_SHIFT); temp_fraction &= 0x000F; temp_fraction *= 625; // convert temp_fraction to characters text[4] = temp_fraction/
CHAPTER 6 mikroC PRO for AVR Libraries //--- Format and display result on Lcd Display_Temperature(temp); Delay_ms(500); } while (1); } HW Connection Example of DS1820 connection 352 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries PORT EXPANDER LIBRARY The mikroC PRO for AVR provides a library for communication with the Microchip’s Port Expander MCP23S17 via SPI interface. Connections of the AVR compliant MCU and MCP23S17 is given on the schematic at the bottom of this page. Note: Library uses the SPI module for communication. The user must initialize SPI module before using the Port Expander Library. Note: Library does not use Port Expander interrupts.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Init Prototype void Expander_Init(char ModuleAddress); Returns Nothing. Initializes Port Expander using SPI communication.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Read_Byte Prototype char Expander_Read_Byte(char ModuleAddress, char RegAddress); Returns Byte read. The function reads byte from Port Expander. Parameters : Description - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - RegAddress: Port Expander's internal register address Requires Port Expander must be initialized. See Expander_Init. Example // Read a byte from Port Expander's register char read_data; ...
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Read_PortA Prototype char Expander_Read_PortA(char ModuleAddress); Returns Byte read. The function reads byte from Port Expander's PortA. Description Parameters : - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Port Expander must be initialized. See Expander_Init. Requires Example Port Expander's PortA should be configured as input. See Expander_Set_DirectionPortA and Expander_Set_DirectionPortAB routines.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Read_PortAB Prototype unsigned int Expander_Read_PortAB(char ModuleAddress); Returns Word read. The function reads word from Port Expander's ports. PortA readings are in the higher byte of the result. PortB readings are in the lower byte of the result. Description Parameters : - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Port Expander must be initialized. See Expander_Init.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Write_PortA Prototype void Expander_Write_PortA(char ModuleAddress, char Data); Returns Nothing. The function writes byte to Port Expander's PortA. Parameters : Description - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data to be written Port Expander must be initialized. See Expander_Init. Requires Port Expander's PortA should be configured as output.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Write_PortB Prototype void Expander_Write_PortB(char ModuleAddress, char Data); Returns Nothing. The function writes byte to Port Expander's PortB. Parameters : Description - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data to be written Port Expander must be initialized. See Expander_Init. Requires Port Expander's PortB should be configured as output.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Write_PortAB Prototype void Expander_Write_PortAB(char ModuleAddress, unsigned int Data); Returns Nothing. The function writes word to Port Expander's ports. Parameters : Description - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data to be written. Data to be written to PortA are passed in Data's higher byte. Data to be written to PortB are passed in Data's lower byte Port Expander must be initialized.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Set_DirectionPortA Prototype void Expander_Set_DirectionPortA(char ModuleAddress, char Data); Returns Nothing. The function sets Port Expander's PortA direction. Parameters : Description - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data to be written to the PortA direction register. Each bit corresponds to the appropriate pin of the PortA register. Set bit designates corresponding pin as input.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Set_DirectionPortAB Prototype void Expander_Set_DirectionPortAB(char ModuleAddress, unsigned int Direction); Returns Nothing. The function sets Port Expander's PortA and PortB direction. Parameters : Description - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Direction: data to be written to direction registers. Data to be written to the PortA direction register are passed in Direction's higher byte.
CHAPTER 6 mikroC PRO for AVR Libraries Expander_Set_PullUpsPortB Prototype void Expander_Set_PullUpsPortB(char ModuleAddress, char Data); Returns Nothing. The function sets Port Expander's PortB pull up/down resistors. Parameters : Description - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data for choosing pull up/down resistors configuration. Each bit corresponds to the appropriate pin of the PortB register.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The example demonstrates how to communicate with Port Expander MCP23S17. Note that Port Expander pins A2 A1 A0 are connected to GND so Port Expander Hardware Address is 0. // Port Expander module connections sbit SPExpanderRST at PORTB.B0; sbit SPExpanderCS at PORTB.B1; sbit SPExpanderRST_Direction at DDRB.B0; sbit SPExpanderCS_Direction at DDRB.
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection Port Expander HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 365
CHAPTER 6 mikroC PRO for AVR Libraries PS/2 LIBRARY The mikroC PRO for AVR provides a library for communication with the common PS/2 keyboard. Note: The library does not utilize interrupts for data retrieval, and requires the oscillator clock to be at least 6MHz. Note: The pins to which a PS/2 keyboard is attached should be connected to the pull-up resistors. Note: Although PS/2 is a two-way communication bus, this library does not provide MCU-to-keyboard communication; e.g.
CHAPTER 6 mikroC PRO for AVR Libraries Ps2_Config Prototype void Ps2_Config(); Returns Nothing. Description Initializes the MCU for work with the PS/2 keyboard. Global variables : Requires - PS2_Data: Data signal line PS2_In_Clock: Clock signal line in PS2_Out_Clock: Clock signal line out PS2_Data_Direction: Direction of the Data pin PS2_Clock_Direction: Direction of the Clock pin must be defined before using this function. Example sbit PS2_Data at PINC.B0; sbit PS2_In_Clock at PINC.
CHAPTER 6 mikroC PRO for AVR Libraries Ps2_Key_Read Prototype Returns unsigned short Ps2_Key_Read(unsigned short *value, unsigned short *special, unsigned short *pressed); - 1 if reading of a key from the keyboard was successful - 0 if no key was pressed The function retrieves information on key pressed. Parameters : Description 368 - value: holds the value of the key pressed. For characters, numerals, punctuation marks, and space value will store the appropriate ASCII code.
CHAPTER 6 mikroC PRO for AVR Libraries Special Function Keys Key Value returned Scroll Lock 28 F1 1 Num Lock 29 F2 2 Left Arrow 30 F3 3 Right Arrow 31 F4 4 Up Arrow 32 F5 5 Down Arrow 33 F6 6 Escape 34 F7 7 Tab 35 F8 8 F9 9 F10 10 F11 11 F12 12 Enter 13 Page Up 14 Page Down 15 Backspace 16 Insert 17 Delete 18 Windows 19 Ctrl 20 Shift 21 Alt 22 Print Screen 23 Pause 24 Caps Lock 25 End 26 Home 27 MIKROELEKTRONIKA - SOFTWARE AND HARDWA
CHAPTER 6 mikroC PRO for AVR Libraries Library Example This simple example reads values of the pressed keys on the PS/2 keyboard and sends them via UART. unsigned short keydata = 0, special = 0, down = 0; sbit PS2_Data at PINC.B0; sbit PS2_In_Clock at PINC.B1; sbit PS2_Out_Clock at PORTC.B1; sbit PS2_Data_Direction at DDRC.B0; sbit PS2_Clock_Direction at DDRC.B1; void main() { ACSR.B7 = 1; SREG.
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection Example of PS2 keyboard connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 371
CHAPTER 6 mikroC PRO for AVR Libraries PWM LIBRARY CMO module is available with a number of AVR MCUs. mikroC PRO for AVR provides library which simplifies using PWM HW Module. Note: For better understanding of PWM module it would be best to start with the example provided in Examples folder of our mikroC PRO for AVR compiler. When you select a MCU, mikroC PRO for AVR automaticaly loads the correct PWM library (or libraries), which can be verified by looking at the Library Manager.
CHAPTER 6 mikroC PRO for AVR Libraries _PWM_PRESCALER_32 Sets prescaler value to 32 (this value is not available on every MCU. Please use Code Assistant to see if this value is available for the given MCU. _PWM_PRESCALER_64 Sets prescaler value to 64. _PWM_PRESCALER_128 Sets prescaler value to 128 (this value is not available on every MCU. Please use Code Assistant to see if this value is available for the given MCU. _PWM_PRESCALER_256 Sets prescaler value to 256.
CHAPTER 6 mikroC PRO for AVR Libraries Note: Not all of the MCUs have both PWM and PWM1 library included. Sometimes, like its the case with ATmega8515, MCU has only PWM library. Therefore constants that have in their name PWM1 are invalid (for ATmega8515) and will not be visible from Code Assistant. It is highly advisable to use this feature, since it handles all the constants (available) nad eliminates any chance of typing error.
mikroC PRO for AVR CHAPTER 6 Libraries Description The N variable represents the prescaler factor (1, 8, 64, 256, or 1024). Some modules also support 32 and 128 prescaler value, but for this you will need to check the datasheet for the desired MCU) PWM_Init must be called before using other functions from PWM Library. You need a CMO on the given MCU (that supports PWM). Requires Before calling this routine you must set the output pin for the PWM (according to the datasheet): DDRB.
CHAPTER 6 mikroC PRO for AVR Libraries PWM_Set_Duty Prototype void PWM_Set_Duty(unsigned short duty); Returns Nothing. Changes PWM duty ratio. Parameter duty takes values from 0 to 255, where 0 Description is 0%, 127 is 50%, and 255 is 100% duty ratio. Other specific values for duty ratio can be calculated as (Percent*255)/100. Requires PWM module must to be initialised (PWM_Init) before using PWM_Set_Duty function.
mikroC PRO for AVR CHAPTER 6 Libraries Note: Not all the AVR MCUs support both PWM and PWM1 library. The best way to verify this is by checking the datasheet for the desired MCU. Also you can check this by selecting a MCU in mikroC PRO for AVR looking at the Library Manager. If library manager loads both PWM and PWM1 library (you are able to check them) then this MCU supports both PWM libraries. Here you can take full advantage of our Code Assistant and Parameter Assistant feature of our compiler.
CHAPTER 6 mikroC PRO for AVR Libraries Description The N variable represents the prescaler factor (1, 8, 64, 256, or 1024). Some modules also support 32 and 128 prescaler value, but for this you will need to check the datasheet for the desired MCU) PWM1_Init must be called before using other functions from PWM Library. You need a CMO on the given MCU (that supports PWM). Requires Before calling this routine you must set the output pin for the PWM (according to the datasheet): DDRD.
mikroC PRO for AVR CHAPTER 6 Libraries PWM1_Set_Duty Prototype void PWM1_Set_Duty(unsigned short duty); Returns Nothing. Changes PWM duty ratio. Parameter duty takes values from 0 to 255, where 0 Description is 0%, 127 is 50%, and 255 is 100% duty ratio. Other specific values for duty ratio can be calculated as (Percent*255)/100. Requires PWM module must to be initialised (PWM1_Init) before using PWM_Set_Duty function.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The example changes PWM duty ratio on pin PB3 continually. If LED is connected to PB3, you can observe the gradual change of emitted light. char current_duty; char current_duty1; void main(){ DDB0 = 0; DDB1 = 0; // Set PORTB pin 0 as input // Set PORTB pin 1 as input DDC0 = 0; DDC1 = 0; // Set PORTC pin 0 as input // Set PORTC pin 1 as input current_duty current_duty1 DDRB.B3 = for the PWM DDRD.
CHAPTER 6 mikroC PRO for AVR Libraries else if (PINC.
CHAPTER 6 mikroC PRO for AVR Libraries PWM 16 BIT LIBRARY CMO module is available with a number of AVR MCUs. mikroC PRO for AVR provides library which simplifies using PWM HW Module. Note: For better understanding of PWM module it would be best to start with the example provided in Examples folder of our mikroC PRO for AVR compiler. When you select a MCU, mikroC PRO for AVR automaticaly loads the correct PWM-16bit library, which can be verified by looking at the Library Manager.
CHAPTER 6 mikroC PRO for AVR Libraries _PWM16_PRESCALER_16bit_1024 Sets prescaler value to 1024. _PWM16_INVERTED Selects the inverted PWM-16bit mode. _PWM16__NON_INVERTED Selects the normal (non inverted) PWM16bit mode. _TIMER1 Selects the Timer/Counter1 (used with PWM16bit_Start and PWM16bit_Stop. _TIMER3 Selects the Timer/Counter3 (used with PWM16bit_Start and PWM16bit_Stop. _TIMER1_CH_A Selects the channel A on Timer/Counter1 (used with PWM16bit_Change_Duty).
CHAPTER 6 mikroC PRO for AVR Libraries PWM16bit_Init Prototype void PWM16bit_Init(unsigned short wave_mode, unsigned short prescaler, unsigned short inverted, unsigned short duty); Returns Nothing. Initializes the PWM module. Parameter wave_mode is a desired PWM-16bit mode.
mikroC PRO for AVR CHAPTER 6 Libraries Description The N variable represents the prescaler factor (1, 8, 64, 256, or 1024). PWM16bit_Init must be called before using other functions from PWM Library. You need a CMO on the given MCU (that supports PWM-16bit). Requires Before calling this routine you must set the output pin for the PWM (according to the datasheet): DDRB.
CHAPTER 6 mikroC PRO for AVR Libraries PWM16bit_Change_Duty Prototype void PWM16bit_Change_Duty(unsigned duty, unsigned short channel); Returns Nothing. Changes PWM duty ratio. Parameter duty takes values shown on the table below. Where 0 is 0%, and TOP value is 100% duty ratio. Other specific values for duty ratio can be calculated as (Percent*TOP)/100.
CHAPTER 6 mikroC PRO for AVR Libraries PWM16bit_Start Prototype void PWM16bit_Start(unsigned int timer); Returns Nothing. Description Starts PWM-16bit module with alredy preset values (wave mode, prescaler, inverted and duty) given in the PWM16bit_Init. Requires MCU must have CMO module to use this library. PWM16bit_Init must be called before using this routine, otherwise it will have no effect as the PWM module is not initialised.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The example changes PWM duty ratio continually by pressing buttons on PORC (03). If LED is connected to PORTB.1 or PORTB.2 ,you can observe the gradual change of emitted light. This example is written for ATmega168. This AVR MCU has only Timer/Counter1 split over two channels A and B. In this example we are changing the duty ratio on both of these channels.
CHAPTER 6 mikroC PRO for AVR Libraries else if (PINC.
CHAPTER 6 mikroC PRO for AVR Libraries RS-485 LIBRARY RS-485 is a multipoint communication which allows multiple devices to be connected to a single bus. The mikroC PRO for AVR provides a set of library routines for comfortable work with RS485 system using Master/Slave architecture. Master and Slave devices interchange packets of information. Each of these packets contains synchronization bytes, CRC byte, address byte and the data. Each Slave has unique address and receives only packets addressed to it.
CHAPTER 6 mikroC PRO for AVR Libraries Library Routines - RS485Master_Init RS485Master_Receive RS485Master_Send RS485Slave_Init RS485Slave_Receive RS485Slave_Send RS485Master_Init Prototype void RS485Master_Init(); Returns Nothing. Description Initializes MCU as a Master for RS-485 communication. Global variables : Requires - RS485_rxtx_pin - this pin is connected to RE/DE input of RS-485 transceiver(see schematic at the bottom of this page).
CHAPTER 6 mikroC PRO for AVR Libraries RS485Master_Receive Prototype void RS485Master_Receive(char *data_buffer); Returns Nothing. Receives messages from Slaves. Messages are multi-byte, so this routine must be called for each byte received. Parameters : Description - data_buffer: 7 byte buffer for storing received data, in the following manner: - data[0..
CHAPTER 6 mikroC PRO for AVR Libraries RS485Master_Send Prototype void RS485Master_Send(char *data_buffer, char datalen, char Slave_address); Returns Nothing. Sends message to Slave(s). Message format can be found at the bottom of this page. Description Parameters : - data_buffer: data to be sent - datalen: number of bytes for transmition. Valid values: 0...3. - Slave_address: Slave(s) address MCU must be initialized as a Master for RS-485 communication. See RS485Master_Init.
CHAPTER 6 mikroC PRO for AVR Libraries RS485Slave_Init Prototype void RS485Slave_Init(char Slave_address); Returns Nothing. Initializes MCU as a Slave for RS-485 communication. Description Parameters : - Slave_address: Slave address Global variables : - RS485_rxtx_pin - this pin is connected to RE/DE input of RS-485 transceiver(see schematic at the bottom of this page). RE/DE signal controls RS-485 transceiver operation mode.
CHAPTER 6 mikroC PRO for AVR Libraries RS485Slave_Receive Prototype void RS485Slave_Receive(char *data_buffer); Returns Nothing. Receives messages from Master. If Slave address and Message address field don't match then the message will be discarded. Messages are multi-byte, so this routine must be called for each byte received. Parameters : Description - data_buffer: 6 byte buffer for storing received data, in the following manner: - data[0..
CHAPTER 6 mikroC PRO for AVR Libraries RS485Slave_Send Prototype void RS485Slave_Send(char *data_buffer, char datalen); Returns Nothing. Sends message to Master. Message format can be found at the bottom of this page. Description Parameters : - data_buffer: data to be sent - datalen: number of bytes for transmition. Valid values: 0...3. Requires Example MCU must be initialized as a Slave for RS-485 communication. See RS485Slave_Init.
CHAPTER 6 mikroC PRO for AVR Libraries char dat[10]; ing messages char i,j; // buffer for receving/send- sbit RS485_rxtx_pin at PORTD.B2; sbit RS485_rxtx_pin_direction at DDRD.
CHAPTER 6 mikroC PRO for AVR Libraries if (dat[5]) { // if an error detected, signal it PORTC = dat[5]; // by setting PORTC } if (dat[4]) { // if message received successfully cnt = 0; dat[4] = 0; // clear message received flag j = dat[3]; for (i = 1; i <= dat[3]; i++) { // show data on PORTB PORTB = dat[i-1]; } // increment received dat[0] dat[0] = dat[0]+1; // send back to Slave Delay_ms(1); RS485Master_Send(dat,1,160); } if (cnt > 100000) { // if in 100000 poll-cycles the answer PORTA++; // was not de
CHAPTER 6 mikroC PRO for AVR Libraries // Pass pointers to UART functions of used UART module UART_Wr_Ptr = UART1_Write; UART_Rd_Ptr = UART1_Read; UART_Rdy_Ptr = UART1_Data_Ready; UART_TX_Idle = UART1_TX_Idle; UART1_Init(9600); Delay_ms(100); RS485Slave_Init(160); dat[4] = 0; dat[5] = 0; dat[6] = 0; SREG_I = 1; RXCIE = 1; // initialize UART1 module // Intialize MCU as Slave, address 160 // ensure that message received flag is 0 // ensure that message received flag is 0 // ensure that error flag is 0 //
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection Example of interfacing PC to AVR MCU via RS485 bus with LTC485 as RS-485 transceiver 400 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroC PRO for AVR Libraries Message format and CRC calculations Q: How is CRC checksum calculated on RS485 Master side? START_BYTE = 0x96; // 10010110 STOP_BYTE = 0xA9; // 10101001 PACKAGE: -------START_BYTE 0x96 ADDRESS DATALEN [DATA1] [DATA2] [DATA3] CRC STOP_BYTE 0xA9 // if exists // if exists // if exists DATALEN bits -----------bit7 = 1 MASTER SENDS 0 SLAVE SENDS bit6 = 1 ADDRESS WAS XORed with 1, IT WAS EQUAL STOP_BYTE 0 ADDRESS UNCHANGED bit5 = 0 FIXED bit4 = 1 DATA3 (if exists) WAS X
CHAPTER 6 mikroC PRO for AVR Libraries Software I²C Library The mikroC PRO for AVR provides routines for implementing Software I˛C communication. These routines are hardware independent and can be used with any MCU. The Software I˛C library enables you to use MCU as Master in I˛C communication. Multi-master mode is not supported. Note: This library implements time-based activities, so interrupts need to be disabled when using Software I˛C.
CHAPTER 6 mikroC PRO for AVR Libraries Library Routines - Soft_I2C_Init Soft_I2C_Start Soft_I2C_Read Soft_I2C_Write Soft_I2C_Stop Soft_I2C_Break Soft_I2C_Init Prototype void Soft_I2C_Init(); Returns Nothing. Description Configures the software I2C module.
CHAPTER 6 mikroC PRO for AVR Libraries Soft_I2C_Start Prototype void Soft_I2C_Start(void); Returns Nothing. Description Determines if the I2C bus is free and issues START signal. Requires Software I2C must be configured before using this function. See Soft_I2C_Init routine. Example // Issue START signal Soft_I2C_Start(); Soft_I2C_Read Prototype unsigned short Soft_I2C_Read(unsigned int ack); Returns One byte from the Slave. Reads one byte from the slave.
CHAPTER 6 mikroC PRO for AVR Libraries Soft_I2C_Write Prototype unsigned short Soft_I2C_Write(unsigned short Data_);b - 0 if there were no errors. - 1 if write collision was detected on the I˛C bus. Returns Sends data byte via the I˛C bus. Description Parameters : - Data: data to be sent Soft I˛C must be configured before using this function. See Soft_I2C_Init routine. Requires Example Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine.
CHAPTER 6 mikroC PRO for AVR Libraries Soft_I2C_Break Prototype void Soft_I2C_Break(void); Returns Nothing. Description All Software I2C Library functions can block the program flow (see note at the top of this page). Call this routine from interrupt to unblock the program execution. This mechanism is similar to WDT. Note: Interrupts should be disabled before using Software I2C routins again (see note at the top of this page). Requires Nothing.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The example demonstrates Software I˛C Library routines usage. The AVR MCU is connected (SCL, SDA pins) to PCF8583 RTC (real-time clock). Program reads date and time are read from the RTC and prints it on LCD. char seconds, minutes, hours, day, month, year; variables // Global date/time // Software I2C connections sbit Soft_I2C_Scl_Output at PORTC.B0; sbit Soft_I2C_Sda_Output at PORTC.B1; sbit Soft_I2C_Scl_Input at PINC.
CHAPTER 6 mikroC PRO for AVR Libraries } //-------------------- Formats date and time void Transform_Time() { seconds = ((seconds & 0xF0) >> 4)*10 + (seconds & 0x0F); Transform seconds minutes = ((minutes & 0xF0) >> 4)*10 + (minutes & 0x0F); Transform months hours = ((hours & 0xF0) >> 4)*10 + (hours & 0x0F); Transform hours year = (day & 0xC0) >> 6; Transform year day = ((day & 0x30) >> 4)*10 + (day & 0x0F); Transform day month = ((month & 0x10) >> 4)*10 + (month & 0x0F); Transform month } // // // // /
CHAPTER 6 mikroC PRO for AVR Libraries Lcd_Out(1,1,"Date:"); Lcd_Chr(1,8,':'); Lcd_Chr(1,11,':'); Lcd_Out(2,1,"Time:"); Lcd_Chr(2,8,':'); Lcd_Chr(2,11,':'); Lcd_Out(1,12,"200"); // Prepare and output static text on LCD } //----------------- Main procedure void main() { Init_Main(); // Perform initialization while (1) { Read_Time(); Transform_Time(); Display_Time(); Delay_ms(1000); // Endless loop // Read time from RTC(PCF8583) // Format date and time // Prepare and display on LCD // Wait 1 second } }
CHAPTER 6 mikroC PRO for AVR Libraries SOFTWARE SPI LIBRARY The mikroC PRO for AVR provides routines for implementing Software SPI communication. These routines are hardware independent and can be used with any MCU. The Software SPI Library provides easy communication with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc. Library configuration: - SPI to Master mode Clock value = 20 kHz. Data sampled at the middle of interval. Clock idle state low.
CHAPTER 6 mikroC PRO for AVR Libraries Library Routines - Soft_SPI_Init - Soft_SPI_Read - Soft_SPI_Write Soft_SPI_Init Prototype void Soft_SPI_Init(); Returns Nothing. Description Configures and initializes the software SPI module.
CHAPTER 6 mikroC PRO for AVR Libraries Soft_SPI_Read Prototype unsigned short Soft_SPI_Read(char sdata); Returns Byte received via the SPI bus. This routine performs 3 operations simultaneously. It provides clock for the Software SPI bus, reads a byte and sends a byte. Description Parameters : - sdata: data to be sent. Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init routine. Example unsigned short data_read; char data_send; ...
CHAPTER 6 mikroC PRO for AVR Libraries Library Example This code demonstrates using library routines for Soft_SPI communication. Also, this example demonstrates working with Microchip's MCP4921 12-bit D/A converter. // DAC module connections sbit Chip_Select at PORTB.B0; sbit SoftSpi_CLK at PORTB.B7; sbit SoftSpi_SDI at PINB.B6; // Note: Input signal sbit SoftSpi_SDO at PORTB.
CHAPTER 6 mikroC PRO for AVR Libraries void main() { InitMain(); value = 2048; // Perform main initialization // When program starts, DAC gives // the output in the mid-range while (1) { if ((PINA.B0) && (value < 4095)) { value++; } else { if ((PINA.
CHAPTER 6 mikroC PRO for AVR Libraries SOFTWARE UART LIBRARY The mikroC PRO for AVR provides routines for implementing Software UART communication. These routines are hardware independent and can be used with any MCU. The Software UART Library provides easy communication with other devices via the RS232 protocol. Note: The Software UART library implements time-based activities, so interrupts need to be disabled when using it.
CHAPTER 6 mikroC PRO for AVR Libraries Soft_UART_Init Prototype Returns char Soft_UART_Init(unsigned long baud_rate, char inverted); - 2 - error, requested baud rate is too low - 1 - error, requested baud rate is too high - 0 - successfull initialization Configures and initializes the software UART module. Parameters : Description - baud_rate: baud rate to be set. Maximum baud rate depends on the MCU’s clock and working conditions. - inverted: inverted output flag.
CHAPTER 6 mikroC PRO for AVR Libraries Soft_UART_Read Prototype char Soft_UART_Read(char * error); Returns Byte received via UART. The function receives a byte via software UART. This is a blocking function call (waits for start bit). Programmer can unblock it by calling Soft_UART_Break routine. Description Parameters : - error: Error flag. Error code is returned through this variable.
CHAPTER 6 mikroC PRO for AVR Libraries Soft_UART_Write Prototype void Soft_UART_Write(char udata); Returns Nothing. This routine sends one byte via the Software UART bus. Description Parameters : - udata: data to be sent. Software UART must be initialized before using this function. See the Soft_UART_Init routine. Requires Example 418 Be aware that during transmission, software UART is incapable of receiving data – data transfer protocol must be set in such a way to prevent loss of information.
CHAPTER 6 mikroC PRO for AVR Libraries Soft_UART_Break Prototype void Soft_UART_Break(); Returns Nothing. Description Soft_UART_Read is blocking routine and it can block the program flow. Call this routine from interrupt to unblock the program execution. This mechanism is similar to WDT. Note: Interrupts should be disabled before using Software UART routines again (see note at the top of this page). Requires Nothing.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example This example demonstrates simple data exchange via software UART. If MCU is connected to the PC, you can test the example from the mikroC PRO for AVR USART Terminal Tool. // Soft UART connections sbit Soft_UART_Rx_Pin at PIND.B0; sbit Soft_UART_Tx_Pin at PORTD.B1; sbit Soft_UART_Rx_Pin_Direction at DDRD.B0; sbit Soft_UART_Tx_Pin_Direction at DDRD.
CHAPTER 6 mikroC PRO for AVR Libraries SOUND LIBRARY The mikroC PRO for AVR provides a Sound Library to supply users with routines necessary for sound signalization in their applications. Sound generation needs additional hardware, such as piezo-speaker (example of piezo-speaker interface is given on the schematic at the bottom of this page).
CHAPTER 6 mikroC PRO for AVR Libraries Sound_Init Prototype void Sound_Init(); Returns Nothing. Description Configures the appropriate MCU pin for sound generation. Global variables: Requires - Sound_Play_Pin: Sound output pin - Sound_Play_Pin_Direction: Direction of the Sound output pin must be defined before using this function. Example // Sound library connections sbit Sound_Play_Pin at PORTC.B3; sbit Sound_Play_Pin_direction at DDRC.B3; // End of Sound library connections ...
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker. // Sound connections sbit Sound_Play_Pin at PORTC.B3; sbit Sound_Play_Pin_direction at DDRC.
CHAPTER 6 mikroC PRO for AVR Libraries void main() { DDRB = 0x00; Sound_Init(); Sound_Play(500, 1000); while (1) { // Configure PORTB as input // Initialize sound pin // Play starting sound, 2kHz, 1 second // endless loop if (PINB.B7) Tone1(); while (PINB.B7) ; // If PORTB.7 is pressed play Tone1 // // Wait for button to be released if (PINB.B6) Tone2(); while (PINB.B6) ; // If PORTB.6 is pressed play Tone2 // // Wait for button to be released if (PINB.B5) Tone3(); while (PINB.B5) ; // If PORTB.
CHAPTER 6 mikroC PRO for AVR Libraries HW Connection Example of Sound Library connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 425
CHAPTER 6 mikroC PRO for AVR Libraries SPI LIBRARY mikroC PRO for AVR provides a library for comfortable with SPI work in Master mode. The AVR MCU can easily communicate with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc. Note: Some AVR MCU's have alternative SPI ports, which SPI signals can be redirected to by setting or clearing SPIPS (SPI Pin Select) bit of the MCUCR register. Please consult the appropriate datasheet.
CHAPTER 6 mikroC PRO for AVR Libraries SPI1_Init_Advanced Prototype void SPI1_Init_Advanced(char mode, char fcy_div, char clock_and_edge) Returns Nothing. Configures and initializes SPI. SPI1_Init_Advanced or SPI1_Init needs to be called before using other functions of SPI Library.
CHAPTER 6 mikroC PRO for AVR Libraries Requires MCU must have SPI module. Example // Set SPI to the Master Mode, clock = Fosc/32 , clock idle level is high, data sampled on falling edge: SPI1_Init_Advanced(_SPI_MASTER, _SPI_FCY_DIV32, _SPI_CLK_HI_TRAILING); SPI1_Read Prototype char SPI1_Read(char buffer); Returns Received data. Reads one byte from the SPI bus.
CHAPTER 6 mikroC PRO for AVR Libraries Library Example The code demonstrates how to use SPI library functions for communication between SPI module of the MCU and MAX7219 chip. MAX7219 controls eight 7 segment displays. // DAC module connections sbit Chip_Select at PORTB.B0; sbit Chip_Select_Direction at DDRB.
CHAPTER 6 mikroC PRO for AVR Libraries if ((PINA.B0) && (value < 4095)) { value++; } else { if ((PINA.
CHAPTER 6 mikroC PRO for AVR Libraries SPI ETHERNET LIBRARY The ENC28J60 is a stand-alone Ethernet controller with an industry standard Serial Peripheral Interface (SPI™). It is designed to serve as an Ethernet network interface for any controller equipped with SPI. The ENC28J60 meets all of the IEEE 802.3 specifications. It incorporates a number of packet filtering schemes to limit incoming packets.
CHAPTER 6 mikroC PRO for AVR Libraries External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Ethernet Library: extern sfr sbit SPI_Ethernet_CS; extern sfr sbit SPI_Ethernet_RST; extern sfr sbit SPI_Ethernet_CS_Direc tion; Description: Example : sbit SPI_Ethernet_CS ENC28J60 chip select pin. at PORTB.B4; sbit SPI_Ethernet_RST at PORTB.B5; sbit Direction of the ENC28J60 SPI_Ethernet_CS_Direc chip select pin. tion at DDRB.B4; ENC28J60 reset pin.
CHAPTER 6 mikroC PRO for AVR Libraries Library Routines - SPI_Ethernet_Init SPI_Ethernet_Enable SPI_Ethernet_Disable SPI_Ethernet_doPacket SPI_Ethernet_putByte SPI_Ethernet_putBytes SPI_Ethernet_putString SPI_Ethernet_putConstString SPI_Ethernet_putConstBytes SPI_Ethernet_getByte SPI_Ethernet_getBytes SPI_Ethernet_UserTCP SPI_Ethernet_UserUDP The following routines are for the internal use by compiler only: - SPI_Ethernet_arpResolve SPI_Ethernet_checksum SPI_Ethernet_clearBitReg SPI_Ethernet_confNetwo
CHAPTER 6 mikroC PRO for AVR Libraries - SPI_Ethernet_renewDHCP SPI_Ethernet_sendUDP SPI_Ethernet_sendUDP2 SPI_Ethernet_setBitReg SPI_Ethernet_setRxReadAddress SPI_Ethernet_TXpacket SPI_Ethernet_writeAddr SPI_Ethernet_writeMem SPI_Ethernet_writeMemory SPI_Ethernet_writeMemory2 SPI_Ethernet_writePHY SPI_Ethernet_writeReg SPI_Ethernet_Init Prototype void SPI_Ethernet_Init(unsigned char *mac, unsigned char *ip, unsigned char fullDuplex); Returns Nothing. This is MAC module routine.
CHAPTER 6 mikroC PRO for AVR Libraries The appropriate hardware SPI module must be previously initialized. Requires Global variables : - SPI_Ethernet_CS: Chip Select line - SPI_Ethernet_CS_Direction: Direction of the Chip Select pin - SPI_Ethernet_RST: Reset line - SPI_Ethernet_RST_Direction: Direction of the Reset pin must be defined before using this function. #define SPI_Ethernet_HALFDUPLEX #define SPI_Ethernet_FULLDUPLEX 0 1 // mE ethernet NIC pinout sfr sbit SPI_Ethernet_Rst at PORTB.
CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_Enable Prototype void SPI_Ethernet_Enable(unsigned char enFlt) ; Returns Nothing. This is MAC module routine. This routine enables appropriate network traffic on the ENC28J60 module by the means of it's receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic will be enabled if a corresponding bit of this routine's input parameter is set. Therefore, more than one type of network traffic can be enabled at the same time.
CHAPTER 6 mikroC PRO for AVR Libraries Requires Ethernet module has to be initialized. See SPI_Ethernet_Init. Example SPI_Ethernet_Enable(SPI_Ethernet_CRC | SPI_Ethernet_UNICAST); // enable CRC checking and Unicast traffic SPI_Ethernet_Disable Prototype void SPI_Ethernet_Disable(unsigned char disFlt) ; Returns Nothing. This is MAC module routine. This routine disables appropriate network traffic on the ENC28J60 module by the means of it's receive filters (unicast, multicast, broadcast, crc).
CHAPTER 6 mikroC PRO for AVR Libraries Note: This routine will change receive filter configuration on-the-fly. It will not, in any way, mess with enabling/disabling receive/transmit logic or any other part of Description the ENC28J60 module. The ENC28J60 module should be properly cofigured by the means of SPI_Ethernet_Init routine. Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_putByte Prototype void SPI_Ethernet_putByte(unsigned char v); Returns Nothing. This is MAC module routine. It stores one byte to address pointed by the current ENC28J60 write pointer (EWRPT). Description Parameters: - v: value to store Requires Ethernet module has to be initialized. See SPI_Ethernet_Init. Example char data; ...
CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_putConstBytes Prototype void SPI_Ethernet_putConstBytes(const unsigned char *ptr, unsigned char n); Returns Nothing. This is MAC module routine. It stores requested number of const bytes into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location. Description Parameters: - ptr: const buffer containing bytes to be written into ENC28J60 RAM. - n: number of bytes to be written. Requires Ethernet module has to be initialized.
CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_putConstString Prototype unsigned int SPI_Ethernet_putConstString(const unsigned char *ptr); Returns Number of bytes written into ENC28J60 RAM. This is MAC module routine. It stores whole const string (excluding null termination) into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location. Description Parameters: - ptr: const string to be written into ENC28J60 RAM. Requires Ethernet module has to be initialized.
CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_getBytes Prototype void SPI_Ethernet_getBytes(unsigned char *ptr, unsigned int addr, unsigned char n); Returns Nothing. This is MAC module routine. It fetches equested number of bytes from ENC28J60 RAM starting from given address. If value of 0xFFFF is passed as the address parameter, the reading will start from current ENC28J60 read pointer (ERDPT) location. Description Parameters: - ptr: buffer for storing bytes read from ENC28J60 RAM.
CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_UserTCP Prototype Returns unsigned int SPI_Ethernet_UserTCP(unsigned char *remoteHost, unsigned int remotePort, unsigned int localPort, unsigned int reqLength); - 0 - there should not be a reply to the request. - Length of TCP/HTTP reply data field - otherwise. This is TCP module routine. It is internally called by the library. The user accesses to the TCP/HTTP request by using some of the SPI_Ethernet_get routines.
CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_UserUDP Prototype unsigned int SPI_Ethernet_UserUDP(unsigned char *remoteHost, unsigned int remotePort, unsigned int destPort, unsigned int reqLength); - 0 - there should not be a reply to the request. - Length of UDP reply data field - otherwise. Returns This is UDP module routine. It is internally called by the library. The user accesses to the UDP request by using some of the SPI_Ethernet_get routines.
CHAPTER 6 mikroC PRO for AVR // duplex config flags #define Spi_Ethernet_HALFDUPLEX #define Spi_Ethernet_FULLDUPLEX Libraries 0x00 0x01 // half duplex // full duplex // mE ehternet NIC pinout sfr sbit SPI_Ethernet_Rst at PORTB.B4; sfr sbit SPI_Ethernet_CS at PORTB.B5; sfr sbit SPI_Ethernet_Rst_Direction at DDRB.B4; sfr sbit SPI_Ethernet_CS_Direction at DDRB.
CHAPTER 6 mikroC PRO for AVR Libraries const char *indexPage2 = "
|