mikroBasic PRO for AVR March 2009. Reader’s note DISCLAIMER: Reader’s Note mikroBasic PRO for AVR and this manual are owned by mikroElektronika and are protected 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.
Table of Contents CHAPTER 1 Introduction CHAPTER 2 mikroBasic PRO for AVR Environment CHAPTER 3 mikroBasic PRO for AVR Specifics CHAPTER 4 AVR Specifics CHAPTER 5 mikroBasic PRO for AVR Language Reference CHAPTER 6 mikroBasic PRO for AVR Libraries
mikroBasic PRO for AVR Table of Contents CHAPTER 1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Where to Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 mikroElektronika Associates License Statement and Limited Warranty . . . . . 4 IMPORTANT - READ CAREFULLY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 This license statement and limited warranty constitute a legal agree .
mikroBasic PRO for AVR Table of Contents Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Styles Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Tools Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Project Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Run Menu Options . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR Special Function Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Summarizes all Special Funct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 General Purpose Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 ROM Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 ROM Memory Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents Metacharacters - Backreferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 mikroBasic PRO for AVR Command Line Options . . . . . . . . . . . . . . . . . . . . . 67 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 New Project Wizard Steps . . . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR Basic Standard Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Divergence from the Basic Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Basic Language Exstensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Predefined Globals and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 SFRs and related constants . . . . . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents "Dead code" ellimination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Stack allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Local vars optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Better code generation and local optimization . . . . . . . . . . . . . . . . . . . 101 Types Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR String Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Case Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents Function Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Example: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Example: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Forward declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Types . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents ADC_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 This example code reads a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 CANSPI Library . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR Cf_Write_Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 Cf_Fat_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Cf_Fat_QuickFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Cf_Fat_Assign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Cf_Fat_Reset . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents Glcd_Write_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Glcd_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Glcd_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 Glcd_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 Glcd_V_Line . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR Man_Receive_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 Man_Receive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Man_Send_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Man_Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Man_Synchro . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents Ow_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Ow_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 Port Expander Library . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR PWM_Set_Duty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 PWM_Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 PWM_Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 PWM1_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 PWM1_Set_Duty . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents Soft_I2C_Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 Soft_I2C_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 Soft_I2C_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 Soft_I2C_Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 Soft_I2C_Break . . . . . . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR SPI Ethernet Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 External dependencies of SPI Ethernet Library . . . . . . . . . . . . . . . . . . 368 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Spi_Ethernet_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Spi_Ethernet_Enable . . . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents SPI_Glcd_Set_Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 SPI_Glcd_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 SPI_Glcd_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 SPI_Glcd_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 Library Example . . . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR SPI_T6963C_WriteCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424 SPI_T6963C_SetPtr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424 SPI_T6963C_WaitReady . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424 SPI_T6963C_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 SPI_T6963C_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents T6963C_WriteData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 T6963C_WriteCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 T6963C_SetPtr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 T6963C_WaitReady . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 T6963C_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR TWI_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466 TWI_Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 TWI_Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 TWI_Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 Library Example . . . . . . . . . . .
mikroBasic PRO for AVR Table of Contents acos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . asin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . atan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . atan2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ceil . . . . . . . . . . . . . . .
Table of Contents mikroBasic PRO for AVR strncmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 strncpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 strpbrk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 strrchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 strspn . . . . . . .
CHAPTER 1 Introduction to mikroBasic PRO for AVR The mikroBasic 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 mikroBasic PRO for AVR Introduction mikroBasic PRO for AVR IDE Features mikroBasic PRO for AVR allows you to quickly develop and deploy complex applications: - Write your Basic source code using the built-in Code Editor (Code and Parameter Assistants, Code Folding, Syntax Highlighting, Spell Checker, Auto Correct, Code Templates, and more.) - Use included mikroBasic PRO libraries to dramatically speed up the development: data acquisition, memory, displays, conversions, communication etc.
CHAPTER 1 mikroBasic PRO for AVR Introduction Where to Start - In case that you’re a beginner in programming AVR microcontrollers, read carefully the AVR Specifics chapter. It might give you some useful pointers on AVR constraints, code portability, and good programming practices. - If you are experienced in Basic programming, you will probably want to consult mikroBasic PRO for AVR Specifics first. For language issues, you can always refer to the comprehensive Language Reference.
CHAPTER 1 mikroBasic 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.
CHAPTER 1 mikroBasic PRO for AVR 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 mikroBasic 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 physi
CHAPTER 1 mikroBasic PRO for AVR 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 mikroBasic 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 mikroBasic PRO for AVR Introduction HOW TO REGISTER The latest version of the mikroBasic 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.
CHAPTER 1 mikroBasic PRO for AVR Introduction MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 9
CHAPTER 1 mikroBasic PRO for AVR 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 2 mikroBasic PRO for AVR Environment The mikroBasic PRO for AVR is an user-friendly and intuitive environment: 11
CHAPTER 2 mikroBasic PRO for AVR Environment IDE OVERVIEW - The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Spell Checker, 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.
CHAPTER 2 mikroBasic PRO for AVR Environment MAIN MENU OPTIONS Available Main Menu options are: Related topics: Keyboard shortcuts MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 13
CHAPTER 2 mikroBasic 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 mikroBasic PRO for AVR Environment EDIT MENU OPTIONS File 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. 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.
CHAPTER 2 mikroBasic PRO for AVR Environment File 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. Indent selected code. Outdent selected code. Changes selected text case to lowercase. Changes selected text case to uppercase. Changes selected text case to titlercase. Find Text Dialog box for searching the document for the specified text. The search is performed in the direction specified.
CHAPTER 2 mikroBasic 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.
CHAPTER 2 mikroBasic PRO for AVR Environment VIEW MENU OPTIONS File 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 mikroBasic 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.
CHAPTER 2 mikroBasic 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 mikroBasic 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 mikroBasic 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. View watch window View stopwatch window Styles Toolbar Styles toolbar allows you to easily customize your workspace.
CHAPTER 2 mikroBasic PRO for AVR Environment 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 mikroBasic PRO for AVR Environment PROJECT MENU OPTIONS 24 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 2 mikroBasic 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 mikroBasic PRO for AVR Environment RUN MENU OPTIONS File 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 Basic source and disassembly.
CHAPTER 2 mikroBasic 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 mikroBasic PRO for AVR Environment HELP MENU OPTIONS File Description Open 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 mikroBasic PRO for AVR Environment KEYBOARD SHORTCUTS Below is a complete list of keyboard shortcuts available in mikroBasic PRO for AVR IDE. You can also view keyboard shortcuts in the Code Explorer window, tab Keyboard.
CHAPTER 2 mikroBasic PRO for AVR Environment Software Simulator Shortcuts 30 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
CHAPTER 2 mikroBasic PRO for AVR Environment IDE OVERVIEW The mikroBasic PRO for AVR is an user-friendly and intuitive environment: - The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Spell Checker, 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.
CHAPTER 2 mikroBasic PRO for AVR 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 mikroBasic 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 mikroBasic 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 mikroBasic 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.
CHAPTER 2 mikroBasic PRO for AVR 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 mikroBasic 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 mikroBasic 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 mikroBasic PRO for AVR Environment Spell Checker The Spell Checker underlines unknown objects in the code, so it 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. Bookmarks Bookmarks make navigation through a large code easier. To set a bookmark, use Ctrl+Shift+number. To jump to a bookmark, use Ctrl+number.
CHAPTER 2 mikroBasic 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 mikroBasic 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.
CHAPTER 2 mikroBasic PRO for AVR 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. Following options are available in the Project Manager: Icon Description Save project Group. Open project group.
CHAPTER 2 mikroBasic 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 mikroBasic 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 mikroBasic 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 mikroBasic 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 mikroBasic 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 mikroBasic 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.
CHAPTER 2 mikroBasic PRO for AVR 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 mikroBasic PRO for AVR Environment ROM Memory Allocation Displays ROM memory allocation. Procedures Windows Provides overview procedures locations and sizes. Procedures Size Window Displays size of each procedure.
CHAPTER 2 mikroBasic PRO for AVR Environment Procedures Locations Window Displays how functions are distributed in microcontroller’s memory. HTML Window Display statistics in default web browser.
CHAPTER 2 mikroBasic PRO for AVR Environment INTEGRATED TOOLS USART Terminal The mikroBasic 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 52 from Tools toolbar.
CHAPTER 2 mikroBasic 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 mikroBasic 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 mikroBasic PRO for AVR IDE - project_name.hex file will be loaded automatically while ihex file must be loaded manually.
CHAPTER 2 mikroBasic 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 Decoder or by clicking the Seven Segment Icon from Tools toolbar.
CHAPTER 2 mikroBasic PRO for AVR Environment UDP Terminal The mikroBasic PRO for AVR includes the UDP Terminal. You can launch it from the drop-down menu Tools › UDP Terminal.
CHAPTER 2 mikroBasic PRO for AVR Environment Graphic Lcd Bitmap Editor The mikroBasic PRO for AVR includes the Graphic Lcd Bitmap Editor. Output is the mikroBasic PRO for AVR compatible code. You can launch it from the drop-down menu Tools › Glcd Bitmap Editor.
CHAPTER 2 mikroBasic PRO for AVR Environment Lcd Custom Character mikroBasic PRO for AVR includes the Lcd Custom Character. Output is mikroBasic PRO for AVR compatible code. You can launch it from the drop-down menu Tools › Lcd Custom Character.
CHAPTER 2 mikroBasic 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 mikroBasic PRO for AVR 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 mikroBasic 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 mikroBasic 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 mikroBasic PRO for AVR specifics). Build all files as library enables user to use compiled library (*.
CHAPTER 2 mikroBasic 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 mikroBasic PRO for AVR Environment 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. but not 'countbr', 'countcr', etc. count[^aeiou]r finds strings 'countbr', 'countcr', etc. but not 'countar', 'counter', etc.
CHAPTER 2 mikroBasic PRO for AVR Environment 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.r - matches strings like 'PORTA', 'PORTB', 'PORT1' and so on The "^" metacharacter by default is only guaranteed to match beginning of the input string/text, and the "$" metacharacter only at the end.
CHAPTER 2 mikroBasic PRO for AVR Environment Metacharacters - Iterators Any item of a regular expression may be followed by another type of metacharacters - iterators. Using this metacharacters,you can specify number of occurences of previous character, metacharacter or subexpression.
CHAPTER 2 mikroBasic PRO for AVR Environment Metacharacters - Alternatives You can specify a series of alternatives for a pattern using "|" to separate them, so that bit|bat|bot will match any of "bit", "bat", or "bot" in the target string as would "b(i|a|o)t)". The first alternative includes everything from the last pattern delimiter ("(", "[", or the beginning of the pattern) up to the first "|", and the last alternative contains everything from the last "|" to the next pattern delimiter.
CHAPTER 2 mikroBasic PRO for AVR Environment MIKROBASIC PRO FOR AVR COMMAND LINE OPTIONS Usage: mBAvr.exe [- [-]] [ [-]] [-]] Infile can be of *.mbas and *.mcl 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 mikroBasic PRO for AVR Environment PROJECTS The mikroBasic PRO for AVR organizes applications into projects, consisting of a single project file (extension .mcpav) and one or more source files (extension ). mikroBasic 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.
CHAPTER 2 mikroBasic PRO for AVR 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 mikroBasic PRO for AVR Environment Step Two - Enter the oscillator frequency value. Step Three - Specify the location where your project will be saved.
CHAPTER 2 mikroBasic PRO for AVR 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 mikroBasic 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.
CHAPTER 2 mikroBasic PRO for AVR Environment The list of relevant source files is stored in the project file (extension .mbpav). 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 . Note: For inclusion of the module files, use the include clause. See File Inclusion for more information.
CHAPTER 2 mikroBasic PRO for AVR Environment SOURCE FILES Source files containing Basic code should have the extension .mbas. The list of source files relevant to the application is stored in project file with extension .mbpav, along with other project information. You can compile source files only if they are part of the project. Managing Source Files Creating new source file To create a new source file, do the following: 1.
CHAPTER 2 mikroBasic PRO for AVR Environment Saving file 1. Make sure that the window containing the file that you want to save is the active window. 2. Select File › Save from the drop-down menu, or press Ctrl+S, or click the Save File Icon from the File Toolbar. Saving file under a different name 1. Make sure that the window containing the file that you want to save is the active window. 2. Select File › Save As from the drop-down menu. The New File Name dialog will be displayed. 3.
CHAPTER 2 mikroBasic PRO for AVR Environment CLEAN PROJECT FOLDER Clean Project Folder This menu gives you option to choose which files from your current project you want to delete. Files marked in bold can be easily recreated by building a project. Other files should be marked for deletion only with a great care, because IDE cannot recover them.
CHAPTER 2 mikroBasic 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 mikroBasic PRO for AVR Environment ERROR MESSAGES Compiler Error Messages: - "%s"is not valid identifier. - Unknown type "%s". - Identifier "%s" was not declared. - Syntax error: Expected "%s" but "%s" found. - Argument is out of range "%s". - Syntax error in additive expression. - File "%s" not found. - Invalid command "%s". - Not enough parameters. - Too many parameters. - Too many characters. - Actual and formal parameters must be identical. - Invalid ASM instruction: "%s".
CHAPTER 2 mikroBasic PRO for AVR Environment - Operator "%s" not applicable to these operands "%s". - Exit cannot be called from the main block. - Complex type parameter must be passed by reference. - Error occured while compiling "%s". - Recursive types are not allowed. - Adding strings is not allowed, use "strcat" procedure instead. - Cannot declare pointer to array, use pointer to structure which has array field. - Return value of the function "%s" is not defined.
CHAPTER 2 mikroBasic PRO for AVR Environment SOFTWARE SIMULATOR OVERVIEW The Source-level Software Simulator is an integral component of the mikroBasic PRO for AVR environment. It is designed to simulate operations of the AVR MCUs and assist the users in debugging Basic code written for these devices.
CHAPTER 2 mikroBasic PRO for AVR Remove All Button Environment 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. 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.
CHAPTER 2 mikroBasic PRO for AVR Environment Stopwatch Window The Software Simulator Stopwatch Window is available from the drop-down menu, View › Debug Windows › Stopwatch. The Stopwatch Window displays a current count of cycles/time since the last Software Simulator action. Stopwatch measures the execution time (number of cycles) from the moment Software Simulator has started and can be reset at any time.
CHAPTER 2 mikroBasic 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 mikroBasic PRO for AVR Environment SOFTWARE SIMULATOR OPTIONS Name Description Function Toolbar Key Icon 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 mikroBasic PRO for AVR Environment CREATING NEW LIBRARY mikroBasic PRO for AVR allows you to create your own libraries. In order to create a library in mikroBasic PRO for AVR follow the steps bellow: 1. Create a new Basic source file, see Managing Source Files 2. Save the file in one of the subfolders of the compiler's Uses folder (LTE64kW or GT64kW, see note on the end of the page): DriveName:\Program Files\Mikroelektronika\mikroBasic PRO for AVR\Uses\LTE64kW\__Lib_Example.mbas 3.
CHAPTER 2 mikroBasic PRO for AVR Environment Multiple Library Versions Library Alias represents unique name that is linked to corresponding Library .mcl file. For example UART library for ATMEGA16 is different from UART library for ATMEGA128 MCU. Therefore, two different UART Library versions were made, see mlk files for these two MCUs. Note that these two libraries have the same Library Alias (UART) in both mlk files.
CHAPTER 3 mikroBasic PRO for AVR Specifics The following topics cover the specifics of mikroBasic PRO for AVR compiler: - Basic Standard Issues - Predefined Globals and Constants - Accessing Individual Bits - Interrupts - AVR Pointers - Linker Directives - Built-in Routines - Code Optimization 87
CHAPTER 3 mikroBasic PRO for AVR Specifics BASIC STANDARD ISSUES Divergence from the Basic Standard Function recursion is not supported because of no easily-usable stack and limited memory AVR Specific Basic Language Exstensions mikroBasic PRO for AVR has additional set of keywords that do not belong to the standard Basic language keywords: - code data io rx register at sbit bit sfr Related topics: Keywords, AVR Specific 88 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 3 mikroBasic PRO for AVR Specifics PREDEFINED GLOBALS AND CONSTANTS In order to facilitate AVR programming, mikroBasic PRO for AVR implements a number of predefined globals and constants. SFRs and related constants All AVR SFRs are implicitly declared as global variables of volatile word type. These identifiers have an external linkage, and are visible in the entire project. When creating a project, the mikroBasic PRO for AVR will include an appropriate (*.
CHAPTER 3 mikroBasic PRO for AVR Specifics ACCESSING INDIVIDUAL BITS The mikroBasic 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 To access the individual bits, simply use the direct member selector (.) with a variable, followed by one of identifiers B0, B1, … , B7, or 0, 1, … 7, with 7 being the most significant bit : // Clear bit 0 on PORTA PORTA.B0 = 0 // Clear bit 5 on PORTB PORTB.
CHAPTER 3 mikroBasic PRO for AVR Specifics bit type The mikroBasic PRO for AVR 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. dim bf as bit ' bit variable There are no pointers to bit variables: dim ptr as ^bit ' invalid An array of type bit is not valid: dim arr as array[5] of bit ' invalid Note : - Bit variables can not be initialized. - Bit variables can not be members of structures.
CHAPTER 3 mikroBasic 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.
CHAPTER 3 mikroBasic PRO for AVR Specifics These principles can be explained on the picture below : Direct accessing interrupt service routine and accessing interrupt service routine via Goto table.
CHAPTER 3 mikroBasic PRO for AVR Specifics LINKER DIRECTIVES mikroBasic PRO for AVR uses internal algorithm to distribute objects within memory. If you need to have a variable or routine at the specific predefined address, use the linker directives absolute and org. Note: You must specify an even address when using the linker directives. Directive absolute The directive absolute specifies the starting address in RAM for a variable.
CHAPTER 3 mikroBasic PRO for AVR Specifics BUILT-IN ROUTINES The mikroBasic 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 mikroBasic PRO for AVR Specifics Lo Prototype sub function Lo(number as longint) as byte Returns Lowest 8 bits (byte) of number, bits 7..0. Function returns 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 mikroBasic PRO for AVR Specifics Highest Prototype sub function Highest(number as longint) as byte Returns Returns the highest byte of number, bits 24..31. Function returns the highest 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.
CHAPTER 3 mikroBasic PRO for AVR Specifics Delay_us Prototype sub procedure Delay_us(const time_in_us as longword) 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 mikroBasic PRO for AVR Specifics Delay_Cyc Prototype sub procedure Delay_Cyc(Cycles_div_by_10 as byte) 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 mikroBasic PRO for AVR Specifics SetFuncCall Prototype sub procedure SetFuncCall(FuncName as string) Returns Nothing. Function informs the linker about a specific routine being called. SetFuncCall has to be called in a routine which accesses another routine via a pointer. Description Function prepares the caller tree, and informs linker about the procedure usage, making it possible to link the called routine. 100 Requires Nothing. Example sub procedure first(p, q as byte) ...
CHAPTER 3 mikroBasic PRO for AVR Specifics CODE OPTIMIZATION Optimizer has been added to extend the compiler usability, cut down the amount of code generated and speed-up its execution. The main features are: Constant folding All expressions that can be evaluated in the compile time (i.e. are constant) are being replaced by their results.
CHAPTER 3 Specifics 102 mikroBasic 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 mikroBasic PRO for AVR 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 mikroBasic PRO for AVR 8051 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.
CHAPTER 4 mikroBasic PRO for AVR 8051 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 8051 Specifics mikroBasic PRO for AVR 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. Due to the complexity, some AVR microcontrollers with more peripherals have Extended I/O memory, which occupies part of the internal SRAM.
CHAPTER 4 mikroBasic PRO for AVR 8051 Specifics MEMORY TYPE SPECIFIERS The mikroBasic 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 register Memory type specifiers can be included in variable declaration.
CHAPTER 4 mikroBasic PRO for AVR 8051 Specifics io Description This memory specifier allows user to access the I/O Memory space. Example ' put io_buff in io memory space dim io_buff as byte io sfr This memory specifier in combination with (rx, io, data) allows user to Description access special function registers. It also instructs compiler to maintain same identifier in Basic and assembly.
CHAPTER 5 mikroBasic PRO for AVR Language Reference The mikroBasic PRO for AVR Language Reference describes the syntax, semantics and implementation of the mikroBasic PRO for AVR language. The aim of this reference guide is to provide a more understandable description of the mikroBasic PRO for AVR language to the user.
CHAPTER 5 mikroBasic PRO for AVR Language Reference MIKROBASIC PRO FOR AVR LANGUAGE REFERENCE Lexical Elements Whitespace Comments Tokens Literals Keywords Identifiers Punctuators Program Organization Program Organization Scope and Visibility Modules Variables Constants Labels Symbols Functions and Procedures Functions Procedures Types Simple Types Arrays Strings Pointers Structures Types Conversions Implicit Conversion Explicit Conversion Operators Introduction to Operators Operators Precedence and Assoc
CHAPTER 5 mikroBasic PRO for AVR Language Reference If Statement Select Case Statement Iteration Statements (Loops) For Statement While Statement Do Statement Jump Statements Break and Continue Statements Exit Statement Goto Statement Gosub Statement asm Statement Directives Compiler Directives Linker Directives LEXICAL ELEMENTS OVERVIEW These topics provide a formal definition of the mikroBasic PRO for AVR lexical elements.
CHAPTER 5 mikroBasic PRO for AVR Language Reference WHITESPACE Whitespace is a collective name given to spaces (blanks), horizontal and vertical tabs, and comments. Whitespace serves to indicate where tokens start and end, but beyond this function, any surplus whitespace is discarded. For example, the two sequences dim tmp as byte dim j as word and dim dim tmp j as as byte word are lexically equivalent and parse identically.
CHAPTER 5 mikroBasic PRO for AVR Language Reference COMMENTS Comments are pieces of text used to annotate a program, and are technically another form of whitespace. Comments are for the programmer’s use only; they are stripped from the source text before parsing. Use the apostrophe to create a comment: ' Any text between an apostrophe and the end of the ' line constitutes a comment. May span one line only.
CHAPTER 5 mikroBasic PRO for AVR Language Reference LITERALS Literals are tokens representing fixed numeric or character values. The data type of a constant is deduced by the compiler using such clues as numeric value and format used in the source code. Integer Literals Integral values can be represented in decimal, hexadecimal or binary notation.
CHAPTER 5 mikroBasic PRO for AVR Language Reference mikroBasic PRO limits floating-point constants to the range of ±1.17549435082 * 10-38 .. ±6.80564774407 * 1038. Here are some examples: 0. -1.23 23.45e6 2e-5 3E+10 .09E34 ' ' ' ' ' ' = = = = = = 0.0 -1.23 23.45 * 10^6 2.0 * 10^-5 3.0 * 10^10 0.09 * 10^34 Character Literals Character literal is one character from the extended ASCII character set, enclosed with quotes (for example, "A").
CHAPTER 5 mikroBasic PRO for AVR Language Reference KEYWORDS Keywords are special-purpose words which cannot be used as normal identifier names. Beside standard BASIC keywords, all relevant SFR are defined as global variables and represent reserved words that cannot be redefined (for example: P0, TMR1, T1CON, etc). Probe Code Assistant for specific letters (Ctrl+Space in Editor) or refer to Predefined Globals and Constants.
CHAPTER 5 mikroBasic 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 be confused with the meaning of object in object-oriented programming). Identifiers can contain letters from a to z and A to Z, the underscore character “_” and digits from 0 to 9.
CHAPTER 5 mikroBasic PRO for AVR Language Reference PUNCTUATORS The mikroBasic PRO punctuators (also known as separators) are: - [ ] – Brackets ( ) – Parentheses , – Comma : – Colon . – Dot Brackets Brackets [ ] indicate single and multidimensional array subscripts: dim alphabet as byte[30] ' ... alphabet[2] = "c" For more information, refer to Arrays.
CHAPTER 5 mikroBasic PRO for AVR Language Reference Colon Colon (:) is used to indicate a labeled statement: start: nop '... goto start For more information, refer to Labels. Dot Dot (.) indicates access to a structure member. For example: person.surname = "Smith" For more information, refer to Structures. Dot is a necessary part of floating point literals. Also, dot can be used for accessing individual bits of registers in mikroBasic PRO.
CHAPTER 5 mikroBasic PRO for AVR Language Reference PROGRAM ORGANIZATION mikroBasic PRO for AVR imposes strict program organization. Below you can find models for writing legible and organized source files. For more information on file inclusion and scope, refer to Modules and to Scope and Visibility. Organization of Main Module Basically, a main source file has two sections: declaration and program body. Declarations should be in their proper place in the code, organized in an orderly manner.
CHAPTER 5 mikroBasic PRO for AVR Language Reference Organization of Other Modules Modules other than main start with the keyword module. Implementation section starts with the keyword implements. Follow the model presented below: module include '******************************************************** '* Interface (globals): '******************************************************** ' symbols declarations symbol ... ' constants declarations const ...
CHAPTER 5 Language Reference mikroBasic PRO for AVR ' procedures declarations sub procedure sub_procedure_name([dim byref] [const] ParamName as [^]type, [dim byref] [const] ParamName2, ParamName3 as [^]type); [ilevel 0x123] [overload] [forward] ... end sub ' functions declarations sub function sub_function_name([dim byref] [const] ParamName as [^]type, [dim byref] [const] ParamName2, ParamName3 as [^]type) as [^]type [ilevel 0x123] [overload] [forward] ...
CHAPTER 5 mikroBasic PRO for AVR Language Reference SCOPE AND VISIBILITY Scope The scope of identifier is a part of the program in which the identifier can be used to access its object. There are different categories of scope, depending on how and where identifiers are declared: Place of declaration Scope Scope extends from the point where it is Identifier is declared in the declared to the end of the current file, including declaration section of the main all routines enclosed within that scope.
CHAPTER 5 Language Reference mikroBasic PRO for AVR MODULES In mikroBasic PRO for AVR, each project consists of a single project file and one or more module files. The project file, with extension .mbpav contains information on the project, while modules, with extension .mbas, contain the actual source code. See Program Organization for a detailed look at module arrangement.
CHAPTER 5 mikroBasic PRO for AVR Language Reference Main Module Every project in mikroBasic PRO for AVR requires a single main module file. The main module is identified by the keyword program at the beginning. It instructs the compiler where to “start”. After you have successfully created an empty project with Project Wizard, Code Editor will display a new main module. It contains the bare-bones of the program: program MyProject ' main procedure main: ' Place program code here end.
CHAPTER 5 Language Reference mikroBasic PRO for AVR Implementation Section Implementation section hides all the irrelevant innards from other modules, allowing encapsulation of code. Everything declared below the keyword implements is private, i.e. has its scope limited to the file. When you declare an identifier in the implementation section of a module, you cannot use it outside the module, but you can use it in any block or routine defined within the module.
CHAPTER 5 mikroBasic PRO for AVR Language Reference VARIABLES Variable is an object whose value can be changed during the runtime. Every variable is declared under unique name which must be a valid identifier. This name is used for accessing the memory location occupied by the variable. Variables are declared in the declaration part of the file or routine — each variable needs to be declared before it is used.
CHAPTER 5 Language Reference mikroBasic PRO for AVR CONSTANTS Constant is a data whose value cannot be changed during the runtime. Using a constant in a program consumes no RAM memory. Constants can be used in any expression, but cannot be assigned a new value. Constants are declared in the declaration part of the program or routine, with the following syntax: const constant_name [as type] = value Every constant is declared under unique constant_name which must be a valid identifier.
CHAPTER 5 mikroBasic PRO for AVR Language Reference LABELS Labels serve as targets for the goto and gosub statements. Mark the desired statement with label and colon like this: label_identifier : statement No special declaration of label is necessary in mikroBasic PRO for AVR. Name of the label needs to be a valid identifier. The labeled statement and goto/gosub statement must belong to the same block. Hence it is not possible to jump into or out of routine.
CHAPTER 5 mikroBasic PRO for AVR Language Reference SYMBOLS mikroBasic PRO symbols allow you to create simple macros without parameters. You can replace any line of code with a single identifier alias. Symbols, when properly used, can increase code legibility and reusability. Symbols need to be declared at the very beginning of the module, right after the module name and (optional) include clauses. Check Program Organization for more details.
CHAPTER 5 mikroBasic PRO for AVR Language Reference FUNCTIONS AND PROCEDURES Functions and procedures, collectively referred to as routines, are subprograms (self-contained statement blocks) which perform a certain task based on a number of input parameters. When executed, a function returns value while procedure does not.
CHAPTER 5 Language Reference mikroBasic PRO for AVR Example Here’s a simple function which calculates xn based on input parameters x and n (n > 0): sub function power(dim x, n as byte) as longint dim i as byte result = 1 if n > 0 then for i = 1 to n result = result*x next i end if end sub Now we could call it to calculate, say, 312: tmp = power(3, 12) PROCEDURES Procedure is declared like this: sub procedure procedure_name(parameter_list) [ local declarations ] procedure body end sub procedure_name rep
CHAPTER 5 mikroBasic PRO for AVR Language Reference Example Here’s an example procedure which transforms its input time parameters, preparing them for output on Lcd: sub procedure time_prep(dim sec = ((sec and $F0) >> min = ((min and $F0) >> hr = ((hr and $F0) >> end sub byref 4)*10 4)*10 4)*10 sec, min, hr as byte) + (sec and $0F) + (min and $0F) + (hr and $0F) Function Pointers Function pointers are allowed in mikroBasic PRO for AVR.
CHAPTER 5 mikroBasic PRO for AVR Language Reference ' main program: main: MyPtr = @Func1 Sample = MyPtr^(1, 2, 3) Func1, the return value is MyPtr = @Func2 Sample = MyPtr^(1, 2, 3) Func2, the return value is MyPtr = @Func3 Sample = MyPtr^(1, 2, 3) Func3, the return value is end.
CHAPTER 5 mikroBasic PRO for AVR Language Reference Forward declaration A function can be declared without having it followed by it's implementation, by having it followed by the forward procedure. The effective implementation of that function must follow later in the module. The function can be used after a forward declaration as if it had been implemented already.
CHAPTER 5 mikroBasic PRO for AVR Language Reference TYPES Basic is strictly typed language, which means that every variable and constant need to have a strictly defined type, known at the time of compilation. The type serves: - to determine correct memory allocation required, - to interpret the bit patterns found in the object during subsequent accesses, - in many type-checking situations, to ensure that illegal assignments are trapped.
CHAPTER 5 mikroBasic PRO for AVR Language Reference SIMPLE TYPES Simple types represent types that cannot be divided into more basic elements and are the model for representing elementary data on machine level. Basic memory unit in mikroBasic PRO for AVR has 8 bits. Here is an overview of simple types in mikroBasic PRO for AVR: Type Size Range byte, char 8–bit 0 .. 255 short 8–bit -127 .. 128 word 16–bit 0 .. 65535 integer 16–bit -32768 .. 32767 longword 32–bit 0 ..
CHAPTER 5 Language Reference mikroBasic PRO for AVR ARRAYS An array represents an indexed collection of elements of the same type (called the base type). Since each element has a unique index, arrays, unlike sets, can meaningfully contain the same value more than once. Array Declaration Array types are denoted by constructions in the following form: type[array_length] Each of elements of an array is numbered from 0 through array_length - 1.
CHAPTER 5 mikroBasic PRO for AVR Language Reference STRINGS A string represents a sequence of characters equivalent to an array of char. It is declared like this: string[string_length] The specifier string_length is a number of characters a string consists of. The string is stored internally as the given sequence of characters plus a final null character (zero). This appended “stamp” does not count against string’s total length. A null string ("") is stored as a single null character.
CHAPTER 5 Language Reference mikroBasic PRO for AVR POINTERS A pointer is a data type which holds a memory address. While a variable accesses that memory address directly, a pointer can be thought of as a reference to that memory address. To declare a pointer data type, add a carat prefix (^) before type. For example, if you are creating a pointer to an integer, you would write: ^integer To access the data at the pointer’s memory location, you add a carat after the variable name.
CHAPTER 5 mikroBasic PRO for AVR Language Reference STRUCTURES A structure represents a heterogeneous set of elements. Each element is called a member; the declaration of a structure type specifies a name and type for each member. The syntax of a structure type declaration is structure structname dim member1 as type1 '... dim membern as typen end structure where structname is a valid identifier, each type denotes a type, and each member is a valid identifier.
CHAPTER 5 mikroBasic PRO for AVR Language Reference Structure Member Access You can access the members of a structure by means of dot (.) as a direct member selector. If we had declared the variables circle1 and circle2 of the previously defined type Circle: dim circle1, circle2 as Circle we could access their individual members like this: circle1.radius = 3.7 circle1.center.x = 0 circle1.center.
CHAPTER 5 mikroBasic PRO for AVR Language Reference TYPES CONVERSIONS Conversion of variable of one type to variable of another type is typecasting. mikroBasic PRO for AVR supports both implicit and explicit conversions for built-in types.
CHAPTER 5 mikroBasic PRO for AVR Language Reference Clipping In assignments and statements that require an expression of particular type, destination will store the correct value only if it can properly represent the result of expression, i.e. if the result fits in destination range. If expression evaluates to more complex type than expected excess data will be simply clipped (the higher bytes are lost). dim i as byte dim j as word '...
CHAPTER 5 mikroBasic PRO for AVR Language Reference OPERATORS Operators are tokens that trigger some computation when being applied to variables and other objects in an expression. There are four types of operators in mikroBasic PRO for AVR: - Arithmetic Operators - Bitwise Operators - Boolean Operators - Relational Operators OPERATORS PRECEDENCE AND ASSOCIATIVITY There are 4 precedence categories in mikroBasic PRO for AVR. Operators in the same category have equal precedence with each other.
CHAPTER 5 mikroBasic PRO for AVR Language Reference ARITHMETIC OPERATORS Arithmetic operators are used to perform mathematical computations. They have numerical operands and return numerical results. Since the char operators are technically bytes, they can be also used as unsigned operands in arithmetic operations. All arithmetic operators associate from left to right.
CHAPTER 5 mikroBasic PRO for AVR Language Reference RELATIONAL OPERATORS Use relational operators to test equality or inequality of expressions. All relational operators return TRUE or FALSE. Operator = <> Operation equal not equal > greater than < less than >= greater than or equal <= less than or equal All relational operators associate from left to right. Relational Operators in Expressions The equal sign (=) can also be an assignment operator, depending on context.
CHAPTER 5 mikroBasic PRO for AVR Language Reference BITWISE OPERATORS Use the bitwise operators to modify the individual bits of numerical operands. Bitwise operators associate from left to right. The only exception is the bitwise complement operator not which associates from right to left.
CHAPTER 5 mikroBasic PRO for AVR Language Reference $1234 and $5678 ' equals $1230 ' because .. ' $1234 : 0001 0010 0011 0100 ' $5678 : 0101 0110 0111 1000 ' ---------------------------' and : 0001 0010 0011 0000 ' .. that is, $1230' Similarly: $1234 or $5678 $1234 xor $5678 not $1234 ' equals $567C ' equals $444C ' equals $EDCB Unsigned and Conversions If number is converted from less complex to more complex data type, the upper bytes are filled with zeroes.
CHAPTER 5 mikroBasic PRO for AVR Language Reference Bitwise Shift Operators The binary operators << and >> move the bits of the left operand by a number of positions specified by the right operand, to the left or right, respectively. Right operand has to be positive and less than 255. With shift left (<<), left most bits are discarded, and “new” bits on the right are assigned zeroes.
CHAPTER 5 mikroBasic PRO for AVR Language Reference EXPRESSIONS An expression is a sequence of operators, operands, and punctuators that returns a value. The primary expressions include: literals, constants, variables and function calls. From them, using operators, more complex expressions can be created. Formally, expressions are defined recursively: subexpressions can be nested up to the limits of memory.
CHAPTER 5 mikroBasic PRO for AVR Language Reference STATEMENTS Statements define algorithmic actions within a program. Each statement needs to be terminated with a semicolon (;). In the absence of specific jump and selection statements, statements are executed sequentially in the order of appearance in the source code. The most simple statements are assignments, procedure calls and jump statements. These can be combined to form loops, branches and other structured statements.
CHAPTER 5 mikroBasic PRO for AVR Language Reference CONDITIONAL STATEMENTS Conditional or selection statements select from alternative courses of action by testing certain values. There are two types of selection statements: - if - select case IF STATEMENT Use the keyword if to implement a conditional statement. The syntax of the if statement has the following form: if expression then statements [else other statements] end if When expression evaluates to true, statements execute.
CHAPTER 5 Language Reference mikroBasic PRO for AVR In order to force the compiler to interpret our example the other way around, we have to write it explicitly: if expression1 then if expression2 then statement1 end if else statement2 end if SELECT CASE STATEMENT Use the select case statement to pass control to a specific program branch, based on a certain condition. The select case statement consists of selector expression (condition) and list of possible values.
CHAPTER 5 mikroBasic PRO for AVR Language Reference Also, you can group values together for a match. Simply separate the items by commas: select case reg case 0 opmode = 0 case 1,2,3,4 opmode = 1 case 5,6,7 opmode = 2 end select Nested Case Statements Note that the select case statements can be nested – values are then assigned to the innermost enclosing select case statement. ITERATION STATEMENTS Iteration statements let you loop a set of statements.
CHAPTER 5 Language Reference mikroBasic PRO for AVR FOR STATEMENT The for statement implements an iterative loop and requires you to specify the number of iterations. The syntax of the for statement is: for counter = initial_value to final_value [step step_value] statements next counter counter is a variable being increased by step_value with each iteration of the loop. The parameter step_value is an optional integral value, and defaults to 1 if omitted.
CHAPTER 5 mikroBasic PRO for AVR Language Reference WHILE STATEMENT Use the while keyword to conditionally iterate a statement. The syntax of the while statement is: while expression statements wend statements are executed repeatedly as long as expression evaluates true. The test takes place before statements are executed. Thus, if expression evaluates false on the first pass, the loop does not execute.
CHAPTER 5 mikroBasic PRO for AVR Language Reference DO STATEMENT The do statement executes until the condition becomes true. The syntax of the do statement is: do statements loop until expression statements are executed repeatedly until expression evaluates true. expression is evaluated after each iteration, so the loop will execute statements at least once.
CHAPTER 5 mikroBasic PRO for AVR Language Reference BREAK AND CONTINUE STATEMENTS Break Statement Sometimes, you might need to stop the loop from within its body. Use the break statement within loops to pass control to the first statement following the innermost loop (for, while, or do). For example: Lcd_Out(1, 1, "No card inserted") ' Wait for CF card to be plugged; refresh every second while true if Cf_Detect() = 1 then break end if Delay_ms(1000) wend ' Now we can work with CF card ...
CHAPTER 5 Language Reference mikroBasic PRO for AVR EXIT STATEMENT The exit statement allows you to break out of a routine (function or procedure). It passes the control to the first statement following the routine call. Here is a simple example: sub procedure Proc1() dim error as byte ... ' we're doing something here if error = TRUE then exit end if ...
CHAPTER 5 mikroBasic PRO for AVR Language Reference GOTO STATEMENT Use the goto statement to unconditionally jump to a local label — for more information, refer to Labels. The syntax of the goto statement is: goto label_name This will transfer control to the location of a local label specified by label_name. The goto line can come before or after the label. Label and goto statement must belong to the same block. Hence it is not possible to jump into or out of a procedure or function.
CHAPTER 5 Language Reference mikroBasic PRO for AVR GOSUB STATEMENT Use the gosub statement to unconditionally jump to a local label — for more information, refer to Labels. The syntax of the gosub statement is: gosub label_name ... label_name: ... return This will transfer control to the location of a local label specified by label_name. Also, the calling point is remembered. Upon encountering the return statement, program execution will continue with the next statement (line) after gosub.
CHAPTER 5 mikroBasic PRO for AVR Language Reference ASM STATEMENT mikroBasic PRO for AVR allows embedding assembly in the source code by means of the asm statement. Note that you cannot use numerals as absolute addresses for register variables in assembly instructions. You may use symbolic names instead (listing will display these names as well as addresses).
CHAPTER 5 mikroBasic PRO for AVR Language Reference DIRECTIVES Directives are words of special significance which provide additional functionality regarding compilation and output. The following directives are at your disposal: - Compiler directives for conditional compilation, - Linker directives for object distribution in memory. COMPILER DIRECTIVES Any line in source code with leading # is taken as a compiler directive. The initial # can be preceded or followed by whitespace (excluding new lines).
CHAPTER 5 mikroBasic PRO for AVR Language Reference #IFDEF flag THEN block of code [ #ELSEIF flag_1 THEN block of code 1 ... #ELSEIF flag_n THEN block of code n ] [ #ELSE alternate block of code ] #ENDIF First, #IFDEF checks if flag is set by means of #DEFINE. If so, only block of code will be compiled. Otherwise, the compiler will check flags flag_1 .. flag_n and execute the appropriate block of code i. Eventually, if none of the flags is set, alternate block of code in #ELSE (if any) will be compiled.
CHAPTER 5 Language Reference mikroBasic PRO for AVR LINKER DIRECTIVES mikroBasic PRO for AVR uses internal algorithm to distribute objects within memory. If you need to have a variable or routine at the specific predefined address, use the linker directives absolute and org. Note: You must specify an even address when using the linker directives. Directive absolute The directive absolute specifies the starting address in RAM for a variable.
CHAPTER 6 mikroBasic PRO for AVR Libraries mikroBasic 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 mikroBasic PRO for AVR Libraries in you project.
CHAPTER 6 mikroBasic 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 - S
CHAPTER 6 mikroBasic PRO for AVR Libraries LIBRARY DEPENDENCIES Certain libraries use (depend on) function and/or variables, constants defined in other libraries. Image below shows clear representation about these dependencies. For example, SPI_Glcd uses Glcd_Fonts and Port_Expander library which uses SPI library. This means that if you check SPI_Glcd library in Library manager, all libraries on which it depends will be checked too.
CHAPTER 6 mikroBasic 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 sub function ADC_Read(dim channel as byte) as word 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 mikroBasic PRO for AVR Libraries HW Connection ADC HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 171
CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPI LIBRARY The SPI module is available with a number of the AVR compliant MCUs. The mikroBasic 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 mikroBasic PRO for AVR Libraries External dependencies of CANSPI Library The following variables must be defined in all projects using CANSPI Library: dim CanSpi_CS as sbit sfr external dim CanSpi_Rst as sbit sfr external dim CanSpi_CS_Bit_Directi on as sbit sfr external Description: Example : Reset line. dim CanSpi_CS as sbit at PORTB.B0 dim CanSpi_Rst as sbit at PORTB.B2 Direction of the Chip Select pin. dim CanSpi_CS_Bit_Directi on as sbit at DDRB.B0 Chip Select line.
CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPISetOperationMode Prototype sub procedure CANSPISetOperationMode(dim mode as byte, dim WAIT as byte) 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 nonblocking.
CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPIInitialize Prototype sub procedure CANSPIInitialize(dim SJW as byte, dim BRP as byte, dim PHSEG1 as byte, dim PHSEG2 as byte, dim PROPSEG as byte, dim CAN_CONFIG_FLAGS as byte) Returns Nothing. Initializes the CANSPI module.
CHAPTER 6 mikroBasic PRO for AVR Libraries ' CANSPI module connections dim CanSpi_CS as sbit at PORTB.B0 CanSpi_CS_Direction as sbit at DDRB.B0 CanSpi_Rst as sbit at PORTB.B2 CanSpi_Rst_Direction as sbit at DDRB.B2 ' End CANSPI module connections ... Example 176 dim Can_Init_Flags as byte ... Can_Init_Flags = CAN_CONFIG_SAMPLE_THRICE and ' form value to be used CAN_CONFIG_PHSEG2_PRG_ON and ' with CANSPIInitialize CAN_CONFIG_XTD_MSG and CAN_CONFIG_DBL_BUFFER_ON and CAN_CONFIG_VALID_XTD_MSG ...
CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPISetBaudRate Prototype sub procedure CANSPISetBaudRate(dim SJW as byte, dim BRP as byte, dim PHSEG1 as byte, dim PHSEG2 as byte, dim PROPSEG as byte, dim CAN_CONFIG_FLAGS as byte) 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 sub function when the CANSPI module is in Config mode. SAM, SEG2PHTS and WAKFIL bits are set according to CAN_CONFIG_FLAGS value.
CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPISetMask Prototype sub procedure CANSPISetMask(dim CAN_MASK as byte, dim val as longint, dim CAN_CONFIG_FLAGS as byte) Returns Nothing. Configures mask for advanced filtering of messages. The parameter value is bit-adjusted to the appropriate mask registers. Parameters: - CAN_MASK: CANSPI module mask number.
CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPISetFilter Prototype sub procedure CANSPISetFilter(dim CAN_FILTER as byte, dim val as longint, dim CAN_CONFIG_FLAGS as byte) 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 mikroBasic PRO for AVR Libraries CANSPIRead Prototype sub function CANSPIRead(dim byref id as longint, dim byref rd_data as byte[8], dim data_len as byte, dim CAN_RX_MSG_FLAGS as byte) as byte - 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
CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPIWrite Prototype Returns sub function CANSPIWrite(dim id as longint, dim byref wr_data as byte[8], dim data_len as byte, dim CAN_TX_MSG_FLAGS as byte) as byte - 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 sub function sends message in the queue for transmission. Parameters: Description - id:CAN message identifier.
CHAPTER 6 mikroBasic 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 mikroBasic PRO for AVR Libraries CANSPI_CONFIG_DBL_BUFFER_BIT CANSPI_CONFIG_DBL_BUFFER_ON CANSPI_CONFIG_DBL_BUFFER_OFF as byte = $10 as byte = $FF as byte = $EF ' 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 as as as as as ' ' ' ' byte byte byte byte byte = = = = = $60 $FF $DF $BF $9F X11XXXXX X10XXXXX X01XXXXX X00XXXXX You may use bitwise and to form config byte out of these values.
CHAPTER 6 mikroBasic 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 otherwise it will be FALSE.
CHAPTER 6 mikroBasic PRO for AVR const CANSPI_FILTER_B1_F1 CANSPI_FILTER_B1_F2 CANSPI_FILTER_B2_F1 CANSPI_FILTER_B2_F2 CANSPI_FILTER_B2_F3 CANSPI_FILTER_B2_F4 Libraries as as as as as as byte byte byte byte byte byte = = = = = = 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. The second node responds by sending back the data incremented by 1.
CHAPTER 6 mikroBasic PRO for AVR Libraries SPI1_Init() ' initialize SPI1 module Spi_Rd_Ptr = @SPI1_Read Pass pointer to SPI Read sub function of used SPI module CANSPIInitialize(1,3,3,3,1,Can_Init_Flags) Initialize external CANSPI module CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF) set CONFIGURATION mode CANSPISetMask(_CANSPI_MASK_B1,-1,_CANSPI_CONFIG_XTD_MSG) set all mask1 bits to ones CANSPISetMask(_CANSPI_MASK_B2,-1,_CANSPI_CONFIG_XTD_MSG) set all mask2 bits to ones CANSPISetFilter(_CANSPI_FILTER_B
CHAPTER 6 mikroBasic PRO for AVR Libraries ' CANSPI module connections dim CanSpi_CS as sbit at PORTB.B0 CanSpi_CS_Direction as sbit at DDRB.B0 CanSpi_Rst as sbit at PORTB.B2 CanSpi_Rst_Direction as sbit at DDRB.
CHAPTER 6 mikroBasic PRO for AVR Libraries while TRUE ' endless loop Msg_Rcvd = CANSPIRead(Rx_ID , RxTx_Data , Rx_Data_Len, Can_Rcv_Flags) ' receive message if ((Rx_ID = 12111) and Msg_Rcvd) then ' if message received check id PORTC = RxTx_Data[0] ' id correct, output data at PORTC Inc(RxTx_Data[0]) ' increment received data CANSPIWrite(Tx_ID, RxTx_Data, 1, Can_Send_Flags) ' send incremented data back end if wend end.
CHAPTER 6 mikroBasic PRO for AVR 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 the microcontroller applications. In CF card, data is divided into sectors. One sector usually comprises 512 bytes.
CHAPTER 6 mikroBasic PRO for AVR Libraries External dependencies of Compact Flash Library The following variables must be defined in all projects using Compact Flash Library: dim CF_Data_Port as byte sfr external dim CF_Data_Port_Direction as byte sfr external dim CF_RDY as sbit sfr external dim CF_WE as sbit sfr external dim CF_OE as sbit sfr external dim CF_CD1 as sbit sfr external dim CF_CE1 as sbit sfr external dim CF_A2 as sbit sfr external dim CF_A1 as sbit sfr external dim CF_A0 as sbit sfr external
CHAPTER 6 mikroBasic PRO for AVR Libraries Library Routines - Cf_Init Cf_Detect Cf_Enable Cf_Disable Cf_Read_Init Cf_Read_Byte Cf_Write_Init Cf_Write_Byte Cf_Read_Sector Cf_Write_Sector Routines for file handling: - Cf_Fat_Init Cf_Fat_QuickFormat Cf_Fat_Assign Cf_Fat_Reset Cf_Fat_Read Cf_Fat_Rewrite Cf_Fat_Append Cf_Fat_Delete Cf_Fat_Write Cf_Fat_Set_File_Date Cf_Fat_Get_File_Date Cf_Fat_Get_File_Size Cf_Fat_Get_Swap_File MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 191
CHAPTER 6 mikroBasic PRO for AVR Libraries Cf_Init Prototype sub procedure Cf_Init() Returns Nothing. Description Initializes ports appropriately for communication with CF card.
CHAPTER 6 mikroBasic PRO for AVR Libraries Cf_Detect Prototype Returns sub function CF_Detect() as byte - 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: while (Cf_Detect() = 0) nop wend Cf_Enable Prototype sub procedure Cf_Enable() Returns Nothing. Enables the device.
CHAPTER 6 mikroBasic PRO for AVR Libraries Cf_Read_Init Prototype sub procedure Cf_Read_Init(dim address as longword, dim sector_count as byte) 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 mikroBasic PRO for AVR Libraries Cf_Write_Init Prototype sub procedure Cf_Write_Init(dim address as longword, dim sectcnt as byte) 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 mikroBasic PRO for AVR Libraries Cf_Read_Sector Prototype sub procedure Cf_Read_Sector(dim sector_number as longword, dim byref buffer as byte[512]) 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 mikroBasic PRO for AVR Libraries Cf_Fat_Init Prototype Returns sub function Cf_Fat_Init() as byte - 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 data needed by the library. Requires Nothing. Example init the FAT library if (Cf_Fat_Init() = 0) then ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Cf_Fat_Assign Prototype sub function Cf_Fat_Assign(dim byref filename as char[12], dim file_cre_attr as byte) as byte - 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 to the assigned file.
CHAPTER 6 mikroBasic PRO for AVR Libraries Cf_Fat_Reset Prototype sub procedure Cf_Fat_Reset(dim byref size as longword) 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 dim size as longword ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Cf_Fat_Rewrite Prototype sub procedure 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 sub procedure Cf_Fat_Append() Returns Nothing.
CHAPTER 6 mikroBasic PRO for AVR Libraries Cf_Fat_Write Prototype sub procedure Cf_Fat_Write(dim byref fdata as byte[512], dim data_len as word) 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Cf_Fat_Get_File_Date Prototype sub procedure Cf_Fat_Get_File_Date(dim byref year as word, dim byref month as byte, dim byref day as byte, dim byref hours as byte, dim byref mins as byte) Returns Nothing. Reads time/date attributes of currently assigned file. Parameters : - 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 mikroBasic PRO for AVR Libraries Cf_Fat_Get_Swap_File Prototype Returns sub function Cf_Fat_Get_Swap_File(dim sectors_cnt as longint, dim byref filename as string[11], dim file_attr as byte) as longword - 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 mikroBasic 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. 204 Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
CHAPTER 6 mikroBasic 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. program CF_Fat16_Test dim ' set compact flash pinout Cf_Data_Port as byte at PORTD Cf_Data_Port_Direction as byte at DDRD CF_RDY CF_WE CF_OE CF_CD1 CF_CE1 CF_A2 CF_A1 CF_A0 as as as as as as as as sbit sbit sbit sbit sbit sbit sbit sbit at at at at at at at at PINB.B7 PORTB.B6 PORTB.B5 PINB.B4 PORTB.B3 PORTB.
CHAPTER 6 mikroBasic PRO for AVR Libraries i = 0 while ostr[i] <> 0 UART1_Write(ostr[i]) Inc(i) wend UART1_Write($0A) end sub'~ '-------------- Creates new file and writes some data to it sub procedure Create_New_File filename[7] = "A" Cf_Fat_Assign(filename, 0xA0) ' Will not find file and then create file Cf_Fat_Rewrite() ' To clear file and start with new data for loop_=1 to 90 ' We want 5 files on the MMC card PORTC = loop_ file_contents[0] = loop_ div 10 + 48 file_contents[1] = loop_ mod 10 + 48 Cf_Fa
CHAPTER 6 mikroBasic PRO for AVR Libraries filename[7] = "C" ' Set filename for single-file tests Cf_Fat_Assign(filename, 0) Cf_Fat_Rewrite for loop_ = 1 to 55 file_contents[0] = byte(loop_ div 10 + 48) file_contents[1] = byte(loop_ mod 10 + 48) Cf_Fat_Write(file_contents, 38) ' write data to the assigned file next loop_ end sub'~ '-------------- Opens an existing file and appends data to it ' (and alters the date/time stamp) sub procedure Open_File_Append filename[7] = "B" Cf_Fat_Assign(filename, 0) Cf_F
CHAPTER 6 mikroBasic PRO for AVR Libraries sub procedure Test_File_Exist(dim fname as byte) dim fsize as longint year as word month_, day, hour_, minute_ as byte outstr as byte[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) <> 0 then '--- file has been found - get its date Cf_Fat_Get_File_Date(year,month_,day,hour_,minute_) WordToStr(year, outstr) Write_Str(outstr)
CHAPTER 6 mikroBasic PRO for AVR Libraries LongIntToStr(size, fat_txt) Write_Str(fat_txt) for i=0 to 4999 Cf_Write_Sector(size, Buffer) size = size+1 UART1_Write(".") next i end if end sub'~ '-------------- Main.
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Pin diagram of CF memory card 210 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroBasic PRO for AVR Libraries EEPROM LIBRARY EEPROM data memory is available with a number of AVR family. The mikroBasic 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 address range.
CHAPTER 6 mikroBasic PRO for AVR Libraries EEPROM_Write Prototype sub procedure EEPROM_Write(dim address as word, dim wrdata as byte) 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. 212 Requires Nothing. Example dim eeWrite as byte wrAddr as word ...
CHAPTER 6 mikroBasic 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 mikroBasic 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries FLASH_Read_Bytes ' for MCUs with 64kb of Flash memory or less sub procedure FLASH_Read_Bytes(dim address as word, dim buffer as ^byte, dim NoBytes as word) Prototype ' for MCUs with Flash memory larger than 64kb sub procedure FLASH_Read_Bytes(dim address as longword, dim buffer as ^byte, dim NoBytes as word) Returns Nothing.
CHAPTER 6 mikroBasic PRO for AVR Libraries FLASH_Read_Words ' for MCUs with 64kb of Flash memory or less sub procedure FLASH_Read_Words(dim address as word, dim buffer as ^word, dim NoWords as word) Prototype ' for MCUs with Flash memory larger than 64kb sub procedure FLASH_Read_Words(dim address as longword, dim buffer as ^word, dim NoWords as word) Returns Nothing.
CHAPTER 6 mikroBasic PRO for AVR Libraries counter = 0 while ( counter < 64 ) ' reading 64 bytes in loop PORTD = FLASH_Read_Byte(F_ADDRESS + counter) ' demonstration of reading single byte Inc(counter) PORTB = FLASH_Read_Byte(F_ADDRESS + counter) ' demonstration of reading single byte Inc(counter) Delay_ms(200) wend FLASH_Read_Bytes(F_ADDRESS, @dat_buff, 64) ' demonstration of reading 64 bytes for counter = 0 to 31 PORTD = dat_buff[counter] ' output low byte to PORTD PORTB = word((dat_buff[counter] >> 8))
CHAPTER 6 mikroBasic PRO for AVR Libraries GRAPHIC LCD LIBRARY The mikroBasic 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.
CHAPTER 6 mikroBasic 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 219
CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd_Init Prototype sub procedure 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 mikroBasic PRO for AVR Libraries Glcd_Set_Side Prototype sub procedure Glcd_Set_Side(dim x_pos as byte) 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 mikroBasic PRO for AVR Libraries Glcd_Set_Page Prototype sub procedure Glcd_Set_Page(dim page as byte) 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 sub function Glcd_Read_Data() as byte Returns One byte from Glcd memory.
CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd_Write_Data Prototype sub procedure Glcd_Write_Data(dim ddata as byte) 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. dim data as byte ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd_Dot Prototype sub procedure Glcd_Dot(dim x_pos as byte, dim y_pos as byte, dim color as byte) Returns Nothing. Draws a dot on Glcd at coordinates (x_pos, y_pos). Parameters : - x_pos: x position. Valid values: 0..127 - y_pos: y position. Valid values: 0..63 Description - 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 mikroBasic PRO for AVR Libraries Glcd_V_Line Prototype sub procedure Glcd_V_Line(dim y_start as byte, dim y_end as byte, dim x_pos as byte, dim color as byte) Returns Nothing. Draws a vertical line on Glcd. Parameters : Description - y_start: y coordinate of the line start. Valid values: 0..63 y_end: y coordinate of the line end. Valid values: 0..63 x_pos: x coordinate of vertical line. Valid values: 0..127 color: color parameter. Valid values: 0..
CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd_Rectangle Prototype sub procedure Glcd_Rectangle(dim x_upper_left as byte, dim y_upper_left as byte, dim x_bottom_right as byte, dim y_bottom_right as byte, dim color as byte) Returns Nothing. Draws a rectangle on Glcd. Parameters : - x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127 - y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..
CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd_Box Prototype sub procedure Glcd_Box(dim x_upper_left as byte, dim y_upper_left as byte, dim x_bottom_right as byte, dim y_bottom_right as byte, dim color as byte) Returns Nothing. Draws a box on Glcd. Parameters : - 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 Description - x_bottom_right: x coordinate of the lower right box corner.
CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd_Set_Font Prototype sub procedure Glcd_Set_Font(dim byref const ActiveFont as ^byte, dim FontWidth as byte, dim FontHeight as byte, dim FontOffs as word) 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 mikroBasic PRO for AVR Libraries Glcd_Write_Char Prototype sub procedure Glcd_Write_Char(dim chr as byte, dim x_pos as byte, dim page_num as byte, dim color as byte) Returns Nothing. Prints character on the Glcd. Parameters : - 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 Description values: 0..7 - color: color parameter. Valid values: 0..
CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd_Write_Text Prototype sub procedure Glcd_Write_Text(dim byref text as string[20], dim x_pos as byte, dim page_num as byte, dim color as byte) Returns Nothing. Prints text on Glcd. Parameters : - 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 Description - color: color parameter. Valid values: 0..
CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example The following example demonstrates routines of the Glcd library: initialization, clear(pattern fill), image displaying, drawing lines, circles, boxes and rectangles, text displaying and handling.
CHAPTER 6 mikroBasic PRO for AVR Libraries while (counter <= 59) ' Draw horizontal and vertical lines Delay_ms(250) Glcd_V_Line(2, 54, counter, 1) Glcd_H_Line(2, 120, counter, 1) Counter = counter + 5 wend Delay2S() Glcd_Fill(0x00) Glcd_Set_Font(@Character8x7, 8, "Character8x7" Glcd_Write_Text("mikroE", 1, 7, 2) for counter = 1 to 10 Glcd_Circle(63,32, 3*counter, 1) next counter Delay2S() Glcd_Box(12,20, 70,57, 2) Delay2S() ' Clear Glcd 7, 32) ' Choose font ' Write string ' Draw circles ' Draw box
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Glcd HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 233
CHAPTER 6 mikroBasic PRO for AVR Libraries KEYPAD LIBRARY The mikroBasic 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 mikroBasic PRO for AVR Libraries Keypad_Init Prototype sub procedure Keypad_Init() Returns Nothing. Description Initializes port for working with keypad. Global variables : Requires - keypadPort_Reg - Keypad port - keypadPort_Reg_Direction - Direction of the Keypad port must be defined before using this function. Example ' Initialize PORTB for communication with keypad dim keypadPort as byte at PORTB dim keypadPort_Direction as byte at DDRB ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example This is a simple example of using the Keypad Library. It supports keypads with 1..4 rows and 1..4 columns. The code being returned by Keypad_Key_Click() function is in range from 1..16. In this example, the code returned is transformed into ASCII codes [0..9,A..F] and displayed on Lcd. In addition, a small single-byte counter displays in the second Lcd row number of key presses.
CHAPTER 6 mikroBasic PRO for AVR Libraries ' Wait for key to be pressed and released while ( kp = 0 ) kp = Keypad_Key_Click() ' Store key code in kp variable wend ' Prepare value for output, transform key to it"s ASCII value select case kp 'case 10: kp = 42 ' "*" ' Uncomment this block for keypad4x3 'case 11: kp = 48 ' "0" 'case 12: kp = 35 ' "#" 'default: kp += 48 case 1 kp = 49 ' 1 case 2 kp = 50 ' 2 case 3 kp = 51 ' 3 case 4 kp = 65 ' A case 5 kp = 52 ' 4 case 6 kp = 53 ' 5 case 7 kp = 54 ' 6 case 8 kp
CHAPTER 6 mikroBasic PRO for AVR Libraries else ' Pressed key is same as previous Inc(cnt) end if Lcd_Chr(1, 10, kp) if (cnt = 255) then cnt = 0 Lcd_Out(2, 10, " end if WordToStr(cnt, txt) Lcd_Out(2, 10, txt) wend end.
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection 4x4 Keypad connection scheme MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 239
CHAPTER 6 mikroBasic PRO for AVR Libraries LCD LIBRARY The mikroBasic 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Library Routines - Lcd_Init Lcd_Out Lcd_Out_Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd Lcd_Init Prototype sub procedure Lcd_Init() Returns Nothing. Description Initializes Lcd module.
CHAPTER 6 mikroBasic PRO for AVR Libraries Lcd_Out Prototype sub procedure Lcd_Out(dim row as byte, dim column as byte, dim byref text as string[20]) 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 mikroBasic PRO for AVR Libraries Lcd_Chr Prototype sub procedure Lcd_Chr(dim row as byte, dim column as byte, dim out_char as byte) 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 mikroBasic PRO for AVR Libraries Lcd_Cmd Prototype sub procedure Lcd_Cmd(dim out_char as byte) 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 SPI Lcd Commands. Requires The Lcd module needs to be initialized. See Lcd_Init table.
CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example The following code demonstrates usage of the Lcd Library routines: ' LCD module connections dim LCD_RS as sbit at PORTD.2 dim LCD_EN as sbit at PORTD.3 dim LCD_D4 as sbit at PORTD.4 dim LCD_D5 as sbit at PORTD.5 dim LCD_D6 as sbit at PORTD.6 dim LCD_D7 as sbit at PORTD.
CHAPTER 6 mikroBasic PRO for AVR Libraries Lcd_Cmd(LCD_SHIFT_RIGHT) Move_Delay() next i while TRUE ' Endless loop for i=0 to 6 ' Move text to the left 7 times Lcd_Cmd(LCD_SHIFT_LEFT) Move_Delay() next i for i=0 to 6 ' Move text to the right 7 times Lcd_Cmd(LCD_SHIFT_RIGHT) Move_Delay() next i wend end.
CHAPTER 6 mikroBasic PRO for AVR Libraries MANCHESTER CODE LIBRARY The mikroBasic PRO for AVR provides a library for handling Manchester coded signals.
CHAPTER 6 mikroBasic PRO for AVR Libraries Library Routines - Man_Receive_Init Man_Receive Man_Send_Init Man_Send Man_Synchro Man_Break The following routines are for the internal use by compiler only: - Manchester_0 - Manchester_1 - Manchester_Out Man_Receive_Init Prototype Returns sub function Man_Receive_Init()as word - 0 - if initialization and synchronization were successful. - 1 - upon unsuccessful synchronization.
CHAPTER 6 mikroBasic PRO for AVR Libraries Man_Receive Prototype sub function Man_Receive(dim byreferror as byte) as byte 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 Example To use this function, the user must prepare the MCU for receiving. See Man_Receive_Init. dim data, error as byte ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Man_Send Prototype sub procedure Man_Send(tr_data as byte) 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 dim msg as byte ... Man_Send(msg) Man_Synchro Prototype sub function Man_Synchro() as word Returns - 0 - if synchronization was not successful.
CHAPTER 6 mikroBasic PRO for AVR Libraries Man_Break Prototype sub procedure 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 mikroBasic 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: program Manchester_Receiver ' Lcd module connections dim LCD_RS as sbit at PORTD.B2 LCD_EN as sbit at PORTD.B3 LCD_D4 as sbit at PORTD.B4 LCD_D5 as sbit at PORTD.B5 LCD_D6 as sbit at PORTD.B6 LCD_D7 as sbit at PORTD.
CHAPTER 6 mikroBasic PRO for AVR Libraries while (temp <> 0x0E) temp = Man_Receive(error_) ' Attempt byte receive if (error_ <> 0) then ' If error occured Lcd_Chr_CP("?") ' Write question mark on Lcd Inc(ErrorCount) ' Update error counter if (ErrorCount > 20) then ' 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 end if else ' No error occured if (temp <> 0x0E) then ' If "End
CHAPTER 6 mikroBasic PRO for AVR Libraries while (character <> 0) Man_Send(character) Delay_ms(90) Inc(index) character = s1[index] wend Man_Send(0x0E) Delay_ms(1000) ' String ends with zero ' Send character ' Wait for a while ' Increment index variable ' Take next char from string ' Send "end" byte wend end.
CHAPTER 6 mikroBasic 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. mikroBasic 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 mikroBasic PRO for AVR Libraries Library Routines - Mmc_Init Mmc_Read_Sector Mmc_Write_Sector Mmc_Read_Cid Mmc_Read_Csd Routines for file handling: - 256 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 mikroBasic PRO for AVR Libraries Mmc_Init Prototype Returns sub function Mmc_Init() as byte - 0 - if MMC/SD card was detected and successfully initialized - 1 - otherwise Initializes MMC through hardware SPI interface. Description Parameters: - port: chip select signal port address. - cspin: chip select pin. Global variables : Requires - Mmc_Chip_Select: Chip Select line - Mmc_Chip_Select_Direction: Direction of the Chip Select pin must be defined before using this function.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Read_Sector Prototype Returns sub function Mmc_Read_Sector(dim sector as longint, dim byref data as byte[512]) as byte - 0 - if reading was successful - 1 - if an error occurred The function reads one sector (512 bytes) from MMC card. Description Parameters: - sector: MMC/SD card sector to be read. - dbuff: buffer of minimum 512 bytes in length for data storage. Requires MMC/SD card must be initialized. See Mmc_Init.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Write_Sector Prototype Returns sub function Mmc_Write_Sector(dim sector as longint, dim byref data_ as byte[512]) as byte - 0 - if writing was successful - 1 - if there was an error in sending write command - 2 - if there was an error in writing (data rejected) The function writes 512 bytes of data to one MMC card sector. Description Parameters: - sector: MMC/SD card sector to be written to.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Read_Cid Prototype sub function Mmc_Read_Cid(dim byref data_cid as byte[16]) as byte - 0 - if CID register was read successfully - 1 - if there was an error while reading Returns The function reads 16-byte CID register. Description Parameters: - data_cid: buffer of minimum 16 bytes in length for storing CID register content. Requires MMC/SD card must be initialized. See Mmc_Init. Example dim error as word dataBuffer as byte[16] ... main: ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Init Prototype Returns Description sub function Mmc_Fat_Init() as byte - 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 mikroBasic PRO for AVR Libraries Mmc_Fat_QuickFormat Prototype Returns sub function Mmc_Fat_QuickFormat(dim mmc_fat_label as string[11]) as byte - 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 - mmc_fat_label: volume label (11 characters in length).
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Assign Prototype sub function Mmc_Fat_Assign(dim byref filename as char[12], dim file_cre_attr as byte) d - 1 - if file already exists or file does not exist but a 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 on an assigned file.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Reset Prototype sub procedure Mmc_Fat_Reset(dim byref size as longword) 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. Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Read Prototype sub procedure Mmc_Fat_Read(dim byref bdata as byte) Returns Nothing. Reads a byte from the currently assigned file opened for reading. Upon function execution file pointers will be set to the next character in the file. Description Parameters: - bdata: buffer to store read byte to. Upon this function execution read byte is returned through this parameter. MMC/SD card and MMC library must be initialized for file operations.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Append Prototype sub procedure Mmc_Fat_Append() Returns Nothing. Opens the currently assigned file for appending. Upon this function execution Description file pointers will be positioned after the last byte in the file, so any subsequent file write operation will start from there. Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Write Prototype sub procedure Mmc_Fat_Write(dim byref fdata as byte[512], dim data_len as word) Returns Nothing. Writes requested number of bytes to the currently assigned file opened for writing. Description Parameters: - fdata: data to be written. - data_len: number of bytes to be written. MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. Requires The file must be previously assigned. See Mmc_Fat_Assign.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Set_File_Date Prototype sub procedure Mmc_Fat_Set_File_Date(dim year as word, dim month, day, hours, mins, seconds as byte) Returns Nothing. Sets the date/time stamp. Any subsequent file write operation will write this stamp to the currently assigned file's time/date attributs. Parameters: Description - year: year attribute. Valid values: 1980-2107 month: month attribute. Valid values: 1-12 day: day attribute.
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Get_File_Date Prototype sub procedure Mmc_Fat_Get_File_Date(dim byref year as word, dim byref month, day, hours, mins as byte) Returns Nothing. Reads time/date attributes of the currently assigned file. Parameters: - 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 mikroBasic PRO for AVR Libraries Mmc_Fat_Get_File_Size Prototype sub function Mmc_Fat_Get_File_Size() as longword Returns Size of the currently assigned file in bytes. Description This function reads size of the currently assigned file in bytes. Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign. Example 270 dim my_file_size as longword ... main: ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc_Fat_Get_Swap_File Prototype Returns sub function Mmc_Fat_Get_Swap_File(dim sectors_cnt as longint, dim byref filename as string[11], dim file_attr as byte) as dword - 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 mikroBasic 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. 272 Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example The following example demonstrates MMC library test. Upon flashing, insert a MMC/SD card into the module, when you should receive the "Init-OK" message. Then, you can experiment with MMC read and write functions, and observe the results through the Usart Terminal. ' if defined, we have a debug messages on PC terminal program MMC_Test {$DEFINE RS232_debug} dim MMC_chip_select as sbit at PORTB.B2 dim MMC_chip_select_direction as sbit at DDRB.
CHAPTER 6 mikroBasic PRO for AVR Libraries {$IFDEF RS232_debug} UART1_Write_Text("AVR-Started") ' If AVR present report UART1_Write(13) UART1_Write(10) {$ENDIF} ' Beffore all, we must initialise a MMC card SPI1_Init_Advanced(_SPI_MASTER, _SPI_FCY_DIV2, _SPI_CLK_LO_LEADING) Spi_Rd_Ptr = @SPI1_Read i = Mmc_Init() PORTC = i {$IFDEF RS232_debug} if(i = 0) then UART1_Write_Text("MMC Init-OK") ' If MMC present report UART1_Write(13) UART1_Write(10) end if if(i) then UART1_Write_Text("MMC Init-error") ' If error
CHAPTER 6 mikroBasic PRO for AVR Libraries end if next k UART1_Write(13) else UART1_Write_Text("CID-error") end if i = Mmc_Read_Csd(data_for_registers) if(i = 0) then for k=0 to 15 printhex(data_for_registers[k]) if(k <> 15) then UART1_Write("-") end if next K UART1_Write(13) UART1_Write(10) else UART1_Write_Text("CSD-error") end if {$ENDIF} end. Following example consists of several blocks that demonstrate various aspects of usage of the Mmc_Fat16 library.
CHAPTER 6 mikroBasic PRO for AVR Libraries '-------------- Writes string to USART sub procedure Write_Str(dim byref ostr as byte[2]) dim i as byte i = 0 while ostr[i] <> 0 UART1_Write (ostr[i]) Inc(i) wend UART1_Write($0A) end sub'~ '-------------- Creates new file sub procedure Create_New_File filename[7] = "A" tests Mmc_Fat_Assign(filename, 0xA0) ate file Mmc_Fat_Rewrite new data for loop_ = 1 to 99 card UART1_Write(".
CHAPTER 6 mikroBasic PRO for AVR Libraries '-------------- Opens an existing file and rewrites it sub procedure Open_File_Rewrite filename[7] = "C" ' Set filename for single-file tests Mmc_Fat_Assign(filename, 0) Mmc_Fat_Rewrite for loop_ = 1 to 55 file_contents[0] = byte(loop_ div 10 + 48) file_contents[1] = byte(loop_ mod 10 + 48) Mmc_Fat_Write(file_contents, 42) ' write data to the assigned file next loop_ end sub'~ '-------------- Opens an existing file and appends data to it ' (and alters the date/ti
CHAPTER 6 mikroBasic PRO for AVR Libraries '-------------- Tests whether file exists, and if so sends its creation date ' and file size via USART sub procedure Test_File_Exist dim fsize as longint year as word month_, day, hour_, minute_ as byte outstr as byte[12] filename[7] = "B" if Mmc_Fat_Assign(filename, 0) <> 0 then '--- file has been found - get its date Mmc_Fat_Get_File_Date(year,month_,day,hour_,minute_) WordToStr(year, outstr) Write_Str(outstr) ByteToStr(month_, outstr) Write_Str(outstr) WordToS
CHAPTER 6 mikroBasic PRO for AVR Libraries if (size <> 0) then LongIntToStr(size, fat_txt) UART1_Write_Text(fat_txt) for i=0 to 4999 Mmc_Write_Sector(size, Buffer) size = size + 1 UART1_Write(".") next i end if end sub '-------------- Main.
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Pin diagram of MMC memory card 280 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroBasic 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 mikroBasic PRO for AVR Libraries Ow_Reset Prototype sub function Ow_Reset() as word - 0 if the device is present - 1 if the device is not present Returns 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. - OW_Bit_Direction: Direction of the OneWire pin must be defined before using this function.
CHAPTER 6 mikroBasic PRO for AVR Libraries Ow_Read Prototype sub function Ow_Read() as byte 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 mikroBasic PRO for AVR Libraries Ow_Write Prototype sub procedure Ow_Write(dim par as byte) Returns Nothing. Writes one byte of data via the OneWire bus. Description Parameters : - par: data to be written 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 mikroBasic 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. program OneWire ' Lcd module connections dim LCD_RS as sbit at PORTD.B2 LCD_EN as sbit at PORTD.B3 LCD_D4 as sbit at PORTD.B4 LCD_D5 as sbit at PORTD.B5 LCD_D6 as sbit at PORTD.B6 LCD_D7 as sbit at PORTD.
CHAPTER 6 mikroBasic PRO for AVR Libraries ' extract temp_whole temp_whole = word(temp2write >> RES_SHIFT) ' convert temp_whole to characters if ( temp_whole div 100 ) then text[0] = temp_whole div 100 + 48 else text[0] = "0" end if text[1] = (temp_whole div 10)mod 10 + 48 ' Extract tens digit text[2] = temp_whole mod 10 + 48 ' Extract ones digit ' extract temp_fraction and convert it to unsigned int temp_fraction = word(temp2write << (4-RES_SHIFT)) temp_fraction = temp_fraction and 0x000F temp_fraction =
CHAPTER 6 mikroBasic PRO for AVR Libraries '--- perform temperature Ow_Reset() Ow_Write(0xCC) Ow_Write(0x44) Delay_us(120) Ow_Reset() Ow_Write(0xCC) Ow_Write(0xBE) reading ' Onewire reset signal ' Issue command SKIP_ROM ' Issue command CONVERT_T ' Issue command SKIP_ROM ' Issue command READ_SCRATCHPAD temp = Ow_Read() temp = (Ow_Read() << 8) + temp '--- Format and display result on Lcd Display_Temperature(temp) Delay_ms(520) wend end.
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Example of DS1820 connection 288 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroBasic PRO for AVR Libraries PORT EXPANDER LIBRARY The mikroBasic 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries - Expander_Write_PortAB Expander_Set_DirectionPortA Expander_Set_DirectionPortB Expander_Set_DirectionPortAB Expander_Set_PullUpsPortA Expander_Set_PullUpsPortB Expander_Set_PullUpsPortAB Expander_Init Prototype sub procedure Expander_Init(dim ModuleAddress as byte) Returns Nothing. Initializes Port Expander using SPI communication.
CHAPTER 6 mikroBasic PRO for AVR Libraries Expander_Read_Byte Prototype sub function Expander_Read_Byte(dim ModuleAddress as byte, dim RegAddress as byte) as byte 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Expander_Read_PortA Prototype sub function Expander_Read_PortA(dim ModuleAddress as byte) as byte 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Expander_Read_PortAB Prototype sub function Expander_Read_PortAB(dim ModuleAddress as byte) as word 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 mikroBasic PRO for AVR Libraries Expander_Write_PortA Prototype sub procedure Expander_Write_PortA(dim ModuleAddress as byte, dim Data_ as byte) 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 mikroBasic PRO for AVR Libraries Expander_Write_PortB Prototype sub procedure Expander_Write_PortB(dim ModuleAddress as byte, dim Data_ as byte) 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 mikroBasic PRO for AVR Libraries Expander_Write_PortAB Prototype sub procedure Expander_Write_PortAB(dim ModuleAddress as byte, dim Data_ as word) 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Expander_Set_DirectionPortA Prototype sub procedure Expander_Set_DirectionPortA(dim ModuleAddress as byte, dim Data_ as byte) 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Expander_Set_DirectionPortAB Prototype sub procedure Expander_Set_DirectionPortAB(dim ModuleAddress as byte, dim Direction as word) Returns Nothing. The function sets Port Expander's PortA and PortB direction. Parameters : - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Description - Direction: data to be written to direction registers.
CHAPTER 6 mikroBasic PRO for AVR Libraries Expander_Set_PullUpsPortB Prototype sub procedure Expander_Set_PullUpsPortB(dim ModuleAddress as byte, dim Data_ as byte) 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 mikroBasic 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. program PortExpander ' Port Expander module connections dim SPExpanderRST as sbit at PORTB.B0 SPExpanderCS as sbit at PORTB.B1 SPExpanderRST_Direction as sbit at DDRB.B0 SPExpanderCS_Direction as sbit at DDRB.
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Port Expander HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 301
CHAPTER 6 mikroBasic PRO for AVR Libraries PS/2 LIBRARY The mikroBasic 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 mikroBasic PRO for AVR Libraries Ps2_Config Prototype sub procedure 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Ps2_Key_Read Prototype Returns sub function Ps2_Key_Read(dim byref value as byte, dim byref special as byte, dim byref pressed as byte) as byte - 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 : - value: holds the value of the key pressed. For characters, numerals, punctuDescription ation marks, and space value will store the appropriate ASCII code.
CHAPTER 6 mikroBasic PRO for AVR Libraries Special Function Keys Adapter Board T6369C datasheet 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 - SOFTW
CHAPTER 6 mikroBasic 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. program PS2_Example dim keydata, special, down as byte dim PS2_Data PS2_Clock_Input PS2_Clock_Output as sbit at PINC.B0 as sbit at PINC.B1 as sbit at PORTC.B1 PS2_Data_Direction as sbit at DDRC.B0 PS2_Clock_Direction as sbit at DDRC.
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Example of PS2 keyboard connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 307
CHAPTER 6 mikroBasic PRO for AVR Libraries PWM LIBRARY CMO module is available with a number of AVR MCUs. mikroBasic 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 mikroBasic PRO for AVR compiler. When you select a MCU, mikroBasic PRO for AVR automaticaly loads the correct PWM library (or libraries), which can be verified by looking at the Library Manager.
CHAPTER 6 mikroBasic PRO for AVR Libraries _PWM_PRESCALER_256 Sets prescaler value to 256. _PWM_PRESCALER_1024 Sets prescaler value to 1024. _PWM1_PRESCALER_1 Sets prescaler value to 1 on second PWM library (if it exists in Library Manager). _PWM1_PRESCALER_8 Sets prescaler value to 8 on second PWM library (if it exists in Library Manager). _PWM1_PRESCALER_32 Sets prescaler value to 32 on second PWM library (if it exists in Library Manager). This value is not available on every MCU.
CHAPTER 6 mikroBasic PRO for AVR Libraries PWM_Init Prototype sub procedure PWM_Init(dim wave_mode as byte, dim prescaler as byte, dim inverted as byte, dim duty as byte) Returns Nothing. Initializes the PWM module. Parameter wave_mode is a desired PWM mode. There are two modes: Phase Correct and Fast PWM. Parameter prescaler chooses prescale value N = 1,8,64,256 or 1024 (some modules support 32 and 128, but for this you will need to check the datasheet for the desired MCU).
CHAPTER 6 mikroBasic PRO for AVR Libraries 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.3 = 1; // set PORTB pin 3 as output for the PWM This code oxample is for ATmega16, for different MCU please consult datasheet for the correct pinout of the PWM module or modules.
CHAPTER 6 mikroBasic PRO for AVR Libraries PWM_Stop Prototype sub procedure PWM_Stop() Returns Nothing. Description Stops the PWM. Requires MCU must have CMO module to use this library. PWM_Init and PWM_Start must be called before using this routine using this routine, otherwise it will have no effect as the PWM module is not running. Example PWM_Stop() 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.
CHAPTER 6 mikroBasic 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries PWM1_Set_Duty Prototype sub procedure PWM1_Set_Duty(dim duty as byte) 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 mikroBasic 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries if (PINC1_bit <> 0) then ' Detect if PORTC pin 1 is pressed Delay_ms(40) ' Small delay to avoid deboucing effect Dec(current_duty1) ' Decrement duty ratio PWM1_Set_Duty(current_duty1) ' Set decremented duty ratio end if wend end.
CHAPTER 6 mikroBasic PRO for AVR Libraries PWM 16 BIT LIBRARY CMO module is available with a number of AVR MCUs. mikroBasic 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 mikroBasic PRO for AVR compiler. When you select a MCU, mikroBasic PRO for AVR automaticaly loads the correct PWM-16bit library, which can be verified by looking at the Library Manager.
CHAPTER 6 mikroBasic PRO for AVR Libraries Predefined constants used in PWM-16bit library The following variables are used in PWM-16bit library functions: 318 Description: _PWM16_PHASE_CORRECT_MODE_8BIT Selects Phase Correct, 8-bit mode. _PWM16_PHASE_CORRECT_MODE_9BIT Selects Phase Correct, 9-bit mode. _PWM16_PHASE_CORRECT_MODE_10BIT Selects Phase Correct, 10-bit mode. _PWM16_FAST_MODE_8BIT Selects Fast, 8-bit mode. _PWM16_FAST_MODE_9BIT Selects Fast, 9-bit mode.
CHAPTER 6 mikroBasic PRO for AVR Libraries Note: Not all of the MCUs have 16bit PWM, and not all of the MCUs have both Timer/Counter1 and Timer/Counter3. Sometimes, like its the case with ATmega168, MCU has only Timer/Counter1 and channels A and B. Therefore constants that have in their name Timer3 or channel C are invalid (for ATmega168) and will not be visible from Code Assistant.
CHAPTER 6 mikroBasic PRO for AVR 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 mikroBasic PRO for AVR Libraries PWM16bit_Change_Duty Prototype sub procedure PWM16bit_Change_Duty(dim duty as word, dim channel as byte) 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 mikroBasic PRO for AVR Libraries PWM16bit_Start Prototype sub procedure PWM16bit_Start(dim timer as byte) 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 mikroBasic PRO for AVR Libraries program PWM_Test dim current_duty as byte current_duty1 as byte main: DDC0_bit = 0 DDC1_bit = 0 ' Set PORTC pin 0 as input ' Set PORTC pin 1 as input DDC2_bit = 0 DDC3_bit = 0 ' Set PORTC pin 2 as input ' Set PORTC pin 3 as input current_duty = 127 current_duty1 = 127 ' initial value for current_duty ' initial value for current_duty DDB1_bit = 1 ' Set PORTB pin 1 as output pin for the PWM (according to datasheet) DDB2_bit = 1 ' Set PORTB pin 2 as output pin
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection PWM demonstration 324 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroBasic 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 mikroBasic 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries External dependencies of RS-485 Library The following variable must be defined in all projects using RS-485 Library: Description: Control RS-485 Trans- Example : dim RS485_rxtx_pin as mit/Receive operation sbit sfr external dim RS485_rxtx_pin as sbit at PORTD.B2 dim RS485_rxtx_pin_direc- Direction of the RS-485 tion as sbit sfr Transmit/Receive pin external dim RS485_rxtx_pin_direction as sbit at DDRD.
CHAPTER 6 mikroBasic PRO for AVR Libraries RS485Master_Init Prototype sub procedure RS485Master_Init() Returns Nothing. Description Initializes MCU as a Master for RS-485 communication. 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 mikroBasic PRO for AVR Libraries RS485Master_Receive Prototype sub procedure RS485Master_Receive(dim byref data_buffer as byte[20]) 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 mikroBasic PRO for AVR Libraries RS485Master_Send Prototype sub procedure Rs485Master_Send(dim byref data_buffer as byte[20], dim datalen as byte, dim slave_address as byte) 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries RS485Slave_Init Prototype sub procedure RS485Slave_Init(dim slave_address as byte) 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 mikroBasic PRO for AVR Libraries RS485Slave_Receive Prototype sub procedure RS485Slave_Receive(dim byref data_buffer as byte[20]) 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 mikroBasic PRO for AVR Libraries RS485Slave_Send Prototype sub procedure RS485Slave_Send(dim byref data_buffer as byte[20], dim datalen as byte) 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 MCU must be initialized as a Slave for RS-485 communication. See RS485Slave_Init.
CHAPTER 6 mikroBasic PRO for AVR Libraries program RS485_Master_Example dim dat as byte[10] ' buffer for receving/sending messages i, j as byte cnt as longint dim rs485_rxtx_pin as sbit at PORTD.2 ' set transcieve pin rs485_rxtx_pin_direction as sbit at DDRD.
CHAPTER 6 mikroBasic PRO for AVR Libraries if (dat[4] <> 0) then ' if message received successfully cnt = 0 dat[4] = 0 ' clear message received flag j = dat[3] for i = 1 to dat[3] ' show data on PORTB PORTB = dat[i-1] next i dat[0] = dat[0]+1 ' increment received dat[0] Delay_ms(1) ' send back to slave RS485Master_Send(dat,1,160) end if if (cnt > 100000) then ' if in 100000 poll-cycles the answer Inc(PORTA) ' was not detected, signal cnt = 0 ' failure of send-message RS485Master_Send(dat,1,160) if (PORTA
CHAPTER 6 mikroBasic PRO for AVR Libraries ' Pass pointers to UART sub functions of used UART module UART_Wr_Ptr = @UART1_Write UART_Rd_Ptr = @UART1_Read UART_Rdy_Ptr = @UART1_Data_Ready UART_TX_Idle_Ptr = @UART1_TX_Idle UART1_Init(9600) Delay_ms(100) RS485Slave_Init(160) ' Intialize MCU as slave, address 160 dat[4] = 0 dat[5] = 0 dat[6] = 0 ' ensure that message received flag is 0 ' ensure that message received flag is 0 ' ensure that error flag is 0 SREG_I_bit = 1 RXCIE_bit = 1 ' initialize UART1 m
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Example of interfacing PC to ATmega16 MCU via RS485 bus with LTC485 as RS485 transceiver 336 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
CHAPTER 6 mikroBasic 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 XOR
CHAPTER 6 mikroBasic PRO for AVR Libraries SOFTWARE I²C LIBRARY The mikroBasic 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 mikroBasic 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 sub procedure Soft_I2C_Init() Returns Nothing. Description Configures the software I2C module.
CHAPTER 6 mikroBasic PRO for AVR Libraries Soft_I2C_Start Prototype sub procedure Soft_I2C_Start() 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 sub function Soft_I2C_Read(dim ack as word) as byte Returns One byte from the Slave. Reads one byte from the slave.
CHAPTER 6 mikroBasic PRO for AVR Libraries Soft_I2C_Write Prototype sub function Soft_I2C_Write(dim _Data as byte) as byte - 0 if there were no errors. Returns - 1 if write collision was detected on the I2C bus. Sends data byte via the I˛C bus. Description Parameters : - _Data: data to be sent Soft I2C 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 mikroBasic PRO for AVR Libraries Soft_I2C_Break Prototype sub procedure Soft_I2C_Break() Returns Nothing. 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 execuDescription tion. This mechanism is similar to WDT. Note: Interrupts should be disabled before using Software I˛C routins again (see note at the top of this page). Requires Nothing.
CHAPTER 6 mikroBasic 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.
CHAPTER 6 Libraries mikroBasic PRO for AVR '-------------------- Formats date and time sub procedure Transform_Time() seconds = ((seconds and 0xF0) >> 4)*10 + (seconds and 0x0F) Transform seconds minutes = ((minutes and 0xF0) >> 4)*10 + (minutes and 0x0F) Transform months hours = ((hours and 0xF0) >> 4)*10 + (hours and 0x0F) Transform hours year = (_day and 0xC0) >> 6 Transform year _day = ((_day and 0x30) >> 4)*10 + (_day and 0x0F) Transform day _month = ((_month and 0x10) >> 4)*10 + (_month and 0x0F) Tr
CHAPTER 6 mikroBasic PRO for AVR Libraries '----------------- Main sub procedure main: Init_Main() ' Perform initialization while TRUE Read_Time() Transform_Time() Display_Time() wend end.
CHAPTER 6 mikroBasic PRO for AVR Libraries SOFTWARE SPI LIBRARY The mikroBasic 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 mikroBasic PRO for AVR Libraries Library Routines - Soft_SPI_Init - Soft_SPI_Read - Soft_SPI_Write Soft_SPI_Init Prototype sub procedure Soft_SPI_Init() Returns Nothing. Description Configures and initializes the software SPI module.
CHAPTER 6 mikroBasic PRO for AVR Libraries Soft_SPI_Read Prototype sub function Soft_SPI_Read(dim sdata as byte) as word 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 dim data_read as byte data_send as byte ...
CHAPTER 6 mikroBasic 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. program Soft_SPI ' DAC module connections dim Chip_Select as sbit at SoftSpi_CLK as sbit at SoftSpi_SDI as sbit at SoftSpi_SDO as sbit at PORTB.0 PORTB.7 PINB.6 PORTB.
CHAPTER 6 mikroBasic PRO for AVR Libraries value = 2048 ' When program starts, DAC gives ' the output in the mid-range while (TRUE) ' Endless loop if ((PINA0_bit) and (value < 4095)) then ' If PA0 button is pressed Inc(value) ' increment value else if ((PINA1_bit) and (value > 0)) then ' If PA1 button is pressed Dec(value) ' decrement value end if end if DAC_Output(value) Delay_ms(1) wend end.
CHAPTER 6 mikroBasic PRO for AVR Libraries SOFTWARE UART LIBRARY The mikroBasic 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 mikroBasic PRO for AVR Libraries Soft_UART_Init Prototype sub function Soft_UART_Init(dim baud_rate as longword, dim inverted as byte) as byte - 2 - error, requested baud rate is too low - 1 - error, requested baud rate is too high - 0 - successfull initialization Returns Configures and initializes the software UART module. Parameters : - 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 mikroBasic PRO for AVR Libraries Soft_UART_Read Prototype sub function Soft_UART_Read(dim byref error as byte) as byte 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 mikroBasic PRO for AVR Libraries Soft_UART_Write Prototype sub procedure Soft_UART_Write(udata as byte) 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Soft_UART_Break Prototype sub procedure 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 mikroBasic 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 mikroBasic PRO for AVR USART Terminal Tool. program Soft_UART ' Soft UART connections dim Soft_UART_Rx_Pin as sbit at PIND.B0 Soft_UART_Tx_Pin as sbit at PORTD.B1 Soft_UART_Rx_Pin_Direction as sbit at DDRD.B0 Soft_UART_Tx_Pin_Direction as sbit at DDRD.
CHAPTER 6 mikroBasic PRO for AVR Libraries SOUND LIBRARY The mikroBasic 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 mikroBasic PRO for AVR Libraries Sound_Init Prototype sub procedure 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 dim Sound_Play_Pin as sbit at PORTC.B3 dim Sound_Play_Pin_Direction as sbit at DDRC.B3 ' End of Sound library connections .
CHAPTER 6 mikroBasic 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. program Sound ' Sound connections dim Sound_Play_Pin as sbit at PORTC.B3 dim Sound_Play_Pin_direction as sbit at DDRC.
CHAPTER 6 mikroBasic PRO for AVR Libraries ToneA ToneC ToneE next counter end sub main: DDRB = 0x00 Delay_ms(2000) Sound_Init() Sound_Play(2000, 1000) ond 360 ' Configure PORTB as input ' Initialize sound pin ' Play starting sound, 2kHz, 1 sec- while TRUE if (PINB.7 <> 0) then Tone1() while (PINB.7 <> 0) nop wend end if ' endless loop ' If PORTB.7 is pressed play Tone1 if (PINB.6 <> 0) then Tone2() while (PINB.6 <> 0) nop wend end if ' If PORTB.6 is pressed play Tone2 if (PINB.
CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Example of Sound Library sonnection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 361
CHAPTER 6 mikroBasic PRO for AVR Libraries SPI LIBRARY mikroBasic 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 mikroBasic PRO for AVR Libraries SPI1_Init_Advanced Prototype sub procedure SPI1_Init_Advanced(dim mode, fcy_div, clock_and_edge as byte) 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 mikroBasic PRO for AVR Libraries SPI1_Read Prototype sub function SPI1_Read(dim buffer as byte) as byte Returns Received data. Reads one byte from the SPI bus. Description Parameters : - buffer: dummy data for clock generation (see device Datasheet for SPI modules implementation details) Requires SPI module must be initialized before using this function. See SPI1_Init and SPI1_Init_Advanced routines. Example ' read a byte from the SPI bus dim take, dummy1 as byte ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example The code demonstrates how to use SPI library functions for communication between SPI module of the MCU and Microchip's MCP4921 12-bit D/A converter program SPI ' DAC module connections dim Chip_Select as sbit at PORTB.B0 Chip_Select_Direction as sbit at DDRB.
CHAPTER 6 mikroBasic PRO for AVR Libraries if ((PINA1_bit) and (value > 0)) then Dec(value) end if end if DAC_Output(value) Delay_ms(1) wend end.
CHAPTER 6 mikroBasic 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 mikroBasic PRO for AVR Libraries External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Ethernet Library: dim SPI_Ethernet_CS as sbit sfr external dim SPI_Ethernet_RST as sbit sfr external dim SPI_Ethernet_CS_Direc tion as sbit sfr external dim SPI_Ethernet_RST_Dire ction as sbit sfr external Description: Example : dim SPI_Ethernet_CS ENC28J60 chip select pin. as sbit at PORTB.B4 dim SPI_Ethernet_RST as sbit at PORTB.
CHAPTER 6 mikroBasic 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 Spi_Ethernet_Init Prototype sub procedure Spi_Ethernet_Init(dim mac as ^byte, dim ip as ^byte, dim fullDuplex as byte) Returns Nothing.
CHAPTER 6 mikroBasic PRO for AVR Libraries Parameters: Description Requires - mac: RAM buffer containing valid MAC address. - ip: RAM buffer containing valid IP address. - fullDuplex: ethernet duplex mode switch. Valid values: 0 (half duplex mode) and 1 (full duplex mode). The appropriate hardware SPI module must be previously initialized. const Spi_Ethernet_HALFDUPLEX = 0 const Spi_Ethernet_FULLDUPLEX = 1 Example myMacAddr as myIpAddr as ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Spi_Ethernet_Enable Prototype sub procedure Spi_Ethernet_Enable(dim enFlt as byte) 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.
CHAPTER 6 mikroBasic PRO for AVR Libraries Description Note: Advance filtering available in the ENC28J60 module such as Pattern Match, Magic Packet and Hash Table can not be enabled by this routine. Additionaly, all filters, except CRC, enabled with this routine will work in OR mode, which means that packet will be received if any of the enabled filters accepts it. Note: This routine will change receive filter configuration on-the-fly.
CHAPTER 6 mikroBasic PRO for AVR Libraries Bit Mask Description Predefined library const MAC Broadcast traffic/receive filter 0 0x01 flag. When set, MAC broadcast traffic Spi_Ethernet_BROADCAST will be disabled. MAC Multicast traffic/receive filter 1 0x02 flag. When set, MAC multicast traffic Spi_Ethernet_MULTICAST will be disabled.
CHAPTER 6 mikroBasic PRO for AVR Libraries Spi_Ethernet_doPacket Prototype sub function Spi_Ethernet_doPacket() as byte Returns - 0 - upon successful packet processing (zero packets received or received packet processed successfully). - 1 - upon reception error or receive buffer corruption. ENC28J60 controller needs to be restarted. - 2 - received packet was not sent to us (not our IP, nor IP broadcast address). - 3 - received IP packet was not IPv4.
CHAPTER 6 mikroBasic PRO for AVR Libraries Spi_Ethernet_putByte Prototype sub procedure Spi_Ethernet_putByte(dim v as byte) 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 dim data as byte ...
CHAPTER 6 mikroBasic PRO for AVR Libraries Spi_Ethernet_putConstBytes Prototype sub procedure Spi_Ethernet_putConstBytes(const ptr as ^byte, dim n as byte) 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 mikroBasic PRO for AVR Libraries Spi_Ethernet_putConstString Prototype sub function Spi_Ethernet_putConstString(const ptr as ^byte) as word 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 mikroBasic PRO for AVR Libraries Spi_Ethernet_getBytes Prototype sub procedure Spi_Ethernet_getBytes(dim ptr as ^byte, dim addr as word, dim n as byte) 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 mikroBasic PRO for AVR Libraries Spi_Ethernet_UserTCP Prototype sub function Spi_Ethernet_UserTCP(dim remoteHost as ^byte, dim remotePort as word, dim localPort as word, dim reqLength as word) as word - 0 - there should not be a reply to the request. - Length of TCP/HTTP reply data field - otherwise. Returns 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 mikroBasic PRO for AVR Libraries Spi_Ethernet_UserUDP Prototype sub function Spi_Ethernet_UserUDP(dim remoteHost as ^byte, dim remotePort as word, dim destPort as word, dim reqLength as word) as word - 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 mikroBasic PRO for AVR Libraries Library Example This code shows how to use the AVR mini Ethernet library : - the board will reply to ARP & ICMP echo requests - the board will reply to UDP requests on any port : returns the request in upper char with a header made of remote host IP & port number - the board will reply to HTTP requests on port 80, GET method with pathnames : / will return the HTML main page /s will return board status as text string /t0 ... /t7 will toggle P3.b0 to P3.
CHAPTER 6 mikroBasic PRO for AVR Libraries myMacAddr[0] myMacAddr[1] myMacAddr[2] myMacAddr[3] myMacAddr[4] myMacAddr[5] 0x00 0x14 0xA5 0x76 0x19 0x3F myIpAddr[0] myIpAddr[1] myIpAddr[2] myIpAddr[3] = = = = 192 168 20 60 gwIpAddr[0] gwIpAddr[1] gwIpAddr[2] gwIpAddr[3] = = = = 192 168 20 6 ipMask[0] ipMask[1] ipMask[2] ipMask[3] 255 255 255 0 = = = = dnsIpAddr[0] dnsIpAddr[1] dnsIpAddr[2] dnsIpAddr[3] ' ' ' ' ' ' ' = = = = = = * * * * * * * = = = = 192 168 20 1 starts ENC28J60 with : reset b
CHAPTER 6 mikroBasic PRO for AVR Libraries Module eth_enc28j60_utils code: module eth_enc28j60_utils '************************************************************ '* ROM constant strings '************************************************************ const httpHeader as string[30] = "HTTP/1.
CHAPTER 6 mikroBasic PRO for AVR Libraries const indexPage2 as string[466] = "
"+ " |