mikroElektronika 8051 User Manual
Below you will find brief information for 8051. mikroBasic for 8051 is intuitive, quick and easy for 8051 Microcontrollers. The IDE provides power with simplicity of Windows. With its tools, code examples, routines and help, it's a reliable tool.
PDF
Document
Advertisement
Advertisement
mikroBASIC for 8051 Develop your applications quickly and easily with the world's most intuitive mikroBASIC for 8051 Microcontrollers. Highly sophisticated IDE provides the power you need with the simplicity of a Windows based point-and-click environment. With useful implemented tools, many practical code examples, broad set of built-in routines, and a comprehensive Help, mikroBASIC for 8051 makes a fast and reliable tool, which can satisfy needs of experienced engineers and beginners alike. mikroBasic for 8051 December 2008. Reader’s note DISCLAIMER: Reader’s Note mikroBasic for 8051 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. The PDF-edition of the manual can be printed for private or local use, but not for distribution. Modifying the manual or the compiler is strictly prohibited. HIGH RISK ACTIVITIES: The mikroBasic for 8051 compiler 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 the Software could lead directly to death, personal injury, or severe physical or environmental damage ("High Risk Activities"). mikroElektronika and its suppliers specifically disclaim any express or implied warranty of fitness for High Risk Activities. LICENSE AGREEMENT: By using the mikroBasic for 8051 compiler, you agree to the terms of this agreement. Only one person may use licensed version of mikroBasic for 8051 compiler at a time. Copyright © mikroElektronika 2003 - 2008. This manual covers mikroBasic for 8051 version 1.1 and the related topics. Newer versions may contain changes without prior notice. COMPILER BUG REPORTS: The compiler has been carefully tested and debugged. It is, however, not possible to guarantee a 100 % error free product. If you would like to report a bug, please contact us at the address [email protected]. Please include next information in your bug report: - Your operating system - Version of mikroBasic for 8051 - Code sample - Description of a bug CONTACT US: mikroElektronika Voice: + 381 (11) 36 28 830 Fax: + 381 (11) 36 28 831 Web: www.mikroe.com E-mail: [email protected] Windows is a Registered trademark of Microsoft Corp. All other trade and/or services marks are the property of the respective owners. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents CHAPTER 1 Introduction CHAPTER 2 mikroBasic for 8051 Environment CHAPTER 3 mikroBasic for 8051 Specifics CHAPTER 4 8051 Specifics CHAPTER 5 mikroBasic for 8051 Language Reference CHAPTER 6 mikroBasic for 8051 Libraries mikroBasic for 8051 Table of Contents CHAPTER 1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Where to Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 mikroElektronika Associates License Statement and Limited Warranty 4 IMPORTANT - READ CAREFULLY . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 LIMITED WARRANTY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 HIGH RISK ACTIVITIES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 GENERAL PROVISIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Technical Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 How to Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Who Gets the License Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 How to Get License Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 After Receving the License Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 CHAPTER 2 IDE Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Main Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 File Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Edit Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Find Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Replace Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Find In Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Go To Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Replace Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Dialog box for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Regular expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 View Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 File Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Edit Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Edit Toolbar is . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Advanced Edit Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Find/Replace Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 IV MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents Project Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Build Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Styles Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tools Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 23 24 25 25 Project Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Run Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Tools Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Help Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 IDE Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Customizing IDE Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Docking Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Saving Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Auto Hide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Advanced Code Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Advanced Editor Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Code Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Code Folding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Parameter Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Code Templates (Auto Complete) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Auto Correct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Spell Checker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Bookmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Goto Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Comment / Uncomment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Code Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Routine List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Project Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Project Settings Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Library Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Error Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Memory Usage Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 RAM Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD V Table of Contents mikroBasic for 8051 Data Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 XData Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 iData Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 bData Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 PData Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Displays PData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Special Function Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 General Purpose Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 ROM Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 ROM Memory Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 ROM Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Procedures Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Procedures Size Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Procedures Locations Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Integrated Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 USART Terminal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 ASCII Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 EEPROM Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 7 Segment Display Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 UDP Terminal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Graphic LCD Bitmap Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 LCD Custom Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Code editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Output settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Simple matches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Escape sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Character classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Metacharacters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Metacharacters - Line separators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Metacharacters - Predefined classes . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Metacharacters - Word boundaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Metacharacters - Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 VI MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents Metacharacters - Alternatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Metacharacters - Subexpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Metacharacters - Backreferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 mikroBasic for 8051 Command Line Options . . . . . . . . . . . . . . . . . . . . 72 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 New Project Wizard Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Customizing Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Edit Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Managing Project Group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Add/Remove Files from Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Managing Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Creating new source file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Opening an existing file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Printing an open file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Saving file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Saving file under a different name . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Closing file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Clean Project Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Clean Project Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Output Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Assembly View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 81 81 82 Compiler Error Messages: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Linker Error Messages: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Hint Messages: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Software Simulator Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Watch Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Stopwatch Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 RAM Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Software Simulator Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Creating New Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Multiple Library Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD VII mikroBasic for 8051 Table of Contents CHAPTER 3 Basic Standard Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Divergence from the Basic Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Basic Language Exstensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Predefined Globals and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 SFRs and related constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Math constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Accessing Individual Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Accessing Individual Bits Of Variables . . . . . . . . . . . . . . . . . . . . . . . . . 96 sbit type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 bit type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Function Calls from Interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Interrupt Priority Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Linker Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Directive absolute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Directive org . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Built-in Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Lo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Hi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Higher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Highest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Delay_us . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Delay_ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Vdelay_ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Delay_Cyc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Clock_KHz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Clock_MHz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SetFuncCall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Uart_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 101 101 102 102 102 103 103 103 104 104 104 105 105 Code Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 VIII MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents Constant folding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Constant propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Copy propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Value numbering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 "Dead code" ellimination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Stack allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Local vars optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Better code generation and local optimization . . . . . . . . . . . . . . . . . . . 106 Types Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 CHAPTER 4 Nested Calls Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 8051 Memory Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Program Memory (ROM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Internal Data Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 External Data Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 SFR Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Memory Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Small model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Compact model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Large model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Memory Type Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . idata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 113 113 113 114 114 CHAPTER 5 mikroBasic Language Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Lexical Elements Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Whitespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD IX Table of Contents mikroBasic for 8051 Newline Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Whitespace in Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Token Extraction Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Integer Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Floating Point Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Character Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . String Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 121 122 122 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Case Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Uniqueness and Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Identifier Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Punctuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Brackets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Colon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 130 130 130 130 Program Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Organization of Main Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Organization of Other Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Scope and Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 The visibili . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Include Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Main Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Other Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Interface Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 Implementation Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 X MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents Variables and 8051 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Calling a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Calling a procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Function Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Example: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Example: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Forward declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Type Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Simple Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Array Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Constant Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 @ Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Structure Member Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Types Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Implicit Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Promotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Clipping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Explicit Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 Operators Precedence and Associativity . . . . . . . . . . . . . . . . . . . . . . . 156 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XI Table of Contents mikroBasic for 8051 Division by Zero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Unary Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 Relational Operators in Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Bitwise Operators Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Logical Operations on Bit Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 The bitwise operators and, or, an . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Unsigned and Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Signed and Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Bitwise Shift Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Nested if statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Select Case Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 Nested Case Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Iteration Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 For Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Endless Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 While Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Do Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Jump Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 asm Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Compiler Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Directives #DEFINE and #UNDEFINE . . . . . . . . . . . . . . . . . . . . . . . . . 173 Directives #IFDEF, #ELSEIF and #ELSE . . . . . . . . . . . . . . . . . . . . . . . 173 Predefined Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Linker Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Directive absolute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Directive org . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 XII MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents CHAPTER 6 Hardware 8051-specific Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Miscellaneous Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Library Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 CANSPI Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 The SPI module i . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 External dependecies of CANSPI Library . . . . . . . . . . . . . . . . . . . . . . . 182 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 CANSPISetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 CANSPIGetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 CANSPIInitialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 CANSPISetBaudRate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 CANSPISetMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 CANSPISetFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 CANSPIread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 CANSPIWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 The following routines are for an internal use by the lib . . . . . . . . . . . . 182 CANSPISetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 CANSPIGetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 CANSPIInitialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 CANSPISetBaudRate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 CANSPISetMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 CANSPISetFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 CANSPIRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 CANSPIWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 CANSPI Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 CANSPI_OP_MODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 CANSPI_CONFIG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 CANSPI_TX_MSG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 CANSPI_RX_MSG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 CANSPI_MASK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 CANSPI_FILTER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XIII Table of Contents mikroBasic for 8051 EEPROM Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Eeprom_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Eeprom_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 Eeprom_Write_Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 The mikroBasic for 80 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 of Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Basic routines: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Glcd_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Glcd_Set_Side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Glcd_Set_X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Glcd_Set_Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Glcd_Read_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Glcd_Write_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Glcd_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 Glcd_Set_Side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 Glcd_Set_X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 Glcd_Set_Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Glcd_Read_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Glcd_Write_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Glcd_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Glcd_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Glcd_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Glcd_V_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 Glcd_H_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 Glcd_Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Glcd_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Glcd_Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Glcd_Set_Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 Glcd_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 Glcd_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 Glcd_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 XIV MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents The following exa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 Keypad Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 External dependencies of Keypad Library . . . . . . . . . . . . . . . . . . . . . . . 217 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Keypad_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Keypad_Key_Press . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 Keypad_Key_Click . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 This is a simple example of using . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 he Keypad Librar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 External dependencies of LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . 222 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 Lcd_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Lcd_Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 Lcd_Out_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 Lcd_Chr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 Lcd_Chr_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 Lcd_Cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 Available LCD Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 OneWire Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 External dependencies of OneWire Library . . . . . . . . . . . . . . . . . . . . . . 229 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Ow_Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 Ow_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 Ow_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 Manchester Code Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Man_Receive_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 Man_Receive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XV Table of Contents mikroBasic for 8051 Man_Send_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Man_Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Man_Synchro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Man_Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 Connection Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 Port Expander Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 External dependencies of Port Expander Library . . . . . . . . . . . . . . . . . 242 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Expander_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 Expander_Read_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 Expander_Write_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 Expander_Read_PortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 Expander_Read_PortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 Expander_Read_PortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 Expander_Write_PortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 Expander_Write_PortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 Expander_Write_PortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Expander_Set_DirectionPortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Expander_Set_DirectionPortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Expander_Set_DirectionPortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 Expander_Set_PullUpsPortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 Expander_Set_PullUpsPortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 Expander_Set_PullUpsPortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 PS/2 Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 External dependencies of PS/2 Library . . . . . . . . . . . . . . . . . . . . . . . . . 255 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 Ps2_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 Ps2_Key_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Special Function Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 RS-485 Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 External dependencies of RS-485 Library . . . . . . . . . . . . . . . . . . . . . . . 261 XVI MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 RS485master_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 RS485master_Receive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 RS485master_Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 RS485slave_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 RS485slave_Receive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 RS485slave_Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 This is a simple demonstration o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Message format and CRC calculations . . . . . . . . . . . . . . . . . . . . . . . . . 271 Software I²C Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 External dependecies of Soft_I2C Library . . . . . . . . . . . . . . . . . . . . . . . 272 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 Soft_I2C_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 Soft_I2C_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Soft_I2C_Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Soft_I2C_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Soft_I2C_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Soft_I2C_Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Software SPI Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 Soft_Spi_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Soft_Spi_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Soft_Spi_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Software UART Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 External dependencies of Software UART Library . . . . . . . . . . . . . . . . 282 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 Soft_Uart_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Soft_Uart_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 Soft_Uart_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 Sound Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XVII Table of Contents mikroBasic for 8051 External dependencies of Sound Library . . . . . . . . . . . . . . . . . . . . . . . 287 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Sound_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Sound_Play . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Sound_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Sound_Play . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 The example is a simple demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 SPI Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 Spi_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 Spi_Init_Advanced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292 Spi_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Spi_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 SPI Ethernet Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 External dependencies of SPI Ethernet Library . . . . . . . . . . . . . . . . . . 296 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 Spi_Ethernet_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 Spi_Ethernet_Enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 Spi_Ethernet_Disable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 Spi_Ethernet_doPacket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Spi_Ethernet_putByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Spi_Ethernet_putBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Spi_Ethernet_putConstBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 Spi_Ethernet_putString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 Spi_Ethernet_putConstString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Spi_Ethernet_getByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Spi_Ethernet_getBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 Spi_Ethernet_UserTCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 Spi_Ethernet_UserUDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 SPI Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 XVIII MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents External dependencies of SPI Graphic LCD Library . . . . . . . . . . . . . . . 317 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 Spi_Glcd_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 Spi_Glcd_Set_Side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 Spi_Glcd_Set_Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 Spi_Glcd_Set_X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 Spi_Glcd_Read_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 Spi_Glcd_Write_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Spi_Glcd_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Spi_Glcd_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Spi_Glcd_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Spi_Glcd_V_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Spi_Glcd_H_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 Spi_Glcd_Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Spi_Glcd_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 Spi_Glcd_Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 Spi_Glcd_Set_Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 Spi_Glcd_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 Spi_Glcd_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 Spi_Glcd_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 SPI LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 External dependencies of SPI LCD Library . . . . . . . . . . . . . . . . . . . . . . 333 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 Spi_Lcd_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 Spi_Lcd_Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 Spi_Lcd_Out_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 Spi_Lcd_Chr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 Spi_Lcd_Chr_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 Spi_Lcd_Cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 Available LCD Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 SPI LCD8 (8-bit interface) Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 External dependencies of SPI LCD Library . . . . . . . . . . . . . . . . . . . . . . 340 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XIX Table of Contents mikroBasic for 8051 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 Spi_Lcd8_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 Spi_Lcd8_Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 Spi_Lcd8_Out_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 Spi_Lcd8_Chr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 Spi_Lcd8_Chr_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Spi_Lcd8_Cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Available LCD Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 SPI T6963C Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 External dependencies of Spi T6963C Graphic LCD Library . . . . . . . . 347 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 Spi_T6963C_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 Spi_T6963C_WriteData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 pi_T6963C_WriteCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 Spi_T6963C_SetPtr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Spi_T6963C_WaitReady . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Spi_T6963C_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Spi_T6963C_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 Spi_T6963C_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 Spi_T6963C_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 Spi_T6963C_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Spi_T6963C_Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Spi_T6963C_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 Spi_T6963C_Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 Spi_T6963C_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 Spi_T6963C_Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 Spi_T6963C_Set_Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 Spi_T6963C_ClearBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 Spi_T6963C_SetBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 Spi_T6963C_NegBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Spi_T6963C_DisplayGrPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Spi_T6963C_DisplayTxtPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Spi_T6963C_SetGrPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360 Spi_T6963C_SetTxtPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360 XX MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents Spi_T6963C_PanelFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 Spi_T6963C_GrFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 Spi_T6963C_TxtFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 Spi_T6963C_Cursor_Height . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 Spi_T6963C_Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 Spi_T6963C_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 Spi_T6963C_Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Spi_T6963C_Cursor_Blink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 T6963C Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 External dependencies of T6963C Graphic LCD Library . . . . . . . . . . . 370 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 T6963C_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 T6963C_WriteData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 T6963C_WriteCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 T6963C_SetPtr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 T6963C_WaitReady . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 T6963C_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 T6963C_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 T6963C_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 T6963C_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 T6963C_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378 T6963C_Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378 T6963C_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 T6963C_Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 T6963C_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380 T6963C_Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380 T6963C_Set_Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 T6963C_ClearBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 T6963C_SetBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 T6963C_NegBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 T6963C_DisplayGrPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 T6963C_DisplayTxtPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 T6963C_SetGrPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383 T6963C_SetTxtPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXI Table of Contents mikroBasic for 8051 T6963C_PanelFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 T6963C_GrFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 T6963C_TxtFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 T6963C_Cursor_Height . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 T6963C_Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 T6963C_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 T6963C_Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 T6963C_Cursor_Blink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 UART Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 Uart_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 Uart_Data_Ready . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 Uart_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 Uart_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 Button Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 External dependecies of Button Library . . . . . . . . . . . . . . . . . . . . . . . . 396 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Conversions Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 ByteToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 ShortToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 WordToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 IntToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 LongintToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 LongWordToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 FloatToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 Dec2Bcd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 Bcd2Dec16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 Dec2Bcd16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 XXII MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic for 8051 Table of Contents Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 acos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 asin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 atan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 atan2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 ceil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 cos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 cosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 eval_poly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 fabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 floor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 frexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 ldexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 log10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 modf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 pow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 sin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 sinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 sqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 String Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 memchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 memcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 memcpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 memmove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 memset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 strcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 strchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 strcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 strcpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 strcspn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 strlen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXIII Table of Contents mikroBasic for 8051 strncat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strncmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strncpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strpbrk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strrchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strspn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 413 414 414 414 414 414 Time Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 Time_dateToEpoch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 Time_epochToDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 Time_dateDiff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 TimeStruct type definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418 Trigonometry Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 sinE3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 cosE3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 XXIV MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 Introduction to mikroBasic for 8051 The mikroBasic 8051 is a powerful, feature-rich development tool 8051 microcontrollers. It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems, without compromising performance or control. 1 CHAPTER 1 mikroBasic for 8051 Introduction Features mikroBasic for 8051 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 libraries to dramatically speed up the development: data acquisition, memory, displays, conversions, communication etc. - Monitor your program structure, variables, and functions in the Code Explorer. - Generate commented, human-readable assembly, and standard HEX compatible with all programmers. - Inspect program flow and debug executable logic with the integrated Software Simulator. - Get detailed reports and graphs: RAM and ROM map, code statistics, assembly listing, calling tree, and more. - mikroBasic 8051 provides plenty of examples to expand, develop, and use as building bricks in your projects. Copy them entirely if you deem fit – that’s why we included them with the compiler. 2 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic for 8051 Introduction Where to Start - In case that you’re a beginner in programming 8051 microcontrollers, read carefully the 8051 Specifics chapter. It might give you some useful pointers on 8051 constraints, code portability, and good programming practices. - If you are experienced in Basic programming, you will probably want to consult mikroBasic Specifics first. For language issues, you can always refer to the comprehensive Language Reference. A complete list of included libraries is available at mikroBasic Libraries. - If you are not very experienced in Basic programming, don’t panic! mikroBasic 8051 provides plenty of examples making it easy for you to go quickly. We suggest that you first consult Projects and Source Files, and then start browsing the examples that you're the most interested in. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 CHAPTER 1 mikroBasic for 8051 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. BY INSTALLING, COPYING, OR OTHERWISE USING SOFTWARE, YOU AGREE TO BE BOUND BY ALL TERMS AND CONDITIONS OF THE LICENSE AGREEMENT. Upon your acceptance of the terms and conditions of the License Agreement, mikroElektronika Associates grants you the right to use Software in a way provided below. This Software is owned by mikroElektronika Associates and is protected by copyright law and international copyright treaty. Therefore, you must treat this Software like any other copyright material (e.g., a book). You may transfer Software and documentation on a permanent basis provided. You retain no copies and the recipient agrees to the terms of the License Agreement. Except as provided in the License Agreement, you may not transfer, rent, lease, lend, copy, modify, translate, sublicense, time-share or electronically transmit or receive Software, media or documentation. You acknowledge that Software in the source code form remains a confidential trade secret of mikroElektronika Associates and therefore you agree not to modify Software or attempt to reverse engineer, decompile, or disassemble it, except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation. If you have purchased an upgrade version of Software, it constitutes a single product with the mikroElektronika Associates software that you upgraded. You may use the upgrade version of Software only in accordance with the License Agreement. 4 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic for 8051 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. Any implied warranties on Software are limited to ninety (90) days. mikroElektronika Associates’ and its suppliers’ entire liability and your exclusive remedy shall be, at mikroElektronika Associates’ option, either (a) return of the price paid, or (b) repair or replacement of Software that does not meet mikroElektronika Associates’ Limited Warranty and which is returned to mikroElektronika Associates with a copy of your receipt. DO NOT RETURN ANY PRODUCT UNTIL YOU HAVE CALLED MIKROELEKTRONIKA ASSOCIATES FIRST AND OBTAINED A RETURN AUTHORIZATION NUMBER. This Limited Warranty is void if failure of Software has resulted from an accident, abuse, or misapplication. Any replacement of Software will be warranted for the rest of the original warranty period or thirty (30) days, whichever is longer. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, MIKROELEKTRONIKA ASSOCIATES AND ITS SUPPLIERS DISCLAIM ALL OTHER WARRANTIES AND CONDITIONS, EITHER EXPRESSED OR IMPLIED, INCLUDED, BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT, WITH REGARD TO SOFTWARE, AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES. IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS AND BUSINESS INFORMATION, BUSINESS INTERRUPTION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE PRODUCT OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF MIKROELEKTRONIKA ASSOCIATES HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY CASE, MIKROELEKTRONIKA ASSOCIATES’ ENTIRE LIABILITY UNDER ANY PROVISION OF THIS LICENSE AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR SOFTWARE PRODUCT PROVIDED, HOWEVER, IF YOU HAVE ENTERED INTO A MIKROELEKTRONIKA ASSOCIATES SUPPORT SERVICES AGREEMENT, MIKROELEKTRONIKA ASSOCIATES’ ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOVERNED BY THE TERMS OF THAT AGREEMENT. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 5 CHAPTER 1 mikroBasic for 8051 Introduction HIGH RISK ACTIVITIES Software is not fault-tolerant and is not designed, manufactured or intended for use or resale as on-line control equipment in hazardous environments requiring fail-safe performance, such as in the operation of nuclear facilities, aircraft navigation or communication systems, air traffic control, direct life support machines, or weapons systems, in which the failure of Software could lead directly to death, personal injury, or severe physical or environmental damage (“High Risk Activities”). mikroElektronika Associates and its suppliers specifically disclaim any expressed or implied warranty of fitness for High Risk Activities. GENERAL PROVISIONS This statement may only be modified in writing signed by you and an authorised officer of mikroElektronika Associates. If any provision of this statement is found void or unenforceable, the remainder will remain valid and enforceable according to its terms. If any remedy provided is determined to have failed for its essential purpose, all limitations of liability and exclusions of damages set forth in the Limited Warranty shall remain in effect. This statement gives you specific legal rights; you may have others, which vary, from country to country. mikroElektronika Associates reserves all rights not specifically granted in this statement. mikroElektronika Visegradska 1A, 11000 Belgrade, Europe. Phone: + 381 11 36 28 830 Fax: +381 11 36 28 831 Web: www.mikroe.com E-mail: [email protected] 6 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic for 8051 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 for 8051 are always appreciated — feel free to drop a note or two on our Wishlist. In our Knowledge Base www.mikroe.com/en/kb/ you can find the answers to Frequently Asked Questions and solutions to known problems. If you can not find the solution to your problem in Knowledge Base then report it to Support Desk www.mikroe.com/en/support/. In this way, we can record and track down bugs more efficiently, which is in our mutual interest. We respond to every bug report and question in a suitable manner, ever improving our technical support. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 CHAPTER 1 mikroBasic for 8051 Introduction HOW TO REGISTER The latest version of the mikroBasic for 8051 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. If you intend to develop really complex projects in the mikroBasic for 8051, then you should consider the possibility of purchasing the license key. Who Gets the License Key Buyers of the mikroBasic for 8051 are entitled to the license key. After you have completed the payment procedure, you have an option of registering your mikroBasic. In this way you can generate hex output without any limitations. How to Get License Key After you have completed the payment procedure, start the program. Select Help › How to Register from the drop-down menu or click the How To Register Icon . Fill out the registration form (figure below), select your distributor, and click the Send button. 8 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic for 8051 Introduction MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 9 CHAPTER 1 mikroBasic for 8051 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. After Receving the License Key The license key comes as a small autoextracting file – just start it anywhere on your computer in order to activate your copy of compiler and remove the demo limit. You do not need to restart your computer or install any additional components. Also, there is no need to run the mikroBasic for 8051 at the time of activation. Notes: - The license key is valid until you format your hard disk. In case you need to format the hard disk, you should request a new activation key. - Please keep the activation program in a safe place. Every time you upgrade the compiler you should start this program again in order to reactivate the license. 10 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment The mikroBasic for 8051 is an user-friendly and intuitive environment: 11 CHAPTER 2 mikroBasic for 8051 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. - The Project Manager alows multiple project management - General project settings can be made in the Project Settings window - Library manager enables simple handling libraries being used in a project - The Error Window displays all errors detected during compiling and linking. - The source-level Software Simulator lets you debug executable logic stepby-step by watching the program flow. - The New Project Wizard is a fast, reliable, and easy way to create a project. - Help files are syntax and context sensitive. - Like in any modern Windows application, you may customize the layout of mikroBasic for 8051 to suit your needs best. - Spell checker underlines identifiers which are unknown to the project. In this way it helps the programmer to spot potential problems early, much before the project is compiled. Spell checker can be disabled by choosing the option in the Preferences dialog (F12). 12 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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 for 8051 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. Related topics: Keyboard shortcuts, File Toolbar, Managing Source Files 14 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment EDIT MENU OPTIONS Edit Description Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard. Paste text from clipboard. Delete selected text. Select all text in active editor. Find text in active editor. Find next occurence of text in active editor. Find previous occurence of text in active editor. Replace text in active editor. Find text in current file, in all opened files, or in files from desired folder. Goto to the desired line in active editor. Advanced Code Editor options. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 15 CHAPTER 2 mikroBasic for 8051 Environment Advanced>> Description Comment selected code or put single line comment if there is no selection. Uncomment selected code or remove single line comment if there is no selection. 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. If the string is not found a message is displayed. 16 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment Replace Text Dialog box for searching for a text string in file and replacing it with another text string. 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 17 CHAPTER 2 mikroBasic for 8051 Environment Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned. Replace Text Dialog box for searching for a text string in file and replacing it with another text string. 18 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment Regular expressions By checking this box, you will be able to advance your search, through Regular expressions. Related topics: Keyboard shortcuts, Edit Toolbar, Advanced Edit Toolbar MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 19 CHAPTER 2 mikroBasic for 8051 Environment VIEW MENU OPTIONS View Description Show/Hide toolbars. Show/Hide debug windows. Show/Hide Routine List in active editor. Show/Hide Project Settings window. Show/Hide Code Explorer window. Show/Hide Project Manager window. Show/Hide Library Manager window. Show/Hide Bookmarks window. Show/Hide Error Messages window. Show/Hide Macro Editor window. Show Window List window. 20 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment TOOLBARS File Toolbar File Toolbar is a standard toolbar with following options: Icon Description Opens a new editor window. Open source file for editing or image file for viewing. Save changes for active window. Save changes in all opened windows. Close current editor. Close all editors. Print Preview. Edit Toolbar Edit Toolbar is a standard toolbar with following options: Icon Description Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard. Paste text from clipboard. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 21 CHAPTER 2 mikroBasic for 8051 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. Generate HTML code suitable for publishing current source code on the web. Find/Replace Toolbar Find/Replace Toolbar is a standard toolbar with following options: Icon Description Find text in current editor. Find next occurence. Find previous occurence. Replace text. Find text in files. 22 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. Start programmer and load current HEX file. Open assembly code in editor. View statistics for current project. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 23 CHAPTER 2 mikroBasic for 8051 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 24 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment Styles Toolbar Styles toolbar allows you to easily customize your workspace. Tools Toolbar Tools Toolbar comes with following default options: Icon Description Run USART Terminal EEPROM ASCII Chart Seven segment decoder tool. The Tools toolbar can easily be customized by adding new tools in Options(F12) window. Related topics: Keyboard shortcuts, Integrated Tools, Debugger Windows MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 25 CHAPTER 2 mikroBasic for 8051 Environment PROJECT MENU OPTIONS 26 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. Related topics: Keyboard shortcuts, Project Toolbar, Creating New Project, Project Manager, Project Settings MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 27 CHAPTER 2 mikroBasic for 8051 Environment RUN MENU OPTIONS Run Description Start Software Simulator. Stop debugger. Pause Debugger. Step Into. Step Over. Step Out. Jump to interrupt in current project. Toggle Breakpoint. Breakpoints. Clear Breakpoints. Show/Hide Watch Window Show/Hide Stopwatch Window Toggle between Basic source and disassembly. Related topics: Keyboard shortcuts, Debug Toolbar 28 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. Open Options window Related topics: Keyboard shortcuts, Tools Toolbar MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 29 CHAPTER 2 mikroBasic for 8051 Environment HELP MENU OPTIONS Help 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. Related topics: Keyboard shortcuts 30 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment KEYBOARD SHORTCUTS Below is a complete list of keyboard shortcuts available in mikroBasic for 8051 IDE. You can also view keyboard shortcuts in the Code Explorer window, tab Keyboard. IDE Shortcuts Ctrl+X Cut F1 Help Ctrl+Y Delete entire line Ctrl+N New Unit Ctrl+Z Undo Ctrl+O Open Ctrl+Shift+Z Redo Ctrl+Shift+O Open Project Ctrl+Shift+N Open New Project Ctrl+Space Code Assistant Ctrl+K Close Project Ctrl+Shift+Space Parameters Assistant Ctrl+F9 Compile Ctrl+D Find declaration Shift+F9 Compile All Ctrl+E Incremental Search Ctrl+F11 Compile and Program Ctrl+L Routine List Shift+F4 View breakpoints Ctrl+G Goto line Ctrl+Shift+F5 Clear breakpoints Ctrl+J Insert Code Template F11 Start 8051Flash Programmer Ctrl+Shift+. Comment Code Ctrl+Shift+, Uncomment Code F12 Preferences Ctrl+number Goto bookmark Basic Editor Shortcuts F3 Find, Find Next Shift+F3 Find Previous Alt+F3 Grep Search, Find in Files Ctrl+A Select All Ctrl+C Copy Ctrl+F Find Ctrl+R Replace Ctrl+P Print Ctrl+S Save unit Ctrl+Shift+S Save All Ctrl+V Paste Advanced Editor Shortcuts Ctrl+Shift+number Set bookmark Ctrl+Shift+I Indent selection Ctrl+Shift+U Unindent selection TAB Indent selection Shift+TAB Unindent selection Alt+Select Select columns Ctrl+Alt+Select Select columns Ctrl+Alt+L Convert selection to lowercase Ctrl+Alt+U Convert selection to uppercase Ctrl+Alt+T Convert to Titlecase MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 31 CHAPTER 2 mikroBasic for 8051 Environment Software Simulator Shortcuts 32 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 for 8051 Environment IDE OVERVIEW The mikroBasic for 8051 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. - The Project Manager alows multiple project management - General project settings can be made in the Project Settings window - Library manager enables simple handling libraries being used in a project - The Error Window displays all errors detected during compiling and linking. - The source-level Software Simulator lets you debug executable logic step-by-step by watching the program flow. - The New Project Wizard is a fast, reliable, and easy way to create a project. - Help files are syntax and context sensitive. - Like in any modern Windows application, you may customize the layout of mikroBasic for 8051 to suit your needs best. - Spell checker underlines identifiers which are unknown to the project. In this way it helps the programmer to spot potential problems early, much before the project is compiled. - Spell checker can be disabled by choosing the option in the Preferences dialog (F12). MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 33 CHAPTER 2 mikroBasic for 8051 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. 34 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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 . To set the layout select the desired layout from the layout drop-down list and click the Set Layout Icon . To remove the layout from the drop-down list, select the desired layout from the list and click the Delete Layout Icon . MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 35 CHAPTER 2 mikroBasic for 8051 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. To display an auto-hidden window, move your pointer over the tab. The window slides back into view and is ready for use. 36 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. Advanced Editor Features - Adjustable Syntax Highlighting - Code Assistant - Code Folding - Parameter Assistant - Code Templates (Auto Complete) - Auto Correct for common typos - Spell Checker - Bookmarks and Goto Line - Comment / Uncomment You can configure the Syntax Highlighting, Code Templates and Auto Correct from the Editor Settings dialog. To access the Settings, click Tools › Options from the drop-down menu, click the Show Options Icon or press F12 key. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 37 CHAPTER 2 Environment 38 mikroBasic for 8051 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. 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. If you place a mouse cursor over the tooltip box, the collapsed text will be shown in a tooltip style box. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 39 CHAPTER 2 mikroBasic for 8051 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. Code Templates (Auto Complete) You can insert the Code Template by typing the name of the template (for instance, whiles), then press Ctrl+J and the Code Editor will automatically generate a code. You can add your own templates to the list. Select Tools › Options from the drop-down menu, or click the Show Options Icon and then select the Auto Complete Tab. Here you can enter the appropriate keyword, description and code of your template. Autocomplete macros can retreive system and project information: - 40 %DATE% - current system date %TIME% - current system time %DEVICE% - device(MCU) name as specified in project settings %DEVICE_CLOCK% - clock as specified in project settings %COMPILER% - current compiler version MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment These macros can be used in template code, see template ptemplate provided with mikroBasic for 8051 installation. Auto Correct The Auto Correct feature corrects common typing mistakes. To access the list of recognized typos, select Tools › Options from the drop-down menu, or click the Show Options Icon and then select the Auto Correct Tab. You can also add your own preferences to the list. Also, the Code Editor has a feature to comment or uncomment the selected code by simple click of a mouse, using the Comment Icon and Uncomment Icon from the Code Toolbar. Spell Checker The Spell Checker underlines unknown objects in the code, so 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. Goto Line The Goto Line option makes navigation through a large code easier. Use the shortcut Ctrl+G to activate this option. Comment / Uncomment Also, the Code Editor has a feature to comment or uncomment the selected code by simple click of a mouse, using the Comment Icon and Uncomment Icon from the Code Toolbar. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 41 CHAPTER 2 mikroBasic for 8051 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. 42 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 43 CHAPTER 2 mikroBasic for 8051 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: 44 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment Icon Description Save project Group. Open project group. Close the active project. Close project group. Add project to the project group. Remove project from the project group. Add file to the active project. Remove selected file from the project. Build the active project. Run mikroElektronika's Flash programmer. For details about adding and removing files from project see Add/Remove Files from Project. Related topics: Project Settings, Project Menu Options, File Menu Options, Project Toolbar, Build Toolbar, Add/Remove Files from Project MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 45 CHAPTER 2 mikroBasic for 8051 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. - Memory Model - Select the desired memory model. Related topics: Memory Model, Project Manager 46 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. In case none library is needed in a project, press the button Clear All and all libraries will be cleared from the project. Only the selected libraries will be linked. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 47 CHAPTER 2 mikroBasic for 8051 Environment Icon 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. Related topics: mikroBasic for 8051 Libraries, Creating New Library 48 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. Double click the message line in the Error Window to highlight the line where the error was encountered. Related topics: Error Messages MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 49 CHAPTER 2 mikroBasic for 8051 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 Data Memory Displays Data memory usage in form of histogram. 50 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment XData Memory Displays XData memory usage in form of histogram. iData Memory Displays iData memory usage in form of histogram. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 51 CHAPTER 2 mikroBasic for 8051 Environment bData Memory Displays bData memory usage in form of histogram. PData Memory Displays PData memory usage in form of histogram. 52 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment Special Function Registers Summarizes all Special Function Registers and their addresses. General Purpose Registers Summarizes all General Purpose Registers and their addresses. Also displays symbolic names of variables and their addresses. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 53 CHAPTER 2 mikroBasic for 8051 Environment ROM Memory ROM Memory Usage Displays ROM memory usage in form of histogram. ROM Memory Allocation Displays ROM memory allocation. 54 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment Procedures Windows Provides overview procedures locations and sizes. Procedures Size Window Displays size of each procedure. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 55 CHAPTER 2 mikroBasic for 8051 Environment Procedures Locations Window Displays how functions are distributed in microcontroller’s memory. 56 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment INTEGRATED TOOLS USART Terminal The mikroBasic for 8051 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 from Tools toolbar. 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 57 CHAPTER 2 Environment 58 mikroBasic for 8051 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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 for 8051 IDE - project_name.hex file will be loaded automatically while ihex file must be loaded manually. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 59 CHAPTER 2 mikroBasic for 8051 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. UDP Terminal The mikroBasic for 8051 includes the UDP Terminal. You can launch it from the drop-down menu Tools › UDP Terminal. 60 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 61 CHAPTER 2 mikroBasic for 8051 Environment Graphic LCD Bitmap Editor The mikroBasic for 8051 includes the Graphic LCD Bitmap Editor. Output is the mikroBasic for 8051 compatible code. You can launch it from the drop-down menu Tools › GLCD Bitmap Editor. 62 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment LCD Custom Character mikroBasic for 8051 includes the LCD Custom Character. Output is mikroBasic for 8051 compatible code. You can launch it from the drop-down menu Tools › LCD Custom Character. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 63 CHAPTER 2 mikroBasic for 8051 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 for 8051 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. 64 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 65 CHAPTER 2 mikroBasic for 8051 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. 66 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. A series of characters matches that series of characters in the target string, so the pattern "short" would match "short" in the target string. You can cause characters that normally function as metacharacters or escape sequences to be interpreted by preceding them with a backslash "\". For instance, metacharacter "^" matches beginning of string, but "\^" matches character "^", and "\\" matches "\", etc. Examples : integer matches string 'integer' \^integer matches string '^integer' Escape sequences Characters may be specified using a escape sequences: "\n" matches a newline, "\t" a tab, etc. More generally, \xnn, where nn is a string of hexadecimal digits, matches the character whose ASCII value is nn. If you need wide(Unicode)character code, you can use '\x{nnnn}', where 'nnnn' - one or more hexadecimal digits. - \xnn - char with hex code nn - \x{nnnn)- char with hex code nnnn (one byte for plain text and two bytes for Unicode) - \t - tab (HT/TAB), same as \x09 - \n - newline (NL), same as \x0a - \r - car.return (CR), same as \x0d - \f - form feed (FF), same as \x0c - \a - alarm (bell) (BEL), same as \x07 - \e - escape (ESC) , same as \x1b Examples: sub\x20procedure matches 'sub procedure' (note space in the middle) \tlongint matches 'longint' (predecessed by tab) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 67 CHAPTER 2 mikroBasic for 8051 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. Within a list, the "-" character is used to specify a range, so that a-z represents all characters between "a" and "z", inclusive. If you want "-" itself to be a member of a class, put it at the start or end of the list, or escape it with a backslash. If you want ']', you may place it at the start of list or escape it with a backslash. Examples: [-az] matches 'a', 'z' and '-' [az-] matches 'a', 'z' and '-' [a\-z] matches 'a', 'z' and '-' [a-z] matches all twenty six small characters from 'a' to 'z' [\n-\x0D] matches any of #10,#11,#12,#13. [\d-t] matches any digit, '-' or 't'. []-a] matches any char from ']'..'a'. Metacharacters Metacharacters are special characters which are the essence of regular expressions.There are different types of metacharacters, described below. Metacharacters - Line separators ^ - start of line $ - end of line \A - start of text \Z - end of text . - any character in line 68 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. Embedded line separators will not be matched by ^" or "$". You may, however, wish to treat a string as a multi-line buffer, such that the "^" will match after any line separator within the string, and "$" will match before any line separator. Regular expressons works with line separators as recommended at www.unicode.org ( http://www.unicode.org/unicode/reports/tr18/ ): Metacharacters - Predefined classes \w \W \d \D \s \S - an alphanumeric character (including "_") a nonalphanumeric a numeric character a non-numeric any space (same as [\t\n\r\f]) a non space You may use \w, \d and \s within custom character classes. Example: routi\de - matches strings like 'routi1e', 'routi6e' and so on, but not 'routine', 'routime' and so on. Metacharacters - Word boundaries A word boundary ("\b") is a spot between two characters that has a "\w" on one side of it and a "\W" on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a "\W". \b - match a word boundary) \B - match a non-(word boundary) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 69 CHAPTER 2 mikroBasic for 8051 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. * - zero or more ("greedy"), similar to {0,} + - one or more ("greedy"), similar to {1,} ? - zero or one ("greedy"), similar to {0,1} {n} - exactly n times ("greedy") {n,} - at least n times ("greedy") {n,m} - at least n but not more than m times ("greedy") *? - zero or more ("non-greedy"), similar to {0,}? +? - one or more ("non-greedy"), similar to {1,}? ?? - zero or one ("non-greedy"), similar to {0,1}? {n}? - exactly n times ("non-greedy") {n,}? - at least n times ("non-greedy") {n,m}? - at least n but not more than m times ("non-greedy") So, digits in curly brackets of the form, {n,m}, specify the minimum number of times to match the item n and the maximum m. The form {n} is equivalent to {n,n} and matches exactly n times. The form {n,} matches n or more times. There is no limit to the size of n or m, but large numbers will chew up more memory and slow down execution. If a curly bracket occurs in any other context, it is treated as a regular character. Examples: count.*r ß- matches strings like 'counter', 'countelkjdflkj9r' and 'countr' count.+r - matches strings like 'counter', 'countelkjdflkj9r' but not 'countr' count.?r - matches strings like 'counter', 'countar' and 'countr' but not 'countelkj9r' counte{2}r - matches string 'counteer' counte{2,}r - matches strings like 'counteer', 'counteeer', 'counteeer' etc. counte{2,3}r - matches strings like 'counteer', or 'counteeer' but not 'counteeeer' A little explanation about "greediness". "Greedy" takes as many as possible, "nongreedy" takes as few as possible. For example, 'b+' and 'b*' applied to string 'abbbbc' return 'bbbb', 'b+?' returns 'b', 'b*?' returns empty string, 'b{2,3}?' returns 'bb', 'b{2,3}' returns 'bbb'. 70 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. For this reason, it's common practice to include alternatives in parentheses, to minimize confusion about where they start and end. Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the one that is chosen. This means that alternatives are not necessarily greedy. For example: when matching rou|rout against "routine", only the "rou" part will match, as that is the first alternative tried, and it successfully matches the target string (this might not seem important, but it is important when you are capturing matched text using parentheses.) Also remember that "|" is interpreted as a literal within square brackets, so if you write [bit|bat|bot], you're really only matching [biao|]. Examples: rou(tine|te) - matches strings 'routine' or 'route'. Metacharacters - Subexpressions The bracketing construct ( ... ) may also be used for define regular subexpressions. Subexpressions are numbered based on the left to right order of their opening parenthesis. First subexpression has number '1' Examples: (int){8,10} matches strings which contain 8, 9 or 10 instances of the 'int' routi([0-9]|a+)e matches 'routi0e', 'routi1e' , 'routine', 'routinne', 'routinnne' etc. Metacharacters - Backreferences Metacharacters \1 through \9 are interpreted as backreferences. \ matches previously matched subexpression #. Examples: (.)\1+ matches 'aaaa' and 'cc'. (.+)\1+ matches 'abab' and '123123' (['"]?)(\d+)\1 matches "13" (in double quotes), or '4' (in single quotes) or 77 (without quotes) etc MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 71 CHAPTER 2 mikroBasic for 8051 Environment MIKROBASIC FOR 8051 COMMAND LINE OPTIONS Usage: mikroBasic8051 [-'opts' [-'opts']] 'opts']] Infile can be of *.mbas and *.mcl type. ['infile' [-'opts']] [- The following parameters and some more (see manual) are valid: - P : MCU for which compilation will be done. - FO : Set oscillator. - SP : Add directory to the search path list. - N : Output files generated to file path specified by filename. - B : Save compiled binary files (*.mcl) to 'directory'. - O : Miscellaneous output options. - DBG : Generate debug info. - E : Set memory model opts ( S | C | L (small, compact, large)). - L : Check and rebuild new libraries. - C : Turn on case sensitivity. Example: mikroBasic8051.exe -MSF -DBG -pAT89S8253 -ES -O11111114 -fo10 -N"C:\Lcd\Lcd.mbproj" -SP"C:\Program Files\Mikroelektronika\mikroBasic 8051\defs\" -SP"C:\Program Files\Mikroelektronika\mikroBasic 8051\uses\" -SP"C:\Lcd\" "Lcd.mbas" "System.mcl" "Math.mcl" "Math_Double.mcl" "Delays.mcl" "__Lib_Lcd.mcl" "__Lib_LcdConsts.mcl" Parameters used in the example: -MSF : Short Message Format; used for internal purposes by IDE. -DBG : Generate debug info. -pAT89S8253 : MCU AT89S8253 selected. -ES : Set small memory model. -O11111114 : Miscellaneous output options. -fo10 : Set oscillator frequency [in MHz]. -N"C:\Lcd\Lcd.mbproj" -SP"C:\Program Files\Mikroelektronika\mikroBasic 8051\defs\" : Output files generated to file path specified by filename. -SP"C:\Program Files\Mikroelektronika\mikroBasic 8051\defs\" : Add directory to the search path list. -SP"C:\Program Files\Mikroelektronika\mikroBasic 8051\uses\" : Add directory to the search path list. -SP"C:\Lcd\" : Add directory to the search path list. "Lcd.mbas" "System.mcl" "Math.mcl" "Math_Double.mcl" "Delays.mcl" "__Lib_Lcd.mcl" "__Lib_LcdConsts.mcl" : Specify input files. 72 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment PROJECTS The mikroBasic 8051 organizes applications into projects, consisting of a single project file (extension .mbproj) and one or more source files (extension .mbas). mikroBasic for 8051 IDE allows you to manage multiple projects (see Project Manager). Source files can be compiled only if they are part of a project. The project file contains the following information: - project name and optional description, target device, memory model, device flags (config word), device clock, list of the project source files with paths, binary files (*.mcl), image files, other files. Note that the project does not include files in the same way as preprocessor does, see Add/Remove Files from Project. New Project The easiest way to create a project is by means of the New Project Wizard, dropdown menu Project › New Project or by clicking the New Project Icon from Pro- ject Toolbar. New Project Wizard Steps MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 73 CHAPTER 2 mikroBasic for 8051 Environment Step One- Provides basic information on settings in the following steps. Step Two - Select the device from the device drop-down list. 74 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment Step Three - enter the oscillator frequency value. Step Four - Select the desired memory model. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 75 CHAPTER 2 mikroBasic for 8051 Environment Step Five - Specify the location where your project will be saved. Step Six - Add project file to the project if they are avaiable at this point. You can always add project files later using Project Manager Related topics: Project Manager, Project Settings, Memory Model 76 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment CUSTOMIZING PROJECTS Edit Project You can change basic project settings in the Project Settings window. You can change chip, oscillator frequency, and memory model. 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. Managing Project Group mikroBasic for 8051 IDE provides covenient option which enables several projects to be open simultaneously. If you have several projects being connected in some way, you can create a project group. The project group may be saved by clicking the Save Project Group Icon from the Project Manager window. The project group may be reopend by clicking the Open Project Group Icon . All relevant data about the project group is stored in the project group file (extension .mpg) ADD/REMOVE FILES FROM PROJECT The project can contain the following file types: - .mbas source files - .mcl binary files - .pld project level defines files (future upgrade) - image files - .hex, .asm and .lst files, see output files. These files can not be added or removed from project. - other files The list of relevant source files is stored in the project file (extension .mbproj). MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 77 CHAPTER 2 mikroBasic for 8051 Environment 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. Related topics: Project Manager, Project Settings, Memory Model 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 .mbproj, along with other project information. You can compile source files only if they are part of the project. Use the preprocessor directive #include to include header files with the extension .h. Do not rely on the preprocessor to include source files other than headers — see Add/Remove Files from Project for more information. Managing Source Files Creating new source file To create a new source file, do the following: 1. Select File › New Unit from the drop-down menu, or press Ctrl+N, or click the New File Icon from the File Toolbar. 2. A new tab will be opened. This is a new source file. Select File › Save from the drop-down menu, or press Ctrl+S, or click the Save File Icon from the File Toolbar and name it as you want. If you use the New Project Wizard, an empty source file, named after the project with extension .mbas, will be created automatically. The mikroBasic 8051 does not require you to have a source file named the same as the project, it’s just a matter of convenience. 78 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment Opening an existing file 1. Select File › Open from the drop-down menu, or press Ctrl+O, or click the Open File Icon from the File Toolbar. In Open Dialog browse to the location of the file that you want to open, select it and click the Open button. 2. The selected file is displayed in its own tab. If the selected file is already open, its current Editor tab will become active. Printing an open file 1. Make sure that the window containing the file that you want to print is the active window. 2. Select File › Print from the drop-down menu, or press Ctrl+P. 3. In the Print Preview Window, set a desired layout of the document and click the OK button. The file will be printed on the selected printer. Saving file 1. Make sure that the window containing the file that you want to save is the active window. 2. 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. In the dialog, browse to the folder where you want to save the file. 4. In the File Name field, modify the name of the file you want to save. 5. Click the Save button. Closing file 1. Make sure that the tab containing the file that you want to close is the active tab. 2. Select File › Close from the drop-down menu, or right click the tab of the file that you want to close and select Close option from the context menu. 3. If the file has been changed since it was last saved, you will be prompted to save your changes. Related topics:File Menu, File Toolbar, Project Manager, Project Settings, MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 79 CHAPTER 2 mikroBasic for 8051 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. 80 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. If there are some errors, you will be notified in the Error Window. If no errors are encountered, the mikroBasic for 8051 will generate output files. OUTPUT FILES Upon successful compilation, the mikroBasic for 8051 will generate output files in the project folder (folder which contains the project file .mbproj). Output files are summarized in the table below: Format Description File Type Intel HEX Intel style hex records. Use this file to program 8051 MCU. Binary mikro Compiled Library. Binary distribution of appli.mcl cation that can be included in other projects. List File Overview of 8051 memory allotment: instruction addresses, registers, routines and labels. .lst Assembler File Human readable assembly with symbolic names, extracted from the List File. .asm .hex ASSEMBLY VIEW After compiling the program in the mikroBasic for 8051, you can click the View Assembly icon or select Project › View Assembly from the drop-down menu to review the generated assembly code (.asm file) in a new tab window. Assembly is human-readable with symbolic names. Related topics:Project Menu, Project Toolbar, Error Window, Project Manager, Project Settings MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 81 CHAPTER 2 mikroBasic for 8051 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". - Identifier "%s" has been already declared in "%s". - Syntax error in multiplicative expression. - Definition file for "%s" is corrupted. - ORG directive is currently supported for interrupts only. - Not enough ROM. - Not enough RAM. - External procedure "%s" used in "%s" was not found. - Internal error: "%s". - Unit cannot recursively use itself. - "%s" cannot be used out of loop. - Supplied and formal parameters do not match ("%s" to "%s"). - Constant cannot be assigned to. - Constant array must be declared as global. - Incompatible types ("%s" to "%s"). - Too many characters ("%s"). - Soft_Uart cannot be initialized with selected baud rate/device clock. - Main label cannot be used in modules. - Break/Continue cannot be used out of loop. - Preprocessor Error: "%s". - Expression is too complicated. - Duplicated label "%s". - Complex type cannot be declared here. - Record is empty. - Unknown type "%s". - File not found "%s". - Constant argument cannot be passed by reference. - Pointer argument cannot be passed by reference. 82 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment - Operator "%s" not applicable to these operands "%s". - Exit cannot be called from the main block. - Array 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. - Assignment to for loop variable is not allowed. - "%s" is allowed only in the main program. - Start address of "%s" has already been defined. - Simple constant cannot have a fixed address. - Invalid date/time format. - Invalid operator "%s". - File "%s" is not accessible. - Forward routine "%s" is missing implementation. - ";" is not allowed before "else". - Not enough elements: expected "%s", but "%s" elements found. - Too many elements: expected "%s" elements. - "external" is allowed for global declarations only. - Integer const expected. - Recusion in definition. - Array corupted. - Arguments cannot have explicit memory specificator. - Bad storage class. - Pointer to function required. - Function required. - Pointer required. - Illegal pointer conversion to double. - Integer type needed. - Members can not have memory specifier. - Members can not be of bit or sbit type. - Too many initializers. - Too many initializers of subaggregate. - Already used [%s]. - Address must be greater than 0. - [%s] Identifier redefined. - User abort. - Expression must be greater then 0. - Invalid declarator expected '(' or identifier. - Typdef name redefined: [%s]. - Declarator error. - Specifer/qualifier list expected. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 83 CHAPTER 2 Environment mikroBasic for 8051 - [%s] already used. - ILevel can be used only with interrupt service routines. - ';' expected but [%s] found. - Expected'[{'. - [%s] Identifier redefined. - '(' expected but [%s] found. - ')' expected but [%s] found. - 'case' out of switch. - ':' expected but [%s] found. - 'default' label out of switch. - Switch expression must evaluate to integral type. - While expected but [%s] found. - 'continue' outside of loop. - Unreachable code. - Label redefined. - Too many chars. - Unresolved type. - Arrays of objects containing zero-size arrays are illegal. - Invalid enumerator. - ILevel can be used only with interrupt service routines. - ILevel value must be integral constant. - ILevel out of range [0..4]. - '}' expected but [%s] found. - '(' expected but [%s] found. - 'break' outside of loop or switch. - Empty char. - Nonexistent field [%s]. - Illegal char representation: [%s]. - Initializer syntax error: multidimension array missing subscript. - Too many initializers of subaggregate. - At least one Search Path must be specified. - Not enough RAM for call satck. - Parameter [%s] must not be of bit or sbit type. - Function must not have return value of bit or sbit type. - Redefinition of [%s] already defined in [%s]. - Main function is not defined. - System routine not found for initialization of: [%s]. - Bad agregate definition [%s]. - Unresolved extern [%s]. - Bad function absolute address [%s]. - Not enough RAM [%s]. - Compilation Started. - Compiled Successfully. - Finished (with errors): 01 Mar 2008, 14:22:26 - Project Linked Successfully. - All files Preprocessed in [%s] ms. - All files Compiled in [%s] ms. - Linked in [%s] ms. - Project [%s] completed: [%s] ms. 84 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment LINKER ERROR MESSAGES: - Linker error: "%s" "%s". - Warning: Variable "%s" is not initialized. - Warning: Return value of the function "%s" is not defined. - Hint: Constant "%s" has been declared, but not used. - Warning: Identifier "%s" overrides declaration in unit "%s". - Constant "%s" was not found. - Address of the routine has already been defined. - Duplicated label "%s". - File "%s" not found. HINT MESSAGES: - Hint: Variable "%s" has been declared, but not used. Warning: Variable "%s" is not initialized. Warning: Return value of the function "%s" is not defined. Hint: Constant "%s" has been declared, but not used. Warning: Identifier "%s" overrides declaration in unit "%s". Warning: Generated baud rate is "%s" bps (error ="%s" percent). Warning: Result size may exceed destination array size. Warning: Infinite loop. Warning: Implicit typecast performed from "%s" to "%s". Hint: Unit "%s" has been recompiled. Hint: Variable "%s" has been eliminated by optimizer. Warning: Implicit typecast of integral value to pointer Warning: Library "%s" was not found in search path. Warning: Interrupt context saving has been turned off. Hint: Compiling unit "%s". MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 85 CHAPTER 2 mikroBasic for 8051 Environment SOFTWARE SIMULATOR OVERVIEW The Source-level Software Simulator is an integral component of the mikroBasic for 8051 environment. It is designed to simulate operations of the 8051 MCUs and assist the users in debugging Basic code written for these devices. After you have successfully compiled your project, you can run the Software Simulator by selecting Run › Start Debugger from the drop-down menu, or by clicking the Start Debugger Icon from the Debugger Toolbar. Starting the Software Sim- ulator makes more options available: Step Into, Step Over, Step Out, Run to Cursor, etc. Line that is to be executed is color highlighted (blue by default). Note: The Software Simulator simulates the program flow and execution of instruction lines, but it cannot fully emulate 8051 device behavior, i.e. it doesn’t update timers, interrupt flags, etc. Watch Window The Software Simulator Watch Window is the main Software Simulator window which allows you to monitor program items while simulating your program. To show the Watch Window, select View › Debug Windows › Watch from the drop-down menu. The Watch Window displays variables and registers of the MCU, along with their addresses and values. There are two ways of adding variable/register to the watch list: - by its real name (variable's name in "Basic" code). Just select desired variable/register from Select variable from list drop-down menu and click the Add Button . - by its name ID (assembly variable name). Simply type name ID of the variable/register you want to display into Search the variable by assemby name box and click the Add Button . Variables can also be removed from the Watch window, just select the variable that you want to remove and then click the Remove Button Add All Button 86 . adds all variables. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 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. Also, you can choose the format of variable/register representation between decimal, hexadecimal, binary, float or character. All representations except float are unsigned by default. For signed representation click the check box next to the Signed label. An item's value can be also changed by double clicking item's value field and typing the new value directly. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 87 CHAPTER 2 mikroBasic for 8051 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. Delta represents the number of cycles between the lines where Software Simulator action has started and ended. Note: The user can change the clock in the Stopwatch Window, which will recalculate values for the latest specified frequency. Changing the clock in the Stopwatch Window does not affect actual project settings – it only provides a simulation. 88 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic for 8051 Specifics 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 89 CHAPTER 2 mikroBasic for 8051 Environment SOFTWARE SIMULATOR OPTIONS Name Description: Start Debugger Start Software Simulator. Run/Pause Debugger Run or pause Software Simulator. 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. Run to cursor Execute all instructions between the current instruction and cursor position. Step Into Execute the current Basic (single or multi–cycle) instruction, then halt. If the instruction is a routine call, enter the routine and halt at the first instruction following the call. Step Over Execute the current Basic (single or multi–cycle) instruction, then halt. Step Out Execute all remaining instructions in the current routine, return and then halt. Related topics: Run Menu, Debug Toolbar 90 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic for 8051 Environment CREATING NEW LIBRARY mikroBasic for 8051 allows you to create your own libraries. In order to create a library in mikroBasic for 8051 follow the steps bellow: 1. Create a new Basic source file, see Managing Source Files 2. Save the file in the compiler's Uses folder: DriveName:\Program 8051\Uses\__Lib_Example.mbas Files\Mikroelektronika\mikroBasic 3. Write a code for your library and save it. 4. Add __Lib_Example.mbas file in some project, see Project Manager. Recompile the project. 5. Compiled file __Lib_Example.mcl should appear in ...\mikroBasic 8051\Uses\ folder. 6. Open the definition file for the MCU that you want to use. This file is placed in the compiler's Defs folder: DriveName:\Program Files\Mikroelektronika\mikroBasic 8051\Defs\ and it is named MCU_NAME.mlk, for example AT89S8253.mlk 7. Add the Library_Alias and Library_Name at the end of the definition file, for example #pragma SetLib([Example_Library, __Lib_Example]) 8. Add Library to mlk file for each MCU that you want to use with your library. 9. Click Refresh button in Library Manager Multiple Library Versions Library Alias represents unique name that is linked to corresponding Library .mcl file. For example UART library for AT89S8253 is different from UART library for AT89S4051 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. This approach enables you to have identical representation of UART library for both MCUs in Library Manager. Related topics: Library Manager, Project Manager, Managing Source Files MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 91 CHAPTER 2 Environment 92 mikroBasic for 8051 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic for 8051 Specific The following topics cover the specifics of mikroBasic compiler: - Basic Standard Issues - Predefined Globals and Constants - Accessing Individual Bits - Interrupts - 8051 Pointers - Linker Directives - Built-in Routines - Code Optimization 93 CHAPTER 3 mikroBasic for 8051 Specifics BASIC STANDARD ISSUES Divergence from the Basic Standard Function recursion is not supported because of no easily-usable stack and limited memory 8051 Specific Basic Language Exstensions mikroBasic for 8051 has additional set of keywords that do not belong to the standard Basic language keywords: - code data idata bdata xdata pdata small compact large at sbit bit sfr ilevel Related topics: Keywords, 8051 Specific 94 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic for 8051 Specifics PREDEFINED GLOBALS AND CONSTANTS In order to facilitate 8051 programming, mikroBasic for 8051 implements a number of predefined globals and constants. SFRs and related constants All 8051 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 for 8051 will include an appropriate (*.mbas) file from defs folder, containing declarations of available SFRs and constants (such as PORTB, ADPCFG, etc). All identifiers are in upper case, identical to nomenclature in the Microchip datasheets. For a complete set of predefined globals and constants, look for “Defs” in the mikroBasic for 8051 installation folder, or probe the Code Assistant for specific letters (Ctrl+Space in the Code Editor). Math constants In addition, several commonly used math constants are predefined in mikroBasic for 8051: PI PI_HALF TWO_PI E = 3.1415926 = 1.5707963 = 6.2831853 = 2.7182818 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 95 CHAPTER 3 mikroBasic for 8051 Specifics ACCESSING INDIVIDUAL BITS The mikroBasic for 8051 allows you to access individual bits of 8-bit variables. It also supports sbit and bit data types Accessing Individual Bits Of Variables Simply use the direct member selector (.) with a variable, followed by one of identifiers 0, 1, … , 15 with 15 being the most significant bit. There is no need of any special declarations. This kind of selective access is an intrinsic feature of mikroBasic for 8051 and can be used anywhere in the code. Identifiers 0–15 are not case sensitive and have a specific namespace. You may override them with your own members 0–15 within any given structure. If you are familiar with a particular MCU, you can also access bits by name: ' Clear Bit 3 on Port0 P0.B3 = 0 See Predefined Globals and Constants for more information on register/bit names. sbit type The mikroBasic Compiler have sbit data type which provides access to bit-addressable SFRs. For example: dim LEDA as sbit at P0.0 dim Name as sbit at sfr-name.<Bbit-position> The previously declared SFR (sfr-name) is the base address for the sbit. It must be evenly divisible by 8. The bit-position (which must be a number from 0-7) follows the dot symbol ('.') and specifies the bit position to access. For example: dim OV as sbit at PSW.2 dim CY as sbit at PSW.7 96 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic for 8051 Specifics bit type The mikroBasic 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 All bit variables are stored in a bit addressable portion 0x20-0x2F segment located in the internal memory area of the 8051. Because this area is only 16 bytes long, a maximum of 128 bit variables may be declared within any one scope. 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 Bit variables can not be initialized nor they can be members of structures and unions. Related topics: Predefined globals and constants MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 97 CHAPTER 3 mikroBasic for 8051 Specifics INTERRUPTS 8051 derivates acknowledges an interrupt request by executing a hardware generated LCALL 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 0 Overflow interrupt source of the AT89S8253. For more information on interrupts and IVT refer to the specific data sheet. Function Calls from Interrupt Calling functions from within the interrupt routine is allowed. The compiler takes care about the registers being used, both in "interrupt" and in "main" thread, and performs "smart" context-switching between them two, saving only the registers that have been used in both threads. It is not recommended to use function call from interrupt. In case of doing that take care of stack depth. Interrupt Priority Level 8051 MCUs has possibilty to assign different priority level trough setting appropriate values to coresponding SFRs. You should also assign ISR same priority level by ilevel keyword followed by interrupt priority number. Available interrupt priority levels are: 0 (default), 1, 2 and 3. sub procedure Timer0ISR() org 0x000B ilevel 2 //set Timer0ISR to be ISR for Timer 0 Overflow priority level 2. end sub Related topics: Basic standard issues 98 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic for 8051 Specifics LINKER DIRECTIVES mikroBasic for 8051 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. If the variable spans more than 1 word (16-bit), higher words will be stored at the consecutive locations. The absolute directive is appended to the declaration of a variable: dim x as word absolute 0x32 ' Variable x will occupy 1 word (16 bits) at address 0x32 dim y as longint absolute 0x34 ' Variable y will occupy 2 words at addresses 0x34 and 0x36 Be careful when using absolute directive, as you may overlap two variables by accident. For example: dim i as word absolute 0x42 ' Variable i will occupy 1 word at address 0x42; dim jj as longint absolute 0x40 ' Variable will occupy 2 words at 0x40 and 0x42; thus, ' changing i changes jj at the same time and vice versa Note: You must specify an even address when using the directive absolute. Directive org The directive org specifies the starting address of a routine in ROM. It is appended to the declaration of routine. For example: sub procedure proc(dim par as word) org 0x200 ' Procedure will start at the address 0x200; ... end sub Note: You must specify an even address when using the directive org. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 99 CHAPTER 3 mikroBasic for 8051 Specifics BUILT-IN ROUTINES The mikroBasic for 8051 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. code is generated in the place of a call, so the call doesn’t count against the nested call limit. The Vdelay_ms, Delay_Cyc and Get_Fosc_kHz are actual Basic routines. Their sources can be found in Delays.mbas file located in the uses folder of the compiler. - Lo Hi Higher Highest - Inc - Dec - Delay_us Delay_ms Vdelay_ms Delay_Cyc - Clock_Khz - Clock_Mhz - SetFuncCall - Uart_Init 100 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic for 8051 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. Arithmetic Types and Pointers). Example d = 0x1AC30F4 tmp = Lo(d) ' Equals 0xF4 Hi Prototype sub function Hi(number as longint) as byte Returns Returns next to the lowest byte of number, bits 8..15. Function returns next to the lowest byte of number. Function does not interpret bit patterns of number – it merely returns 8 bits as found in register. Description This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Requires Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers). Example d = 0x1AC30F4 tmp = Hi(d) ' Equals 0x30 Higher Prototype sub function Higher(number as longint) as byte Returns Returns next to the highest byte of number, bits 16..23. Function returns next to 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. Requires Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers). Example d = 0x1AC30F4 tmp = Higher(d) ' Equals 0xAC MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 101 CHAPTER 3 mikroBasic for 8051 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. Requires Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers). Example d = 0x1AC30F4 tmp = Highest(d) ' Equals 0x01 Inc Prototype sub procedure Inc(dim byref par as longint) Returns Nothing. Description Increases parameter par by 1. Requires Nothing. Example p = 4 Inc(p) ' p is now 5 Dec Prototype sub procedure Dec(dim byref par as longint) Returns Nothing. Description Decreases parameter par by 1. 102 Requires Nothing. Example p = 4 Dec(p) ' p is now 3 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic for 8051 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. Example Delay_us(1000) ' One millisecond pause Delay_ms Prototype sub procedure Delay_ms(const time_in_ms as longword) Returns Nothing. Creates a software delay in duration of time_in_ms milliseconds (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. Example Delay_ms(1000) ' One second pause Vdelay_ms Prototype sub procedure Vdelay_ms(time_in_ms as word) Returns Nothing. Creates a software delay in duration of time_in_ms milliseconds (a variable). Generated delay is not as precise as the delay created by Delay_ms. Description Note that Vdelay_ms is library function rather than a built-in routine; it is presented in this topic for the sake of convenience. Requires Nothing. Example pause = 1000 ' ... Vdelay_ms(pause) ' ~ one second pause MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 103 CHAPTER 3 mikroBasic for 8051 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. Example Delay_Cyc(10) ' Hundred MCU cycles pause Clock_KHz Prototype sub function Clock_Khz() as word Returns Device clock in KHz, rounded to the nearest integer. Function returns device clock in KHz, rounded to the nearest integer. 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. Example clk = Clock_kHz() Clock_MHz Prototype sub function Clock_MHz() as byte Returns Device clock in MHz, rounded to the nearest integer. Function returns device clock in MHz, rounded to the nearest integer. Description 104 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. Example clk = Clock_Mhz() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic for 8051 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. Requires Nothing. Example sub procedure first(p, q as byte) ... SetFuncCall(second) ' let linker know that we will call the routine 'second' ... end sub Uart_Init Prototype sub procedure Uart_Init(baud_rate as longword) Returns Nothing. Configures and initializes the UART module. The internal UART module module is set to: Description - 8-bit data, no parity 1 STOP bit disabled automatic address recognition timer1 as baudrate source (mod2 = autoreload 8bit timer) Parameters : - baud_rate: requested baud rate Refer to the device data sheet for baud rates allowed for specific Fosc. Requires MCU with the UART module and TIMER1 to be used as baudrate source. Example // Initialize hardware UART and establish communication at 2400 bps Uart_Init(2400) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 105 CHAPTER 3 mikroBasic for 8051 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. (3 + 5 -> 8); Constant propagation When a constant value is being assigned to a certain variable, the compiler recognizes this and replaces the use of the variable by constant in the code that follows, as long as the value of a variable remains unchanged. Copy propagation The compiler recognizes that two variables have the same value and eliminates one of them further in the code. Value numbering The compiler "recognizes" if two expressions yield the same result and can therefore eliminate the entire computation for one of them. "Dead code" ellimination The code snippets that are not being used elsewhere in the programme do not affect the final result of the application. They are automatically removed. Stack allocation Temporary registers ("Stacks") are being used more rationally, allowing VERY complex expressions to be evaluated with a minimum stack consumption. Local vars optimization No local variables are being used if their result does not affect some of the global or volatile variables. Better code generation and local optimization Code generation is more consistent and more attention is payed to implement specific solutions for the code "building bricks" that further reduce output code size. 106 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 8051 Specifics Types Efficiency First of all, you should know that 8051 ALU, which performs arithmetic operations, is optimized for working with bytes. Although mikroBasic is capable of handling very complex data types, 8051 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. It applies to all programming in general, and doubly so with microcontrollers. Types efficiency is determined by the part of RAM memory that is used to store a variable/constant. See the example. 107 CHAPTER 4 mikroBasic for 8051 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. Note: There are many different types of derivates, so it is necessary to be familiar with characteristics and special features of the microcontroller in you are using. 8051 MEMORY ORGANIZATION The 8051 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. Program Memory (ROM) Program Memory (ROM) is used for permanent saving program (CODE) being executed. The memory is read only. Depending on the settings made in compiler, program memory may also used to store a constant variables. The 8051 executes programs stored in program memory only. code memory type specifier is used to refer to program memory. 8051 memory organization alows external program memory to be added. How does the microcontroller handle external memory depends on the pin EA logical state. 108 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroBasic for 8051 8051 Specifics Internal Data Memory Up to 256 bytes of internal data memory are available depending on the 8051 derivative. Locations available to the user occupy addressing space from 0 to 7Fh, i.e. first 128 registers and this part of RAM is divided in several blocks. The first 128 bytes of internal data memory are both directly and indirectly addressable. The upper 128 bytes of data memory (from 0x80 to 0xFF) can be addressed only indirectly. Since internal data memory is used for CALL stack also and there is only 256 bytes splited over few different memory areas fine utilizing of this memory is crucial for fast and compact code. See types efficiency also. Memory block in the range of 20h to 2Fh is bit-addressable, which means that each bit being there has its own address from 0 to 7Fh. Since there are 16 such registers, this block contains in total of 128 bits with separate addresses ( Bit 0 of byte 20h has the bit address 0, and bit 7 of byte 2Fh has the bit address 7Fh). Three memory type specifiers can be used to refer to the internal data memory: data, idata, and bdata. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 109 CHAPTER 4 mikroBasic for 8051 8051 Specifics External Data Memory Access to external memory is slower than access to internal data memory. There may be up to 64K Bytes of external data memory. Several 8051 devices provide onchip XRAM space that is accessed with the same instructions as the traditional external data space. This XRAM space is typically enabled via proper setting of SFR register and overlaps the external memory space. Setting of that register must be manualy done in code, before any access to external memory or XRAM space is made. The mikroBasic for 8051 has two memory type specifiers that refers to external memory space: xdata and pdata. SFR Memory The 8051 provides 128 bytes of memory for Special Function Registers (SFRs). SFRs are bit, byte, or word-sized registers that are used to control timers, counters, serial I/O, port I/O, and peripherals. Refer to Special Function Registers for more information. See sbit also. Related topics: Accessing individual bits, SFRs, Memory type specifiers, Memory models 110 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroBasic for 8051 8051 Specifics MEMORY MODELS The memory model determines the default memory type to use for function arguments, automatic variables, and declarations that include no explicit memory type. The mikroBasic for 8051 provides three memory models: - Small - Compact - Large You may also specify the memory model on a function-by-function basis by adding the memory model to the function declaration. Small memory model generates the fastest, most efficient code. This is default memory model. You may override the default memory type imposed by the memory model by explicitly declaring a variable with a memory type specifier. Small model In this model, all variables, by default, reside in the internal data memory of the 8051 system—as if they were declared explicitly using the data memory type specifier. In this memory model, variable access is very efficient. However, all objects (that are not explicitly located in another memory area) and the call stack must fit into the internal RAM. Call Stack size is critical because the stack space used depends on the nesting depth of the various functions. Compact model Using the compact model, by default, all variables are allocated in a single page 256 bytes of external data memory of the 8051 system—as if they were explicitly declared using the pdata memory type specifier. This memory model can accommodate a maximum of 256 bytes of variables. The limitation is due to the addressing scheme used which is indirect through registers R0 and R1 (@R0, @R1). This memory model is not as efficient as the small model and variable access is not as fast. However, the compact model is faster than the large model. mikroBasic for 8051 uses the @R0 and @R1 operands to acess external memory with instructions that use 8 bit wide pointers and provide only the low-order byte of the address. The high-order address byte (or page) is provided by Port 2 on most 8051 derivates (see data sheet for details). MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 111 CHAPTER 4 mikroBasic for 8051 8051 Specifics Large model In the large model all variables reside in external data memory (which may be up to 64K Bytes). This is the same as if they were explicitly declared using the xdata memory type specifier. The DPTR is used to address external memory. Instruction set is not optimized for this memory model(access to external memory) so it neeeds more code than the small or compact model to manipulate with the variables. sub function xadd(dim a1 as byte, dim a2 as byte) as byte; large 'allocate parameters and local variables in xdata space return xadd = a1+a2 end sub Related topics: Memory type specifiers, 8051 Memory Organization, Accessing individual bits, SFRs, Project Settings MEMORY TYPE SPECIFIERS The mikroBasic for 8051 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 (based on a memory model). The following memory type specifiers can be used: - code data idata bdata xdata pdata Memory type specifiers can be included in svariable declaration. For example: data data_buffer as byte xdata x_data as array[100] of byte ory idata ibuffer as real ' puts data_buffer in data ram ' puts array in external mem' puts ibuffer in idata ramm If no memory type is specified for a variable, the compiler locates the variable in the memory space determined by the memory model: Small, Compact, or Large. 112 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroBasic for 8051 8051 Specifics code Program memory (64 KBytes); accessed by opcode MOVC @A+DPTR. Description Example The code memory type may be used for constants and functions. This memory is accessed using 16-bit addresses and may be on-chip or external. ' puts txt in program memory code const txt as string[11] = 'Enter text:' data Directly addressable internal data memory; fastest access to variables (128 bytes). Description Example This memory is directly accessed using 8-bit addresses and is the on-chip RAM of the 8051. It has the shortest (fastest) access time but the amount of data is limited in size (to 128 bytes or less). ' puts x in data ram data x as byte idata Indirectly addressable internal data memory; accessed across the full internal address space (256 bytes). Description Example This memory is indirectly accessed using 8-bit addresses and is the on-chip RAM of the 8051. The amount of idata is limited in size (to 128 bytes or less) it is upper 128 addresses of RAM ' puts x in idata ram idata x as byte bdata Bit-addressable internal data memory; supports mixed bit and byte access (16 bytes). Description This memory is directly accessed using 8-bit addresses and is the on-chip bitaddressable RAM of the 8051. Variables declared with the bdata type are bitaddressable and may be read and written using bit instructions. For more information about the bdata type refer to the Accessing Individual Bits. Example ' puts x in bdata bdata x as byte MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 113 CHAPTER 4 mikroBasic for 8051 8051 Specifics xdata External data memory (64 KBytes); accessed by opcode MOVX @DPTR. Description Example This memory is indirectly accessed using 16-bit addresses and is the external data RAM of the 8051. The amount of xdata is limited in size (to 64K or less). ' puts x in xdata xdata x as byte pdata Paged (256 bytes) external data memory; accessed by opcode MOVX @Rn. Description This memory is indirectly accessed using 8-bit addresses and is one 256-byte page of external data RAM of the 8051. The amount of pdata is limited in size (to 256 bytes). Example ' puts x in pdata pdata x as byte Related topics: 8051 Memory Organization, Memory models, Accessing individual bits, SFRs, Constants, Functions 114 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic Language Reference The mikroBasic for 8051 Language Reference describes the syntax, semantics and implementation of the mikroBasic for 8051 language. The aim of this reference guide is to provide a more understandable description of the mikroBasic for 8051 language to the user. 115 CHAPTER 5 mikroBasic for 8051 Language Reference MIKROBASIC 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 Associativity Arithmetic Operators Relational Operators Bitwise Operators Boolean Operators Expressions Expressions 116 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference Statements Introduction to Statements Assignment Statements Conditional Statements 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 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 117 CHAPTER 5 mikroBasic for 8051 Language Reference LEXICAL ELEMENTS OVERVIEW These topics provide a formal definition of the mikroBasic for 8051 lexical elements. They describe different categories of word-like units (tokens) recognized by the language. In tokenizing phase of compilation, the source code file is parsed (that is, broken down) into tokens and whitespace. The tokens in mikroBasic are derived from a series of operations performed on your programs by the compiler. A mikroBasic program starts as a sequence of ASCII characters representing the source code, created by keystrokes using a suitable text editor (such as the mikroBasic Code Editor). The basic program unit in mikroBasic is a file. This usually corresponds to a named file located in RAM or on disk, having the extension .mbas. 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. Newline Character Newline character (CR/LF) is not a whitespace in BASIC, and serves as a statement terminator/separator. In mikroBasic for 8051, however, you may use newline to break long statements into several lines. Parser will first try to get the longest possible expression (across lines if necessary), and then check for statement terminators. 118 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference Whitespace in Strings The ASCII characters representing whitespace can occur within string literals, where they are protected from the normal parsing process (they remain as a part of the string). For example, statement some_string = "mikro foo" parses to four tokens, including a single string literal token: some_string = "mikro foo" newline character 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. There are no multi-line comments in mikroBasic for 8051 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 119 CHAPTER 5 mikroBasic for 8051 Language Reference TOKENS Token is the smallest element of a mikroBasic for 8051 program, meaningful to the compiler. The parser separates tokens from the input stream by creating the longest token possible using the input characters in a left–to–right scan. mikroBasic for 8051 recognizes the following kinds of tokens: - keywords identifiers constants operators punctuators (also known as separators) Token Extraction Example Here is an example of token extraction. See the following code sequence: end_flag = 0 The compiler would parse it into four tokens: end_flag = 0 newline ' variable identifier ' assignment operator ' literal ' statement terminator Note that end_flag would be parsed as a single identifier, rather than the keyword end followed by the identifier _flag. 120 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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. In decimal notation, numerals are represented as a sequence of digits (without commas, spaces or dots), with optional prefix + or - operator to indicate the sign. Values default to positive (6258 is equivalent to +6258). The dollar-sign prefix ($) or the prefix 0x indicates a hexadecimal numeral (for example, $8F or 0x8F). The percent-sign prefix (%) indicates a binary numeral (for example, %0101). Here are some examples: 11 $11 0x11 %11 ' ' ' ' decimal literal hex literal, equals decimal 17 hex literal, equals decimal 17 binary literal, equals decimal 3 The allowed range of values is imposed by the largest data type in mikroBasic for 8051 – longword. The compiler will report an error if the literal exceeds 4294967295 ($FFFFFFFF). Floating Point Literals A floating-point value consists of: - Decimal integer Decimal point Decimal fraction e or E and a signed integer exponent (optional) You can omit either decimal integer or decimal fraction (but not both). Negative floating constants are taken as positive constants with the unary operator minus (-) prefixed. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 121 CHAPTER 5 mikroBasic for 8051 Language Reference mikroBasic 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"). Character literal can be assigned to variables of byte and char type (variable of byte will be assigned the ASCII value of the character). Also, you can assign character literal to a string variable. String Literals String literal is a sequence of characters from the extended ASCII character set, enclosed with quotes. Whitespace is preserved in string literals, i.e. parser does not “go into” strings but treats them as single tokens. Length of string literal is a number of characters it consists of. String is stored internally as the given sequence of characters plus a final null character. This null character is introduced to terminate the string, it does not count against the string’s total length. String literal with nothing in between the quotes (null string) is stored as a single null character. You can assign string literal to a string variable or to an array of char. Here are several string literals: "Hello world!" "Temperature is stable" " " "C" "" ' message, 12 chars long ' message, 21 chars long ' two spaces, 2 chars long ' letter, 1 char long ' null string, 0 chars long The quote itself cannot be a part of the string literal, i.e. there is no escape sequence. You could use the built-in function Chr to print a quote: Chr(34). Also, see String Splicing. 122 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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. Here is the alphabetical listing of keywords in mikroBasic for 8051: - abs and appactivate array as asc asm atn attribute base bdata beep begin bit boolean byte call case cbool cbyte ccur cdate cdate cdbl char chdir chdrive chr cint circle class clear clng close code command MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 123 CHAPTER 5 mikroBasic for 8051 Language Reference - 124 compact compare const cos createobject csng cstr curdir currency cvar cverr date dateadd datediff datepart dateserial datevalue ddb deftype dim dir div do doevents double each empty end end environ eof eqv erase err error exit exp explicit explicit fileattr fileattr filecopy filedatetime filelen fix float for form format MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference - forward freefile fv get getattr getobject gosub goto hex hour idata if iif ilevel imp include input instr int integer ipmt irr is isarray isdate isempty iserror ismissing isnull isnumeric isobject kill large lbound lcase left len let line loc lock lof log long longint loop lset ltrim me mid MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 125 CHAPTER 5 mikroBasic for 8051 Language Reference - 126 minute mirr mkdir mod module month msgbox name new next not not nothing now nper npv object oct on open option option option or org pdata pmt ppmt print private property pset public put pv qbcolor raise randomize rate real redim rem reset resume return rgb right rmdir rnd rset MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference - rtrim sbit second seek select sendkeys set setattr sfr sgn shell short sin single sln small space spc sqr static step stop str strcomp strconv string sub switch syd system tab tan time timer timeserial timevalue to trim typedef typename ubound ucase unlock until val variant vartype version volatile MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 127 CHAPTER 5 mikroBasic for 8051 Language Reference - weekday wend while width with word write xdata xor Also, mikroBasic includes a number of predefined identifiers used in libraries. You could replace them by your own definitions, if you plan to develop your own libraries. For more information, see mikroBasic Libraries. 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. First character must be a letter or an underscore, i.e. identifier cannot begin with a numeral. Case Sensitivity mikroBasic for 8051 is not case sensitive, so Sum, sum, and suM are equivalent identifiers. Uniqueness and Scope Although identifier names are arbitrary (within the rules stated), errors result if the same name is used for more than one identifier within the same scope. Simply, duplicate names are illegal within the same scope. For more information, refer to Scope and Visibility. 128 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference Identifier Examples Here are some valid identifiers: temperature_V1 Pressure no_hit dat2string SUM3 _vtext … and here are some invalid identifiers: 7temp %higher xor j23.07.04 ' NO -- cannot begin with a numeral ' NO -- cannot contain special characters ' NO -- cannot match reserved word ' NO -- cannot contain special characters (dot) PUNCTUATORS The mikroBasic 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 129 CHAPTER 5 Language Reference mikroBasic for 8051 Parentheses Parentheses ( ) are used to group expressions, isolate conditional expressions and indicate function calls and function declarations: d = c * (a + b) ' Override normal precedence if (d = z) then ... ' Useful with conditional statements func() ' Function call, no arguments sub function func2(dim n as word)' Function declaration w/ parameters For more information, refer to Operators Precedence and Associativity, Expressions, or Functions and Procedures. Comma Comma (,) separates the arguments in function calls: Lcd_Out(1, 1, txt) Furthermore, the comma separates identifiers in declarations: dim i, j, k as word The comma also separates elements in initialization lists of constant arrays: const MONTHS as byte[12] = (31,28,31,30,31,30,31,31,30,31,30,31) 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. 130 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference PROGRAM ORGANIZATION mikroBasic for 8051 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. Otherwise, the compiler may not be able to comprehend the program correctly. When writing code, follow the model presented below. The main module should look like this: program <program name> include <include other modules> '******************************************************** '* Declarations (globals): '******************************************************** ' symbols declarations symbol ... ' constants declarations const ... ' structures declarations structure ... ' variables declarations dim Name[, Name2...] as [volatile] [register] [sfr] [^]type [absolute 0x123] [external] ' procedures declarations sub procedure procedure_name(...) <local declarations> ... end sub ' functions declarations sub function function_name(...) as return_type <local declarations> ... end sub '******************************************************** '* Program body: '******************************************************** main: ' write your code here end. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 131 CHAPTER 5 mikroBasic for 8051 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 <module name> include <include other modules> '******************************************************** '* Interface (globals): '******************************************************** ' symbols declarations symbol ... ' constants declarations const ... ' structures declarations structure ... ' variables declarations dim Name[, Name2...] as [volatile] [register] [sfr] [^]type [absolute 0x123] [external] ' procedures prototypes sub procedure sub_procedure_name([dim byref] [const] ParamName as [^]type, [dim byref] [const] ParamName2, ParamName3 as [^]type) ' functions prototypes sub function sub_function_name([dim byref] [const] ParamName as [^]type, [dim byref] [const] ParamName2, ParamName3 as [^]type) as [^]type '******************************************************** '* Implementation: '******************************************************** implements ' constants declarations const ... ' variables declarations dim ... ' procedures declarations sub procedure sub_procedure_name([dim byref] [const] ParamName as [^]type, [dim byref] [const] ParamName2, ParamName3 as [^]type); [ilevel 0x123] [overload] [forward] <local declarations> ... end sub 132 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference ' 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] <local declarations> ... end sub end. Note: Sub functions and sub procedures must have the same declarations in the interface and implementation section. Otherwise, compiler will report an error. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 133 CHAPTER 5 mikroBasic for 8051 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 Identifier is declared in the declaration section of the main module, out of any function or procedure Scope extends from the point where it is declared to the end of the current file, including all routines enclosed within that scope. These identifiers have a file scope and are referred to as globals. Scope extends from the point where it is declared to Identifier is declared in the the end of the current routine. These identifiers are function or procedure referred to as locals. Scope extends the interface section of a module from the point where it is declared to the end of the Identifier is declared in the module, and to any other module or program that interface section of the uses that module. The only exception are symbols module which have a scope limited to the file in which they are declared. Identifier is declared in the Scope extends from the point where it is declared to implementation section of the end of the module. The identifier is available to the module, but not within any function or procedure in the module. any function or procedure Visibility The visibility of an identifier is a region of the program source code from where a legal access to the identifier’s associated object can be made . Scope and visibility usually coincide, though there are circumstances under which an object becomes temporarily hidden by the appearance of a duplicate identifier: the object still exists but the original identifier cannot be used to access it until the scope of the duplicate identifier is ended. Technically, visibility cannot exceed scope, but scope can exceed visibility. 134 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference MODULES In mikroBasic for 8051, each project consists of a single project file and one or more module files. The project file, with extension .mbproj 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. Modules allow you to: - break large programs into encapsulated modules that can be edited separately, - create libraries that can be used in different projects, - distribute libraries to other developers without disclosing the source code. Each module is stored in its own file and compiled separately; compiled modules are linked to create an application. To build a project, the compiler needs either a source file or a compiled module file for each module. Include Clause mikroBasic includes modules by means of the include clause. It consists of the reserved word include, followed by a quoted module name. Extension of the file should not be included. You can include one file per include clause. There can be any number of the include clauses in each source file, but they all must be stated immediately after the program (or module) name. Here’s an example: program MyProgram include "utils" include "strings" include "MyUnit" ... For the given module name, the compiler will check for the presence of .mcl and .mbasj files, in order specified by search paths. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 135 CHAPTER 5 mikroBasic for 8051 Language Reference - If both .mbasj and .mcl files are found, the compiler will check their dates and include the newer one in the project. If the .mbasj file is newer than the .mcl, then .mbasj file will be recompiled and new .mcl will be created, overwriting the old .mcl. - If only the .mbasj file is found, the compiler will create the .mcl file and include it in the project; - If only the .mcl file is present, i.e. no source code is available, the compil er will include it as found; - If none of the files found, the compiler will issue a “File not found” warning. Main Module Every project in mikroBasic 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. Other than comments, nothing should precede the keyword program. After the program name, you can optionally place the include clauses. Place all global declarations (constants, variables, labels, routines, structures) before the label main. Other Modules Modules other than main start with the keyword module. Newly created blank module contains the bare-bones: module MyModule implements end. Other than comments, nothing should precede the keyword module. After the module name, you can optionally place the include clauses. 136 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference Interface Section Part of the module above the keyword implements is referred to as interface section. Here, you can place global declarations (constants, variables, labels, routines, structures) for the project. Do not define routines in the interface section. Instead, state the prototypes of routines (from implementation section) that you want to be visible outside the module. Prototypes must exactly match the declarations. 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. By placing the prototype in the interface section of the module (above the implements) you can make the routine public, i.e. visible outside of module. Prototypes must exactly match the declarations. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 137 CHAPTER 5 Language Reference mikroBasic for 8051 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. Global variables (those that do not belong to any enclosing block) are declared below the include statements, above the label main. Specifying a data type for each variable is mandatory. mikroBasic syntax for variable declaration is: dim identifier_list as type Here, identifier_list is a comma-delimited list of valid identifiers, and type can be any data type. For more details refer to Types and Types Conversions. For more information on variables’ scope refer to the chapter Scope and Visibility. Here are a few examples: dim i, j, k as byte dim counter, temp as word dim samples as longint[100] Variables and 8051 Every declared variable consumes part of RAM memory. Data type of variable determines not only the allowed range of values, but also the space a variable occupies in RAM memory. Bear in mind that operations using different types of variables take different time to be completed. mikroBasic for 8051 recycles local variable memory space – local variables declared in different functions and procedures share the same memory space, if possible. There is no need to declare SFR explicitly, as mikroBasic for 8051 automatically declares relevant registers as global variables of word. For example: W0, TMR1, etc. 138 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference 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. It is a tradition to write constant names in uppercase. Constant requires you to specify value, which is a literal appropriate for the given type. type is optional and in the absence of it , the compiler assumes the “smallest” type that can accommodate value. Note: You cannot omit type if declaring a constant array. Here are a few examples: const const const const const MAX as longint = 10000 MIN = 1000 ' compiler will assume word type SWITCH = "n" ' compiler will assume char type MSG = "Hello" ' compiler will assume string type MONTHS as byte[12] = (31,28,31,30,31,30,31,31,30,31,30,31) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 139 CHAPTER 5 Language Reference mikroBasic for 8051 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 for 8051. 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. Do not mark more than one statement in a block with the same label. Note: The label main marks the entry point of a program and must be present in the main module of every project. See Program Organization for more information. Here is an example of an infinite loop that calls the procedure Beep repeatedly: loop: Beep goto loop 140 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference SYMBOLS mikroBasic 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. Scope of a symbol is always limited to the file in which it has been declared. Symbol is declared as: symbol alias = code Here, alias must be a valid identifier which you will use throughout the code. This identifier has a file scope. The code can be any line of code (literals, assignments, function calls, etc). Using a symbol in the program consumes no RAM – the compiler will simply replace each instance of a symbol with the appropriate line of code from the declaration. Here is an example: symbol MAXALLOWED = 216 symbol PORT = P0 symbol MYDELAY = Delay_ms(1000) dim cnt as byte ' Symbol as alias for numeric value ' Symbol as alias for SFR ' Symbol as alias for procedure call ' Some variable '... main: if cnt > MAXALLOWED then cnt = 0 PORT.1 = 0 MYDELAY end if Note: Symbols do not support macro expansion in a way the C preprocessor does. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 141 CHAPTER 5 Language Reference mikroBasic for 8051 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. FUNCTIONS Function is declared like this: sub function function_name(parameter_list) as return_type [ local declarations ] function body end sub function_name represents a function’s name and can be any valid identifier. return_type is a type of return value and can be any simple type. Within parentheses, parameter_list is a formal parameter list similar to variable declaration. In mikroBasic for 8051, parameters are always passed to a function by value. To pass an argument by address, add the keyword byref ahead of identifier. Local declarations are optional declarations of variables and/or constants, local for the given function. Function body is a sequence of statements to be executed upon calling the function. Calling a function A function is called by its name, with actual arguments placed in the same sequence as their matching formal parameters. The compiler is able to coerce mismatching arguments to the proper type according to implicit conversion rules. Upon a function call, all formal parameters are created as local objects initialized by values of actual arguments. Upon return from a function, a temporary object is created in the place of the call and it is initialized by the value of the function result. This means that function call as an operand in complex expression is treated as the function result. In standard Basic, a function_name is automatically created local variable that can be used for returning a value of a function. mikroBasic for 8051 also allows you to use the automatically created local variable result to assign the return value of a function if you find function name to be too ponderous. If the return value of a function is not defined the compiler will report an error. Function calls are considered to be primary expressions and can be used in situations where expression is expected. A function call can also be a self-contained statement and in that case the return value is discarded. 142 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference 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 represents a procedure’s name and can be any valid identifier. Within parentheses, parameter_list is a formal parameter list similar to variable declaration. In mikroBasic for 8051, parameters are always passed to procedure by value; to pass argument by address, add the keyword byref ahead of identifier. Local declarations are optional declaration of variables and/or constants, local for the given procedure. Procedure body is a sequence of statements to be exe- cuted upon calling the procedure. Calling a procedure A procedure is called by its name, with actual arguments placed in the same sequence as their matching formal parameters. The compiler is able to coerce mismatching arguments to the proper type according to implicit conversion rules. Upon procedure call, all formal parameters are created as local objects initialized by values of actual arguments. Procedure call is a self-contained statement. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 143 CHAPTER 5 mikroBasic for 8051 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 for 8051. The example shows how to define and use a function pointer: Example: Example demonstrates the usage of function pointers. It is shown how to declare a procedural type, a pointer to function and finally how to call a function via pointer. program Example; typedef TMyFunctionType = function (dim param1, param2 as byte, dim param3 as word) as word ' First, define the procedural type dim MyPtr as ^TMyFunctionType defined type dim sample as word ' This is a pointer to previously sub function Func1(dim p1, p2 as byte, dim p3 as word) as word ' Now, define few functions which will be pointed to. Make sure that parameters match the type definition result = p1 and p2 or p3 end sub sub function Func2(dim abc, def as byte, dim ghi as word) as word ' Another function of the same kind. Make sure that parameters match the type definition result = abc * def + ghi end sub sub function Func3(dim first, yellow as byte, dim monday as word) as word ' Yet another function. Make sure that parameters match the type definition result = monday - yellow - first end sub ' main program: 144 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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. Language Reference ' MyPtr ' Perform 3 ' MyPtr ' Perform 5 ' MyPtr ' Perform 0 now points to Func1 function call via pointer, call now points to Func2 function call via pointer, call now points to Func3 function call via pointer, call A function can return a complex type. Follow the example bellow to learn how to declare and use a function which returns a complex type. Example: This example shows how to declare a function which returns a complex type. program Example structure TCircle ' Structure dim CenterX, CenterY as word dim Radius as byte end structure dim MyCircle as TCircle ' Global variable sub function DefineCircle(dim x, y as word, dim r as byte) as TCircle ' DefineCircle function returns a Structure result.CenterX = x result.CenterY = y result.Radius = r end sub main: MyCircle = DefineCircle(100, 200, 30) ' Get a Structure via function call MyCircle.CenterX = DefineCircle(100, 200, 30).CenterX + 20 ' Access a Structure field via function call ' |------------------------| |-----| ' | | ' Function returns TCircle Access to one field of TCircle end. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 145 CHAPTER 5 Language Reference mikroBasic for 8051 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. The following is an example of a forward declaration: program Volume dim Volume as word sub function First(a as word, b as word) as word forward sub function Second(c as word) as word dim tmp as word tmp = First(2, 3) result = tmp * c end sub sub function First(a, b as word) as word result = a * b end sub main: Volume = Second(4) end. 146 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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. mikroBasic supports many standard (predefined) and user-defined data types, including signed and unsigned integers of various sizes, arrays, strings, pointers and structures. Type Categories Types can be divided into: - simple types arrays strings pointers structures MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 147 CHAPTER 5 mikroBasic for 8051 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 for 8051 has 16 bits. Here is an overview of simple types in mikroBasic for 8051: 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 .. 4294967295 longint 32–bit -2147483648 .. 2147483647 float 32–bit ±1.17549435082 * 10-38 .. ±6.80564774407 * 1038 bit 1–bit 0 or 1 sbit 1–bit 0 or 1 You can assign signed to unsigned or vice versa only using the explicit conversion. Refer to Types Conversions for more information. 148 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference 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. Every element of an array is of type and can be accessed by specifying array name followed by element’s index within brackets. Here are a few examples of array declaration: dim weekdays as byte[7] dim samples as word[50] main: ' Now we can access elements of array variables, for example: samples[0] = 1 if samples[37] = 0 then ' ... Constant Arrays Constant array is initialized by assigning it a comma-delimited sequence of values within parentheses. For example: ' Declare a constant array which holds number of days in each month: const MONTHS as byte[12] = (31,28,31,30,31,30,31,31,30,31,30,31) Note that indexing is zero based; in the previous example, number of days in January is MONTHS[0] and number of days in December is MONTHS[11]. The number of assigned values must not exceed the specified length. Vice versa is possible, when the trailing “excess” elements will be assigned zeroes. For more information on arrays of char, refer to Strings. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 149 CHAPTER 5 mikroBasic for 8051 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. You can assign string literals or other strings to string variables. The string on the right side of an assignment operator has to be shorter than another one, or of equal length. For example: dim msg1 as string[20] dim msg2 as string[19] main: msg1 = "This is some message" msg2 = "Yet another message" msg1 = msg2 ' this is ok, but vice versa would be illegal Alternately, you can handle strings element–by–element. For example: dim s as string[5] ' ... s = "mik" ' s[0] is char literal "m" ' s[1] is char literal "i" ' s[2] is char literal "k" ' s[3] is zero ' s[4] is undefined ' s[5] is undefined Be careful when handling strings in this way, since overwriting the end of a string will cause an unpredictable behavior. Note mikroBasic for 8051 includes String Library which automatizes string related tasks. 150 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference 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. For example, let’s declare variable p which points to word, and then assign the pointed memory location value 5: dim p as ^word '... p^ = 5 A pointer can be assigned to another pointer. However, note that only address, not value, is copied. Once you modify the data located at one pointer, the other pointer, when dereferenced, also yields modified data. @ Operator The @ operator returns the address of a variable or routine, i.e. @ constructs a pointer to its operand. The following rules are applied to @: - If X is a variable, @X returns the address of X. - If F is a routine (a function or procedure), @F returns F’s entry point (the result is of longint). MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 151 CHAPTER 5 Language Reference mikroBasic for 8051 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. The scope of a member identifier is limited to the structure in which it occurs, so you don’t have to worry about naming conflicts between member identifiers and other variables. For example, the following declaration creates a structure type called Dot: structure Dot dim x as float dim y as float end structure Each Dot contains two members: x and y coordinates; memory is allocated when you instantiate the structure, like this: dim m, n as Dot This variable declaration creates two instances of Dot, called m and n. A member can be of the previously defined structure type. For example: ' Structure defining a circle: structure Circle dim radius as float dim center as Dot end structure 152 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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.y = 0 You can also commit assignments between complex variables, if they are of the same type: circle2 = circle1 ' This will copy values of all members MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 153 CHAPTER 5 mikroBasic for 8051 Language Reference TYPES CONVERSIONS Conversion of variable of one type to variable of another type is typecasting. mikroBasic for 8051 supports both implicit and explicit conversions for built-in types. Implicit Conversion Compiler will provide an automatic implicit conversion in the following situations: - statement requires an expression of particular type (according to language definition) and we use an expression of different type, - operator requires an operand of particular type and we use an operand of different type, - function requires a formal parameter of particular type and we pass it an object of different type, - result does not match the declared function return type. Promotion When operands are of different types, implicit conversion promotes the less complex to the more complex type taking the following steps: byte/char short short integer integral ? ? ? ? ? word integer longint longint float Higher bytes of extended unsigned operand are filled with zeroes. Higher bytes of extended signed operand are filled with bit sign (if number is negative, fill higher bytes with one, otherwise with zeroes). For example: dim a as byte dim b as word '... a = $FF b = a ' a is promoted to word, b becomes $00FF 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). 154 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference dim i as byte dim j as word '... j = $FF0F i = j ' i becomes $0F, higher byte $FF is lost Explicit Conversion Explicit conversion can be executed at any point by inserting type keyword (byte, word, short, integer, longint, or float) ahead of the expression to be converted. The expression must be enclosed in parentheses. Explicit conversion can be performed only on the operand left of the assignment operator. Special case is the conversion between signed and unsigned types. Explicit conversion between signed and unsigned data does not change binary representation of data — it merely allows copying of source to destination. For example: dim a as byte dim b as short '... b = -1 a = byte(b) ' a is 255, not 1 ' This is because binary representation remains ' 11111111; it's just interpreted differently now You cannot execute explicit conversion on the operand left of the assignment operator: word(b) = a ' Compiler will report an error MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 155 CHAPTER 5 mikroBasic for 8051 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 for 8051: - Arithmetic Operators - Bitwise Operators - Boolean Operators - Relational Operators OPERATORS PRECEDENCE AND ASSOCIATIVITY There are 4 precedence categories in mikroBasic for 8051. Operators in the same category have equal precedence with each other. Each category has an associativity rule: left-to-right (), or right-to-left (). In the absence of parentheses, these rules resolve the grouping of expressions with operators of equal precedence. Precedence Operands 4 1 3 2 2 2 1 2 Operators @ * / div + = not <> + mod < Associativity and or > << xor <= >> >= 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. 156 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference Operator Operation Operands Result addition byte, short, word, integer, longint, longword, float byte, short, word, integer, longint, longword, float - subtraction byte, short, word, integer, longint, longword, float byte, short, word, integer, longint, longword, float * multiplication byte, short, word, integer, longint, longword, float word, integer, longint, longword, float / division, floating-point byte, short, word, integer, longint, longword, float float div division, rounds down to nearest integer + mod byte, short, word, byte, short, integer, longint, word, integer, longword longint, longword modulus, returns the byte, short, word, byte, short, remainder of integer integer, longint, word, integer, division (cannot be used longword longint, longword with floating points) Division by Zero If 0 (zero) is used explicitly as the second operand (i.e. x div 0), the compiler will report an error and will not generate code. But in case of implicit division by zero: x div y, where y is 0 (zero), the result will be the maximum integer (i.e 255, if the result is byte type; 65536, if the result is word type, etc.). Unary Arithmetic Operators Operator - can be used as a prefix unary operator to change sign of a signed value. Unary prefix operator + can be used, but it doesn’t affect data. For example: b = -a MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 157 CHAPTER 5 mikroBasic for 8051 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. Precedence of arithmetic and relational operators was designated in such a way to allow complex expressions without parentheses to have expected meaning: if aa + 5 >= bb - 1.0 / cc then (1.0 / cc)) then dd = My_Function() end if 158 ' same as: if (aa + 5) >= (bb - MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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. Bitwise Operators Overview Operator Operation bitwise AND; compares pairs of bits and generates a 1 result if both bits are 1, otherwise it returns 0 and bitwise (inclusive) OR; compares pairs of bits and generates a 1 result if either or both bits are 1, otherwise it returns 0 or xor bitwise exclusive OR (XOR); compares pairs of bits and generates a 1 result if the bits are complementary, otherwise it returns 0 not bitwise complement (unary); inverts each bit << bitwise shift left; moves the bits to the left, it discards the far left bit and assigns 0 to the right most bit. >> bitwise shift right; moves the bits to the right, discards the far right bit and if unsigned assigns 0 to the left most bit, otherwise sign extends Logical Operations on Bit Level and 0 1 or 0 1 xor 0 1 0 0 0 0 0 1 0 0 1 1 0 1 1 1 1 1 1 0 not 0 1 1 0 The bitwise operators and, or, and xor perform logical operations on the appropriate pairs of bits of their operands. The operator not complements each bit of its operand. For example: MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 159 CHAPTER 5 mikroBasic for 8051 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. If number is converted from more complex to less complex data type, the data is simply truncated (upper bytes are lost). For example: dim a dim b ' ... a = b = b = ' a as byte as word $AA $F0F0 b and a is extended with zeroes; b becomes $00A0 Signed and Conversions If number is converted from less complex to more complex data type, the upper bytes are filled with ones if sign bit is 1 (number is negative); the upper bytes are filled with zeroes if sign bit is 0 (number is positive). If number is converted from more complex to less complex data type, the data is simply truncated (the upper bytes are lost). For example: 160 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 dim a dim b ' ... a = b = b = Language Reference as byte as word -12 $70FF b and a ' a is sign extended, upper byte is $FF; ' b becomes $70F4 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. Thus, shifting unsigned operand to the left by n positions is equivalent to multiplying it by 2n if all discarded bits are zero. This is also true for signed operands if all discarded bits are equal to the sign bit. With shift right (>>), right most bits are discarded, and the “freed” bits on the left are assigned zeroes (in case of unsigned operand) or the value of the sign bit (in case of signed operand). Shifting operand to the right by n positions is equivalent to dividing it by 2n. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 161 CHAPTER 5 mikroBasic for 8051 Language Reference BOOLEAN OPERATORS Although mikroBasic for 8051 does not support boolean type, you have Boolean operators at your disposal for building complex conditional expressions. These operators conform to standard Boolean logic and return either TRUE (all ones) or FALSE (zero): Operator and or Operation logical AND logical OR xor logical exclusive OR (XOR) not logical negation Boolean operators associate from left to right. Negation operator not associates from right to left. 162 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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. Expressions are evaluated according to certain conversion, grouping, associativity and precedence rules that depend on the operators used, presence of parentheses, and data types of the operands. The precedence and associativity of the operators are summarized in Operator Precedence and Associativity. The way operands and subexpressions are grouped does not necessarily specify the actual order in which they are evaluated by mikroBasic for 8051. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 163 CHAPTER 5 mikroBasic for 8051 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. Refer to: - Assignment Statements - Conditional Statements - Iteration Statements (Loops) - Jump Statements - asm Statement ASSIGNMENT STATEMENTS Assignment statements have the following form: variable = expression The statement evaluates expression and assigns its value to variable. All rules of implicit conversion are applied. Variable can be any declared variable or array element, and expression can be any expression. Do not confuse the assignment with relational operator = which tests for equality. mikroBasic for 8051 will interpret the meaning of the character = from the context. 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 164 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference 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. If expression is false, other statements execute. The expression must convert to a boolean type; otherwise, the condition is ill-formed. The else keyword with an alternate block of statements (other statements) is optional. Nested if statements Nested if statements require additional attention. A general rule is that the nested conditionals are parsed starting from the innermost conditional, with each else bound to the nearest available if on its left: if expression1 then if expression2 then statement1 else statement2 end if end if The compiler treats the construction in this way: if expression1 then if expression2 then statement1 else statement2 end if end if 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 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 165 CHAPTER 5 Language Reference mikroBasic for 8051 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. The syntax of the select case statement is: select case selector case value_1 statements_1 ... case value_n statements_n [case else default_statements] end select selector is an expression which should evaluate as integral value. values can be literals, constants or expressions and statements can be any statements. The case else clause is optional. First, the selector expression (condition) is evaluated. The select case statement then compares it against all available values. If the match is found, the statements following the match evaluate, and the select case statement terminates. In case there are multiple matches, the first matching statement will be executed. If none of the values matches the selector, then default_statements in the case else clause (if there is one) are executed. Here is a simple example of the select case statement: select case operator case "*" res = n1 * n2 case "/" res = n1 / n2 case "+" res = n1 + n2 case "-" res = n1 - n2 case else res = 0 cnt = cnt + 1 end select Also, you can group values together for a match. Simply separate the items by commas: 166 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 167 CHAPTER 5 mikroBasic for 8051 Language Reference ITERATION STATEMENTS Iteration statements let you loop a set of statements. There are three forms of iteration statements in mikroBasic for 8051: - for - while - repeat You can use the statements break and continue to control the flow of a loop statement. break terminates the statement in which it occurs, while continue begins executing the next iteration of the sequence. 168 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference 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. Before the first iteration, counter is set to initial_value and will be incremented until it reaches (or exceeds) the final_value. With each iteration, statements will be executed. initial_value and final_value should be expressions compatible with counter; statements can be any statements that do not change the value of counter. Note that the parameter step_value may be negative, allowing you to create a countdown. Here is an example of calculating scalar product of two vectors, a and b, of length n, using the for statement: s = 0 for i = 0 to n-1 s = s + a[i] * b[i] next i Endless Loop The for statement results in an endless loop if final_value equals or exceeds the range of the counter’s type. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 169 CHAPTER 5 Language Reference mikroBasic for 8051 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. Here is an example of calculating scalar product of two vectors, using the while statement: s = 0 i = 0 while i < n s = s + a[i] * b[i] i = i + 1 wend Probably the easiest way to create an endless loop is to use the statement: while TRUE ' ... wend 170 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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. Here is an example of calculating scalar product of two vectors, using the do statement: s = 0 i = 0 do s = s + a[i] * b[i] i = i + 1 loop until i = n JUMP STATEMENTS A jump statement, when executed, transfers control unconditionally. There are five such statements in mikroBasic for 8051: - break continue exit goto gosub MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 171 CHAPTER 5 Language Reference mikroBasic for 8051 ASM STATEMENT mikroBasic for 8051 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). You can group assembly instructions with the asm keyword: asm block of assembly instructions end asm mikroBasic comments are not allowed in embedded assembly code. Instead, you may use one-line assembly comments starting with semicolon. If you plan to use a certain mikroBasic variable in embedded assembly only, be sure to at least initialize it (assign it initial value) in mikroBasic code; otherwise, the linker will issue an error. This is not applied to predefined globals such as P0. For example, the following code will not be compiled because the linker won’t be able to recognize the variable myvar: program test dim myvar as word main: asm MOV #10, W0 MOV W0, _myvar end asm end. Adding the following line (or similar) above the asm block would let linker know that variable is used: myvar = 20 172 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 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). The compiler directives are not case sensitive. You can use conditional compilation to select particular sections of code to compile while excluding other sections. All compiler directives must be completed in the source file in which they begun. Directives #DEFINE and #UNDEFINE Use directive #DEFINE to define a conditional compiler constant (“flag”). You can use any identifier for a flag, with no limitations. No conflicts with program identifiers are possible because the flags have a separate name space. Only one flag can be set per directive. For example: #DEFINE extended_format Use #UNDEFINE to undefine (“clear”) previously defined flag. Directives #IFDEF, #ELSEIF and #ELSE Conditional compilation is carried out by the #IFDEF directive. #IFDEF tests whether a flag is currently defined or not; i.e. whether the previous #DEFINE directive has been processed for that flag and is still in force. The directive #IFDEF is terminated by the #ENDIF directive and can have any number of the #ELSEIF clauses and an optional #ELSE clause: MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 173 CHAPTER 5 Language Reference mikroBasic for 8051 #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. #ENDIF ends the conditional sequence. The result of the preceding scenario is that only one section of code (possibly empty) is passed on for further processing. The processed section can contain further conditional clauses, nested to any depth; each #IFDEF must be matched with a closing #ENDIF. Here is an example: ' Uncomment the appropriate flag for your application: '#DEFINE resolution8 '#DEFINE resolution10 '#DEFINE resolution12 #IFDEF resolution8 THEN ... ' code specific to 8-bit resolution #ELSEIF resolution10 THEN ... ' code specific to 10-bit resolution #ELSEIF resolution12 THEN ... ' code specific to 12-bit resolution #ELSE ... ' default code #ENDIF Predefined Flags The compiler sets directives upon completion of project settings, so the user doesn't need to define certain flags. Here is an example: #IFDEF AT89S8253 ' If AT89S8253 MCU is selected #IFDEF AT89 ' AT89S8253 and AT89 flags will be automatically defined 174 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic for 8051 Language Reference LINKER DIRECTIVES mikroBasic for 8051 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. If the variable spans more than 1 word (16-bit), higher words will be stored at the consecutive locations. The absolute directive is appended to the declaration of a variable: dim x as word absolute 0x32 ' Variable x will occupy 1 word (16 bits) at address 0x32 dim y as longint absolute 0x34 ' Variable y will occupy 2 words at addresses 0x34 and 0x36 Be careful when using absolute directive, as you may overlap two variables by accident. For example: dim i as word absolute 0x42 ' Variable i will occupy 1 word at address 0x42; dim jj as longint absolute 0x40 ' Variable will occupy 2 words at 0x40 and 0x42; thus, ' changing i changes jj at the same time and vice versa Note: You must specify an even address when using the directive absolute. Directive org The directive org specifies the starting address of a routine in ROM. It is appended to the declaration of routine. For example: sub procedure proc(dim par as word) org 0x200 ' Procedure will start at the address 0x200; ... end sub Note: You must specify an even address when using the directive org. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 175 CHAPTER 5 Language Reference 176 mikroBasic for 8051 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroBasic for 8051 Libraries 6 mikroBasic for 8051 provides a set of libraries which simplify the initialization and use of 8051 compliant MCUs and their modules: Use Library manager to include mikroBasic for 8051 Libraries in you project. 177 CHAPTER 6 mikroBasic for 8051 Libraries Hardware 8051-specific Libraries - CANSPI Library - EEPROM Library - Graphic LCD Library - Keypad Library - LCD Library - Manchester Code Library - OneWire Library - Port Expander Library - PS/2 Library - RS-485 Library - Software I2C Library - Software SPI Library - Software UART Library - Sound Library - SPI Library - SPI Ethernet Library - SPI Graphic LCD Library - SPI LCD Library - SPI LCD8 Library - SPI T6963C Graphic LCD Library - T6963C Graphic LCD Library - UART Library Miscellaneous Libraries - Button Library - Conversions Library - Math Library - String Library - Time Library - Trigonometry Library See also Built-in Routines. 178 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 179 CHAPTER 6 mikroBasic for 8051 Libraries Related topics: Library manager, 8051 Libraries 180 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries CANSPI LIBRARY The SPI module is available with a number of the 8051 compliant MCUs. The mikroBasic for 8051 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. Data transfer rates depend on distance. For example, 1 Mbit/s can be achieved at network lengths below 40m while 250 Kbit/s can be achieved at network lengths below 250m. The greater distance the lower maximum bitrate that can be achieved. The lowest bitrate defined by the standard is 200Kbit/s. Cables used are shielded twisted pairs. CAN supports two message formats: - Standard format, with 11 identifier bits and - Extended format, with 29 identifier bits Note: - Consult the CAN standard about CAN bus termination resistance. - An effective CANSPI communication speed depends on SPI and certainly is slower than “real” CAN. - CANSPI module refers to mikroElektronika's CANSPI Add-on board connected to SPI module of MCU. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 181 CHAPTER 6 mikroBasic for 8051 Libraries External dependecies of CANSPI Library The following variables must be defined in all projects using CANSPI Library: Description: Example : dim CanSpi_CS as sbit Chip Select line. external dim CanSpi_CS as sbit at P1.B0 dim CanSpi_RST as sbit external dim CanSpi_Rst as sbit at P1.B2 Reset line. Library Routines - CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialize CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIread CANSPIWrite The following routines are for an internal use by the library only: - RegsToCANSPIID - CANSPIIDToRegs Be sure to check CANSPI constants necessary for using some of the sub functions. 182 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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 constants (see CANSPI constants). Description - WAIT: CANSPI mode switching verification request. If WAIT = 0, the call is non-blocking. The sub function does not verify if the CANSPI module is switched to requested mode or not. Caller must use CANSPIGetOperationMode to verify correct operation mode before performing mode specific operation. If WAIT != 0, the call is blocking – the sub function won’t “return” until the requested mode is set. The CANSPI routines are supported only by MCUs with the SPI module. Requires Example MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar hardware. See connection example at the bottom of this page. ' set the CANSPI module into configuration mode (wait inside CANSPISetOperationMode until this mode is set) CANSPISetOperationMode(CANSPI_MODE_CONFIG, 0xFF) CANSPIGetOperationMode Prototype sub function CANSPIGetOperationMode() as byte Returns Current operation mode. The sub function returns current operation mode of the CANSPI module. Check Description CANSPI_OP_MODE constants (see CANSPI constants) or device datasheet for operation mode codes. The CANSPI routines are supported only by MCUs with the SPI module. Requires Example MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar hardware. See connection example at the bottom of this page. ' check whether the CANSPI module is in Normal mode and if it is do something. if (CANSPIGetOperationMode() = CANSPI_MODE_NORMAL) then ... end if MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 183 CHAPTER 6 mikroBasic for 8051 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. Stand-Alone CAN controller in the CANSPI module is set to: Description - Disable CAN capture Continue CAN operation in Idle mode Do not abort pending transmissions Fcan clock: 4*Tcy (Fosc) Baud rate is set according to given parameters CAN mode: Normal Filter and mask registers IDs are set to zero Filter and mask message frame type is set according to CAN_CONFIG_FLAGS value SAM, SEG2PHTS, WAKFIL and DBEN bits are set according to CAN_CONFIG_FLAGS value. Parameters: - SJW as defined in CAN controller's datasheet BRP as defined in CAN controller's datasheet PHSEG1 as defined in CAN controller's datasheet PHSEG2 as defined in CAN controller's datasheet PROPSEG as defined in CAN controller's datasheet CAN_CONFIG_FLAGS is formed from predefined constants (see CANSPI constants) CanSpi_CS and CanSpi_Rst variables must be defined before using this sub function. The CANSPI routines are supported only by MCUs with the SPI module. Requires The SPI module needs to be initialized. See the Spi_Init and Spi_Init_Advanced routines. MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar hardware. See connection example at the bottom of this page. 184 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Example Libraries ' initialize the CANSPI module with the appropriate baud rate and message acceptance flags along with the sampling rules 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 ... Spi_Init() ' initialize SPI module CANSPIInitialize(1,3,3,3,1,Can_Init_Flags) ' initialize external CANSPI module MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 185 CHAPTER 6 mikroBasic for 8051 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. Refer to datasheet for details. Description Parameters: - SJW as defined in CAN controller's datasheet BRP as defined in CAN controller's datasheet PHSEG1 as defined in CAN controller's datasheet PHSEG2 as defined in CAN controller's datasheet PROPSEG as defined in CAN controller's datasheet CAN_CONFIG_FLAGS is formed from predefined constants (see CANSPI constants) The CANSPI module must be in Config mode, otherwise the sub function will be ignored. See CANSPISetOperationMode. Requires The CANSPI routines are supported only by MCUs with the SPI module. MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar hardware. See connection example at the bottom of this page. Example 186 ' set required baud rate and sampling rules dim can_config_flags as byte ... CANSPISetOperationMode(CANSPI_MODE_CONFIG, 0xFF) ' set CONFIGURATION mode (CANSPI module mast be in config mode for baud rate settings) can_config_flags = CANSPI_CONFIG_SAMPLE_THRICE and CANSPI_CONFIG_PHSEG2_PRG_ON and CANSPI_CONFIG_STD_MSG and CANSPI_CONFIG_DBL_BUFFER_ON and CANSPI_CONFIG_VALID_XTD_MSG and CANSPI_CONFIG_LINE_FILTER_OFF CANSPISetBaudRate(1, 1, 3, 3, 1, can_config_flags) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. Valid values: CANSPI_MASK con stants (see CANSPI constants) Description - val: mask register value - CAN_CONFIG_FLAGS: selects type of message to filter. Valid values: CANSPI_CONFIG_ALL_VALID_MSG, CANSPI_CONFIG_MATCH_MSG_TYPE and CANSPI_CONFIG_STD_MSG, CANSPI_CONFIG_MATCH_MSG_TYPE and CANSPI_CONFIG_XTD_MSG. (see CANSPI constants) The CANSPI module must be in Config mode, otherwise the sub function will be ignored. See CANSPISetOperationMode. Requires The CANSPI routines are supported only by MCUs with the SPI module. MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar hardware. See connection example at the bottom of this page. ' set the appropriate filter mask and message type value CANSPISetOperationMode(CANSPI_MODE_CONFIG,0xFF) ' set CONFIGURATION mode (CANSPI module must be in config mode for mask settings) Example ' Set all B1 mask bits to 1 (all filtered bits are relevant): ' Note that -1 is just a cheaper way to write 0xFFFFFFFF. ' Complement will do the trick and fill it up with ones. CANSPISetMask(CANSPI_MASK_B1, -1, CANSPI_CONFIG_MATCH_MSG_TYPE and CANSPI_CONFIG_XTD_MSG) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 187 CHAPTER 6 mikroBasic for 8051 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. Valid values: CANSPI_CONFIG_ALL_VALID_MSG, CANSPI_CONFIG_MATCH_MSG_TYPE and CANSPI_CONFIG_STD_MSG, CANSPI_CONFIG_MATCH_MSG_TYPE and CANSPI_CONFIG_XTD_MSG. (see CANSPI constants) The CANSPI module must be in Config mode, otherwise the sub function will be ignored. See CANSPISetOperationMode. Requires The CANSPI routines are supported only by MCUs with the SPI module. MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar hardware. See connection example at the bottom of this page. Example ' set the appropriate filter value and message type CANSPISetOperationMode(CANSPI_MODE_CONFIG,0xFF) ' set CONFIGURATION mode (CANSPI module must be in config mode for filter settings) ' Set id of filter B1_F1 to 3: CANSPISetFilter(CANSPI_FILTER_B1_F1, 3, CANSPI_CONFIG_XTD_MSG) 188 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries CANSPIRead Prototype sub function CANSPIRead(dim byref id as longint, dim byref rd_data as array[20] of byte, 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 to a buffer provided by the rd_data parameter - Message length is retrieved and stored to location provided by the data_len parameter - Message flags are retrieved and stored to location provided by the Description CAN_RX_MSG_FLAGS parameter Parameters: - id: message identifier storage address rd_data: data buffer (an array of bytes up to 8 bytes in length) data_len: data length storage address. CAN_RX_MSG_FLAGS: message flags storage address The CANSPI module must be in a mode in which receiving is possible. See CANSPISetOperationMode. Requires The CANSPI routines are supported only by MCUs with the SPI module. MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar hardware. See connection example at the bottom of this page. Example ' check the CANSPI module for received messages. If any was received do something. dim msg_rcvd, rx_flags, data_len as byte rd_data as array[8] of byte msg_id as longint ... CANSPISetOperationMode(CANSPI_MODE_NORMAL,0xFF) ' set NORMAL mode (CANSPI module must be in mode in which receive is possible) ... rx_flags = 0 ' clear message flags if (msg_rcvd = CANSPIRead(msg_id, rd_data, data_len, rx_flags) ... end if MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 189 CHAPTER 6 mikroBasic for 8051 Libraries CANSPIWrite Prototype Returns sub function CANSPIWrite(dim id as longint, dim byref wr_data as array[20] of byte, 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. Valid values: 11 or 29 bit values, depending on message type (standard or extended) - wr_data: data to be sent (an array of bytes up to 8 bytes in length) - data_len: data length. Valid values: 1 to 8 - CAN_RX_MSG_FLAGS: message flags The CANSPI module must be in mode in which transmission is possible. See CANSPISetOperationMode. Requires The CANSPI routines are supported only by MCUs with the SPI module. MCU has to be properly connected to mikroElektronika's CANSPI Extra Board or similar hardware. See connection example at the bottom of this page. Example ' send message extended CAN message with the appropriate ID and data dim tx_flags as byte rd_data as array[8] of byte msg_id as longint ... CANSPISetOperationMode(CAN_MODE_NORMAL, 0xFF) ' set NORMAL mode (CANSPI must be in mode in which transmission is possible) tx_flags = CANSPI_TX_PRIORITY_0 ands CANSPI_TX_XTD_FRAME ' set message flags CANSPIWrite(msg_id, rd_data, 2, tx_flags) 190 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. sub function CANSPISetOperationMode expects one of these as it's argument: const CANSPI_MODE_BITS CANSPI_MODE_NORMAL CANSPI_MODE_SLEEP CANSPI_MODE_LOOP CANSPI_MODE_LISTEN CANSPI_MODE_CONFIG = = = = = = 0xE0 0x00 0x20 0x40 0x60 0x80 ' Use this to access opmode bits CANSPI_CONFIG_FLAGS The CANSPI_CONFIG_FLAGS constants define flags related to the CANSPI module configuration. The sub functions CANSPIInitialize, CANSPISetBaudRate, CANSPISetMask and CANSPISetFilter expect one of these (or a bitwise combination) as their argument: const CANSPI_CONFIG_DEFAULT CANSPI_CONFIG_PHSEG2_PRG_BIT CANSPI_CONFIG_PHSEG2_PRG_ON CANSPI_CONFIG_PHSEG2_PRG_OFF = 0xFF ' 11111111 = 0x01 = 0xFF = 0xFE ' XXXXXXX1 ' XXXXXXX0 CANSPI_CONFIG_LINE_FILTER_BIT = 0x02 CANSPI_CONFIG_LINE_FILTER_ON = 0xFF CANSPI_CONFIG_LINE_FILTER_OFF = 0xFD ' XXXXXX1X ' XXXXXX0X CANSPI_CONFIG_SAMPLE_BIT CANSPI_CONFIG_SAMPLE_ONCE CANSPI_CONFIG_SAMPLE_THRICE = 0x04 = 0xFF = 0xFB ' XXXXX1XX ' XXXXX0XX CANSPI_CONFIG_MSG_TYPE_BIT CANSPI_CONFIG_STD_MSG CANSPI_CONFIG_XTD_MSG = 0x08 = 0xFF = 0xF7 ' XXXX1XXX ' XXXX0XXX MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 191 CHAPTER 6 mikroBasic for 8051 Libraries CANSPI_CONFIG_MSG_BITS CANSPI_CONFIG_ALL_MSG CANSPI_CONFIG_VALID_XTD_MSG CANSPI_CONFIG_VALID_STD_MSG CANSPI_CONFIG_ALL_VALID_MSG = 0x60 = 0xFF = 0xDF = 0xBF = 0x9F ' X11XXXXX ' X10XXXXX ' X01XXXXX ' X00XXXXX You may use bitwise and to form config byte out of these values. For example: init = CANSPI_CONFIG_SAMPLE_THRICE CANSPI_CONFIG_PHSEG2_PRG_ON CANSPI_CONFIG_STD_MSG CANSPI_CONFIG_DBL_BUFFER_ON CANSPI_CONFIG_VALID_XTD_MSG CANSPI_CONFIG_LINE_FILTER_OFF ... CANSPIInitialize(1, 1, 3, 3, 1, init) and and and and and ' initialize CANSPI CANSPI_TX_MSG_FLAGS CANSPI_TX_MSG_FLAGS are flags related to transmission of a CAN message: const CANSPI_TX_PRIORITY_BITS CANSPI_TX_PRIORITY_0 CANSPI_TX_PRIORITY_1 CANSPI_TX_PRIORITY_2 CANSPI_TX_PRIORITY_3 = = = = = 0x03 0xFC 0xFD 0xFE 0xFF ' ' ' ' XXXXXX00 XXXXXX01 XXXXXX10 XXXXXX11 CANSPI_TX_FRAME_BIT CANSPI_TX_STD_FRAME CANSPI_TX_XTD_FRAME = 0x08 = 0xFF = 0xF7 ' XXXXX1XX ' XXXXX0XX CANSPI_TX_RTR_BIT CANSPI_TX_NO_RTR_FRAME CANSPI_TX_RTR_FRAME = 0x40 = 0xFF = 0xBF ' X1XXXXXX ' X0XXXXXX You may use bitwise and to adjust the appropriate flags. For example: ' form value to be used as sending message flag: send_config = CANSPI_TX_PRIORITY_0 and CANSPI_TX_XTD_FRAME and CANSPI_TX_NO_RTR_FRAME ... CANSPIWrite(id, data, 1, send_config) 192 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries CANSPI_RX_MSG_FLAGS CANSPI_RX_MSG_FLAGS are flags related to reception of CAN message. If a particular bit is set then corresponding meaning is TRUE or else it will be FALSE. const CANSPI_RX_FILTER_BITS CANSPI_RX_FILTER_1 CANSPI_RX_FILTER_2 CANSPI_RX_FILTER_3 CANSPI_RX_FILTER_4 CANSPI_RX_FILTER_5 CANSPI_RX_FILTER_6 = = = = = = = 0x07 0x00 0x01 0x02 0x03 0x04 0x05 ' Use this to access filter bits CANSPI_RX_OVERFLOW = 0x08 ' Set if Overflowed else cleared CANSPI_RX_INVALID_MSG = 0x10 ' Set if invalid else cleared CANSPI_RX_XTD_FRAME = 0x20 ' Set if XTD message else cleared CANSPI_RX_RTR_FRAME = 0x40 ' Set if RTR message else cleared CANSPI_RX_DBL_BUFFERED = 0x80 ' Set if this message was hardware double-buffered You may use bitwise and to adjust the appropriate flags. For example: if (MsgFlag and CANSPI_RX_OVERFLOW <> 0) then ... ' Receiver overflow has occurred. ' We have lost our previous message. end if CANSPI_MASK The CANSPI_MASK constants define mask codes. sub function CANSPISetMask expects one of these as it's argument: const CANSPI_MASK_B1 = 0 CANSPI_MASK_B2 = 1 CANSPI_FILTER The CANSPI_FILTER constants define filter codes. sub functions CANSPISetFilter expects one of these as it's argument: 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 = = = = = = 0 1 2 3 4 5 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 193 CHAPTER 6 mikroBasic for 8051 Libraries 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. First node then does the same and sends incremented data back to second node, etc. Code for the first CANSPI node: program CanSpi1st dim Can_Init_Flags, Can_Send_Flags, flags Rx_Data_Len as byte RxTx_Data as byte[8] Msg_Rcvd as byte Tx_ID, Rx_ID as longint Can_Rcv_Flags as byte ' CAN ' Received data length in bytes ' CAN rx/tx data buffer ' Reception flag ' CAN rx and tx ID ' CANSPI module connections dim CanSpi_CS as sbit at P1.B0 dim CanSpi_Rst as sbit at P1.B2 ' End CANSPI module connections main: Can_Init_Flags = 0 Can_Send_Flags = 0 Can_Rcv_Flags = 0 Can_Send_Flags = CAN_TX_PRIORITY_0 and CAN_TX_XTD_FRAME and CAN_TX_NO_RTR_FRAME ' ' Clear flags ' ' Form value to be used ' with CANSPIWrite Can_Init_Flags = CAN_CONFIG_SAMPLE_THRICE and ' Form value to be used CAN_CONFIG_PHSEG2_PRG_ON and ' with CANSPIInit CAN_CONFIG_XTD_MSG and CAN_CONFIG_DBL_BUFFER_ON and CAN_CONFIG_VALID_XTD_MSG Spi_Init() ' Initialize SPI module CANSPIInitialize(1,3,3,3,1,Can_Init_Flags) ' Initialize external CANSPI module CANSPISetOperationMode(CAN_MODE_CONFIG,0xFF) mode 194 ' Set CONFIGURATION MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries CANSPISetMask(CAN_MASK_B1,-1,CAN_CONFIG_XTD_MSG) mask1 bits to ones CANSPISetMask(CAN_MASK_B2,-1,CAN_CONFIG_XTD_MSG) all mask2 bits to ones CANSPISetFilter(CAN_FILTER_B2_F4,3,CAN_CONFIG_XTD_MSG) of filter B2_F4 to 3 CANSPISetOperationMode(CAN_MODE_NORMAL,0xFF) RxTx_Data[0] = 9 ' Set all ' Set ' Set id ' Set NORMAL mode ' Set initial data to be sent Tx_ID = 12111 ' Set transmit ID CANSPIWrite(Tx_ID, RxTx_Data, 1, Can_Send_Flags) initial message while TRUE Endless loop Msg_Rcvd = CANSPIRead( Rx_ID , Can_Rcv_Flags) ' Receive message if (Rx_ID = 3) and ' If message received check id ' Send ' RxTx_Data , (Msg_Rcvd P0 = Rx_Data_Len, <> 0) then RxTx_Data[0] ' ID correct, output data at PORT0 Inc(RxTx_Data[0]) ' Increment received data Delay_ms(10) CANSPIWrite(Tx_ID, ' Send incremented data back end if wend end. RxTx_Data, 1, Can_Send_Flags) Code for the second CANSPI node: program CanSpi2nd dim Can_Init_Flags, Can_Send_Flags, flags Rx_Data_Len as byte RxTx_Data as byte[8] Msg_Rcvd as byte Tx_ID, Rx_ID as longint Can_Rcv_Flags as byte ' ' ' ' ' CAN Received data length in bytes CAN rx/tx data buffer Reception flag CAN rx and tx ID ' CANSPI module connections dim CanSpi_CS as sbit at P1.B0 dim CanSpi_Rst as sbit at P1.B2 ' End CANSPI module connections MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 195 CHAPTER 6 mikroBasic for 8051 Libraries main: Can_Init_Flags = 0 Can_Send_Flags = 0 Can_Rcv_Flags = 0 Can_Send_Flags = CAN_TX_PRIORITY_0 and CAN_TX_XTD_FRAME and with CANSPIWrite CAN_TX_NO_RTR_FRAME ' ' Clear flags ' ' Form value to be used ' Can_Init_Flags = CAN_CONFIG_SAMPLE_THRICE and value to be used CAN_CONFIG_PHSEG2_PRG_ON and with CANSPIInit CAN_CONFIG_XTD_MSG and CAN_CONFIG_DBL_BUFFER_ON and CAN_CONFIG_VALID_XTD_MSG and CAN_CONFIG_LINE_FILTER_OFF ' Form ' Spi_Init() ' Initialize SPI module CANSPIInitialize(1,3,3,3,1,Can_Init_Flags) ' Initialize CAN-SPI module CANSPISetOperationMode(CAN_MODE_CONFIG,0xFF) CONFIGURATION mode ' Set CANSPISetMask(CAN_MASK_B1,-1,CAN_CONFIG_XTD_MSG) ' Set all mask1 bits to ones CANSPISetMask(CAN_MASK_B2,-1,CAN_CONFIG_XTD_MSG) ' Set all mask2 bits to ones CANSPISetFilter(CAN_FILTER_B2_F3,12111,CAN_CONFIG_XTD_MSG) ' Set id of filter B2_F3 to 12111 CANSPISetOperationMode(CAN_MODE_NORMAL,0xFF) Tx_ID = 3 ' Set NORMAL mode ' Set tx ID while TRUE ' Endless loop Msg_Rcvd = CANSPIRead( Rx_ID , RxTx_Data , Rx_Data_Len, Can_Rcv_Flags) ' Receive message if Rx_ID = 12111 then ' If message received check id if Msg_Rcvd <> 0 then P0 = RxTx_Data[0] ' ID correct, output data at PORT0 Inc(RxTx_Data[0]) ' Increment received data CANSPIWrite(Tx_ID, RxTx_Data, 1, Can_Send_Flags) ' Send incremented data back end if end if wend end. 196 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries HW Connection Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 197 CHAPTER 6 mikroBasic for 8051 Libraries EEPROM LIBRARY EEPROM data memory is available with a number of 8051 family. The mikroBasic for 8051 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. Library Routines - Eeprom_Read - Eeprom_Write - Eeprom_Write_Block Eeprom_Read Prototype sub function Eeprom_Read(dim address as word) as byte Returns Byte from the specified address. Reads data from specified address. Description Parameters : - address: address of the EEPROM memory location to be read. 198 Requires Nothing. Example dim eeAddr as word temp as byte ... eeAddr = 2 temp = Eeprom_Read(eeAddr) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Eeprom_Write Prototype Returns sub function Eeprom_Write(dim address as word, dim wrdata as byte) as byte - 0 writing was successful - 1 if error occured 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. Requires Nothing. Example dim eeWrite as byte = 0x55 wrAddr as word = 0x732 ... eeWrite = 0x55 wrAddr = 0x732 Eeprom_Write(wrAddr, eeWrite) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 199 CHAPTER 6 mikroBasic for 8051 Libraries Eeprom_Write_Block Prototype Returns sub function Eeprom_Write_Block(dim address as word, dim byref ptrdata as byte) as byte - 0 writing was successful - 1 if error occured Writes one EEPROM row (32 bytes block) of data. Parameters : Description - address: starting address of the EEPROM memory block to be written. - ptrdata: data block to be written. Note: Specified memory block will be erased before writing starts. EEPROM module must support block write operations. Requires Example 200 It is the user's responsibility to maintain proper address alignment. In this case, address has to be a multiply of 32, which is the size (in bytes) of one row of MCU's EEPROM memory. dim wrAddr as word iArr as string[16] ... wrAddr = 0x0100 iArr = 'mikroElektronika' Eeprom_Write_Block(wrAddr, iArr) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Library Example This example demonstrates using the EEPROM Library with AT89S8253 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 P0, P1 and P2. program Eeprom dim dat as byte[32] i as byte ' Data buffer, loop variable main: for i = 0 to 31 dat[i] = i next i Eeprom_Write(2,0xAA) Eeprom_Write(0x732,0x55) Eeprom_Write_Block(0x100,dat) address 0x100 Delay_ms(1000) P0 = 0xFF P1 = 0xFF Delay_ms(1000) P0 = 0x00 P1 = 0x00 Delay_ms(1000) P0 = Eeprom_Read(2) and display it on PORT0 P1 = Eeprom_Read(0x732) and display it on PORT1 Delay_ms(1000) for i = 0 to 31 address 0x100 P2 = Eeprom_Read(0x100+i) Delay_ms(100) next i end. ' Fill data buffer ' Write some data at address 2 ' Write some data at address 0x732 ' Write 32 bytes block at ' Blink P0 and P1 diodes ' to indicate reading start ' Read data from address 2 ' Read data from address 0x732 ' Read 32 bytes block from ' and display data on PORT2 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 201 CHAPTER 6 mikroBasic for 8051 Libraries Graphic LCD Library The mikroBasic for 8051 provides a library for operating Graphic LCD 128x64 (with commonly used Samsung KS108/KS107 controller). For creating a custom set of GLCD images use GLCD Bitmap Editor Tool. External dependencies of Graphic LCD Library The following variables must be defined in all projects using Graphic LCD Library: dim GLCD_DataPort as byte external volatile sfr dim GLCD_CS1 as sbit external dim GLCD_CS2 as sbit external dim GLCD_RS as sbit external dim GLCD_RW as sbit external dim GLCD_RST as sbit external dim GLCD_EN as sbit external Description: LCD Data Port. Chip Select 1 line. Chip Select 2 line. Register select line. Read/Write line. Reset line. Enable line. Example : dim GLCD_DataPort as byte at P0 sfr dim GLCD_CS1 as sbit at P2.B0 dim GLCD_CS2 as sbit at P2.B0 dim GLCD_RS as sbit at P2.B0 dim GLCD_RW as sbit at P2.B0 dim GLCD_RST as sbit at P2.B0 dim GLCD_EN as sbit at P2.B0 Library Routines Basic routines: - 202 Glcd_Init Glcd_Set_Side Glcd_Set_X Glcd_Set_Page Glcd_Read_Data Glcd_Write_Data MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries 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 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>). Global variables : - Requires GLCD_CS1 : chip select 1 signal pin GLCD_CS2 : chip select 2 signal pin GLCD_RS : register select signal pin GLCD_RW : read/write signal pin GLCD_EN : enable signal pin GLCD_RST : reset signal pin GLCD_DataPort : data port must be defined before using this function. ' glcd pinout settings dim GLCD_DataPort as byte at P0 sfr Example dim dim dim dim dim dim GLCD_CS1 GLCD_CS2 GLCD_RS GLCD_RW GLCD_RST GLCD_EN as as as as as as sbit sbit sbit sbit sbit sbit at at at at at at P2.B0 P2.B1 P2.B2 P2.B3 P2.B5 P2.B4 ... Glcd_Init() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 203 CHAPTER 6 mikroBasic for 8051 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. Requires GLCD needs to be initialized, see Glcd_Init routine. The following two lines are equivalent, and both of them select the left side of GLCD: Example Glcd_Select_Side(0) Glcd_Select_Side(10) Glcd_Set_X Prototype sub procedure Glcd_Set_X(dim x_pos as byte) Returns Nothing. Sets x-axis position to x_pos dots from the left border of GLCD within the selected side. Parameters : Description - x_pos: position on x-axis. Valid values: 0..63 Note: For side, x axis and page layout explanation see schematic at the bottom of this page. 204 Requires GLCD needs to be initialized, see Glcd_Init routine. Example Glcd_Set_X(25) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. Description Reads data from from the current location of GLCD memory and moves to the next location. 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 ... data = Glcd_Read_Data() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 205 CHAPTER 6 mikroBasic for 8051 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 ... Glcd_Write_Data(data) Glcd_Fill Prototype sub procedure Glcd_Fill(dim pattern as byte) Returns Nothing. Fills GLCD memory with the byte pattern. Parameters : Description - pattern: byte to fill GLCD memory with To clear the GLCD screen, use Glcd_Fill(0). To fill the screen completely, use Glcd_Fill(0xFF). 206 Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Clear screen Glcd_Fill(0) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. Note: For x and y axis layout explanation see schematic at the bottom of this page. Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Invert the dot in the upper left corner Glcd_Dot(0, 0, 2) Glcd_Line Prototype sub procedure Glcd_Line(dim x_start as integer, dim y_start as integer, dim x_end as integer, dim y_end as integer, dim color as byte) Returns Nothing. Draws a line on GLCD. Parameters : Description - x_start: x coordinate of the line start. Valid values: 0..127 y_start: y coordinate of the line start. Valid values: 0..63 x_end: x coordinate of the line end. Valid values: 0..127 y_end: y coordinate of the line end. Valid values: 0..63 color: color parameter. Valid values: 0..2 The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Draw a line between dots (0,0) and (20,30) Glcd_Line(0, 0, 20, 30, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 207 CHAPTER 6 mikroBasic for 8051 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..2 The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Draw a vertical line between dots (10,5) and (10,25) Glcd_V_Line(5, 25, 10, 1) Glcd_H_Line Prototype sub procedure Glcd_V_Line(dim x_start as byte, dim x_end as byte, dim y_pos as byte, dim color as byte) Returns Nothing. Draws a horizontal line on GLCD. Parameters : Description - x_start: x coordinate of the line start. Valid values: 0..127 x_end: x coordinate of the line end. Valid values: 0..127 y_pos: y coordinate of horizontal line. Valid values: 0..63 color: color parameter. Valid values: 0..2 The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. 208 Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Draw a horizontal line between dots (10,20) and (50,20) Glcd_H_Line(10, 50, 20, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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..63 Description - x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: 0..127 - y_bottom_right: y coordinate of the lower right rectangle corner. Valid values: 0..63 - color: color parameter. Valid values: 0..2 The parameter color determines the color of the rectangle border: 0 white, 1 black, and 2 inverts each dot. Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Draw a rectangle between dots (5,5) and (40,40) Glcd_Rectangle(5, 5, 40, 40, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 209 CHAPTER 6 mikroBasic for 8051 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. Valid values: 0..127 - y_bottom_right: y coordinate of the lower right box corner. Valid values: 0..63 - color: color parameter. Valid values: 0..2 The parameter color determines the color of the box fill: 0 white, 1 black, and 2 inverts each dot. Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Draw a box between dots (5,15) and (20,40) Glcd_Box(5, 15, 20, 40, 1) Glcd_Circle Prototype sub procedure Glcd_Circle(dim x_center as integer, dim y_center as integer, dim radius as integer, dim color as byte) Returns Nothing. Draws a circle on GLCD. Parameters : Description - x_center: x coordinate of the circle center. Valid values: 0..127 y_center: y coordinate of the circle center. Valid values: 0..63 radius: radius size color: color parameter. Valid values: 0..2 The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot. 210 Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Draw a circle with center in (50,50) and radius=10 Glcd_Circle(50, 50, 10, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. aFontOffs: number that represents difference between the mikroBasic for 8051 character set and regular ASCII set (eg. if 'A' is 65 in ASCII character, and 'A' is 45 in the mikroBasic for 8051 character set, aFontOffs is 20). Demo fonts supplied with the library have an offset of 32, which means that they start with space. The user can use fonts given in the file “__Lib_GLCDFonts.mpas” file located in the Uses folder or create his own fonts. Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Use the custom 5x7 font "myfont" which starts with space (32): Glcd_Set_Font(myfont, 5, 7, 32) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 211 CHAPTER 6 mikroBasic for 8051 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..2 The parameter color determines the color of the character: 0 white, 1 black, and 2 inverts each dot. Note: For x axis and page layout explanation see schematic at the bottom of this page. 212 Requires GLCD needs to be initialized, see Glcd_Init routine. Use Glcd_Set_Font to specify the font for display; if no font is specified, then default 5x8 font supplied with the library will be used. Example ' Write character 'C' on the position 10 inside the page 2: Glcd_Write_Char('C', 10, 2, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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 : Description - text: text to be written x_pos: text starting position on x-axis. page_num: the number of the page on which text will be written. Valid values: 0..7 color: color parameter. Valid values: 0..2 The parameter color determines the color of the text: 0 white, 1 black, and 2 inverts each dot. Note: For x axis and page layout explanation see schematic at the bottom of this page. Requires GLCD needs to be initialized, see Glcd_Init routine. Use Glcd_Set_Font to specify the font for display; if no font is specified, then default 5x8 font supplied with the library will be used. Example ' Write text "Hello world!" on the position 10 inside the page 2: Glcd_Write_Text("Hello world!", 10, 2, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 213 CHAPTER 6 mikroBasic for 8051 Libraries Glcd_Image Prototype sub procedure Glcd_Image(dim byref const image as ^byte) Returns Nothing. Displays bitmap on GLCD. Parameters : Description - image: image to be displayed. Bitmap array must be located in code memory. Use the mikroBasic for 8051 integrated GLCD Bitmap Editor to convert image to a constant array suitable for displaying on GLCD. Requires GLCD needs to be initialized, see Glcd_Init routine. Example ' Draw image my_image on GLCD Glcd_Image(my_image) 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. program Glcd ' Declarations include bitmap ' end Declarations ' Glcd module connections dim GLCD_DataPort as byte at P0 sfr ' GLCD data port dim GLCD_CS1 as sbit at P2.B0 dim GLCD_CS2 as sbit at P2.B1 dim GLCD_RS as sbit at P2.B2 dim GLCD_RW as sbit at P2.B3 dim GLCD_RST as sbit at P2.B5 dim GLCD_EN as sbit at P2.B4 ' End Glcd module connections ' ' ' ' ' ' sub procedure delay2S() Delay_ms(2000) end sub ' 2 seconds delay sub function GLCD GLCD GLCD GLCD GLCD GLCD chip select 1 signal chip select 2 signal register select signal read/write signal reset signal enable signal dim conter as word someText as char[17] 214 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries main: Glcd_Init() Glcd_Fill(0x00) while TRUE Glcd_Image(@advanced8051_bmp) Delay2S() Glcd_Fill(0x00) Glcd_Box(62,40,124,56,1) Glcd_Rectangle(5,5,84,35,1) Glcd_Line(0, 63, 127, 0,1) ' Initialize GLCD ' Clear GLCD ' Draw image ' Clear GLCD ' Draw box ' Draw rectangle ' Draw line delay2S() for conter = 5 to 59 vertical lines Delay_ms(50) Glcd_V_Line(2, 54, conter, 2) Glcd_H_Line(2, 120, conter, 2) next conter ' Draw horizontal and Delay2S() Glcd_Fill(0x00) Glcd_Set_Font(@Character8x8, 8, 8, 32) Glcd_Write_Text("mikroE", 5, 7, 2) for conter = 1 to 10 Glcd_Circle(63,32, 3*conter, 1) next conter Delay2S() Glcd_Box(12,20, 70,63, 2) Delay2S() ' Choose font ' Write string ' Draw circles ' Draw box Glcd_Set_Font(@FontSystem5x8, 5, 8, 32) ' Change font someText = "Font 5x8" Glcd_Write_Text(someText, 5, 3, 1) ' Write string Delay2S() Glcd_Set_Font(@System3x6, 3, 6, 32) someText = "SMALL:FONT:3X6" Glcd_Write_Text(someText, 20, 7, 0) Delay2S() wend ' Change font ' Write string end. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 215 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection GLCD HW connection 216 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries KEYPAD LIBRARY The mikroBasic for 8051 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 8051 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.20 External dependencies of Keypad Library The following variable must be defined in all projects using Keypad Library: dim keypadPort as byte external sfr Description: Keypad Port. Example : dim keypadPort as byte at P0 sfr Library Routines - Keypad_Init - Keypad_Key_Press - Keypad_Key_Click Keypad_Init Prototype sub procedure Keypad_Init() Returns Nothing. Description Initializes port for working with keypad. Requires keypadPort variable must be defined before using this function. Example ' Initialize P0 for communication with keypad dim keypadPort as byte at P0 sfr ... Keypad_Init() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 217 CHAPTER 6 mikroBasic for 8051 Libraries Keypad_Key_Press Prototype sub function Keypad_Key_Press() as byte The code of a pressed key (1..16). Returns If no key is pressed, returns 0. Description Reads the key from keypad when key gets pressed. Requires Port needs to be initialized for working with the Keypad library, see Keypad_Init. Example dim kp as byte ... kp = Keypad_Key_Press() Keypad_Key_Click Prototype sub function Keypad_Key_Click() as byte The code of a clicked key (1..16). Returns If no key is clicked, returns 0. Call to Keypad_Key_Click is a blocking call: the function waits until some key is pressed and released. When released, the function returns 1 to 16, depending Description on the key. If more than one key is pressed simultaneously the function will wait until all pressed keys are released. After that the function will return the code of the first pressed key. Requires Port needs to be initialized for working with the Keypad library, see Keypad_Init. Example dim kp as byte ... kp = Keypad_Key_Click() 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. 218 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries program Keypad dim kp, cnt, oldstate as byte txt as byte[5] ' Keypad module connections dim keypadPort as byte at P0 sfr ' End Keypad module connections ' Lcd pinout definition dim LCD_RS as sbit at P2.B0 dim LCD_EN as sbit at P2.B1 dim LCD_D7 as sbit at dim LCD_D6 as sbit at dim LCD_D5 as sbit at dim LCD_D4 as sbit at ' end Lcd definitions P2.B5 P2.B4 P2.B3 P2.B2 main: oldstate = 0 cnt = 0 Keypad_Init() Lcd_Init() Lcd_Cmd(LCD_CLEAR) Lcd_Cmd(LCD_CURSOR_OFF) Lcd_Out(1, 1, "Key :") on LCD Lcd_Out(2, 1, "Times:") ' Reset counter ' Initialize Keypad ' Initialize LCD ' Clear display ' Cursor off ' Write message text while TRUE kp = 0 ' Reset key code variable ' Wait for key to be pressed and released while ( kp = 0 ) kp = Keypad_Key_Click() variable wend ' Store key code in kp ' Prepare value for output, transform key to it's ASCII value select case kp 'case 10: kp = 42 ' "*" for keypad4x3 'case 11: kp = 48 ' "0" 'case 12: kp = 35 ' "#" 'default: kp += 48 ' Uncomment this block MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 219 CHAPTER 6 mikroBasic for 8051 Libraries case 1 kp = 49 ' 1 case 2 kp = 50 ' case 3 kp = 51 ' case 4 kp = 65 ' case 5 kp = 52 ' case 6 kp = 53 ' case 7 kp = 54 ' case 8 kp = 66 ' case 9 kp = 55 ' case 10 kp = 56 ' case 11 kp = 57 ' case 12 kp = 67 ' case 13 kp = 42 ' case 14 kp = 48 ' case 15 kp = 35 ' case 16 kp = 68 ' end select ' end case ' Uncomment this block for keypad4x4 2 3 A 4 5 6 B 7 8 9 C * 0 # D if (kp <> oldstate) then ' Pressed key differs from previous cnt = 1 oldstate = kp else ' Pressed key is same as previous Inc(cnt) end if Lcd_Chr(1, 10, kp) ' Print key ASCII value on LCD if (cnt = 255) then cnt = 0 Lcd_Out(2, 10, " end if WordToStr(cnt, txt) value to string Lcd_Out(2, 10, txt) on LCD wend end. 220 ' If counter varialble overflow ") ' Transform counter ' Display counter value MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries HW Connection 4x4 Keypad connection scheme MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 221 CHAPTER 6 mikroBasic for 8051 Libraries LCD LIBRARY The mikroBasic for 8051 provides a library for communication with LCDs (with HD44780 compliant controllers) through the 4-bit interface. An example of LCD connections is given on the schematic at the bottom of this page. For creating a set of custom LCD characters use LCD Custom Character Tool. External dependencies of LCD Library The following variables must be defined in all projects using LCD Library: dim LCD_RS external dim LCD_EN external dim LCD_D7 external dim LCD_D6 external dim LCD_D5 external dim LCD_D4 external as sbit as sbit as sbit as sbit as sbit as sbit Description: Register Select line. Enable line. Data 7 line. Data 6 line. Data 5 line. Data 4 line. Example : dim LCD_RS P2.B0 dim LCD_EN P2.B1 dim LCD_D7 P2.B5 dim LCD_D6 P2.B4 dim LCD_D5 P2.B3 dim LCD_D4 P2.B2 as sbit at as sbit at as sbit at as sbit at as sbit at as sbit at Library Routines - 222 Lcd_Init Lcd_Out Lcd_Out_Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Lcd_Init Prototype sub procedure Lcd_Init() Returns Nothing. Description Initializes LCD module. Global variables: Requires - LCD_D7: data bit 7 LCD_D6: data bit 6 LCD_D5: data bit 5 LCD_D4: data bit 4 RS: register select (data/instruction) signal pin EN: enable signal pin must be defined before using this function. ' lcd pinout settings Example dim LCD_RS LCD_EN LCD_D7 LCD_D6 LCD_D5 LCD_D4 as as as as as as sbit sbit sbit sbit sbit sbit at at at at at at P2.B0 P2.B1 P2.B5 P2.B4 P2.B3 P2.B2 ... Lcd_Init() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 223 CHAPTER 6 mikroBasic for 8051 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. Example ' Write text "Hello!" on LCD starting from row 1, column 3: Lcd_Out(1, 3, "Hello!") Lcd_Out_Cp Prototype sub procedure Lcd_Out_Cp(dim byref text as string[19]) Returns Nothing. Prints text on LCD at current cursor position. Both string variables and literals can be passed as a text. Description Parameters : - text: text to be written 224 Requires The LCD module needs to be initialized. See Lcd_Init routine. Example ' Write text "Here!" at current cursor position: Lcd_Out_Cp("Here!") MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. Example ' Write character "i" at row 2, column 3: Lcd_Chr(2, 3, 'i') Lcd_Chr_Cp Prototype sub procedure Lcd_Chr_Cp(dim out_char as byte) Returns Nothing. Prints character on LCD at current cursor position. Both variables and literals can be passed as a character. Description Parameters : - out_char: character to be written Requires The LCD module needs to be initialized. See Lcd_Init routine. Example ' Write character "e" at current cursor position: Lcd_Chr_Cp('e') MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 225 CHAPTER 6 mikroBasic for 8051 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 LCD Commands. Requires The LCD module needs to be initialized. See Lcd_Init table. Example ' Clear LCD display: Lcd_Cmd(LCD_CLEAR) Available LCD Commands Lcd Command 226 Purpose LCD_FIRST_ROW Move cursor to the 1st row LCD_SECOND_ROW Move cursor to the 2nd row LCD_THIRD_ROW Move cursor to the 3rd row LCD_FOURTH_ROW Move cursor to the 4th row LCD_CLEAR Clear display LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display data RAM is unaffected. LCD_CURSOR_OFF Turn off cursor LCD_UNDERLINE_ON Underline cursor on LCD_BLINK_CURSOR_ON Blink cursor on LCD_MOVE_CURSOR_LEFT Move cursor left without changing display data RAM LCD_MOVE_CURSOR_RIGHT Move cursor right without changing display data RAM LCD_TURN_ON Turn LCD display on LCD_TURN_OFF Turn LCD display off LCD_SHIFT_LEFT Shift display left without changing display data RAM LCD_SHIFT_RIGHT Shift display right without changing display data RAM MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Library Example The following code demonstrates usage of the LCD Library routines: program Lcd ' LCD module connections dim LCD_RS as sbit at P2.0 dim LCD_EN as sbit at P2.1 dim LCD_D7 as sbit at P2.5 dim LCD_D6 as sbit at P2.4 dim LCD_D5 as sbit at P2.3 dim LCD_D4 as sbit at P2.2 ' End LCD module connections dim txt1 txt2 txt3 txt4 i as as char[16] as char[9] as char[8] as char[7] byte sub procedure Move_Delay() Delay_ms(400) end sub main: txt1 = "mikroElektronika" txt2 = "Easy8051B" txt3 = "lcd 4bit" txt4 = "example" Lcd_Init() Lcd_Cmd(LCD_CLEAR) Lcd_Cmd(LCD_CURSOR_OFF) LCD_Out(1,6,txt3) LCD_Out(2,6,txt4) Delay_ms(2000) Lcd_Cmd(LCD_CLEAR) LCD_Out(1,1,txt1) LCD_Out(2,4,txt2) Delay_ms(500) ' Moving texts for i = 0 to 3 Lcd_Cmd(LCD_SHIFT_RIGHT) Move_Delay() next i ' Loop variable ' Function used for text moving ' You can change the moving speed here ' Initialize LCD ' Clear display ' Cursor off ' Write text in first row ' Write text in second row ' Clear display ' Write text in first row ' Write text in second row ' Move text to the right 4 times MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 227 CHAPTER 6 mikroBasic for 8051 Libraries while TRUE for i = 0 to 6 Lcd_Cmd(LCD_SHIFT_LEFT) Move_Delay() next i for i = 0 to 6 Lcd_Cmd(LCD_SHIFT_RIGHT) Move_Delay() next i ' Endless loop ' Move text to the left 7 times ' Move text to the right 7 times wend end. LCD HW connection 228 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. For detailed schematic see device datasheet. Some basic characteristics of this protocol are: - single master system, low cost, low transfer rates (up to 16 kbps), fairly long distances (up to 300 meters), small data transfer packages. Each OneWire device has also a unique 64-bit registration number (8-bit device type, 48-bit serial number and 8-bit CRC), so multiple slaves can co-exist on the same bus. Note: Oscillator frequency Fosc needs to be at least 8MHz in order to use the routines with Dallas digital thermometers. External dependencies of OneWire Library This variable must be defined in any project that is using OneWire Library: dim OW_Bit as sbit external Description: OneWire line. Example : dim OW_Bit as sbit at P2.B7 Library Routines - Ow_Reset - Ow_Read - Ow_Write MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 229 CHAPTER 6 mikroBasic for 8051 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. Requires Global variable OW_Bit must be defined before using this function. Example ' Issue Reset signal on One-Wire Bus Ow_Reset() 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. Requires Global variable OW_Bit must be defined before using this function. Example 230 ' Read a byte from the One-Wire Bus dim read_data as byte ... read_data = Ow_Read() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. Requires Global variable OW_Bit must be defined before using this function. Example ' Send a byte to the One-Wire Bus Ow_Write(0xCC) Library Example This example reads the temperature using DS18x20 connected to pin P1.2. After reset, MCU obtains temperature from the sensor and prints it on the LCD. Make sure to pull-up P1.2 line and to turn off the P1 leds. program OneWire ' Lcd pinout definition dim LCD_RS as sbit at P2.0 dim LCD_EN as sbit at P2.1 dim LCD_D7 as sbit at dim LCD_D6 as sbit at dim LCD_D5 as sbit at dim LCD_D4 as sbit at ' end Lcd definition P2.5 P2.4 P2.3 P2.2 ' OneWire pinout dim OW_Bit as sbit at P1.B2 ' end OneWire definition ' Set TEMP_RESOLUTION to the corresponding resolution of used DS18x20 sensor: ' 18S20: 9 (default setting can be 9,10,11,or 12) ' 18B20: 12 const TEMP_RESOLUTION as byte = 9 dim text as char[8] temp as word MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 231 CHAPTER 6 mikroBasic for 8051 Libraries sub procedure Display_Temperature(dim temp2write as word) const RES_SHIFT as byte = TEMP_RESOLUTION - 8 dim temp_whole as byte temp_fraction as word text = "000.0000" ' check if temperature is negative if (temp2write and 0x8000) then text[0] = "-" temp2write = not temp2write + 1 end if ' extract temp_whole temp_whole = temp2write >> RES_SHIFT ' convert temp_whole to characters if (temp_whole div 100 ) then text[0] = temp_whole div 100 + 48 end if text[1] = (temp_whole div 10) mod 10 + 48 tens digit text[2] = temp_whole mod 10 + 48 ones digit ' Extract ' Extract ' extract temp_fraction and convert it to unsigned int temp_fraction = temp2write << (4-RES_SHIFT) temp_fraction = temp_fraction and 0x000F temp_fraction = temp_fraction * 625 ' convert temp_fraction to characters text[4] = temp_fraction thousands digit text[5] = (temp_fraction hundreds digit text[6] = (temp_fraction tens digit text[7] = temp_fraction ones digit div 1000 + 48 ' Extract div 100) mod 10 + 48 ' Extract div 10) mod 10 ' Extract mod 10 + 48 + 48 ' Extract ' print temperature on LCD Lcd_Out(2, 5, text) end sub 232 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries main: Lcd_Init() Lcd_Cmd(LCD_CLEAR) Lcd_Cmd(LCD_CURSOR_OFF) Lcd_Out(1, 1, " Temperature: ") ' Print degree character, "C" for Centigrades Lcd_Chr(2,13,223) Lcd_Chr(2,14,"C") ' main loop while TRUE ' Perform temperature reading Ow_Reset() signal Ow_Write(0xCC) SKIP_ROM Ow_Write(0x44) CONVERT_T Delay_us(120) Ow_Reset() Ow_Write(0xCC) SKIP_ROM Ow_Write(0xBE) READ_SCRATCHPAD ' Initialize LCD ' Clear LCD ' Turn cursor off ' Onewire reset ' Issue command ' Issue command ' Issue command ' Issue command temp = Ow_Read() temp = (Ow_Read() << 8) or temp ' Format and display result on Lcd Display_Temperature(temp) Delay_ms(500) wend end. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 233 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection Example of DS1820 connection 234 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries MANCHESTER CODE LIBRARY The mikroBasic for 8051 provides a library for handling Manchester coded signals. The Manchester code is a code in which data and clock signals are combined to form a single self-synchronizing data stream; each encoded bit contains a transition at the midpoint of a bit period, the direction of transition determines whether the bit is 0 or 1; the second half is the true bit value and the first half is the complement of the true bit value (as shown in the figure below). Notes: The Manchester receive routines are blocking calls (Man_Receive_Init and Man_Synchro). This means that MCU will wait until the task has been performed (e.g. byte is received, synchronization achieved, etc). The following variables must be defined in all projects using Manchester Code Library: dim MANRXPIN as sbit external dim MANTXPIN as sbit external Description: Receive line. Transmit line. Example : dim MANRXPIN as sbit at P0.B0 dim MANTXPIN as sbit at P1.B1 Library Routines - Man_Receive_Init Man_Receive Man_Send_Init Man_Send Man_Synchro Man_Out MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 235 CHAPTER 6 mikroBasic for 8051 Libraries The following routines are for the internal use by compiler only: - Manchester_0 - Manchester_1 - Manchester_Out Man_Receive_Init Prototype sub function Man_Receive_Init()as word - 0 - if initialization and synchronization were successful. - 1 - upon unsuccessful synchronization. Returns The function configures Receiver pin and performs synchronization procedure in order to retrieve baud rate out of the incoming signal. Description Note: In case of multiple persistent errors on reception, the user should call this routine once again or Man_Synchro routine to enable synchronization. Requires MANRXPIN variable must be defined before using this function. Example ' Initialize Receiver dim MANRXPIN as sbit at P0.B0 ... Man_Receive_Init() 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 ... data = 0 error = 0 data = Man_Receive(&error) if (error <> 0) then ' error handling end if 236 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Man_Send_Init Prototype sub procedure Man_Send_Init() Returns Nothing. Description The function configures Transmitter pin. Requires MANTXPIN variable must be defined before using this function. Example ' Initialize Transmitter: dim MANTXPIN as sbit at P1.B1 ... Man_Send_Init() 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) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 237 CHAPTER 6 mikroBasic for 8051 Libraries Man_Synchro Prototype Returns sub function Man_Synchro() as word - 0 - if synchronization was not successful. - Half of the manchester bit length, given in multiples of 10us - upon successful synchronization. Description Measures half of the manchester bit length with 10us resolution. Requires To use this function, you must first prepare the MCU for receiving. See Man_Receive_Init. Example dim man__half_bit_len as word ... man__half_bit_len = Man_Synchro() Man_Out Prototype sub procedure Man_Out(BitValue as byte) Returns Nothing. Sends one byte in Manchester format. Description Parameters : - BitValue: data to be sent 238 Requires To use this function, the user must prepare the MCU for sending. See Man_Send_Init. Example dim BitValue as byte ... Man_Out(BitValue) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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 P2.0 dim LCD_EN as sbit at P2.1 dim LCD_D7 as sbit at P2.5 dim LCD_D6 as sbit at P2.4 dim LCD_D5 as sbit at P2.3 dim LCD_D4 as sbit at P2.2 ' End LCD module connections ' Manchester module connections dim MANRXPIN as sbit at P0.B0 dim MANTXPIN as sbit at P1.B1 ' End Manchester module connections dim error_, ErrorCount, temp as byte main: ErrorCount = 0 Lcd_Init() Lcd_Cmd(LCD_CLEAR) ' Initialize LCD ' Clear LCD display Man_Receive_Init() ' Initialize Receiver while TRUE Lcd_Cmd(LCD_FIRST_ROW) 1st row while TRUE byte temp = Man_Receive(error_) if (temp = 0x0B) then Transmitter example break ing sequence end if if (error_ <> 0) then loop forever break end if ' Inc(P1) wend ' Endless loop ' Move cursor to the ' Wait for the "start" ' Attempt byte receive ' "Start" byte, see ' We got the start- ' Exit so we do not MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 239 CHAPTER 6 mikroBasic for 8051 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" byte was received(see Transmitter example) Lcd_Chr_CP(temp) ' do not write received byte on LCD end if end if Delay_ms(25) wend wend ' If "End" byte was received exit do loop end. The following code is code for the Manchester transmitter, it shows how to use the Manchester Library for transmitting data: program Manchester_Transmitter ' Manchester module connections dim MANRXPIN as sbit at P0.B0 dim MANTXPIN as sbit at P1.B1 ' End Manchester module connections dim index, character as byte s1 as char[17] main: s1 = "mikroElektronika" Man_Send_Init() while TRUE Man_Send(0x0B) Delay_ms(100) character = s1[0] index = 0 while (character <> 0) Man_Send(character) Delay_ms(90) Inc(index) character = s1[index] wend Man_Send(0x0E) Delay_ms(1000) wend end. 240 ' Initialize transmitter ' Endless loop ' Send "start" byte ' Wait for a while ' Take first char from string ' Initialize index variable ' String ends with zero ' Send character ' Wait for a while ' Increment index variable ' Take next char from string ' Send "end" byte MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Connection Example Simple Transmitter connection Simple Receiver connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 241 CHAPTER 6 mikroBasic for 8051 Libraries PORT EXPANDER LIBRARY The mikroBasic for 8051 provides a library for communication with the Microchip’s Port Expander MCP23S17 via SPI interface. Connections of the 8051 compliant MCU and MCP23S17 is given on the schematic at the bottom of this page. Note: Library uses the SPI module for communication. The user must initialize SPI module before using the Port Expander Library. Note: Library does not use Port Expander interrupts. External dependencies of Port Expander Library The following variables must be defined in all projects using Port Expander Library: dim SPExpanderCS as sbit external dim SPExpanderRST as sbit external Description: Chip Select line. Reset line. Example : dim SPExpanderCS as sbit at P1.B1 dim SPExpanderRST as sbit at P1.B0 Library Routines - 242 Expander_Init Expander_Read_Byte Expander_Write_Byte Expander_Read_PortA Expander_Read_PortB Expander_Read_PortAB Expander_Write_PortA Expander_Write_PortB Expander_Write_PortAB Expander_Set_DirectionPortA Expander_Set_DirectionPortB Expander_Set_DirectionPortAB Expander_Set_PullUpsPortA Expander_Set_PullUpsPortB Expander_Set_PullUpsPortAB MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Expander_Init Prototype sub procedure Expander_Init(dim ModuleAddress as byte) Returns Nothing. Initializes Port Expander using SPI communication. Port Expander module settings : Description - hardware addressing enabled automatic address pointer incrementing disabled (byte mode) BANK_0 register adressing slew rate enabled Parameters : - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page SPExpanderCS and SPExpanderRST variables must be defined before using this function. Requires SPI module needs to be initialized. See Spi_Init and Spi_Init_Advanced routines. Example ' port expander pinout definition dim SPExpanderCS as sbit at P1.B1 SPExpanderRST as sbit at P1.B0 ... Spi_Init() ' initialize SPI module Expander_Init(0) ' initialize port expander MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 243 CHAPTER 6 mikroBasic for 8051 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. Example ' Read a byte from Port Expander's register dim read_data as byte ... read_data = Expander_Read_Byte(0,1) Expander_Write_Byte Prototype sub procedure Expander_Write_Byte(dim ModuleAddress as byte, dim RegAddress as byte, dim Data_ as byte) Returns Nothing. Routine writes a byte to Port Expander. Parameters : Description 244 - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - RegAddress: Port Expander's internal register address - Data_: data to be written Requires Port Expander must be initialized. See Expander_Init. Example ' Write a byte to the Port Expander's register Expander_Write_Byte(0,1,0xFF) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. See Expander_Set_DirectionPortA and Expander_Set_DirectionPortAB routines. ' Read a byte from Port Expander's PORTA dim read_data as byte ... Expander_Set_DirectionPortA(0,0xFF) to be input ... read_data = Expander_Read_PortA(0) ' set expander's porta Expander_Read_PortB Prototype sub function Expander_Read_PortB(dim ModuleAddress as byte) as byte Returns Byte read. The function reads byte from Port Expander's PortB. 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 PortB should be configured as input. See Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines. ' Read a byte from Port Expander's PORTB dim read_data as byte ... Expander_Set_DirectionPortB(0,0xFF) to be input ... read_data = Expander_Read_PortB(0) ' set expander's portb MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 245 CHAPTER 6 mikroBasic for 8051 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. Requires Example 246 Port Expander's PortA and PortB should be configured as inputs. See Expander_Set_DirectionPortA, Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines. ' Read a byte from Port Expander's PORTA and PORTB dim read_data as word ... Expander_Set_DirectionPortAB(0,0xFFFF) ' set expander's porta and portb to be input ... read_data = Expander_Read_PortAB(0) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. See Expander_Set_DirectionPortA and Expander_Set_DirectionPortAB routines. ' Write a byte to Port Expander's PORTA Example ... Expander_Set_DirectionPortA(0,0x00) to be output ... Expander_Write_PortA(0, 0xAA) ' set expander's porta MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 247 CHAPTER 6 mikroBasic for 8051 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. See Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines. ' Write a byte to Port Expander's PORTB Example 248 ... Expander_Set_DirectionPortB(0,0x00) to be output ... Expander_Write_PortB(0, 0x55) ' set expander's portb MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. Data to be written to PortB are passed in Data's lower byte Port Expander must be initialized. See Expander_Init. Requires Port Expander's PortA and PortB should be configured as outputs. See Expander_Set_DirectionPortA, Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines. ' Write a byte to Port Expander's PORTA and PORTB Example ... Expander_Set_DirectionPortAB(0,0x0000) porta and portb to be output ... Expander_Write_PortAB(0, 0xAA55) ' set expander's MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 249 CHAPTER 6 mikroBasic for 8051 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. Set bit designates corresponding pin as input. Cleared bit designates corresponding pin as output. Requires Port Expander must be initialized. See Expander_Init. Example ' Set Port Expander's PORTA to be output Expander_Set_DirectionPortA(0,0x00) Expander_Set_DirectionPortB Prototype sub procedure Expander_Set_DirectionPortB(dim ModuleAddress as byte, dim Data_ as byte) Returns Nothing. The function sets Port Expander's PortB direction. Parameters : Description - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data_: data to be written to the PortB direction register. Each bit corresponds to the appropriate pin of the PortB register. Set bit designates corresponding pin as input. Cleared bit designates corresponding pin as output. 250 Requires Port Expander must be initialized. See Expander_Init. Example ' Set Port Expander's PORTB to be input Expander_Set_DirectionPortB(0,0xFF) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. Data to be written to the PortA direction register are passed in Direction's higher byte. Data to be written to the PortB direction register are passed in Direction's lower byte. Each bit corresponds to the appropriate pin of the PortA/PortB register. Set bit designates corresponding pin as input. Cleared bit designates corresponding pin as output. Requires Port Expander must be initialized. See Expander_Init. Example ' Set Port Expander's PORTA to be output and PORTB to be input Expander_Set_DirectionPortAB(0,0x00FF) Expander_Set_PullUpsPortA Prototype sub procedure Expander_Set_PullUpsPortA(dim ModuleAddress as byte, dim Data_ as byte) Returns Nothing. The function sets Port Expander's PortA 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 PortA register. Set bit enables pull-up for corresponding pin. Requires Port Expander must be initialized. See Expander_Init. Example ' Set Port Expander's PORTA pull-up resistors Expander_Set_PullUpsPortA(0, 0xFF) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 251 CHAPTER 6 mikroBasic for 8051 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. Set bit enables pull-up for corresponding pin. Requires Port Expander must be initialized. See Expander_Init. Example ' Set Port Expander's PORTB pull-up resistors Expander_Set_PullUpsPortB(0, 0xFF) Expander_Set_PullUpsPortAB Prototype sub procedure Expander_Set_PullUpsPortAB(dim ModuleAddress as byte, dim PullUps as word) Returns Nothing. The function sets Port Expander's PortA and PortB pull up/down resistors. Parameters : Description 252 - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - PullUps: data for choosing pull up/down resistors configuration. PortA pull up/down resistors configuration is passed in PullUps's higher byte. PortB pull up/down resistors configuration is passed in PullUps's lower byte. Each bit corresponds to the appropriate pin of the PortA/PortB register. Set bit enables pull-up for corresponding pin. Requires Port Expander must be initialized. See Expander_Init. Example ' Set Port Expander's PORTA and PORTB pull-up resistors Expander_Set_PullUpsPortAB(0, 0xFFFF) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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 dim i as byte ' Port Expander module connections dim SPExpanderRST as sbit at P1.B0 dim SPExpanderCS as sbit at P1.B1 ' End Port Expander module connections main: i = 0 Spi_Init() ule Expander_Init(0) Expander ' Initialize SPI mod- ' Initialize Port Expander_Set_DirectionPortA(0, 0x00) to be output ' Set Expander"s PORTA Expander_Set_DirectionPortB(0,0xFF) to be input Expander_Set_PullUpsPortB(0,0xFF) of the Expander"s PORTB pins ' Set Expander"s PORTB while TRUE Expander_Write_PortA(0, i) PORTA Inc(i) P0 = Expander_Read_PortB(0) and write it to PORT0 Delay_ms(100) wend end. ' Set pull-ups to all ' Endless loop ' Write i to expander"s ' Read expander"s PORTB MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 253 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection Port Expander HW connection 254 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries PS/2 LIBRARY The mikroBasic for 8051 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. pressing the Caps Lock key will not turn on the Caps Lock LED. External dependencies of PS/2 Library The following variables must be defined in all projects using PS/2 Library: Description: dim PS2_DATA as sbit PS/2 Data line. external dim PS2_CLOCK as sbit PS/2 Clock line. external Example : dim PS2_DATA as sbit at P0.B0 dim PS2_CLOCK as sbit at P0.B1 Library Routines - Ps2_Config - Ps2_Key_Read MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 255 CHAPTER 6 mikroBasic for 8051 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 pin - PS2_CLOCK: Clock signal pin must be defined before using this function. Example 256 ' PS2 pinout definition dim PS2_DATA as sbit at P0.B0 PS2_CLOCK as sbit at P0.B1 ... Ps2_Config() ' Init PS/2 Keyboard MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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 : Description - value: holds the value of the key pressed. For characters, numerals, punctuation marks, and space value will store the appropriate ASCII code. Routine “recognizes” the function of Shift and Caps Lock, and behaves appropriately. For special function keys see Special Function Keys Table. - special: is a flag for special function keys (F1, Enter, Esc, etc). If key pressed is one of these, special will be set to 1, otherwise 0. - pressed: is set to 1 if the key is pressed, and 0 if it is released. Requires PS/2 keyboard needs to be initialized. See Ps2_Config routine. Example dim value, special, pressed as byte ... do { if (Ps2_Key_Read(value, special, pressed)) then if ((value = 13) and (special = 1)) then break end if end if loop until (0=1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 257 CHAPTER 6 mikroBasic for 8051 Libraries Special Function Keys Key 258 Value returned Scroll Lock 28 F1 1 Num Lock 29 F2 2 Left Arrow 30 F3 3 Right Arrow 31 F4 4 Up Arrow 32 F5 5 Down Arrow 33 F6 6 Escape 34 F7 7 Tab 35 F8 8 F9 9 F10 10 F11 11 F12 12 Enter 13 Page Up 14 Page Down 15 Backspace 16 Insert 17 Delete 18 Windows 19 Ctrl 20 Shift 21 Alt 22 Print Screen 23 Pause 24 Caps Lock 25 End 26 Home 27 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Library Example This simple example reads values of the pressed keys on the PS/2 keyboard and sends them via UART. program PS2 dim keydata, special, down as byte ' PS2 module connections dim PS2_DATA as sbit at P0.B0 PS2_CLOCK as sbit at P0.B1 ' End PS2 module connections main: Uart_Init(4800) Ps2_Config() Delay_ms(100) keydata = 0 special = 0 down ' ' ' = Initialize UART module at 4800 bps Initialize PS/2 Keyboard Wait for keyboard to finish 0 while true if (Ps2_Key_Read(keydata, special, down)) <> 0 then was read from PS/2 if ((down = 1) and (keydata = 16)) <> 0 then Backspace read Uart_Write(0x08) Backspace to usart terminal else if ((down = 1) and (keydata = 13)) <> 0 then ' If data ' ' Send ' Enter read Uart_Write(10) Uart_Write(13) also expects line feed ' Send carriage return to usart terminal ' Uncomment this line if usart terminal ' for new line transition else if ((down = 1) and (special = 0) and (keydata <> 0)) then ' Common key read Uart_Write(keydata) ' Send key to usart terminal end if end if end if end if Delay_ms(10) ' Debounce period wend end. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 259 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection Example of PS2 keyboard connection 260 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries RS-485 LIBRARY RS-485 is a multipoint communication which allows multiple devices to be connected to a single bus. The mikroBasic for 8051 provides a set of library routines for comfortable work with RS485 system using Master/Slave architecture. Master and Slave devices interchange packets of information. Each of these packets contains synchronization bytes, CRC byte, address byte and the data. Each Slave has unique address and receives only packets addressed to it. The Slave can never initiate communication. It is the user’s responsibility to ensure that only one device transmits via 485 bus at a time. The RS-485 routines require the UART module. Pins of UART need to be attached to RS-485 interface transceiver, such as LTC485 or similar (see schematic at the bottom of this page). Library constants: - START byte value = 150 - STOP byte value = 169 - Address 50 is the broadcast address for all Slaves (packets containing address 50 will be received by all Slaves except the Slaves with addresses 150 and 169). External dependencies of RS-485 Library The following variable must be defined in all projects using RS-485 Library: Description: Control RS-485 dim rs485_transceive as Transmit/Receive sbit external operation mode Example : dim rs485_transceive as sbit at P3.B2 Library Routines - RS485master_Init RS485master_Receive RS485master_Send RS485slave_Init RS485slave_Receive RS485slave_Send MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 261 CHAPTER 6 mikroBasic for 8051 Libraries RS485master_Init Prototype sub procedure Rs485master_Init() Returns Nothing. Description Initializes MCU as a Master for RS-485 communication. rs485_transceive variable must be defined before using this function. This pin Requires 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. Valid values: 1 (for transmitting) and 0 (for receiving) UART HW module needs to be initialized. See Uart_Init. Example ' rs485 module pinout dim rs485_transceive as sbit at P3.B2 ' transmit/receive control set to port3.bit2 ... Uart_Init(9600) ' initialize usart module Rs485master_Init() ' intialize mcu as a Master for RS-485 communication RS485master_Receive Prototype sub procedure Rs485master_Receive(dim byref data_buffer as array[20] of byte) 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..2]: message content data[3]: number of message bytes received, 1–3 data[4]: is set to 255 when message is received data[5]: is set to 255 if error has occurred data[6]: address of the Slave which sent the message The function automatically adjusts data[4] and data[5] upon every received message. These flags need to be cleared by software. 262 Requires MCU must be initialized as a Master for RS-485 communication. See RS485master_Init. Example dim msg as array[20] of byte ... RS485master_Receive(msg) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries RS485master_Send Prototype sub procedure Rs485master_Send(dim byref data_buffer as array[20] of byte, 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. See RS485master_Init. Requires It is the user’s responsibility to ensure (by protocol) that only one device sends data via 485 bus at a time. Example dim msg as array[20] of byte ... ' send 3 bytes of data to slave with address 0x12 RS485master_Send(msg, 3, 0x12) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 263 CHAPTER 6 mikroBasic for 8051 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 rs485_transceive variable must be defined before using this function. This pin Requires 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. Valid values: 1 (for transmitting) and 0 (for receiving) UART HW module needs to be initialized. See Uart_Init. Example 264 ' rs485 module pinout dim rs485_transceive as sbit at P3.B2 ' transmit/receive control set to port3.bit2 ... Uart_Init(9600) ' initialize usart module Rs485slave_Init(160) ' intialize mcu as a Slave for RS-485 communication with address 160 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries RS485slave_Receive Prototype sub procedure RS485slave_Receive(dim byref data_buffer as array[20] of byte) 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..2]: message content data[3]: number of message bytes received, 1–3 data[4]: is set to 255 when message is received data[5]: is set to 255 if error has occurred The function automatically adjusts data[4] and data[5] upon every received message. These flags need to be cleared by software. Requires MCU must be initialized as a Slave for RS-485 communication. See RS485slave_Init. Example dim msg as array[5] of byte ... RS485slave_Read(msg) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 265 CHAPTER 6 mikroBasic for 8051 Libraries RS485slave_Send Prototype sub procedure Rs485slave_Send(dim byref data_buffer as array[20] of byte, 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. It is the user’s responsibility to ensure (by protocol) that only one device sends data via 485 bus at a time. Example dim msg as array[8] of byte ... ' send 2 bytes of data to the master RS485slave_Send(msg, 2) Library Example This is a simple demonstration of RS485 Library routines usage. Master sends message to Slave with address 160 and waits for a response. The Slave accepts data, increments it and sends it back to the Master. Master then does the same and sends incremented data back to Slave, etc. Master displays received data on P0, while error on receive (0xAA) and number of consecutive unsuccessful retries are displayed on P1. Slave displays received data on P0, while error on receive (0xAA) is displayed on P1. Hardware configurations in this example are made for the Easy8051B board and AT89S8253. RS485 Master code: program RS485_Master dim dat as byte[20] counter, j as byte count as longint ' RS485 module connections dim rs485_transceive as sbit at P3.B2 ' End RS485 module connections 266 ' Buffer for receving/sending messages ' Transmit/Receive control set to P3.2 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries ' Interrupt routine sub procedure UartRxHandler() ORG 0x23 EA = 0 ' Clear global interrupt enable flag if ( RI <> 0 ) then ' Test UART receive interrupt flag Rs485master_Receive(dat) ' UART receive interrupt detected, ' receive data using RS485 communication RI = 0 ' Clear UART interrupt flag end if EA = 1 ' Set global interrupt enable flag end sub main: count = 0 P0 = 0 P1 = 0 Uart_Init(9600) Delay_ms(100) ' Clear ports ' Initialize UART module at 9600 bps Rs485master_Init() ' Intialize MCU as RS485 master dat[0] = 0x55 ' Fill buffer dat[1] = 0x00 dat[2] = 0x00 dat[4] = 0 ' Ensure that message received flag is 0 dat[5] = 0 ' Ensure that error flag is 0 dat[6] = 0 Rs485master_Send(dat,1,160) ' Send message to slave with address 160 ' message data is stored in dat ' message is 1 byte long ES = 1 RI = 0 flag EA = 1 while TRUE ' Enable UART interrupt ' Clear UART RX interrupt ' Enable interrupts ' Endless loop ' Upon completed valid message receiving Inc(count) ' data[4] is set to 255 ' Increment loop pass count- er if (dat[5] <> 0) then nal it by P1 = 0xAA end if ' If error detected, sig' setting PORT1 to 0xAA MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 267 CHAPTER 6 mikroBasic for 8051 Libraries if (dat[4] <> 0) then ' If message received successfully count = 0 ' Reset loop pass counter dat[4] = 0 ' Clear message received flag j = dat[3] ' Read number of message received bytes for counter = 1 to j P0 = dat[counter-1] ' Show received data on PORT0 next counter Inc(dat[0]) ' Increment first received byte dat[0] Delay_ms(10) Rs485master_Send(dat,1,160) end if if ( count > 10000 ) then times with ' And send it back to Slave ' If loop is passed 100000 ' no message received Inc(P1) ' Signal receive message failure on PORT1 count = 0 ' Reset loop pass counter Rs485master_Send(dat,1,160) ' Retry send message if (P1 > 10) then ' If sending failed 10 times P1 = 0 ' Clear PORT1 Rs485master_Send(dat,1,50) ' Send message on broadcast address end if end if wend end. RS485 Slave code: program RS485_Slave dim dat as byte[20] ing messages counter, j as byte ' RS485 module connections dim rs485_transceive as sbit at P3.B2 set to P3.2 ' End RS485 module connections ' Buffer for receving/send- ' Transmit/Receive control ' Interrupt routine sub procedure UartRxHandler() ORG 0x23 EA = 0 ' Clear global interrupt enable flag if( RI <> 0) then ' Test UART receive interrupt flag Rs485slave_Receive(dat) ' UART receive interrupt detected, 268 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries RI = 0 end if EA = 1 end sub ' receive data using RS485 communication ' Clear UART interrupt flag ' Set global interrupt enable flag main: P0 = 0 P1 = 0 Uart_Init(9600) Delay_ms(100) Rs485slave_Init(160) dat[4] = 0 dat[5] = 0 ' Clear ports ' Initialize UART module at 9600 bps ' Intialize MCU as slave, address 160 ' ensure that message received flag is 0 ' ensure that error flag is 0 ES = 1 RI = 0 EA = 1 while TRUE ' Enable UART interrupt ' Clear UART RX interrupt flag ' Enable interrupts ' Endless loop ' Upon completed valid message receiving if (dat[5] <> 0) then nal it by P1 = 0xAA end if if (dat[4] <> 0) then cessfully dat[4] = 0 ' data[4] is set to 255 ' If error detected, sig' setting PORT1 to 0xAA ' If message received suc- ' Clear message received flag j = dat[3] received bytes for counter = 1 to j P0 = dat[counter-1] PORT0 next counter dat[0] = dat[0] + 1 Delay_ms(10) Rs485slave_Send(dat,1) end if wend end. ' Read number of message ' Show received data on ' Increment received dat[0] ' And send back to Master MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 269 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection Example of interfacing PC to 8051 MCU via RS485 bus with LTC485 as RS-485 transceiver 270 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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 XORed with 1, START_BYTE or STOP_BYTE 0 DATA3 (if exists) UNCHANGED bit3 = 1 DATA2 (if exists) WAS XORed with 1, START_BYTE or STOP_BYTE 0 DATA2 (if exists) UNCHANGED bit2 = 1 DATA1 (if exists) WAS XORed with 1, START_BYTE or STOP_BYTE 0 DATA1 (if exists) UNCHANGED bit1bit0 = 0 to 3 NUMBER OF DATA BYTES SEND TO START_BYTE or IT WAS EQUAL TO IT WAS EQUAL TO IT WAS EQUAL TO CRC generation : ---------------crc_send = datalen ^ address; crc_send ^= data[0]; ' if exists crc_send ^= data[1]; ' if exists crc_send ^= data[2]; ' if exists crc_send = ~crc_send; if ((crc_send == START_BYTE) || (crc_send == STOP_BYTE)) crc_send++; NOTE: DATALEN<4..0> can STOP_BYTE<4..0> values. not take the START_BYTE<4..0> MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD or 271 CHAPTER 6 mikroBasic for 8051 Libraries SOFTWARE I²C LIBRARY The mikroBasic for 8051 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. Note: All I˛C Library functions are blocking-call functions (they are waiting for I˛C clock line to become logical one). Note: The pins used for I˛C communication should be connected to the pull-up resistors. Turning off the LEDs connected to these pins may also be required. External dependecies of Soft_I2C Library The following variables must be defined in all projects using Soft_I2C Library: dim Soft_I2C_Scl as sbit external dim Soft_I2C_Sda as sbit external Description: Soft I˛C Clock line. Soft I˛C Data line. Example : dim Soft_I2C_Scl as sbit at P1.B3 dim Soft_I2C_Sda as sbit at P1.B4 Library Routines - 272 Soft_I2C_Init Soft_I2C_Start Soft_I2C_Read Soft_I2C_Write Soft_I2C_Stop MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Soft_I2C_Init Prototype sub procedure Soft_I2C_Init() Returns Nothing. Description Configures the software I˛C module. Requires Example Soft_I2C_Scl and Soft_I2C_Sda variables must be defined before using this function. ' soft_i2c pinout definition dim Soft_I2C_Scl as sbit at P1.B3 Soft_I2C_Sda as sbit at P1.B4 ... Soft_I2C_Init() Soft_I2C_Start Prototype sub procedure Soft_I2C_Start() Returns Nothing. Description Determines if the I˛C bus is free and issues START signal. Requires Software I˛C 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. Description Parameters : - ack: acknowledge signal parameter. If the ack==0 not acknowledge signal will be sent after reading, otherwise the acknowledge signal will be sent. Soft I˛C must be configured before using this function. See Soft_I2C_Init routine. Requires Example Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine. dim take as word ... ' Read data and send the not_acknowledge signal take = Soft_I2C_Read(0) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 273 CHAPTER 6 mikroBasic for 8051 Libraries Soft_I2C_Write Prototype sub function Soft_I2C_Write(dim _Data as byte) as byte - 0 if there were no errors. - 1 if write collision was detected on the I˛C bus. Returns Sends data byte via the I˛C bus. Description Parameters : - _Data: data to be sent Soft I˛C must be configured before using this function. See Soft_I2C_Init routine. Requires Example Also, START signal needs to be issued in order to use this function. See Soft_I2C_Start routine. dim _data, error as byte ... error = Soft_I2C_Write(data) error = Soft_I2C_Write(0xA3) Soft_I2C_Stop Prototype sub procedure Soft_I2C_Stop() Returns Nothing. Description Issues STOP signal. 274 Requires Soft I˛C must be configured before using this function. See Soft_I2C_Init routine Example ' Issue STOP signal Soft_I2C_Stop() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Library Example The example demonstrates Software I˛C Library routines usage. The 8051 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. program Soft_I2C dim seconds, minutes, hours, day, month_, year as byte date/time variables ' Global ' Software I2C connections dim Soft_I2C_Scl as sbit at P1.B3 dim Soft_I2C_Sda as sbit at P1.B4 ' End Software I2C connections ' LCD module connections dim LCD_RS as sbit at P2.0 dim LCD_EN as sbit at P2.1 dim LCD_D7 as sbit at P2.5 dim LCD_D6 as sbit at P2.4 dim LCD_D5 as sbit at P2.3 dim LCD_D4 as sbit at P2.2 ' End LCD module connections '--------------------- Reads (PCF8583) sub procedure Read_Time() time Soft_I2C_Start() Soft_I2C_Write(0xA0) datasheet Soft_I2C_Write(2) Soft_I2C_Start() Soft_I2C_Write(0xA1) R/W=1 seconds = Soft_I2C_Read(1) minutes = Soft_I2C_Read(1) hours = Soft_I2C_Read(1) day = Soft_I2C_Read(1) month_ = Soft_I2C_Read(0) Soft_I2C_Stop() end sub and date information from RTC ' Issue start signal ' Address PCF8583, see PCF8583 ' Start from address 2 ' Issue repeated start signal ' Address PCF8583 for reading ' Read seconds byte ' Read minutes byte ' Read hours byte ' Read year/day byte ' Read weekday/month byte ' Issue stop signal MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 275 CHAPTER 6 mikroBasic for 8051 Libraries '-------------------- 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) Transform month end sub ' ' ' ' ' ' '-------------------- Output values to LCD sub procedure Display_Time() Lcd_Chr(1, 6, (day / 10) + 48) ' Print tens digit of day variable Lcd_Chr(1, 7, (day mod 10) + 48) ' Print oness digit of day variable Lcd_Chr(1, 9, (month_ / 10) + 48) Lcd_Chr(1,10, (month_ mod 10) + 48) Lcd_Chr(1,15, year + 56) ' Print year vaiable + 8 (start from year 2008) Lcd_Chr(2, 6, Lcd_Chr(2, 7, Lcd_Chr(2, 9, Lcd_Chr(2,10, Lcd_Chr(2,12, Lcd_Chr(2,13, end sub (hours / 10) + 48) (hours mod 10) + 48) (minutes / 10) + 48) (minutes mod 10) + 48) (seconds / 10) + 48) (seconds mod 10) + 48) '------------------ Performs project-wide init sub procedure Init_Main() Soft_I2C_Init() Lcd_Init() Lcd_Cmd(LCD_CLEAR) Lcd_Cmd(LCD_CURSOR_OFF) 276 ' Initialize Soft I2C communication ' Initialize LCD ' Clear LCD display ' Turn cursor off MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 LCD_Out(1,1,"Date:") LCD_Chr(1,8,":") LCD_Chr(1,11,":") LCD_Out(2,1,"Time:") LCD_Chr(2,8,":") LCD_Chr(2,11,":") LCD_Out(1,12,"200") end sub Libraries ' Prepare and output static text on LCD '----------------- Main sub procedure main: Init_Main() ' Perform initialization while TRUE Read_Time() Transform_Time() Display_Time() wend end. ' Endless loop ' Read time from RTC(PCF8583) ' Format date and time ' Prepare and display on LCD MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 277 CHAPTER 6 mikroBasic for 8051 Libraries SOFTWARE SPI LIBRARY The mikroBasic for 8051 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. Data sampled at the middle of interval. Data transmitted at low to high edge. Note: The Software SPI library implements time-based activities, so interrupts need to be disabled when using it. The following variables must be defined in all projects using Software SPI Library: dim SoftSpi_SDI as sbit external dim SoftSpi_SDO as sbit external dim SoftSpi_CLK as sbit external Description: Data In line. Data Out line. Clock line. Example : dim SoftSpi_SDI as sbit at P0.B4 dim SoftSpi_SDO as sbit at P0.B5 dim SoftSpi_CLK as sbit at P0.B3 Library Routines - Soft_Spi_Init - Soft_Spi_Read - Soft_Spi_Write 278 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Soft_Spi_Init Prototype sub procedure Soft_SPI_Init() Returns Nothing. Description Configures and initializes the software SPI module. Requires SoftSpi_CLK, SoftSpi_SDI and SoftSpi_SDO variables must be defined before using this function. Example ' soft_spi pinout definition dim SoftSpi_SDI as sbit at P0.B4 SoftSpi_SDO as sbit at P0.B5 SoftSpi_CLK as sbit at P0.B3 ... Soft_SPI_Init() ' Init Soft_SPI Soft_Spi_Read Prototype sub function Soft_Spi_Read(dim sdata as byte) as byte 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 ... ' Read a byte and assign it to data_read variable ' (data_send byte will be sent via SPI during the Read operation) data_read = Soft_Spi_Read(data_send) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 279 CHAPTER 6 mikroBasic for 8051 Libraries Soft_Spi_Write Prototype sub procedure Soft_Spi_Write(dim sdata as byte) Returns Nothing. This routine sends one byte via the Software SPI bus. Description Parameters : - sdata: data to be sent. Requires Soft SPI must be initialized before using this function. See Soft_Spi_Init routine. Example ' Write a byte to the Soft SPI bus Soft_Spi_Write(0xAA) 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 P3.B4 SoftSpi_CLK as sbit at P1.B7 SoftSpi_SDI as sbit at P1.B6 SoftSpi_SDO as sbit at P1.B5 ' End DAC module connections dim value as word sub procedure InitMain() P0 = 255 Soft_SPI_Init() end sub ' Set PORT0 as input ' Initialize Soft_SPI ' DAC increments (0..4095) --> output voltage (0..Vref) sub procedure DAC_Output(dim valueDAC as word) dim temp as byte Chip_Select = 0 ' Send High Byte temp = word(valueDAC >> 8) temp = (temp and 0x0F) or 0x30 datasheet Soft_SPI_Write(temp) 280 ' Select DAC chip ' Store valueDAC[11..8] to temp[3..0] ' Define DAC setting, see MCP4921 ' Send high byte via Soft SPI MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 ' Send Low Byte temp = valueDAC Soft_SPI_Write(temp) Chip_Select = 1 end sub main: InitMain() Libraries ' Store valueDAC[7..0] to temp[7..0] ' Send low byte via Soft SPI ' Deselect DAC chip ' Perform main initialization value = 2048 ' When program starts, DAC gives ' the output in the mid-range while TRUE ' Endless loop if ((P0_0 = 0) and (value < 4095)) then ' If P0.0 is connected to GND Inc(value) ' increment value else if (( P0_1 = 0 ) and (value > 0)) then ' If P0.1 is connected to GND Dec(value) ' decrement value end if end if DAC_Output(value) Delay_ms(10) wend end. ' Perform output ' Slow down key repeat pace MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 281 CHAPTER 6 mikroBasic for 8051 Libraries SOFTWARE UART LIBRARY The mikroBasic for 8051 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. External dependencies of Software UART Library The following variable must be defined in all projects using RS-485 Library: dim Soft_Uart_RX as sbit external dim Soft_Uart_TX as sbit external Description: Receive line. Transmit line. Example : dim Soft_Uart_RX as sbit at P3.B0 dim Soft_Uart_TX as sbit at P3.B1 Library Routines - Soft_Uart_Init - Soft_Uart_Read - Soft_Uart_Write 282 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Soft_Uart_Init Prototype sub function Soft_Uart_Init(dim baud_rate as longword, dim inverted as byte) as word Returns Nothing. Configures and initializes the software UART module. Parameters : Description - baud_rate: baud rate to be set. Maximum baud rate depends on the MCU’s clock and working conditions. - inverted: inverted output flag. When set to a non-zero value, inverted logic on output is used. Global variables: Requires - Soft_Uart_RX receiver pin - Soft_Uart_TX transmiter pin must be defined before using this function. Example ' Initialize Software UART communication on pins Rx, Tx, at 9600 bps Soft_Uart_Init(9600, 0) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 283 CHAPTER 6 mikroBasic for 8051 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). Description Parameters : - error: Error flag. Error code is returned through this variable. Upon successful transfer this flag will be set to zero. An non zero value indicates communication error. Requires Example Software UART must be initialized before using this function. See the Soft_Uart_Init routine. dim data as byte error as byte ... ' wait until data is received do data = Soft_Uart_Read(error) loop until (error = 0) ' Now we can work with data: if (data) then ... end if 284 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Soft_Uart_Write Prototype sub procedure Soft_Uart_Write(dim 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. Requires Example Be aware that during transmission, software UART is incapable of receiving data – data transfer protocol must be set in such a way to prevent loss of information. dim some_byte as byte ... ' Write a byte via Soft Uart some_byte = 0x0A Soft_Uart_Write(some_byte) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 285 CHAPTER 6 mikroBasic for 8051 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 for 8051 USART Terminal Tool. program Soft_UART ' Soft UART connections dim Soft_Uart_RX as sbit at P3.B0 dim Soft_Uart_TX as sbit at P3.B1 ' End Soft UART connections dim i, error_, byte_read as byte main: Soft_Uart_Init(4800, 0) at 4800 bps for i = "A" to "z" step -1 downto "z" Soft_Uart_Write(i) Delay_ms(100) next i while TRUE byte_read = Soft_Uart_Read ( error_ ) error flag if (error_ <> 0) then ed P0 = 0xAA PORT0 else Soft_Uart_Write(byte_read) detected, return byte read end if wend end. 286 ' Auxiliary variables ' Initialize Soft UART ' Send bytes from "A" ' Endless loop ' Read byte, then test ' If error was detect' signal it on ' If error was not MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries SOUND LIBRARY The mikroBasic for 8051 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). External dependencies of Sound Library The following variables must be defined in all projects using Sound Library: Description: dim Sound_Play_Pin as Sound output pin. sbit external Example : dim Sound_Play_Pin as sbit at P0.B3 Library Routines - Sound_Init - Sound_Play Sound_Init Prototype sub procedure Sound_Init() Returns Nothing. Description Configures the appropriate MCU pin for sound generation. Requires Sound_Play_Pin variable must be defined before using this function. Example ' Initialize the pin P0.3 for playing sound dim Sound_Play_Pin as sbit at P0.B3 ... Sound_Init() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 287 CHAPTER 6 mikroBasic for 8051 Libraries Sound_Play Prototype sub procedure Sound_Play(dim byref freq_in_Hz as word, dim byref duration_ms as word) Returns Nothing. Generates the square wave signal on the appropriate pin. Description Parameters : - freq_in_Hz: signal frequency in Hertz (Hz) - duration_ms: signal duration in miliseconds (ms) Requires In order to hear the sound, you need a piezo speaker (or other hardware) on designated port. Also, you must call Sound_Init to prepare hardware for output before using this function. Example ' Play sound of 1KHz in duration of 100ms Sound_Play(1000, 100) 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 P0.B3 ' End Sound connections sub procedure Tone1() Sound_Play(500, 200) 200ms end sub sub procedure Tone2() Sound_Play(555, 200) 200ms end sub sub procedure Tone3() Sound_Play(625, 200) 200ms end sub 288 ' Frequency = 500Hz, Duration = ' Frequency = 555Hz, Duration = ' Frequency = 625Hz, Duration = MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 sub procedure Melody() "Yellow house" Tone1() Tone2() Tone3() Tone1() Tone2() Tone3() Tone1() Tone2() Tone3() Tone1() Tone2() Tone3() Tone1() Tone2() Tone3() Tone3() Tone3() Tone2() end sub sub procedure ToneA() sub function Sound_Play(1250, 20) end sub Libraries ' Plays the melody Tone3() Tone3() Tone3() Tone2() Tone1() ' Tones used in Melody2 sub procedure ToneC() Sound_Play(1450, 20) end sub sub procedure ToneE() Sound_Play(1650, 80) end sub sub procedure Melody2() dim i as byte i = 1 while (i < 9) ToneA() ToneC() ToneE() Inc(i) wend end sub main: P1 = 255 Sound_Init() Sound_Play(2000, 1000) ond while TRUE if (P1_7 = 0) then Tone1() while ( P1_7 = 0) nop wend end if ' Plays Melody2 ' Configure PORT1 as input ' Initialize sound pin ' Play starting sound, 2kHz, 1 sec' endless loop ' If P1.7 is pressed play Tone1 ' Wait for button to be released MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 289 CHAPTER 6 mikroBasic for 8051 Libraries if ( P1_6 = 0) then Tone2() while ( P1_6 = 0) nop wend end if if ( P1_5 = 0) then Tone3() while ( P1_5 = 0) nop wend end if if ( P1_4 = 0 ) then Melody2() while ( P1_4 = 0 ) nop wend end if if ( P1_3 = 0) then Melody() while ( P1_3 = 0 ) nop wend end if wend end. ' If P1.6 is pressed play Tone2 ' Wait for button to be released ' If P1.5 is pressed play Tone3 ' Wait for button to be released ' If P1.4 is pressed play Melody2 ' Wait for button to be released ' If P1.3 is pressed play Melody ' Wait for button to be released HW Connection Example of Sound Library sonnection 290 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries SPI LIBRARY mikroBasic for 8051 provides a library for comfortable with SPI work in Master mode. The 8051 MCU can easily communicate with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc. Library Routines - Spi_Init Spi_Init_Advanced Spi_Read Spi_Write Spi_Init Prototype sub procedure Spi_Init() Returns Nothing. This routine configures and enables SPI module with the following settings: Description - master mode clock idle low 8 bit data transfer most significant bit sent first serial output data changes on idle to active transition of clock state serial clock = fosc/128 (fosc/64 in x2 mode) Requires MCU must have SPI module. Example ' Initialize the SPI module with default settings Spi_Init() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 291 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Init_Advanced Prototype sub procedure Spi_Init_Advanced(dim adv_setting as byte) Returns Nothing. This routine configures and enables the SPI module with the user defined settings. Parameters : - adv_setting: SPI module configuration flags. Predefined library constants (see the table below) can be ORed to form appropriate configuration value. Bit Mask Description Predefined library const Master/slave [4] and clock rate select [1:0] bits 4, 1, 0 Description 0x10 Sck = Fosc/4 (Fosc/2 in x2 mode), Master mode MASTER_OSC_DIV4 0x11 Sck = Fosc/16 (f/8 in x2 mode), Master mode MASTER_OSC_DIV16 0x12 Sck = Fosc/64 (f/32 in x2 mode), MASTER_OSC_DIV64 Master mode 0x13 Sck = Fosc/128 (f/64 in x2 mode), Master mode MASTER_OSC_DIV128 SPI clock phase 2 Data changes on idle to active 0x00 transition of the clock IDLE_2_ACTIVE Data changes on active to idle transition of the clock ACTIVE_2_IDLE 0x04 SPI clock polarity 3 0x00 Clock idle level is low CLK_IDLE_LOW 0x08 Clock idle level is high CLK_IDLE_HIGH Data order 292 0x00 Most significant bit sent first DATA_ORDER_MSB 0x20 Least significant bit sent first DATA_ORDER_LSB Requires MCU must have SPI module. Example ' Set SPI to the Master Mode, clock = Fosc/4 , clock IDLE state low and data transmitted at low to high clock edge: Spi_Init_Advanced(MASTER_OSC_DIV4 or DATA_ORDER_MSB or CLK_IDLE_LOW or IDLE_2_ACTIVE) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Read Prototype sub function Spi_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 Spi_Init and Spi_Init_Advanced routines. Example ' read a byte from the SPI bus dim take, dummy1 as byte ... take = Spi_Read(dummy1) Spi_Write Prototype sub procedure Spi_Write(dim wrdata as byte) Returns Nothing. Writes byte via the SPI bus. Description Parameters : - wrdata: data to be sent Requires SPI module must be initialized before using this function. See Spi_Init and Spi_Init_Advanced routines. Example ' write a byte to the SPI bus dim buffer as byte ... Spi_Write(buffer) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 293 CHAPTER 6 mikroBasic for 8051 Libraries Library Example The code demonstrates how to use SPI library functions for communication between SPI module of the MCU and MAX7219 chip. MAX7219 controls eight 7 segment displays. program SPI ' Serial 7-seg Display connections dim CHIP_SEL as sbit at P1.B0 ' Chip Select pin definition ' End Serial 7-seg Display connections sub procedure Select_max() CHIP_SEL = 0 Delay_us(1) end sub ' Function for selecting MAX7219 sub procedure Deselect_max() Delay_us(1) CHIP_SEL = 1 end sub ' Function for deselecting MAX7219 sub procedure Max7219_init() ' Initializing MAX7219 Select_max() Spi_Write(0x09) ' BCD mode for digit decoding Spi_Write(0xFF) Deselect_max() Select_max() Spi_Write(0x0A) Spi_Write(0x0F) Deselect_max() Select_max() Spi_Write(0x0B) Spi_Write(0x07) Deselect_max() Select_max() Spi_Write(0x0C) Spi_Write(0x01) Deselect_max() Select_max() Spi_Write(0x00) Spi_Write(0xFF) Deselect_max() end sub 294 ' Segment luminosity intensity ' Display refresh ' Turn on the display ' No test MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries dim digit_position, digit_value as byte main: Spi_Init() ' Initialize SPI module, standard configuration ' Instead of SPI_init, you can use SPI_init_Advanced as shown below ' Spi_Init_Advanced(MASTER_OSC_DIV4 | DATA_ORDER_MSB | CLK_IDLE_LOW | IDLE_2_ACTIVE) Max7219_init() ' Initialize max7219 while TRUE ' Endless loop for digit_value = 0 to 9 for digit_position = 8 to 1 step -1 Select_max() ' Select max7219 Spi_Write(digit_position) ' Send digit position Spi_Write(digit_value) ' Send digit value Deselect_max() ' Deselect MAX7219 Delay_ms(300) next digit_position next digit_value wend end. HW Connection SPI HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 295 CHAPTER 6 mikroBasic for 8051 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. It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calculations. Communication with the host controller is implemented via two interrupt pins and the SPI, with data rates of up to 10 Mb/s. Two dedicated pins are used for LED link and network activity indication. This library is designed to simplify handling of the underlying hardware (ENC28J60). It works with any 8051 MCU with integrated SPI and more than 4 Kb ROM memory. SPI Ethernet library supports: - IPv4 protocol. - ARP requests. - ICMP echo requests. - UDP requests. - TCP requests (no stack, no packet reconstruction). - packet fragmentation is NOT supported. Note: The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines. Refer to Spi Library. 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 external sfr dim Spi_Ethernet_RST as sbit external sfr 296 Description: ENC28J60 chip select pin. ENC28J60 reset pin. Example : dim Spi_Ethernet_CS as sbit at P1.B1 sfr dim Spi_Ethernet_RST as sbit at P1.B0 sfr MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries The following routines must be defined in all project using SPI Ethernet Library: Description: sub function Spi_Ethernet_UserTCP(dim remoteHost as ^byte, dim remotePort as word, dim TCP request handler. Example : Refer to the library example at the bottom of this page localPort as word, dim for code implementation. reqLength as word) as word sub function Spi_Ethernet_UserUDP(dim remoteHost as ^byte, dim remotePort as word, dim destPort as word, dim reqLength as word) as word UDP request handler. Refer to the library example at the bottom of this page for code implementation. 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 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 297 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Ethernet_Init Prototype sub procedure Spi_Ethernet_Init(dim mac as ^byte, dim ip as ^byte, dim fullDuplex as byte) Returns Nothing. This is MAC module routine. It initializes ENC28J60 controller. This function is internaly splited into 2 parts to help linker when coming short of memory. ENC28J60 controller settings (parameters not mentioned here are set to default): Description - receive buffer start address : 0x0000. receive buffer end address : 0x19AD. transmit buffer start address: 0x19AE. transmit buffer end address : 0x1FFF. RAM buffer read/write pointers in auto-increment mode. receive filters set to default: CRC + MAC Unicast + MAC Broadcast in OR mode. flow control with TX and RX pause frames in full duplex mode. frames are padded to 60 bytes + CRC. maximum packet size is set to 1518. Back-to-Back Inter-Packet Gap: 0x15 in full duplex mode; 0x12 in half duplex mode. Non-Back-to-Back Inter-Packet Gap: 0x0012 in full duplex mode; 0x0C12 in half duplex mode. - Collision window is set to 63 in half duplex mode to accomodate some ENC28J60 revisions silicon bugs. - CLKOUT output is disabled to reduce EMI generation. - half duplex loopback disabled. - LED configuration: default (LEDA-link status, LEDB-link activity). Parameters: - 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). Requires The appropriate hardware SPI module must be previously initialized. const Spi_Ethernet_HALFDUPLEX = 0 const Spi_Ethernet_FULLDUPLEX = 1 Example 298 myMacAddr as myIpAddr as ... myMacAddr[0] myMacAddr[1] byte[6] ' my MAC address byte[4] ' my IP addr = 0x00 = 0x14 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries myMacAddr[2] = myMacAddr[3] myMacAddr[4] myMacAddr[5] Example myIpAddr[0] myIpAddr[1] myIpAddr[2] myIpAddr[3] 0xA5 = 0x76 = 0x19 = 0x3F = = = = 192 168 20 60 Spi_Init() Spi_Ethernet_Init(PORTC, 0, PORTC, 1, myMacAddr, myIpAddr, Spi_Ethernet_FULLDUPLEX) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 299 CHAPTER 6 mikroBasic for 8051 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. Therefore, more than one type of network traffic can be enabled at the same time. For this purpose, predefined library constants (see the table below) can be ORed to form appropriate input value. Parameters: - enFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network traffic/receive filter: Bit Mask Description Description Predefined library const 0 0x01 MAC Broadcast traffic/receive filter flag. When set, MAC broadcast traffic will be Spi_Ethernet_BROADCAST enabled. 1 0x02 MAC Multicast traffic/receive filter flag. When set, MAC multicast traffic will be enabled. 2 0x04 not used none 3 0x08 not used none 4 0x10 not used none 5 0x20 CRC check flag. When set, packets with invalid CRC field will be discarded. 6 0x40 not used 7 0x80 Spi_Ethernet_MULTICAST Spi_Ethernet_CRC none MAC Unicast traffic/receive filter flag. When Spi_Ethernet_UNICAST set, MAC unicast traffic will be enabled. 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. It will not, in any way, mess with enabling/disabling receive/transmit logic or any other part of the ENC28J60 module. The ENC28J60 module should be properly cofigured by the means of Spi_Ethernet_Init routine. 300 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example Spi_Ethernet_Enable(Spi_Ethernet_CRC or Spi_Ethernet_UNICAST) ' enable CRC checking and Unicast traffic Spi_Ethernet_Disable Prototype sub procedure Spi_Ethernet_Disable(dim disFlt as byte) Returns Nothing. This is MAC module routine. This routine disables appropriate network traffic on the ENC28J60 module by the means of it's receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic will be disabled if a corresponding bit of this routine's input parameter is set. Therefore, more than one type of network traffic can be disabled at the same time. For this purpose, predefined library constants (see the table below) can be ORed to form appropriate input value. Parameters: - disFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network traffic/receive filter: Bit Mask Description Predefined library const 0 0x01 MAC Broadcast traffic/receive filter flag. When set, MAC broadcast traffic will be Spi_Ethernet_BROADCAST disabled. 1 0x02 MAC Multicast traffic/receive filter flag. When set, MAC multicast traffic will be disabled. 2 0x04 not used none 3 0x08 not used none 4 0x10 not used none 5 0x20 6 0x40 7 0x80 Description Spi_Ethernet_MULTICAST CRC check flag. When set, CRC check will be disabled and packets with invalid CRC Spi_Ethernet_CRC field will be accepted. not used none MAC Unicast traffic/receive filter flag. When Spi_Ethernet_UNICAST set, MAC unicast traffic will be disabled. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 301 CHAPTER 6 mikroBasic for 8051 Libraries Note: Advance filtering available in the ENC28J60 module such as Pattern Match, Magic Packet and Hash Table can not be disabled by this routine. Description Note: This routine will change receive filter configuration on-the-fly. It will not, in any way, mess with enabling/disabling receive/transmit logic or any other part of the ENC28J60 module. The ENC28J60 module should be properly cofigured by the means of Spi_Ethernet_Init routine. Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example Spi_Ethernet_Disable(Spi_Ethernet_CRC or Spi_Ethernet_UNICAST) ' disable CRC checking and Unicast traffic 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. - 4 - received packet was of type unknown to the library. This is MAC module routine. It processes next received packet if such exists. Packets are processed in the following manner: - ARP & ICMP requests are replied automatically. - upon TCP request the Spi_Ethernet_UserTCP function is called for further Description processing. - upon UDP request the Spi_Ethernet_UserUDP function is called for further processing. Note: Spi_Ethernet_doPacket must be called as often as possible in user's code. 302 Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example while TRUE ... Spi_Ethernet_doPacket() ' process received packets ... wend MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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 ... Spi_Ethernet_putByte(data) ' put an byte into ENC28J60 buffer Spi_Ethernet_putBytes Prototype sub procedure Spi_Ethernet_putBytes(dim ptr as ^byte, dim n as byte) Returns Nothing. This is MAC module routine. It stores requested number of bytes into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location. Description Parameters: - ptr: RAM buffer containing bytes to be written into ENC28J60 RAM. - n: number of bytes to be written. Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example dim buffer as byte[17] ... buffer = "mikroElektronika" ... Spi_Ethernet_putBytes(buffer, 16) ' put an RAM array into ENC28J60 buffer MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 303 CHAPTER 6 mikroBasic for 8051 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. See Spi_Ethernet_Init. Example const buffer as byte[17] ... buffer = "mikroElektronika" ... Spi_Ethernet_putConstBytes(buffer, 16) ' put a const array into ENC28J60 buffer Spi_Ethernet_putString Prototype sub function Spi_Ethernet_putString(dim ptr as ^byte) as word Returns Number of bytes written into ENC28J60 RAM. This is MAC module routine. It stores whole string (excluding null termination) into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location. Description Parameters: - ptr: string to be written into ENC28J60 RAM. 304 Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example dim buffer as string[16] ... buffer = "mikroElektronika" ... Spi_Ethernet_putString(buffer) ' put a RAM string into ENC28J60 buffer MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. See Spi_Ethernet_Init. Example const buffer as string[16] ... buffer = "mikroElektronika" ... Spi_Ethernet_putConstString(buffer) ' put a const string into ENC28J60 buffer Spi_Ethernet_getByte Prototype sub function Spi_Ethernet_getByte() as byte Returns Byte read from ENC28J60 RAM. Description This is MAC module routine. It fetches a byte from address pointed to by current ENC28J60 read pointer (ERDPT). Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example dim buffer as byte<> ... buffer = Spi_Ethernet_getByte() ' read a byte from ENC28J60 buffer MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 305 CHAPTER 6 mikroBasic for 8051 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. - addr: ENC28J60 RAM start address. Valid values: 0..8192. - n: number of bytes to be read. 306 Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example dim buffer as byte[16] ... Spi_Ethernet_getBytes(buffer, 0x100, 16) ' read 16 bytes, starting from address 0x100 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 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. The user puts data in the transmit buffer by using some of the Spi_Ethernet_put routines. The function must return the length in bytes of the TCP/HTTP reply, or 0 if there is nothing to transmit. If there is no need to reply to the TCP/HTTP requests, just define this function with return(0) as a single statement. Description Parameters: - remoteHost: client's IP address. remotePort: client's TCP port. localPort: port to which the request is sent. reqLength: TCP/HTTP request data field length. Note: The function source code is provided with appropriate example projects. The code should be adjusted by the user to achieve desired reply. Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example This function is internally called by the library and should not be called by the user's code. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 307 CHAPTER 6 mikroBasic for 8051 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. The user puts data in the transmit buffer by using some of the Spi_Ethernet_put routines. The function must return the length in bytes of the UDP reply, or 0 if nothing to transmit. If you don't need to reply to the UDP requests, just define this function with a return(0) as single statement. Description Parameters: - remoteHost: client's IP address. remotePort: client's port. destPort: port to which the request is sent. reqLength: UDP request data field length. Note: The function source code is provided with appropriate example projects. The code should be adjusted by the user to achieve desired reply. Requires Ethernet module has to be initialized. See Spi_Ethernet_Init. Example This function is internally called by the library and should not be called by the user's code. Library Example This code shows how to use the 8051 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.b7 bit and return HTML main page all other requests return also HTML main page. 308 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 // duplex config flags #define Spi_Ethernet_HALFDUPLEX #define Spi_Ethernet_FULLDUPLEX Libraries 0x00 0x01 // half duplex // full duplex // mE ehternet NIC pinout sfr sbit Spi_Ethernet_RST at P1.B0; sfr sbit Spi_Ethernet_CS at P1.B1; // end ethernet NIC definitions /************************************************************ * ROM constant strings */ const code byte httpHeader[] = "HTTP/1.1 200 OK\nContent-type: " ; // HTTP header const code byte httpMimeTypeHTML[] = "text/html\n\n" ; // HTML MIME type const code byte httpMimeTypeScript[] = "text/plain\n\n" ; // TEXT MIME type idata byte httpMethod[] = "GET /"; /* * web page, splited into 2 parts : * when coming short of ROM, fragmented data is handled more efficiently by linker * * this HTML page calls the boards to get its status, and builds itself with javascript */ const code char *indexPage = // Change the IP address of the page to be refreshed "<meta http-equiv=\"refresh\" content=\"3;url=http://192.168.1.60\">\ <HTML><HEAD></HEAD><BODY>\ <h1>8051 + ENC28J60 Mini Web Server</h1>\ <a href=/>Reload</a>\ <script src=/s></script>\ <table><tr><td><table border=1 style=\"font-size:20px ;font-family: terminal ;\">\ <tr><th colspan=2>P0</th></tr>\ <script>\ var str,i;\ str=\"\";\ for(i=0;i<8;i++)\ {str+=\"<tr><td bgcolor=pink>BUTTON #\"+i+\"</td>\";\ if(P0&(1<<i)){str+=\"<td bgcolor=red>ON\";}\ else {str+=\"<td bgcolor=#cccccc>OFF\";}\ str+=\"</td></tr>\";}\ document.write(str) ;\ </script>\ " ; MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 309 CHAPTER 6 mikroBasic for 8051 Libraries const char *indexPage2 = "</table></td><td>\ <table border=1 style=\"font-size:20px ;font-family: terminal ;\">\ <tr><th colspan=3>P3</th></tr>\ <script>\ var str,i;\ str=\"\";\ for(i=0;i<8;i++)\ {str+=\"<tr><td bgcolor=yellow>LED #\"+i+\"</td>\";\ if(P3&(1<<i)){str+=\"<td bgcolor=red>ON\";}\ else {str+=\"<td bgcolor=#cccccc>OFF\";}\ str+=\"</td><td><a href=/t\"+i+\">Toggle</a></td></tr>\";}\ document.write(str) ;\ </script>\ </table></td></tr></table>\ This is HTTP request #<script>document.write(REQ)</script></BODY></HTML>\ " ; /*********************************** * RAM variables */ idata byte myMacAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f} ; // my MAC address idata byte myIpAddr[4] = {192, 168, 1, 60} ; // my IP address idata byte getRequest[15] ; // HTTP request buffer idata byte dyna[29] ; // buffer for dynamic response idata unsigned long httpCounter = 0 ; // counter of HTTP requests /******************************************* * functions */ /* * put the constant string pointed to by s to the ENC transmit buffer. */ /*unsigned int putConstString(const code char *s) { unsigned int ctr = 0 ; while(*s) { Spi_Ethernet_putByte(*s++) ; ctr++ ; } return(ctr) ; }*/ 310 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries /* * it will be much faster to use library Spi_Ethernet_putConstString routine * instead of putConstString routine above. However, the code will be a little * bit bigger. User should choose between size and speed and pick the implementation that * suites him best. If you choose to go with the putConstString definition above * the #define line below should be commented out. * */ #define putConstString Spi_Ethernet_putConstString /* * put the string pointed to by s to the ENC transmit buffer */ /*unsigned int putString(char *s) { unsigned int ctr = 0 ; while(*s) { Spi_Ethernet_putByte(*s++) ; ctr++ ; } return(ctr) ; }*/ /* * it will be much faster to use library Spi_Ethernet_putString routine * instead of putString routine above. However, the code will be a little * bit bigger. User should choose between size and speed and pick the implementation that * suites him best. If you choose to go with the putString definition above * the #define line below should be commented out. * */ #define putString Spi_Ethernet_putString /* * this function is called by the library * the user accesses to the HTTP request by successive calls to Spi_Ethernet_getByte() * the user puts data in the transmit buffer by successive calls to Spi_Ethernet_putByte() * the function must return the length in bytes of the HTTP reply, or 0 if nothing to transmit * * if you don't need to reply to HTTP requests, * just define this function with a return(0) as single statement * */ MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 311 CHAPTER 6 mikroBasic for 8051 Libraries unsigned int Spi_Ethernet_UserTCP(byte *remoteHost, unsigned int remotePort, unsigned int localPort, unsigned int reqLength) { idata unsigned int len; // my reply length if(localPort != 80) only to web request on port 80 { return(0) ; } // I listen // get 10 first bytes only of the request, the rest does not matter here for(len = 0 ; len < 10 ; len++) { getRequest[len] = Spi_Ethernet_getByte() ; } getRequest[len] = 0 ; len = 0; if(memcmp(getRequest, httpMethod, 5)) method is supported here { return(0) ; } // only GET httpCounter++ ; request done // one more if(getRequest[5] == 's') // if request path name starts with s, store dynamic data in transmit buffer { // the text string replied by this request can be interpreted as javascript statements // by browsers len = putConstString(httpHeader) ; // HTTP header len += putConstString(httpMimeTypeScript) ; with text MIME type // // add P3 value (buttons) to reply len += putConstString("var P3=") ; WordToStr(P3, dyna) ; len += putString(dyna) ; len += putConstString(";") ; 312 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries // add P0 value (LEDs) to reply len += putConstString("var P0=") ; WordToStr(P0, dyna) ; len += putString(dyna) ; len += putConstString(";") ; // add HTTP requests counter to reply WordToStr(httpCounter, dyna) ; len += putConstString("var REQ=") ; len += putString(dyna) ; len += putConstString(";") ; } else if(getRequest[5] == 't') // if request path name starts with t, toggle P3 (LED) bit number that comes after { byte bitMask = 0 ; // for bit mask if(isdigit(getRequest[6])) // if 0 <= bit number <= 9, bits 8 & 9 does not exist but does not matter { bitMask = getRequest[6] - '0' ; // convert ASCII to integer bitMask = 1 << bitMask ; // create bit mask P3 ^= bitMask ; // toggle P3 with xor operator } } if(len == 0) what do to by default { len = HTTP header len += with HTML MIME type len += HTML page first part len += HTML page second part } // putConstString(httpHeader) ; // putConstString(httpMimeTypeHTML) ; // putConstString(indexPage) ; // putConstString(indexPage2) ; // return(len) ; return to the library with the number of bytes to transmit } MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD // 313 CHAPTER 6 mikroBasic for 8051 Libraries /* * this function is called by the library * the user accesses to the UDP request by successive calls to Spi_Ethernet_getByte() * the user puts data in the transmit buffer by successive calls to Spi_Ethernet_putByte() * the function must return the length in bytes of the UDP reply, or 0 if nothing to transmit * * if you don't need to reply to UDP requests, * just define this function with a return(0) as single statement * */ unsigned int Spi_Ethernet_UserUDP(byte *remoteHost, unsigned int remotePort, unsigned int destPort, unsigned int reqLength) { idata unsigned int len ; // my reply length idata byte * ptr ; // pointer to the dynamic buffer // reply is made of the remote host IP address in human readable format ByteToStr(remoteHost[0], dyna) ; // first IP address byte dyna[3] = '.' ; ByteToStr(remoteHost[1], dyna + 4) ; // second dyna[7] = '.' ; ByteToStr(remoteHost[2], dyna + 8) ; // third dyna[11] = '.' ; ByteToStr(remoteHost[3], dyna + 12) ; // fourth dyna[15] = ':' ; // add separator // then remote host port number WordToStr(remotePort, dyna + 16) ; dyna[21] = '[' ; WordToStr(destPort, dyna + 22) ; dyna[27] = ']' ; dyna[28] = 0 ; // the total length of the request is the length of the dynamic string plus the text of the request len = 28 + reqLength; // puts the dynamic string into the transmit buffer Spi_Ethernet_putBytes(dyna, 28) ; 314 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries // then puts the request string converted into upper char into the transmit buffer while(reqLength--) { Spi_Ethernet_putByte(toupper(Spi_Ethernet_getByte())) ; } return(len) ; length of the UDP reply } // back to the library with the /* * main entry */ procedure main() { /* * starts ENC28J60 with : * reset bit on P1_0 * CS bit on P1_1 * my MAC & IP address * full duplex */ Spi_Init_Advanced(MASTER_OSC_DIV16 | CLK_IDLE_LOW | IDLE_2_ACTIVE | DATA_ORDER_MSB); Spi_Ethernet_Init(myMacAddr, myIpAddr, Spi_Ethernet_FULLDUPLEX) ; // full duplex, CRC + MAC Unicast + MAC Broadcast filtering while(1) // do forever { /* * if necessary, test the return value to get error code */ Spi_Ethernet_doPacket() ; // process incoming Ethernet packets /* * add your stuff here if needed * Spi_Ethernet_doPacket() must be called as often as possible * otherwise packets could be lost */ } } MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 315 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection 316 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries SPI GRAPHIC LCD LIBRARY The mikroBasic for 8051 provides a library for operating Graphic LCD 128x64 (with commonly used Samsung KS108/KS107 controller) via SPI interface. For creating a custom set of GLCD images use GLCD Bitmap Editor Tool. Note: The library uses the SPI module for communication. User must initialize SPI module before using the SPI Graphic LCD Library. Note: This Library is designed to work with the mikroElektronika's Serial LCD/GLCD Adapter Board pinout, see schematic at the bottom of this page for details. External dependencies of SPI Graphic LCD Library The implementation of SPI Graphic LCD Library routines is based on Port Expander Library routines. External dependencies are the same as Port Expander Library external dependencies. Library Routines Basic routines: - Spi_Glcd_Init Spi_Glcd_Set_Side Spi_Glcd_Set_Page Spi_Glcd_Set_X Spi_Glcd_Read_Data Spi_Glcd_Write_Data Advanced routines: - Spi_Glcd_Fill Spi_Glcd_Dot Spi_Glcd_Line Spi_Glcd_V_Line Spi_Glcd_H_Line Spi_Glcd_Rectangle Spi_Glcd_Box Spi_Glcd_Circle Spi_Glcd_Set_Font Spi_Glcd_Write_Char Spi_Glcd_Write_Text Spi_Glcd_Image MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 317 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Init Prototype sub procedure Spi_Glcd_Init(dim DeviceAddress as byte) Returns Nothing. Initializes the GLCD module via SPI interface. Description Parameters : - DeviceAddress: spi expander hardware address, see schematic at the bottom of this page SPExpanderCS and SPExpanderRST variables must be defined before using this function. Requires The SPI module needs to be initialized. See Spi_Init and Spi_Init_Advanced routines. Example 318 ' port expander pinout definition dim SPExpanderRST as sbit at P1.B0 SPExpanderCS as sbit at P1.B1 ... Spi_Init_Advanced(MASTER_OSC_DIV4 or CLK_IDLE_LOW or IDLE_2_ACTIVE or DATA_ORDER_MSB) Spi_Glcd_Init(0) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Set_Side Prototype sub procedure SPI_Glcd_Set_Side(dim x_pos as byte) Returns Nothing. Selects GLCD side. Refer to the GLCD datasheet for detail explanation. 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. Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. The following two lines are equivalent, and both of them select the left side of GLCD: Example SPI_Glcd_Set_Side(0) SPI_Glcd_Set_Side(10) Spi_Glcd_Set_Page Prototype sub procedure Spi_Glcd_Set_Page(dim page as byte) Returns Nothing. Selects page of 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 for SPI communication, see Spi_Glcd_Init routines. Example Spi_Glcd_Set_Page(5) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 319 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Set_X Prototype sub procedure SPI_Glcd_Set_X(dim x_pos as byte) Returns Nothing. Sets x-axis position to x_pos dots from the left border of GLCD within the selected side. Parameters : Description - x_pos: position on x-axis. Valid values: 0..63 Note: For side, x axis and page layout explanation see schematic at the bottom of this page. Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example Spi_Glcd_Set_X(25) Spi_Glcd_Read_Data Prototype sub function Spi_Glcd_Read_Data() as byte Returns One byte from GLCD memory. Description Reads data from the current location of GLCD memory and moves to the next location. GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Requires Example 320 GLCD side, x-axis position and page should be set first. See the functions Spi_Glcd_Set_Side, Spi_Glcd_Set_X, and Spi_Glcd_Set_Page. dim data as byte ... data = Spi_Glcd_Read_Data() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Write_Data Prototype sub procedure Spi_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 for SPI communication, see Spi_Glcd_Init routines. Requires Example GLCD side, x-axis position and page should be set first. See the functions Spi_Glcd_Set_Side, Spi_Glcd_Set_X, and Spi_Glcd_Set_Page. dim ddata as byte ... Spi_Glcd_Write_Data(ddata) Spi_Glcd_Fill Prototype sub procedure Spi_Glcd_Fill(dim pattern as byte) Returns Nothing. Fills GLCD memory with byte pattern. Parameters : Description - pattern: byte to fill GLCD memory with To clear the GLCD screen, use Spi_Glcd_Fill(0). To fill the screen completely, use Spi_Glcd_Fill(0xFF). Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Clear screen Spi_Glcd_Fill(0) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 321 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Dot Prototype sub procedure Spi_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 - color: colx_pos as byte; page_num as byte; color as byte) Description or parameter. Valid values: 0..2 The parameter color determines the dot state: 0 clears dot, 1 puts a dot, and 2 inverts dot state. Note: For x and y axis layout explanation see schematic at the bottom of this page. 322 Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Invert the dot in the upper left corner Spi_Glcd_Dot(0, 0, 2) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Line Prototype sub procedure SPI_Glcd_Line(dim x_start as integer, dim y_start as integer, dim x_end as integer, dim y_end as integer, dim color as byte) Returns Nothing. Draws a line on GLCD. Parameters : Description - x_start: x coordinate of the line start. Valid values: 0..127 y_start: y coordinate of the line start. Valid values: 0..63 x_end: x coordinate of the line end. Valid values: 0..127 y_end: y coordinate of the line end. Valid values: 0..63 color: color parameter. Valid values: 0..2 Parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Draw a line between dots (0,0) and (20,30) Spi_Glcd_Line(0, 0, 20, 30, 1) Spi_Glcd_V_Line Prototype sub procedure Spi_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..2 Parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Draw a vertical line between dots (10,5) and (10,25) Spi_Glcd_V_Line(5, 25, 10, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 323 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_H_Line Prototype sub procedure Spi_Glcd_V_Line(dim x_start as byte, dim x_end as byte, dim y_pos as byte, dim color as byte) Returns Nothing. Draws a horizontal line on GLCD. Parameters : Description - x_start: x coordinate of the line start. Valid values: 0..127 x_end: x coordinate of the line end. Valid values: 0..127 y_pos: y coordinate of horizontal line. Valid values: 0..63 color: color parameter. Valid values: 0..2 The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. 324 Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Draw a horizontal line between dots (10,20) and (50,20) Spi_Glcd_H_Line(10, 50, 20, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Rectangle Prototype sub procedure Spi_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..63 - x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: Description 0..127 - y_bottom_right: y coordinate of the lower right rectangle corner. Valid values: 0..63 - color: color parameter. Valid values: 0..2 The parameter color determines the color of the rectangle border: 0 white, 1 black, and 2 inverts each dot. Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Draw a rectangle between dots (5,5) and (40,40) Spi_Glcd_Rectangle(5, 5, 40, 40, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 325 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Box Prototype sub procedure Spi_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 : Description - x_upper_left: x coordinate of the upper left box corner. Valid values: 0..127 y_upper_left: y coordinate of the upper left box corner. Valid values: 0..63 x_bottom_right: x coordinate of the lower right box corner. Valid values: 0..127 y_bottom_right: y coordinate of the lower right box corner. Valid values: 0..63 color: color parameter. Valid values: 0..2 The parameter color determines the color of the box fill: 0 white, 1 black, and 2 inverts each dot. Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Draw a box between dots (5,15) and (20,40) Spi_Glcd_Box(5, 15, 20, 40, 1) Spi_Glcd_Circle Prototype sub procedure Spi_Glcd_Circle(dim x_center as integer, dim y_center as integer, dim radius as integer, dim color as byte) Returns Nothing. Draws a circle on GLCD. Parameters : Description - x_center: x coordinate of the circle center. Valid values: 0..127 y_center: y coordinate of the circle center. Valid values: 0..63 radius: radius size color: color parameter. Valid values: 0..2 The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot. 326 Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routine. Example ' Draw a circle with center in (50,50) and radius=10 Spi_Glcd_Circle(50, 50, 10, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Set_Font Prototype sub procedure SPI_Glcd_Set_Font(dim const activeFont as ^byte, dim aFontWidth as byte, dim aFontHeight as byte, dim aFontOffs as word) Returns Nothing. Sets font that will be used with Spi_Glcd_Write_Char and Spi_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. aFontOffs: number that represents difference between the mikroBasic charac- ter set and regular ASCII set (eg. if 'A' is 65 in ASCII character, and 'A' is 45 in the mikroBasic character set, aFontOffs is 20). Demo fonts supplied with the library have an offset of 32, which means that they start with space. The user can use fonts given in the file “__Lib_GLCD_fonts.mpas” file located in the Uses folder or create his own fonts. Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Use the custom 5x7 font "myfont" which starts with space (32): Spi_Glcd_Set_Font(myfont, 5, 7, 32) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 327 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Write_Char Prototype sub procedure SPI_Glcd_Write_Char(dim chr1 as byte, dim x_pos as byte, dim page_num as byte, dim color as byte) Returns Nothing. Prints character on GLCD. Parameters : - chr1: 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..2 The parameter color determines the color of the character: 0 white, 1 black, and 2 inverts each dot. Note: For x axis and page layout explanation see schematic at the bottom of this page. GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Requires Example 328 Use the Spi_Glcd_Set_Font to specify the font for display; if no font is specified, then the default 5x8 font supplied with the library will be used. ' Write character 'C' on the position 10 inside the page 2: Spi_Glcd_Write_Char("C", 10, 2, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Write_Text Prototype sub procedure SPI_Glcd_Write_Text(dim byref text as string[20], dim x_pos as byte, dim page_numb as byte, dim color as byte) Returns Nothing. Prints text on GLCD. Parameters : Description - text: text to be written x_pos: text starting position on x-axis. page_num: the number of the page on which text will be written. Valid values: 0..7 color: color parameter. Valid values: 0..2 The parameter color determines the color of the text: 0 white, 1 black, and 2 inverts each dot. Note: For x axis and page layout explanation see schematic at the bottom of this page. GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Requires Example Use the Spi_Glcd_Set_Font to specify the font for display; if no font is specified, then the default 5x8 font supplied with the library will be used. ' Write text "Hello world!" on the position 10 inside the page 2: Spi_Glcd_Write_Text("Hello world!", 10, 2, 1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 329 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Glcd_Image Prototype sub procedure Spi_Glcd_Image(dim const image as ^byte) Returns Nothing. Displays bitmap on GLCD. Parameters : Description - image: image to be displayed. Bitmap array can be located in both code and RAM memory (due to the mikroBasic for 8051 pointer to const and pointer to RAM equivalency). Use the mikroBasic’s integrated GLCD Bitmap Editor (menu option Tools › GLCD Bitmap Editor) to convert image to a constant array suitable for displaying on GLCD. Requires GLCD needs to be initialized for SPI communication, see Spi_Glcd_Init routines. Example ' Draw image my_image on GLCD Spi_Glcd_Image(my_image) Library Example The example demonstrates how to communicate to KS0108 GLCD via the SPI module, using serial to parallel convertor MCP23S17. program SPI_Glcd include bitmap ' Port Expander module connections dim SPExpanderRST as sbit at P1.B0 dim SPExpanderCS as sbit at P1.B1 ' End Port Expander module connections dim counter, counter2 as byte jj as word someText as string[20] sub procedure delay2S Delay_ms(2000) end sub main: Spi_Init_Advanced(MASTER_OSC_DIV4 DATA_ORDER_MSB) Spi_Glcd_Init(0) Spi_Glcd_Fill(0x00) 330 or CLK_IDLE_LOW or IDLE_2_ACTIVE or ' Initialize GLCD via SPI ' Clear GLCD MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries while TRUE Spi_Glcd_Image(@truck_bmp) Delay2S() Delay2S() Spi_Glcd_Fill(0x0) Delay2S Spi_Glcd_Box(62,40,124,56,1) Spi_Glcd_Rectangle(5,5,84,35,1) Spi_Glcd_Line(0, 63, 127, 0,1) Delay2S() counter = 5 and vertical line while counter < 60 Delay_ms(250) Spi_Glcd_V_Line(2, 54, counter, 1) Spi_Glcd_H_Line(2, 120, counter, 1) counter = counter + 5 wend ' Draw image ' Draw box ' Draw rectangle ' Draw line ' Draw horizontal Delay2S() Spi_Glcd_Fill(0x00) Spi_Glcd_Set_Font(@Character8x8, 8, 8, 32) Spi_Glcd_Write_Text("mikroE", 5, 7, 2) for counter2 = 1 to 10 Spi_Glcd_Circle(63,32, 3*counter2, 1) next counter2 Delay2S() ' Choose font ' Write string ' Draw circles Spi_Glcd_Box(12,20, 70,63, 2) Delay2S() ' Draw box Spi_Glcd_Set_Font(@FontSystem5x8, 5, 8, 32) someText = "Hello 8051" Spi_Glcd_Write_Text(someText, 5, 3, 0) Delay2S() ' Change font Spi_Glcd_Set_Font(@System3x6, 3, 6, 32) someText = "SMALL:NOT:SMALLER" Spi_Glcd_Write_Text(someText, 20,5, 1) Delay2S() wend end. ' Write string ' Write string MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 331 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection SPI GLCD HW connection 332 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries SPI LCD LIBRARY The mikroBasic for 8051 provides a library for communication with LCD (with HD44780 compliant controllers) in 4-bit mode via SPI interface. For creating a custom set of LCD characters use LCD Custom Character Tool. Note: The library uses the SPI module for communication. The user must initialize the SPI module before using the SPI LCD Library. Note: This Library is designed to work with the mikroElektronika's Serial LCD Adapter Board pinout. See schematic at the bottom of this page for details. External dependencies of SPI LCD Library The implementation of SPI LCD Library routines is based on Port Expander Library routines. External dependencies are the same as Port Expander Library external dependencies. Library Routines - Spi_Lcd_Config Spi_Lcd_Out Spi_Lcd_Out_Cp Spi_Lcd_Chr Spi_Lcd_Chr_Cp Spi_Lcd_Cmd MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 333 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Lcd_Config Prototype sub procedure Spi_Lcd_Config(dim DeviceAddress as byte) Returns Nothing. Initializes the LCD module via SPI interface. Description Parameters : - DeviceAddress: spi expander hardware address, see schematic at the bottom of this page SPExpanderCS and SPExpanderRST variables must be defined before using this function. Requires The SPI module needs to be initialized. See Spi_Init and Spi_Init_Advanced routines. Example ' port expander pinout definition dim SPExpanderCS as sbit at P1.B1 SPExpanderRST as sbit at P1.B0 ... Spi_Init() ' initialize spi Spi_Lcd_Config(0) ' initialize lcd over spi interface Spi_Lcd_Out Prototype sub procedure Spi_Lcd_Out(dim row as byte, dim column as byte, dim byref text as string[19]) Returns Nothing. Prints text on the 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 334 Requires LCD needs to be initialized for SPI communication, see Spi_Lcd_Config routines. Example ' Write text "Hello!" on LCD starting from row 1, column 3: Spi_Lcd_Out(1, 3, "Hello!") MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Lcd_Out_Cp Prototype sub procedure Spi_Lcd_Out_CP(dim text as string[19]) Returns Nothing. Prints text on the LCD at current cursor position. Both string variables and literals can be passed as a text. Description Parameters : - text: text to be written Requires LCD needs to be initialized for SPI communication, see Spi_Lcd_Config routines. Example ' Write text "Here!" at current cursor position: Spi_Lcd_Out_CP("Here!") Spi_Lcd_Chr Prototype sub procedure Spi_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 character. Description Parameters : - Row: writing position row number - Column: writing position column number - Out_Char: character to be written Requires LCD needs to be initialized for SPI communication, see Spi_Lcd_Config routines. Example ' Write character "i" at row 2, column 3: Spi_Lcd_Chr(2, 3, 'i') MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 335 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Lcd_Chr_Cp Prototype sub procedure Spi_Lcd_Chr_CP(dim Out_Char as byte) Returns Nothing. Prints character on LCD at current cursor position. Both variables and literals can be passed as character. Description Parameters : - Out_Char: character to be written Requires LCD needs to be initialized for SPI communication, see Spi_Lcd_Config routines. Example ' Write character "e" at current cursor position: Spi_Lcd_Chr_Cp('e') Spi_Lcd_Cmd Prototype sub procedure Spi_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 LCD Commands. 336 Requires LCD needs to be initialized for SPI communication, see Spi_Lcd_Config routines. Example ' Clear LCD display: Spi_Lcd_Cmd(LCD_CLEAR) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Available LCD Commands Lcd Command Purpose LCD_FIRST_ROW Move cursor to the 1st row LCD_SECOND_ROW Move cursor to the 2nd row LCD_THIRD_ROW Move cursor to the 3rd row LCD_FOURTH_ROW Move cursor to the 4th row LCD_CLEAR Clear display LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display data RAM is unaffected. LCD_CURSOR_OFF Turn off cursor LCD_UNDERLINE_ON Underline cursor on LCD_BLINK_CURSOR_ON Blink cursor on LCD_MOVE_CURSOR_LEFT Move cursor left without changing display data RAM LCD_MOVE_CURSOR_RIGHT Move cursor right without changing display data RAM LCD_TURN_ON Turn LCD display on LCD_TURN_OFF Turn LCD display off LCD_SHIFT_LEFT Shift display left without changing display data RAM LCD_SHIFT_RIGHT Shift display right without changing display data RAM MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 337 CHAPTER 6 mikroBasic for 8051 Libraries Library Example This example demonstrates how to communicate LCD via the SPI module, using serial to parallel convertor MCP23S17. program Spi_LCD dim text as char[17] ' Port Expander module connections dim SPExpanderRST as sbit at P1.B0 dim SPExpanderCS as sbit at P1.B1 ' End Port Expander module connections main: text = "mikroElektronika" Spi_Init() ' Initialize SPI Spi_Lcd_Config(0) ' Initialize LCD over SPI interface Spi_Lcd_Cmd(LCD_CLEAR) ' Clear display Spi_Lcd_Cmd(LCD_CURSOR_OFF) ' Turn cursor off Spi_Lcd_Out(1,6, "mikroE")' Print text to LCD, 1st row, 6th column Spi_Lcd_Chr_CP("!") ' Append "!" Spi_Lcd_Out(2,1, text) ' Print text to LCD, 2nd row, 1st column Spi_Lcd_Out(3,1,"mikroE") ' For LCD with more than two rows Spi_Lcd_Out(4,15,"mikroE") ' For LCD with more than two rows end. 338 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries HW Connection SPI LCD HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 339 CHAPTER 6 mikroBasic for 8051 Libraries SPI LCD8 (8-BIT INTERFACE) LIBRARY The mikroBasic for 8051 provides a library for communication with LCD (with HD44780 compliant controllers) in 8-bit mode via SPI interface. For creating a custom set of LCD characters use LCD Custom Character Tool. Note: Library uses the SPI module for communication. The user must initialize the SPI module before using the SPI LCD Library. Note: This Library is designed to work with mikroElektronika's Serial LCD/GLCD Adapter Board pinout, see schematic at the bottom of this page for details. External dependencies of SPI LCD Library The implementation of SPI LCD Library routines is based on Port Expander Library routines. External dependencies are the same as Port Expander Library external dependencies. Library Routines - 340 Spi_Lcd8_Config Spi_Lcd8_Out Spi_Lcd8_Out_Cp Spi_Lcd8_Chr Spi_Lcd8_Chr_Cp Spi_Lcd8_Cmd MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Lcd8_Config Prototype sub procedure Spi_Lcd8_Config(dim DeviceAddress as byte) Returns Nothing. Initializes the LCD module via SPI interface. Description Parameters : - DeviceAddress: spi expander hardware address, see schematic at the bottom of this page SPExpanderCS and SPExpanderRST variables must be defined before using this function. Requires The SPI module needs to be initialized. See Spi_Init and Spi_Init_Advanced routines. Example ' port expander pinout definition dim SPExpanderCS as sbit at P1.B1 SPExpanderRST as sbit at P1.B0 ... Spi_Init() ' initialize spi interface Spi_Lcd8_Config(0) ' intialize lcd in 8bit mode via spi Spi_Lcd8_Out Prototype sub procedure Spi_Lcd8_Out(dim row as byte, dim column as byte, dim byref text as string[19]) 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 LCD needs to be initialized for SPI communication, see Spi_Lcd8_Config routines. Example ' Write text "Hello!" on LCD starting from row 1, column 3: Spi_Lcd8_Out(1, 3, "Hello!") MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 341 CHAPTER 6 mikroBasic for 8051 Libraries Spi_Lcd8_Out_Cp Prototype sub procedure Spi_Lcd8_Out_CP(dim text as string[19]) Returns Nothing. Prints text on LCD at current cursor position. Both string variables and literals can be passed as a text. Description Parameters : - text: text to be written Requires LCD needs to be initialized for SPI communication, see Spi_Lcd8_Config routines. Example ' Write text "Here!" at current cursor position: Spi_Lcd8_Out_CP("Here!") Spi_Lcd8_Chr Prototype sub procedure Spi_Lcd8_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 character. Description Parameters : - row: writing position row number - column: writing position column number - out_char: character to be written 342 Requires LCD needs to be initialized for SPI communication, see Spi_Lcd8_Config routines. Example ' Write character "i" at row 2, column 3: Spi_Lcd8_Chr(2, 3, 'i') MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_Lcd8_Chr_Cp Prototype sub procedure Spi_Lcd8_Chr_CP(dim Out_Char as byte) Returns Nothing. Prints character on LCD at current cursor position. Both variables and literals can be passed as character. Description Parameters : - out_char: character to be written Requires LCD needs to be initialized for SPI communication, see Spi_Lcd8_Config routines. Print “e” at current cursor position: Example ' Write character "e" at current cursor position: Spi_Lcd8_Chr_Cp('e') Spi_Lcd8_Cmd Prototype sub procedure Spi_Lcd8_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 LCD Commands. Requires LCD needs to be initialized for SPI communication, see Spi_Lcd8_Config routines. Example ' Clear LCD display: Spi_Lcd8_Cmd(LCD_CLEAR) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 343 CHAPTER 6 mikroBasic for 8051 Libraries Available LCD Commands Lcd Command 344 Purpose LCD_FIRST_ROW Move cursor to the 1st row LCD_SECOND_ROW Move cursor to the 2nd row LCD_THIRD_ROW Move cursor to the 3rd row LCD_FOURTH_ROW Move cursor to the 4th row LCD_CLEAR Clear display LCD_RETURN_HOME Return cursor to home position, returns a shifted display to its original position. Display data RAM is unaffected. LCD_CURSOR_OFF Turn off cursor LCD_UNDERLINE_ON Underline cursor on LCD_BLINK_CURSOR_ON Blink cursor on LCD_MOVE_CURSOR_LEFT Move cursor left without changing display data RAM LCD_MOVE_CURSOR_RIGHT Move cursor right without changing display data RAM LCD_TURN_ON Turn LCD display on LCD_TURN_OFF Turn LCD display off LCD_SHIFT_LEFT Shift display left without changing display data RAM LCD_SHIFT_RIGHT Shift display right without changing display data RAM MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Library Example This example demonstrates how to communicate LCD in 8-bit mode via the SPI module, using serial to parallel convertor MCP23S17. program SPI_Lcd8 dim text as char[16] ' Port Expander module connections dim SPExpanderRST as sbit at P1.B0 dim SPExpanderCS as sbit at P1.B1 ' End Port Expander module connections main: text = "mikroE" Spi_Init() face Spi_Lcd8_Config(0) 8bit mode via SPI Spi_Lcd8_Cmd(LCD_CLEAR) Spi_Lcd8_Cmd(LCD_CURSOR_OFF) Spi_Lcd8_Out(1,6, text) 1st row, 6th column... Spi_Lcd8_Chr_CP("!") Spi_Lcd8_Out(2,1, "mikroelektronika") 2nd row, 1st column... Spi_Lcd8_Out(3,1, text) more than two rows Spi_Lcd8_Out(4,15, text) more than two rows end. ' Initialize SPI inter' Intialize LCD in ' Clear display ' Turn cursor off ' Print text to LCD, ' Append "!" ' Print text to LCD, ' For LCD modules with ' For LCD modules with MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 345 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection SPI LCD8 HW connection 346 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries SPI T6963C GRAPHIC LCD LIBRARY The mikroBasic for 8051 provides a library for working with GLCDs based on TOSHIBA T6963C controller via SPI interface. The Toshiba T6963C is a very popular LCD controller for the use in small graphics modules. It is capable of controlling displays with a resolution up to 240x128. Because of its low power and small outline it is most suitable for mobile applications such as PDAs, MP3 players or mobile measurement equipment. Although this controller is small, it has a capability of displaying and merging text and graphics and it manages all interfacing signals to the displays Row and Column drivers. For creating a custom set of GLCD images use GLCD Bitmap Editor Tool. Note: The library uses the SPI module for communication. The user must initialize SPI module before using the Spi T6963C GLCD Library. Note: This Library is designed to work with mikroElektronika's Serial GLCD 240x128 and 240x64 Adapter Boards pinout, see schematic at the bottom of this page for details. Note: Some mikroElektronika's adapter boards have pinout different from T6369C datasheets. Appropriate relations between these labels are given in the table below: Adapter Board T6369C datasheet RS C/D R/W /RD E /WR External dependencies of Spi T6963C Graphic LCD Library The implementation of Spi T6963C Graphic LCD Library routines is based on Port Expander Library routines. External dependencies are the same as Port Expander Library external dependencies. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 347 CHAPTER 6 mikroBasic for 8051 Libraries Library Routines - Spi_T6963C_Config Spi_T6963C_WriteData Spi_T6963C_WriteCommand Spi_T6963C_SetPtr Spi_T6963C_WaitReady Spi_T6963C_Fill Spi_T6963C_Dot Spi_T6963C_Write_Char Spi_T6963C_Write_Text Spi_T6963C_Line Spi_T6963C_Rectangle Spi_T6963C_Box Spi_T6963C_Circle Spi_T6963C_Image Spi_T6963C_Sprite Spi_T6963C_Set_Cursor Note: The following low level library routines are implemented as macros. These macros can be found in the Spi_T6963C.h header file which is located in the SPI T6963C example projects folders. - 348 Spi_T6963C_ClearBit Spi_T6963C_SetBit Spi_T6963C_NegBit Spi_T6963C_DisplayGrPanel Spi_T6963C_DisplayTxtPanel Spi_T6963C_SetGrPanel Spi_T6963C_SetTxtPanel Spi_T6963C_PanelFill Spi_T6963C_GrFill Spi_T6963C_TxtFill Spi_T6963C_Cursor_Height Spi_T6963C_Graphics Spi_T6963C_Text Spi_T6963C_Cursor Spi_T6963C_Cursor_Blink MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Config Prototype sub procedure Spi_T6963C_Config(dim width as word, dim height as byte, dim fntW as byte, dim DeviceAddress as byte, dim wr as byte, dim rd as byte, dim cd as byte, dim rst as byte) Returns Nothing. Initalizes the Graphic Lcd controller. Parameters : Description - width: width of the GLCD panel height: height of the GLCD panel fntW: font width DeviceAddress: SPI expander hardware address, see schematic at the - bottom of this page wr: write signal pin on GLCD control port rd: read signal pin on GLCD control port cd: command/data signal pin on GLCD control port rst: reset signal pin on GLCD control port Display RAM organization: The library cuts RAM into panels : a complete panel is one graphics panel followed by a text panel (see schematic below). schematic: +---------------------+ /\ + GRAPHICS PANEL #0 + | + + | + + | + + | +---------------------+ | PANEL 0 + TEXT PANEL #0 + | + + \/ +---------------------+ /\ + GRAPHICS PANEL #1 + | + + | + + | + + | +---------------------+ | PANEL 1 + TEXT PANEL #2 + | + + | +---------------------+ \/ MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 349 CHAPTER 6 mikroBasic for 8051 Libraries SPExpanderCS and SPExpanderRST variables must be defined before using this function. Requires The SPI module needs to be initialized. See the Spi_Init and Spi_Init_Advanced routines. Example ' port expander pinout definition dim SPExpanderRST as sbit at P1.B0 dim SPExpanderCS sbit at P1.B1 ... Spi_Init_Advanced(MASTER_OSC_DIV4 OR CLK_IDLE_LOW OR IDLE_2_ACTIVE OR DATA_ORDER_MSB) Spi_T6963C_Config(240, 64, 8, 0, 0, 1, 3, 4) Spi_T6963C_WriteData Prototype sub procedure Spi_T6963C_WriteData(dim Ddata as byte) Returns Nothing. Writes data to T6963C controller via SPI interface. Description Parameters : - Ddata: data to be written Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_WriteData(AddrL) Spi_T6963C_WriteCommand Prototype sub procedure Spi_T6963C_WriteCommand(dim Ddata as byte) Returns Nothing. Writes command to T6963C controller via SPI interface. Description Parameters : - Ddata: command to be written 350 Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_WriteCommand(Spi_T6963C_CURSOR_POINTER_SET) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_SetPtr Prototype sub procedure Spi_T6963C_SetPtr(dim p as word, dim c as byte) Returns Nothing. Sets the memory pointer p for command c. Description Parameters : - p: address where command should be written - c: command to be written Requires SToshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_SetPtr(T6963C_grHomeAddr + start, T6963C_ADDRESS_POINTER_SET) Spi_T6963C_WaitReady Prototype sub procedure Spi_T6963C_WaitReady() Returns Nothing. Description Pools the status byte, and loops until Toshiba GLCD module is ready. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_WaitReady() Spi_T6963C_Fill Prototype sub procedure Spi_T6963C_Fill(dim v as byte, dim start as word, dim len as word) Returns Nothing. Fills controller memory block with given byte. Parameters : Description - v: byte to be written - start: starting address of the memory block - len: length of the memory block in bytes Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Fill(0x33, 0x00FF, 0x000F) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 351 CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Dot Prototype sub procedure Spi_T6963C_Dot(dim x as integer, dim y as integer, dim color as byte) Returns Nothing. Draws a dot in the current graphic panel of GLCD at coordinates (x, y). Parameters : Description 352 - x: dot position on x-axis - y: dot position on y-axis - color: color parameter. Valid values: Spi_T6963C_BLACK and Spi_T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Dot(x0, y0, pcolor) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Write_Char Prototype sub procedure Spi_T6963C_Write_Char(dim c as byte, dim x as byte, dim y as byte, dim mode as byte) Returns Nothing. Writes a char in the current text panel of GLCD at coordinates (x, y). Parameters : - c: char to be written x: char position on x-axis y: char position on y-axis mode: mode parameter. Valid values: Spi_T6963C_ROM_MODE_OR, Spi_T6963C_ROM_MODE_XOR, Spi_T6963C_ROM_MODE_AND and Spi_T6963C_ROM_MODE_TEXT Description Mode parameter explanation: - OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically “OR-ed”. This is the most common way of combining text and graphics for example labels on buttons. - XOR-Mode: In this mode, the text and graphics data are combined via the logical “exclusive OR”. This can be useful to display text in negative mode, i.e. white text on black background. - AND-Mode: The text and graphic data shown on display are combined via the logical “AND function”. - TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are stored in the graphic area of display memory. For more details see the T6963C datasheet. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Write_Char("A",22,23,AND) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 353 CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Write_Text Prototype sub procedure Spi_T6963C_Write_Text(dim str as ^byte, dim x as byte, dim y as byte, dim mode as byte) Returns Nothing. Writes text in the current text panel of GLCD at coordinates (x, y). Parameters : - str: text to be written x: text position on x-axis y: text position on y-axis mode: mode parameter. Valid values: Spi_T6963C_ROM_MODE_OR, Spi_T6963C_ROM_MODE_XOR, Spi_T6963C_ROM_MODE_AND and Spi_T6963C_ROM_MODE_TEXT Description Mode parameter explanation: - OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically “OR-ed”. This is the most common way of combining text and graphics for example labels on buttons. - XOR-Mode: In this mode, the text and graphics data are combined via the logical “exclusive OR”. This can be useful to display text in negative mode, i.e. white text on black background. - AND-Mode: The text and graphic data shown on the display are combined via the logical “AND function”. - TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are stored in the graphic area of display memory. For more details see the T6963C datasheet. 354 Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Write_Text("GLCD LIBRARY DEMO, WELCOME !", 0, 0, T6963C_ROM_MODE_EXOR) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Line Prototype sub procedure Spi_T6963C_Line(dim x0 as integer, dim y0 as integer, dim x1 as integer, dim y1 as integer, dim pcolor as byte) Returns Nothing. Draws a line from (x0, y0) to (x1, y1). Parameters : Description - x0: x coordinate of the line start y0: y coordinate of the line end x1: x coordinate of the line start y1: y coordinate of the line end pcolor: color parameter. Valid values: Spi_T6963C_BLACK and Spi_T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Line(0, 0, 239, 127, T6963C_WHITE) Spi_T6963C_Rectangle Prototype sub procedure Spi_T6963C_Rectangle(dim x0 as integer, dim y0 as integer, dim x1 as integer, dim y1 as integer, dim pcolor as byte) Returns Nothing. Draws a rectangle on GLCD. Parameters : Description - x0: x coordinate of the upper left rectangle corner y0: y coordinate of the upper left rectangle corner x1: x coordinate of the lower right rectangle corner y1: y coordinate of the lower right rectangle corner pcolor: color parameter. Valid values: Spi_T6963C_BLACK and Spi_T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Rectangle(20, 20, 219, 107, T6963C_WHITE) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 355 CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Box Prototype sub procedure Spi_T6963C_Box(dim x0 as integer, dim y0 as integer, dim x1 as integer, dim y1 as integer, dim pcolor as byte) Returns Nothing. Draws a box on the GLCD Parameters : Description - x0: x coordinate of the upper left box corner y0: y coordinate of the upper left box corner x1: x coordinate of the lower right box corner y1: y coordinate of the lower right box corner pcolor: color parameter. Valid values: Spi_T6963C_BLACK and Spi_T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Box(0, 119, 239, 127, T6963C_WHITE) Spi_T6963C_Circle Prototype sub procedure Spi_T6963C_Circle(dim x as integer, dim y as integer, dim r as longint, dim pcolor as byte) Returns Nothing. Draws a circle on the GLCD. Parameters : Description - x: x coordinate of the circle center y: y coordinate of the circle center r: radius size pcolor: color parameter. Valid values: Spi_T6963C_BLACK and Spi_T6963C_WHITE 356 Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Circle(120, 64, 110, T6963C_WHITE) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Image Prototype sub procedure Spi_T6963C_image(const pic as ^byte) Returns Nothing. Displays bitmap on GLCD. Parameters : Description - pic: image to be displayed. Bitmap array can be located in both code and RAM memory (due to the mikroBasic for 8051 pointer to const and pointer to RAM equivalency). Use the mikroBasic’s integrated GLCD Bitmap Editor (menu option Tools › GLCD Bitmap Editor) to convert image to a constant array suitable for displaying on GLCD. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Image(my_image) Spi_T6963C_Sprite Prototype sub procedure Spi_T6963C_sprite(dim px, py, sx, sy as byte, const pic as ^byte) Returns Nothing. Fills graphic rectangle area (px, py) to (px+sx, py+sy) with custom size picture. Parameters : - px: x coordinate of the upper left picture corner. Valid values: multiples of the font width Description - py: y coordinate of the upper left picture corner - pic: picture to be displayed - sx: picture width. Valid values: multiples of the font width - sy: picture height Note: If px and sx parameters are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Sprite(76, 4, einstein, 88, 119) ' draw a sprite MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 357 CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Set_Cursor Prototype sub procedure Spi_T6963C_set_cursor(dim x, y as byte) Returns Nothing. Sets cursor to row x and column y. Description Parameters : - x: cursor position row number - y: cursor position column number Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Set_Cursor(cposx, cposy) Spi_T6963C_ClearBit Prototype sub procedure Spi_T6963C_clearBit(dim b as byte) Returns Nothing. Clears control port bit(s). Description Parameters : - b: bit mask. The function will clear bit x on control port if bit x in bit mask is set to 1. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' clear bits 0 and 1 on control port Spi_T6963C_ClearBit(0x03) Spi_T6963C_SetBit Prototype sub procedure Spi_T6963C_setBit(dim b as byte) Returns Nothing. Sets control port bit(s). Description Parameters : - b: bit mask. The function will set bit x on control port if bit x in bit mask is set to 1. 358 Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' set bits 0 and 1 on control port Spi_T6963C_SetBit(0x03) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_NegBit Prototype sub procedure Spi_T6963C_negBit(dim b as byte) Returns Nothing. Negates control port bit(s). Description Parameters : - b: bit mask. The function will negate bit x on control port if bit x in bit mask is set to 1. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' negate bits 0 and 1 on control port Spi_T6963C_NegBit(0x03) Spi_T6963C_DisplayGrPanel Prototype sub procedure Spi_T6963C_DisplayGrPanel(dim n as byte) Returns Nothing. Display selected graphic panel. Description Parameters : - n: graphic panel number. Valid values: 0 and 1. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' display graphic panel 1 Spi_T6963C_DisplayGrPanel(1) Spi_T6963C_DisplayTxtPanel Prototype sub procedure Spi_T6963C_DisplayTxtPanel(dim n as byte) Returns Nothing. Display selected text panel. Description Parameters : - n: text panel number. Valid values: 0 and 1. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' display text panel 1 Spi_T6963C_DisplayTxtPanel(1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 359 CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_SetGrPanel Prototype sub procedure Spi_T6963C_SetGrPanel(dim n as byte) Returns Nothing. Compute start address for selected graphic panel and set appropriate internal pointers. All subsequent graphic operations will be preformed at this graphic panel. Description Parameters : - n: graphic panel number. Valid values: 0 and 1. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' set graphic panel 1 as current graphic panel. Spi_T6963C_SetGrPanel(1) Spi_T6963C_SetTxtPanel Prototype sub procedure Spi_T6963C_SetTxtPanel(dim n as byte) Returns Nothing. Compute start address for selected text panel and set appropriate internal pointers. All subsequent text operations will be preformed at this text panel. Description Parameters : - n: text panel number. Valid values: 0 and 1. 360 Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' set text panel 1 as current text panel. Spi_T6963C_SetTxtPanel(1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_PanelFill Prototype sub procedure Spi_T6963C_PanelFill(dim v as byte) Returns Nothing. Fill current panel in full (graphic+text) with appropriate value (0 to clear). Description Parameters : - v: value to fill panel with. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example clear current panel Spi_T6963C_PanelFill(0) Spi_T6963C_GrFill Prototype sub procedure Spi_T6963C_GrFill(dim v as byte) Returns Nothing. Fill current graphic panel with appropriate value (0 to clear). Description Parameters : - v: value to fill graphic panel with. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' clear current graphic panel Spi_T6963C_GrFill(0) Spi_T6963C_TxtFill Prototype sub procedure Spi_T6963C_TxtFill(dim v as byte) Returns Nothing. Fill current text panel with appropriate value (0 to clear). Description Parameters : - v: this value increased by 32 will be used to fill text panel. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' clear current text panel Spi_T6963C_TxtFill(0) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 361 CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Cursor_Height Prototype sub procedure Spi_T6963C_Cursor_Height(dim n as byte) Returns Nothing. Set cursor size. Description Parameters : - n: cursor height. Valid values: 0..7. Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example Spi_T6963C_Cursor_Height(7) Spi_T6963C_Graphics Prototype sub procedure Spi_T6963C_Graphics(dim n as byte) Returns Nothing. Enable/disable graphic displaying. Description Parameters : - n: graphic enable/disable parameter. Valid values: 0 (disable graphic dispaying) and 1 (enable graphic displaying). Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example enable graphic displaying Spi_T6963C_Graphics(1) Spi_T6963C_Text Prototype sub procedure Spi_T6963C_Text(dim n as byte) Returns Nothing. Enable/disable text displaying. Description Parameters : - n: text enable/disable parameter. Valid values: 0 (disable text dispaying) and 1 (enable text displaying). 362 Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' enable text displaying Spi_T6963C_Text(1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Spi_T6963C_Cursor Prototype sub procedure Spi_T6963C_Cursor(dim n as byte) Returns Nothing. Set cursor on/off. Description Parameters : - n: on/off parameter. Valid values: 0 (set cursor off) and 1 (set cursor on). Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' set cursor on Spi_T6963C_Cursor(1) Spi_T6963C_Cursor_Blink Prototype sub procedure Spi_T6963C_Cursor_Blink(dim n as byte) Returns Nothing. Enable/disable cursor blinking. Description Parameters : - n: cursor blinking enable/disable parameter. Valid values: 0 (disable cursor blinking) and 1 (enable cursor blinking). Requires Toshiba GLCD module needs to be initialized. See Spi_T6963C_Config routine. Example ' enable cursor blinking Spi_T6963C_Cursor_Blink(1) Library Example The following drawing demo tests advanced routines of the Spi T6963C GLCD library. Hardware configurations in this example are made for the T6963C 240x128 display, Easy8051B board and AT89S8253. program SPI_T6963C_240x128 include __Lib_T6963C_Consts include bitmap include bitmap2 ' Port Expander module connections dim SPExpanderRST as sbit at P1.B0 dim SPExpanderCS as sbit at P1.B1 ' End Port Expander module connections MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 363 CHAPTER 6 mikroBasic for 8051 Libraries dim panel as byte ' current panel i as word ' general purpose register curs as byte ' cursor visibility cposx, cposy as word ' cursor x-y position txtcols as byte ' number of text coloms txt, txt1 as string[29] idata txt1 = " EINSTEIN WOULD HAVE LIKED mC" txt = " GLCD LIBRARY DEMO, WELCOME !" P0 = 255 ' ' ' ' ' ' ' ' ' ' ' all inputs * init display for 240 pixel width and 128 pixel height * 8 bits character width * data bus on MCP23S17 portB * control bus on MCP23S17 portA * bit 2 is !WR * bit 1 is !RD * bit 0 is !CD * bit 4 is RST * * chip enable, reverse on, 8x8 font internaly set in library ' Initialize SPI module Spi_Init_Advanced(MASTER_OSC_DIV4 or CLK_IDLE_LOW IDLE_2_ACTIVE or DATA_ORDER_MSB) ' Initialize SPI Toshiba 240x128 Spi_T6963C_Config(240, 128, 8, 0, 2, 1, 0, 4) Delay_ms(1000) ' ' ' or * * Enable both graphics and text display at the same time * Spi_T6963C_graphics(1) Spi_T6963C_text(1) panel = 0 i = 0 curs = 0 cposy = 0 cposx = 0 ' ' ' * * Text messages * Spi_T6963C_write_text(txt, 0, 0, T6963C_ROM_MODE_XOR) Spi_T6963C_write_text(txt1, 0, 15, T6963C_ROM_MODE_XOR) 364 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 ' ' ' Libraries * * Cursor * Spi_T6963C_cursor_height(8) Spi_T6963C_set_cursor(0, 0) Spi_T6963C_cursor(0) ' ' ' ' 8 pixel height ' Move cursor to top left ' Cursor off * * Draw rectangles * Spi_T6963C_rectangle( 0, 0, 239, 127, T6963C_WHITE) Spi_T6963C_rectangle(20, 20, 219, 107, T6963C_WHITE) Spi_T6963C_rectangle(40, 40, 199, 87, T6963C_WHITE) Spi_T6963C_rectangle(60, 60, 179, 67, T6963C_WHITE) ' ' ' * * Draw a cross * Spi_T6963C_line(0, 0, 239, 127, T6963C_WHITE) Spi_T6963C_line(0, 127, 239, 0, T6963C_WHITE) ' ' ' * * Draw solid boxes * Spi_T6963C_box(0, 0, 239, 8, T6963C_WHITE) Spi_T6963C_box(0, 119, 239, 127, T6963C_WHITE) ' ' ' * * Draw circles * Spi_T6963C_circle(120, Spi_T6963C_circle(120, Spi_T6963C_circle(120, Spi_T6963C_circle(120, Spi_T6963C_circle(120, Spi_T6963C_circle(120, Spi_T6963C_circle(120, 64, 64, 64, 64, 64, 64, 64, 10, T6963C_WHITE) 30, T6963C_WHITE) 50, T6963C_WHITE) 70, T6963C_WHITE) 90, T6963C_WHITE) 110, T6963C_WHITE) 130, T6963C_WHITE) Spi_T6963C_sprite(76, 4, @einstein, 88, 119) Spi_T6963C_setGrPanel(1) Spi_T6963C_image(@banner_bmp) screen with a picture ' Draw a sprite ' Select other graphic panel ' Fill the graphic MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 365 CHAPTER 6 mikroBasic for 8051 Libraries while TRUE ' Endless loop ' * ' * If P0_0 is pressed, toggle the display between graphic panel 0 and graphic 1 ' * if ( P0_0 = 0) then Inc(panel) panel = panel and 1 Spi_T6963C_displayGrPanel(panel) Delay_ms(300) ' ' ' * * If P0_1 is pressed, display only graphic panel * else if ( P0_1 = 0) then Spi_T6963C_graphics(1) Spi_T6963C_text(0) Delay_ms(300) ' ' ' * * If P0_2 is pressed, display only text panel * else if ( P0_2 = 0) then Spi_T6963C_graphics(0) Spi_T6963C_text(1) Delay_ms(300) ' ' ' * * If P0_3 is pressed, display text and graphic panels * else if( P0_3 = 0) then Spi_T6963C_graphics(1) Spi_T6963C_text(1) Delay_ms(300) ' ' ' 366 * * If P0_4 is pressed, change cursor * MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries else if ( P0_4 = 0) then Inc(curs) if (curs = 3) then curs = 0 end if select case curs case 0 ' No cursor Spi_T6963C_cursor(0) case 1 ' Blinking cursor Spi_T6963C_cursor(1) Spi_T6963C_cursor_blink(1) case 2 ' Non blinking cursor Spi_T6963C_cursor(1) Spi_T6963C_cursor_blink(0) end select 'end case end if Delay_ms(300) end if end if end if end if ' ' ' * * Move cursor, even if not visible * Inc(cposx) if (cposx = txtcols) then cposx = 0 cposy = cposy + 1 if (cposy = (128 div T6963C_CHARACTER_HEIGHT)) then if y end cposy = 0 grafic height (128) div character height end if Spi_T6963C_set_cursor(cposx, cposy) Delay_ms(100) end if wend end. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD ' ' 367 CHAPTER 6 mikroBasic for 8051 Libraries HW Connection Spi T6963C GLCD HW connection 368 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries T6963C GRAPHIC LCD LIBRARY The mikroBasic for 8051 provides a library for working with GLCDs based on TOSHIBA T6963C controller. The Toshiba T6963C is a very popular LCD controller for the use in small graphics modules. It is capable of controlling displays with a resolution up to 240x128. Because of its low power and small outline it is most suitable for mobile applications such as PDAs, MP3 players or mobile measurement equipment. Although small, this contoller has a capability of displaying and merging text and graphics and it manages all the interfacing signals to the displays Row and Column drivers. For creating a custom set of GLCD images use GLCD Bitmap Editor Tool. Note: ChipEnable(CE), FontSelect(FS) and Reverse(MD) have to be set to appropriate levels by the user outside of the T6963C_Init function. See the Library Example code at the bottom of this page. Note: Some mikroElektronika's adapter boards have pinout different from T6369C datasheets. Appropriate relations between these labels are given in the table below: Adapter Board T6369C datasheet RS C/D R/W /RD E /WR MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 369 CHAPTER 6 mikroBasic for 8051 Libraries External dependencies of T6963C Graphic LCD Library The following variables must be defined in all projects using T6963C Graphic LCD library: dim T6963C_dataPort as byte external sfr dim T6963C_ctrlPort as byte external sfr dim T6963C_ctrlwr as sbit external dim T6963C_ctrlrd as sbit external dim T6963C_ctrlcd as sbit external dim T6963C_ctrlrst as sbit external Description: T6963C Data Port. T6963C Control Port. Write signal. Read signal. Command/Data signal. Reset signal. Example : dim T6963C_dataPort as byte at P0 sfr dim T6963C_ctrlPort as byte at P1 sfr dim T6963C_ctrlwr as sbit at P1.B2 dim T6963C_ctrlrd as sbit at P1.B1 dim T6963C_ctrlcd as sbit at P1.B0 dim T6963C_ctrlrst as sbit at P1.B4 Library Routines - T6963C_Init - T6963C_WriteData - T6963C_WriteCommand - T6963C_SetPtr - T6963C_WaitReady - T6963C_Fill - T6963C_Dot - T6963C_Write_Char - T6963C_Write_Text - T6963C_Line - T6963C_Rectangle - T6963C_Box - T6963C_Circle - T6963C_Image - T6963C_Sprite - T6963C_Set_Cursor Note: The following low level library routines are implemented as macros. These macros can be found in the T6963C.h header file which is located in the T6963C example projects folders. 370 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries - T6963C_ClearBit - T6963C_SetBit - T6963C_NegBit - T6963C_DisplayGrPanel - T6963C_DisplayTxtPanel - T6963C_SetGrPanel - T6963C_SetTxtPanel - T6963C_PanelFill - T6963C_GrFill - T6963C_TxtFill - T6963C_Cursor_Height - T6963C_Graphics - T6963C_Text - T6963C_Cursor - T6963C_Cursor_Blink MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 371 CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Init Prototype sub procedure T6963C_init(dim width as word, dim height, fntW as byte) Returns Nothing. Initalizes the Graphic Lcd controller. Parameters : - width: width of the GLCD panel - height: height of the GLCD panel - fntW: font width Display RAM organization: The library cuts the RAM into panels : a complete panel is one graphics panel followed by a text panel (see schematic below). schematic: +---------------------+ /\ Description + GRAPHICS PANEL #0 + | + + | + + | + + | +---------------------+ | PANEL 0 + TEXT PANEL #0 + | + + \/ +---------------------+ /\ + GRAPHICS PANEL #1 + | + + | + + | + + | +---------------------+ | PANEL 1 + TEXT PANEL #2 + | + + | +---------------------+ \/ Global variables : Requires - T6963C_dataPort : Data Port T6963C_ctrlPort : Control Port T6963C_ctrlwr : write signal pin T6963C_ctrlrd : read signal pin T6963C_ctrlcd : command/data signal pin T6963C_ctrlrst : reset signal pin must be defined before using this function. 372 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Example Libraries ' T6963CGLCD pinout definition dim T6963C_dataPort as byte at P0 sfr ' pointer to DATA BUS port dim T6963C_ctrlPort as byte at P1 sfr ' pointer to CONTROL BUS port dim T6963C_ctrlwr as sbit at P1.B2 ' WR write signal dim T6963C_ctrlrd as sbit at P1.B1 ' RD read signal dim T6963C_ctrlcd as sbit at P1.B0 ' CD command/data signal dim T6963C_ctrlrst as sbit at P1.B4 ' RST reset signal ... ' init display for 240 pixel width, 128 pixel height and 8 bits character width T6963C_init(240, 128, 8) T6963C_WriteData Prototype sub procedure T6963C_WriteData(dim mydata as byte) Returns Nothing. Writes data to T6963C controller. Description Parameters : - mydata: data to be written Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_WriteData(AddrL) T6963C_WriteCommand Prototype sub procedure T6963C_WriteCommand(dim mydata as byte) Returns Nothing. Writes command to T6963C controller. Description Parameters : - mydata: command to be written Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_WriteCommand(T6963C_CURSOR_POINTER_SET) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 373 CHAPTER 6 mikroBasic for 8051 Libraries T6963C_SetPtr Prototype sub procedure T6963C_SetPtr(dim p as word, dim c as byte) Returns Nothing. Sets the memory pointer p for command c. Description Parameters : - p: address where command should be written - c: command to be written Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_SetPtr(T6963C_grHomeAddr + start, T6963C_ADDRESS_POINTER_SET) T6963C_WaitReady Prototype sub procedure T6963C_WaitReady() Returns Nothing. Description Pools the status byte, and loops until Toshiba GLCD module is ready. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_WaitReady() T6963C_Fill Prototype sub procedure T6963C_Fill(dim v as byte, dim start, len as word) Returns Nothing. Fills controller memory block with given byte. Parameters : Description - v: byte to be written - start: starting address of the memory block - len: length of the memory block in bytes 374 Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Fill(0x33,0x00FF,0x000F) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Dot Prototype sub procedure T6963C_Dot(dim x, y as integer, dim color as byte) Returns Nothing. Draws a dot in the current graphic panel of GLCD at coordinates (x, y). Parameters : Description - x: dot position on x-axis - y: dot position on y-axis - color: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Dot(x0, y0, pcolor) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 375 CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Write_Char Prototype sub procedure T6963C_Write_Char(dim c, x, y, mode as byte) Returns Nothing. Writes a char in the current text panel of GLCD at coordinates (x, y). Parameters : - c: char to be written - x: char position on x-axis - y: char position on y-axis - mode: mode parameter. Valid values: T6963C_ROM_MODE_OR, T6963C_ROM_MODE_XOR, T6963C_ROM_MODE_AND and T6963C_ROM_MODE_TEXT Mode parameter explanation: Description - OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically “OR-ed”. This is the most common way of combining text and graphics for example labels on buttons. - XOR-Mode: In this mode, the text and graphics data are combined via the logical “exclusive OR”. This can be useful to display text in the negative mode, i.e. white text on black background. - AND-Mode: The text and graphic data shown on display are combined via the logical “AND function”. - TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are stored in the graphic area of display memory. For more details see the T6963C datasheet. 376 Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Write_Char('A',22,23,AND) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Write_Text Prototype sub procedure T6963C_Write_Text(dim str as ^byte, dim x, y, mode as byte) Returns Nothing. Writes text in the current text panel of GLCD at coordinates (x, y). Parameters : - str: text to be written x: text position on x-axis y: text position on y-axis mode: mode parameter. Valid values: T6963C_ROM_MODE_OR, T6963C_ROM_MODE_XOR, T6963C_ROM_MODE_AND and T6963C_ROM_MODE_TEXT Mode parameter explanation: Description - OR Mode: In the OR-Mode, text and graphics can be displayed and the data is logically “OR-ed”. This is the most common way of combining text and graphics for example labels on buttons. - XOR-Mode: In this mode, the text and graphics data are combined via the logical “exclusive OR”. This can be useful to display text in the negative mode, i.e. white text on black background. - AND-Mode: The text and graphic data shown on display are combined via the logical “AND function”. - TEXT-Mode: This option is only available when displaying just a text. The Text Attribute values are stored in the graphic area of display memory. For more details see the T6963C datasheet. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Write_Text(" GLCD LIBRARY DEMO, WELCOME !", 0, 0, T6963C_ROM_MODE_XOR) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 377 CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Line Prototype sub procedure T6963C_Line(dim x0, y0, x1, y1 as integer, dim pcolor as byte) Returns Nothing. Draws a line from (x0, y0) to (x1, y1). Parameters : Description - x0: x coordinate of the line start y0: y coordinate of the line end x1: x coordinate of the line start y1: y coordinate of the line end pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Line(0, 0, 239, 127, T6963C_WHITE) T6963C_Rectangle Prototype sub procedure T6963C_Rectangle(dim x0, y0, x1, y1 as integer, dim pcolor as byte) Returns Nothing. Draws a rectangle on GLCD. Parameters : Description - 378 x0: x coordinate of the upper left rectangle corner y0: y coordinate of the upper left rectangle corner x1: x coordinate of the lower right rectangle corner y1: y coordinate of the lower right rectangle corner pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Rectangle(20, 20, 219, 107, T6963C_WHITE) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Box Prototype sub procedure T6963C_Box(dim x0, y0, x1, y1 as integer, dim pcolor as byte) Returns Nothing. Draws a box on GLCD Parameters : Description - x0: x coordinate of the upper left box corner y0: y coordinate of the upper left box corner x1: x coordinate of the lower right box corner y1: y coordinate of the lower right box corner pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Box(0, 119, 239, 127, T6963C_WHITE) T6963C_Circle Prototype sub procedure T6963C_Circle(dim x, y as integer, dim r as longint, dim pcolor as byte) Returns Nothing. Draws a circle on GLCD. Parameters : Description - x: x coordinate of the circle center y: y coordinate of the circle center r: radius size pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Circle(120, 64, 110, T6963C_WHITE) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 379 CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Image Prototype sub procedure T6963C_Image(const pic as ^byte) Returns Nothing. Displays bitmap on GLCD. Parameters : Description - pic: image to be displayed. Bitmap array can be located in both code and RAM memory (due to the mikroBasic for 8051 pointer to const and pointer to RAM equivalency). Use the mikroBasic’s integrated GLCD Bitmap Editor (menu option Tools › GLCD Bitmap Editor) to convert image to a constant array suitable for displaying on GLCD. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Image(mc) T6963C_Sprite Prototype sub procedure T6963C_Sprite(dim px, py, sx, sy as byte, const pic as ^byte) Returns Nothing. Fills graphic rectangle area (px, py) to (px+sx, py+sy) with custom size picture. Parameters : - px: x coordinate of the upper left picture corner. Valid values: multiples of the font width Description - py: y coordinate of the upper left picture corner - pic: picture to be displayed - sx: picture width. Valid values: multiples of the font width - sy: picture height Note: If px and sx parameters are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width. 380 Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Sprite(76, 4, einstein, 88, 119) ' draw a sprite MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Set_Cursor Prototype sub procedure T6963C_Set_Cursor(dim x, y as byte) Returns Nothing. Sets cursor to row x and column y. Description Parameters : - x: cursor position row number - y: cursor position column number Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Set_Cursor(cposx, cposy) T6963C_ClearBit Prototype sub procedure T6963C_ClearBit(dim b as byte) Returns Nothing. Clears control port bit(s). Description Parameters : - b: bit mask. The function will clear bit x on control port if bit x in bit mask is set to 1. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' clear bits 0 and 1 on control port T6963C_ClearBit(0x03) T6963C_SetBit Prototype sub procedure T6963C_SetBit(dim b as byte) Returns Nothing. Sets control port bit(s). Description Parameters : - b: bit mask. The function will set bit x on control port if bit x in bit mask is set to 1. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' set bits 0 and 1 on control port T6963C_SetBit(0x03) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 381 CHAPTER 6 mikroBasic for 8051 Libraries T6963C_NegBit Prototype sub procedure T6963C_NegBit(dim b as byte) Returns Nothing. Negates control port bit(s). Description Parameters : - b: bit mask. The function will negate bit x on control port if bit x in bit mask is set to 1. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' negate bits 0 and 1 on control port T6963C_NegBit(0x03) T6963C_DisplayGrPanel Prototype sub procedure T6963C_DisplayGrPanel(dim n as byte) Returns Nothing. Display selected graphic panel. Description Parameters : - n: graphic panel number. Valid values: 0 and 1. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' display graphic panel 1 T6963C_DisplayGrPanel(1) T6963C_DisplayTxtPanel Prototype sub procedure T6963C_DisplayTxtPanel(dim n as byte) Returns Nothing. Display selected text panel. Description Parameters : - n: text panel number. Valid values: 0 and 1. 382 Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' display text panel 1 T6963C_DisplayTxtPanel(1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries T6963C_SetGrPanel Prototype sub procedure T6963C_SetGrPanel(dim n as byte) Returns Nothing. Compute start address for selected graphic panel and set appropriate internal pointers. All subsequent graphic operations will be preformed at this graphic panel. Description Parameters : - n: graphic panel number. Valid values: 0 and 1. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' set graphic panel 1 as current graphic panel. T6963C_SetGrPanel(1) T6963C_SetTxtPanel Prototype sub procedure T6963C_SetTxtPanel(dim n as byte) Returns Nothing. Compute start address for selected text panel and set appropriate internal pointers. All subsequent text operations will be preformed at this text panel. Description Parameters : - n: text panel number. Valid values: 0 and 1. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' set text panel 1 as current text panel. T6963C_SetTxtPanel(1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 383 CHAPTER 6 mikroBasic for 8051 Libraries T6963C_PanelFill Prototype sub procedure T6963C_PanelFill(dim v as byte) Returns Nothing. Fill current panel in full (graphic+text) with appropriate value (0 to clear). Description Parameters : - v: value to fill panel with. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example clear current panel T6963C_PanelFill(0) T6963C_GrFill Prototype sub procedure T6963C_GrFill(dim v as byte) Returns Nothing. Fill current graphic panel with appropriate value (0 to clear). Description Parameters : - v: value to fill graphic panel with. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' clear current graphic panel T6963C_GrFill(0) T6963C_TxtFill Prototype sub procedure T6963C_TxtFill(dim v as byte) Returns Nothing. Fill current text panel with appropriate value (0 to clear). Description Parameters : - v: this value increased by 32 will be used to fill text panel. 384 Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' clear current text panel T6963C_TxtFill(0) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Cursor_Height Prototype sub procedure T6963C_Cursor_Height(dim n as byte) Returns Nothing. Set cursor size. Description Parameters : - n: cursor height. Valid values: 0..7. Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example T6963C_Cursor_Height(7) T6963C_Graphics Prototype sub procedure T6963C_Graphics(dim n as byte) Returns Nothing. Enable/disable graphic displaying. Description Parameters : - n: on/off parameter. Valid values: 0 (disable graphic dispaying) and 1 (enable graphic displaying). Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' enable graphic displaying T6963C_Graphics(1) T6963C_Text Prototype sub procedure T6963C_Text(dim n as byte) Returns Nothing. Enable/disable text displaying. Description Parameters : - n: on/off parameter. Valid values: 0 (disable text dispaying) and 1 (enable text displaying). Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' enable text displaying T6963C_Text(1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 385 CHAPTER 6 mikroBasic for 8051 Libraries T6963C_Cursor Prototype sub procedure T6963C_Cursor(dim n as byte) Returns Nothing. Set cursor on/off. Description Parameters : - n: on/off parameter. Valid values: 0 (set cursor off) and 1 (set cursor on). Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' set cursor on T6963C_Cursor(1) T6963C_Cursor_Blink Prototype sub procedure T6963C_Cursor_Blink(dim n as byte) Returns Nothing. Enable/disable cursor blinking. Description Parameters : - n: on/off parameter. Valid values: 0 (disable cursor blinking) and 1 (enable cursor blinking). Requires Toshiba GLCD module needs to be initialized. See the T6963C_Init routine. Example ' enable cursor blinking T6963C_Cursor_Blink(1) Library Example The following drawing demo tests advanced routines of the T6963C GLCD library. Hardware configurations in this example are made for the T6963C 240x128 display, Easy8051B board and AT89S8253. program T6963C_240x128 include __Lib_T6963C_Consts include bitmap include bitmap2 ' T6963C module connections dim T6963C_dataPort as byte at P0 sfr dim T6963C_cntlPort as byte at P1 sfr 386 ' DATA port ' CONTROL port MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries dim T6963C_cntlwr as sbit at P1.B2 dim T6963C_cntlrd as sbit at P1.B1 dim T6963C_cntlcd as sbit at P1.B0 dim T6963C_cntlrst as sbit at P1.B4 ' End T6963C module connections dim ' ' ' ' WR write signal RD read signal CD command/data signal RST reset signal panel as byte ' current panel i as word ' general purpose register curs as byte ' cursor visibility cposx, cposy as word ' cursor x-y position txtcols as byte ' number of text coloms txt, txt1 as string[29] idata txt1 = " EINSTEIN WOULD HAVE LIKED mC" txt = " GLCD LIBRARY DEMO, WELCOME !" P2 = 255 ' all inputs ' Clear T6963C ports P1 = 0 ' control bus P0 = 0 ' data bus ' ' ' ' ' ' ' ' * * * * * * * * init display for 240 pixel width and 128 pixel height 8 bits character width data bus on P0 control bus on P1 bit 2 is !WR bit 1 is !RD bit 0 is !CD bit 4 is RST T6963C_init(240, 128, 8) ' ' ' * * enable both graphics and text display at the same time * T6963C_graphics(1) T6963C_text(1) panel = 0 i = 0 curs = 0 cposx = 0 cposy = 0 txtcols = 240 div 8 ' calculate number of text colomns ' (grafic display width divided by font width) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 387 CHAPTER 6 mikroBasic for 8051 Libraries ' ' ' * * text messages * T6963C_write_text(txt, 0, 0, T6963C_ROM_MODE_XOR) T6963C_write_text(txt1, 0, 15, T6963C_ROM_MODE_XOR) ' ' ' * * cursor * T6963C_cursor_height(8) T6963C_set_cursor(0, 0) T6963C_cursor(0) ' ' ' ' 8 pixel height ' move cursor to top left ' cursor off * * draw rectangles * T6963C_rectangle(0, 0, 239, 127, T6963C_BLACK) T6963C_rectangle(20, 20, 219, 107, T6963C_BLACK) T6963C_rectangle(40, 40, 199, 87, T6963C_BLACK) T6963C_rectangle(60, 60, 179, 67, T6963C_BLACK) ' ' ' * * draw a cross * T6963C_line(0, 0, 239, 127, T6963C_BLACK) T6963C_line(0, 127, 239, 0, T6963C_BLACK) ' ' ' * * draw solid boxes * T6963C_box(0, 0, 239, 8, T6963C_BLACK) T6963C_box(0, 119, 239, 127, T6963C_BLACK) ' ' ' * * draw circles * T6963C_circle(120, 64, 10, T6963C_BLACK) T6963C_circle(120, 64, 30, T6963C_BLACK) T6963C_sprite(76, 4, @einstein, 88, 119) T6963C_setGrPanel(1) ' draw a sprite ' select other graphic panel T6963C_Image(@banner_bmp) 388 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries while TRUE ' * ' * if P2_0 is pressed, toggle the display between graphic panel 0 and graphic 1 ' * if ( P2_0 = 0 ) then Inc(panel) panel = panel and 1 T6963C_displayGrPanel(panel) Delay_ms(300) ' ' ' * * if P2_1 is pressed, display only graphic panel * else if ( P2_1 = 0 ) then T6963C_graphics(1) T6963C_text(0) Delay_ms(300) ' ' ' * * if P2_2 is pressed, display only text panel * else if (P2_2 = 0) then T6963C_graphics(0) T6963C_text(1) Delay_ms(300) ' ' ' * * if P2_3 is pressed, display text and graphic panels * else if(P2_3 = 0) then T6963C_graphics(1) T6963C_text(1) Delay_ms(300) ' ' ' * * if P2_4 is pressed, change cursor * MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 389 CHAPTER 6 mikroBasic for 8051 Libraries else if(P2_4 = 0) then curs = curs + 1 if (curs = 3) then curs = 0 end if select case curs case 0 T6963C_cursor(0) case 1 T6963C_cursor(1) T6963C_cursor_blink(1) case 2 T6963C_cursor(1) T6963C_cursor_blink(0) end select ' end case Delay_ms(300) end if end if end if end if end if ' ' ' * * move cursor, even if not visible * Inc(cposx) if(cposx = txtcols) then cposx = 0 cposy = cposy + 1 if (cposy = (128 div T6963C_CHARACTER_HEIGHT)) then if y end cposy = 0 grafic height (128) div character height end if end if T6963C_set_cursor(cposx, cposy) Delay_ms(100) wend end. 390 ' ' MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries HW Connection T6963C GLCD HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 391 CHAPTER 6 mikroBasic for 8051 Libraries UART LIBRARY The UART hardware module is available with a number of 8051 compliant MCUs. The mikroBasic for 8051 UART Library provides comfortable work with the Asynchronous (full duplex) mode. Library Routines - Uart_Init Uart_Data_Ready Uart_Read Uart_Write Uart_Init Prototype sub procedure Uart_Init(dim baud_rate as longint) Returns Nothing. Configures and initializes the UART module. The internal UART module module is set to: Description - 8-bit data, no parity 1 STOP bit disabled automatic address recognition timer1 as baudrate source (mod2 = autoreload 8bit timer) Parameters : - baud_rate: requested baud rate Refer to the device data sheet for baud rates allowed for specific Fosc. 392 Requires MCU with the UART module and TIMER1 to be used as baudrate source. Example ' Initialize hardware UART and establish communication at 2400 bps Uart_Init(2400) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Uart_Data_Ready Prototype Returns sub function Uart_Data_Ready() as byte - 1 if data is ready for reading - 0 if there is no data in the receive register Description The function tests if data in receive buffer is ready for reading. MCU with the UART module. Requires Example The UART module must be initialized before using this routine. See the Uart_Init routine. dim receive as byte ... ' read data if ready if (Uart_Data_Ready()=1) then receive = Uart_Read() Uart_Read Prototype sub function Uart_Read() as byte Returns Received byte. Description The function receives a byte via UART. Use the Uart_Data_Ready function to test if data is ready first. MCU with the UART module. Requires Example The UART module must be initialized before using this routine. See Uart_Init routine. dim receive as byte ... ' read data if ready if (Uart_Data_Ready()=1) then receive = Uart_Read() MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 393 CHAPTER 6 mikroBasic for 8051 Libraries Uart_Write Prototype sub procedure Uart_Write(dim TxData as byte) Returns Nothing. The function transmits a byte via the UART module. Description Parameters : - TxData: data to be sent MCU with the UART module. Requires Example The UART module must be initialized before using this routine. See Uart_Init routine. dim data as byte ... data = 0x1E Uart_Write(data) Library Example This example demonstrates simple data exchange via UART. If MCU is connected to the PC, you can test the example from the mikroBasic for 8051 USART Terminal. program UART dim uart_rd as byte main: Uart_Init(4800) Delay_ms(100) while TRUE if (Uart_Data_Ready() <> 0) then data uart_rd = Uart_Read() Uart_Write(uart_rd) end if wend end. 394 ' Initialize UART module at 4800 bps ' Wait for UART module to stabilize ' Endless loop ' Check if UART module has received ' Read data ' Send the same data back MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries HW Connection UART HW connection MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 395 CHAPTER 6 mikroBasic for 8051 Libraries BUTTON LIBRARY The Button library contains miscellaneous routines useful for a project development. External dependecies of Button Library The following variable must be defined in all projects using Button library: dim Button_Pin as sbit external Description: Example : Declares Button_Pin, dim Button_Pin as which will be used by But- sbit at P0_0 ton Library. Library Routines - Button 396 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Button Prototype sub function Button(dim time_ms as byte, dim active_state as byte) as byte - 255 if the pin was in the active state for given period. - 0 otherwise Returns The function eliminates the influence of contact flickering upon pressing a button (debouncing). The Button pin is tested just after the function call and then again after the debouncing period has expired. If the pin was in the active state in both cases then the function returns 255 (true). Description Parameters : - time_ms: debouncing period in milliseconds - active_state: determines what is considered as active state. Valid values: 0 (logical zero) and 1 (logical one) Button_Pin variable must be defined before using this function. Requires Button pin must be configured as input. P2 is inverted on every P0.B0 one-to-zero transition : program Button ' Button connections dim Button_Pin as sbit at P0.B0; It will be used by Button Library. ' End Button connections bit oldstate; Example main: P0 = 255 P2 = 0xAA ' Declare Button_Pin. ' Old state flag ' Configure PORT0 as input ' Initial PORT2 value do { if (Button(1, 1)) ' Detect logical one oldstate = 1; ' Update flag if (oldstate && Button(1, 0)) { ' Detect one-to-zero transition P2 = ~P2; ' Invert PORT2 oldstate = 0; ' Update flag } } while(1); ' Endless loop }'~! MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 397 CHAPTER 6 mikroBasic for 8051 Libraries CONVERSIONS LIBRARY mikroBasic for 8051 Conversions Library provides routines for numerals to strings and BCD/decimal conversions. Library Routines You can get text representation of numerical value by passing it to one of the following routines: - ByteToStr ShortToStr WordToStr IntToStr LongintToStr LongWordToStr FloatToStr The following sub functions convert decimal values to BCD and vice versa: - Dec2Bcd - Bcd2Dec16 - Dec2Bcd16 398 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries ByteToStr Prototype sub procedure ByteToStr(dim input as word, dim byref output as string[2]) Returns Nothing. Converts input byte to a string. The output string is right justified and remaining positions on the left (if any) are filled with blanks. Description Parameters : - input: byte to be converted - output: destination string Requires Nothing. Example dim t as word txt as string[2] ... t = 24 ByteToStr(t, txt) ' txt is " 24" (one blank here) ShortToStr Prototype sub procedure ShortToStr(dim input as short, dim byref output as string[3]) Returns Nothing. Converts input short (signed byte) number to a string. The output string is right justified and remaining positions on the left (if any) are filled with blanks. Description Parameters : - input: short number to be converted - output: destination string Requires Nothing. Example dim t as short txt as string[3] ... t = -24 ByteToStr(t, txt) ' txt is " -24" (one blank here) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 399 CHAPTER 6 mikroBasic for 8051 Libraries WordToStr Prototype sub procedure WordToStr(dim input as word, dim byref output as string[4]) Returns Nothing. Converts input word to a string. The output string is right justified and the remaining positions on the left (if any) are filled with blanks. Description Parameters : - input: word to be converted - output: destination string Requires Nothing. Example dim t as word txt as string[4] ... t = 437 WordToStr(t, txt) ' txt is " 437" (two blanks here) IntToStr Prototype sub procedure IntToStr(dim input as integer, dim byref output as string[5] Returns Nothing. Converts input integer number to a string. The output string is right justified and the remaining positions on the left (if any) are filled with blanks. Description Parameters : - input: integer number to be converted - output: destination string Requires Example Nothing. dim input as integer txt as string[5] '... input = -4220 IntToStr(input, txt) 400 ' txt is ' -4220' MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries LongintToStr Prototype sub procedure LongintToStr(dim input as longint, dim byref output as string[10]) Returns Nothing. Converts input longint number to a string. The output string is right justified and the remaining positions on the left (if any) are filled with blanks. Description Parameters : - input: longint number to be converted - output: destination string Requires Example Nothing. dim input as longint txt as string[10] '... input = -12345678 IntToStr(input, txt) ' txt is ' -12345678' LongWordToStr Prototype sub procedure LongWordToStr(dim input as longword, dim byref output as string[9]) Returns Nothing. Converts input double word number to a string. The output string is right justified and the remaining positions on the left (if any) are filled with blanks. Description Parameters : - input: double word number to be converted - output: destination string Requires Example Nothing. dim input as longint txt as string[9] '... input = 12345678 IntToStr(input, txt) ' txt is ' 12345678' MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 401 CHAPTER 6 mikroBasic for 8051 Libraries FloatToStr Prototype Returns sub function FloatToStr(dim input as real, dim byref output as string[22]) - 3 2 1 0 if if if if input number is NaN input number is -INF input number is +INF conversion was successful Converts a floating point number to a string. Parameters : - input: floating point number to be converted Description - output: destination string The output string is left justified and null terminated after the last digit. Note: Given floating point number will be truncated to 7 most significant digits before conversion. Requires Nothing. Example dim ff1, ff2, ff3 as real txt as string[22] ... ff1 = -374.2 ff2 = 123.456789 ff3 = 0.000001234 FloatToStr(ff1, txt) FloatToStr(ff2, txt) FloatToStr(ff3, txt) 402 ' txt is "-374.2" ' txt is "123.4567" ' txt is "1.234e-6" MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Dec2Bcd Prototype sub function Dec2Bcd(dim decnum as byte) as byte Returns Converted BCD value. Converts input number to its appropriate BCD representation. Description Parameters : - decnum: number to be converted Requires Nothing. Example dim a, b as byte ... a = 22 b = Dec2Bcd(a) ' b equals 34 Bcd2Dec16 Prototype sub function Bcd2Dec16(dim bcdnum as word) as word Returns Converted decimal value. Converts 16-bit BCD numeral to its decimal equivalent. Description Parameters : - bcdnum: 16-bit BCD numeral to be converted Requires Nothing. Example dim a, b as word ... a = 0x1234 b = Bcd2Dec16(a) ' a equals 4660 ' b equals 1234 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 403 CHAPTER 6 mikroBasic for 8051 Libraries Dec2Bcd16 Prototype sub function Dec2Bcd16(dim decnum as word) as word Returns Converted BCD value. Converts decimal value to its BCD equivalent. Description Parameters : - decnum decimal number to be converted 404 Requires Nothing. Example dim a, b as word ... a = 2345 b = Dec2Bcd16(a) ' b equals 9029 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries MATH LIBRARY The mikroBasic for 8051 provides a set of library functions for floating point math handling. See also Predefined Globals and Constants for the list of predefined math constants. Library Functions - acos asin atan atan2 ceil cos cosh eval_poly exp fabs floor frexp ldexp log log10 modf pow sin sinh sqrt tan tanh MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 405 CHAPTER 6 mikroBasic for 8051 Libraries acos Prototype sub function acos(dim x as real) as real The function returns the arc cosine of parameter x; that is, the value whose Description cosine is x. The input parameter x must be between -1 and 1 (inclusive). The return value is in radians, between 0 and Π (inclusive). asin Prototype sub function asin(dim x as real) as real The function returns the arc sine of parameter x; that is, the value whose sine is Description x. The input parameter x must be between -1 and 1 (inclusive). The return value is in radians, between -Π/2 and Π/2 (inclusive). atan Prototype sub function atan(dim arg as real) as real The function computes the arc tangent of parameter arg; that is, the value Description whose tangent is arg. The return value is in radians, between -Π/2 and Π/2 (inclusive). atan2 Prototype sub function atan2(dim y as real, dim x as real) as real This is the two-argument arc tangent function. It is similar to computing the arc tangent of y/x, except that the signs of both arguments are used to determine Description the quadrant of the result and x is permitted to be zero. The return value is in radians, between -Π and Π (inclusive). ceil Prototype sub function ceil(dim x as real) as real Description The function returns value of parameter x rounded up to the next whole number. cos Prototype sub function cos(dim arg as real) as real Description The function returns the cosine of arg in radians. The return value is from -1 to 1. cosh 406 Prototype sub function cosh(dim x as real) as real Description The function returns the hyperbolic cosine of x, defined mathematically as (ex+e-x)/2. If the value of x is too large (if overflow occurs), the function fails. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries eval_poly Prototype sub function eval_poly(dim x as real, dim byref d as array[10] of real, dim n as integer) as real Description Function Calculates polynom for number x, with coefficients stored in d[], for degree n. exp Prototype sub function exp(dim x as real) as real Description The function returns the value of e — the base of natural logarithms — raised to the power x (i.e. ex). fabs Prototype sub function fabs(dim d as real) as real Description The function returns the absolute (i.e. positive) value of d. floor Prototype sub function floor(dim x as real) as real Description The function returns the value of parameter x rounded down to the nearest integer. frexp Prototype sub function frexp(dim value as real, dim byref eptr as integer) as real The function splits a floating-point value value into a normalized fraction and an Description integral power of 2. The return value is a normalized fraction and the integer exponent is stored in the object pointed to by eptr. ldexp Prototype sub function ldexp(dim value as real, dim newexp as integer) as real Description The function returns the result of multiplying the floating-point number value by 2 raised to the power newexp (i.e. returns value * 2newexp). log Prototype sub function log(dim x as real) as real Description The function returns the natural logarithm of x (i.e. loge(x)). MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 407 CHAPTER 6 mikroBasic for 8051 Libraries log10 Prototype sub function log10(dim x as real) as real Description The function returns the base-10 logarithm of x (i.e. log10(x)). modf Prototype sub function modf(dim val as real, dim byref iptr as real) as real Description The function returns the signed fractional component of val, placing its whole number component into the variable pointed to by iptr. pow Prototype sub function pow(dim x as real, dim y as real) as real Description The function returns the value of x raised to the power y (i.e. xy). If x is negative, the function will automatically cast y into longint. sin Prototype sub function sin(dim arg as real) as real Description The function returns the sine of arg in radians. The return value is from -1 to 1. sinh Prototype sub function sinh(dim x as real) as real Description The function returns the hyperbolic sine of x, defined mathematically as (ex-e-x)/2. If the value of x is too large (if overflow occurs), the function fails. sqrt Prototype sub function sqrt(dim x as real) as real Description The function returns the non negative square root of x. tan 408 Prototype sub function tan(dim x as real) as real Description The function returns the tangent of x in radians. The return value spans the allowed range of floating point in mikroBasic for 8051. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries tanh Prototype sub function tanh(dim x as real) as real) Description The function returns the hyperbolic tangent of x, defined mathematically as sinh(x)/cosh(x). MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 409 CHAPTER 6 mikroBasic for 8051 Libraries STRING LIBRARY The mikroBasic for 8051 includes a library which automatizes string related tasks. Library Functions - memchr memcmp memcpy memmove memset strcat strchr strcmp strcpy strlen strncat strncpy strspn strcspn strncmp strpbrk strrchr strstr memchr Prototype sub function memchr(dim p as word, dim ch as byte, dim n as word) as word The function locates the first occurrence of the word ch in the initial n words of memory area starting at the address p. The function returns the offset of this occurrence from the memory address p or 0xFFFF if ch was not found. Description For the parameter p you can use either a numerical value (literal/variable/constant) indicating memory address or a dereferenced value of an object, for example @mystring or @PORTB. 410 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries memcmp Prototype sub function memcmp(p1, p2, n as word) as integer The function returns a positive, negative, or zero value indicating the relationship of first n words of memory areas starting at addresses p1 and p2. This function compares two memory areas starting at addresses p1 and p2 for n words and returns a value indicating their relationship as follows: Value < 0 Description = 0 > 0 Meaning p1 "less than" p2 p1 "equal to" p2 p1 "greater than" p2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared. For parameters p1 and p2 you can use either a numerical value (literal/variable/constant) indicating memory address or a dereferenced value of an object, for example @mystring or @PORTB. memcpy Prototype Description sub procedure memcpy(p1, p2, nn as word) The function copies nn words from the memory area starting at the address p2 to the memory area starting at p1. If these memory buffers overlap, the memcpy function cannot guarantee that words are copied before being overwritten. If these buffers do overlap, use the memmove function. For parameters p1 and p2 you can use either a numerical value (literal/variable/constant) indicating memory address or a dereferenced value of an object, for example @mystring or @PORTB. memmove Prototype sub procedure memmove(p1, p2, nn as word) The function copies nn words from the memory area starting at the address p2 to the memory area starting at p1. If these memory buffers overlap, the Memmove function ensures that the words in p2 are copied to p1 before being overwritten. Description For parameters p1 and p2 you can use either a numerical value (literal/variable/constant) indicating memory address or a dereferenced value of an object, for example @mystring or @PORTB. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 411 CHAPTER 6 mikroBasic for 8051 Libraries memset Prototype sub procedure memset(dim p as word, dim character as byte, dim n as word) The function fills the first n words in the memory area starting at the address p with the value of word character. Description For parameter p you can use either a numerical value (literal/variable/constant) indicating memory address or a dereferenced value of an object, for example @mystring or @PORTB. strcat Prototype sub procedure strcat(dim byref s1, s2 as string[100]) Description The function appends the value of string s2 to string s1 and terminates s1 with a null character. strchr Prototype sub function strchr(dim byref s as string[100], dim ch as byte) as word The function searches the string s for the first occurrence of the character ch. The null character terminating s is not included in the search. Description The function returns the position (index) of the first character ch found in s; if no matching character was found, the function returns 0xFFFF. strcmp Prototype sub function strcmp(dim byref s1, s2 as string[100]) as integer The function lexicographically compares the contents of the strings s1 and s2 and returns a value indicating their relationship: Value < 0 Description = 0 > 0 Meaning s1 "less than" s2 s1 "equal to" s2 s1 "greater than" s2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared. 412 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries strcpy Prototype sub procedure strcpy(dim byref s1, s2 as string[100]) Description The function copies the value of the string s2 to the string s1 and appends a null character to the end of s1. strcspn Prototype sub function strcspn(dim byref s1, s2 as string[100]) as word The function searches the string s1 for any of the characters in the string s2. Description The function returns the index of the first character located in s1 that matches any character in s2. If the first character in s1 matches a character in s2, a value of 0 is returned. If there are no matching characters in s1, the length of the string is returned (not including the terminating null character). strlen Prototype sub function strlen(dim byref s as string[100]) as word Description The function returns the length, in words, of the string s. The length does not include the null terminating character. strncat Prototype sub procedure strncat(dim byref s1, s2 as string[100], dim size as byte) The function appends at most size characters from the string s2 to the string s1 Description and terminates s1 with a null character. If s2 is shorter than the size characters, s2 is copied up to and including the null terminating character. strncmp Prototype sub function strncmp(dim byref s1, s2 as string[100], dim len as byte) as integer The function lexicographically compares the first len words of the strings s1 and s2 and returns a value indicating their relationship: Value < 0 Description = 0 > 0 Meaning s1 "less than" s2 s1 "equal to" s2 s1 "greater than" s2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared (within first len words). MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 413 CHAPTER 6 Libraries mikroBasic for 8051 strncpy Prototype sub procedure strncpy(dim byref s1, s2 as string[100], dim size as byte) The function copies at most size characters from the string s2 to the string s1. Description If s2 contains fewer characters than size, s1 is padded out with null characters up to the total length of the size characters. strpbrk Prototype sub function strpbrk(dim byref s1, s2 as string[100]) as word The function searches s1 for the first occurrence of any character from the string s2. The null terminator is not included in the search. The function returns Description an index of the matching character in s1. If s1 contains no characters from s2, the function returns 0xFFFF. strrchr Prototype sub function strrchr(dim byref s as string[100], dim ch as byte) as word The function searches the string s for the last occurrence of the character ch. The null character terminating s is not included in the search. The function Description returns an index of the last ch found in s; if no matching character was found, the function returns 0xFFFF. strspn Prototype sub function strspn(dim byref s1, s2 as string[100]) as word The function searches the string s1 for characters not found in the s2 string. Description The function returns the index of first character located in s1 that does not match a character in s2. If the first character in s1 does not match a character in s2, a value of 0 is returned. If all characters in s1 are found in s2, the length of s1 is returned (not including the terminating null character). strstr Prototype sub function strstr( dim byref s1, s2 as string[100]) as word The function locates the first occurrence of the string s2 in the string s1 (excluding the terminating null character). Description The function returns a number indicating the position of the first occurrence of s2 in s1; if no string was found, the function returns 0xFFFF. If s2 is a null string, the function returns 0. 414 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries TIME LIBRARY The Time Library contains functions and type definitions for time calculations in the UNIX time format which counts the number of seconds since the "epoch". This is very convenient for programs that work with time intervals: the difference between two UNIX time values is a real-time difference measured in seconds. What is the epoch? Originally it was defined as the beginning of 1970 GMT. ( January 1, 1970 Julian day ) GMT, Greenwich Mean Time, is a traditional term for the time zone in England. The TimeStruct type is a structure type suitable for time and date storage. Library Routines - Time_dateToEpoch - Time_epochToDate - Time_datediff Time_dateToEpoch Prototype sub function Time_dateToEpoch(dim byref ts as TimeStruct) as longint Returns Number of seconds since January 1, 1970 0h00mn00s. This function returns the UNIX time : number of seconds since January 1, 1970 0h00mn00s. Description Parameters : - ts: time and date value for calculating UNIX time. Requires Nothing. Example dm ts1 as TimeStruct Epoch as longint ... ' what is the epoch of the date in ts ? epoch = Time_dateToEpoch(ts1) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 415 CHAPTER 6 mikroBasic for 8051 Libraries Time_epochToDate Prototype sub procedure Time_epochToDate(dim e as longint, dim byref ts as TimeStruct) Returns Nothing. Converts the UNIX time to time and date. Description Parameters : - e: UNIX time (seconds since UNIX epoch) - ts: time and date structure for storing conversion output Requires Nothing. Example dim ts2 as TimeStruct epoch as longint ... ' what date is epoch 1234567890 ? epoch = 1234567890 Time_epochToDate(epoch,ts2) Time_dateDiff Prototype sub function Time_dateDiff(dim t1 as ^TimeStruct, dim t2 as ^TimeStruct) as longint Returns Time difference in seconds as a signed long. This function compares two dates and returns time difference in seconds as a signed long. The result is positive if t1 is before t2, null if t1 is the same as t2 and negative if t1 is after t2. Description Parameters : - t1: time and date structure (the first comparison parameter) - t2: time and date structure (the second comparison parameter) 416 Requires Nothing. Example dim ts1, ts2 as TimeStruct diff as longint ... ' how many seconds between these two dates contained in ts1 and ts2 buffers? diff = Time_dateDiff(ts1, ts2) MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries Library Example Demonstration of Time library routines usage for time calculations in UNIX time format. program Time_Demo; {* * simple time structure *} type TimeStruct = record ss as byte ; ' seconds mn as byte ; ' minutes hh as byte ; ' hours md as byte ; ' day in month, from 1 to 31 wd as byte ; ' day in week, monday=0, tuesday=1, .... sunday=6 mo as byte ; ' month number, from 1 to 12 (and not from 0 to 11 as with UNIX C time !) yy as word ; ' year Y2K compliant, from 1892 to 2038 end; var ts1, ts2 : TimeStruct ; buf as array[256] of byte ; epoch, diff : longint ; ts1.ss ts1.mn ts1.hh ts1.md ts1.mo ts1.yy := := := := := := 0 ; 7 ; 17 ; 23 ; 5 ; 2006 ; {* * what is the epoch of the date in ts ? *} epoch := Time_dateToEpoch(ts1) ; ' epoch = 1148404020 {* * what date is epoch 1234567890 ? *} epoch := 1234567890 ; Time_epochToDate(epoch, ts2) ; ' ts2.ss := ' ts2.mn ' ts2.hh ' ts2.md ' ts2.wd ' ts2.mo ' ts2.yy 30 := := := := := := ; 31 ; 23 ; 13 ; 4 ; 2 ; 2009 ; MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 417 CHAPTER 6 mikroBasic for 8051 Libraries {* * how much seconds between this two dates ? *} diff := Time_dateDiff(ts1, ts2) ; ' diff = 86163870 end. TimeStruct type definition type TimeStruct = record ss as byte ; ' seconds mn as byte ; ' minutes hh as byte ; ' hours md as byte ; ' day in month, from 1 to 31 wd as byte ; ' day in week, monday=0, tuesday=1, .... sunday=6 mo as byte ; ' month number, from 1 to 12 (and not from 0 to 11 as with UNIX C time !) yy as word ; ' year Y2K compliant, from 1892 to 2038 end; 418 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic for 8051 Libraries TRIGONOMETRY LIBRARY The mikroBasic for 8051 implements fundamental trigonometry functions. These functions are implemented as look-up tables. Trigonometry functions are implemented in integer format in order to save memory. Library Routines - sinE3 - cosE3 sinE3 Prototype sub function sinE3(dim angle_deg as word) as integer Returns The function returns the sine of input parameter. The function calculates sine multiplied by 1000 and rounded to the nearest integer: result = round(sin(angle_deg)*1000) Description Parameters: angle_deg: input angle in degrees Note: Return value range: -1000..1000. Requires Nothing. Example dim res as integer ... res = sinE3(45) ' result is 707 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 419 CHAPTER 6 mikroBasic for 8051 Libraries cosE3 Prototype sub function cosE3(dim angle_deg as word) as integer Returns The function returns the cosine of input parameter. The function calculates cosine multiplied by 1000 and rounded to the nearest integer: result = round(cos(angle_deg)*1000) Description Parameters: angle_deg: input angle in degrees Note: Return value range: -1000..1000. 420 Requires Nothing. Example dim res as integer ... res = cosE3(196) ' result is -193 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Mouser Electronics Authorized Distributor Click to View Pricing, Inventory, Delivery & Lifecycle Information: mikroElektronika: MIKROE-406 MIKROE-720 ">
/
Download
Just a friendly reminder. You can view the document right here. But most importantly, our AI has already read it. It can explain complex things in simple terms, answer your questions in any language, and help you quickly navigate even the longest or most compilcated documents.
Advertisement
Key features
Intuitive development environment
Windows-based point-and-click interface
Broad set of built-in routines
Comprehensive Help system
Practical code examples
Software Simulator
Frequently asked questions
mikroBasic for 8051 is a BASIC compiler designed for developing applications for 8051 microcontrollers.
mikroBasic for 8051 provides implemented tools, many practical code examples, broad set of built-in routines, and a comprehensive Help.