Manual MiKrobasic Ingles
Manual MiKrobasic Ingles
April 2009.
DISCLAIMER:
Readers note
mikroBASIC PRO for PIC 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 PRO for PICcompiler 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 PRO for PIC compiler, you agree to the terms of this agreement. Only one person may use licensed version of mikroBASIC PRO for PIC compiler at a time. Copyright mikroElektronika 2003 - 2009. This manual covers mikroBASIC PRO for PIC version 1.0 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 PRO for PIC - 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.
ii
Table of Contents
CHAPTER 1 CHAPTER 2 CHAPTER 3 CHAPTER 4 CHAPTER 5 CHAPTER 6 CHAPTER 7 Introduction mikroBASIC PRO for PIC Environment mikroICD (In-Circuit Debugger) mikroBASIC PRO for PIC Specifics PIC Specifics mikroBASIC PRO for PIC Language Reference mikroBASIC PRO for PIC Libraries
iii
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 File Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Edit Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Find Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Replace Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Find In Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Go To Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Regular expressions option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 View Menu Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 File Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Edit Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Advanced Edit Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Find/Replace Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Project Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Build Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Build Toolbar come . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
iv
Table of Contents
Styles Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Tools Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Docking Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Saving Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Auto Hide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Advanced Code Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Advanced Editor Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Code Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Code Folding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Parameter Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Code Templates (Auto Complete) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Auto Correct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Spell Checker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Bookmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Bookmarks m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Goto Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Also, the Code Edito . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Code Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Routine List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Project Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Project Settings Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Library Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Error Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 STatisticS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Memory Usage Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 RAM Memory Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Used RAM Locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 SFR Locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
Table of Contents
ROM Memory Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 ROM Memory Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Functions Sorted By Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Functions Sorted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Sorts and displays functi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Functions Sorted By Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Functions Sorted By Name Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Sorts and displays functions by their names in a ch . . . . . . . . . . . . . . . 55 Functions Sorted By Size Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Functions Sorted By Addresses Chart . . . . . . . . . . . . . . . . . . . . . . . . . 56 Function Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Memory Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Displays summary of RAM and ROM m . . . . . . . . . . . . . . . . . . . . . . . . 57 Integrated Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 USART Terminal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 EEPROM Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 ASCII Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Seven Segment Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Lcd Custom Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 mikroBasic PRO for PIC includes the L . . . . . . . . . . . . . . . . . . . . . . . . 61 Graphic LCD Bitmap Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 HID Terminal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 The mikroBasic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Udp Terminal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 The mikroBasic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 mikroBootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 What is a Bootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Macro Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Code editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Output settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Simple matches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
vi
Table of Contents
Escape sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Character classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Metacharacters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Metacharacters - Line separators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Metacharacters - Predefined classes . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Metacharacters - Word boundaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Metacharacters - Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Metacharacters - Alternatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Metacharacters - Subexpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Metacharacters - Backreferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 mikroBasic PRO for PIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Command Line Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 New Project Wizard Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Customizing Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Managing Project Group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Add/Remove Files from Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Project Level Defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Managing Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Creating new source file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Opening an existing file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Printing an open file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Saving file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Saving file under a different name . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Closing file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Clean Project Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Output Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Assembly View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Compiler Error Messages: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Warning Messages: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Hint Messages: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Software Simulator Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
vii
Table of Contents
Breakpoints Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . View RAM Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Stopwatch Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Software Simulator Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating New Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Multiple Library Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . mikroICD (In-Circuit Debugger) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CHAPTER 3
mikroICD Debugger Optional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 mikroICD Debugger Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 mikroICD (In-Circuit Debugger) Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Breakpoints Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Watch Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Debugger Watch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 EEPROM Watch Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Code Watch Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 View RAM Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 mikro ICD Advanced Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Program Memory Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 File Register Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Emulator Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Event Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Stopwatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 CHAPTER 4 BASIC Standard Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Divergence from the Basic Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Basic Language Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Predefined Globals and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 SFRs and related constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 All PIC SFRs are implicitly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 These defines are based on a valu . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
viii
Table of Contents
Accessing Individual Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Accessing Individual Bits Of Variables . . . . . . . . . . . . . . . . . . . . . . . . . 114 sbit type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 bit type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Linker Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Directive absolute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Directive org . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Built-in Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Lo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Hi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Higher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Highest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Inc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Dec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Delay_us . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 Delay_ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 Clock_KHz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 Clock_MHz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 ClrWdt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 DisableContextSaving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 SetFuncCall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 GetDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 GetVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Code Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 Optimizer has been . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 CHAPTER 5 Types Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Nested call represents a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . PIC18FxxJxx Specifics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Shared Address SFRs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . PIC16 Specifics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Breaking Through Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 130 131 131 131 131
ix
Table of Contents
Limits of Indirect Approach Through FSR . . . . . . . . . . . . . . . . . . . . . . . 131 Memory Type Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 rx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 sfr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 CHAPTER 6 Lexical Elements Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Whitespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Newline Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Whitespace in Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Integer Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Floating Point Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Character Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Case Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Uniqueness and Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Identifier Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Punctuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Brackets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Comma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Colon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Program Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Organization of Main Unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Organization of Other Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Scope and Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Table of Contents
Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 mikroBasic PRO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Main Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Every project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Modules other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Implementation Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 External Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Variables and PIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Calling a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Calling a procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Function Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Forward declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Functions reentrancy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 Type Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 Simple Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 Array Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 Constant Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 POINTERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Structure Member Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 Types Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Implicit Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Promotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
xi
Table of Contents
Clipping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Explicit Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Operators Precedence and Associativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 Division by Zero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 Unary Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Relational Operators in Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Bitwise Operators Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Unsigned and Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 Signed and Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 Bitwise Shift Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 BoOlean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Nested if statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 SELECT Case statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 Iteration Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 For Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 Endless Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 While Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Do Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 The do stateme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Jump Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Break and Continue Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Exit Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 Goto Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Gosub Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 asm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
xii
Table of Contents
Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 Compiler Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 Directives #DEFINE and #UNDEFINE . . . . . . . . . . . . . . . . . . . . . . . . . 193 Directives #IFDEF, $IFNDEF, #ELSEIF and #ELSE . . . . . . . . . . . . . . 194 Predefined Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Linker Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Directive absolute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Directive org . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 CHAPTER 7 Hardware PIC-specific Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Miscellaneous Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Library Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 Hardware Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 ADC Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 ADC_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 CAN Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 CANSetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 CANGetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 CANInitialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 CANSetBaudRate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 CANSetMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 CANSetFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 CANRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 CANWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 CAN Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 CAN_OP_MODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 CAN_CONFIG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 CAN_TX_MSG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 CAN_RX_MSG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
xiii
Table of Contents
CAN_MASK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 CAN_FILTER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 CANSPI Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 External dependecies of CANSPI Library . . . . . . . . . . . . . . . . . . . . . . . 220 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPISetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPIGetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPIInitialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPISetBaudRate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPISetMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPISetFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPIread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPIWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 CANSPISetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 CANSPIGetOperationMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 CANSPIInitialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 CANSPISetBaudRate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 CANSPISetMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 CANSPISetFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 CANSPIRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 CANSPIWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 CANSPI Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 CANSPI_OP_MODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 CANSPI_CONFIG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 CANSPI_TX_MSG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 CANSPI_RX_MSG_FLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 CANSPI_MASK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 CANSPI_FILTER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Compact Flash Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 External dependencies of Compact Flash Library . . . . . . . . . . . . . . . . 236 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Cf_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
xiv
Table of Contents
240 240 240 241 241 242 242 243 243 244 244 245 246 246 247 247 248 248 249 250 250 251 253 258 259 259 259 260 260 263 264 265 266 267 268 268
Cf_Detect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Disable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Read_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Read_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Write_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Write_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Read_Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Write_Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_QuickFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Assign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Rewrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Append . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Set_File_Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Get_File_Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Get_File_Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cf_Fat_Get_Swap_File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . EEPROM Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . EEPROM_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . EEPROM_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ethernet_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ethernet_Enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ethernet_Disable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ethernet_doPacket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ethernet_putByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ethernet_putBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xv
Table of Contents
Ethernet_putConstBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 Ethernet_putString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 Ethernet_putConstString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Ethernet_getByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Ethernet_getBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Ethernet_UserTCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 Ethernet_UserUDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Ethernet_getIpAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Ethernet_getGwIpAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Ethernet_getDnsIpAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Ethernet_getIpMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Ethernet_confNetwork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Ethernet_arpResolve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Ethernet_sendUDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 Ethernet_dnsResolve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Ethernet_initDHCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Ethernet_doDHCPLeaseTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 Ethernet_renewDHCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 Flash Memory Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 FLASH_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 FLASH_Read_N_Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 FLASH_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292 FLASH_Erase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 FLASH_Erase_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 External dependencies of Graphic LCD Library . . . . . . . . . . . . . . . . . . 296 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 Glcd_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 Glcd_Set_Side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 Glcd_Set_X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 Glcd_Set_Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 Glcd_Read_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 Glcd_Write_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
xvi
Table of Contents
Glcd_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 Glcd_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Glcd_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Glcd_V_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Glcd_H_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Glcd_Rectangl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 Glcd_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 Glcd_Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Glcd_Set_Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Glcd_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 Glcd_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 Glcd_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Glcd HW connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 IC Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 2C1_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 I2C1_Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 I2C1_Repeated_Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 I2C1_Is_Idle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 I2C1_Rd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 I2C1_Wr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 I2C1_Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Keypad Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 External dependencies of Keypad Library . . . . . . . . . . . . . . . . . . . . . . . 316 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Keypad_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Keypad_Key_Press . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Keypad_Key_Click . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Keypad_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Keypad_Key_Press . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 Keypad_Key_Click . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
xvii
CHAPTER 7
Libraries
mikroBasic PRO for PIC HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 External dependencies of LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . 321 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Lcd_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Lcd_Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Lcd_Out_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Lcd_Chr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 Lcd_Chr_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 Lcd_Cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Available LCD Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 LCD HW connecti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 Manchester Code Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 External dependencies of Manchester Code Library . . . . . . . . . . . . . . 329 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 Man_Receive_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 Man_Receive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 Man_Send_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 Man_Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 Man_Synchro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 Man_Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 Connection Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 Multi Media Card Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 External dependencies of MMC Library . . . . . . . . . . . . . . . . . . . . . . . . 339 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Mmc_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Mmc_Read_Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Mmc_Write_Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Mmc_Read_Cid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Mmc_Read_Csd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Routines for file handling: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Mmc_Fat_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Mmc_Fat_QuickFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
xviii
Table of Contents
339 339 339 339 339 339 339 339 339 339 339 340 341 342 343 343 344 345 346 347 347 348 348 349 349 350 351 352 352 354 357 358 358 358 358 358
Mmc_Fat_Assign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Rewrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Append . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Set_File_Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Get_File_Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Get_File_Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Get_Swap_File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Read_Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Write_Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Read_Cid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Read_Csd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_QuickFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Assign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Rewrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Append . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Set_File_Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Get_File_Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Get_File_Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmc_Fat_Get_Swap_File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . OneWire Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ow_Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ow_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ow_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xix
Table of Contents
Ow_Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Ow_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Ow_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 Port Expander Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 External dependencies of Port Expander Library . . . . . . . . . . . . . . . . . 363 Library Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Read_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Write_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Read_PortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Read_PortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Read_PortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Write_PortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Write_PortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Write_PortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Set_DirectionPortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Set_DirectionPortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Set_DirectionPortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Set_PullUpsPortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Set_PullUpsPortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Set_PullUpsPortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Expander_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364 Expander_Read_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 Expander_Write_Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 Expander_Read_PortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 Expander_Read_PortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 Expander_Read_PortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Expander_Write_PortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Expander_Write_PortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 Expander_Write_PortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 Expander_Set_DirectionPortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Expander_Set_DirectionPortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Expander_Set_DirectionPortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 Expander_Set_PullUpsPortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
xx
Table of Contents
Expander_Set_PullUpsPortB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 Expander_Set_PullUpsPortAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 PS/2 Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 External dependencies of PS/2 Library . . . . . . . . . . . . . . . . . . . . . . . . . 374 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 Ps2_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 Ps2_Key_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 Ps2_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 Ps2_Key_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 Special Function Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 PWM Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380 PWM1_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380 PWM1_Set_Duty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 PWM1_Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 PWM1_Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383 RS-485 Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 External dependencies of RS-485 Library . . . . . . . . . . . . . . . . . . . . . . . 384 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 RS485master_Receive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 RS485master_Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 RS485slave_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387 RS485slave_Receive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388 RS485slave_Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 Software IC Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 External dependecies of Soft_I2C Library . . . . . . . . . . . . . . . . . . . . . . . 394 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 Soft_I2C_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
xxi
Table of Contents
Soft_I2C_Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 Soft_I2C_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 Soft_I2C_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 Soft_I2C_Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Soft_I2C_Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 LLibrary Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 Software SPI Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 External dependencies of Software SPI Library . . . . . . . . . . . . . . . . . . 401 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 Soft_Spi_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 Soft_Spi_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 Soft_Spi_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 Software UART Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 Soft_Uart_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 Soft_UART_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 Soft_Uart_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 Soft_UART_Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 Sound Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 Sound_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 Sound_Play . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 Sound_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 Sound_Play . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 The example is a simple dem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 Example of Sound Library sonnection . . . . . . . . . . . . . . . . . . . . . . . . . . 413 SPI Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 SPI1_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 _LOW_2_HIGH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 _CLK_IDLE_LOW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 _CLK_IDLE_HIGH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
xxii
Table of Contents
_DATA_SAMPLE_END . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 _DATA_SAMPLE_MIDDLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 _SLAVE_SS_ENABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 _MASTER_TMR2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 _MASTER_OSC_DIV64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 _MASTER_OSC_DIV16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 _MASTER_OSC_DIV4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 Spi1_Init_Advanced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 Spi1_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 Spi1_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 SPI_Set_Active . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 The code demonstrates how to u . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418 SPI HW connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418 SPI Ethernet Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 SPI_Ethernet_RST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 SPI_Ethernet_CS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 External dependencies of SPI Ethernet Library . . . . . . . . . . . . . . . . . . 420 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 SPI_Ethernet_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 SPI_Ethernet_Enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423 SPI_Ethernet_Disable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424 SPI_Ethernet_doPacket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 SPI_Ethernet_putByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 SPI_Ethernet_putBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 SPI_Ethernet_putConstBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 SPI_Ethernet_putString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 SPI_Ethernet_putConstString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 SPI_Ethernet_getByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 SPI_Ethernet_getBytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 SPI_Ethernet_UserTCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430 SPI_Ethernet_UserUDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 SPI Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
xxiii
Table of Contents
External dependencies of SPI Graphic LCD Library . . . . . . . . . . . . . . . 440 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440 SPI_Glcd_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 SPI_Glcd_Set_Side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442 SPI_Glcd_Set_Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442 SPI_Glcd_Set_X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 SPI_Glcd_Read_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 SPI_Glcd_Write_Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 SPI_Glcd_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 SPI_Glcd_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 SPI_Glcd_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 SPI_Glcd_V_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 SPI_Glcd_H_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 SPI_Glcd_Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 SPI_Glcd_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 SPI_Glcd_Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 SPI_Glcd_Set_Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449 SPI_Glcd_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450 SPI_Glcd_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451 SPI_Glcd_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454 SPI LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 External dependencies of SPI LCD Library . . . . . . . . . . . . . . . . . . . . . . 455 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 SPI_Lcd_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 SPI_Lcd_Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 SPI_Lcd_Out_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 SPI_Lcd_Chr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 SPI_Lcd_Chr_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458 SPI_Lcd_Cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458 Available LCD Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 SPI LCD8 (8-bit interface) Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462 External dependencies of SPI LCD Library . . . . . . . . . . . . . . . . . . . . . . 462
xxiv
Table of Contents
Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462 SPI_Lcd8_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 SPI_Lcd8_Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 SPI_Lcd8_Out_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464 SPI_Lcd8_Chr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464 SPI_Lcd8_Chr_Cp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 SPI_Lcd8_Cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 Available LCD Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468 SPI T6963C Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469 External dependencies of SPI T6963C Graphic Lcd Library . . . . . . . . 469 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470 SPI_T6963C_Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 SPI_T6963C_WriteData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 SPI_T6963C_WriteCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 SPI_T6963C_SetPtr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 SPI_T6963C_WaitReady . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 SPI_T6963C_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 SPI_T6963C_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474 SPI_T6963C_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475 SPI_T6963C_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 SPI_T6963C_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 SPI_T6963C_Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 SPI_T6963C_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478 SPI_T6963C_Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478 SPI_T6963C_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 SPI_T6963C_Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 SPI_T6963C_Set_Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 SPI_T6963C_ClearBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 SPI_T6963C_SetBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 SPI_T6963C_NegBit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 SPI_T6963C_DisplayGrPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 SPI_T6963C_DisplayTxtPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 SPI_T6963C_SetGrPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482 SPI_T6963C_SetTxtPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482 MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
xxv
Table of Contents
mikroBasic PRO for PIC 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483 483 483 484 484 484 485 485 485 490
T6963C Graphic LCD Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 External dependencies of T6963C Graphic LCD Library . . . . . . . . . . . 491 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492 T6963C_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492 T6963C_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 T6963C_WriteData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494 T6963C_WriteCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494 T6963C_SetPtr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 T6963C_WaitReady . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 T6963C_Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 T6963C_Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 T6963C_Write_Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 T6963C_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498 T6963C_Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 T6963C_Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 T6963C_Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500 T6963C_Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500 T6963C_Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 T6963C_Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 T6963C_Set_Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502 T6963C_DisplayGrPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502 T6963C_DisplayTxtPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502 T6963C_SetGrPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 T6963C_SetTxtPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 T6963C_PanelFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
xxvi
Table of Contents
504 504 505 505 505 506 506 506 512 513 513 513 513 514 514 515 515 516 516 517 517 518 518 518 519 519 519 519 520 520 520 521 523 524 524 524
T6963C_GrFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . T6963C_TxtFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . T6963C_Cursor_Height . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . T6963C_Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . T6963C_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . T6963C_Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . T6963C_Cursor_Blink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Data_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Data_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Tx_Idle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Read_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART1_Write_Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART_Set_Active . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UART HW connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . USB HID Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Descriptor File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Hid_Enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Hid_Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Hid_Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Hid_Disable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HW Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Miscellaneous Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Button Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Button libra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xxvii
Table of Contents
mikroBasic PRO for PIC 525 525 526 526 527 527 528 528 529 530 530 530 531 531 532 532 533 533 533 533 533 533 533 534 534 534 534 534 534 534 535 535 535 535 535 535
Conversions Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ByteToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ShortToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . WordToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IntToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . LongintToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . LongWordToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . FloatToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . StrToInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . StrToWord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dec2Bcd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bcd2Dec16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dec2Bcd16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . acos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . asin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . atan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . atan2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ceil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . eval_poly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . fabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . floor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . frexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ldexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . log10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . modf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xxviii
Table of Contents
tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535 tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535 String Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536 Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536 memchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537 memcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537 memcpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 memmove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 memset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 strcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 strchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 strcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 strcpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 strcspn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 strlen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 strncat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 strncmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 strncpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 strpbrk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 strrchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541 strspn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541 strstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541 Time Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542 Time_dateToE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542 Time_epochToDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543 Time_dateDiff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543 Library Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544 TimeStruct type definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545 Trigonometry Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 Library Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 sinE3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 cosE3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
xxix
Table of Contents
xxx
CHAPTER
CHAPTER 1
Introduction
Features
mikroBasic PRO for PIC allows you to quickly develop and deploy complex applications: Write your Basic source code using the built-in Code Editor (Code and Parame ter Assistants, Code Folding, Syntax Highlighting, Spell Checker, Auto Correct, Code Templates, and more.) Use included mikroBasic PRO libraries to dramatically speed up the develop ment: 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 compati ble with all programmers. Use the integrated mikroICD (In-Circuit Debugger) Real-Time debugging tool to monitor program execution on the hardware level. Inspect program flow and debug executable logic with the integrated Software Simulator. Get detailed reports and graphs: RAM and ROM map, code statistics, assembly isting, calling tree, and more. mikroBasic PRO for PIC provides plenty of examples to expand, develop, and use as building bricks in your projects. Copy them entirely if you deem fit thats why we included them with the compiler.
Introduction
Where to Start
In case that youre a beginner in programming PIC microcontrollers, read carefully th PIC Specifics chapter. It might give you some useful pointers on PIC constraints, code portability, and good programming practices. If you are experienced in Basic programming, you will probably want to con sult mikroBasic PRO for PIC Specifics first. For language issues, you can always refer to the comprehensive Language Reference. A complete list of included libraries is available at mikroBasic PRO for PIC Libraries. If you are not very experienced in Basic programming, dont panic! mikroBa sic PRO for PIC 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.
CHAPTER 1
Introduction
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
CHAPTER 1
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]
Introduction
TECHNICAL SUPPORT
In case you encounter any problem, you are welcome to our support forums at www.mikroe.com/forum/. Here, you may also find helpful information, hardware tips, and practical code snippets. Your comments and suggestions on future development of the mikroBasic PRO for PIC 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
CHAPTER 1
Introduction
How to Register
The latest version of the mikroBasic PRO for PIC 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 PRO for PIC, then you should consider the possibility of purchasing the license key.
Introduction
This will start your e-mail client with message ready for sending. Review the information you have entered, and add the comment if you deem it necessary. Please, do not modify the subject line. Upon receiving and verifying your request, we will send the license key to the e-mail address you specified in the form.
CHAPTER 1
Introduction
After Receving the License Key
The license key comes as a small autoextracting file just start it anywhere on your computer in order to activate your copy of compiler and remove the demo limit. You do not need to restart your computer or install any additional components. Also, there is no need to run the mikroBasic PRO for PIC at the time of activation. Notes: The license key is valid until you format your hard disk. In case you need to for mat 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
CHAPTER
11
CHAPTER 2
The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Spell Checker, Auto Correct for com mon typos and Code Templates (Auto Complete). The Code Explorer 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 PRO for PIC to suit your needs best.
12
Environment
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).
13
CHAPTER 2
14
Environment
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.
15
CHAPTER 2
Description
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
16
CHAPTER 2 mikroBasic PRO for PIC 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.
Environment
Find Text
Dialog box for searching the document for the specified text. The search is performed in the direction specified. If the string is not found a message is displayed.
17
CHAPTER 2
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.
18
Environment
Go To Line
Dialog box that allows the user to specify the line number at which the cursor should be positioned.
19
CHAPTER 2
File
Description Show/Hide toolbars. Show/Hide Software Simulator/mikroICD (In-Circuit Debugger) 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
Environment
TOOLBARS
File Toolbar
File Toolbar is a standard toolbar with following options: Icon 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. Description
Edit Toolbar
Edit Toolbar is a standard toolbar with following options: Icon Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard. Paste text from clipboard. Description
21
CHAPTER 2
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 Find text in current editor. Find next occurence. Find previous occurence. Replace text. Find text in files. Description
22
Environment
Project Toolbar
Project Toolbar comes with following options: Icon New project Open Project Save Project Close current project Edit project settings. Add existing project to project group. Remove existing project from project group Add File To Project Remove File From Project Description
Build Toolbar
Build Toolbar comes with following options: Icon Build current project. Build all opened projects. Build and program active project. Start programmer and load current HEX file. Open assembly code in editor. Open listing file in editor. View statistics for current project. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Description
23
CHAPTER 2
Environment
Debugger
Debugger Toolbar comes with following options: Icon Description Start Software Simulator or mikro ICD (In-Circuit Debugger). Run/Pause debugger. Stop debugger. Step into. Step over. Step out. Run to cursor. Toggle breakpoint. Toggle breakpoints. Clear breakpoints. View watch window View stopwatch window
Styles Toolbar
24
Environment
Tools Toolbar
Tools Toolbar comes with following default options: Icon Run USART Terminal EEPROM ASCII Chart Seven segment decoder tool. Optiions menu The Tools toolbar can easily be customized by adding new tools in Options(F12) window. Related topics: Keyboard shortcuts, Integrated Tools, Debugger Windows Description
25
CHAPTER 2
26
CHAPTER 2 mikroBasic PRO for PIC 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. Edit project settings 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
Environment
27
CHAPTER 2
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.
28
Environment
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. Run Lcd custom character Run Glcd bitmap editor Run HID Terminal Run UDP communication terminal Run mikroBootloader Open Options window
Related topics: Keyboard shortcuts, Tools Toolbar MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
29
CHAPTER 2
Help
Description Open Help File. Open Code Migration Document. 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.
30
Environment
KEYBOARD SHORTCUTS
Below is a complete list of keyboard shortcuts available in mikroBasic PRO for PIC IDE. You can also view keyboard shortcuts in the Code Explorer window, tab Keyboard. IDE Shortcuts F1 Ctrl+N Ctrl+O Ctrl+Shift+O Ctrl+Shift+N Ctrl+K Ctrl+Shift+E Ctrl+F9 Shift+F9 Ctrl+F11 Shift+F4 Help New Unit Open Open Project Open New Project Close Project Edit Project Compile Compile All Compile and Program View breakpoints Ctrl+X Ctrl+Y Ctrl+Z Ctrl+Shift+Z Cut Delete entire line Undo Redo
Advanced Editor Shortcuts Ctrl+Space Ctrl+Shift+Space Ctrl+D Ctrl+E Ctrl+L Ctrl+G Ctrl+J Ctrl+Shift+. Ctrl+Shift+, Ctrl+number Code Assistant Parameters Assistant Find declaration Incremental Search Routine List Goto line Insert Code Template Comment Code Uncomment Code Goto bookmark
Ctrl+Shift+F5 Clear breakpoints F11 F12 Start PICFlash Programmer Preferences Basic Editor Shortcuts F3 Shift+F3 Alt+F3 Ctrl+A Ctrl+C Ctrl+F Ctrl+R Ctrl+P Ctrl+S Ctrl+Shift+S Ctrl+V Find, Find Next Find Previous Grep Search, Find in Files Select All Copy Find Replace Print Save unit Save All Paste
Ctrl+Shift+number Set bookmark Ctrl+Shift+I Ctrl+Shift+U TAB Shift+TAB Alt+Select Ctrl+Alt+Select Ctrl+Alt+L Ctrl+Alt+U Ctrl+Alt+T Indent selection Unindent selection Indent selection Unindent selection Select columns Select columns Convert selection to lowercase Convert selection to uppercase Convert to Titlecase
31
CHAPTER 2
Environment
mikroICD Debugger and Software Simulator Shortcuts F2 F4 F5 F6 F7 F8 F9 Ctrl+F2 Ctrl+F5 Ctrl+F8 Alt+D Shift+F5 Ctrl+Shift+A Jump To Interrupt Run to Cursor Toggle Breakpoint Run/Pause Debugger Step into Step over Debug Reset Add to Watch List Step out Dissasembly view Open Watch Window Show Advanced Breakpoints
32
Environment
IDE OVERVIEW
The mikroBasic PRO for PIC 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 com mon typos and Code Templates (Auto Complete). The Code Explorer 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.
33
CHAPTER 2
Environment
mikroBasic PRO for PIC Like in any modern Windows application, you may customize the layout of mikroBacic for PIC 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).
34
Environment
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.
35
CHAPTER 2
Environment
mikroBasic PRO for PIC 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 the Set Layout Icon . . . To set the layout select the desired layout from the layout drop-down list and click To remove the layout from the drop-down list, select the desired layout from the list and click the Delete Layout Icon
36
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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
37
CHAPTER 2
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.
38
Environment
39
CHAPTER 2
Environment
Code Assistant
If you type the first few letters of a word and then press Ctrl+Space, all valid identifiers matching the letters you have typed will be prompted in a floating panel (see the image below). Now you can keep typing to narrow the choice, or you can select one from the list using the keyboard arrows and Enter.
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.
40
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.
41
CHAPTER 2
Environment
mikroBasic PRO for PIC These macros can be used in template code, see template ptemplate provided with mikroBasic PRO for PIC 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 the Code Toolbar. and Uncomment Icon from
Spell Checker
The Spell Checker underlines unknown objects in the code, so they can be easily noticed and corrected before compiling your project. Select Tools Options from the drop-down menu, or click the Show Options Icon and then select the Spell Checker Tab.
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 ment Icon from the Code Toolbar. and Uncom-
42
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.
43
CHAPTER 2
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.
44
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.
45
CHAPTER 2
Environment
Icon 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. Description
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
46
Environment
47
CHAPTER 2
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.
48
Environment
Description Refresh Library by scanning files in "Uses" folder.Useful when new libraries are added by copying files to "Uses" folder. Rebuild all available libraries. Useful when library sources are available and need refreshing. Include all available libraries in current project. No libraries from the list will be included in current project. Restore library to the state just before last project saving.
Icon
Related topics: mikroBasic PRO for PIC Libraries, Creating New Library
49
CHAPTER 2
In case that errors were encountered during compiling, the compiler will report them and wont 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
50
Environment
STATISTICS
After successful compilation, you can review statistics of your code. Click the Statistics Icon .
51
CHAPTER 2
Environment
Used RAM Locations
Displays used RAM memory locations and their names.
SFR Locations
Displays list of used SFR locations.
52
Environment
53
CHAPTER 2
Environment
Functions Sorted By Name
Sorts and displays functions by their addresses, symbolic names, and unique assembler names.
54
Environment
55
CHAPTER 2
Environment
Functions Sorted By Size Chart
Sorts and displays functions by their sizes in a chart-like form
56
Environment
Function Tree
Displays Function Tree with the relevant data for each function.
Memory Summary
Displays summary of RAM and ROM memory in a pie-like form.
57
CHAPTER 2
The mikroBasic PRO for PIC 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.
58
Environment
EEPROM Editor
The EEPROM Editor is used for manipulating MCU's EEPROM memory. You can launch it from the drop-down menu Tools EEPROM Editor. When Use this EEPROM definition is checked compiler will generate Intel hex file project_name.ihex that contains data from EEPROM editor. When you run mikroElektronika programmer software from mikroBasic PRO for PIC IDE - project_name.hex file will be loaded automatically while ihex file must be loaded manually.
59
CHAPTER 2
Environment
ASCII Chart
The ASCII Chart is a handy tool, particularly useful when working with Lcd display. You can launch it from the drop-down menu Tools ASCII chart or by clicking the View ASCII Chart Icon from Tools toolbar.
60
Environment
61
CHAPTER 2
Environment
Graphic LCD Bitmap Editor
The mikroBasic PRO for PIC includes the Graphic Lcd Bitmap Editor. Output is the mikroBasic PRO for PIC compatible code. You can launch it from the drop-down menu Tools Glcd Bitmap Editor.
62
Environment
HID Terminal
The mikroBasic PRO for PIC includes the HID communication terminal for USB communication. You can launch it from the drop-down menu Tools HID Terminal.
63
CHAPTER 2
Environment
Udp Terminal
The mikroBasic PRO for PIC includes the UDP Terminal. You can launch it from the drop-down menu Tools UDP Terminal.
64
Environment
MIKROBOOTLOADER
What is a Bootloader
(From Microchips document AN732) The PIC16F87X family of microcontrollers has the ability to write to their own program memory. This feature allows a small bootloader program to receive and write new firmware into memory. In its most simple form, the bootloader starts the user code running, unless it finds that new firmware should be downloaded. If there is new firmware to be downloaded, it gets the data and writes it into program memory. There are many variations and additional features that can be added to improve reliability and simplify the use of the bootloader. Note: mikroBootloader can be used only with PIC MCUs that support flash write.
65
CHAPTER 2
Environment
Features
The boot code gives the computer 5 seconds to get connected to it. If not, it starts running the existing user code. If there is a new user code to be downloaded, the boot code receives and writes the data into program memory. The more common features a bootloader may have are listed below: Code at the Reset location. Code elsewhere in a small area of memory. Checks to see if the user wants new user code to be loaded. Starts execution of the user code if no new user code is to be loaded. Receives new user code via a communication channel if code is to be loaded. Programs the new user code into memory.
66
Environment
Macro Editor
A macro is a series of keystrokes that have been 'recorded' in the order performed. A macro allows you to 'record' a series of keystrokes and then 'playback', or repeat, the recorded keystrokes.
The Macro offers the following commands: Icon Description Starts 'recording' keystrokes for later playback. Stops capturing keystrokesthat was started when the Start Recordig command was selected. Allows a macro that has been recorded to be replayed. New macro. Delete macro. Related topics: Advanced Code Editor, Code Templates
67
CHAPTER 2
Environment
Options
Options menu consists of three tabs: Code Editor, Tools and Output settings
Code editor
The Code Editor is advanced text editor fashioned to satisfy needs of professionals.
Tools
The mikroBasic PRO for PIC 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.
68
Environment
Output settings
By modifying Output Settings, user can configure the content of the output files. You can enable or disable, for example, generation of ASM and List file. Also, user can choose optimization level, and compiler specific settings, which include case sensitivity, dynamic link for string literals setting (described in mikroBasic PRO for PIC specifics). Build all files as library enables user to use compiled library (*.mcl) on any PIC MCU (when this box is checked), or for a selected PIC MCU (when this box is left unchecked). For more information on creating new libraries, see Creating New Library.
69
CHAPTER 2
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 :
unsigned matches string 'unsigned' \^unsigned matches string '^unsigned'
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 \t \n \r \f \a \e
for Unicode) - tab (HT/TAB), same as \x09 - newline (NL), same as \x0a - car.return (CR), same as \x0d - form feed (FF), same as \x0c - alarm (bell) (BEL), same as \x07 - escape (ESC) , same as \x1b
70
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.
71
CHAPTER 2
Environment
Metacharacters - Line separators
^ - start of line $ - end of line \A - start of text \Z - end of text . - any character in line
Examples:
^PORTA - matches string ' PORTA ' only if it's at the beginning of line PORTA$ - matches string ' PORTA ' only if it's at the end of line ^PORTA$ - matches string ' PORTA ' only if it's the only string in line PORT.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/ ):
an alphanumeric character (including "_") a nonalphanumeric a numeric character a non-numeric any space (same as [\t\n\r\f]) a non space
Example:
routi\de - matches strings like 'routi1e', 'routi6e' and so on, but not 'routine', 'routime' and so on.
72
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.
73
CHAPTER 2
Environment
Examples:
'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'.
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'.
74
Environment
Metacharacters - Subexpressions
The bracketing construct ( ... ) may also be used for define regular subexpressions. Subexpressions are numbered based on the left to right order of their opening parenthesis. First subexpression has number '1' Examples:
(int){8,10} matches strings which contain 8, 9 or 10 instances of the 'int' routi([0-9]|a+)e matches 'routi0e', 'routi1e' , 'routine', 'routinne', 'routinnne' etc.
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
75
CHAPTER 2
Environment
76
Environment
PROJECTS
The mikroBasic PRO for PIC organizes applications into projects, consisting of a single project file (extension .mcpav) and one or more source files (extension ). mikroBasic PRO for PIC 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, device flags (config word), device clock, list of the project source files with paths, 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 Project Toolbar.
77
CHAPTER 2
Environment
New Project Wizard Steps
Start creating your New project, by clicking Next button:
Step One - Select the device from the device drop-down list.
78
CHAPTER 2 mikroBasic PRO for PIC Step Two- enter the oscillator frequency value.
Environment
Step Three - Specify the location where your project will be saved.
79
CHAPTER 2
Environment
mikroBasic PRO for PIC Step Four - Add project file to the project if they are avaiable at this point. You can always add project files later using Project Manager.
80
Environment
CUSTOMIZING PROJECTS
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. Also, you can change configuration bits of the selected chip in the Edit Project window.
image files
.hex, .asm and .lst files, see output files. These files can not be added
81
CHAPTER 2
Environment
The list of relevant source files is stored in the project file (extension .mbpav). To add source file to the project, click the Add File to Project Icon Each added source file must be self-contained, i.e. it must have all necessary definitions after preprocessing. To remove file(s) from the project, click the Remove File from Project Icon Note: For inclusion of the module files, use the include clause. See File Inclusion for more information.
There are some predefined project level defines. See predefined project level defines Related topics: Project Manager, Project Settings
82
Environment
SOURCE FILES
Source files containing Basic code should have the extension .mbas. The list of source files relevant to the application is stored in project file with extension .mbpav, along with other project information. You can compile source files only if they are part of the project.
83
CHAPTER 2
Environment
Saving file
1. Make sure that the window containing the file that you want to save is the active window. 2. Select File Save from the drop-down menu, or press Ctrl+S, or click the Save File Icon from the File Toolbar.
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,
84
Environment
85
CHAPTER 2
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 PRO for PIC will generate output files.
Output Files
Upon successful compilation, the mikroBasic PRO for PIC will generate output files in the project folder (folder which contains the project file .mbpav). Output files are summarized in the table below: Format Intel HEX Binary List File Assembler File Description Intel style hex records. Use this file to program PIC MCU mikro Compiled Library. Binary distribution of application that can be included in other projects. Overview of PIC memory allotment: instruction addresses, registers, routines and labels. Human readable assembly with symbolic names, extracted from the List File. File Type
.hex .mcl .lst .asm
Assembly View
After compiling the program in the mikroBasic PRO for PIC, 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
86
Environment
ERROR MESSAGES
Compiler Error Messages:
"%s" is not valid identifier. Unknown type "%s". IIdentifier "%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. Actual 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
87
CHAPTER 2
Environment
mikroBasic PRO for PIC Operator "%s" not applicable to these operands "%s". Exit cannot be called from the main block. Complex type parameter must be passed by reference. Error occured while compiling "%s". Recursive types are not allowed. Adding strings is not allowed, use "strcat" procedure instead. Cannot declare pointer to array, use pointer to structure which has array field. Return value of the function "%s" is not defined. 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. Destination size ("%s") does not match source size ("%s"). Routine prototype is different from previous declaration. Division by zero. Uart module cannot be initialized with selected baud rate/device clock. "%s" cannot be of "%s" type. Array of "%s" can not be declared. Incomplete variable declaration: "%s". Recursive build of units is not allowed (""%s""). Object must be smaller than 64kb in size: ""%s"". Index out of bounds. With statment cannot be used with this argument ""%s"". Reset directive is available only on P18 family.
88
Environment
Warning Messages:
Variable "%s" is not initialized. Return value of the function "%s" is not defined. Identifier "%s" overrides declaration in unit "%s". Generated baud rate is %s bps (error = %s percent). Result size may exceed destination array size. Infinite loop. Implicit typecast performed from "%s" to "%s". Implicit typecast of integral value to pointer. Library "%s" was not found in search path. Interrupt context saving has been turned off. Source size (%s) does not match destination size (%s). Aggregate padded with zeros (%s) in order to match declared size (%s). Suspicious pointer conversion. Source size may exceed destination size.
Hint Messages:
Constant "%s" has been declared, but not used. Variable "%s" has been declared, but not used. Unit "%s" has been recompiled. Variable "%s" has been eliminated by optimizer. Compiling unit "%s".
89
CHAPTER 2
The Source-level Software Simulator is an integral component of the mikroBasic PRO for PIC environment. It is designed to simulate operations of the PIC MCUs and assist the users in debugging Basic code written for these devices. Upon completion of writing your program, choose Release build Type in the Project Settings window:
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 Simulator 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 doesnt update timers, interrupt flags, etc.
Breakpoints Window
The Breakpoints window manages the list of currently set breakpoints in the project. Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code.
90
Environment
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 Butto . 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 . Viables can also be removed from the Watch window, just select the vari able that you want to remove and then click the Remove Button . Add All Button Remove All Button adds all variables. removes all variables.
You can also expand/collapse complex variables, i.e. struct type variables, strings... Values are updated as you go through the simulation. Recently changed items are colored red. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
91
CHAPTER 2
Environment
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.
92
Environment
93
CHAPTER 2
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.
94
Environment
Run or pause Software Simulator. Stop Software Simulator. Toggle breakpoint at the current cursor position. To view all breakpoints, select Run > View Breakpoints from the dropdown menu. Double clicking an item in the Breakpoints Window List locates the breakpoint. Execute all instructions between the current instruction and cursor position. Execute the current Basic (single or multicycle) instruction, then halt. If the instruction is a routine call, enter the routine and halt at the first instruction following the call. Execute the current Basic (single or multicycle) instruction, then halt. Execute all remaining instructions in the current routine, return and then halt.
Toggle Breakpoints
[F5]
Run to cursor
[F4]
Step Into
[F7]
[F8] [Ctrl+F8]
95
CHAPTER 2
mikroBasic PRO for PIC allows you to create your own libraries. In order to create a library in mikroBasic PRO for PIC 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 Files\Mikroelektronika\mikroBasic PRO for PIC\Uses\P16\ DriveName:\Program Files\Mikroelektronika\mikroBasic PRO for PIC\Uses\P18\
If you are creating library for PIC16 MCU family the file should be saved in P16 folder. If you are creating library for PIC18 MCU family the file should be saved in P18 folder. If you are creating library for PIC16 and PIC18 MCU families the file should be saved in both folders. 3. Write a code for your library and save it. 4. Add _Lib_Example file in some project, see Project Manager. Recompile the project. If you wish to use this library for all MCUs, then you should go to Tools Options Output settings, and check Build all files as library box. This will build libraries in a common form which will work with all MCUs. If this box is not checked, then the library will be built for selected MCU. Bear in mind that compiler will report an error if a library built for specific MCU is used for another one. 5.Compiled file __Lib_Example.mcl should appear in ...\mikroBasic PRO for PIC\Uses\P16\ 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 PRO for PIC\Defs\
and it is named MCU_NAME.mlk, for example P16F887.mlk 7.Add the the following segment of code to <LIBRARIES> node of the definition file (definition file is in XML format):
<LIB> <ALIAS>Example_Library</ALIAS> <FILE>__Lib_Example</FILE> <TYPE>REGULAR</TYPE> </LIB>
8. Add Library to mlk file for each MCU that you want to use with your library. 9. Click Refresh button in Library Manager 10.Example_Library should appear in the Library manager window.
96
CHAPTER
mikroICD is highly effective tool for Real-Time debugging on hardware level. ICD debugger enables you to execute a mikroBasic PRO for PIC program on a host PIC microcontroller and view variable values, Special Function Registers (SFR), memory and EEPROM as the program is running.
97
CHAPTER 3
mikroICD
If you have appropriate hardware and software for using mikroICD then you have to upon completion of writing your program to choose between Release build Type or ICD Debug build type.
You can run the mikroICD by selecting Run Debug from the drop-down menu, or by clicking Debug Icon . Starting the Debugger makes more options available: Step Into, Step Over, Run to Cursor, etc. Line that is to be executed is color highlighted (blue by default). There is also notification about program execution and it can be found on Watch Window (yellow status bar). Note that some functions take time to execute, so running of program is indicated on Watch Window.
98
mikroICD
Description
Start Software Simulator. Run or pause Software Simulator. Toggle breakpoint at the current cursor position. To view all breakpoints, select Run > View Breakpoints from the dropdown menu. Double clicking an item in the window list locates the breakpoint. Execute all instructions between the current instruction and cursor position. Execute the current C (single or multicycle) instruction, then halt. If the instruction is a routine call, enter the routine and halt at the first instruction following the call. Execute the current C (single or multicycle) instruction, then halt. If the instruction is a routine call, skip it and halt at the first instruction following the call. Flushes current PIC RAM. All variable values will be changed according to values from watch window. Toggle between disassembly and Basic source view.
[F5]
Run to cursor
[F4]
Step Into
[F7]
Step Over
[F8]
Flush RAM
N/A
Disassembly View
[Alt+D]
99
CHAPTER 3
First you have to write a program. We will show how mikroICD works using this example:
program Lcd_Test dim dim dim dim dim dim dim dim dim dim dim dim LCD_RS LCD_EN LCD_D4 LCD_D5 LCD_D6 LCD_D7 as as as as as as sbit sbit sbit sbit sbit sbit at at at at at at RB4_bit RB5_bit RB0_bit RB1_bit RB2_bit RB3_bit sbit sbit sbit sbit sbit sbit at at at at at at TRISB4_bit TRISB5_bit TRISB0_bit TRISB1_bit TRISB2_bit TRISB3_bit
as as as as as as
dim text as char[17] i as byte main: PORTB = 0 TRISB = 0 ANSEL = 0 ANSELH = 0 text = "mikroElektronika" Lcd_Init() Lcd_Cmd(_LCD_CLEAR) Lcd_Cmd(_LCD_CURSOR_OFF) for i=1 to 17 Lcd_Chr(1,i,text[i-1]) next i end.
100
mikroICD
After successful compilation and PIC programming press F9 for starting mikroICD. After mikroICD initialization blue active line should appear.
We will debug program line by line. Pressing F8 we are executing code line by line. It is recommended that user does not use Step Into [F7] and Step Over [F8] over Delays routines and routines containing delays. Instead use Run to cursor [F4] and Breakpoints functions. All changes are read from PIC and loaded into Watch Window. Note that PORTB, TRISB, ANSEL and ANSELH changed its value.
101
CHAPTER 3
mikroICD
Step Into [F7] and Step Over [F8] are mikroICD debugger functions that are used in stepping mode. There is also Real-Time mode supported by mikroICD. Functions that are used in Real-Time mode are Run/ Pause Debugger [F6] and Run to cursor [F4]. Pressing F4 goes to line selected by user. User just have to select line with cursor and press F4, and code will be executed until selected line is reached.
Run(Pause) Debugger [F6] and Toggle Breakpoints [F5] are mikroICD debugger functions that are used in Real-Time mode. Pressing F5 marks line selected by user for breakpoint. F6 executes code until breakpoint is reached. After reaching breakpoint Debugger halts. Here at our example we will use breakpoints for writing "mikroElektronika" on Lcd char by char. Breakpoint is set on Lcd_Chr and program will stop everytime this function is reached. After reaching breakpoint we must press F6 again for continuing program execution.
102
mikroICD
Breakpoints has been separated into two groups. There are hardware and software break points. Hardware breakpoints are placed in PIC and they provide fastest debug. Number of hardware breakpoints is limited (1 for P16 and 1 or 3 or 5 for P18). If all hardware brekpoints are used, next breakpoints that will be used are software breakpoint. Those breakpoints are placed inside mikroICD, and they simulate hardware breakpoints. Software breakpoints are much slower than hardware breakpoints. This differences between hardware and software differences are not visible in mikroICD software but their different timings are quite notable, so it is important to know that there is two types of breakpoints.
103
CHAPTER 3
The Breakpoints window manages the list of currently set breakpoints in the project. Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code.
Watch Window
Debugger Watch Window is the main Debugger window which allows you to monitor program items while running your program. To show the Watch Window, select View Debug Windows Watch Window from the drop-down menu. The Watch Window displays variables and registers of PIC, with their addresses and values. Values are updated as you go through the simulation. Use the drop-down menu to add and remove the items that you want to monitor. Recently changed items are colored red.
104
mikroICD
Double clicking an item opens the Edit Value window in which you can assign a new value to the selected variable/register. Also, you can change view to binary, hex, char, or decimal for the selected item.
105
CHAPTER 3
mikroICD
Code Watch Window
mikroICD Code Watch Window is available from the drop-down menu, View Debug Windows View Code. The Code Watch window shows code (hex code) written into PIC. There is action button concerning Code Watch window - Read Code. Read Code reads code from PIC and loads it up in View Code Window. Also, you can set an address scope in which hex code will be read.
106
mikroICD
Common Errors
Trying to program PIC while mikroICD is active. Trying to debug Release build Type version of program. Trying to debug changed program code which hasn't been compiled and pro grammed into PIC. Trying to select line that is empty for Run to cursor [F4] and Toggle Break points [F5] functions. Trying to debug PIC with mikroICD while Watch Dog Timer is enabled. Trying to debug PIC with mikroICD while Power Up Timer is enabled. It is not possible to force Code Protect while trying to debug PIC with mikroICD. Trying to debug PIC with mikroICD with pull-up resistors set to ON on RB6 and RB7. For correct mikroICD debugging do not use pull-ups.
107
CHAPTER 3
mikro ICD provides the possibility to use the Advanced Breakpoints. Advanced Breakpoints can be used with PIC18 and PIC18FJ MCUs. To enable Advanced Breakpoints set the Advanced Breakpoints checkbox inside Watch window :
To configure Advanced Breakpoints, start mikroICD [F9] and select View Debug Windows Advanced Breakpoints option from the drop-down menu or use [Ctrl+Shift+A] shortcut
Note: When Advanced Breakpoints are enabled mikroICD operates in Real-Time mode, so it will support only the following set of commands: Start Debugger [F9], Run/Pause Debugger [F6] and Stop Debugger [Ctrl+F2]. Once the Advanced Breakpoint is reached, the Advanced Breakpoints feature can be disabled and mikroICD debugging can be continued with full set of commands. If needed, Advanced Breakepoints can be re-enabled without restarting mikroICD. Note: Number of Advanced Breakpoints is equal to number of Hardware breakpoints and it depends on used MCU.
108
mikroICD
Stopwatch
Stopwatch uses Breakpoint#2 and Breakpoint#3 as a Start and Stop conditions. To use the Stopwatch define these two Breakpoints and check the Enable Stopwatch checkbox. Stopwatch options: Halt on Start Condition (Breakpoint#2): when checked, the program exe cution will stop on Breakpoint#2. Otherwise, Breakpoint#2 will be used only to start the Stopwatch. Halt on Stop Condition (Breakpoint#3): when checked, the program exe cution will stop on Breakpoint#3. Otherwise, Breakpoint#3 will be used only to stop the Stopwatch. Reset Stopwatch on Run : when checked, the Stopwatch will be cleared before continuing program execution and the next counting will start from zero. Otherwise, the next counting will start from the previous Stopwatch value. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
109
CHAPTER 3
mikroICD
110
CHAPTER
111
CHAPTER 4
Function recursion is not supported because of no easily-usable stack and limited memory PIC Specific
112
Specifics
Math constants
In addition, several commonly used math constants are predefined in mikroBasic PRO for PIC:
PI PI_HALF TWO_PI E = 3.1415926 = 1.5707963 = 6.2831853 = 2.7182818
113
CHAPTER 4
The mikroBasic PRO for PIC allows you to access individual bits of 8-bit variables. It also supports sbit and bit data types
Also, you can simply use the direct member selector (.) with a variable, followed by one of identifiers B0, B1, , B7, or 0, 1, 7, with 7 being the most significant bit
' Clear bit 0 on PORTA PORTA.B0 = 0 ' Clear bit 5 on PORTB PORTB.5 = 0
There is no need of any special declarations. This kind of selective access is an intrinsic feature of mikroBasic PRO for PIC and can be used anywhere in the code. Identifiers B0B7 are not case sensitive and have a specific namespace. You may override them with your own members B0B7 within any given structure. See Predefined Globals and Constants for more information on register/bit names.
sbit type
The mikroBasic PRO for PIC compiler has sbit data type which provides access to bit-addressable SFRs. You can access them in several ways:
dim LEDA as sbit at PORTA.B0 dim Name as sbit at sfr-name.B<bit-position> dim LEDB as sbit at PORTB.0 dim Name as sbit at sfr-name.<bit-position> dim LEDC as sbit at RC0_bit dim Name as sbit at bit-name_bit;
114
Specifics
bit type
The mikroBasic PRO for PIC 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
Note : Bit Bit Bit of) variables can not be initialized. variables can not be members of structures. variables do not have addresses, therefore unary operator @ (address is not applicable to these variables.
115
CHAPTER 4
Specifics INTERRUPTS
Interrupts can be easily handled by means of reserved word interrupt. mikroBasic PRO for PIC implictly declares procedure interrupt which cannot be redeclared. Write your own procedure body to handle interrupts in your application. Note that you cannot call routines from within interrupt due to stack limitations. mikroBasic PRO for PIC saves the following SFR on stack when entering interrupt and pops them back upon return: PIC12 family: W, STATUS, FSR, PCLATH PIC16 family: W, STATUS, FSR, PCLATH PIC18 family: FSR (fast context is used to save WREG, STATUS, BSR)
If interrupt priority feature is to be used then the user should set the appropriate SFR bits to enable it. For more information refer to datasheet for specific device.
116
Specifics
Interrupt Examples
Here is a simple example of handling the interrupts from TMR0 (if no other interrupts are allowed):
sub procedure interrupt counter = counter + 1 TMR0 = 96 INTCON = $20 end sub
In case of multiple interrupts enabled, you need to test which of the interrupts occurred and then proceed with the appropriate code (interrupt handling):
sub procedure interrupt if TestBit(INTCON, TMR0IF) = 1 then counter = counter + 1 TMR0 = 96 ClearBit(INTCON, TMR0F) ' ClearBit is realised as an inline function, ' and may be called from within an interrupt else if TestBit(INTCON, RBIF) = 1 then counter = counter + 1 TMR0 = 96 ClearBit(INTCON,RBIF) end if end if end sub
117
CHAPTER 4
mikroBasic PRO for PIC 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
Directive absolute specifies the starting address in RAM for a variable. If the variable spans more than 1 word (16-bit), the 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 the absolute directive because 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.
Directive orgal
Use the orgall directive to specify the address above which all routines, constants will be placed. Example:
main: orgall(0x200) ' All the routines, constants in main program will be above the address 0x200 ... end.
118
Specifics
BUILT-IN ROUTINES
The mikroBasic PRO for PIC 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 doesnt 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 SetBit ClearBit TestBit Delay_us Delay_ms Clock_KHz Clock_MHz Reset ClrWdt DisableContextSaving SetFuncCall GetDateTime GetVersion
119
CHAPTER 4
Specifics
Lo
Prototype Returns
sub function Lo(number as longint) as byte
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 doesnt count against the nested call limit. Requires Example Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers).
d = 0x1AC30F4 tmp = Lo(d) ' Equals 0xF4
Hi
Prototype Returns
sub function Hi(number as longint) as byte
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 doesnt count against the nested call limit. Requires Example Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers).
d = 0x1AC30F4 tmp = Hi(d) ' Equals 0x30
Higher
Prototype Returns
sub function Higher(number as longint) as byte
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 doesnt count against the nested call limit. Requires Example Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers).
d = 0x1AC30F4 tmp = Higher(d) ' Equals 0xAC
120
Specifics
Highest
Prototype Returns
sub function Highest(number as longint) as byte
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 doesnt count against the nested call limit. Requires Example Arguments must be variable of scalar type (i.e. Arithmetic Types and Pointers).
d = 0x1AC30F4 tmp = Highest(d) ' Equals 0x01
Inc
Prototype Returns
sub procedure Inc(dim byref par as longint)
Nothing.
Dec
Prototype Returns
sub procedure Dec(dim byref par as longint)
Nothing.
121
CHAPTER 4
Specifics
Delay_us
Prototype 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 doesnt count against the nested call limit. Requires Example Nothing.
Delay_us(1000) ' One millisecond pause
Delay_ms
Prototype Returns
sub procedure Delay_ms(const time_in_ms as longword)
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 doesnt count against the nested call limit. Requires Example Nothing.
Delay_ms(1000) ' One second pause
Clock_KHz
Prototype Returns
sub function Clock_Khz() as word
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 doesnt count against the nested call limit. Nothing.
clk = Clock_kHz()
Requires Example
122
Specifics
Clock_MHz
Prototype Returns
sub function Clock_MHz()as byte
Device clock in MHz, rounded to the nearest integer. Function returns device clock in MHz, rounded to the nearest integer.
Description
This is an inline routine; code is generated in the place of the call, so the call doesnt count against the nested call limit. Nothing.
clk = Clock_MHz()
Requires Example
Reset
Prototype Returns Description Requires Example
sub procedure Reset
Nothing. This procedure is equal to assembler instruction reset. This procedure works only for P18. Nothing.
Reset 'Resets the PIC MCU
ClrWdt
Prototype Returns
sub procedure ClrWdt
Nothing.
Description This procedure is equal to assembler instruction clrwdt. Requires Example Nothing.
ClrWdt 'Clears PIC's WDT
123
CHAPTER 4
Specifics
DisableContextSaving
Prototype Returns
sub procedure DisableContextSaving()
Nothing.
Use the DisableContextSaving() to instruct the compiler not to automatically perform context-switching. This means that no regiser will be saved/restored by Description the compiler on entrance/exit from interrupt service routine. This enables the user to manually write code for saving registers upon entrance and to restore them before exit from interrupt. Requires Nothing.
DisableContextSaving() 'instruct the compiler not to automatically perform context-switching
Example
SetFuncCall
Prototype Returns
sub procedure SetFuncCall(FuncName as string)
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.
sub procedure first(p, q as byte) ... SetFuncCall(second) ' let linker know that we will call the routine 'second' ... end sub
Example
124
Specifics
GetDateTime
Prototype Returns Description Requires Example
sub function GetDateTime() as string
String with date and time when this routine is compiled. Use the GetDateTime() to get date and time of compilation as string in your code. Nothing.
str : GetDateTime()
GetVersion
Prototype Returns
sub function GetVersion() as string
Description Use the GetVersion() to get the current version of compiler. Requires Example Nothing.
str = GetVersion() ' for example, str will take the value of '8.2.1.6'
125
CHAPTER 4
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.
Stack allocation
Temporary registers ("Stacks") are being used more rationally, allowing VERY complex expressions to be evaluated with a minimum stack consumption.
126
CHAPTER
PIC Specifics
In order to get the most from your mikroBasic PRO for PIC compiler, you should be familiar with certain aspects of PIC MCU. This knowledge is not essential, but it can provide you a better understanding of PICs capabilities and limitations, and their impact on the code writing.
127
CHAPTER 5
PIC Specifics
Types Efficiency
First of all, you should know that PICs ALU, which performs arithmetic operations, is optimized for working with bytes. Although mikroBasic PRO for PIC is capable of handling very complex data types, PIC 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. Get to know your tool. When it comes down to calculus, not all PIC MCUs are of equal performance. For example, PIC16 family lacks hardware resources to multiply two bytes, so it is compensated by a software algorithm. On the other hand, PIC18 family has HW multiplier, and multiplication works considerably faster.
130
PIC Specifics
131
CHAPTER 5
The mikroBasic PRO for PIC supports usage of all memory areas. Each variable may be explicitly assigned to a specific memory space by including a memory type specifier in the declaration, or implicitly assigned. The following memory type specifiers can be used:
code data rx sfr
code
Description Example The code memory type may be used for allocating constants in program memory.
puts txt in program memory const txt = "Enter parameter" code;
data
Description This memory specifier is used when storing variable to the internal data SRAM. Example
' puts data_buffer in data ram dim data_buffer as byte data
rx
This memory specifier allows variable to be stored in the Rx space (Register file). Description Note: In most of the cases, there will be enough space left for the user variables in the Rx space. However, since compiler uses Rx space for storing temporary variables, it might happen that user variables will be stored in the internal data SRAM, when writing complex programs. Example
' puts y in Rx space dim y as char rx
132
PIC Specifics
sfr
This memory specifier in combination with (rx, io, data) allows user to access Description special function registers. It also instructs compiler to maintain same identifier in Basic and assembly.
dim io_buff as byte io sfr ' put io_buff in I/O memory space dim y as char rx sfr ' puts y in Rx space dim temp as byte data sfr and dim temp as byte sfr are equivalent, and put temp in Extended I/O Space.
Example
Note: If none of the memory specifiers are used when declaring a variable, data specifier will be set as default by the compiler. Related topics: Accessing individual bits, SFRs, Constants, Functions
133
CHAPTER 5
PIC Specifics
134
CHAPTER
135
CHAPTER 6
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 Relational Operators Bitwise Operators Boolean Operators
136
CHAPTER 6 mikroBasic PRO for PIC Expressions Expressions 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
Language Reference
137
CHAPTER 6
The following topics provide a formal definition of the mikroBasic PRO for PIC lexical elements. They describe different categories of word-like units (tokens) recognized by language. In the tokenizing phase of compilation, the source code file is parsed (i.e. broken down) into tokens and whitespace. The tokens in mikroBasic PRO for PIC are derived from a series of operations performed on your programs by the compiler. A mikroBasic PRO for PIC program starts as a sequence of ASCII characters representing the source code, created by keystrokes using a suitable text editor (such as the mikroBasic PRO for PIC Code Editor). The basic program unit in mikroBasic PRO for PIC 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, newline characters and comments. Whitespace can serve to indicate where tokens start and end, but beyond this function, any surplus whitespace is discarded. For example, two sequences
dim tmp as byte dim j as wordand and dim dim tmp j as as byte word
Newline Character
Newline character (CR/LF) is not a whitespace in BASIC, and serves as a statement terminator/separator. In mikroBasic PRO for PIC, 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.
138
Language Reference
Whitespace in Strings
The ASCII characters representing whitespace can occur within string literals, in which case they are protected from the normal parsing process (they remain a part of the string). For example,
some_string = mikro foo
COMMENTS
Comments are pieces of a text used to annotate a program, and are technically another form of whitespace. Comments are for the programmers 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.
139
CHAPTER 6
Token is the smallest element of a mikroBasic PRO for PIC 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 lefttoright scan. mikroBasic PRO for PIC recognizes the following kinds of tokens: keywords identifiers constants operators punctuators (also known as separators)
Note that end_flag would be parsed as a single identifier, rather than the keyword end followed by the identifier _flag.
140
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 PRO for PIC longword. The compiler will report an error if the literal exceeds 4294967295 ($FFFFFFFF).
141
CHAPTER 6
Language Reference
mikroBasic PRO for PIC limits floating-point constants to the range of 1.17549435082 * 10-38 .. 6.80564774407 * 1038.
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 strings 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:
142
Language Reference
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.
143
CHAPTER 6
Keywords are the words reserved for special purposes and must not 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 PRO for PIC:
Abstract And Array As at Asm Assembler Automated bdata Begin bit Case Cdecl Class Code compact Const Constructor Contains Data Default deprecated Destructor Dispid Dispinterface Div Do Downto Dynamic Else End Except Export Exports External Far
144
Language Reference
145
CHAPTER 6
Language Reference
Record Register Reintroduce Repeat requires Reset Resourcestring Resume Safecall sbit Set sfr Shl Shr small Stdcall Stored String Stringresource Then Threadvar To Try Type Unit Until Uses Var Virtual Volatile While With Write Writeonly xdata Xor
Also, mikroBasic PRO for PIC 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 PRO for PIC Libraries.
146
Language Reference
IDENTIFIERS
Identifiers are arbitrary names of any length given to functions, variables, symbolic constants, user-defined data types and labels. All these program elements will be referred to as objects throughout the help (don't get confused about the meaning of object in object-oriented programming). Identifiers can contain the letters a to z and A to Z, 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 PRO for PIC is not case sensitive, so Sum, sum, and suM are equivalent identifiers.
Identifier Examples
Here are some valid identifiers:
temperature_V1 Pressure no_hit dat2string SUM3 _vtext
147
CHAPTER 6
Brackets
Brackets [ ] indicate single and multidimensional array subscripts:
dim alphabet as byte[30] ' ... alphabet[2] = "c"
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);
148
Language Reference
Colon
Colon (:) is used to indicate a labeled statement:
start: nop '... goto start
Dot
Dot (.) indicates access to a structure member. For example:
person.surname = "Smith"
For more information, refer to Structures. Dot is a necessary part of floating point literals. Also, dot can be used for accessing individual bits of registers in mikroBasic PRO.
149
CHAPTER 6
mikroBasic PRO for PIC 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.
[^]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 '********************************************************
150
Language Reference
'* Program body: '******************************************************** main: ' write your code here end.
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
151
CHAPTER 6
Language Reference
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 ' 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.
152
Language Reference
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 that region of the program source code from which legal access to the identifiers 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, i.e. 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.
153
CHAPTER 6
In mikroBasic PRO for PIC, each project consists of a single project file and one or more module files. The project file, with extension .mbpav contains information on the project, while modules, with extension .mbas, contain the actual source code. See Program Organization for a detailed look at module arrangement. Modules allow you to: break large programs into encapsulated modules that can be edited sepa rately, 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 PRO for PIC 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. Heres 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 .mbas files, in order specified by search paths. If both .mbas and .mcl files are found, the compiler will check their dates and include the newer one in the project. If the.mbas file is newer than the .mcl, then .mbas file will be recompiled and new.mcl will be created, overwriting the old .mcl. If only the .mbas file is found, the compiler will create the.mcl file and
154
Language Reference
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 PRO for PIC 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.
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.
155
CHAPTER 6
Language Reference
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 irrelevant innards from other units, 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.
156
Language Reference
VARIABLES
Variable is an object whose value can be changed during the runtime. Every variable is declared under unique name which must be a valid identifier. This name is used for accessing the memory location occupied by the variable. Variables are declared in the declaration part of the file or routine each variable needs to be declared before it is used. 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 PRO for PIC 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]
External Modifier
Use the external modifier to indicate that the actual place and initial value of the variable, or body of the function, is defined in a separate source code module.
157
CHAPTER 6
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)
158
Language Reference
LABELS
Labels serve as targets for the goto and gosub statements. Mark the desired statement with label and colon like this:
label_identifier : statement
No special declaration of label is necessary in mikroBasic PRO for PIC. 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
159
CHAPTER 6
mikroBasic PRO for PIC 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 '... main: if cnt > MAXALLOWED then cnt = 0 PORT.1 = 0 MYDELAY end if ' Symbol as alias for numeric value ' Symbol as alias for SFR ' Symbol as alias for procedure call
Note: Symbols do not support macro expansion in a way the C preprocessor does.
160
Language Reference
Functions
A function is declared like this:
sub function function_name(parameter_list) as return_type [ local declarations ] function body end sub function_name represents a functions 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 very similar to variable declara-
tion.In mikroBasic PRO for PIC, 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
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 PRO for PIC 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. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
161
CHAPTER 6
Language Reference
Example
PROCEDURES
Procedure is declared like this:
sub procedure procedure_name(parameter_list) [ local declarations ] procedure body end sub procedure_name represents a procedures name and can be any valid identifier. Within parentheses, parameter_list is a formal parameter list very similar to variable declaration. In mikroBasic PRO for PIC, 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 executed upon calling the procedure.
162
Language Reference
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.
Example
Heres an example procedure which transforms its input time parameters, preparing them for output on LCD:
sub procedure time_prep(dim sec = ((sec and $F0) >> min = ((min and $F0) >> hr = ((hr and $F0) >> end sub byref 4)*10 4)*10 4)*10 sec, min, hr as byte) + (sec and $0F) + (min and $0F) + (hr and $0F)
Function Pointers
Function pointers are allowed in mikroBasic PRO for PIC. 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
163
CHAPTER 6
Language Reference
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: 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.
MyPtr now points to Func1 Perform function call via pointer, call MyPtr now points to Func2 Perform function call via pointer, call MyPtr now points to Func3 Perform 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
164
Language Reference
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.
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.
Functions reentrancy
Functions reentrancy is allowed if the function has no parameters and local variables, or if the local variables are placed in the Rx space. Remember that the PIC has stack and memory limitations which can varies greatly between MCUs.
165
CHAPTER 6
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 PRO for PIC 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
166
Language Reference
SIMPLE TYPES
Simple types represent types that cannot be divided into more basic elements and are the model for representing elementary data on machine level. Basic memory unit in mikroBasic PRO for PIC has 8 bits. Here is an overview of simple types in mikroBasic PRO for PIC: Type
byte, char short word integer longword longint float bit sbit
Size 8bit 8bit 16bit 16bit 32bit 32bit 32bit 1bit 1bit 0 .. 255 -127 .. 128 0 .. 65535
Range
You can assign signed to unsigned or vice versa only using the explicit conversion. Refer to Types Conversions for more information.
167
CHAPTER 6
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 elements 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.
168
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 strings 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
Be careful when handling strings in this way, since overwriting the end of a string will cause an unpredictable behavior. Note mikroBasic PRO for PIC includes String Library which automatizes string related tasks.
169
CHAPTER 6
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 pointers memory location, you add a carat after the variable name. For example, lets 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 the address, not the value, is copied. Once you modify the data located at one pointer, the other pointer, when dereferenced, also yields modified data.
@ Operator
The @ operator constructs a pointer to its operand. The following rules are applied to @: If X is a variable, @X returns a pointer to X. Note: If variable X is of array type, the @ operator will return pointer to it's first basic element, except when the left side of the statement in which X is used is an array pointer. In this case, the @ operator will return pointer to array, not to it's first basic element.
program example dim w as word ptr_b as ^byte ptr_arr as ^byte[10] arr as byte[10] main: ptr_b = @arr ' @ operator will return ^byte w = @arr ' @ operator will return ^byte ptr_arr = @arr ' @ operator will return ^byte[10] end.
170
Language Reference
STRUCTURES
A structure represents a heterogeneous set of elements. Each element is called a member; the declaration of a structure type specifies a name and type for each member. The syntax of a structure type declaration is
structure structname dim member1 as type1 '... dim membern as typen end structure
where structname is a valid identifier, each type denotes a type, and each member is a valid identifier. The scope of a member identifier is limited to the structure in which it occurs, so you dont 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 structures
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
171
CHAPTER 6
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
You can also commit assignments between complex variables, if they are of the same type:
circle2 = circle1 ' This will copy values of all members
172
Language Reference
TYPES CONVERSIONS
Conversion of variable of one type to variable of another type is typecasting. mikroBasic PRO for PIC 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 type to 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
173
CHAPTER 6
Language Reference
Clipping
In assignments and statements that require an expression of particular type, destination will store the correct value only if it can properly represent the result of expression, i.e. if the result fits in destination range. If expression evaluates to a more complex type than expected, excess of data will be simply clipped (higher bytes are lost).
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 an 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
174
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 in mikroBasic PRO for PIC: Arithmetic Operators Bitwise Operators Boolean Operators Relational Operators
Operators
+ mod < and or > << xor <= >= >>
Associativity
175
CHAPTER 6
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. Operator
+
Operation addition
Operands
Result
byte, short, word, byte, short, word, integer, longint, integer, longint, longword, float longword, float byte, short, word, byte, short, word, integer, longint, integer, longint, longword, float longword, float byte, short, word, byte, short, word, integer, longint, integer, longint, longword, float longword, float byte, short, word, longint, float longword, float byte, short, word, byte, short, word, longint, integer, longint, longword
subtraction
multiplication
division, floating-point integer, division, rounds down integer, to nearest integer longword
div
mod
modulus, returns the remainder of integer byte, short, word, byte, short, word, longint, integer, longint, division (cannot be integer, longword used with floating longword 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.).
176
Language Reference
RELATIONAL OPERATORS
Use relational operators to test equality or inequality of expressions. All relational operators return TRUE or FALSE. Operator = <> > < >= <= equal not equal greater than less than greater than or equal less than or equal Operation
177
CHAPTER 6
Use bitwise operators to modify 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.
Operation bitwise AND; compares pairs of bits and generates a 1 result if both bits are 1, otherwise it returns 0 bitwise (inclusive) OR; compares pairs of bits and generates a 1 result if either or both bits are 1, otherwise it returns 0 bitwise exclusive OR (XOR); compares pairs of bits and generates a 1 result if the bits are complementary, otherwise it returns 0 bitwise complement (unary); inverts each bit bitwise shift left; moves the bits to the left, 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
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:
$1234 and $5678 ' because .. '$1234 : 0001 0010 0011 0100 '$5678 : 0101 0110 0111 1000 '---------------------------'equals $1230
178
Language Reference
179
CHAPTER 6
Language Reference
Bitwise Shift Operators
The binary operators << and >> move the bits of the left operand by a number of positions specified by the right operand, to the left or right, respectively. Right operand has to be positive and less than 255. With shift left (<<), left most bits are discarded, and new bits on the right are assigned zeroes. 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.
BOOLEAN OPERATORS
Although mikroBasic PRO for PIC 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 xor not
Boolean operators associate from left to right. Negation operator not associates from right to left.
180
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. More complex expressions can be created from primary expressions by using operators. 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 PRO for PIC.
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
181
CHAPTER 6
The statement evaluates expression and assigns its value to variable. All the 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 PRO for PIC will interpret the meaning of the character = from the context
CONDITIONAL STATEMENTS
Conditional or selection statements select one of alternative courses of action by testing certain values. There are two types of selection statements: if select case
If Statement
Use the keyword if to implement a conditional statement. The syntax of the if statement has the following form:
if expression then statements [else other statements] end if
When expression evaluates to true, statements execute. 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.
182
Language Reference
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
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
183
CHAPTER 6
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:
184
Language Reference
185
CHAPTER 6
Iteration statements let you loop a set of statements. There are three forms of iteration statements in mikroBasic PRO for PIC: for while do 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.
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 counters type.
186
Language Reference
WHILE STATEMENT
Use the while keyword to conditionally iterate a statement. The syntax of the while statement is:
while expression statements wend statements executed repeatedly as long as expression evaluates true. The test takes place before statement 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
187
CHAPTER 6
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
188
Language Reference
JUMP STATEMENTS
A jump statement, when executed, transfers control unconditionally. There are five such statements in in mikroBasic PRO for PIC: break continue exit goto gosub
Continue Statement
You can use the continue statement within loops to skip the cycle:
continue statement in for loop moves program counter to the line with key word for continue statement in while loop moves program counter to the line with
189
CHAPTER 6
Language Reference
continue jumps here for i := ... ... continue; ... next i do ... continu ... continue jumps here loop until condition continue jumps here while condition ... continue; ... wend
EXIT STATEMENT
The exit statement allows you to break out of a routine (function or procedure). It passes the control to the first statement following the routine call. Here is a simple example:
sub procedure Proc1() dim error as byte ... ' we're doing something here if error = TRUE then exit end if ... ' some code, which won't be executed if error is true end sub
Note: If breaking out of a function, return value will be the value of the local variable result at the moment of exit.
190
Language Reference
GOTO STATEMENT
Use the goto statement to unconditionally jump to a local label for more information, refer to Labels. Syntax of goto statement is:
goto label_name
This will transfer control to the location of a local label specified by label_name. The goto line can come before or after the label. Label and goto statement must belong to the same block. Hence it is not possible to jump into or out of a procedure or function. You can use goto to break out from any level of nested control structures. Never jump into a loop or other structured statement, since this can have unpredictable effects. The use of goto statement is generally discouraged as practically every algorithm can be realized without it, resulting in legible structured programs. One possible application of the goto statement is breaking out from deeply nested control structures:
for i = 0 to n for j = 0 to m ... if disaster goto Error end if ... next j next i . . . Error: ' error handling code
191
CHAPTER 6
Use the gosub statement to unconditionally jump to a local label for more information, refer to Labels. The syntax of the gosub statement is:
gosub label_name ... label_name: ... return
This will transfer control to the location of a local label specified by label_name. Also, the calling point is remembered. Upon encountering the return statement, program execution will continue with the next statement (line) after gosub. The gosub line can come before or after the label. It is not possible to jump into or out of routine by means of gosub. Never jump into a loop or other structured statement, since this can have unpredictable effects. Note: Like with goto, the use of gosub statement is generally discouraged. mikroBasic PRO for PIC supports gosub only for the sake of backward compatibility. It is better to rely on functions and procedures, creating legible structured programs.
asm STATEMENT
mikroBasic PRO for PIC 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 PRO for PIC comments are not allowed in embedded assembly code. Instead, you may use one-line assembly comments starting with semicolon. Note: Compiler doesn't expect memory banks to be changed inside the assembly code. If the user wants to do this, then he must restore the previous bank selection.
192
Language Reference
DIRECTIVES
Directives are words of special significance which provide additional functionality regarding compilation and output. The following directives are available for use: 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.
193
CHAPTER 6
Language Reference
Directives #IFDEF, $IFNDEF, #ELSEIF and #ELSE
Conditional compilation is carried out by the #IFDEF and $IFNDEF directives. #IFDEF tests whether a flag is currently defined, and $IFNDEF if the flag is not defined; i.e. whether a previous #DEFINE directive has been processed for that flag and is still in force. Directives #IFDEF and $IFNDEF are terminated by the #ENDIF directive and can have any number of the #ELSEIF clauses and an optional #ELSE clause:
#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 defined 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.
Unlike $IFDEF, $IFNDEF checks if flag is not defined by means of $DEFINE, thus producing the opposite results. 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
194
Language Reference
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 16F887 ' If 16F887 MCU is selected #IFNDEF 18F4550 ' If 18F4550 MCU is selected
Linker Directives
mikroBasic PRO for PIC 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
195
CHAPTER 6
Language Reference
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.
Directive orgall
Use the orgall directive to specify the address above which all routines, constants will be placed. Example:
main: orgall(0x200) ' All the routines, constants in main program will be above the address 0x200 ... end.
196
CHAPTER
197
CHAPTER 7
Libraries
Hardware PIC-specific Libraries
ADC Library CAN Library CANSPI Library Compact Flash Library EEPROM Library Ethernet PIC18FxxJ60 Library Flash Memory Library Graphic Lcd Library I2C Library Keypad Library Lcd Library Manchester Code Library Multi Media Card library OneWire Library Port Expander Library PS/2 Library PWM 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 USB HID Library
Miscellaneous Libraries
Button Library Conversions Library Math Library String Library Time Library Trigonometry Library See also Built-in Routines.
198
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.
199
CHAPTER 7
Libraries
200
Libraries
Hardware Libraries
ADC Library CAN Library CANSPI Library Compact Flash Library EEPROM Library Ethernet PIC18FxxJ60 Library Flash Memory Library Graphic Lcd Library I2C Library Keypad Library Lcd Library Manchester Code Library Multi Media Card library OneWire Library Port Expander Library PS/2 Library PWM 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 USB HID Library
201
CHAPTER 7
ADC (Analog to Digital Converter) module is available with a number of PIC MCUs. Library function Adc_Read is included to provide you comfortable work with the module.
Library Routines
ADC_Read
ADC_Read
Prototype Returns
sub function ADC_Read(dim channel as byte) as word
10-bit unsigned value read from the specified channel Initializes PICs internal ADC module to work with RC clock. Clock determines the time period necessary for performing AD conversion (min 12TAD).
Description Parameter channel represents the channel from which the analog value is to be acquired. Refer to the appropriate datasheet for channel-to-pin mapping Requires Example Nothing.
dim tmp as word ... tmp = ADC_Read(2)
202
Libraries
Library Example
This example code reads analog value from channel 2 and displays it on PORTB and PORTC.
program ADC_on_LEDs dim adc_rd as word main: EBDIS_bit = 1 CMCON = CMCON or 0x07 ADCON1 = ADCON1 or 0x0C TRISA2_bit = 1 TRISB = 0x00 TRISC = 0x00 while (TRUE) adc_rd = ADC_Read(2) PORTB = adc_rd PORTC = Hi(adc_rd) wend end.
' set External Bus Disable bit ' turn off comparators ' Set AN2 channel pin as analog ' input ' Set PORTB as output ' Set PORTC as output
' get ADC value from 2nd channel ' display adc_rd[7..0] ' display adc_rd[9..8]
HW Connection
ADC HW connection
203
CHAPTER 7
mikroBasic provides a library (driver) for working with the CAN module. CAN is a very robust protocol that has error detection and signalling, selfchecking and fault confinement. Faulty CAN data and remote frames are re-transmitted automatically, similar to the Ethernet. Data transfer rates vary from up to 1 Mbit/s at network lengths below 40m to 250 Kbit/s at 250m cables, and can go even lower at greater network distances, down to 200Kbit/s, which is the minimum bitrate defined by the standard. Cables used are shielded twisted pairs, and maximum cable length is 1000m. CAN supports two message formats: Standard format, with 11 identifier bits, and Extended format, with 29 identifier bits Note: Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus.
Library Routines
CANSetOperationMode CANGetOperationMode CANInitialize CANSetBaudRate CANSetMask CANSetFilter CANRead CANWrite Following routines are for the internal use by compiler only: RegsToCANID CANIDToRegs Be sure to check CAN constants necessary for using some of the functions
204
Libraries
CANSetOperationMode
Prototype Returns
sub procedure CANSetOperationMode(dim mode, wait_flag as byte)
Nothing. Sets CAN to requested mode, i.e. copies mode to CANSTAT. Parameter mode needs to be one of CAN_OP_MODE constants (see CAN constants). Parameter wait_flag needs to be either 0 or $FF:
Description
If set to $FF, this is a blocking call the function wont return until the requested mode is set. If 0, this is a non-blocking call. It does not verify if CAN module is switched to requested mode or not. Caller must use CANGetOperationMode to verify correct operation mode before performing mode specific operation. Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus.
CANSetOperationMode(_CAN_MODE_CONFIG, $FF)
Requires Example
CANGetOperationMode
Prototype Returns
sub function CANGetOperationMode as byte
Current opmode.
Description Function returns current operational mode of CAN module. Requires Example Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus.
if CANGetOperationMode = _CAN_MODE_NORMAL then ...
205
CHAPTER 7
Libraries
CANInitialize
Prototype Returns
sub procedure CANInitialize(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CAN_CONFIG_FLAGS as byte)
Nothing. Initializes CAN. All pending transmissions are aborted. Sets all mask registers to 0 to allow all messages. Filter registers are set according to flag value:
if (CAN_CONFIG_FLAGS and _CAN_CONFIG_VALID_XTD_ MSG)<> 0 ' Set all filters to XTD_MSG else if (config and _CAN_CONFIG_VALID_STD_MSG) <> 0 ' Set all filters to STD_MSG else ' Set half of the filters to STD, and the rest to XTD_MSG.
Description
Parameters: SJW as defined in 18XXX8 datasheet (14) BRP as defined in 18XXX8 datasheet (164) PHSEG1 as defined in 18XXX8 datasheet (18) PHSEG2 as defined in 18XXX8 datasheet (18) PROPSEG as defined in 18XXX8 datasheet (18) CAN_CONFIG_FLAGS is formed from predefined constants (see CAN constants) CAN must be in Config mode; otherwise the function will be ignored. Requires Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus. init = _CAN_CONFIG_SAMPLE_THRICE and _CAN_CONFIG_PHSEG2_PRG_ON and _CAN_CONFIG_STD_MSG and _CAN_CONFIG_DBL_BUFFER_ON and _CAN_CONFIG_VALID_XTD_MSG and _CAN_CONFIG_LINE_FILTER_OFF
Initialize CAN
Example ...
CANInitialize(1,1,3,3,1,init)
206
Libraries
CANSetBaudRate
Prototype Returns
sub procedure CANSetBaudRate(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CAN_CONFIG_FLAGS as byte)
Nothing. Sets CAN baud rate. Due to complexity of CAN protocol, you cannot simply force a bps value. Instead, use this function when CAN is in Config mode. Refer to datasheet for details. Parameters:
Description
SJW as defined in 18XXX8 datasheet (14) BRP as defined in 18XXX8 datasheet (164) PHSEG1 as defined in 18XXX8 datasheet (18) PHSEG2 as defined in 18XXX8 datasheet (18) PROPSEG as defined in 18XXX8 datasheet (18) CAN_CONFIG_FLAGS is formed from predefined constants (see CAN constants)
CAN must be in Config mode; otherwise the function will be ignored. Requires Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus.
init = _CAN_CONFIG_SAMPLE_THRICE and _CAN_CONFIG_PHSEG2_PRG_ON _CAN_CONFIG_STD_MSG _CAN_CONFIG_DBL_BUFFER_ON _CAN_CONFIG_VALID_XTD_MSG _CAN_CONFIG_LINE_FILTER_OFF ... CANSetBaudRate (1, 1, 3, 3, 1, init) and and and and
Example
207
CHAPTER 7
Libraries
CANSetMask
Prototype Returns
sub procedure CANSetMask(dim CAN_MASK as byte, dim value as longint, dim CAN_CONFIG_FLAGS as byte) Nothing. Function sets mask for advanced filtering of messages. Given value is bit adjusted to appropriate buffer mask registers. Parameters:
Description
CAN_MASK is one of predefined constant values (see CAN constants) value is the mask register value CAN_CONFIG_FLAGS selects type of message to filter, either _CAN_CONFIG_XTD_MSG or _CAN_CONFIG_STD_MSG
CAN must be in Config mode; otherwise the function will be ignored. Requires Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus. ' Set all mask bits to 1, i.e. all filtered bits are relevant:
CANSetMask(_CAN_MASK_B1, -1,_CAN_CONFIG_XTD_MSG)
Example
' Note that -1 is just a cheaper way to write $FFFFFFFF. ' Complement will do the trick and fill it up with ones.
208
Libraries
CANSetFilter
Prototype Returns
sub procedure CANSetFilter(dim CAN_FILTER as byte, dim value as longint, dim CAN_CONFIG_FLAGS as byte)
Nothing. Function sets message filter. Given value is bit adjusted to appropriate buffer mask registers. Parameters:
Description
CAN_FILTER is one of predefined constant values (see CAN constants) value is the filter register value CAN_CONFIG_FLAGS selects type of message to filter, either _CAN_CONFIG_XTD_MSG or _CAN_CONFIG_STD_MSG
CAN must be in Config mode; otherwise the function will be ignored. Requires Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus.
' Set id of filter B1_F1 to 3: CANSetFilter(_CAN_FILTER_B1_F1, 3, _CAN_CONFIG_XTD_MSG)
Example
209
CHAPTER 7
Libraries
CANRead
Prototype Returns
sub function CANRead(dim byref id as longint, dim byref data as byte[8], dim byref datalen, CAN_RX_MSG_FLAGS as byte) as byte
Message from receive buffer or zero if no message found. Function reads message from receive buffer. If at least one full receive buffer is found, it is extracted and returned. If none found, function returns zero. Parameters:
Description
id is message identifier data is an array of bytes up to 8 bytes in length datalen is data length, from 18. CAN_RX_MSG_FLAGS is value formed from constants (see CAN constants)
CAN must be in mode in which receiving is possible. Requires Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus.
dim len, rcv, rx as byte dim id as longint dim data as byte[8]
Example
210
Libraries
CANWrite
Prototype Returns
sub function CANWrite(dim id as longint, dim byref data as byte[8], dim datalen, CAN_TX_MSG_FLAGS as byte) as byte
Returns zero if message cannot be queued (buffer full). If at least one empty transmit buffer is found, function sends message on queue for transmission. If buffer is full, function returns 0. Parameters:
Description
CAN must be in Normal mode. Requires Microcontroller must be connected to CAN transceiver (MCP2551 or similar) which is connected to CAN bus.
dim id as longint dim tx, data as byte
Example
' ... tx = _CAN_TX_PRIORITY_0 and _CAN_TX_XTD_FRAME ' ... CANWrite(id, data, 2, tx)
211
CHAPTER 7
Libraries
CAN Constants
There is a number of constants predefined in CAN library. To be able to use the library effectively, you need to be familiar with these. You might want to check the example at the end of the chapter.
CAN_OP_MODE
CAN_OP_MODE constants define CAN operation CANSetOperationMode expects one of these as its argument: const const const const const const _CAN_MODE_BITS _CAN_MODE_NORMAL _CAN_MODE_SLEEP _CAN_MODE_LOOP _CAN_MODE_LISTEN _CAN_MODE_CONFIG = = = = = = $E0 0 $20 $40 $60 $80
mode.
Function
CAN_CONFIG_FLAGS
CAN_CONFIG_FLAGS constants define flags related to CAN module configuration. Functions CANInitialize and CANSetBaudRate expect one of these (or a bitwise combination) as their argument: const _CAN_CONFIG_DEFAULT const _CAN_CONFIG_PHSEG2_PRG_BIT const _CAN_CONFIG_PHSEG2_PRG_ON const _CAN_CONFIG_PHSEG2_PRG_OFF const _CAN_CONFIG_LINE_FILTER_BIT const _CAN_CONFIG_LINE_FILTER_ON const _CAN_CONFIG_LINE_FILTER_OFF const _CAN_CONFIG_SAMPLE_BIT const _CAN_CONFIG_SAMPLE_ONCE const _CAN_CONFIG_SAMPLE_THRICE const _CAN_CONFIG_MSG_TYPE_BIT const _CAN_CONFIG_STD_MSG const _CAN_CONFIG_XTD_MSG const const const const const const const const _CAN_CONFIG_DBL_BUFFER_BIT _CAN_CONFIG_DBL_BUFFER_ON _CAN_CONFIG_DBL_BUFFER_OFF _CAN_CONFIG_MSG_BITS _CAN_CONFIG_ALL_MSG _CAN_CONFIG_VALID_XTD_MSG _CAN_CONFIG_VALID_STD_MSG _CAN_CONFIG_ALL_VALID_MSG = $FF = $01 = $FF = $FE = $02 = $FF = $FD = $04 = $FF = $FB = $08 = $FF = $F7 = = = = = = = = $10 $FF $EF $60 $FF $DF $BF $9F ' 11111111
212
Libraries
You may use bitwise and to form config byte out of these values. For example:
init = _CAN_CONFIG_SAMPLE_THRICE and _CAN_CONFIG_PHSEG2_PRG_ON and _CAN_CONFIG_STD_MSG and _CAN_CONFIG_DBL_BUFFER_ON and _CAN_CONFIG_VALID_XTD_MSG and _CAN_CONFIG_LINE_FILTER_OFF ' Initialize CAN
CAN_TX_MSG_FLAGS
CAN_TX_MSG_FLAGS are flags related to transmission of a CAN message:
const const const const const _CAN_TX_PRIORITY_BITS _CAN_TX_PRIORITY_0 _CAN_TX_PRIORITY_1 _CAN_TX_PRIORITY_2 _CAN_TX_PRIORITY_3 = = = = = $03 $FC $FD $FE $FF ' ' ' ' XXXXXX00 XXXXXX01 XXXXXX10 XXXXXX11
const _CAN_TX_FRAME_BIT const _CAN_TX_STD_FRAME const _CAN_TX_XTD_FRAME const _CAN_TX_RTR_BIT const _CAN_TX_NO_RTR_FRAME const _CAN_TX_RTR_FRAME
You may use bitwise and to adjust the appropriate flags. For example:
' form value to be used with CANSendMessage: send_config = _CAN_TX_PRIORITY_0 and _CAN_TX_XTD_FRAME and _CAN_TX_NO_RTR_FRAME; ... CANSendMessage(id, data, 1, send_config)
213
CHAPTER 7
Libraries
CAN_RX_MSG_FLAGS
CAN_RX_MSG_FLAGS are flags related to reception of CAN message. If a particular bit is set; corresponding meaning is TRUE or else it will be FALSE. const const const const const const const const const const const const _CAN_RX_FILTER_BITS _CAN_RX_FILTER_1 _CAN_RX_FILTER_2 _CAN_RX_FILTER_3 _CAN_RX_FILTER_4 _CAN_RX_FILTER_5 _CAN_RX_FILTER_6 _CAN_RX_OVERFLOW _CAN_RX_INVALID_MSG _CAN_RX_XTD_FRAME _CAN_RX_RTR_FRAME _CAN_RX_DBL_BUFFERED = = = = = = = = = = = = $07 $00 $01 $02 $03 $04 $05 $08 $10 $20 $40 $80 'Use it to access filter bits
' Set if Overflowed; else clear ' Set if invalid; else clear ' Set if XTD message; else clear ' Set if RTR message; else clear ' Set if message was ' hardware double-buffered
You may use bitwise and to adjust the appropriate flags. For example:
if (MsgFlag and CAN_RX_OVERFLOW) = 0 then ... ' Receiver overflow has occurred. ' We have lost our previous message.
CAN_MASK
CAN_MASK constants define mask codes. Function these as its argument: const CAN_MASK_B1 const CAN_MASK_B2 = 0 = 1 CANSetMask expects one of
CAN_FILTER
CAN_FILTER constants define filter codes. Function CANSetFilter expects one of
214
Libraries
Library Example
This is a simple demonstration of CAN 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 CAN_1st dim Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags as byte ' can flags Rx_Data_Len as byte ' received data length in bytes RxTx_Data as byte[8] ' can rx/tx data buffer Msg_Rcvd as byte ' reception flag ID_1st, ID_2nd as longint ' node IDs Rx_ID as longint main: PORTC = 0 TRISC = 0 Can_Init_Flags = 0 Can_Send_Flags = 0 Can_Rcv_Flags = 0
' clear PORTC ' set PORTC as output ' ' clear flags ' ' form value to be used ' with CANWrite
Can_Init_Flags = _CAN_CONFIG_SAMPLE_THRICE and 'form value to be used _CAN_CONFIG_PHSEG2_PRG_ON and 'with CANInit _CAN_CONFIG_XTD_MSG and _CAN_CONFIG_DBL_BUFFER_ON and _CAN_CONFIG_VALID_XTD_MSG ID_1st = 12111 ID_2nd = 3 RxTx_Data[0] = 9 ' set initial data to be sent CANInitialize(1,3,3,3,1,Can_Init_Flags) ' Initialize CAN module CANSetOperationMode(_CAN_MODE_CONFIG,0xFF) ' set CONFIGURATION mode CANSetMask(_CAN_MASK_B1,-1,_CAN_CONFIG_XTD_MSG) ' set all mask1 bits to ones CANSetMask(_CAN_MASK_B2,-1,_CAN_CONFIG_XTD_MSG) ' set all mask2 bits to ones CANSetFilter(_CAN_FILTER_B2_F4,ID_2nd,_CAN_CONFIG_XTD_MSG) 'set id of filter B2_F4 to 2nd node ID CANSetOperationMode(_CAN_MODE_NORMAL,0xFF) 'set NORMAL mode
215
CHAPTER 7
Libraries
' clear PORTC ' set PORTC as output ' ' clear flags '
Can_Send_Flags = _CAN_TX_PRIORITY_0 and ' form value to be used _CAN_TX_XTD_FRAME and ' with CANWrite _CAN_TX_NO_RTR_FRAME Can_Init_Flags = _CAN_CONFIG_SAMPLE_THRICE and ' form value to be used _CAN_CONFIG_PHSEG2_PRG_ON and 'with CANInit _CAN_CONFIG_XTD_MSG and _CAN_CONFIG_DBL_BUFFER_ON and _CAN_CONFIG_VALID_XTD_MSG and _CAN_CONFIG_LINE_FILTER_OFF ID_1st = 12111 ID_2nd = 3 RxTx_Data[0] = 9 ' set initial data to be sent
216
Libraries
CANInitialize(1,3,3,3,1,Can_Init_Flags ' initialize external CAN module CANSetOperationMode(_CAN_MODE_CONFIG,0xFF) ' set CONFIGURATION mode CANSetMask(_CAN_MASK_B1,-1,_CAN_CONFIG_XTD_MSG) ' set all mask1 bits to ones CANSetMask(_CAN_MASK_B2,-1,_CAN_CONFIG_XTD_MSG) ' set all mask2 bits to ones CANSetFilter(_CAN_FILTER_B2_F3,ID_1st,_CAN_CONFIG_XTD_MSG) ' set id of filter B2_F3 to 1st node ID CANSetOperationMode(_CAN_MODE_NORMAL,0xFF) ' set NORMAL mode
while true ' endless loop Msg_Rcvd = CANRead(Rx_ID , RxTx_Data , Rx_Data_Len, Can_Rcv_ Flags) ' receive message if ((Rx_ID = ID_1st) and (Msg_Rcvd <> 0)) <> 0 then ' if message received check id PORTC = RxTx_Data[0] ' id correct, output data at PORTC Inc(RxTx_Data[0]) ' increment received data CANWrite(ID_2nd, RxTx_Data, 1, Can_Send_Flags)' send incremented data back end if wend end.
217
CHAPTER 7
Libraries
HW Connection
218
Libraries
CANSPI LIBRARY
The SPI module is available with a number of the PIC compliant MCUs. The mikroBasic PRO for PIC 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, selfchecking 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. The library uses the SPI module for communication. User must initialize SPI module before using the SPI Graphic Lcd Library. For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the SPI_Set_Active routine. CANSPI module refers to mikroElektronika's CANSPI Add-on board connect ed to SPI module of MCU.
219
CHAPTER 7
Libraries
External dependecies of CANSPI Library
The following variables must be defined in all projects using CANSPI Library:
dim CanSpi_CS as sbit sfr external
Description:
Example :
Reset line.
dim dim CanSpi_Rst_Bit_Dire CanSpi_Rst_Bit_Direc ction as sbit sfr Direction of the Reset pin. tion as sbit at TRISC2_bit external
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.
220
Libraries
CANSPISetOperationMode
Prototype Returns
sub procedure CANSPISetOperationMode(dim mode as byte, dim WAIT as byte)
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 wont return until the requested mode is set.
The CANSPI routines are supported only by MCUs with the SPI module. Requires 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)
Example
CANSPIGetOperationMode
Prototype Returns
sub function CANSPIGetOperationMode() as byte
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 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
Example
221
CHAPTER 7
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 CANSPI_CONFIG_FLAGS as byte)
Returns
Stand-Alone CAN controller in the CANSPI module is set to: 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 Description 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 con stants) Global variables :
CanSpi_CS: Chip Select line CanSpi_Rst: Reset line CanSpi_CS_Bit_Direction: Direction of the Chip Select pin
CanSpi_Rst_Bit_Direction: Direction of the Reset pin Requires must be defined before using this function. The CANSPI routines are supported only by MCUs with the SPI module. The SPI module needs to be initialized. See the SPI1_Init and SPI1_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.
222
Libraries
Example
223
CHAPTER 7
Libraries
CANSPISetBaudRate
Prototype Returns
sub procedure CANSPISetBaudRate(dim SJW as byte, dim BRP as byte, dim PHSEG1 as byte, dim PHSEG2 as byte, dim PROPSEG as byte, dim CANSPI_CONFIG_FLAGS as byte)
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 CANSPI_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 con stants) 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 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)
Example
224
Libraries
CANSPISetMask
Prototype Returns
sub procedure CANSPISetMask(dim CANSPI_MASK as byte, dim val as longint, dim CANSPI_CONFIG_FLAGS as byte)
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 costants (see CANSPI constants) 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.
Description
(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)
225
CHAPTER 7
Libraries
CANSPISetFilter
Prototype Returns
sub procedure CANSPISetFilter(dim CANSPI_FILTER as byte, dim val as longint, dim CANSPI_CONFIG_FLAGS as byte)
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) 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.
Description
The CANSPI module must be in Config mode, otherwise the 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 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)
Example
226
Libraries
CANSPIRead
Prototype Returns
sub function CANSPIRead(dim byref id as longint, dim byref rd_data as byte[8], dim data_len as byte, dim CANSPI_RX_MSG_FLAGS as byte) as byte 0 if nothing is received 0xFF if one of the Receive Buffers is full (message received)
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.
' 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 byte[8] 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
Example
227
CHAPTER 7
Libraries
CANSPIWrite
Prototype
sub function CANSPIWrite(dim id as longint, dim byref wr_data as byte[8], dim data_len as byte, dim CANSPI_TX_MSG_FLAGS as byte) as byte 0 if all Transmit Buffers are busy 0xFF if at least one Transmit Buffer is available
Returns
If at least one empty Transmit Buffer is found, the function sends message in the queue for transmission. Parameters: Description
id:CAN message identifier. Valid values: 11 or 29 bit values, depending
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.
' send message extended CAN message with the appropriate ID and data dim tx_flags as byte rd_data as byte[8] msg_id as longint ... CANSPISetOperationMode(_CANSPI_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)
Example
228
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. Function CANSPISetOperationMode expects one of these as it's argument:
const _CANSPI_MODE_BITS as byte = 0xE0 Use this to access opmode _CANSPI_MODE_NORMAL as byte = 0x00 _CANSPI_MODE_SLEEP as byte = 0x20 _CANSPI_MODE_LOOP as byte = 0x40 _CANSPI_MODE_LISTEN as byte = 0x60 _CANSPI_MODE_CONFIG as byte = 0x80 bits
CANSPI_CONFIG_FLAGS
The CANSPI_CONFIG_FLAGS constants define flags related to the CANSPI module configuration. The 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 _CANSPI_CONFIG_LINE_FILTER_BIT _CANSPI_CONFIG_LINE_FILTER_ON _CANSPI_CONFIG_LINE_FILTER_OFF _CANSPI_CONFIG_SAMPLE_BIT _CANSPI_CONFIG_SAMPLE_ONCE _CANSPI_CONFIG_SAMPLE_THRICE _CANSPI_CONFIG_MSG_TYPE_BIT _CANSPI_CONFIG_STD_MSG _CANSPI_CONFIG_XTD_MSG as byte as byte as byte as byte = $FF = $01 = $FF = $FE ' 11111111
as byte = $02 as byte = $FF as byte = $FD as byte = $04 as byte = $FF as byte = $FB as byte = $08 as byte = $FF as byte = $F7
_CANSPI_CONFIG_DBL_BUFFER_BIT _CANSPI_CONFIG_DBL_BUFFER_ON
229
CHAPTER 7
Libraries
_CANSPI_CONFIG_DBL_BUFFER_OFF as byte = $EF _CANSPI_CONFIG_MSG_BITS _CANSPI_CONFIG_ALL_MSG _CANSPI_CONFIG_VALID_XTD_MSG _CANSPI_CONFIG_VALID_STD_MSG _CANSPI_CONFIG_ALL_VALID_MSG as as as as as byte byte byte byte byte = = = = = $60 $FF $DF $BF $9F
' XXX0XXXX
You may use bitwise and to form config byte out of these values. For example:
init = _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 ' 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 _CANSPI_TX_FRAME_BIT _CANSPI_TX_STD_FRAME _CANSPI_TX_XTD_FRAME _CANSPI_TX_RTR_BIT _CANSPI_TX_NO_RTR_FRAME _CANSPI_TX_RTR_FRAME
as as as as as
= = = = =
$03 $FC $FD $FE $FF = $08 = $FF = $F7 = $40 = $FF = $BF
You may use bitwise and to adjust the appropriate flags. For example:
' form value to be used with CANSendMessage: send_config = _CANSPI_TX_PRIORITY_0 and _CANSPI_TX_XTD_FRAME and _CANSPI_TX_NO_RTR_FRAME ... CANSPI1Write(id, data, 1, send_config)
230
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 ter 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 _CANSPI_RX_OVERFLOW cleared _CANSPI_RX_INVALID_MSG cleared _CANSPI_RX_XTD_FRAME cleared _CANSPI_RX_RTR_FRAME cleare _CANSPI_RX_DBL_BUFFERED hardware double-buffered as byte = $07 as as as as as as byte byte byte byte byte byte = = = = = = $00 $01 $02 $03 $04 $05 ' Set if Overflowed else ' Set if invalid else ' Set if XTD message else ' Set if RTR message else ' Set if this message was ' Use this to access fil-
as byte = $08 as byte = $10 as byte = $20 as byte = $40 as byte = $80
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. Function CANSPISetMask expects one of these as it's argument:
const _CANSPI_MASK_B1 as byte = 0 _CANSPI_MASK_B2 as byte = 1
CANSPI_FILTER
The CANSPI_FILTER constants define filter codes. 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 as as as as as as byte byte byte byte byte byte = = = = = = 0 1 2 3 4 5
231
CHAPTER 7
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 Can_Spi_1st 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 RC0_bit CanSpi_CS_Direction as sbit at TRISC0_bit CanSpi_Rst as sbit at RC2_bit CanSpi_Rst_Direction as sbit at TRISC2_bit ' End CANSPI module connections main: ANSEL = 0 ANSELH = 0 PORTB = 0 TRISB = 0 Can_Init_Flags = 0 Can_Send_Flags = 0 Can_Rcv_Flags = 0
Can_Send_Flags = _CANSPI_TX_PRIORITY_0 and ' form value to be used _CANSPI_TX_XTD_FRAME and ' with CANSPIWrite _CANSPI_TX_NO_RTR_FRAME Can_Init_Flags = _CANSPI_CONFIG_SAMPLE_THRICE and ' form value to be used _CANSPI_CONFIG_PHSEG2_PRG_ON and ' with CANSPIInit _CANSPI_CONFIG_XTD_MSG and _CANSPI_CONFIG_DBL_BUFFER_ON and _CANSPI_CONFIG_VALID_XTD_MSG
232
Libraries
SPI1_Init() ' initialize SPI1 module CANSPIInitialize(1,3,3,3,1,Can_Init_Flags) 'Initialize external CANSPI module CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF) 'set CONFIGURATION mode CANSPISetMask(_CANSPI_MASK_B1,-1,_CANSPI_CONFIG_XTD_MSG) 'set all mask1 bits to ones CANSPISetMask(_CANSPI_MASK_B2,-1,_CANSPI_CONFIG_XTD_MSG) 'set all mask2 bits to ones CANSPISetFilter(_CANSPI_FILTER_B2_F4,3,_CANSPI_CONFIG_XTD_MSG) 'set id of filter B1_F1 to 3 CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF) RxTx_Data[0] = 9 Tx_ID = 12111 set transmit ID 'set NORMAL mode
CANSPIWrite(Tx_ID, RxTx_Data, 1, Can_Send_Flags) ' send initial message while TRUE ' endless loop Msg_Rcvd = CANSPIRead(Rx_ID , RxTx_Data , Rx_Data_Len, Can_Rcv_Flags) ' receive message if ((Rx_ID = 3) and Msg_Rcvd) then ' if message received check id PORTB = RxTx_Data[0] ' id correct, output data at PORTC Inc(RxTx_Data[0]) ' increment received data Delay_ms(10) CANSPIWrite(Tx_ID, RxTx_Data, 1, Can_Send_Flags) ' send incremented data back end if wend end.
233
CHAPTER 7
Libraries
CanSpi_Rst as sbit at PORTC.B2 CanSpi_Rst_Direction as sbit at TRISC2_bit ' End CANSPI module connections main: ANSEL = 0 ANSELH = 0 PORTB = 0 TRISB = 0 Can_Init_Flags = 0 Can_Send_Flags = 0 Can_Rcv_Flags = 0
' Configure AN pins as digital I/O ' clear PORTB ' set PORTB as output ' ' clear flags '
Can_Send_Flags = _CANSPI_TX_PRIORITY_0 and ' form value to be used _CANSPI_TX_XTD_FRAME and ' with CANSPIWrite _CANSPI_TX_NO_RTR_FRAME Can_Init_Flags = _CANSPI_CONFIG_SAMPLE_THRICE and ' Form value to be used _CANSPI_CONFIG_PHSEG2_PRG_ON and ' with CANSPIInit _CANSPI_CONFIG_XTD_MSG and _CANSPI_CONFIG_DBL_BUFFER_ON and _CANSPI_CONFIG_VALID_XTD_MSG and _CANSPI_CONFIG_LINE_FILTER_OFF SPI1_Init() ' initialize SPI1 module CANSPIInitialize(1,3,3,3,1,Can_Init_Flags) ' initialize external CANSPI module CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF) ' set CONFIGURATION mode CANSPISetMask(_CANSPI_MASK_B1,-1,_CANSPI_CONFIG_XTD_MSG) ' set all mask1 bits to ones CANSPISetMask(_CANSPI_MASK_B2,-1,_CANSPI_CONFIG_XTD_MSG) ' set all mask2 bits to ones CANSPISetFilter(_CANSPI_FILTER_B2_F3,12111,_CANSPI_CONFIG_XTD_MSG) ' set id of filter B1_F1 to 3 CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF) ' set NORMAL mode Tx_ID = 3 ' set tx ID while TRUE ' endless loop Msg_Rcvd = CANSPIRead(Rx_ID, RxTx_Data, Rx_Data_Len, Can_Rcv_Flags) 'receive message if ((Rx_ID = 12111) and Msg_Rcvd) then PORTB = RxTx_Data[0] ' id correct, output data at PORTC Inc(RxTx_Data[0]) ' increment received data
234
Libraries
' send incremented
HW Connection
Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface
235
CHAPTER 7
The Compact Flash Library provides routines for accessing data on Compact Flash card (abbr. CF further in text). CF cards are widely used memory elements, commonly used with digital cameras. Great capacity and excellent access time of only a few microseconds make them very attractive for the microcontroller applications. In CF card, data is divided into sectors. One sector usually comprises 512 bytes. Routines for file handling, the Cf_Fat routines, are not performed directly but successively through 512B buffer. Note: Routines for file handling can be used only with FAT16 file system. Note: Library functions create and read files from the root directory only. Note: Library functions populate both FAT1 and FAT2 tables when writing to files, but the file data is being read from the FAT1 table only; i.e. there is no recovery if the FAT1 table gets corrupted. Note: If MMC/SD card has Master Boot Record (MBR), the library will work with the first available primary (logical) partition that has non-zero size. If MMC/SD card has Volume Boot Record (i.e. there is only one logical partition and no MBRs), the library works with entire card as a single partition. For more information on MBR, physical and logical drives, primary/secondary partitions and partition tables, please consult other resources, e.g. Wikipedia and similar. Note: Before writing operation, make sure not to overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable. Drive mapping tools, such as Winhex, can be of great assistance.
236
Libraries
Output Enable line. signal dim CF_OE as sbit at
RB5_bit
dim CF_CE1 as sbit sfr external dim CF_A2 as sbit sfr external dim CF_A1 as sbit sfr external dim CF_A0 as sbit sfr external
dim CF_CE1 as sbit at RB3_bit dim CF_A2 as sbit at RB2_bit dim CF_A1 as sbit at RB1_bit dim CF_A0 as sbit at RB0_bit dim CF_RDY_direction as sbit at TRISB7_bit dim CF_WE_direction as sbit at TRISB6_bit
Address pin 1.
Address pin 0.
dim CF_RDY_direction as Direction of the Ready sbit sfr external pin. dim CF_WE_direction as sbit sfr external dim CF_OE_direction as sbit sfr external
dim CF_CD1_direction as Direction of the Chip sbit sfr external Detect pin. dim CF_CE1_direction as Direction of the Chip sbit sfr external Enable pin. dim CF_A2_direction as sbit sfr external dim CF_A1_direction as sbit sfr external dim CF_A0_direction as sbit sfr external
Direction of the Address dim CF_A2_direction as sbit at TRISB2_bit 2 pin. Direction of the Address dim CF_A1_direction as sbit at TRISB1_bit 1 pin. Direction of the Address dim CF_A0_direction as sbit at TRISB0_bit 0 pin.
237
CHAPTER 7
Libraries
Library Routines
Cf_Init Cf_Detect Cf_Enable Cf_Disable Cf_Read_Init Cf_Read_Byte Cf_Write_Init Cf_Write_Byte Cf_Read_Sector Cf_Write_Sector Routines for file handling: Cf_Fat_Init Cf_Fat_QuickFormat Cf_Fat_Assign Cf_Fat_Reset Cf_Fat_Read Cf_Fat_Rewrite Cf_Fat_Append Cf_Fat_Delete Cf_Fat_Write Cf_Fat_Set_File_Date Cf_Fat_Get_File_Date Cf_Fat_Get_File_Size Cf_Fat_Get_Swap_File
238
Libraries
Cf_Init
Prototype Returns
sub procedure Cf_Init()
Nothing.
Description Initializes ports appropriately for communication with CF card. Global variables :
CF_Data_Port : Compact Flash data port CF_RDY : Ready signal line CF_WE : Write enable signal line CF_OE : Output enable signal line CF_CD1 : Chip detect signal line CF_CE1 : Enable signal line CF_A2 : Address pin 2 CF_A1 : Address pin 1 CF_A0 : Address pin 0 CF_Data_Port_direction : Direction of the Compact Flash data direction port CF_RDY_direction : Direction of the Ready pin CF_WE_direction : Direction of the Write enable pin CF_OE_direction : Direction of the Output enable pin CF_CD1_direction : Direction of the Chip detect pin CF_CE1_direction : Direction of the Chip enable pin CF_A2_direction : Direction of the Address 2 pin CF_A1_direction : Direction of the Address 1 pin CF_A0_direction : Direction of the Address 0 pin
Requires
Example
239
CHAPTER 7
Libraries
Cf_Detect
Prototype Returns sub function CF_Detect() as byte 1 - if CF card was detected 0 - otherwise
Description Checks for presence of CF card by reading the chip detect pin. Requires Example
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init. ' Wait until CF card is inserted: while (Cf_Detect() = 0) nop wend
Cf_Enable
Prototype Returns sub procedure Cf_Enable() Nothing.
Enables the device. Routine needs to be called only if you have disabled the Description device by means of the Cf_Disable routine. These two routines in conjunction allow you to free/occupy data line when working with multiple devices. Requires Example The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
' enable compact flash Cf_Enable()
Cf_Disable
Prototype Returns sub procedure Cf_Disable() Nothing.
Routine disables the device and frees the data lines for other devices. To Description enable the device again, call Cf_Enable. These two routines in conjunction allow you to free/occupy data line when working with multiple devices. Requires Example
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init. ' disable compact flash Cf_Disable()
240
Libraries
Cf_Read_Init
Prototype Returns sub procedure Cf_Read_Init(dim address as longword, dim sector_count as byte) Nothing. Initializes CF card for reading. Description Parameters :
address: the first sector to be prepared for reading opera tion. sector_count: number of sectors to be prepared for read ing operation.
Requires Example
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init. ' initialize compact flash for reading from sector 590 Cf_Read_Init(590, 1)
Cf_Read_Byte
Prototype Returns Note: Higher byte of the unsigned return value is cleared. Description Requires
CF card must be initialized for reading operation. See Cf_Read_Init. ' Read a byte from compact flash: dim data as byte ... data = Cf_Read_Byte() sub function CF_Read_Byte() as byte
Reads one byte from Compact Flash sector buffer location currently pointed to by internal read pointers. These pointers will be autoicremented upon reading.
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
Example
241
CHAPTER 7
Libraries
Cf_Write_Init
Prototype Returns
sub procedure Cf_Write_Init(dim address as longword, dim sectcnt as byte) Nothing. Initializes CF card for writing.
Description
Parameters :
address: the first sector to be prepared for writing operation sectcnt: number of sectors to be prepared for writing operation.
Requires Example
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init. ' initialize compact flash for writing to sector 590 Cf_Write_Init(590, 1)
Cf_Write_Byte
Prototype Returns sub procedure Cf_Write_Byte(dim data_ as byte) Nothing. Writes a byte to Compact Flash sector buffer location currently pointed to by writing pointers. These pointers will be autoicremented upon reading. When sector buffer is full, its content will be transfered to appropriate flash memory sector. Parameters :
data_: byte to be written.
Description
Requires
The corresponding MCU ports must be appropriately initialized for CF card. CF card must be initialized for writing operation. See Cf_Write_Init. dim data_ as byte ... data = 0xAA Cf_Write_Byte(data)
Example
242
Libraries
Cf_Read_Sector
Prototype Returns
sub procedure Cf_Read_Sector(dim sector_number as longword, dim byref buffer as byte[512])
Nothing. Reads one sector (512 bytes). Read data is stored into buffer provided by the buffer parameter.
Description
Parameters :
sector_number: sector to be read. buffer: data buffer of at least 512 bytes in length.
Requires Example
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init. ' read sector 22 dim data as array[512] of byte ... Cf_Read_Sector(22, data)
Cf_Write_Sector
Prototype Returns
sub procedure Cf_Write_Sector(dim sector_number as longword, dim byref buffer as byte[512])
Nothing. Writes 512 bytes of data provided by the buffer parameter to one CF sector. Parameters :
Description
sector_number: sector to be written to. buffer: data buffer of 512 bytes in length
Requires Example
The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init. ' write to sector 22 dim data as array[512] of byte ... Cf_Write_Sector(22, data)
243
CHAPTER 7
Libraries
Cf_Fat_Init
Prototype Returns
sub function Cf_Fat_Init() as byte
0 - if CF card was detected and successfully initialized 1 - if FAT16 boot sector was not found 255 - if card was not detected
Initializes CF card, reads CF FAT16 boot sector and extracts data needed by the library.
Nothing. init the FAT library if (Cf_Fat_Init() = 0) then ... end if
Cf_Fat_QuickFormat
Prototype
sub function Cf_Fat_QuickFormat(dim byref cf_fat_label as string[11]) as byte 0 - if CF card was detected and formated and initialized 1 - if FAT16 format was unseccessful 255 - if card was not detected
Returns
Note: If CF card already contains a valid boot sector, it will remain unchanged (except volume label field) and only FAT and ROOT tables will be erased. Also, the new volume label will be set. Requires Example
Nothing. '--- format and initialize the FAT library if ( Cf_Fat_QuickFormat('mikroE') = 0) then ... end if
244
Libraries
Cf_Fat_Assign
Prototype Returns
sub function Cf_Fat_Assign(dim byref filename as char[12], dim file_cre_attr as byte) as byte
0 if file does not exist and no new file is created. 1 if file already exists or file does not exist but a new file is created.
Assigns file for file operations (read, write, delete...). All subsequent file operations will be applied to the assigned file. Parameters : filename: name of the file that should be assigned for file operations. The file name should be in DOS 8.3 (file_name.extension) format. The file name and extension will be automatically padded with spaces by the library if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so the user does not have to take care of that. The file name and extension are case insensitive. The library will convert them to the proper case automatically, so the user does not have to take care of that. Also, in order to keep backward compatibility with the first version of this library, file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension (i.e. "MIKROELETXT" -> MIKROELE.TXT). In this case the last 3 characters of the string are considered to be file extension. file_cre_attr: file creation and attributs flags. Each bit corresponds to Description the appropriate file attribut:
Bit 0 1 2 3 4 5 6 7 Mask 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80 Description Read Only Hidden System Volume Label Subdirectory Archive Device (internal use only, never found on disk) File creation flag. If the file does not exist and this flag is set, a new file with specified name will be created.
Note: Long File Names (LFN) are not supported. Requires Example CF card and CF library must be initialized for file operations. See Cf_Fat_Init
' create file with archive attribut if it does not already exist Cf_Fat_Assign('MIKRO007.TXT',0xA0)
245
CHAPTER 7
Libraries
Cf_Fat_Reset
Prototype Returns
Opens currently assigned file for reading. Parameters : Description size: buffer to store file size to. After file has been open for reading its size is returned through this parameter. Requires Example CF card and CF library must be initialized for file operations. See Cf_Fat_Init. File must be previously assigned. See Cf_Fat_Assign
dim size as longword ... Cf_Fat_Reset(size)
Cf_Fat_Read
Prototype Returns sub procedure Cf_Fat_Read(dim byref bdata as byte) Nothing.
Reads a byte from currently assigned file opened for reading. Upon function execution file pointers will be set to the next character in the file. Description Parameters : bdata: buffer to store read byte to. Upon this function execution read byte is returned through this parameter Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init. File must be previously assigned. See Cf_Fat_Assign. File must be open for reading. See Cf_Fat_Reset.
dim character as byte ... Cf_Fat_Read(character)
Example
246
Libraries
Cf_Fat_Rewrite
Prototype Returns Description sub procedure Cf_Fat_Read() Nothing. Opens currently assigned file for writing. If the file is not empty its content will be erased. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires The file must be previously assigned. See Cf_Fat_Assign. Example
' open file for writing Cf_Fat_Rewrite()
Cf_Fat_Append
Prototype Returns sub procedure Cf_Fat_Append() Nothing.
Opens currently assigned file for appending. Upon this function execution file Description pointers will be positioned after the last byte in the file, so any subsequent file writing operation will start from there. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. Example
'open file for appending Cf_Fat_Append()
247
CHAPTER 7
Libraries
Cf_Fat_Delete
Prototype Returns sub procedure Cf_Fat_Delete() Nothing.
Description Deletes currently assigned file from CF card. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. Example
'delete current file Cf_Fat_Delete()
Cf_Fat_Write
Prototype Returns sub procedure Cf_Fat_Write(dim byref fdata as byte[512], dim data_len as word) Nothing. Writes requested number of bytes to currently assigned file opened for writing. Parameters : Description
fdata: data to be written. data_len: number of bytes to be written.
CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append
dim file_contents as array[42] of byte ... Cf_Fat_Write(file_contents, 42) ' write data to the assigned file
Example
248
Libraries
Cf_Fat_Set_File_Date
Prototype Returns sub procedure Cf_Fat_Set_File_Date(dim year as word, dim month as byte, dim day as byte, dim hours as byte, dim mins as byte, dim seconds as byte) Nothing. Sets the date/time stamp. Any subsequent file writing operation will write this stamp to currently assigned file's time/date attributs. Parameters : Description
year: year attribute. Valid values: 1980-2107 month: month attribute. Valid values: 1-12 day: day attribute. Valid values: 1-31 hours: hours attribute. Valid values: 0-23 mins: minutes attribute. Valid values: 0-59 seconds: seconds attribute. Valid values: 0-59
CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append. Example
Cf_Fat_Set_File_Date(2005,9,30,17,41,0)
249
CHAPTER 7
Libraries
Cf_Fat_Get_File_Date
Prototype Returns
sub procedure Cf_Fat_Get_File_Date(dim byref year as word, dim byref month as byte, dim byref day as byte, dim byref hours as byte, dim byref mins as byte) Nothing. Reads time/date attributes of currently assigned file.
Parameters : year:buffer to store year attribute to. Upon function execution year attribute is returned through this parameter. month: buffer to store month attribute to. Upon function execution month Description attribute is returned through this parameter. day: buffer to store day attribute to. Upon function execution day attribute is returned through this parameter. hours: buffer to store hours attribute to. Upon function execution hours attribute is returned through this parameter. mins: buffer to store minutes attribute to. Upon function execution minutes attribute is returned through this parameter. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. Example
dim year as word month, day, hours, mins as byte ... Cf_Fat_Get_File_Date(year, month, day, hours, mins)
Cf_Fat_Get_File_Size
Prototype Returns sub function Cf_Fat_Get_File_Size() as longword Size of the currently assigned file in bytes.
Description This function reads size of currently assigned file in bytes. CF card and CF library must be initialized for file operations. See Cf_Fat_Init. Requires File must be previously assigned. See Cf_Fat_Assign. Example
dim my_file_size as longword ... my_file_size = Cf_Fat_Get_File_Size()
250
Libraries
Cf_Fat_Get_Swap_File
Prototype sub function Cf_Fat_Get_Swap_File(dim sectors_cnt as longint, dim byref filename as string[11], dim file_attr as byte) as longword Number of the start sector for the newly created swap file, if there was enough free space on CF card to create file of required size. 0 - otherwise. This function is used to create a swap file of predefined name and size on the CF media. If a file with specified name already exists on the media, search for consecutive sectors will ignore sectors occupied by this file. Therefore, it is recommended to erase such file if it exists before calling this function. If it is not erased and there is still enough space for a new swap file, this function will delete it after allocating new memory space for a new swap file. The purpose of the swap file is to make reading and writing to CF media as fast as possible, by using the Cf_Read_Sector() and Cf_Write_Sector() functions directly, without potentially damaging the FAT system. The swap file can be considered as a "window" on the media where the user can freely write/read data. Its main purpose in the mikroBasic's library is to be used for fast data acquisition; when the time-critical acquisition has finished, the data can be re-written into a "normal" file, and formatted in the most suitable way. Parameters: Description
sectors_cnt: number of consecutive sectors that user wants the swap file
Returns
to have.
filename: name of the file that should be assigned for file operations. The file name should be in DOS 8.3 (file_name.extension) format. The file name and extension will be automatically padded with spaces by the library if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so the user does not have to take care of that. The file name and extension are case insensitive. The library will convert them to the proper case automatically, so the user does not have to take care of that. Also, in order to keep backward compatibility with the first version of this library, file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension (i.e. "MIKROELETXT" -> MIKROELE.TXT). In this case the last 3 characters of the string are considered to be file extension.
file_attr: file creation and attributs flags. Each bit corresponds to the appropriate file attribut:
251
CHAPTER 7
Libraries
Bit 0 1 2
Mask Description 0x01 Read Only 0x02 Hidden 0x04 System 0x08 Volume Label 0x10 Subdirectory 0x20 Archive 0x40 Device (internal use only, never found on disk) 0x80 Not used
Description
3 4 5 6 7
Note: Long File Names (LFN) are not supported. Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init.
program '-------------- Try to create a swap file with archive atribute, whose size will be at least 1000 sectors. ' If it succeeds, it sends the No. of start sector over USART dim size as longword ... main: ... size = Cf_Fat_Get_Swap_File(1000, "mikroE.txt", 0x20) if size then UART1_Write(0xAA) UART1_Write(Lo(size)) UART1_Write(Hi(size)) UART1_Write(Higher(size)) UART1_Write(Highest(size)) UART1_Write(0xAA) end if end.
Example
252
Libraries
Library Example
The following example demonstrates various aspects of the Cf_Fat16 library: Creation of new file and writing down to it; Opening existing file and re-writing it (writing from start-of-file); Opening existing file and appending data to it (writing from end-of-file); Opening a file and reading data from it (sending it to USART terminal); Creating and modifying several files at once;
program CF_Fat16_Test ' set compact flash pinout dim Cf_Data_Port as byte at PORTD CF_RDY CF_WE CF_OE CF_CD1 CF_CE1 CF_A2 CF_A1 CF_A0 as as as as as as as as sbit sbit sbit sbit sbit sbit sbit sbit at at at at at at at at RB7_bit RB6_bit RB5_bit RB4_bit RB3_bit RB2_bit RB1_bit RB0_bit sbit sbit sbit sbit sbit sbit sbit sbit at at at at at at at at TRISB7_bit TRISB6_bit TRISB5_bit TRISB4_bit TRISB3_bit TRISB2_bit TRISB1_bit TRISB0_bit
CF_RDY_direction as CF_WE_direction as CF_OE_direction as CF_CD1_direction as CF_CE1_direction as CF_A2_direction as CF_A1_direction as CF_A0_direction as ' end of cf pinout
FAT_TXT as string[20] file_contents as string[50] filename as string[14] character as byte loop_, loop2 as byte size as longint Buffer as byte[512] '-------------- Writes string to USART sub procedure Write_Str(dim byref ostr as byte[2] ) ' File names
253
CHAPTER 7
Libraries
dim i as byte i = 0 while ostr[i] <> 0 UART1_Write(ostr[i]) Inc(i) wend UART1_Write($0A) end sub
'-------------- Creates new file and writes some data to it sub procedure Create_New_File filename[7] = "A" Cf_Fat_Assign(filename, 0xA0) create file Cf_Fat_Rewrite() new data for loop_=1 to 90 card
' Will not find file and then ' To clear file and start with ' We want 5 files on the MMC
PORTC = loop_ file_contents[0] = loop_ div 10 + 48 file_contents[1] = loop_ mod 10 + 48 Cf_Fat_Write(file_contents, 38) ' write data to the assigned file UART1_Write(".") next loop_ end sub '-------------- Creates many new files and writes data to them sub procedure Create_Multiple_Files for loop2 = "B" to "Z" UART1_Write(loop2) ' this line can slow down the performance filename[7] = loop2 ' set filename Cf_Fat_Assign(filename, 0xA0) ' find existing file or create a new one Cf_Fat_Rewrite ' To clear file and start with new data for loop_ = 1 to 44 file_contents[0] = loop_ div 10 + 48 file_contents[1] = loop_ mod 10 + 48 Cf_Fat_Write(file_contents, 38) ' write data to the assigned file next loop_ next loop2 end sub '-------------- Opens an existing file and rewrites it
254
Libraries
'-------------- Opens an existing file, reads data from it and puts it to USART sub procedure Open_File_Read filename[7] = "B" Cf_Fat_Assign(filename, 0) Cf_Fat_Reset(size) ' To read file, sub procedure returns size of file while size > 0 Cf_Fat_Read(character) UART1_Write(character) ' Write data to USART Dec(size) wend end sub '-------------- Deletes a file. If file doesn"t exist, it will first be created ' and then deleted. sub procedure Delete_File filename[7] = "F" Cf_Fat_Assign(filename, 0) Cf_Fat_Delete end sub
255
CHAPTER 7
Libraries
' see
256
Libraries
UART1_Init(19200) ' Set up USART for file reading delay_ms(100) UART1_Write_Text(":Start:") ' --- Init the FAT library ' --- use Cf_Fat_QuickFormat instead of init routine if a format is needed if Cf_Fat_Init() = 0 then '--- test sub functions '----- test group #1 Create_New_File() Create_Multiple_Files() '----- test group #2 Open_File_Rewrite() Open_File_Append() Delete_File '----- test group #3 Open_File_Read() Test_File_Exist("F") M_Create_Swap_File() '--- Test termination UART1_Write(0xAA) else UART1_Write_Text(FAT_TXT) end if '--- signal end-of-test UART1_Write_Text(":End:") end.
257
CHAPTER 7
Libraries
HW Connection
258
Libraries
EEPROM LIBRARY
EEPROM data memory is available with a number of PIC MCUs. mikroBasic PRO for PIC includes library for comfortable work with EEPROM.
Library Routines
EEPROM_Read EEPROM_Write
EEPROM_Read
Prototype Returns
sub function EEPROM_Read(dim Address as word) as byte
Reads data from specified address. Parameter address is of byte type, which means it can address only 256 locations. For PIC18 micros with more EEPROM Description data locations, it is programmers responsibility to set SFR EEADRH register appropriately. Requires EEPROM module. Requires Ensure minimum 20ms delay between successive use of routines EEPROM_Write and EEPROM_Read. Although PIC will write the correct value, EEPROM_Read might return an undefined result.
tmp = EEPROM_Read($3F)
Example
259
CHAPTER 7
Libraries
EEPROM_Write
Prototype Returns
Nothing.
Writes data to specified address. Parameter address is of byte type, which means it can address only 256 locations. For PIC18 micros with more EEPROM data locations, it is programmers responsibility to set SFR EEADRH register Description appropriately. Be aware that all interrupts will be disabled during execution of EEPROM_Write routine (GIE bit of INTCON register will be cleared). Routine will set this bit on exit. Requires EEPROM module. Requires Ensure minimum 20ms delay between successive use of routines EEPROM_Write and EEPROM_Read. Although PIC will write the correct value, EEPROM_Read might return an undefined result.
EEPROM_Write($32)
Example
Library Example
The example writes values at 20 successive locations of EEPROM. Then, it reads the written data and prints on PORTB for a visual check.
program Eeprom dim counter as byte main: ANSEL = ANSELH = C1ON_bit C2ON_bit ' loop variable
0 0 = 0 = 0
PORTB = 0 PORTC = 0 PORTD = 0 TRISB = 0 TRISC = 0 TRISD = 0 for counter = 0 to 31 ' Fill data buffer EEPROM_Write(0x80+counter, counter) 'Write data to address 0x80+ii next counter EEPROM_Write(0x02,0xAA) EEPROM_Write(0x50,0x55) ' Write some data at address 2 ' Write some data at address 0150
260
Libraries
' Blink PORTB and PORTC diodes ' to indicate reading start
261
CHAPTER 7
Libraries
Ethernet PIC18FxxJ60 Library
PIC18FxxJ60 family of microcontrollers feature an embedded Ethernet controller module. This is a complete connectivity solution, including full implementations of both Media Access Control (MAC) and Physical Layer transceiver (PHY) modules. Two pulse transformers and a few passive components are all that are required to connect the microcontroller directly to an Ethernet network.
The Ethernet module meets all of the IEEE 802.3 specifications for 10-BaseT connectivity to a twisted-pair network. 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. Provisions are also made for two LED outputs to indicate link and network activity This library provides the posibility to easily utilize ethernet feature of the above mentioned MCUs. Ethernet PIC18FxxJ60 library supports: IPv4 protocol. ARP requests. ICMP echo requests. UDP requests. TCP requests (no stack, no packet reconstruction). ARP client with cache. DNS client. UDP client. DHCP client. packet fragmentation is NOT supported. Note: Global library variable Ethernet_userTimerSec is used to keep track of time for all client implementations (ARP, DNS, UDP and DHCP). It is user responsibility to increment this variable each second in it's code if any of the clients is used. Note: For advanced users there are header files ("eth_j60LibDef.h" and "eth_j60LibPrivate.h") in Uses\P18 folder of the compiler with description of all routines and global variables, relevant to the user, implemented in the Ethernet PIC18FxxJ60 Library.
262
Libraries
Library Routines
Ethernet_Init Ethernet_Enable Ethernet_Disable Ethernet_doPacket Ethernet_putByte Ethernet_putBytes Ethernet_putString Ethernet_putConstString Ethernet_putConstBytes Ethernet_getByte Ethernet_getBytes Ethernet_UserTCP Ethernet_UserUDP Ethernet_getIpAddress Ethernet_getGwIpAddress Ethernet_getDnsIpAddress Ethernet_getIpMask Ethernet_confNetwork Ethernet_arpResolve Ethernet_sendUDP Ethernet_dnsResolve Ethernet_initDHCP Ethernet_doDHCPLeaseTime Ethernet_renewDHCP
263
CHAPTER 7
Libraries
Ethernet_Init
Prototype Returns
sub procedure Ethernet_Init(dim byref mac as byte, dim byref ip as byte, dim fullDuplex as byte)
Nothing. This is MAC module routine. It initializes Ethernet controller. This function is internaly splited into 2 parts to help linker when coming short of memory. Ethernet controller settings (parameters not mentioned here are set to default): 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 Broad cast 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. half duplex loopback disabled. LED configuration: default (LEDA-link status, LEDB-link activity). Parameters:
mac: RAM buffer containing valid MAC address.
Description
ip: RAM buffer containing valid IP address. fullDuplex: ethernet duplex mode switch. Valid values: 0 (half duplex mode, predefined library const Ethernet_HALFDUPLEX) and 1 (full duplex mode, predefined library const Ethernet_FULLDUPLEX). Note: If a DHCP server is to be used, IP address should be set to 0.0.0.0. Requires Nothing.
dim myMacAddr as myIpAddr as ... myMacAddr[0] myMacAddr[1] myMacAddr[2] myMacAddr[3] myMacAddr[4] myMacAddr[5] myIpAddr[0] myIpAddr[1] myIpAddr[2] myIpAddr[3] byte[6] ' my MAC address byte[4] ' my IP addr = = = = = = = = = = 0x00 0x14 0xA5 0x76 0x19 0x3F 192 168 20 60
Example
264
Libraries
Ethernet_Enable
Prototype Returns
sub procedure Ethernet_Enable(dim enFlt as byte)
Nothing. This is MAC module routine. This routine enables appropriate network traffic on the MCU's internal Ethernet 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
MAC Broadcast traffic/receive filter flag. When _Ethernet_BROADCAST set, MAC broadcast traffic will be enabled. MAC Multicast traffic/receive filter flag. When set, MAC multicast traffic will be enabled. not used not used not used CRC check flag. When set, packets with invalid CRC field will be discarded. not used _Ethernet_MULTICAST
Description
2 3 4 5 6 7
none
MAC Unicast traffic/receive filter flag. When _Ethernet_UNICAST set, MAC unicast traffic will be enabled.
Note: Advance filtering available in the MCU's internal Ethernet 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 MCU's internal Ethernet module. The MCU's internal Ethernet module should be properly cofigured by the means of Ethernet_Init routine. Requires Example Ethernet module has to be initialized. See Ethernet_Init.
Ethernet_Enable(_Ethernet_CRC or _Ethernet_UNICAST) ' enable CRC checking and Unicast traffic
265
CHAPTER 7
Libraries
Ethernet_Disable
Prototype Returns
Nothing. This is MAC module routine. This routine disables appropriate network traffic on the MCU's internal Ethernet 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 0 1 Mask Description 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80
MAC Broadcast traffic/receive filter flag. When _Ethernet_BROADCAST set, MAC broadcast traffic will be disabled. MAC Multicast traffic/receive filter flag. When set, MAC multicast traffic will be disabled. not used not used not used _Ethernet_MULTICAST
Description
2 3 4 5 6 7
CRC check flag. When set, CRC check will be disabled and packets with invalid CRC _Ethernet_CRC field will be accepted. not used
none
MAC Unicast traffic/receive filter flag. When _Ethernet_UNICAST set, MAC unicast traffic will be disabled.
Note: Advance filtering available in the MCU's internal Ethernet module such as Pattern Match, Magic Packet and Hash Table can not be disabled by this routine. 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 MCU's internal Ethernet module. The MCU's internal Ethernet module should be properly cofigured by the means of Ethernet_Init routine. Requires Example Ethernet module has to be initialized. See Ethernet_Init.
Ethernet_Enable(_Ethernet_CRC or _Ethernet_UNICAST) ' enable CRC checking and Unicast traffic
266
Libraries
Ethernet_doPacket
Prototype
sub procedure EEPROM_Write(dim Address as word, dim Data as byte)
Returns
0 - upon successful packet processing (zero packets received or received packet processed successfully). 1 - upon reception error or receive buffer corruption. Ethernet 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:
Description
ARP & ICMP requests are replied automatically. upon TCP request the Ethernet_UserTCP function is called for further processing. upon UDP request the Ethernet_UserUDP function is called for further processing. Note: Ethernet_doPacket must be called as often as possible in user's code.
Requires
Example
267
CHAPTER 7
Libraries
Ethernet_putByte
Prototype Returns
sub procedure Ethernet_putByte(dim v as byte)
Nothing. This is MAC module routine. It stores one byte to address pointed by the current Ethernet controller's write pointer (EWRPT).
Description
Parameters:
v: value to store
Requires
Example
Ethernet_putBytes
Prototype Returns
sub procedure Ethernet_putBytes(dim ptr as ^byte, dim n as byte)
Nothing. This is MAC module routine. It stores requested number of bytes into Ethernet controller's RAM starting from current Ethernet controller's write pointer (EWRPT) location.
Description
Parameters:
ptr: RAM buffer containing bytes to be written into Ethernet controller's RAM. n: number of bytes to be written
Requires
Example
268
Libraries
Ethernet_putConstBytes
Prototype Returns
sub procedure Ethernet_putConstBytes(const ptr as ^byte, dim n as byte)
Nothing. This is MAC module routine. It stores requested number of const bytes into Ethernet controller's RAM starting from current Ethernet controller's write pointer (EWRPT) location.
Description
Parameters:
ptr: const buffer containing bytes to be written into Ethernet controller's RAM. n: number of bytes to be written.
Requires
Example
Ethernet_putString
Prototype Returns
sub function Ethernet_putString(dim ptr as ^byte) as word
Number of bytes written into Ethernet controller's RAM. This is MAC module routine. It stores whole string (excluding null termination) into Ethernet controller's RAM starting from current Ethernet controller's write pointer (EWRPT) location.
Description Parameters:
ptr: string to be written into Ethernet controller's RAM.
Requires
Example
269
CHAPTER 7
Libraries
Ethernet_putConstString
Prototype Returns
Number of bytes written into Ethernet controller's RAM. This is MAC module routine. It stores whole const string (excluding null termination) into Ethernet controller's RAM starting from current Ethernet controller's write pointer (EWRPT) location.
Description Parameters:
ptr: const string to be written into Ethernet controller's RAM.
Requires
Example
Ethernet_getByte
Prototype Returns Description Requires
sub function Ethernet_getByte() as byte
Byte read from Ethernet controller's RAM. This is MAC module routine. It fetches a byte from address pointed to by current Ethernet controller's read pointer (ERDPT). Ethernet module has to be initialized. See Ethernet_Init.
dim buffer as byte ... buffer = Ethernet_getByte() buffer
Example
270
Libraries
Ethernet_getBytes
Prototype Returns
sub procedure Ethernet_getBytes(dim ptr as ^byte, dim addr as word, dim n as byte)
Nothing. This is MAC module routine. It fetches equested number of bytes from Ethernet controller's RAM starting from given address. If value of 0xFFFF is passed as the address parameter, the reading will start from current Ethernet controller's read pointer (ERDPT) location.
Description
Parameters:
ptr: buffer for storing bytes read from Ethernet controller's RAM. addr: Ethernet controller's RAM start address. Valid values: 0..8192. n: number of bytes to be read.
Requires
Example
271
CHAPTER 7
Libraries
Ethernet_UserTCP
Prototype Returns
sub function Ethernet_UserTCP(dim byref remoteHost as byte[4], dim remotePort, localPort, reqLength as word) as word
0 - there should not be a reply to the request. Length of TCP/HTTP reply data field - otherwise. This is TCP module routine. It is internally called by the library. The user accesses to the TCP/HTTP request by using some of the Ethernet_get routines. The user puts data in the transmit buffer by using some of the 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 Example Ethernet module has to be initialized. See Ethernet_Init. This function is internally called by the library and should not be called by the user's code.
272
Libraries
Ethernet_UserUDP
Prototype Returns
sub function Ethernet_UserUDP(dim byref remoteHost as byte[4], dim remotePort, destPort, reqLength as word) as word
0 - there should not be a reply to the request. Length of UDP reply data field - otherwise. This is UDP module routine. It is internally called by the library. The user accesses to the UDP request by using some of the Ethernet_get routines. The user puts data in the transmit buffer by using some of the 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. Parameters:
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 Example Ethernet module has to be initialized. See Ethernet_Init. This function is internally called by the library and should not be called by the user's code.
273
CHAPTER 7
Libraries
Ethernet_getIpAddress
Prototype Returns
sub function Ethernet_getIpAddress() as word
Ponter to the global variable holding IP address. This routine should be used when DHCP server is present on the network to fetch assigned IP address.
Description
Note: User should always copy the IP address from the RAM location returned by this routine into it's own IP address buffer. These locations should not be altered by the user in any case! Ethernet module has to be initialized. See Ethernet_Init.
dim ipAddr as byte[4] ' user IP address buffer ... memcpy(ipAddr, Ethernet_getIpAddress(), 4) ' fetch IP address
Requires Example
Ethernet_getGwIpAddress
Prototype Returns
sub function Ethernet_getGwIpAddress() as word
Ponter to the global variable holding gateway IP address. This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address.
Description
Note: User should always copy the IP address from the RAM location returned by this routine into it's own gateway IP address buffer. These locations should not be altered by the user in any case! Ethernet module has to be initialized. See Ethernet_Init.
dim gwIpAddr as byte[4] ' user gateway IP address buffer ... memcpy(gwIpAddr, Ethernet_getGwIpAddress(), 4) ' fetch gateway IP address
Requires
Example
274
Libraries
Ethernet_getDnsIpAddress
Prototype Returns
sub function Ethernet_getDnsIpAddress() as word
Ponter to the global variable holding DNS IP address. This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address.
Description
Note: User should always copy the IP address from the RAM location returned by this routine into it's own DNS IP address buffer. These locations should not be altered by the user in any case! Ethernet module has to be initialized. See Ethernet_Init.
dim dnsIpAddr as byte[4] ' user DNS IP address buffer ... memcpy(dnsIpAddr, Ethernet_getDnsIpAddress(), 4) ' fetch DNS server address
Requires
Example
Ethernet_getIpMask
Prototype Returns
sub function Ethernet_getIpMask() as word
Ponter to the global variable holding IP subnet mask. This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask.
Description
Note: User should always copy the IP address from the RAM location returned by this routine into it's own IP subnet mask buffer. These locations should not be altered by the user in any case! Ethernet module has to be initialized. See Ethernet_Init.
dim IpMask as byte[4] ' user IP subnet mask buffer ... memcpy(IpMask, Ethernet_getIpMask(), 4) ' fetch IP subnet mask
Requires
Example
275
CHAPTER 7
Libraries
Ethernet_confNetwork
Prototype Returns
Nothing. Configures network parameters (IP subnet mask, gateway IP address, DNS IP address) when DHCP is not used. Parameters:
Description
Note: The above mentioned network parameters should be set by this routine only if DHCP module is not used. Otherwise DHCP will override these settings. Requires Ethernet module has to be initialized. See Ethernet_Init.
dim ipMask as 255.255.255.0) gwIpAddr as dnsIpAddr as ... gwIpAddr[0] gwIpAddr[1] gwIpAddr[2] gwIpAddr[3] byte[4] byte[4] byte[4] = = = = = = = = 192 168 20 6 192 168 20 100 ' network mask (for example : ' gateway (router) IP address ' DNS server IP address
Example
ipMask[0] = 255 ipMask[1] = 255 ipMask[2] = 255 ipMask[3] = 0 ... Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr) ' set network configuration parameters
276
Libraries
Ethernet_arpResolve
Prototype Returns
sub function Ethernet_arpResolve(dim byref ip as byte[4], dim tmax as byte) as word
MAC address behind the IP address - the requested IP address was resolved. 0 - otherwise. This is ARP module routine. It sends an ARP request for given IP address and waits for ARP reply. If the requested IP address was resolved, an ARP cash entry is used for storing the configuration. ARP cash can store up to 3 entries. For ARP cash structure refer to "eth_j60LibDef.h" header file in the compiler's Uses/P18 folder. Parameters:
ip: IP address to be resolved. tmax: time in seconds to wait for an reply.
Description
Note: The Ethernet services are not stopped while this routine waits for ARP reply. The incoming packets will be processed normaly during this time. Requires Ethernet module has to be initialized. See Ethernet_Init.
dim IpAddr as byte[4] ' IP address ... IpAddr[0] = 192 IpAddr[0] = 168 IpAddr[0] = 1 IpAddr[0] = 1 ... Ethernet_arpResolve(IpAddr, 5) ' get MAC address behind the above IP address, wait 5 secs for the response
Example
277
CHAPTER 7
Libraries
Ethernet_sendUDP
Prototype Returns
sub function Ethernet_sendUDP(dim byref destIP as byte[4], dim sourcePort, destPort as word, dim pkt as ^byte, dim pktLen as word) as byte
1 - UDP packet was sent successfully. 0 - otherwise. This is UDP module routine. It sends an UDP packet on the network. Parameters:
Description
destIP: remote host IP address. sourcePort: local UDP source port number. destPort: destination UDP port number. pkt: packet to transmit. pktLen: length in bytes of packet to transmit.
Requires
Example
278
Libraries
Ethernet_dnsResolve
Prototype Returns
sub function Ethernet_dnsResolve(dim byref host as byte[4], dim tmax as byte) as word
pointer to the location holding the IP address - the requested host name was resolved. 0 - otherwise. This is DNS module routine. It sends an DNS request for given host name and waits for DNS reply. If the requested host name was resolved, it's IP address is stored in library global variable and a pointer containing this address is returned by the routine. UDP port 53 is used as DNS port. Parameters:
Description
host: host name to be resolved. tmax: time in seconds to wait for an reply.
Note: The Ethernet services are not stopped while this routine waits for DNS reply. The incoming packets will be processed normaly during this time. Note: User should always copy the IP address from the RAM location returned by this routine into it's own resolved host IP address buffer. These locations should not be altered by the user in any case! Requires Ethernet module has to be initialized. See Ethernet_Init.
dim remoteHostIpAddr as byte[4] ' user host IP address buffer ... ' SNTP server: ' Zurich, Switzerland: Integrated Systems Lab, Swiss Fed. Inst. of Technology ' 129.132.2.21: swisstime.ethz.ch ' Service Area: Switzerland and Europe memcpy(remoteHostIpAddr, Ethernet_dnsResolve("swisstime.ethz.ch", 5), 4)
Example
279
CHAPTER 7
Libraries
Ethernet_initDHCP
Prototype Returns
1 - network parameters were obtained successfully. 0 - otherwise. This is DHCP module routine. It sends an DHCP request for network parameters (IP, gateway, DNS addresses and IP subnet mask) and waits for DHCP reply. If the requested parameters were obtained successfully, their values are stored into the library global variables. These parameters can be fetched by using appropriate library IP get routines: Ethernet_getIpAddress - fetch IP address. Ethernet_getGwIpAddress - fetch gateway IP address. Ethernet_getDnsIpAddress - fetch DNS IP address. Ethernet_getIpMask - fetch IP subnet mask.
Description
UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port. Parameters:
tmax: time in seconds to wait for an reply. Note: The Ethernet services are not stopped while this routine waits for DNS reply. The incoming packets will be processed normaly during this time.
to increment this variable each second in it's code. Requires Example Ethernet module has to be initialized. See Ethernet_Init.
... Ethernet_initDHCP(5) ' get network configuration from DHCP server, wait 5 sec for the response ...
280
Libraries
Ethernet_doDHCPLeaseTime
Prototype Returns
sub function Ethernet_doDHCPLeaseTime() as byte
0 - lease time has not expired yet. 1 - lease time has expired, it's time to renew it.
This is DHCP module routine. It takes care of IP address lease time by decreDescription menting the global lease time library counter. When this time expires, it's time to contact DHCP server and renew the lease. Requires Ethernet module has to be initialized. See Ethernet_Init.
while true ... if(Ethernet_doDHCPLeaseTime() <> 0) then ... ' it's time to renew the IP address lease end if wend
Example
Ethernet_renewDHCP
Prototype Returns
sub function Ethernet_renewDHCP(dim tmax as byte) as byte
1 - upon success (lease time was renewed). 0 - otherwise (renewal request timed out).
This is DHCP module routine. It sends IP address lease time renewal request to DHCP server. Description Parameters:
tmax: time in seconds to wait for an reply.
Requires
Example
281
CHAPTER 7
Libraries
Library Example
This code shows how to use the PIC18FxxJ60 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 path
names :
/ will return the HTML main page /s will return board status as text string /t0 ... /t7 will toggle RD0 to RD7 bit and return HTML main page all other requests return also HTML main page.
program enc_ethernet ' *********************************** ' * RAM variables ' * dim myMacAddr myIpAddr gwIpAddr ipMask 255.255.255.0) dnsIpAddr as as as as byte[6] byte[4] byte[4] byte[4] ' ' ' ' my MAC address my IP address gateway (router) IP address network mask (for example:
as byte[4]
const httpHeader as string[31] = "HTTP/1.1 200 OK"+chr(10)+"Contenttype: " ' HTTP header const httpMimeTypeHTML as string[13] = "text/html"+chr(10)+chr(10) ' HTML MIME type const httpMimeTypeScript as string[14] = "text/plain"+chr(10)+chr(10) ' TEXT MIME type const httpMethod as string[5] = "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 indexPage as string[763] =
282
Libraries
"<meta http-equiv=" + Chr(34) + "refresh" + Chr(34) + " con tent=" + Chr(34) + "3;url=http://192.168.20.60" + Chr(34) + ">" + "<HTML><HEAD></HEAD><BODY>"+ "<h1>PIC18FxxJ60 Mini Web Server</h1>"+ "<a href=/>Reload</a>"+ "<script src=/https/www.scribd.com/s></script>"+ "<table><tr><td valign=top><table border=1 style="+chr(34)+"font-size:20px ;font-family: terminal
;"+chr(34)+"> "+
"<tr><th colspan=2>ADC</th></tr>"+ "<tr><td>AN2</td><td><script>document.write(AN2)</script> </td></tr>"+ "<tr><td>AN3</td><td><script>document.write(AN3) </script></td></tr>"+ "</table></td><td><table border=1 style="+chr(34)+"fontsize:20px ;font-family: terminal ;"+chr(34)+"> "+ "<tr><th colspan=2>PORTB</th></tr>"+ "<script>"+ "var str,i;"+ "str="+chr(34)+chr(34)+"; "+ "for(i=0;i<8;i++)"+ "{str+="+chr(34)+"<tr><tb gcolor=pink>BUTTON #"+chr(34)+"+i+" +chr(34)+"</td>"+chr(34)+"; "+ "if(PORTB&(1<<i)){str+="+chr(34)+"<td bgcolor=red>ON" +chr(34)+";}"+ "else {str+="+chr(34)+"<td bgcolor=#cccccc>OFF"+chr(34)+";}"+ "str+="+chr(34)+"</td></tr>"+chr(34)+";}"+ "document.write(str) ;"+ "</script>" const indexPage2 as string[470] = "</table></td><td>"+ "<table border=1 style="+chr(34)+"font-size:20px ;font-fami ly: terminal ;"+chr(34)+"> "+ "<tr><th colspan=3>PORTD</th></tr>"+ "<script>"+ "var str,i;"+ "str="+chr(34)+chr(34)+"; "+ "for(i=0;i<3;i++)"+ "{str+="+chr(34)+"<tr><td bgcolor=yellow>LED #"+chr(34)+"+i+"+chr(34)+"</td>"+chr(34)+"; "+ "if(PORTD&(1<<i)){str+="+chr(34)+"<td bgcolor=red>ON"+chr (34)+";}"+ "else {str+="+chr(34)+"<td bgcolor=#cccccc>OFF"+chr(34)+";}"+ "str+="+chr(34)+"</td><td><a href=/https/www.scribd.com/t"+chr(34)+"+i+"+chr(34)+ ">Toggle</a></td></tr>"+chr(34)+";}"+ "document.write(str) ;"+ "</script>"
283
CHAPTER 7
Libraries
' ******************************************* ' * user defined functions ' * ' * * this function is called by the library ' * the user accesses to the HTTP request by successive calls to Ethernet_getByte() ' * the user puts data in the transmit buffer by successive calls to 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 ' * ' * sub function Ethernet_UserTCP(dim byref remoteHost as byte[4], dim remotePort, localPort, reqLength as word) as word dim i as word ' my reply length bitMask as byte ' for bit mask txt as string[11] result = 0 if(localPort <> 80) then ' I listen only to web request on port 80 result = 0 exit end if 'get 10 first bytes only of the request, the rest does not mat ter here for i = 0 to 10 getRequest[i] = Ethernet_getByte() next i getRequest[i] = 0 ' copy httpMethod to ram for use in memcmp routine for i = 0 to 4 txt[i] = httpMethod[i] next i
284
Libraries
' only GET method
if(getRequest[5] = "s") then ' 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 result = Ethernet_putConstString(@httpHeader) ' HTTP header result = result + Ethernet_putConstString(@httpMimeTypeScript) ' with text MIME type ' add AN2 value to reply WordToStr(ADC_Read(2), dyna) txt = "var AN2=" result = result + Ethernet_putString(@txt) result = result + Ethernet_putString(@dyna) txt = ";" result = result + Ethernet_putString(@txt) ' add AN3 value to reply WordToStr(ADC_Read(3), dyna) txt = "var AN3=" result = result + Ethernet_putString(@txt) result = result + Ethernet_putString(@dyna) txt = ";" result = result + Ethernet_putString(@txt) ' add PORTB value (buttons) to reply txt = "var PORTB=" result = result + Ethernet_putString(@txt) WordToStr(PORTB, dyna) result = result + Ethernet_putString(@dyna) txt = ";" result = result + Ethernet_putString(@txt) ' add PORTD value (LEDs) to reply txt = "var PORTD=" result = result + Ethernet_putString(@txt) WordToStr(PORTD, dyna) result = result + Ethernet_putString(@dyna) txt = ";" result = result + Ethernet_putString(@txt)
285
CHAPTER 7
Libraries
286
Libraries
dim txt as string[5] result = 0 ' 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], txt) ' second dyna[4] = txt[0] dyna[5] = txt[1] dyna[6] = txt[2] dyna[7] = "." byteToStr(remoteHost[2], txt) ' second dyna[8] = txt[0] dyna[9] = txt[1] dyna[10] = txt[2] dyna[11] = "." byteToStr(remoteHost[3], txt) dyna[12] = txt[0] dyna[13] = txt[1] dyna[14] = txt[2] dyna[15] = ":" ' then remote host port number WordToStr(remotePort, txt) dyna[16] = txt[0] dyna[17] = txt[1] dyna[18] = txt[2] dyna[19] = txt[3] dyna[20] = txt[4] dyna[21] = "[" WordToStr(destPort, txt) dyna[22] = txt[0] dyna[23] = txt[1] dyna[24] = txt[2] dyna[25] = txt[3] dyna[26] = txt[4] dyna[27] = "]" dyna[28] = 0 ' the total length of the request is the length of the dynam ic string plus the text of the request result = 28 + reqLength ' puts the dynamic string into the transmit buffer Ethernet_putBytes(@dyna, 28) 'then puts the request string converted into upper char into the transmit buffer
' second
287
CHAPTER 7
Libraries
while(reqLength <> 0) Ethernet_putByte(Ethernet_getByte()) reqLength = reqLength - 1 wend
' back to the library with the length of the UDP reply end sub main: ADCON1 = 0x0B CMCON = 0x07 PORTA TRISA = 0 = 0x0C
' ADC convertors will be used with AN2 and AN3 ' turn off comparators
= 0 = 0xFF = 0 = 0
httpCounter = 0 ' set mac address myMacAddr[0] = 0x00 myMacAddr[1] = 0x14 myMacAddr[2] = 0xA5 myMacAddr[3] = 0x76 myMacAddr[4] = 0x19 myMacAddr[5] = 0x3F ' set IP address myIpAddr[0] = 192 myIpAddr[1] = 168 myIpAddr[2] = 20 myIpAddr[3] = 60 ' set gateway address gwIpAddr[0] = 192 gwIpAddr[1] = 168 gwIpAddr[2] = 20 gwIpAddr[3] = 6 ' set dns address dnsIpAddr[0] = 192 dnsIpAddr[1] = 168 dnsIpAddr[2] = 20 dnsIpAddr[3] = 1
288
Libraries
* * starts ENC28J60 with : * reset bit on PORTC.B0 * CS bit on PORTC.B1 * my MAC & IP address * full duplex * Ethernet_Init(myMacAddr, myIpAddr, _Ethernet_FULLDUPLEX) ' init ethernet module Ethernet_setUserHandlers(@Ethernet_UserTCP, @Ethernet_UserUDP) ' set user handlers ' dhcp will not be used here, so use preconfigured addresses Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr) while TRUE Ethernet_doPacket() ' do forever ' process incoming Ethernet packets
* * add your stuff here if needed * Ethernet_doPacket() must be called as often as possible * otherwise packets could be lost * wend end.
289
CHAPTER 7
This library provides routines for accessing microcontroller Flash memory. Note that prototypes differ for PIC16 and PIC18 families. Note: Due to the P16/P18 family flash specifics, flash library is MCU dependent. Since the P18 family differ significantlly in number of bytes that can be erased and/or written to specific MCUs, the appropirate suffix is added to the names of functions in order to make it easier to use them. Flash memory operations are MCU dependent : 1. Read operation supported. For this group of MCU's only read function is implemented. 2. Read and Write operations supported (write is executed as erase-and-write). For this group of MCU's read and write functions are implemented. Note that write operation which is executed as erase-and-write, may write less bytes than it erases. 3. Read, Write and Erase operations supported. For this group of MCU's read, write and erase functions are implemented. Further more, flash memory block has to be erased prior to writting (write operation is not executed as erase-and-write). Please refer to MCU datasheet before using flash library. Please refer to MCU datasheet before using flash library.
Library Routines
FLASH_Read FLASH_Read_N_Bytes FLASH_Write FLASH_Write_8 FLASH_Write_16 FLASH_Write_32 FLASH_Write_64 FLASH_Erase FLASH_Erase_64 FLASH_Erase_1024 FLASH_Erase_Write FLASH_Erase_Write_64 FLASH_Erase_Write_1024
290
Libraries
FLASH_Read
' for PIC16 sub function FLASH_Read(dim Address as word) as word
Prototype
' forPIC18 sub function FLASH_Read(dim address as dword)as byte
Returns
Description Reads data from the specified address in Flash memory. Requires Nothing.
' for PIC18 dim tmp as byte ... main: ... tmp = FLASH_Read(0x0D00) ... end.
Example
FLASH_Read_N_Bytes
Prototype Returns Description Requires Example
' for PIC18 sub procedure FLASH_Read_N_Bytes(dim address as longint, dim byref data as byte, dim N as word)
Nothing. Reads N data from the specified address in Flash memory to varibale pointed by data Nothing.
FLASH_Read_N(0x0D00,data_buffer,sizeof(data_buffer))
291
CHAPTER 7
Libraries
FLASH_Write
' for PIC16 sub procedure FLASH_Write(dim Address as word, dim byref Data as word[4]) ' forPIC18 sub procedure FLASH_Write_8(dim address as dword, dim byref data as byte[8])
Prototype
sub procedure FLASH_Write_16(dim address as dword, dim byref data as byte[16]) sub procedure FLASH_Write_32(dim address as dword, dim byref data as byte[32]) sub procedure FLASH_Write_64(dim address as dword, dim byref data as byte[64])
Returns
Nothing.
Writes block of data to Flash memory. Block size is MCU dependent. P16: This function may erase memory segment before writing block of data to it (MCU dependent). Furthermore, memory segment which will be erased may be greater than the size of the data block that will be written (MCU dependent). Description Therefore it is recommended to write as many bytes as you erase. FLASH_Write writes 4 flash memory locations in a row, so it needs to be called as many times as it is necessary to meet the size of the data block that will be written. P18: This function does not perform erase prior to write. Requires Flash memory that will be written may have to be erased before this function is called (MCU dependent). Refer to MCU datasheet for details. Write consecutive values in 64 consecutive locations, starting from 0x0D00:
dim toWrite as byte[64] ... main: ... ' initialize array: for i = 0 to 63 toWrite[i] = i next i ... ' write contents of the array to the address 0x0D00: FLASH_Write_64(0x0D00, toWrite) ... end.
Example
292
Libraries
FLASH_Erase
' for PIC16 sub procedure FLASH_Erase(dim address as word)
Prototype
'forPIC18 sub procedure FLASH_Erase_64(dim address as dword) sub procedure FLASH_Erase_1024(dim address as dword)
Returns
Nothing.
Erases memory block starting from a given address. For P16 familly is impleDescription mented only for those MCU's whose flash memory does not support erase-andwrite operations (refer to datasheet for details). Requires Example
FLASH_Erase_64($0D00)
Nothing. Erase 64 byte memory memory block, starting from address $0D00:
FLASH_Erase_Write
' for PIC18 sub procedure FLASH_Erase_Write_64(dim address as dword, dim byref data as byte[64]) sub procedure FLASH_Erase_Write_1024(dim address as dword, dim byref data as byte[1024])
Prototype
Returns
None.
Description Erase then write memory block starting from a given address. Requires Nothing.
dim toWrite as byte[64] ... main: ... ' initialize array: for i = 0 to 63 toWrite[i] = i next i ... ' erase block of memory at address 0x0D00 then write contents of the array to the address 0x0D00: FLASH_Erase_Write_64(0x0D00, toWrite) ... end.
Example
293
CHAPTER 7
Libraries
Library Example
This is a simple demonstration how to use to PIC16 internal flash memory to store data. The data is being written starting from the given location; then, the same locations are read and the data is displayed on PORTB and PORTC.
program Flash_Write dim counter as byte addr, data_ as word dataAR as word[4][4] ANSEL = 0 ANSELH = 0 C1ON_bit = 0 C2ON_bit = 0 PORTB = 0 TRISB = 0 PORTC = 0 TRISC = 0 Delay_ms(500) ' ' ' ' ' ' Configure AN pins as digital ' Disable comparators ' ' ' ' Initial PORTB value Set PORTB as output Initial PORTC value Set PORTC as output
All block writes to program memory are done as 16-word erase by eight-word write operations. The write operation is edge-aligned and cannot occur across boundaries. Therefore it is recommended to perform flash writes in 16-word chunks. ' That is why lower 4 bits of start address [3:0] must be zero. ' Since FLASH_Write routine performs writes in 4-word chunks, ' we need to call it 4 times in a row. dataAR[0][0]= dataAR[0][1]= dataAR[0][2]= dataAR[0][3]= dataAR[1][0]= dataAR[1][1]= dataAR[1][2]= dataAR[1][3]= dataAR[2][0]= dataAR[2][1]= dataAR[2][2]= dataAR[2][3]= dataAR[3][0]= dataAR[3][1]= dataAR[3][2]= dataAR[3][3]= 0x3FAA+0 0x3FAA+1 0x3FAA+2 0x3FAA+3 0x3FAA+4 0x3FAA+5 0x3FAA+6 0x3FAA+7 0x3FAA+8 0x3FAA+9 0x3FAA+10 0x3FAA+11 0x3FAA+12 0x3FAA+13 0x3FAA+14 0x3FAA+15
294
Libraries
addr = 0x0430 ' starting Flash address, valid for P16F88 for counter = 0 to 3 ' write some data to Flash Delay_ms(100) FLASH_Write(addr+counter*4, dataAR[counter]) next counter Delay_ms(500) addr = 0x0430 for counter = 0 to 15 data_ = FLASH_Read(addr) Inc(addr) Delay_us(10) PORTB = data_ PORTC = word(data_ >> 8) Delay_ms(500) next counter end.
' P16's FLASH is 14-bit wide, so ' two MSB's will always be '00' ' display data on PORTB LS Byte ' and PORTC MS Byte
295
CHAPTER 7
The mikroBasic PRO for PIC 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.
Description:
Example :
Glcd Data Port Chip Select 1 line. Chip Select 2 line. Register select line. Read/Write line. Reset line. Enable line.
dim GLCD_DataPort as byte at PORTD_bit dim GLCD_CS1 as sbit at RB0_bit dim GLCD_CS2 as sbit at RB1_bit dim GLCD_RS as sbit at RB2_bit dim GLCD_RW as sbit at RB3_bit dim GLCD_RST as sbit at RB4_bit dim GLCD_EN as sbit at RB5_bit
296
Libraries
Library Routines
Basic routines: Glcd_Init Glcd_Set_Side Glcd_Set_X Glcd_Set_Page Glcd_Read_Data Glcd_Write_Data Advanced routines: Glcd_Fill Glcd_Dot Glcd_Line Glcd_V_Line Glcd_H_Line Glcd_Rectangle Glcd_Box Glcd_Circle Glcd_Set_Font Glcd_Write_Char Glcd_Write_Text Glcd_Image
297
CHAPTER 7
Libraries
Glcd_Init
Prototype Returns Description
sub procedure Glcd_Init()
Nothing. 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 :
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 GLCD_CS1_Direction : Direction of the Chip select 1 pin GLCD_CS2_Direction : Direction of the Chip select 2 pin GLCD_RS_Direction : Direction of the Register select signal pin GLCD_RW_Direction : Direction of the Read/Write signal pin GLCD_EN_Direction : Direction of the Enable signal pin GLCD_RST_Direction : Direction of the Reset signal pin
Requires
Example
dim GLCD_CS1_Direction as sbit GLCD_CS2_Direction as sbit GLCD_RS_Direction as sbit GLCD_RW_Direction as sbit GLCD_EN_Direction as sbit GLCD_RST_Direction as sbit ' End Glcd module connections ... Glcd_Init()
298
Libraries
Glcd_Set_Side
Prototype Returns
sub procedure Glcd_Set_Side(dim x_pos as byte)
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 Returns
sub procedure Glcd_Set_X(dim x_pos as byte)
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 Example Glcd needs to be initialized, see Glcd_Init routine.
Glcd_Set_X(25)
299
CHAPTER 7
Libraries
Glcd_Set_Page
Prototype Returns
sub procedure Glcd_Set_Page(dim page as byte)
Description
Note: For side, x axis and page layout explanation see schematic at the bottom of this page. Requires Example Glcd needs to be initialized, see Glcd_Init routine.
Glcd_Set_Page(5)
Glcd_Read_Data
Prototype Returns Description
sub function Glcd_Read_Data() as byte
One byte from Glcd memory. 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
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()
Example
300
Libraries
Glcd_Write_Data
Prototype Returns
sub procedure Glcd_Write_Data(dim ddata as byte)
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 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)
Example
Glcd_Fill
Prototype Returns
sub procedure Glcd_Fill(dim pattern as byte)
Description
To clear the Glcd screen, use Glcd_Fill(0). To fill the screen completely, use Glcd_Fill(0xFF). Requires Example Glcd needs to be initialized, see Glcd_Init routine.
' Clear screen Glcd_Fill(0)
301
CHAPTER 7
Libraries
Glcd_Dot
Prototype Returns
sub procedure Glcd_Dot(dim x_pos as byte, dim y_pos as byte, dim color as byte)
Description
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 Example Glcd needs to be initialized, see Glcd_Init routine.
' Invert the dot in the upper left corner Glcd_Dot(0, 0, 2)
Glcd_Line
Prototype Returns
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)
Description
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires Example Glcd needs to be initialized, see Glcd_Init routine.
' Draw a line between dots (0,0) and (20,30) Glcd_Line(0, 0, 20, 30, 1)
302
Libraries
Glcd_V_Line
Prototype Returns
sub procedure Glcd_V_Line(dim y_start as byte, dim y_end as byte, dim x_pos as byte, dim color as byte)
Description
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires Example Glcd needs to be initialized, see Glcd_Init routine.
' Draw a vertical line between dots (10,5) and (10,25) Glcd_V_Line(5, 25, 10, 1)
Glcd_H_Line
Prototype Returns
sub procedure Glcd_V_Line(dim x_start as byte, dim x_end as byte, dim y_pos as byte, dim color as byte)
Description
The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires Example Glcd needs to be initialized, see Glcd_Init routine.
' Draw a horizontal line between dots (10,20) and (50,20) Glcd_H_Line(10, 50, 20, 1)
303
CHAPTER 7
Libraries
Glcd_Rectangl
Prototype Returns
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)
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 Example Glcd needs to be initialized, see Glcd_Init routine.
' Draw a rectangle between dots (5,5) and (40,40) Glcd_Rectangle(5, 5, 40, 40, 1)
Glcd_Box
Prototype Returns
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)
0..127
y_upper_left: y coordinate of the upper left box corner. Valid values:
Description
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 Example Glcd needs to be initialized, see Glcd_Init routine.
' Draw a box between dots (5,15) and (20,40) Glcd_Box(5, 15, 20, 40, 1)
304
Libraries
Glcd_Circle
Prototype Returns
sub procedure Glcd_Circle(dim x_center as integer, dim y_center as integer, dim radius as integer, dim color as byte)
Description
The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot. Requires Example Glcd needs to be initialized, see Glcd_Init routine.
' Draw a circle with center in (50,50) and radius=10 Glcd_Circle(50, 50, 10, 1)
Glcd_Set_Font
Prototype Returns
sub procedure Glcd_Set_Font(dim byref const ActiveFont as ^byte, dim FontWidth as byte, dim FontHeight as byte, dim FontOffs as word)
Nothing. Sets font that will be used with Glcd_Write_Char and Glcd_Write_Text routines. Parameters :
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
Description
PRO for PIC character set and regular ASCII set (eg. if 'A' is 65 in ASCII character, and 'A' is 45 in the mikroBasic PRO for PIC 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 Example Glcd needs to be initialized, see Glcd_Init routine.
' Use the custom 5x7 font "myfont" which starts with space (32): Glcd_Set_Font(myfont, 5, 7, 32)
305
CHAPTER 7
Libraries
Glcd_Write_Char
Prototype Returns
sub procedure Glcd_Write_Char(dim chr as byte, dim x_pos as byte, dim page_num as byte, dim color as byte)
Width) Description
page_num: the number of the page on which character will be written. Valid 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. Requires Example 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.
' Write character 'C' on the position 10 inside the page 2: Glcd_Write_Char('C', 10, 2, 1)
306
Libraries
Glcd_Write_Text
Prototype Returns
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)
Description
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 Example 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.
' Write text "Hello world!" on the position 10 inside the page 2: Glcd_Write_Text("Hello world!", 10, 2, 1);
Glcd_Image
Prototype Returns
sub procedure Glcd_Image(dim byref const image as ^byte)
Description
image: image to be displayed. Bitmap array must be located in code memory. Use the mikroBasic PRO for PIC integrated Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd.
Requires Example
307
CHAPTER 7
Libraries
Library Example
The following example demonstrates routines of the Glcd library: initialization, clear(pattern fill), image displaying, drawing lines, circles, boxes and rectangles, text displaying and handling.
program Glcd_Test; include bitmap ' Glcd module connections dim GLCD_DataPort as byte at PORTD dim GLCD_CS1 GLCD_CS2 GLCD_RS GLCD_RW GLCD_EN GLCD_RST as as as as as as sbit sbit sbit sbit sbit sbit at at at at at at RB0_bit RB1_bit RB2_bit RB3_bit RB4_bit RB5_bit at at at at at at TRISB0_bit TRISB1_bit TRISB2_bit TRISB3_bit TRISB4_bit TRISB5_bit
dim GLCD_CS1_Direction as sbit GLCD_CS2_Direction as sbit GLCD_RS_Direction as sbit GLCD_RW_Direction as sbit GLCD_EN_Direction as sbit GLCD_RST_Direction as sbit ' End Glcd module connections dim counter as byte someText as char[18] sub procedure Delay2S() Delay_ms(2000) end sub main: ANSEL = 0 ANSELH = 0 Glcd_Init() Glcd_Fill(0x00) while TRUE Glcd_Image(@truck_bmp) Delay2S() delay2S() Glcd_Fill(0x00) Glcd_Box(62,40,124,63,1)
308
Libraries
while (counter <= 59) ' Draw horizontal and vertical lines Delay_ms(250) Glcd_V_Line(2, 54, counter, 1) Glcd_H_Line(2, 120, counter, 1) Counter = counter + 5 wend Delay2S() Glcd_Fill(0x00) Glcd_Set_Font(@Character8x7, 8, 7, 32) "Character8x7" Glcd_Write_Text("mikroE", 1, 7, 2) for counter = 1 to 10 Glcd_Circle(63,32, 3*counter, 1) next counter Delay2S() Glcd_Box(10,20, 70,63, 2) Delay2S() Glcd_Fill(0xFF) Glcd_Set_Font(@Character8x7, 8, 7, 32) someText = "8x7 Font" Glcd_Write_Text(someText, 5, 0, 2) delay2S() Glcd_Set_Font(@System3x6, 3, 5, 32) someText = "3X5 CAPITALS ONLY" Glcd_Write_Text(someText, 60, 2, 2) delay2S() Glcd_Set_Font(@font5x7, 5, 7, 32) someText = "5x7 Font" Glcd_Write_Text(someText, 5, 4, 2) delay2S() ' Clear Glcd ' Choose font ' Write string ' Draw circles
Glcd_Set_Font(@FontSystem5x7_v2, 5, 7, 32) ' Change font someText = "5x7 Font (v2)" Glcd_Write_Text(someText, 5, 6, 2) ' Write string delay2S()
309
CHAPTER 7
Libraries
HW Connection
Glcd HW connection
310
Libraries
IC LIBRARY
I2C full master MSSP module is available with a number of PIC MCU models. mikroBasic PRO for PIC provides library which supports the master I2C mode. Note: Some MCUs have multiple I2C modules. In order to use the desired I2C library routine, simply change the number 1 in the prototype with the appropriate module number, i.e.
I2C1_Init(100000)
Library Routines
I2C1_Init I2C1_Start I2C1_Repeated_Start I2C1_Is_Idle I2C1_Rd I2C1_Wr I2C1_Stop
Nothing. Initializes I2C with desired clock (refer to device data sheet for correct values in respect with Fosc). Needs to be called before using other functions of I2C Library. You dont need to configure ports manually for using the module; library will take care of the initialization. Library requires MSSP module on PORTB or PORTC.
Description
Requires
Note: Calculation of the I2C clock value is carried out by the compiler, as it would produce a relatively large code if performed on the libary level. Therefore, compiler needs to know the value of the parameter in the compile time. That is why this parameter needs to be a constant, and not a variable.
I2C1_Init(100000)
Example
311
CHAPTER 7
Libraries
I2C1_Start
Prototype Returns
sub function I2C1_Start as byte
Description Determines if I2C bus is free and issues START signal. Requires Example I2C must be configured before using this function. See I2C1_Init.
if I2C1_Start = 0 then ...
I2C1_Repeated_Start
Prototype Returns
sub procedure I2C1_Repeated_Start
Nothing.
Description Issues repeated START signal. Requires Example I2C must be configured before using this function. See I2C1_Init.
I2C1_Repeated_Start
I2C1_Is_Idle
Prototype Returns
sub function I2C1_Is_Idle as byte
Description Tests if I2C bus is free. Requires Example I2C must be configured before using this function. See I2C1_Init.
if I2C1_Is_Idle then ...
312
Libraries
I2C1_Rd
Prototype Returns Description
sub function I2C1_Rd(dim ack as byte) as byte
Returns one byte from the slave. Reads one byte from the slave, and sends not acknowledge signal if parameter ack is 0, otherwise it sends acknowledge. I2C must be configured before using this function. See I2C1_Init.
Requires
Also, START signal needs to be issued in order to use this function. See I2C1_Start. Read data and send not acknowledge signal:
tmp = I2C1_Rd(0)
Example
I2C1_Wr
Prototype Returns
sub function I2C1_Wr(dim data as byte) as byte
Description Sends data byte (parameter data) via I2C bus. Requires Example I2C must be configured before using this function. See I2C1_Init. Also, START signal needs to be issued in order to use this function. See I2C1_Start.
I2C1_Write($A3)
I2C1_Stop
Prototype Returns
sub procedure I2C1_Stop
Nothing.
Description Issues STOP signal. Requires Example I2C must be configured before using this function. See I2C1_Init.
I2C1_Stop
313
CHAPTER 7
Libraries
Library Example
This code demonstrates use of I2C Library procedures and functions. PIC MCU is connected (pins SCL and SDA) to 24c02 EEPROM. Program sends data to EEPROM (data is written at address 2). Then, we read data via I2C from EEPROM and send its value to PORTD, to check if the cycle was successful. The figure below shows how to interface 24c02 to PIC.
program I2C_Simple main: ANSEL = 0 ANSELH = 0 PORTB = 0 TRISB = 0 I2C1_Init(100000) I2C1_Start() I2C1_Wr(0xA2) I2C1_Wr(2) I2C1_Wr(0xAA) I2C1_Stop() Delay_100ms() I2C1_Start() I2C1_Wr(0xA2) I2C1_Wr(2) I2C1_Repeated_Start() I2C1_Wr(0xA3) PORTB = I2C1_Rd(0) I2C1_Stop() end. ' issue I2C start signal ' send byte via I2C (device address + W) ' send byte (data address) ' issue I2C signal repeated start ' send byte (device address + R) ' Read the data (NO acknowledge) ' issue I2C stop signal
' Configure PORTB as output ' initialize I2C communication ' issue I2C start signal ' send byte via I2C (device address + W) ' send byte (address of EEPROM location) ' send data (data to be written) ' issue I2C stop signal
314
Libraries
HW Connection
315
CHAPTER 7
The mikroBasic PRO for PIC 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.
Description:
Example :
dim keypadPort as byte at PORTD
Keypad Port
Library Routines
Keypad_Init Keypad_Key_Press Keypad_Key_Click
Keypad_Init
Prototype Returns
sub procedure Keypad_Init()
Nothing.
Description Initializes port for working with keypad. Global variables : Requires
keypadPort - Keypad port must be defined before using this function. ' Keypad module connections dim keypadPort as byte at PORTD ' End of keypad module connections ... Keypad_Init()
Example
316
Libraries
Keypad_Key_Press
Prototype Returns If no key is pressed, returns 0. Description Reads the key from keypad when key gets pressed. Requires Example Port needs to be initialized for working with the Keypad library, see Keypad_Init.
dim kp as byte ... kp = Keypad_Key_Press() sub function Keypad_Key_Press() as byte
Keypad_Key_Click
Prototype 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, dependDescription ing 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 Example Port needs to be initialized for working with the Keypad library, see Keypad_Init.
dim kp as byte ... kp = Keypad_Key_Click() sub function Keypad_Key_Click() as byte
317
CHAPTER 7
Libraries
Library Example
This is a simple example of using the Keypad Library. It supports keypads with 1..4 rows and 1..4 columns. The code being returned by Keypad_Key_Click() function is in range from 1..16. In this example, the code returned is transformed into ASCII codes [0..9,A..F] and displayed on Lcd. In addition, a small single-byte counter displays in the second Lcd row number of key presses.
program Keypad_Test dim kp, cnt, oldstate as byte txt as byte[7] ' Keypad module connections dim keypadPort as byte at PORTC ' End Keypad module connections ' Lcd module connections dim LCD_RS as sbit at RB4_bit LCD_EN as sbit at RB5_bit LCD_D4 as sbit at RB0_bit LCD_D5 as sbit at RB1_bit LCD_D6 as sbit at RB2_bit LCD_D7 as sbit at RB3_bit LCD_RS_Direction as sbit LCD_EN_Direction as sbit LCD_D4_Direction as sbit LCD_D5_Direction as sbit LCD_D6_Direction as sbit LCD_D7_Direction as sbit ' End Lcd module connections main: oldstate = 0 cnt = 0 Keypad_Init() ANSEL = 0 ANSELH = Lcd_Init() Lcd_Cmd(_LCD_CLEAR) Lcd_Cmd(_LCD_CURSOR_OFF) Lcd_Out(1, 1, "Key :") Lcd_Out(2, 1, "Times:") while TRUE kp = 0 ' Reset key code variable at at at at at at TRISB4_bit TRISB5_bit TRISB0_bit TRISB1_bit TRISB2_bit TRISB3_bit
' Reset counter ' Initialize Keypad ' Configure AN pins as digital I/O ' ' ' ' Initialize Lcd Clear display Cursor off Write message text on Lcd
318
Libraries
' Store key code in kp vari-
' 1
' 2 ' 3 ' A ' 4 ' 5 ' 6 ' B ' 7 ' 8 ' 9 ' C ' * ' 0 ' # ' D
319
CHAPTER 7
Libraries
oldstate = kp else Inc(cnt) end if Lcd_Chr(1, 10, kp) if (cnt = 255) then cnt = 0 Lcd_Out(2, 10, " end if WordToStr(cnt, txt) Lcd_Out(2, 10, txt) wend end.
' Print key ASCII value on Lcd ' If counter varialble overflow ")
' Transform counter value to string ' Display counter value on Lcd
HW Connection
320
Libraries
LCD LIBRARY
The mikroBasic PRO for PIC 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.
Description:
Example :
Register Select line. Enable line. Data 7 line. Data 6 line. Data 5 line. Data 4 line. Register Select direction pin. Enable direction pin. Data 7 direction pin. Data 6 direction pin.
dim LCD_RS as sbit at RB4_bit dim LCD_EN as sbit at RB5_bit dim LCD_D7 as sbit at RB3_bit dim LCD_D6 as sbit at RB2_bit dim LCD_D5 as sbit at RB1_bit dim LCD_D4 as sbit at RB0_bit dim LCD_RS_Direction as sbit at TRISB4_bit dim LCD_EN_Direction as sbit at TRISB5_bit dim LCD_D7_Direction as sbit at TRISB3_bit dim LCD_D6_Direction as sbit at TRISB2_bit dim LCD_D5_Direction as sbit at TRISB1_bit dim LCD_D4_Direction as sbit at TRISB0_bit
dim LCD_D5_Direction Data 5 direction pin. as sbit sfr externald dim LCD_D4_Direction as sbit sfr external
321
CHAPTER 7
Libraries
Library Routines
Lcd_Init Lcd_Out Lcd_Out_Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd
Lcd_Init
Prototype Returns
sub procedure Lcd_Init()
Nothing.
LCD_D7: Data bit 7 LCD_D6: Data bit 6 LCD_D5: Data bit 5 LCD_D4: Data bit 4 LCD_RS: Register Select (data/instruction) signal pin LCD_EN: Enable signal pin LCD_D7_Direction: Direction of the Data 7 pin LCD_D6_Direction: Direction of the Data 6 pin LCD_D5_Direction: Direction of the Data 5 pin LCD_D4_Direction: Direction of the Data 4 pin LCD_RS_Direction: Direction of the Register Select pin LCD_EN_Direction: Direction of the Enable signal pin
Requires
Example
dim LCD_RS as sbit LCD_EN as sbit LCD_D7 as sbit LCD_D6 as sbit LCD_D5 as sbit LCD_D4 as sbit ' End Lcd module ... Lcd_Init()
322
Libraries
Lcd_Out
Prototype Returns
sub procedure Lcd_Out(dim row as byte, dim column as byte, dim byref text as string[20])
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 Example
Lcd_Out_Cp
Prototype Returns
sub procedure Lcd_Out_Cp(dim byref text as string[19])
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 Example The LCD module needs to be initialized. See Lcd_Init routine.
' Write text "Here!" at current cursor position: Lcd_Out_Cp("Here!")
323
CHAPTER 7
Libraries
Lcd_Chr
Prototype Returns
sub procedure Lcd_Chr(dim row as byte, dim column as byte, dim out_char as byte)
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 Example
Lcd_Chr_Cp
Prototype Returns
sub procedure Lcd_Chr_Cp(dim out_char as byte)
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 Example
324
Libraries
Lcd_Cmd
Prototype Returns
sub procedure Lcd_Cmd(dim out_char as byte)
Description
Note: Predefined constants can be passed to the function, see Available LCD Commands. Requires Example The LCD module needs to be initialized. See Lcd_Init table.
' Clear Lcd display: Lcd_Cmd(_LCD_CLEAR)
Purpose Move cursor to the 1st row Move cursor to the 2nd row Move cursor to the 3rd row Move cursor to the 4th row Clear display Return cursor to home position, returns a shifted display to its original position. Display data RAM is unaffected. Turn off cursor Underline cursor on Blink cursor on Move cursor left without changing display data RAM Move cursor right without changing display data RAM Turn LCD display on Turn LCD display off Shift display left without changing display data RAM Shift display right without changing display data RAM
325
CHAPTER 7
Libraries
Library Example
' Loop variable ' Function used for text moving ' You can change the moving speed here
sub procedure Move_Delay() Delay_ms(500) end sub main: TRISB = 0 PORTB = 0xFF TRISB = 0xFF ANSEL = 0 ANSELH = 0 txt1 txt2 txt3 txt4 = = = = "mikroElektronika" "EasyPIC5" "Lcd4bit" "example"
' Initialize Lcd ' Clear display ' Cursor off ' Write text in first row ' Write text in second row
326
Libraries
' Clear display ' Write text in first row ' Write text in second row
327
CHAPTER 7
Libraries
HW Connection
LCD HW connection
328
Libraries
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). Note: Manchester code library implements time-based activities, so interrupts need to be disabled when using it.
Description:
Example :
dim MANRXPIN as sbit at RC0_bit dim MANTXPIN as sbit at RC1_bit dim MANRXPIN_Direction as sbit at TRISC0_bit dim MANTXPIN_Direction as sbit at TRISC1_bit
dim MANRXPIN_Direction Direction of the Receive as sbit sfr external pin. dim MANTXPIN_Direction Direction of the Transmit as sbit sfr external pin.
329
CHAPTER 7
Libraries
Library Routines
Man_Receive_Init Man_Receive Man_Send_Init Man_Send Man_Synchro Man_Out The following routines are for the internal use by compiler only: Manchester_0 Manchester_1 Manchester_Out
Man_Receive_Init
Prototype Returns
sub function Man_Receive_Init()as word 0 - if initialization and synchronization were successful. 1 - upon unsuccessful synchronization. 255 - upon user abort.
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. Global variables : Requires
MANRXPIN : Receive line MANRXPIN_Direction : Direction of the receive pin
Example
330
Libraries
Man_Receive
Prototype Returns
sub function Man_Receive(dim byreferror as byte) as byte
A byte read from the incoming signal. The function extracts one byte from incoming signal.
Description
Parameters :
error: error flag. If signal format does not match the expected, the error flag will be set to non-zero.
Requires
To use this function, the user must prepare the MCU for receiving. See Man_Receive_Init.
dim data, error as byte ... data = 0 error = 0 data = Man_Receive(&error) if (error <> 0) then ' error handling end if
Example
Man_Send_Init
Prototype Returns
sub procedure Man_Send_Init()
Nothing.
Example
331
CHAPTER 7
Libraries
Man_Send
Prototype Returns
sub procedure Man_Send(tr_data as byte)
Description
tr_data: data to be sent
Note: Baud rate used is 500 bps. Requires Example To use this function, the user must prepare the MCU for sending. See Man_Send_Init.
dim msg as byte ... Man_Send(msg)
Man_Synchro
Prototype
sub function Man_Synchro() as word 0 - if synchronization was not successful.
Returns
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.
dim man__half_bit_len as word ... man__half_bit_len = Man_Synchro()
Example
332
Libraries
Man_Break
Prototype Returns
sub procedure Man_Break()
Nothing. Man_Receive is blocking routine and it can block the program flow. Call this routine from interrupt to unblock the program execution. This mechanism is similar to WDT. Note: Interrupts should be disabled before using Manchester routines again (see note at the top of this page).
Description
Requires
Nothing.
dim data1, error_, counter as byte sub procedure interrupt() if (INTCON.T0IF <> 0) then if (counter >= 20) then Man_Break() counter = 0 ' reset counter end if else Inc(counter) ' increment counter INTCON.T0IF = 0 ' Clear Timer0 overflow interrupt flag end if end sub
Example
' try Man_Receive with blocking prevention mechanism INTCON.GIE = 1 ' Global interrupt enable INTCON.T0IE = 1 ' Enable Timer0 overflow interrupt data1 = Man_Receive(error_) INTCON.GIE = 0 ' Global interrupt disable end.
333
CHAPTER 7
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 RB4_bit LCD_EN as sbit at RB5_bit LCD_D4 as sbit at RB0_bit LCD_D5 as sbit at RB1_bit LCD_D6 as sbit at RB2_bit LCD_D7 as sbit at RB3_bit LCD_RS_Direction as sbit LCD_EN_Direction as sbit LCD_D4_Direction as sbit LCD_D5_Direction as sbit LCD_D6_Direction as sbit LCD_D7_Direction as sbit ' End LCD module connections at at at at at at TRISB4_bit TRISB5_bit TRISB0_bit TRISB1_bit TRISB2_bit TRISB3_bit
' Manchester module connections dim MANRXPIN as sbit at RC0_bit MANRXPIN_Direction as sbit at TRISC0_bit MANTXPIN as sbit at RC1_bit MANTXPIN_Direction as sbit at TRISC1_bit ' End Manchester module connections dim error_flag, ErrorCount, temp as byte main: ErrorCount = 0 ANSEL = 0 ANSELH = 0 C1ON_bit = 0 C2ON_bit = 0 TRISC5_bit = 0 Lcd_Init() Lcd_Cmd(_LCD_CLEAR) Man_Receive_Init()
' Initialize LCD ' Clear LCD display ' Initialize Receiver
while TRUE ' Endless loop Lcd_Cmd(_LCD_FIRST_ROW) ' Move cursor to the 1st row while TRUE ' Wait for the "start" byte temp = Man_Receive(error_flag) ' Attempt byte receive
334
Libraries
if (temp = 0x0B) then ' "Start" byte, see Transmitter example break ' We got the starting sequence end if if (error_flag <> 0) then ' Exit so we do not loop forever break end if wend do temp = Man_Receive(error_flag) ' Attempt byte receive if (error_flag <> 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 ' end if else ' if (temp <> 0x0E) then received(see Transmitter example) Lcd_Chr_CP(temp) ' byte on LCD end if Delay_ms(25) end if loop until ( temp = 0x0E ) wend ' If "End" byte was end. Reset error counter No error occured ' If "End" byte was do not write received
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 RC0_bit MANRXPIN_Direction as sbit at TRISC0_bit MANTXPIN as sbit at RC1_bit MANTXPIN_Direction as sbit at TRISC1_bit ' End Manchester module connections dim index, character as byte s1 as char[17] main: s1 = "mikroElektronika"
335
CHAPTER 7
Libraries
ANSEL = ANSELH = C1ON_bit C2ON_bit 0 0 = 0 = 0
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.
' 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
336
Libraries
Connection Example
337
CHAPTER 7
The Multi Media Card (MMC) is a flash memory card standard. MMC cards are currently available in sizes up to and including 1 GB, and are used in cell phones, mp3 players, digital cameras, and PDAs. mikroBasic PRO for PIC provides a library for accessing data on Multi Media Card via SPI communication.This library also supports SD(Secure Digital) memory cards.
must be called before initializing Mmc_Init. Note: Once the MMC/SD card is initialized, the user can reinitialize SPI at higher speed. See the Mmc_Init and Mmc_Fat_Init routines.
338
Libraries
Description:
Example :
Library Routines
Mmc_Init Mmc_Read_Sector Mmc_Write_Sector Mmc_Read_Cid Mmc_Read_Csd Routines for file handling: Mmc_Fat_Init Mmc_Fat_QuickFormat Mmc_Fat_Assign Mmc_Fat_Reset Mmc_Fat_Read Mmc_Fat_Rewrite Mmc_Fat_Append Mmc_Fat_Delete Mmc_Fat_Write Mmc_Fat_Set_File_Date Mmc_Fat_Get_File_Date Mmc_Fat_Get_File_Size Mmc_Fat_Get_Swap_File
339
CHAPTER 7
Libraries
Mmc_Init
Prototype Returns
sub function Mmc_Init() as byte
0 - if MMC/SD card was detected and successfully initialized 1 - otherwise Initializes MMC through hardware SPI interface.
Description Mmc_Init needs to be called before using other functions of this library. Global variables :
Mmc_Chip_Select: Chip Select line Mmc_Chip_Select_Direction: Direction of the Chip Select pin
Requires
must be defined before using this function. The appropriate hardware SPI module must be previously initialized. See the SPI1_Init, SPI1_Init_Advanced routines.
' MMC module connections dim Mmc_Chip_Select as sbit sfr at RC2_bit dim Mmc_Chip_Select_Direction as sbit sfr at TRISC2_bit ' MMC module connections
Example
dim error as byte ... SPI1_Init() error = Mmc_Init() ' Init with CS line at RB2
340
Libraries
Mmc_Read_Sector
Prototype Returns
sub function Mmc_Read_Sector(dim sector as longint, dim byref data as byte[512]) as byte
0 - i if reading was successful 1 - otherwise The function reads one sector (512 bytes) from MMC card.
Description
Parameters:
sector: MMC/SD card sector to be read. dbuff: buffer of minimum 512 bytes in length for data storage.
Requires
Example
341
CHAPTER 7
Libraries
Mmc_Write_Sector
Prototype
sub function Mmc_Write_Sector(dim sector as longint, dim byref data_ as byte[512]) as byte 0 - if writing was successful 1 -if there was an error in sending write command 2 - if there was an error in writing (data rejected)
Returns
The function writes 512 bytes of data to one MMC card sector. Description Parameters:
sector: MMC/SD card sector to be written to. dbuff: data to be written (buffer of minimum 512 bytes in length).
Requires
Example
342
Libraries
Mmc_Read_Cid
Prototype Returns
sub function Mmc_Read_Cid(dim byref data_cid as byte[16]) as byte 0 - if CID register was read successfully 1 -if there was an error while reading
Example
Mmc_Read_Csd
Prototype Returns
sub function Mmc_Read_Csd(dim byref data_for_registers as byte[16]) as byte 0 - if CSD register was read successfully 1- if there was an error while reading
Example
343
CHAPTER 7
Libraries
Mmc_Fat_Init
Prototype Returns
sub function Mmc_Fat_Init() as byte
0 - if MMC/SD card was detected and successfully initialized 1 - if FAT16 boot sector was not found 255 - if MMC/SD card was not detected
Description
Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by the library. Note: MMC/SD card has to be formatted to FAT16 file system. Global variables :
Mmc_Chip_Select: Chip Select line Mmc_Chip_Select_Direction: Direction of the Chip Select pin
Requires must be defined before using this function. The appropriate hardware SPI module must be previously initialized. See the SPI1_Init, SPI1_Init_Advanced routines.
' MMC module connections dim Mmc_Chip_Select as sbit sfr at RC2_bit dim Mmc_Chip_Select_Direction as sbit sfr at TRISC2_bit ' MMC module connections ' Initialize SPI1 module and set pointer(s) to SPI1 functions SPI1_Init_Advanced(MASTER_OSC_DIV64, DATA_SAMPLE_MIDDLE, CLK_IDLE_LOW, LOW_2_HIGH)
Example
'use fat16 quick format instead of init routine if a formatting is needed if (Mmc_Fat_Init() = 0) then ... end if ' reinitialize SPI1 at higher speed SPI1_Init_Advanced(MASTER_OSC_DIV4, DATA_SAMPLE_MIDDLE, CLK_IDLE_LOW, LOW_2_HIGH)
344
Libraries
Mmc_Fat_QuickFormat
Prototype Returns
sub function Mmc_Fat_QuickFormat(dim mmc_fat_label as string[11]) as byte 0 - if MMC/SD card was detected, successfully formated and initialized 1 - if FAT16 format was unseccessful 255 - if MMC/SD card was not detected
Description
Note: This routine can be used instead or in conjunction with Mmc_Fat_Init routine. Note: If MMC/SD card already contains a valid boot sector, it will remain unchanged (except volume label field) and only FAT and ROOT tables will be erased. Also, the new volume label will be set. Requires The appropriate hardware SPI module must be previously initialized.
Initialize SPI1 module and set pointer(s) to SPI1 functions SPI1_Init_Advanced(MASTER_OSC_DIV64, DATA_SAMPLE_MIDDLE, CLK_IDLE_LOW, LOW_2_HIGH) ' Format and initialize MMC/SD card and MMC_FAT16 library globals if (Mmc_Fat_QuickFormat('mikroE') = 0) then ... end if ' Reinitialize the SPI module at higher speed (change primary prescaler). SPI1_Init_Advanced(MASTER_OSC_DIV4, DATA_SAMPLE_MIDDLE, CLK_IDLE_LOW, LOW_2_HIGH)
Example
345
CHAPTER 7
Libraries
Mmc_Fat_Assign
Prototype Returns
sub function Mmc_Fat_Assign(dim byref filename as char[12], dim file_cre_attr as byte) as byt
1 - if file already exists or file does not exist but a new file is created. 0 - if file does not exist and no new file is created. Assigns file for file operations (read, write, delete...). All subsequent file operations will be applied on an assigned file. Parameters:
filename: name of the file that should be assigned for file operations.
Description
Bit 0 1 2 3 4 5 6 7
File name should be in DOS 8.3 (file_name.extension) format. The file name and extension will be automatically padded with spaces by the library if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so the user does no have to take care of that. The file name and extension are case insensitive. The library will convert them to proper case automatically, so the user does not have to take care of that. Also, in order to keep backward compatibility with the first version of this library, file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension (i.e. "MIKROELETXT" -> MIKROELE.TXT). In this case last 3 charac ters of the string are considered to be file extension. file_cre_attr: file creation and attributs flags. Each bit corresponds to the appropriate file attribut:
Mask 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80 Description Read Only Hidden System Volume Label Subdirectory Archive Device (internal use only, never found on disk) File creation flag. If file does not exist and this flag is set, a new file with specified name will be created.
Note: Long File Names (LFN) are not supported. Requires Example MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init
' create file with archive attribut if it does not already exist Mmc_Fat_Assign("MIKRO007.TXT",0xA0)
346
Libraries
Mmc_Fat_Reset
Prototype Returns
sub procedure Mmc_Fat_Reset(dim byref size as longword)
Description
Parameters:
size: buffer to store file size to. After file has been open for reading its size is returned through this parameter.
Requires
MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign.
dim size as longword ... main: ... Mmc_Fat_Reset(size) ... end.
Example
Mmc_Fat_Read
Prototype Returns
sub procedure Mmc_Fat_Read(dim byref bdata as byte)
Nothing. Reads a byte from the currently assigned file opened for reading. Upon function execution file pointers will be set to the next character in the file.
Description
Parameters:
bdata: buffer to store read byte to. Upon this function execution read
byte is returned through this parameter. MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign. The file must be opened for reading. See Mmc_Fat_Reset.
dim character as byte ... main: ... Mmc_Fat_Read(character) ... end.
Requires
Example
347
CHAPTER 7
Libraries
Mmc_Fat_Rewrite
Prototype Returns Description
sub procedure Mmc_Fat_Rewrite()
Nothing. Opens the currently assigned file for writing. If the file is not empty its content will be erased. MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign.
Requires
Example
Mmc_Fat_Append
Prototype Returns Description
sub procedure Mmc_Fat_Append()
Nothing. Opens the currently assigned file for appending. Upon this function execution file pointers will be positioned after the last byte in the file, so any subsequent file write operation will start from there. MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign.
Requires
Example
348
Libraries
Mmc_Fat_Delete
Prototype Returns Description
sub procedure Mmc_Fat_Delete()
Nothing. Deletes currently assigned file from MMC/SD card. MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign
Requires
Example
Mmc_Fat_Write
Prototype Returns
sub procedure Mmc_Fat_Write(dim byref fdata as byte[512], dim data_len as word)
Nothing. Writes requested number of bytes to the currently assigned file opened for writing.
Description
Parameters:
fdata: data to be written. data_len: number of bytes to be written.
MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. Requires The file must be previously assigned. See Mmc_Fat_Assign. The file must be opened for writing. See Mmc_Fat_Rewrite or Mmc_Fat_Append.
'dim file_contents as char[42] ... main: ... Mmc_Fat_Write(file_contents, 42) 'write data to the assigned file ... end.
Example
349
CHAPTER 7
Libraries
Mmc_Fat_Set_File_Date
Prototype Returns
sub procedure Mmc_Fat_Set_File_Date(dim year as word, dim month, day, hours, mins, seconds as byte)
Nothing. Sets the date/time stamp. Any subsequent file write operation will write this stamp to the currently assigned file's time/date attributs. Parameters:
Description
year: year attribute. Valid values: 1980-2107 month: month attribute. Valid values: 1-12 day: day attribute. Valid values: 1-31 hours: hours attribute. Valid values: 0-23 mins: minutes attribute. Valid values: 0-59 seconds: seconds attribute. Valid values: 0-59
MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. Requires The file must be previously assigned. See Mmc_Fat_Assign. The file must be opened for writing. See Mmc_Fat_Rewrite or Mmc_Fat_Append. Example
Mmc_Fat_Set_File_Date(2005,9,30,17,41,0)
350
Libraries
Mmc_Fat_Get_File_Date
Prototype Returns
sub procedure Mmc_Fat_Get_File_Date(dim byref year as word, dim byref month, day, hours, mins as byte)
Description
Requires
MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign.
dim year as word month, day, hours, mins as byte ... main: ... Mmc_Fat_Get_File_Date(year, month, day, hours, mins) ... end.
Example
351
CHAPTER 7
Libraries
Mmc_Fat_Get_File_Size
Prototype Returns Description
sub function Mmc_Fat_Get_File_Size() as longword
Size of the currently assigned file in bytes. This function reads size of the currently assigned file in bytes. MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign.
dim my_file_size as longword ... main: ... my_file_size = Mmc_Fat_Get_File_Size ... end.
Requires
Example
Mmc_Fat_Get_Swap_File
Prototype
sub function Mmc_Fat_Get_Swap_File(dim sectors_cnt as longint, dim byref filename as string[11], dim file_attr as byte) as dword
Returns
Number of the start sector for the newly created swap file, if there was enough free space on the MMC/SD card to create file of required size. 0 - otherwise. This function is used to create a swap file of predefined name and size on the MMC/SD media. If a file with specified name already exists on the media, search for consecutive sectors will ignore sectors occupied by this file. Therefore, it is recommended to erase such file if it already exists before calling this function. If it is not erased and there is still enough space for a new swap file, this function will delete it after allocating new memory space for a new swap file. The purpose of the swap file is to make reading and writing to MMC/SD media as fast as possible, by using the Mmc_Read_Sector() and Mmc_Write_Sector() functions directly, without potentially damaging the FAT system. The swap file can be considered as a "window" on the media where the user can freely write/read data. It's main purpose in the mikroBasic PRO for PIC's library is to be used for fast data acquisition; when the time-critical acquisition has finished, the data can be re-written into a "normal" file, and formatted in the most suitable way. Parameters:
sectors_cnt: number of consecutive sectors that user wants the swap
Description
file to have.
352
Libraries
filename: name of the file that should be assigned for file operations. File name should be in DOS 8.3 (file_name.extension) format. The file name and extension will be automatically padded with spaces by the library if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so the user does no have to take care of that. The file name and extension are case insensitive. The library will convert them to proper case automatically, so the user does not have to take care of that. Also, in order to keep backward compatibility with the first version of this library, file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension (i.e. "MIKROELETXT" -> MIKROELE.TXT). In this case last 3 characters of the string are considered to be file extension. file_attr: file creation and attributs flags. Each bit corresponds to the appropriate file attribut: Bit Mask 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80 Description Read Only Hidden System Volume Label Subdirectory Archive Device (internal use only, never found on disk) Not used
Description
0 1 2 3 4 5 6 7
Note: Long File Names (LFN) are not supported. Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init
'-------------- Try to create a swap file with archive atribute, whose size will be at least 1000 sectors. ' If it succeeds, it sends No. of start sector over UART dim size as longword ... main: ... size = Mmc_Fat_Get_Swap_File(1000, "mikroE.txt", 0x20) if size then UART1_Write(0xAA) UART1_Write(Lo(size)) UART1_Write(Hi(size)) UART1_Write(Higher(size)) UART1_Write(Highest(size)) UART1_Write(0xAA end if ... end.
Example
353
CHAPTER 7
Libraries
Library Example
The following example demonstrates MMC library test. Upon flashing, insert a MMC/SD card into the module, when you should receive the "Init-OK" message. Then, you can experiment with MMC read and write functions, and observe the results through the Usart Terminal.
program MMC_Test dim MMC_chip_select as sbit at RC2_bit dim MMC_chip_select_direction as sbit at TRISC2_bit const dim dim dim FILL_CHAR = "m" i, SectorNo as word mmc_error as byte data_ok as bit
' Variables for MMC routines SectorData as byte[512] ' Buffer for MMC sector reading/writing data_for_registers as byte[16] ' buffer for CID and CSD registers ' UART write text and new line (carriage return + line feed) sub procedure UART_Write_Line(dim byref uart_text as byte) UART1_Write_Text(uart_text) UART1_Write(13) UART1_Write(10) end sub ' Display byte in hex sub procedure printhex(dim i as byte) dim high, low as byte high = i and 0xF0 high = high >> 4 high = high + "0" if ( high > "9" ) then high = high + 7 low = (i and 0x0F) + "0" if ( low > "9" ) then low = low + 7 end if UART1_Write(high) UART1_Write(low) end if end sub ' High nibble
354
Libraries
' Configure AN pins as digital ' Turn off comparators
355
CHAPTER 7
Libraries
' Reading of CSD register mmc_error = Mmc_Read_Csd(data_for_registers) if ( mmc_error = 0 ) then UART1_Write_Text("CSD : ") for i = 0 to 15 printhex(data_for_registers[i]) next i UART_Write_Line(" ") else UART_Write_Line("CSD-error") end if ' Read sector mmc_error = Mmc_Read_Sector(SectorNo, SectorData) if ( mmc_error = 0 ) then UART_Write_Line("Read-OK") else ' if there are errors..... UART_Write_Line("Read-Error") end if ' Chech data match data_ok = 1 for i = 0 to 511 UART1_Write(SectorData[i]) if (SectorData[i] <> FILL_CHAR) then data_ok = 0 break end if next i if ( data_ok <> 0 ) then UART_Write_Line("Content-OK") else UART_Write_Line("Content-Error") end if ' Signal test end UART_Write_Line("Test End.") end.
356
Libraries
HW Connection
357
CHAPTER 7
The OneWire library provides routines for communication via the Dallas OneWire protocol, for example 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 that oscillator frequency Fosc needs to be at least 4MHz in order to use the routines with Dallas digital thermometers. Note: This library implements time-based activities, so interrupts need to be disabled when using OneWire library.
Library Routines
Ow_Reset Ow_Read Ow_Write
358
Libraries
Ow_Reset
Prototype Returns Description Requires Example
sub function Ow_Reset(dim byref port as byte, pin as byte) as byte
0 if DS1820 is present, and 1 if not present. Issues OneWire reset signal for DS1820. Parameters port and pin specify the location of DS1820. Works with Dallas DS1820 temperature sensor only. To reset the DS1820 that is connected to the RA5 pin:
Ow_Reset(PORTA, 5)
Ow_Read
Prototype Returns
sub function Ow_Read(dim byref port as byte, dim pin as byte) as byte
Description Reads one byte of data via the OneWire bus. Requires Example Works with Dallas DS1820 temperature sensor only.
tmp = Ow_Read(PORTA, 5)
Ow_Write
Prototype Returns
sub procedure Ow_Write(dim byref port as byte, dim pin, par as byte)
Nothing.
Description Writes one byte of data (argument par) via OneWire bus. Requires Example Works with Dallas DS1820 temperature sensor only.
Ow_Write(PORTA, 5, $CC)
359
CHAPTER 7
Libraries
Library Example
This example reads the temperature using DS18x20 connected to pin PORTA.B5. After reset, MCU obtains temperature from the sensor and prints it on the Lcd. Make sure to pull-up PORTA.B5 line and to turn off the PORTA LEDs.
program OneWire ' Lcd module connections dim LCD_RS as sbit at RB4_bit LCD_EN as sbit at RB5_bit LCD_D4 as sbit at RB0_bit LCD_D5 as sbit at RB1_bit LCD_D6 as sbit at RB2_bit LCD_D7 as sbit at RB3_bit LCD_RS_Direction as sbit at LCD_EN_Direction as sbit at LCD_D4_Direction as sbit at LCD_D5_Direction as sbit at LCD_D6_Direction as sbit at LCD_D7_Direction as sbit at ' End Lcd module connections
' Set TEMP_RESOLUTION to the corresponding resolution DS18x20 sensor: ' 18S20: 9 (default setting can be 9,10,11,or 12) ' 18B20: 12 const TEMP_RESOLUTION as byte = 9 dim text as byte[9] temp as word sub procedure Display_Temperature( dim temp2write as word ) const RES_SHIFT = 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 = word(temp2write >> RES_SHIFT) ' convert temp_whole to characters if ( temp_whole div 100 ) then
of
used
360
Libraries
' extract temp_fraction and convert it to unsigned int temp_fraction = word(temp2write << (4-RES_SHIFT)) temp_fraction = temp_fraction and 0x000F temp_fraction = temp_fraction * 625 ' convert temp_fraction to characters text[4] = word(temp_fraction div 1000) + 48 ' Extract thousands digit text[5] = word((temp_fraction div 100)mod 10 + 48) ' Extract hundreds digit text[6] = word((temp_fraction div 10)mod 10 + 48) ' Extract tens digit text[7] = word(temp_fraction mod 10) + 48 ' Extract ones digit ' print temperature on Lcd Lcd_Out(2, 5, text) end sub main: ANSEL = 0 ANSELH = 0 text = "000.0000" Lcd_Init() Lcd_Cmd(_LCD_CLEAR) Lcd_Cmd(_LCD_CURSOR_OFF) Lcd_Out(1, 1, " Temperature: Lcd_Chr(2,13,178) code for degree Lcd_Chr(2,14,"C") 178 instead of 223
' Initialize Lcd ' Clear Lcd ' Turn cursor off ")
' Print degree character, "C" for Centigrades ' different Lcd displays have different char ' if you see greek alpha letter try typing
'--- main loop while (TRUE) '--- perform temperature reading Ow_Reset(PORTE, 2) ' Onewire reset signal Ow_Write(PORTE, 2, 0xCC) ' Issue command SKIP_ROM Ow_Write(PORTE, 2, 0x44) ' Issue command CONVERT_T Delay_us(120)
361
CHAPTER 7
Libraries
Ow_Reset(PORTE, 2) Ow_Write(PORTE, 2, 0xCC) Ow_Write(PORTE, 2, 0xBE)
temp = Ow_Read(PORTE, 2) temp = (Ow_Read(PORTE, 2) << 8) + temp '--- Format and display result on Lcd Display_Temperature(temp) Delay_ms(520) wend end.
HW Connection
362
Libraries
dim SPExpanderRST as sbit Reset line. sfr external; dim SPExpanderCS as sbit sfr external dim SPExpanderRST_Direction as sbit sfr external dim SPExpanderCS_Direction as sbit sfr external
Chip Select line. Direction of the Reset pin. Direction of the Chip Select pin.
Library Routine
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
363
CHAPTER 7
Libraries
Expander_Init
Prototype Returns
Nothing. Initializes Port Expander using SPI communication. Port Expander module settings : 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
Description
Global variables :
SPExpanderCS: Chip Select line SPExpanderRST: Reset line SPExpanderCS_Direction: Direction of the Chip Select pin SPExpanderRST_Direction: Direction of the Reset pin
Requires
must be defined before using this function. SPI module needs to be initialized. See SPI1_Init and SPI1_Init_Advanced routines.
' port expander pinout definition dim SPExpanderCS as sbit at RC1_bit SPExpanderRST as sbit at RC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit ... SPI1_Init() Expander_Init(0)
Example
364
Libraries
Expander_Read_Byte
Prototype Returns
sub function Expander_Read_Byte(dim ModuleAddress as byte, dim RegAddress as byte) as byte
Description
Parameters :
ModuleAddress: Port Expander hardware address, see schematic at the
Requires Example
Expander_Write_Byte
Prototype Returns
sub procedure Expander_Write_Byte(dim ModuleAddress as byte, dim RegAddress as byte, dim Data_ as byte)
Description
Requires Example
365
CHAPTER 7
Libraries
Expander_Read_PortA
Prototype Returns
Byte read.
The function reads byte from Port Expander's PortA. Parameters : Description ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Port Expander must be initialized. See Expander_Init. Requires 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) 'set expander's porta to be input ... read_data = Expander_Read_PortA(0)
Example
Expander_Read_PortB
Prototype Returns
sub function Expander_Read_PortB(dim ModuleAddress as byte) as byte
Byte read.
The function reads byte from Port Expander's PortB. Parameters : Description ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Port Expander must be initialized. See Expander_Init. Requires 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)
Example
366
Libraries
Expander_Read_PortAB
Prototype Returns
sub function Expander_Read_PortAB(dim ModuleAddress as byte) as word
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 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)
Example
Expander_Write_PortA
Prototype Returns
sub procedure Expander_Write_PortA(dim ModuleAddress as byte, dim Data_ as byte)
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
367
CHAPTER 7
Libraries
Expander_Write_PortB
Prototype 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 PORT ... Expander_Set_DirectionPortB(0,0x00) output ... Expander_Write_PortB(0, 0x55)
Example
Expander_Write_PortAB
Prototype Returns
sub procedure Expander_Write_PortAB(dim ModuleAddress as byte, dim Data_ as word)
Nothing.
The function writes word to Port Expander's ports. Parameters : ModuleAddress: Port Expander hardware address, see schematic at the Description 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 Requires Port Expander must be initialized. See Expander_Init. 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
368
Libraries
Expander_Set_DirectionPortA
Prototype Returns
sub procedure Expander_Set_DirectionPortA(dim ModuleAddress as byte, dim Data_ as byte)
Nothing.
The function sets Port Expander's PortA direction. Parameters : ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Description Data_: data to be written to the PortA direction register. Each bit corre sponds to the appropriate pin of the PortA register. Set bit designates cor responding pin as input. Cleared bit designates corresponding pin as out put. Requires Example Port Expander must be initialized. See Expander_Init.
' Set Port Expander's PORTA to be output Expander_Set_DirectionPortA(0,0x00)
Expander_Set_DirectionPortB
Prototype Returns
sub procedure Expander_Set_DirectionPortB(dim ModuleAddress as byte, dim Data_ as byte)
Nothing.
The function sets Port Expander's PortB direction. Parameters : ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Description Data_: data to be written to the PortB direction register. Each bit corre sponds to the appropriate pin of the PortB register. Set bit designates cor responding pin as input. Cleared bit designates corresponding pin as out put. Requires Example Port Expander must be initialized. See Expander_Init.
' Set Port Expander's PORTB to be input Expander_Set_DirectionPortB(0,0xFF)
369
CHAPTER 7
Libraries
Expander_Set_DirectionPortAB
Prototype 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 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.
Description
Requires Example
Expander_Set_PullUpsPortA
Prototype Returns
sub procedure Expander_Set_PullUpsPortA(dim ModuleAddress as byte, dim Data_ as byte)
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 Example
370
Libraries
Expander_Set_PullUpsPortB
Prototype Returns
sub procedure Expander_Set_PullUpsPortB(dim ModuleAddress as byte, dim Data_ as byte)
Nothing. The function sets Port Expander's PortB pull up/down resistors. Parameters :
Description
corresponds to the appropriate pin of the PortB register. Set bit enables pull-up for corresponding pin. Requires Example Port Expander must be initialized. See Expander_Init.
Set Port Expander's PORTB pull-up resistors Expander_Set_PullUpsPortB(0, 0xFF)
Expander_Set_PullUpsPortAB
Prototype Returns
sub procedure Expander_Set_PullUpsPortAB(dim ModuleAddress as byte, dim PullUps as word)
Nothing. The function sets Port Expander's PortA and PortB pull up/down resistors. Parameters :
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.
Description
Requires Example
371
CHAPTER 7
Libraries
Library Example
The example demonstrates how to communicate with Port Expander MCP23S17. Note that Port Expander pins A2 A1 A0 are connected to GND so Port Expander Hardware Address is 0.
program PortExpander ' Port Expander module connections dim SPExpanderRST as sbit at RC0_bit SPExpanderCS as sbit at RC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit ' End Port Expander module connections dim counter as byte' = 0 main: counter = 0 ANSEL = 0 ANSELH = 0 TRISB = 0 PORTB = 0
SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV4, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH) Expander_Init(0) ' Initialize Port Expander Expander_Set_DirectionPortA(0, 0x00) ' Set Expander's PORTA to be output Expander_Set_DirectionPortB(0,0xFF) ' Set Expander's PORTB to be input Expander_Set_PullUpsPortB(0,0xFF) ' Set pull-ups to all of the Expander's PORTB pins while TRUE Expander_Write_PortA(0, counter) Inc(counter) PORTB = Expander_Read_PortB(0) write it to LEDs Delay_ms(100) wend end. ' Endless loop ' Write i to expander's PORTA ' Read expander's PORTB and
372
Libraries
HW Connection
373
CHAPTER 7
The mikroBasic PRO for PIC 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.
Description:
Example :
Library Routines
Ps2_Config Ps2_Key_Read
374
Libraries
Ps2_Config
Prototype Returns
sub procedure Ps2_Config()
Nothing.
Description Initializes the MCU for work with the PS/2 keyboard. Global variables :
PS2_Data: Data signal line PS2_Clock: Clock signal line in PS2_Data_Direction: Direction of the Data pin PS2_Clock_Direction: Direction of the Clock pin
Requires
Example
375
CHAPTER 7
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
Description
Requires
Example
376
Libraries
377
CHAPTER 7
Libraries
Library Example
This simple example reads values of the pressed keys on the PS/2 keyboard and sends them via UART.
program PS2_Example dim keydata, special, down as byte dim PS2_Data PS2_Clock as sbit at PORTC.0 as sbit at PORTC.1
Initialize UART module at 9600 bps Init PS/2 Keyboard Wait for keyboard to finish Ready
while TRUE ' Endless loop if Ps2_Key_Read(keydata, special, down) then ' If data was read from PS/2 if (down <> 0) and (keydata = 16) then ' Backspace read UART1_Write(0x08) ' Send Backspace to usart terminal else if (down <> 0) and (keydata = 13) then ' Enter read UART1_Write(10) ' Send carriage return to usart terminal UART1_Write(13) ' Uncomment this line if usart terminal also expects line feed ' for new line transition else if (down <> 0) and (special = 0) and (keydata <> 0) then ' Common key read UART1_Write(keydata) ' Send key to usart terminal end if end if end if end if Delay_ms(10) ' Debounce period wend end.
378
Libraries
HW Connection
379
CHAPTER 7
CCP module is available with a number of PIC MCUs. mikroBasic PRO for PIC provides library which simplifies using PWM HW Module. Note: Some MCUs have multiple CCP modules. In order to use the desired CCP library routine, simply change the number 1 in the prototype with the appropriate module number, i.e.
PWM2_Start()
Library Routines
PWM1_Init PWM1_Set_Duty PWM1_Start PWM1_Stop
PWM1_Init
Prototype Returns
sub procedure PWM1_Init(dim freq as longint)
Nothing.
Initializes the PWM module with duty ratio 0. Parameter freq is a desired PWM frequency in Hz (refer to device data sheet for correct values in respect with Description Fosc). This routine needs to be called before using other functions from PWM Library. MCU must have CCP module. Requires Note: Calculation of the PWM frequency value is carried out by the compiler, as it would produce a relatively large code if performed on the libary level. Therefore, compiler needs to know the value of the parameter in the compile time. That is why this parameter needs to be a constant, and not a variable. Initialize PWM module at 5KHz: Example
PWM1_Init(5000)
380
Libraries
PWM1_Set_Duty
Prototype Returns
sub procedure PWM1_Set_Duty(dim duty_ratio as byte)
Nothing.
Sets PWM duty ratio. Parameter duty takes values from 0 to 255, where 0 is Description 0%, 127 is 50%, and 255 is 100% duty ratio. Other specific values for duty ratio can be calculated as (Percent*255)/100. Requires Example
PWM1_Set_Duty(192)
MCU must have CCP module. PWM1_Init must be called before using this routine. Set duty ratio to 75%:
PWM1_Start
Prototype Returns
sub procedure PWM1_Star
Nothing. MCU must have CCP module. PWM1_Init must be called before using this routine.
PWM1_Start
PWM1_Stop
Prototype Returns
sub procedure PWM1_Stop
Nothing.
Description Stops PWM. Requires Example MCU must have CCP module. PWM1_Init must be called before using this routine. PWM1_Start should be called before using this routine, otherwise it will have no effect as the PWM module is not running.
PWM1_Stop
381
CHAPTER 7
Libraries
Library Example
The example changes PWM duty ratio on pin PB3 continually. If LED is connected to PB3, you can observe the gradual change of emitted light.
program PWM_Test dim current_duty, current_duty1, old_duty, old_duty1 as byte sub procedure InitMain() ANSEL = 0 ANSELH = 0 PORTA = 255 TRISA = 255 PORTB = 0 TRISB = 0 PORTC = 0 TRISC = 0 PWM1_Init(5000) PWM2_Init(5000) end sub main: InitMain() current_duty = 16 current_duty1 = 16 PWM1_Start() PWM2_Start() PWM1_Set_Duty(current_duty) PWM2_Set_Duty(current_duty1) while (TRUE) if (RA0_bit <> 0) then Delay_ms(40) Inc(current_duty) PWM1_Set_Duty(current_duty) end if if (RA1_bit <> 0) then Delay_ms(40) Dec(current_duty) PWM1_Set_Duty(current_duty) end if if (RA2_bit <> 0) then Delay_ms(40) Inc(current_duty1) PWM2_Set_Duty(current_duty1)
configure PORTA set PORTB to 0 designate PORTB set PORTC to 0 designate PORTC Initialize PWM1 Initialize PWM2
pins as input pins as output pins as output module at 5KHz module at 5KHz
' initial value for current_duty ' initial value for current_duty1 ' start PWM1 ' start PWM2 ' Set current duty for PWM1 ' Set current duty for PWM2 ' endless loop ' button on RA0 pressed ' increment current_duty
382
Libraries
HW Connection
PWM demonstration
383
CHAPTER 7
RS-485 is a multipoint communication which allows multiple devices to be connected to a single bus. The mikroBasic PRO for PIC 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 users 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). Note: The library uses the UART module for communication. The user must initialize the appropriate UART module before using the RS-485 Library. For MCUs with two UART modules it is possible to initialize both of them and then switch by using the UART_Set_Active function. See the UART Library functions. 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).
Description:
Example :
dim dim RS485_rxtx_pin_direction Direction of the RS-485 RS485_rxtx_pin_direcas sbit sfr ternal tion as sbit at Transmit/Receive pin TRISC2_bit
384
Libraries
Library Routines
RS485Master_Init RS485Master_Receive RS485Master_Send RS485Slave_Init RS485Slave_Receive RS485Slave_Send
RS485master_Init
Prototype Returns
sub procedure RS485Master_Init()
Nothing.
ceiver(see schematic at the bottom of this page). RE/DE signal controls RS-485 transceiver operation mode. Requires
RS485_rxtx_pin_direction - direction of the RS-485 Transmit/Receive
pin must be defined before using this function. UART HW module needs to be initialized. See UARTx_Init
' RS485 module pinout dim RS485_rxtx_pin as sbit at RC2_bit dim RS485_rxtx_pin_direction as sbit at TRISC2_bit ' End of RS485 module pinout ... UART1_Init(9600) ' initialize UART module RS485Master_Init() ' intialize MCU as a Master for RS-485 communication
Example
385
CHAPTER 7
Libraries
RS485master_Receive
Prototype Returns
Nothing.
Receives messages from Slaves. Messages are multi-byte, so this routine must be called for each byte received. Parameters : data_buffer: 7 byte buffer for storing received data, in the following man ner: data[0..2]: message content Description data[3]: number of message bytes received, 13 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. Requires Example MCU must be initialized as a Master for RS-485 communication. See RS485master_Init.
dim msg as byte[20] ... RS485Master_Receive(msg)
RS485master_Send
Prototype Returns
sub procedure Rs485Master_Send(dim byref data_buffer as byte[20], dim datalen as byte, dim slave_address as byte)
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 users responsibility to ensure (by protocol) that only one device sends data via 485 bus at a time. Example
dim msg as byte[20] ... ' send 3 bytes of data to slave with address 0x12 RS485Master_Send(msg, 3, 0x12)
386
Libraries
RS485slave_Init
Prototype Returns
sub procedure RS485Slave_Init(dim slave_address as byte)
Description Parameters :
slave_address: Slave address
Global variables :
RS485_rxtx_pin - this pin is connected to RE/DE input of RS-485 trans
ceiver(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) Requires
RS485_rxtx_pin_direction - direction of the RS-485 Transmit/Receive
pin must be defined before using this function. UART HW module needs to be initialized. See UARTx_Init.
' RS485 module pinout dim RS485_rxtx_pin as sbit at RC2_bit dim RS485_rxtx_pin_direction as sbit at TRISC2_bit ' End of RS485 module pinout ... UART1_Init(9600) ' initialize UART module RS485Slave_Init(160) ' intialize MCU as a Slave for RS-485 communication with address 160
Example
387
CHAPTER 7
Libraries
RS485slave_Receive
Prototype 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 :
data_buffer: 6 byte buffer for storing received data, in the following mann
Description
er:
data[0..2]: message content data[3]: number of message bytes received, 13 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 Example MCU must be initialized as a Slave for RS-485 communication. See RS485slave_Init.
dim msg as byte[5] ... RS485Slave_Read(msg)
RS485slave_Send
Prototype Returns
sub procedure RS485Slave_Send(dim byref data_buffer as byte[20], dim datalen as byte)
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 users responsibility to ensure (by protocol) that only one device sends data via 485 bus at a time.
dim msg as byte[8] ... ' send 2 bytes of data to the master RS485Slave_Send(msg, 2)
Example
388
Libraries
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 PORTB, while error on receive (0xAA) and number of consecutive unsuccessful retries are displayed on PORTD. Slave displays received data on PORTB, while error on receive (0xAA) is displayed on PORTD. Hardware configurations in this example are made for the EasyPIC5 board and 16F887. RS485 Master code:
program RS485_Master_Example dim dat as byte[10] i, j as byte cnt as longint ' buffer for receving/sending messages
dim rs485_rxtx_pin as sbit at RC2_bit ' set transcieve pin rs485_rxtx_pin_direction as sbit at TRISC2_bit ' set tran scieve pin direction ' Interrupt routine sub procedure interrupt() RS485Master_Receive(dat) end sub main: cnt = 0 ANSEL = 0 ANSELH = 0 C1ON_bit = 0 C2ON_bit = 0 PORTB PORTD TRISB TRISD = = = = 0 0 0 0 ' initialize UART1 module
UART1_Init(9600) Delay_ms(100)
389
CHAPTER 7
Libraries
RS485Master_Init() dat[0] = 0xAA dat[1] = 0xF0 dat[2] = 0x0F dat[4] = 0 dat[5] = 0 dat[6] = 0
' ensure that message received flag is 0 ' ensure that error flag is 0
RS485Master_Send(dat,1,160) PIE1.RCIE = 1 PIE2.TXIE = 0 INTCON.PEIE = 1 INTCON.GIE = 1 while TRUE Inc(cnt) if (dat[5] <> 0) then PORTD = 0xAA end if ' ' ' ' enable interrupt on UART1 receive disable interrupt on UART1 transmit enable peripheral interrupts enable all interrupts
' upon completed valid message receiving ' data[4] is set to 255 ' if an error detected, signal it ' by setting portd to 0xAA
if (dat[4] <> 0) then ' if message received successfully cnt = 0 dat[4] = 0 ' clear message received flag j = dat[3] for i = 1 to dat[3] ' show data on PORTB PORTB = dat[i-1] next i dat[0] = dat[0]+1 ' increment received dat[0] Delay_ms(1) ' send back to slave RS485Master_Send(dat,1,160) end if if (cnt > 100000) then ' if in 100000 poll-cycles the answer Inc(PORTD) ' was not detected, signal cnt = 0 ' failure of send-message RS485Master_Send(dat,1,160) if (PORTD > 10) then ' if sending failed 10 times RS485Master_Send(dat,1,50) ' send message on broadcast address end if end if wend end.
390
Libraries
dim rs485_rxtx_pin as sbit at RC2_bit ' set transcieve pin rs485_rxtx_pin_direction as sbit at TRISC2_bit ' set transcieve pin direction ' Interrupt routine sub procedure interrupt() RS485Slave_Receive(dat) end sub main: ANSEL = ANSELH = C1ON_bit C2ON_bit PORTB PORTD TRISB TRISD = = = =
0 0 = 0 = 0 0 0 0 0
UART1_Init(9600) Delay_ms(100) RS485Slave_Init(160) dat[4] = 0 dat[5] = 0 dat[6] = 0 PIE1.RCIE = 1 PIE2.TXIE = 0 INTCON.PEIE = 1 INTCON.GIE = 1
' initialize UART1 module ' Initialize MCU as slave, address 160 ' ensure that message received flag is 0 ' ensure that message received flag is 0 ' ensure that error flag is 0 ' ' ' ' enable interrupt on UART1 receive disable interrupt on UART1 transmit enable peripheral interrupts enable all interrupts
while TRUE if (dat[5] <> 0) then ' if an error detected, signal it by PORTD = 0xAA ' setting PORTD to 0xAA dat[5] = 0 end if if (dat[4] <> 0) then ' upon completed valid message receive dat[4] = 0 ' data[4] is set to 0xFF j = dat[3] for i = 1 to dat[3] ' show data on PORTB
391
CHAPTER 7
Libraries
PORTB = dat[i-1] next i dat[0] = dat[0]+1 Delay_ms(1) RS485Slave_Send(dat,1) end if wend end.
HW Connection
Example of interfacing PC to PIC16F887 MCU via RS485 bus with LTC485 as RS-485 transceiver
392
Libraries
DATALEN bits -----------bit7 = 1 MASTER SENDS 0 SLAVE SENDS bit6 = 1 ADDRESS WAS XORed with 1, IT WAS EQUAL TO _STOP_BYTE 0 ADDRESS UNCHANGED bit5 = 0 FIXED bit4 = 1 DATA3 (if exists) WAS XORed with 1, IT WAS _START_BYTE or _STOP_BYTE 0 DATA3 (if exists) UNCHANGED bit3 = 1 DATA2 (if exists) WAS XORed with 1, IT WAS _START_BYTE or _STOP_BYTE 0 DATA2 (if exists) UNCHANGED bit2 = 1 DATA1 (if exists) WAS XORed with 1, IT WAS _START_BYTE or _STOP_BYTE 0 DATA1 (if exists) UNCHANGED bit1bit0 = 0 to 3 NUMBER OF DATA BYTES SEND
_START_BYTE or
EQUAL TO
EQUAL TO
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 not take the _START_BYTE<4..0> or _STOP_BYTE<4..0> values.
393
CHAPTER 7
The mikroBasic PRO for PIC provides routines for implementing Software I2C communication. These routines are hardware independent and can be used with any MCU. The Software I2C library enables you to use MCU as Master in I2C communication. Multi-master mode is not supported. Note: This library implements time-based activities, so interrupts need to be disabled when using Software I2C. Note: All Software I2C Library functions are blocking-call functions (they are waiting for I2C clock line to become logical one). Note: The pins used for the Software I2C communication should be connected to the pull-up resistors. Turning off the LEDs connected to these pins may also be required.
Description:
Example :
dim Soft_I2C_Scl as sbit at RC3_bit dim Soft_I2C_Sda as sbit at RC4_bit dim Soft_I2C_Scl_Direction as sbit at TRISC3_bit dim Soft_I2C_Sda_Direction as sbit at TRISC4_bit
dim Direction of the Soft I2C Soft_I2C_Scl_Direction Clock pin. as sbit sfr external dim Direction of the Soft I2C Soft_I2C_Sda_Direction Data pin. as sbit sfr external
Library Routines
Soft_I2C_Init Soft_I2C_Start Soft_I2C_Read Soft_I2C_Write Soft_I2C_Stop Soft_I2C_Break
394
Libraries
Soft_I2C_Init
Prototype Returns
sub procedure Soft_I2C_Init()
Nothing.
Example
Soft_I2C_Start
Prototype Returns
sub procedure Soft_I2C_Start()
Nothing.
Description Determines if the I2C bus is free and issues START signal. Requires Example Software I2C must be configured before using this function. See Soft_I2C_Init routine.
' Issue START signal Soft_I2C_Start()
395
CHAPTER 7
Libraries
Soft_I2C_Read
Prototype Returns
One byte from the Slave. Reads one byte from the slave.
Description
Parameters :
ack: acknowledge signal parameter. If the ack==0 not acknowledge sig nal will be sent after reading, otherwise the acknowledge signal will be sent.
Soft I2C must be configured before using this function. See Soft_I2C_Init routine. Requires 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)
Example
Soft_I2C_Write
Prototype Returns
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 I2C bus.
Soft I2C must be configured before using this function. See Soft_I2C_Init routine. Requires 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)
Example
396
Libraries
Soft_I2C_Stop
Prototype Returns
sub procedure Soft_I2C_Stop()
Nothing.
Description Issues STOP signal. Requires Example Soft I2C must be configured before using this function. See Soft_I2C_Init routine.
' Issue STOP signal Soft_I2C_Stop()
Soft_I2C_Break
Prototype Returns
sub procedure Soft_I2C_Break()
Nothing.
All Software I2C Library functions can block the program flow (see note at the top of this page). Calling this routine from interrupt will unblock the program Description execution. This mechanism is similar to WDT. Note: Interrupts should be disabled before using Software I2C routines again (see note at the top of this page). Requires Nothing.
dim data1, error_, counter as byte sub procedure interrupt() if (INTCON.T0IF <> 0) then if (counter >= 20) then Soft_I2C_Break() counter = 0 ' reset counter end if else Inc(counter) ' increment counter INTCON.T0IF = 0 ' Clear Timer0 overflow interrupt flag end if end sub main: counter = 0 OPTION_REG = 0x04 ... ' try Soft_I2C_Init with blocking prevention mechanism INTCON.GIE = 1 ' Global interrupt enable INTCON.T0IE = 1 ' Enable Timer0 overflow interrupt data1 = Soft_I2C_Init(error_) INTCON.GIE = 0 ' Global interrupt disable end.
Example
397
CHAPTER 7
Libraries
LLibrary Example
The example demonstrates Software IC Library routines usage. The PIC 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 RTC_Read dim seconds, minutes, hours, _day, _month, year as byte date/time variables ' Software I2C connections dim Soft_I2C_Scl as sbit at RC3_bit Soft_I2C_Sda as sbit at RC4_bit Soft_I2C_Scl_Direction as sbit at TRISC3_bit Soft_I2C_Sda_Direction as sbit at TRISC4_bit ' End Software I2C connections ' Lcd module connections dim LCD_RS as sbit at RB4_bit LCD_EN as sbit at RB5_bit LCD_D4 as sbit at RB0_bit LCD_D5 as sbit at RB1_bit LCD_D6 as sbit at RB2_bit LCD_D7 as sbit at RB3_bit LCD_RS_Direction as sbit at LCD_EN_Direction as sbit at LCD_D4_Direction as sbit at LCD_D5_Direction as sbit at LCD_D6_Direction as sbit at LCD_D7_Direction as sbit at ' End Lcd module connections ' Global
'--------------------- Reads time and date information from RTC (PCF8583) sub procedure Read_Time() Soft_I2C_Start() ' Issue start signal Soft_I2C_Write(0xA0) ' Address PCF8583, see PCF8583 datasheet Soft_I2C_Write(2) ' Start from address 2 Soft_I2C_Start() ' Issue repeated start signal Soft_I2C_Write(0xA1) ' Address PCF8583 for reading R/W=1 seconds = Soft_I2C_Read(1) ' Read seconds byte minutes = Soft_I2C_Read(1) ' Read minutes byte hours = Soft_I2C_Read(1) ' Read hours byte _day = Soft_I2C_Read(1) ' Read year/day byte _month = Soft_I2C_Read(0) ' Read weekday/month byte} Soft_I2C_Stop() ' Issue stop signal} end sub
398
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, 7, (_day / 10) + 48) ' Print tens digit of day variable Lcd_Chr(1, 8, (_day mod 10) + 48) ' Print oness digit of day variable Lcd_Chr(1,10, (_month / 10) + 48) Lcd_Chr(1,11, (_month mod 10) + 48) Lcd_Chr(1,16, year + 56) ' Print year vaiable + 8 (start from year 2008) Lcd_Chr(2, 7, Lcd_Chr(2, 8, Lcd_Chr(2,10, Lcd_Chr(2,11, Lcd_Chr(2,13, Lcd_Chr(2,14, end sub (hours / 10) + (hours mod 10) (minutes / 10) + (minutes mod 10) (seconds / 10) + (seconds mod 10) 48) + 48) 48) + 48) 48) + 48)
'------------------ Performs project-wide init sub procedure Init_Main() TRISB = 0 PORTB = 0xFF TRISB = 0xFF ANSEL = 0 ' Configure AN pins as digital I/O ANSELH = 0 Soft_I2C_Init() ' Initialize Soft I2C communication Lcd_Init() ' Initialize Lcd Lcd_Cmd(_LCD_CLEAR) ' Clear Lcd display Lcd_Cmd(_LCD_CURSOR_OFF) ' Turn cursor off Lcd_Out(1,1,"Date:") ' Prepare and output static text on Lcd Lcd_Chr(1,9,":") Lcd_Chr(1,12,":") Lcd_Out(2,1,"Time:") Lcd_Chr(2,9,":")
399
CHAPTER 7
Libraries
Lcd_Chr(2,12,":") Lcd_Out(1,13,"200") end sub
'----------------- 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
400
Libraries
Description:
Example :
dim SoftSpi_CLK as sbit at RC3_bit dim Direction of the Data In pin. SoftSpi_SDI_Direction as sbit at TRISC4_bit Direction of the Data Out dim SoftSpi_SDO_Direction pin as sbit at TRISC5_bit dim Direction of the Clock pin SoftSpi_CLK_Direction as sbit at TRISC3_bit
Library Routines
Soft_Spi_Init Soft_Spi_Read Soft_Spi_Write MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
401
CHAPTER 7
Libraries
Soft_Spi_Init
Prototype Returns
sub procedure Soft_SPI_Init()
Nothing.
Description Configures and initializes the software SPI module. Global variables:
Chip_Select: Chip select line SoftSpi_SDI: Data in line SoftSpi_SDO: Data out line SoftSpi_CLK: Data clock line Chip_Select_Direction: Direction SoftSpi_SDI_Direction: Direction SoftSpi_SDO_Direction: Direction SoftSpi_CLK_Direction: Direction
Requires
of of of of
Chip select pin Data in pin Data out pin Data clock pin
Example
dim Chip_Select_Direction as sbit at dim SoftSpi_SDI_Direction as sbit at dim SoftSpi_SDO_Direction as sbit at dim SoftSpi_CLK_Direction as sbit at ' end of soft_spi pinout definition ... Soft_SPI_Init() ' Init Soft_SPI
402
Libraries
Soft_Spi_Read
Prototype Returns
sub function Soft_SPI_Read(dim sdata as byte) as word
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.
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)
Example
Soft_Spi_Write
Prototype Returns
sub procedure Soft_SPI_Write(dim sdata as byte)
Nothing. This routine sends one byte via the Software SPI bus.
Description Parameters :
sdata: data to be sent
Requires Example
Soft SPI must be initialized before using this function. See Soft_SPI_Init routine.
' Write a byte to the Soft SPI bus Soft_SPI_Write(0xAA)
403
CHAPTER 7
Libraries
Library Example
This code demonstrates using library routines for Soft_SPI communication. Also, this example demonstrates working with Microchip's MCP4921 12-bit D/A con verter.
program Soft_SPI ' DAC module connections dim Chip_Select as sbit at SoftSpi_CLK as sbit at SoftSpi_SDI as sbit at SoftSpi_SDO as sbit at
RC1_bit RC3_bit RC4_bit RC5_bit sbit sbit sbit sbit at at at at TRISC1_bit TRISC3_bit TRISC4_bit TRISC5_bit
dim Chip_Select_Direction as SoftSpi_CLK_Direction as SoftSpi_SDI_Direction as SoftSpi_SDO_Direction as ' End DAC module connections dim value as word sub procedure InitMain() TRISA0_bit = 1 TRISA1_bit = 1 Chip_Select = 1 Chip_Select_Direction = 0 Soft_Spi_Init() end sub
Set RA0 pin as input Set RA1 pin as input Deselect DAC Set CS# pin as Output 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 ' Select DAC chip ' Send High Byte temp = word(valueDAC >> 8) and 0x0F ' Store valueDAC[11..8] to temp[3..0] temp = temp or 0x30 Soft_SPI_Write(temp) ' Send Low Byte temp = valueDAC Soft_SPI_Write(temp) Chip_Select = 1 end sub ' Define DAC setting, see MCP4921 datasheet ' Send high byte via Soft SPI
' Store valueDAC[7..0] to temp[7..0] ' Send low byte via Soft SPI ' Deselect DAC chip
404
Libraries
' Perform main initialization ' When program starts, DAC gives ' the output in the mid-range while (TRUE) ' Endless loop if ((RA0_bit) and (value < 4095)) then ' If PA0 button is pressed Inc(value) ' increment value else if ((RA1_bit) and (value > 0)) then 'If PA1 button is pressed Dec(value) ' decrement value end if end if DAC_Output(value) Delay_ms(1) wend end. ' Send value to DAC chip ' Slow down key repeat pace
405
CHAPTER 7
mikroBasic provides library which implements software UART. These routines are hardware independent and can be used with any MCU. You can easily communicate with other devices via RS232 protocol simply use the functions listed below. Note: This library implements time-based activities, so interrupts need to be disabled when using Soft UART.
Library Routines
Soft_Uart_Init Soft_Uart_Read Soft_Uart_Write Soft_UART_Break
Soft_UART_Init
Prototype Returns
sub procedure Soft_UART_Init(dim byref port as byte, dim rx_pin, tx_pin, baud_rate, inverted as byte) as byte 2 - error, requested baud rate is too low 1 - error, requested baud rate is too high 0 - successfull initialization
Description
MCUs clock and working conditions. inverted: inverted output flag. When set to a non-zero value, inverted logic on output is used. Software UART routines use Delay_Cyc routine. If requested baud rate is too low then calculated parameter for calling Delay_Cyc exceeeds Delay_Cyc argument range. If requested baud rate is too high then rounding error of Delay_Cyc argument corrupts Software UART timings.
Requires Example
Nothing. This will initialize software UART and establish the communication at 9600 bps:
dim error as byte ... error = Soft_UART_Init(PORTB, 1, 2, 9600, 0)
406
Libraries
Soft_UART_Read
Prototype Returns
sub function Soft_UART_Read(dim byref error as byte) as byte
Function receives a byte via software UART. Parameter error will be zero if the Description transfer was successful. This is a non-blocking function call, so you should test the error manually (check the example below). Requires Soft UART must be initialized and communication established before using this function. See Soft_UART_Init. Heres a loop which holds until data is received: Example
error = 1 do data = Soft_UART_Read(error) loop until error = 0
Soft_Uart_Write
Prototype Returns
sub procedure Soft_UART_Write(dim data as byte)
Nothing.
Description Function transmits a byte (data) via UART. Soft UART must be initialized and communication established before using this function. See Soft_UART_Init. Requires 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.
Soft_UART_Write($0A)
Example
407
CHAPTER 7
Libraries
Soft_UART_Break
Prototype Returns
sub procedure Soft_UART_Break()
Nothing. Soft_UART_Read is blocking routine and it can block the program flow. Call this routine from interrupt to unblock the program execution. This mechanism is similar to WDT. Note: Interrupts should be disabled before using Software UART routines again (see note at the top of this page).
Description
Requires
Nothing.
dim data1, error_, counter as byte sub procedure interrupt() if (INTCON.T0IF <> 0) then if (counter >= 20) then Soft_UART_Break() counter = 0 ' reset counter end if else Inc(counter) ' increment counter INTCON.T0IF = 0 ' Clear Timer0 overflow interrupt flag end if end sub main: counter = 0 OPTION_REG = 0x04 ... if (Soft_UART_Init(PORTC, 7, 6, 9600, 0) = 0) then Soft_UART_Write(0x55) end if ... ' try Soft_UART_Read with blocking prevention mechanism INTCON.GIE = 1 ' Global interrupt enable INTCON.T0IE = 1 ' Enable Timer0 overflow interrupt data1 = Soft_UART_Read(error_) INTCON.GIE = 0 ' Global interrupt disable end.
Example
408
Libraries
Library Example
The example demonstrates simple data exchange via software UART. When PIC MCU receives data, it immediately sends the same data back. If PIC is connected to the PC (see the figure below), you can test the example from mikroBasic PRO for PIC terminal for RS232 communication, menu choice Tools Terminal.
program Soft_UART dim error_flag as byte counter, byte_read as byte main: ANSEL = 0 ANSELH = 0
TRISB = 0x00 ' Set PORTB as output (error sig nalization) PORTB = 0 ' No error VDelay_ms(370) error_flag = Soft_UART_Init(PORTC, 7, 6, 14400, 0) ' Initialize Soft UART at 14400 bps if (error_flag > 0) then PORTB = error_flag ' Signalize Init error while (TRUE) nop ' Stop program wend end if Delay_ms(100)
while TRUE ' Endless loop byte_read = Soft_UART_Read(error_flag)' Read byte, then test error flag if (error_flag <> 0) then ' If error was detected PORTB = error_flag ' signal it on PORTB else Soft_UART_Write(byte_read) ' If error was not detected, return byte read end if wend end.
409
CHAPTER 7
The mikroBasic PRO for PIC provides a Sound Library to supply users with rou tines 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).
Library Routines
Sound_Init Sound_Play
Sound_Init
Prototype Returns
sub procedure Sound_Init(dim byref snd_port as byte, dim snd_pin as byte)
Description
Parameters :
snd_port: sound output port address snd_pin: sound output pin
Requires Example
Nothing.
Sound_Init(PORTD, 3) ' Initialize sound at RD3
410
Libraries
Sound_Play
Prototype Returns
sub procedure Sound_Play(dim freq_in_Hz as word, dim duration_ms as word)
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.
' Play sound of 1KHz in duration of 100ms Sound_Play(1000, 100)
Example
Library Example
The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker.
program Sound sub procedure Tone1() Sound_Play(659, 250) end sub sub procedure Tone2() Sound_Play(698, 250) end sub sub procedure Tone3() Sound_Play(784, 250) end sub sub procedure Melody() Tone1() Tone2() Tone3() Tone1() Tone2() Tone3() Tone1() Tone2() Tone3() Tone1() Tone2() Tone3() Tone1() Tone2() Tone3() Tone3() Tone3() Tone2() end sub sub procedure ToneA()
' Plays the melody "Yellow house" Tone3() Tone3() Tone3() Tone2() Tone1()
411
CHAPTER 7
Libraries
Sound_Play( 880, 50) end sub sub procedure ToneC() Sound_Play(1046, 50) end sub sub procedure ToneE() Sound_Play(1318, 50) end sub sub procedure Melody2() dim counter as byte for counter = 9 to 1 step -1 ToneA() ToneC() ToneE() next counter end sub main: ANSEL = 0 ANSELH = 0 C1ON_bit = 0 C2ON_bit = 0 TRISB = 0xF0 as output Sound_Init(PORTD, 3) Sound_Play(880, 5000)
while TRUE ' endless loop if (Button(PORTB,7,1,1)) then ' If PORTB.7 is pressed play Tone1 Tone1() while (RB7_bit <> 0) nop ' Wait for button to be released wend end if if (Button(PORTB,6,1,1)) then ' If PORTB.6 is pressed play Tone1 Tone2() while (RB6_bit <> 0) nop ' Wait for button to be released wend end if
412
Libraries
if (Button(PORTB,4,1,1)) then ' If PORTB.4 is pressed play Tone1 Melody() while (RB4_bit <> 0) nop ' Wait for button to be released wend end if wend end.
HW Connection
413
CHAPTER 7
SPI module is available with a number of PIC MCU models. mikroBasic PRO for PIC provides a library for initializing Slave mode and comfortable work with Master mode. PIC can easily communicate with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc. You need PIC MCU with hardware integrated SPI (for example, PIC16F877). Note: Some PIC18 MCUs have multiple SPI modules. Switching between the SPI modules in the SPI library is done by the SPI_Set_Active function (SPI module has to be previously initialized). Note: In order to use the desired SPI library routine, simply change the number 1 in the prototype with the appropriate module number, i.e. SPI2_Init()
Library Routines
Spi_Init Spi_Init_Advanced Spi_Read Spi_Write SPI_Set_Active
SPI1_Init
Prototype Returns
sub procedure SPI1_Init()
Nothing. This routine configures and enables SPI module with the following settings: master mode 8 bit data transfer most significant bit sent first serial clock low when idle data sampled on leading edge serial clock = fosc/4 MCU must have SPI module.
' Initialize the SPI module with default settings SPI1_Init()
Description
Requires Example
414
Libraries
Spi1_Init_Advanced
Prototype Returns
sub procedure SPI1_Init_Advanced(dim master_slav, data_sample, clock_idle, transmit_edge as byte)
Nothing. Configures and initializes SPI. SPI1_Init_Advanced or SPI1_Init needs to be called before using other functions of SPI Library. Parameters mode, data_sample and clock_idle configure the SPI module, and can have the following values: Description Predefined library const SPI work mode:
Master clock = Fosc/4 Master clock = Fosc/16 Master clock = Fosc/64 Master clock source TMR2 Slave select enabled _MASTER_OSC_DIV4 _MASTER_OSC_DIV16 _MASTER_OSC_DIV64 _MASTER_TMR2 _SLAVE_SS_ENABLE _SLAVE_SS_DIS
Description
Transmit edge:
Data transmit on low to high edgefirst Data transmit on high to low edge _HIGH_2_LOW _LOW_2_HIGH
_HIGH_2_LOW
Requires
Example
415
CHAPTER 7
Libraries
Spi1_Read
Prototype Returns
Description
Parameters :
buffer: dummy data for clock generation (see device Datasheet for SPI
modules implementation details) Requires SPI module must be initialized before using this function. See SPI1_Init and SPI1_Init_Advanced routines.
' read a byte from the SPI bus dim take, dummy1 as byte ... take = SPI1_Read(dummy1)
Example
Spi1_Write
Prototype Returns
sub procedure SPI1_Write(dim wrdata as byte)
Description Parameters :
wrdata: data to be sent
Requires
SPI module must be initialized before using this function. See SPI1_Init and SPI1_Init_Advanced routines.
' write a byte to the SPI bus dim buffer as byte ... SPI1_Write(buffer)
Example
416
Libraries
SPI_Set_Active
Prototype Returns
void SPI_Set_Active(char (*read_ptr)(char))
Nothing. Sets the active SPI module which will be used by the SPI routines.
Description Parameters :
read_ptr: SPI1_Read handler
Routine is available only for MCUs with two SPI modules. Requires Used SPI module must be initialized before using this function. See the SPI1_Init, SPI1_Init_Advanced
SPI_Set_Active(SPI2_Read) ' Sets the SPI2 module active
Example
Library Example
The code demonstrates how to use SPI library functions for communication between SPI module of the MCU and Microchip's MCP4921 12-bit D/A converter
program SPI ' DAC module connections dim Chip_Select as sbit at RC1_bit Chip_Select_Direction as sbit at TRISC1_bit ' End DAC module connections dim value as word sub procedure InitMain() TRISA0_bit = 1 TRISA1_bit = 1 Chip_Select = 1 Chip_Select_Direction = 0 SPI1_Init() end sub
Set RA0 pin as input Set RA1 pin as input Deselect DAC Set CS# pin as Output Initialize SPI1 module
' DAC increments (0..4095) --> output voltage (0..Vref) sub procedure DAC_Output(dim valueDAC as word) dim temp as byte Chip_Select = 0 ' Select DAC chip ' Send High Byte temp = word(valueDAC >> 8) and 0x0F ' Store valueDAC[11..8] to temp[3..0] temp = temp or 0x30 ' Define DAC setting, see MCP4921 datasheet
417
CHAPTER 7
Libraries
SPI1_Write(temp) ' Send Low Byte temp = valueDAC SPI1_Write(temp) Chip_Select = 1 end sub main: ANSEL = 0 ANSELH = 0 InitMain() value = 2048
' Store valueDAC[7..0] to temp[7..0] ' Send low byte via SPI ' Deselect DAC chip
' Perform main initialization ' When program starts, DAC gives ' the output in the mid-range while TRUE ' Endless loop if ((RA0_bit) and (value < 4095)) then ' If RA0 button is pressed Inc(value) ' increment value else if ((RA1_bit) and (value > 0)) then ' If RA1 button is pressed Dec(value) ' decrement value end if end if ' Send value to DAC chip ' Slow down key repeat pace
HW Connection
SPI HW connection
418
Libraries
419
CHAPTER 7
Libraries
mikroBasic PRO for PIC Note: The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines. Refer to SPI Library. For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the SPI_Set_Active() routine.
Description:
ENC28J60 chip select pin. ENC28J60 reset pin. Direction of the ENC28J60 chip select pin.
Example :
dim SPI_Ethernet_CS as sbit at RC1_bit dim SPI_Ethernet_RST as sbit at RC0_bit dim SPI_Ethernet_CS_Direc tion as sbit at TRISC1_bit dim SPI_Ethernet_RST_Dire ction as sbit at TRISC0_bit
dim Direction of the SPI_Ethernet_RST_Direct ENC28J60 reset pin. ion as sbit sfr external
The following routines must be defined in all project using SPI Ethernet Library:
Description:
Example :
sub function SPI_Ethernet_UserTCP Refer to the (dim remoteHost as ^byte, library example at TCP request handler. the bottom of this dim remotePort as word, dim localPort as word, page for code dim reqLength as word) as implementation. word sub function SPI_Ethernet_UserUDP(dim Refer to the remoteHost as ^byte, library example at UDP request handler. the bottom of this dim remotePort as word, dim destPort as word, page for code dim reqLength as word) as implementation. word
420
Libraries
Library Routines
SPI_Ethernet_Init SPI_Ethernet_Enable SPI_Ethernet_Disable SPI_Ethernet_doPacket SPI_Ethernet_putByte SPI_Ethernet_putBytes SPI_Ethernet_putString SPI_Ethernet_putConstString SPI_Ethernet_putConstBytes SPI_Ethernet_getByte SPI_Ethernet_getBytes SPI_Ethernet_UserTCP SPI_Ethernet_UserUDP
SPI_Ethernet_Init
Prototype Returns
sub procedure SPI_Ethernet_Init(dim mac as ^byte, dim ip as ^byte, dim fullDuplex as byte)
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.
421
CHAPTER 7
Libraries
mikroBasic PRO for PIC half duplex loopback disabled. LED configuration: default (LEDA-link status, LEDB-link activity). Parameters:
Description
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).
Global variables :
SPI_Ethernet_CS: Chip Select line SPI_Ethernet_CS_Direction: Direction of the Chip Select pin SPI_Ethernet_RST: Reset line SPI_Ethernet_RST_Direction: Direction of the Reset pin
Requires
must be defined before using this function. The SPI module needs to be initialized. See the SPI1_Init and SPI1_Init_Advanced routines. ' mE ehternet NIC pinout
dim SPI_Ethernet_RST as sbit at RC0_bit dim SPI_Ethernet_CS as sbit at RC1_bit dim SPI_Ethernet_RST_Direction as sbit at TRISC0_bit dim SPI_Ethernet_CS_Direction as sbit at TRISC1_bit ' end mE ehternet NIC pinout const SPI_Ethernet_HALFDUPLEX = 0 const SPI_Ethernet_FULLDUPLEX = 1 myMacAddr as myIpAddr as ... myMacAddr[0] myMacAddr[1] myMacAddr[2] myMacAddr[3] myMacAddr[4] myMacAddr[5] myIpAddr[0] myIpAddr[1] myIpAddr[2] myIpAddr[3] byte[6] ' my MAC address byte[4] ' my IP addr = = = = = = = = = = 0x00 0x14 0xA5 0x76 0x19 0x3F 192 168 20 60
Example
422
Libraries
SPI_Ethernet_Enable
Prototype Returns
sub procedure SPI_Ethernet_Enable(dim enFlt as byte)
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
will be enabled.
0x04 not used 0x08 not used 0x10 not used 0x20
CRC check flag. When set, packets _SPI_Ethernet_CRC with invalid CRC field will be discarded.
none
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.
423
CHAPTER 7
Libraries
Note: This routine will change receive filter configuration on-the-fly. It will not, in any way, mess with enabling/disabling receive/transmit logic or any other part of Description the ENC28J60 module. The ENC28J60 module should be properly cofigured by the means of SPI_Ethernet_Init routine. Requires Example Ethernet module has to be initialized. See SPI_Ethernet_Init.
SPI_Ethernet_Enable(_SPI_Ethernet_CRC or _SPI_Ethernet_UNICAST) ' enable CRC checking and Unicast traffic
SPI_Ethernet_Disable
Prototype Returns
sub procedure SPI_Ethernet_Disable(dim disFlt as byte)
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
0 0x01 0x02
Description MAC Broadcast traffic/receive filter flag. When set, MAC broadcast traffic will be disabled.
Description
1 2 3 4 5 6 7
MAC Multicast traffic/receive filter flag. When _SPI_Ethernet_MU LTICAST set, MAC multicast traffic will be disabled.
none none none _SPI_Ethernet_CR C none _SPI_Ethernet_UN ICAST
MAC Unicast traffic/receive filter flag. When set, MAC unicast traffic will be disabled.
424
CHAPTER 7 mikroBasic PRO for PIC 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 Example Ethernet module has to be initialized. See SPI_Ethernet_Init.
SPI_Ethernet_Disable(_SPI_Ethernet_CRC or _SPI_Ethernet_UNICAST) ' disable CRC checking and Unicast traffic
Libraries
SPI_Ethernet_doPacket
Prototype
sub function SPI_Ethernet_doPacket() as byte 0 - upon successful packet processing (zero packets received or received
Returns
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. Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
while TRUE ... SPI_Ethernet_doPacket() ' process received packets ... wend
Example
425
CHAPTER 7
Libraries
SPI_Ethernet_putByte
Prototype Returns
sub procedure SPI_Ethernet_putByte(dim v as byte)
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 Example
SPI_Ethernet_putBytes
Prototype Returns
sub procedure SPI_Ethernet_putBytes(dim ptr as ^byte, dim n as byte)
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
Example
426
Libraries
SPI_Ethernet_putConstBytes
Prototype Returns
sub procedure SPI_Ethernet_putConstBytes(const ptr as ^byte, dim n as byte)
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
Example
SPI_Ethernet_putString
Prototype Returns
sub function SPI_Ethernet_putString(dim ptr as ^byte) as word
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.
Requires
Example
427
CHAPTER 7
Libraries
SPI_Ethernet_putConstString
Prototype 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
Example
SPI_Ethernet_getByte
Prototype Returns Description Requires Example
sub function SPI_Ethernet_getByte() as byte
Byte read from ENC28J60 RAM. This is MAC module routine. It fetches a byte from address pointed to by current ENC28J60 read pointer (ERDPT). Ethernet module has to be initialized. See Spi_Ethernet_Init.
dim buffer as byte<> ... buffer = SPI_Ethernet_getByte() ' read a byte from ENC28J60 buffer
428
Libraries
SPI_Ethernet_getBytes
Prototype Returns
sub procedure SPI_Ethernet_getBytes(dim ptr as ^byte, dim addr as word, dim n as byte)
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.
Requires
Example
429
CHAPTER 7
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.
Returns
Length of TCP/HTTP reply data field - otherwise. This is TCP module routine. It is internally called by the library. The user accesses to the TCP/HTTP request by using some of the SPI_Ethernet_get routines. 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 Example Ethernet module has to be initialized. See SPI_Ethernet_Init. This function is internally called by the library and should not be called by the user's code.
430
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 Example Ethernet module has to be initialized. See SPI_Ethernet_Init. 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 PIC 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 path names / 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. Main program code:
431
CHAPTER 7
Libraries
program enc_ethernet ' *********************************** ' * RAM variables ' * dim myMacAddr as byte[6] ' my MAC address myIpAddr as byte[4] ' my IP address ' mE ehternet NIC pinout SPI_Ethernet_Rst as sbit at RC0_bit SPI_Ethernet_CS as sbit at RC1_bit SPI_Ethernet_Rst_Direction as sbit at TRISC0_bit SPI_Ethernet_CS_Direction as sbit at TRISC1_bit ' end ethernet NIC definitions
' ************************************************************ ' * ROM constant strings ' * const httpHeader as string[31] = "HTTP/1.1 200 OK"+chr(10)+"Contenttype: " ' HTTP header const httpMimeTypeHTML as string[13] = "text/html"+chr(10)+chr(10) ' HTML MIME type const httpMimeTypeScript as string[14] = "text/plain"+chr(10)+chr(10) ' TEXT MIME type const httpMethod as string[5] = "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 indexPage as string[763] = "<meta http-equiv=" + Chr(34) + "refresh" + Chr(34) + " content=" + Chr(34) + "3;url=http://192.168.20.60" + Chr(34) + ">" + "<HTML><HEAD></HEAD><BODY>"+ "<h1>PIC + ENC28J60 Mini Web Server</h1>"+ "<a href=/>Reload</a>"+ "<script src=/https/www.scribd.com/s></script>"+ "<table><tr><td valign=top><table border=1 style="+chr(34)+"font-size:20px ;font-family: terminal ;"+chr(34)+"> "+ "<tr><th colspan=2>ADC</th></tr>"+ "<script>"+ "var str,i;"+ "str="+chr(34)+chr(34)+"; "+
432
Libraries
"for(i=0;i<8;i++)"+ "{str+="+chr(34)+"<tr><td bgcolor=pink>BUTTON#"+chr(34) +"+i+"+chr(34)+"</td>"+chr(34)+"; "+ "if(PORTB&(1<<i)){str+="+chr(34)+"<td bgcolor=red>ON"+ chr(34)+";}" "else {str+="+chr(34)+"<td bgcolor=#cccccc>OFF"+chr(34) +";}"+ "str+="+chr(34)+"</td></tr>"+chr(34)+";}"+ "document.write(str) ;"+ "</script>" const indexPage2 as string[470] = "</table></td><td>"+ "<table border=1 style="+chr(34)+"font-size:20px ;fontfamily: terminal ;"+chr(34)+"> "+ "<tr><th colspan=3>PORTD</th></tr>"+ "<script>"+ "var str,i;"+ "str="+chr(34)+chr(34)+"; "+ "for(i=0;i<8;i++)"+ "{str+="+chr(34)+"<tr><td bgcolor=yellow>LED #"+chr(34)+"+i+"+chr(34)+"</td>"+chr(34)+"; "+ "if(PORTD&(1<<i)){str+="+chr(34)+"<td bgcolor= red>ON"+chr(34)+";}"+ "else {str+="+chr(34)+"<td bgcolor=#cccccc> OFF"+ chr(34)+";}"+ "str+="+chr(34)+"</td><td><a href=/https/www.scribd.com/t"+chr(34)+"+i+ "+chr(34)+">Toggle</a></td></tr>"+chr(34)+";}"+ "document.write(str) ;"+ "</script>"+ "</table></td></tr></table>"+ "This is HTTP request #<script>document.write(REQ) </script></BODY></HTML>" dim getRequest dyna httpCounter tmp as as as as byte[15] byte[30] word string[11] ' HTTP request buffer ' buffer for dynamic response ' counter of HTTP requests
' ******************************************* ' * user defined sub functions ' * ' * ' * this sub 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()
433
CHAPTER 7
Libraries
sub function Spi_Ethernet_UserTCP(dim byref remoteHost as byte[4], dim remotePort, localPort, reqLength as word) as word dim i as word ' general purpose integer bitMask as byte ' for bit mask result = 0 if(localPort <> 80) then ' I listen only to web request on port 80 result = 0 exit end if ' get 10 first bytes only of the request, the rest does not matter here for i = 0 to 10 getRequest[i] = Spi_Ethernet_getByte() next i getRequest[i] = 0 ' copy httpMethod to ram for use in memcmp routine for i = 0 to 4 tmp[i] = httpMethod[i] next i if(memcmp(@getRequest, @tmp, 5) <> 0) then supported here result = 0 exit end if Inc(httpCounter) ' only GET method is
if(getRequest[5] = "s") then ' 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
434
Libraries
result = SPI_Ethernet_putConstString(@httpHeader) ' HTTP header result=result + SPI_Ethernet_putConstString(@httpMimeType Script) ' with text MIME type ' add AN2 value to reply WordToStr(ADC_Read(2), dyna) tmp = "var AN2=" result = result + SPI_Ethernet_putString(@tmp) result = result + SPI_Ethernet_putString(@dyna) tmp = ";" result = result + SPI_Ethernet_putString(@tmp) ' add AN3 value to reply WordToStr(ADC_Read(3), dyna) tmp = "var AN3=" result = result + SPI_Ethernet_putString(@tmp) result = result + SPI_Ethernet_putString(@dyna) tmp = ";" result = result + SPI_Ethernet_putString(@tmp) ' add PORTB value (buttons) to reply tmp = "var PORTB= " result = result + SPI_Ethernet_putString(@tmp) WordToStr(PORTB, dyna) result = result + SPI_Ethernet_putString(@dyna) tmp = ";" result = result + SPI_Ethernet_putString(@tmp) ' add PORTD value (LEDs) to reply tmp = "var PORTD= " result = result + SPI_Ethernet_putString(@tmp) WordToStr(PORTD, dyna) result = result + SPI_Ethernet_putString(@dyna) tmp = ";" result = result + SPI_Ethernet_putString(@tmp) ' add HTTP requests counter to reply WordToStr(httpCounter, dyna) tmp = "var REQ= " result = result + SPI_Ethernet_putString(@tmp) result = result + SPI_Ethernet_putString(@dyna) tmp = ";" result = result + SPI_Ethernet_putString(@tmp) else if(getRequest[5] = "t") then ' if request path name starts with t, toggle PORTD (LED) bit number that comes after bitMask = 0 if(isdigit(getRequest[6]) <> 0) then ' if 0 <= bit number <=
435
CHAPTER 7
Libraries
436
Libraries
' second
437
CHAPTER 7
Libraries
PORTB TRISB = 0 = 0xff
PORTD = 0 TRISD = 0 httpCounter = 0 ' set mac address myMacAddr[0] = 0x00 myMacAddr[1] = 0x14 myMacAddr[2] = 0xA5 myMacAddr[3] = 0x76 myMacAddr[4] = 0x19 myMacAddr[5] = 0x3F ' set IP address myIpAddr[0] = 192 myIpAddr[1] = 168 myIpAddr[2] = 20 myIpAddr[3] = 60 ' ' ' ' ' ' ' * * * * * * *
starts ENC28J60 with : reset bit on PORTC.B0 CS bit on PORTC.B1 my MAC & IP address full duplex
SPI1_Init() ' init spi module SPI_Ethernet_Init(myMacAddr, myIpAddr, _SPI_Ethernet_FULLDUPLEX) ' init ethernet module SPI_Ethernet_setUserHandlers(@SPI_Ethernet_UserTCP, @SPI_Ethernet_UserUDP) ' set user handlers while TRUE SPI_Ethernet_doPacket() ' ' ' ' ' wend end. ' endless loop ' 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 *
438
Libraries
HW Connection
439
CHAPTER 7
The mikroBasic PRO for PIC 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. For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the SPI_Set_Active() routine. 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.
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
440
Libraries
SPI_Glcd_Init
Prototype Returns
sub procedure SPI_Glcd_Init(dim DeviceAddress as byte)
Description
Parameters :
DeviceAddress: SPI expander hardware address, see schematic at
Requires
must be defined before using this function. SPI module needs to be initialized. See SPI1_Init and SPI1_Init_Advanced routines.
' port expander pinout definition dim SPExpanderRST as sbit at RC0_bit SPExpanderCS as sbit at RC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit ' end of port expander pinout definition ... ' If Port Expander Library uses SPI1 module : SPI1_Init() ' Initialize SPI module used with PortExpander SPI_Glcd_Init(0)
Example
441
CHAPTER 7
Libraries
SPI_Glcd_Set_Side
Prototype 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 Example 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:
SPI_Glcd_Set_Side(0); SPI_Glcd_Set_Side(10);
SPI_Glcd_Set_Page
Prototype Returns
procedure Spi_Glcd_Set_Page(page : byte);
Description
Note: For side, x axis and page layout explanation see schematic at the bottom of this page. Requires Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
SPI_Glcd_Set_Page(5)
442
Libraries
SPI_Glcd_Set_X
Prototype Returns
sub procedure SPI_Glcd_Set_X(dim x_pos as byte)
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 Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
SPI_Glcd_Set_X(25)
SPI_Glcd_Read_Data
Prototype Returns Description
sub function SPI_Glcd_Read_Data() as byte
One byte from Glcd memory. 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
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()
Example
443
CHAPTER 7
Libraries
SPI_Glcd_Write_Data
Prototype 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 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)
Example
SPI_Glcd_Fill
Prototype Returns
sub procedure SPI_Glcd_Fill(dim pattern as byte)
Description
To clear the Glcd screen, use SPI_Glcd_Fill(0). To fill the screen completely, use SPI_Glcd_Fill(0xFF). Requires Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
' Clear screen SPI_Glcd_Fill(0)
444
Libraries
SPI_Glcd_Dot
Prototype Returns
sub procedure SPI_Glcd_Dot(dim x_pos as byte, dim y_pos as byte, dim color as byte)
Description
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. Requires Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
Invert the dot in the upper left corner SPI_Glcd_Dot(0, 0, 2)
SPI_Glcd_Line
Prototype Returns
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)
Description
Parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
' Draw a line between dots (0,0) and (20,30) SPI_Glcd_Line(0, 0, 20, 30, 1)
445
CHAPTER 7
Libraries
SPI_Glcd_V_Line
Prototype Returns
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)
Description
Parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Requires Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
' Draw a vertical line between dots (10,5) and (10,25) SPI_Glcd_V_Line(5, 25, 10, 1)
SPI_Glcd_H_Line
Prototype Returns
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)
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. Requires Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
Draw a horizontal line between dots (10,20) and (50,20) SPI_Glcd_H_Line(10, 50, 20, 1)
446
Libraries
SPI_Glcd_Rectangle
Prototype Returns
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)
0..127
y_upper_left: y coordinate of the upper left rectangle corner. Valid values:
Description
0..63
x_bottom_right: x coordinate of the lower right rectangle corner. Valid val
ues: 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 Example Glcd needs to be initialized for SPI communication, see S_Glcd_Init routines.
' Draw a rectangle between dots (5,5) and (40,40) SPI_Glcd_Rectangle(5, 5, 40, 40, 1)
447
CHAPTER 7
Libraries
SPI_Glcd_Box
Prototype Returns
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)
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 Example
SPI_Glcd_Circle
Prototype Returns
sub procedure SPI_Glcd_Circle(dim x_center as integer, dim y_center as integer, dim radius as integer, dim color as byte)
Description
The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot. Requires Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
' Draw a circle with center in (50,50) and radius=10 SPI_Glcd_Circle(50, 50, 10, 1)
448
Libraries
SPI_Glcd_Set_Font
Prototype Returns
sub procedure SPI_Glcd_Set_Font(dim activeFont as longint, dim aFontWidth as byte, dim aFontHeight as byte, dim aFontOffs as word)
Nothing. Sets font that will be used with SPI_Glcd_Write_Char and SPI_Glcd_Write_Text routines. Parameters :
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
Description
PRO for PIC character set and regular ASCII set (eg. if 'A' is 65 in ASCII character, and 'A' is 45 in the mikroBasic PRO for PIC 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.mbas file located in the Uses folder or create his own fonts. Requires Example Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routines.
' Use the custom 5x7 font "myfont" which starts with space (32): SPI_Glcd_Set_Font(@myfont, 5, 7, 32)
449
CHAPTER 7
Libraries
SPI_Glcd_Write_Char
Prototype Returns
sub procedure SPI_Glcd_Write_Char(dim chr1 as byte, dim x_pos as byte, dim page_num as byte, dim color as byte)
tWidth) Description
page_num: the number of the page on which character will be written. Valid
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 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)
Example
450
Libraries
SPI_Glcd_Write_Text
Prototype Returns
sub procedure SPI_Glcd_Write_Text(dim byref text as string[40], dim x_pos as byte, dim page_numb as byte, dim color as byte)
Description
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 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)
Example
451
CHAPTER 7
Libraries
SPI_Glcd_Image
Prototype Returns
Description
and RAM memory (due to the mikroBasic PRO for PIC pointer to const and pointer to RAM equivalency). Use the mikroBasic PROs integrated Glcd Bitmap Editor (menu option Tools Glcd Bitmap Editor) to convert image to a constant array suitable for displaying on Glcd.
Requires Example
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 RC0_bit SPExpanderCS as sbit at RC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit ' End Port Expander module connections dim someText as char[20] counter as byte sub procedure Delay2S delay_ms(2000) end sub main: SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV4,_SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH) ' Initialize SPI module
452
Libraries
' Initialize Glcd via SPI ' Clear Glcd
SPI_Glcd_Box(62,40,124,56,1) ' Draw box SPI_Glcd_Rectangle(5,5,84,35,1) ' Draw rectangle SPI_Glcd_Line(0, 63, 127, 0,1) ' Draw line Delay2s() counter = 5 while (counter < 60) ' Draw horizontal and vertical line Delay_ms(250) SPI_Glcd_V_Line(2, 54, counter, 1) SPI_Glcd_H_Line(2, 120, counter, 1) counter = counter + 5 wend Delay2s() SPI_Glcd_Fill(0x00) SPI_Glcd_Set_Font(@Character8x7, 8, 8, 32) SPI_Glcd_Write_Text("mikroE", 5, 7, 2) for counter = 1 to 10 ' Draw circles SPI_Glcd_Circle(63,32, 3*counter, 1) next counter Delay2s() SPI_Glcd_Box(12,20, 70,63, 2) Delay2s() SPI_Glcd_Fill(0xFF) SPI_Glcd_Set_Font(@Character8x7, 8, 7, 32) someText = "8x7 Font" SPI_Glcd_Write_Text(someText, 5, 1, 2) Delay2s() SPI_Glcd_Set_Font(@System3x6, 3, 5, 32) someText = "3X5 CAPITALS ONLY" SPI_Glcd_Write_Text(someText, 5, 3, 2) Delay2s() SPI_Glcd_Set_Font(@font5x7, 5, 7, 32) someText = "5x7 Font" SPI_Glcd_Write_Text(someText, 5, 5, 2) Delay2s() wend end. ' Draw box ' Clear Glcd ' Choose font ' Write string
453
CHAPTER 7
Libraries
HW Connection
454
Libraries
Library Routines
Spi_Lcd_Config Spi_Lcd_Out Spi_Lcd_Out_Cp Spi_Lcd_Chr Spi_Lcd_Chr_Cp Spi_Lcd_Cmd
455
CHAPTER 7
Libraries
SPI_Lcd_Config
Prototype Returns
Description
Parameters :
DeviceAddress: SPI expander hardware address, see schematic at the
Example
SPI_Lcd_Out
Prototype Returns
sub procedure SPI_Lcd_Out(dim row as byte, dim column as byte, dim byref text as string[20])
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
Requires Example
456
Libraries
SPI_Lcd_Out_Cp
Prototype Returns
sub procedure SPI_Lcd_Out_CP(dim text as string[19])
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 Example
SPI_Lcd_Chr
Prototype Returns
sub procedure SPI_Lcd_Chr(dim Row as byte, dim Column as byte, dim Out_Char as byte)
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 Example
457
CHAPTER 7
Libraries
SPI_Lcd_Chr_Cp
Prototype 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 Example
SPI_Lcd_Cmd
Prototype Returns
sub procedure SPI_Lcd_Cmd(dim out_char as byte)
Description
Note: Predefined constants can be passed to the function, see Available SPI Lcd Commands. Requires Example Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routines.
' Clear Lcd display: SPI_Lcd_Cmd(_LCD_CLEAR)
458
Libraries
Purpose Move cursor to the 1st row Move cursor to the 2nd row Move cursor to the 3rd row Move cursor to the 4th row Clear display Return cursor to home position, returns a shifted display to its original position. Display data RAM is unaffected. Turn off cursor Underline cursor on Blink cursor on Move cursor left without changing display data RAM
_LCD_MOVE_CURSOR_RIGHT Move cursor right without changing display data RAM _LCD_TURN_ON _LCD_TURN_OFF _LCD_SHIFT_LEFT _LCD_SHIFT_RIGHT
Turn Lcd display on Turn Lcd display off Shift display left without changing display data RAM Shift display right without changing display data RAM
459
CHAPTER 7
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 RC0_bit SPExpanderCS as sbit at RC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit ' End Port Expander module connections main: text = "mikroElektronika" SPI1_Init() PortExpander SPI_Lcd_Config(0) face SPI_Lcd_Cmd(_LCD_CLEAR) SPI_Lcd_Cmd(_LCD_CURSOR_OFF) SPI_Lcd_Out(1,6, "mikroE") 6th column SPI_Lcd_Chr_CP("!") SPI_Lcd_Out(2,1, text) column end.
' Initialize SPI module used with ' Initialize Lcd over SPI inter' Clear display ' Turn cursor off ' Print text to Lcd, 1st row, ' Append "!" ' Print text to Lcd, 2nd row, 1st
460
Libraries
HW Connection
461
CHAPTER 7
The mikroBasic PRO for PIC 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. For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the SPI_Set_Active() routine. 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.
Library Routines
SPI_Lcd8_Config SPI_Lcd8_Out SPI_Lcd8_Out_Cp SPI_Lcd8_Chr SPI_Lcd8_Chr_Cp SPI_Lcd8_Cmd
462
Libraries
SPI_Lcd8_Config
Prototype Returns
sub procedure SPI_Lcd8_Config(dim DeviceAddress as byte)
Description
DeviceAddress: spi expander hardware address, see schematic at the bot
Requires
must be defined before using this function. SPI module needs to be initialized. See SPI1_Init and SPI1_Init_Advanced routines.
' port expander pinout definition dim SPExpanderRST as sbit at RC0_bit SPExpanderCS as sbit at RC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit ' end of port expander pinout definition ... SPI1_Init() ' Initialize SPI interface SPI_Lcd8_Config(0) ' Intialize Lcd in 8bit mode via spi
Example
SPI_Lcd8_Out
Prototype Returns
sub procedure SPI_Lcd8_Out(dim row as byte, dim column as byte, dim byref text as string[19])
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 Example
463
CHAPTER 7
Libraries
SPI_Lcd8_Out_Cp
Prototype 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 Example
SPI_Lcd8_Chr
Prototype Returns
sub procedure SPI_Lcd8_Chr(dim Row as byte, dim Column as byte, dim Out_Char as byte)
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 Example
464
Libraries
SPI_Lcd8_Chr_Cp
Prototype Returns
sub procedure SPI_Lcd8_Chr_CP(dim Out_Char as byte)
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
SPI_Lcd8_Cmd
Prototype Returns
sub procedure SPI_Lcd8_Cmd(dim out_char as byte)
Description
Note: Predefined constants can be passed to the function, see Available SPI Lcd8 Commands. Requires Example Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routines.
' Clear Lcd display: SPI_Lcd8_Cmd(_LCD_CLEAR)
465
CHAPTER 7
Libraries
Available LCD Commands
Lcd Command
_LCD_FIRST_ROW _LCD_SECOND_ROW _LCD_THIRD_ROW _LCD_FOURTH_ROW _LCD_CLEAR _LCD_RETURN_HOME _LCD_CURSOR_OFF _LCD_UNDERLINE_ON _LCD_BLINK_CURSOR_ON _LCD_MOVE_CURSOR_LEFT
Purpose Move cursor to the 1st row Move cursor to the 2nd row Move cursor to the 3rd row Move cursor to the 4th row Clear display Return cursor to home position, returns a shifted display to its original position. Display data RAM is unaffected. Turn off cursor Underline cursor on Blink cursor on Move cursor left without changing display data RAM
_LCD_MOVE_CURSOR_RIGHT Move cursor right without changing display data RAM _LCD_TURN_ON _LCD_TURN_OFF _LCD_SHIFT_LEFT _LCD_SHIFT_RIGHT
Turn Lcd display on Turn Lcd display off Shift display left without changing display data RAM Shift display right without changing display data RAM
466
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_Test dim text as char[16] ' Port Expander module connections dim SPExpanderRST as sbit at RC0_bit SPExpanderCS as sbit at RC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit ' End Port Expander module connections main: text = "mikroE" SPI1_Init() ' Initialize SPI module with PortExpander SPI_Lcd8_Config(0) ' Intialize Lcd in 8bit via SPI SPI_Lcd8_Cmd(_LCD_CLEAR) ' Clear display SPI_Lcd8_Cmd(_LCD_CURSOR_OFF) ' Turn cursor off SPI_Lcd8_Out(1,6, text) ' Print text to Lcd, 1st 6th column... SPI_Lcd8_Chr_CP("!") ' Append "!" SPI_Lcd8_Out(2,1, "mikroElektronika") ' Print text to Lcd, 2nd 1st column... SPI_Lcd8_Out(3,1, text) ' For Lcd modules with than two rows SPI_Lcd8_Out(4,15, text) ' For Lcd modules with than two rows end.
used mode
row,
467
CHAPTER 7
Libraries
HW Connection
468
Libraries
469
CHAPTER 7
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 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
470
Libraries
SPI_T6963C_Config
Prototype Returns
sub procedure SPI_T6963C_Config(dim width as word, dim height as word, dim fntW as word, dim DeviceAddress as byte, dim wr as byte, dim rd as byte, dim cd as byte, dim rst as byte)
Description
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 + + + +--------------------+ TEXT PANEL #0 + +--------------------+ GRAPHICS PANEL #1 + + + +--------------------+ TEXT PANEL #2 + +--------------------+ + + + + + + + + + + + + + + + + /\ | | | | | PANEL 0 | \/ /\ | | | | | PANEL 1 | | \/
471
CHAPTER 7
Libraries
Requires SPI module needs to be initialized. See SPI1_Init and SPI1_Init_Advanced routines.
' port expander pinout definition dim SPExpanderRST as sbit at RC0_bit SPExpanderCS as sbit at RC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit ' end of port expander pinout definition ... ' Initialize SPI module SPI1_Init() SPI_T6963C_Config(240, 64, 8, 0, 0, 1, 3, 4)
Example
SPI_T6963C_WriteData
Prototype Returns
sub procedure SPI_T6963C_WriteData(dim Ddata as byte)
Description Parameters :
Ddata: data to be written
Requires Example
SPI_T6963C_WriteCommand
Prototype Returns
sub procedure SPI_T6963C_WriteCommand(dim Ddata as byte)
Description Parameters :
Ddata: command to be written
Requires Example
472
Libraries
SPI_T6963C_SetPtr
Prototype Returns
sub procedure SPI_T6963C_SetPtr(dim p as word, dim c as byte)
Description
Parameters :
p: address where command should be written c: command to be written
Requires Example
SPI_T6963C_WaitReady
Prototype Returns
sub procedure SPI_T6963C_WaitReady()
Nothing.
Description Pools the status byte, and loops until Toshiba Glcd module is ready. Requires Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_WaitReady()
SPI_T6963C_Fill
Prototype Returns
sub procedure SPI_T6963C_Fill(dim v as byte, dim start as word, dim len as word)
Description
v: byte to be written start: starting address of the memory block len: length of the memory block in bytes
Requires Example
473
CHAPTER 7
Libraries
SPI_T6963C_Dot
Prototype 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: SPI_T6963C_BLACK and
SPI_T6963C_WHITE Requires Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_Dot(x0, y0, pcolor)
474
Libraries
SPI_T6963C_Write_Char
Prototype Returns
sub procedure SPI_T6963C_Write_Char(dim c as byte, dim x as byte, dim y as byte, dim mode as byte)
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 Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_Write_Char("A",22,23,AND)
475
CHAPTER 7
Libraries
SPI_T6963C_Write_Text
Prototype Returns
sub procedure SPI_T6963C_Write_Text(dim byref str as byte[10], dim x as byte, dim y as byte, dim mode as byte)
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,
Requires Example
476
Libraries
SPI_T6963C_Line
Prototype Returns
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)
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 Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_Line(0, 0, 239, 127, T6963C_WHITE)
SPI_T6963C_Rectangle
Prototype Returns
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)
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 Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_Rectangle(20, 20, 219, 107, T6963C_WHITE)
477
CHAPTER 7
Libraries
SPI_T6963C_Box
Prototype Returns
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)
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 Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_Box(0, 119, 239, 127, T6963C_WHITE)
SPI_T6963C_Circle
Prototype Returns
sub procedure SPI_T6963C_Circle(dim x as integer, dim y as integer, dim r as longint, dim pcolor as byte)
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 Requires Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_Circle(120, 64, 110, T6963C_WHITE)
478
Libraries
SPI_T6963C_Image
Prototype Returns
sub procedure SPI_T6963C_image(const pic as ^byte)
Description
Use the mikroBasic PROs integrated Glcd Bitmap Editor (menu option Tools Glcd Bitmap Editor) to convert image to a constant array suitable for displaying on Glcd. Note: Image dimension must match the display dimension. Requires Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_Image(my_image)
SPI_T6963C_Sprite
Prototype Returns
sub procedure SPI_T6963C_sprite(dim px, py as byte, const pic as ^byte, dim sx, sy as byte)
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 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
Description
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 Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
SPI_T6963C_Sprite(76, 4, einstein, 88, 119) ' draw a sprite
479
CHAPTER 7
Libraries
SPI_T6963C_Set_Cursor
Prototype Returns
Description
Parameters :
x: cursor position row number y: cursor position column number
Requires Example
SPI_T6963C_ClearBit
Prototype Returns
sub procedure SPI_T6963C_clearBit(dim b as byte)
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 Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
' clear bits 0 and 1 on control port SPI_T6963C_ClearBit(0x03)
SPI_T6963C_SetBit
Prototype Returns
sub procedure SPI_T6963C_setBit(dim b as byte)
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 Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
' set bits 0 and 1 on control port SPI_T6963C_SetBit(0x03)
480
Libraries
SPI_T6963C_NegBit
Prototype Returns
sub procedure SPI_T6963C_negBit(dim b as byte)
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 Example Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
' negate bits 0 and 1 on control port SPI_T6963C_NegBit(0x03)
SPI_T6963C_DisplayGrPanel
Prototype Returns
sub procedure SPI_T6963C_DisplayGrPanel(dim n as byte)
Description Parameters :
n: graphic panel number. Valid values: 0 and 1.
Requires Example
SPI_T6963C_DisplayTxtPanel
Prototype Returns
sub procedure SPI_T6963C_DisplayTxtPanel(dim n as byte)
Description Parameters :
n: text panel number. Valid values: 0 and 1.
Requires Example
481
CHAPTER 7
Libraries
SPI_T6963C_SetGrPanel
Prototype 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 Example
SPI_T6963C_SetTxtPanel
Prototype Returns
sub procedure SPI_T6963C_SetTxtPanel(dim n as byte)
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 Example
482
Libraries
SPI_T6963C_PanelFill
Prototype Returns
sub procedure SPI_T6963C_PanelFill(dim v as byte)
Nothing. Fill current panel in full (graphic+text) with appropriate value (0 to clear).
Description Parameters :
v: value to fill panel with.
Requires Example
SPI_T6963C_GrFill
Prototype Returns
sub procedure SPI_T6963C_GrFill(dim v as byte)
Description Parameters :
v: value to fill graphic panel with.
Requires Example
SPI_T6963C_TxtFill
Prototype Returns
sub procedure SPI_T6963C_TxtFill(dim v as byte)
Description Parameters :
v: this value increased by 32 will be used to fill text panel.
Requires Example
483
CHAPTER 7
Libraries
SPI_T6963C_Cursor_Height
Prototype Returns
Description Parameters :
n: cursor height. Valid values: 0..7.
Requires Example
SPI_T6963C_Graphics
Prototype Returns
sub procedure SPI_T6963C_Graphics(dim n as byte)
Description
Parameters :
n: graphic enable/disable parameter. Valid values: 0 (disable graphic dispaying) and 1 (enable graphic displaying).
Requires Example
SPI_T6963C_Text
Prototype Returns
sub procedure SPI_T6963C_Text(dim n as byte)
Description
Parameters :
n: text enable/disable parameter. Valid values: 0 (disable text dispaying) and 1 (enable text displaying).
Requires Example
484
Libraries
SPI_T6963C_Cursor
Prototype Returns
sub procedure SPI_T6963C_Cursor(dim n as byte)
Description Parameters :
n: on/off parameter.Valid values: 0 (set cursor off) and 1 (set cursor on).
Requires Example
SPI_T6963C_Cursor_Blink
Prototype Returns
sub procedure SPI_T6963C_Cursor_Blink(dim n as byte)
Description
Parameters :
n: cursor blinking enable/disable parameter. Valid values: 0 (disable cursor blinking) and 1 (enable cursor blinking).
Requires Example
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, EasyPIC5 board and PIC16F887.
program SPI_T6963C_240x128 include __Lib_SPIT6963C_Const include bitmap include bitmap2 dim ' Port Expander module connections
485
CHAPTER 7
Libraries
SPExpanderRST as sbit at RC0_bit SPExpanderCS as sbit at RC1_bit SPExpanderRST_Direction as sbit at TRISC0_bit SPExpanderCS_Direction as sbit at TRISC1_bit ' End Port Expander module connections 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 txt, txt1 as string[29]
main: txt1 = " EINSTEIN WOULD HAVE LIKED mE" txt = " GLCD LIBRARY DEMO, WELCOME !" ANSEL = ANSELH = C1ON_bit C2ON_bit 0 0 = 0 = 0 = = = = = 1 1 1 1 1 ' Configure AN pins as digital I/O ' Disable comparators
as as as as as
' Initialize SPI module SPI1_Init() ' ' If Port Expander Library uses SPI2 module ' Pass pointer to SPI Read sub function of used SPI module ' Initialize SPI module used with PortExpander ' SPI2_Init_Advanced(_SPI_MASTER, _SPI_FCY_DIV32, TRAILING) ' ' ' ' ' ' ' ' ' ' * * * * * * * * * *
_SPI_CLK_HI_
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
486
Libraries
' 8 pixel height ' move cursor to top left ' cursor off
'
' '
* * Draw rectangles * SPI_T6963C_rectangle(0, 0, 239, 127, SPI_T6963C_WHITE) SPI_T6963C_rectangle(20, 20, 219, 107, SPI_T6963C_WHITE) SPI_T6963C_rectangle(40, 40, 199, 87, SPI_T6963C_WHITE) SPI_T6963C_rectangle(60, 60, 179, 67, SPI_T6963C_WHITE)
* * Draw a cross * SPI_T6963C_line(0, 0, 239, 127, SPI_T6963C_WHITE) SPI_T6963C_line(0, 127, 239, 0, SPI_T6963C_WHITE) *
'
487
CHAPTER 7
Libraries
' '
SPI_T6963C_WHITE) SPI_T6963C_WHITE) SPI_T6963C_WHITE) SPI_T6963C_WHITE) SPI_T6963C_WHITE) SPI_T6963C_WHITE) SPI_T6963C_WHITE) ' Draw a sprite
SPI_T6963C_sprite(0, 0, @mikroe, 240, 64) ' 240x128 can"t be stored in most of PIC16 MCUs SPI_T6963C_sprite(0, 64, @mikroe, 240, 64) ' it is replaced with smaller picture 240x64 ' Smaller picture is drawn two times while TRUE ' Endless loop
'* '* If PORTB_0 is pressed, toggle the display between graphic panel 0 and graphic 1 '* if (RB0_bit <> 0) then Inc(panel) panel = panel and 1 SPI_T6963C_displayGrPanel(panel) Delay_ms(300) '* '* If PORTB_2 is pressed, display only text panel '* else if (RB2_bit <> 0) then SPI_T6963C_graphics(0) SPI_T6963C_text(1) Delay_ms(300) '* '* If PORTB_3 is pressed, display text and graphic panels '*
488
Libraries
If PORTB_4 is pressed, change cursor else if(RB4_bit <> 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 'case Delay_ms(300)
end if end if end if end if end if '* '* Move cursor, even if not visible '* Inc(cposx) if (cposx = SPI_T6963C_txtCols) then cposx = 0 Inc(cposy) if (cposy = SPI_T6963C_grHeight / SPI_T6963C_CHARACTER_ HEIGHT) then cposy = 0 end if end if SPI_T6963C_set_cursor(cposx, cposy)
489
CHAPTER 7
Libraries
Delay_ms(100) wend end.
HW Connection
490
Libraries
Description:
Example :
dim T6963C_dataPort as byte at PORTD dim T6963C_ctrlwr as sbit at RC2_bit dim T6963C_ctrlrd as sbit at RC1_bit dim T6963C_ctrlcd as dim T6963C_ctrlrst as sbit at RC4_bit dim T6963C_ctrlwr_ Direction as sbit at TRISC2_bit
Command/Data signal. sbit at RC0_bit Reset signal. Direction of the Write pin.
491
CHAPTER 7
Libraries
The following variables must be defined in all projects using T6963C Graphic LCD library:
dim T6963C_ctrlrd_Direction as sbit sfr external dim T6963C_ctrlcd_Direction as sbit sfr external dim T6963C_ctrlrst_Direction as sbit sfr external
Description:
dim
Example :
Direction of the Read T6963C_ctrlrd_Direction pin. as sbit at TRISC1_bit Direction of the ComT6963C_ctrlcd_Direction mand/Data pin. as sbit at TRISC0_bit
dim dim
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 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
492
Libraries
T6963C_Init
Prototype Returns
sub procedure T6963C_init(dim width, height, fntW as byte)
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: +--------------------+ GRAPHICS PANEL #0 + + + +--------------------+ TEXT PANEL #0 + +--------------------+ GRAPHICS PANEL #1 + + + +--------------------+ TEXT PANEL #1 + +--------------------+ + + + + + + + + + + + + + + + + /\ | | | | | PANEL 0 | \/ /\ | | | | | PANEL 1 | | \/
Description
Global variables :
T6963C_dataPort: Data Port T6963C_ctrlwr: Write signal pin T6963C_ctrlrd: Read signal pin T6963C_ctrlcd: Command/Data signal pin T6963C_ctrlrst: Reset signal pin T6963C_ctrlwr_Direction: Direction of Write signal pin T6963C_ctrlrd_Direction: Direction of Read signal pin T6963C_ctrlcd_Direction: Direction of Command/Data signal pin T6963C_ctrlrst_Direction: Direction of Reset signal pin
Requires
must be defined before using this function. MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
493
CHAPTER 7
Libraries
Example
T6963C_WriteData
Prototype Returns
sub procedure T6963C_WriteData(dim mydata as byte)
Description Parameters :
mydata: data to be written
Requires Example
T6963C_WriteCommand
Prototype Returns
sub procedure T6963C_WriteCommand(dim mydata as byte)
Description Parameters :
mydata: command to be written
Requires Example
494
Libraries
T6963C_SetPtr
Prototype Returns
sub procedure T6963C_SetPtr(dim p as word, dim c as byte)
Description
Parameters :
p: address where command should be written c: command to be written
Requires Example
T6963C_WaitReady
Prototype Returns
sub procedure T6963C_WaitReady()
Nothing.
Description Pools the status byte, and loops until Toshiba Glcd module is ready. Requires Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
T6963C_WaitReady()
T6963C_Fill
Prototype Returns
sub procedure T6963C_Fill(dim v as byte, dim start, len as word)
Description
v: byte to be written start: starting address of the memory block len: length of the memory block in bytes
Requires Example
495
CHAPTER 7
Libraries
T6963C_Dot
Prototype 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 Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
T6963C_Dot(x0, y0, pcolor)
496
Libraries
T6963C_Write_Char
Prototype Returns
sub procedure T6963C_Write_Char(dim c, x, y, mode as byte)
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,
Requires Example
497
CHAPTER 7
Libraries
T6963C_Write_Text
Prototype 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,
Requires Example
498
Libraries
T6963C_Line
Prototype Returns
sub procedure T6963C_Line(dim x0, y0, x1, y1 as integer, dim pcolor as byte)
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 Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
T6963C_Line(0, 0, 239, 127, T6963C_WHITE)
T6963C_Rectangle
Prototype Returns
sub procedure T6963C_Rectangle(dim x0, y0, x1, y1 as integer, dim pcolor as byte)
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: T6963C_BLACK and
T6963C_WHITE Requires Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
T6963C_Rectangle(20, 20, 219, 107, T6963C_WHITE)
499
CHAPTER 7
Libraries
T6963C_Box
Prototype Returns
psub procedure T6963C_Box(dim x0, y0, x1, y1 as integer, dim pcolor as byte)
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 Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
T6963C_Box(0, 119, 239, 127, T6963C_WHITE)
T6963C_Circle
Prototype Returns
sub procedure T6963C_Circle(dim x, y as integer, dim r as longint, dim pcolor as byte)
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 Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
T6963C_Circle(120, 64, 110, T6963C_WHITE)
500
Libraries
T6963C_Image
Prototype Returns
sub procedure T6963C_Image(const pic as ^byte)
Description
Use the mikroBasic PROs integrated Glcd Bitmap Editor (menu option Tools Glcd Bitmap Editor) to convert image to a constant array suitable for displaying on Glcd. Note: Image dimension must match the display dimension. Requires Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
TT6963C_Image(mc)
T6963C_Sprite
Prototype Returns
sub procedure T6963C_Sprite(dim px, py, sx, sy as byte, const pic as ^byte)
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 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
Description
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 Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
T6963C_Sprite(76, 4, einstein, 88, 119) ' draw a sprite
501
CHAPTER 7
Libraries
T6963C_Set_Cursor
Prototype Returns
sub procedure T6963C_Set_Cursor(dim x, y as byte)
Description
Parameters :
x: cursor position row number y: cursor position column number
Requires Example
T6963C_DisplayGrPanel
Prototype Returns
sub procedure T6963C_DisplayGrPanel(dim n as byte)
Description Parameters :
n: graphic panel number. Valid values: 0 and 1.
Requires Example
T6963C_DisplayTxtPanel
Prototype Returns
sub procedure T6963C_DisplayTxtPanel(dim n as byte)
Description Parameters :
n: text panel number. Valid values: 0 and 1.
Requires Example
502
Libraries
T6963C_SetGrPanel
Prototype Returns
sub procedure T6963C_SetGrPanel(dim n as byte)
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 Example
T6963C_SetTxtPanel
Prototype Returns
sub procedure T6963C_SetTxtPanel(dim n as byte)
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 Example
503
CHAPTER 7
Libraries
T6963C_PanelFill
Prototype Returns
sub procedure T6963C_PanelFill(dim v as byte)
Nothing. Fill current panel in full (graphic+text) with appropriate value (0 to clear).
Description Parameters :
v: value to fill panel with.
Requires Example
T6963C_GrFill
Prototype Returns
procedure T6963C_GrFill(v : byte);
Description Parameters :
v: value to fill graphic panel with.
Requires Example
T6963C_TxtFill
Prototype Returns
sub procedure T6963C_TxtFill(dim v as byte)
Description Parameters :
v: this value increased by 32 will be used to fill text panel.
Requires Example
504
Libraries
T6963C_Cursor_Height
Prototype Returns
sub procedure T6963C_Cursor_Height(dim n as byte)
Description Parameters :
n cursor height. Valid values: 0..7.
Requires Example
T6963C_Graphics
Prototype Returns
sub procedure T6963C_Graphics(dim n as byte)
Description
Parameters :
n: on/off parameter. Valid values: 0 (disable graphic dispaying) and 1
(enable graphic displaying). Requires Example Toshiba Glcd module needs to be initialized. See the T6963C_Init routine.
' enable graphic displaying T6963C_Graphics(1)
T6963C_Text
Prototype Returns
sub procedure T6963C_Text(dim n as byte)
Description
Parameters :
n: on/off parameter. Valid values: 0 (disable text dispaying) and 1 (enable text displaying).
Requires Example
505
CHAPTER 7
Libraries
T6963C_Cursor
Prototype Returns
sub procedure T6963C_Cursor(dim n as byte)
Description
Parameters :
n: on/off parameter. Valid values: 0 (set cursor off) and 1 (set cursor on).
Requires Example
T6963C_Cursor_Blink
Prototype Returns
sub procedure T6963C_Cursor_Blink(dim n as byte)
Description
Parameters :
n: on/off parameter. Valid values: 0 (disable cursor blinking) and 1 (enable cursor blinking).
Requires Example
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, EasyPIC5 board and PIC16F887.
506
Libraries
dim T6963C_ctrlwr as sbit at RC2_bit ' WR write signal dim T6963C_ctrlrd as sbit at RC1_bit ' RD read signal dim T6963C_ctrlcd as sbit at RC0_bit ' CD command/data signal dim T6963C_ctrlrst as sbit at RC4_bit ' RST reset signal dim T6963C_ctrlwr_Direction as sbit at TRISC2_bit ' WR write signal direction dim T6963C_ctrlrd_Direction as sbit at TRISC1_bit ' RD read signal direction dim T6963C_ctrlcd_Direction as sbit at TRISC0_bit ' CD command/data signal direction dim T6963C_ctrlrst_Direction as sbit at TRISC4_bit ' RST reset signal direction ' Signals not used by library, they are set in main sub function dim T6963C_ctrlce as sbit at RC3_bit ' CE signal dim T6963C_ctrlfs as sbit at RC6_bit ' FS signal dim T6963C_ctrlmd as sbit at RC5_bit ' MD signal dim T6963C_ctrlce_Direction as sbit at TRISC3_bit ' CE signal direction dim T6963C_ctrlfs_Direction as sbit at TRISC6_bit ' FS signal direction dim T6963C_ctrlmd_Direction as sbit at TRISC5_bit ' MD signal direction ' End T6963C module connections dim panel as byte ' i as word ' curs as byte ' cposx, cposy as word ' txtcols as byte ' txt, txt1 as string[29] current panel general purpose register cursor visibility cursor x-y position number of text coloms
main: txt1 = " EINSTEIN WOULD HAVE LIKED mE" txt = " GLCD LIBRARY DEMO, WELCOME !" ANSEL = ANSELH = C1ON_bit C2ON_bit 0 0 = 0 = 0 ' Configure AN pins as digital I/O ' Disable comparators
507
CHAPTER 7
Libraries
TRISB0_bit TRISB1_bit TRISB2_bit TRISB3_bit TRISB4_bit = = = = = 1 1 1 1 1 ' ' ' ' ' Set Set Set Set Set RB0 RB1 RB2 RB3 RB4 as as as as as
T6963C_ctrlce_Direction = 0 T6963C_ctrlce = 0 T6963C_ctrlfs_Direction = 0 T6963C_ctrlfs = 0 T6963C_ctrlmd_Direction = 0 T6963C_ctrlmd = 0 panel = 0 i = 0 curs = 0 cposx = 0 cposy = 0 ' Initialize T6369C T6963C_init(240, 128, 8) ' ' '
' Enable T6963C ' Font Select 8x8 ' Column number select
* * Enable both graphics and text display at the same time * T6963C_graphics(1) T6963C_text(1) * * Text messages * T6963C_write_text(txt, 0, 0, T6963C_ROM_MODE_XOR) T6963C_write_text(txt1, 0, 15, T6963C_ROM_MODE_XOR)
' 8 pixel height ' Move cursor to top left ' Cursor off
* * Draw rectangles * T6963C_rectangle(0, 0, 239, 127, T6963C_WHITE) T6963C_rectangle(20, 20, 219, 107, T6963C_WHITE) T6963C_rectangle(40, 40, 199, 87, T6963C_WHITE) T6963C_rectangle(60, 60, 179, 67, T6963C_WHITE)
508
Libraries
10, T6963C_WHITE) 30, T6963C_WHITE) 50, T6963C_WHITE) 70, T6963C_WHITE) 90, T6963C_WHITE) 110, T6963C_WHITE) 130, T6963C_WHITE) ' Draw a sprite
T6963C_sprite(0, 0, @mikroe_bmp, 240, 64) ' 240x128 can"t be stored in most of PIC16 MCUs T6963C_sprite(0, 64, @mikroe_bmp, 240, 64) ' it is replaced with smaller picture 240x64 ' Smaller picture is drawn two times while TRUE ' Endless loop
'* '* If PORTB_0 is pressed, toggle the display between graphic panel 0 and graphic 1 '* if (RB0_bit <> 0) then T6963C_graphics(1) T6963C_text(0) Delay_ms(300) '* '* If PORTB_1 is pressed, display only graphic panel '*
509
CHAPTER 7
Libraries
else if (RB1_bit <> 0) then Inc(panel) panel = panel and 1 T6963C_setPtr((T6963C_grMemSize panel, T6963C_GRAPHIC_HOME_ADDRESS_SET) Delay_ms(300)
T6963C_txtMemSize)
'* '* If PORTB_2 is pressed, display only text panel '* else if (RB2_bit <> 0) then T6963C_graphics(0) T6963C_text(1) Delay_ms(300) '* '* If PORTB_3 is pressed, display text and graphic panels '* else if (RB3_bit <> 0) then T6963C_graphics(1) T6963C_text(1) Delay_ms(300) '* '* '*
If PORTB_4 is pressed, change cursor else if(RB4_bit <> 0) then Inc(curs) if (curs = 3) then curs = 0 end if select case curs case 0 ' no cursor T6963C_cursor(0) case 1 ' blinking cursor T6963C_cursor(1) T6963C_cursor_blink(1) case 2 ' non blinking cursor T6963C_cursor(1) T6963C_cursor_blink(0) end select 'case Delay_ms(300)
510
Libraries
511
CHAPTER 7
Libraries
HW Connection
512
Libraries
UART LIBRARY
UART hardware module is available with a number of PIC MCUs. mikroBasic PRO for PIC UART Library provides comfortable work with the Asynchronous (full duplex) mode. You can easily communicate with other devices via RS-232 protocol (for example with PC, see the figure at the end of the topic RS-232 HW connection). You need a PIC MCU with hardware integrated UART, for example 16F887. Then, simply use the functions listed below. Note: Some PIC18 MCUs have multiple UART modules. Switching between the UART modules in the UART library is done by the UART_Set_Active function (UART module has to be previously initialized). Note: In order to use the desired UART library routine, simply change the number 1 in the prototype with the appropriate module number, i.e. UART2_Init(2400)
Library Routines
UART1_Init UART1_Data_Ready UART1_Tx_Idle UART1_Read UART1_Read_Text UART1_Write UART1_Write_Text UART_Set_Active
513
CHAPTER 7
Libraries
UART1_Init
Prototype Returns
Nothing. Configures and initializes the UART module. The internal UART module module is set to: receiver enabled transmitter enabled frame size 8 bits 1 STOP bit parity mode disabled asynchronous operation Parameters :
baud_rate: requested baud rate Refer to the device data sheet for baud rates allowed for specific Fosc.
Description
Library. Requires Note: Calculation of the UART baud rate value is carried out by the compiler, as it would produce a relatively large code if performed on the libary level. Therefore, compiler needs to know the value of the parameter in the compile time. That is why this parameter needs to be a constant, and not a variable. Example
'This will initialize hardware UART1 module and establish the communication at 2400 bps UART1_Init(2400)
UART1_Data_Read
Prototype Returns
sub function UART1_Data_Ready() as byte
Function returns 1 if data is ready or 0 if there is no data. MCU with the UART module.
Description The function tests if data in receive buffer is ready for reading. Requires
The UART module must be initialized before using this routine. See the UART1_Init routine.
dim receive as byte ... ' read data if ready if (UART1_Data_Ready() = 1) then receive = UART1_Read() end if
Example
514
Libraries
UART1_Tx_Idle
Prototype
char UART1_Tx_Idle() 1 if the data has been transmitted 0 otherwise
Description Use the function to test if the transmit shift register is empty or not. Requires UART HW module must be initialized and communication established before using this function. See UART1_Init.
' If the previous data has been shifted out, send next data: if (UART1_Tx_Idle = 1) then UART1_Write(_data) end if
Example
UART1_Read
Prototype Returns Description
sub function UART1_Read() as byte
Received byte. The function receives a byte via UART. Use the UART1_Data_Ready function to test if data is ready first. MCU with the UART module. The UART module must be initialized before using this routine. See UART1_Init routine.
dim receive as byte ... ' read data if ready if (UART1_Data_Ready() = 1) then receive = UART1_Read()
Requires
Example
515
CHAPTER 7
Libraries
UART1_Read_Text
Prototype Returns
sub procedure UART1_Read_Text(dim byref Output as string[255], dim byref Delimiter as string[10], dim Attempts as byte)
Nothing. Reads characters received via UART until the delimiter sequence is detected. The read sequence is stored in the parameter output; delimiter sequence is stored in the parameter delimiter.
Description
This is a blocking call: the delimiter sequence is expected, otherwise the procedure exits( if the delimiter is not found). Attempts defines number of received characters in which Delimiter sequence is expected. If Attempts is set to 255, this routine will continously try to detect the Delimiter sequence. UART HW module must be initialized and communication established before using this function. See UART1_Init. Read text until the sequence OK is received, and send back whats been received:
UART1_Init(4800) Delay_ms(100) ' initialize UART module
Requires
Example
while TRUE if (UART1_Data_Ready() = 1) ' if data is received UART1_Read_Text(output, 'delim', 10) ' reads text until 'delim' is found UART1_Write_Text(output) ' sends back text end if wend.
UART1_Write
Prototype Returns
sub procedure UART1_Write(dim TxData as byte)
Description Parameters :
TxData: data to be sent
MCU with the UART module. Requires The UART module must be initialized before using this routine. See UART1_Init routine.
dim data_ as byte ... data_ = 0x1E UART1_Write(data_)
Example
516
Libraries
UART1_Write_Text
Prototype Returns
sub procedure UART1_Write_Text(dim byref uart_text as string[255]
Nothing.
Description Sends text (parameter uart_text) via UART. Text should be zero terminated. Requires UART HW module must be initialized and communication established before using this function. See UART1_Init. Read text until the sequence OK is received, and send back whats been received:
UART1_Init(4800) Delay_ms(100) ' initialize UART module
Example
while TRUE if (UART1_Data_Ready() = 1) ' if data is received UART1_Read_Text(output, 'delim', 10) ' reads text until 'delim' is found UART1_Write_Text(output) ' sends back text end if wend.
UART_Set_Active
Prototype Returns
sub procedure UART_Set_Active (dim read_ptr as ^Tread_ptr, dim write_ptr as ^Twrite_ptr, dim ready_ptr as ^Tready_ptr, dim tx_idle_ptr as ^Ttx_idle_ptr)
Nothing. Sets active UART module which will be used by the UART library routines. Parameters :
Description
read_ptr: UART1_Read handler write_ptr: UART1_Write handler ready_ptr: UART1_Data_Ready handler tx_idle_ptr: UART1_Tx_Idle handler
Routine is available only for MCUs with two UART modules. Requires Used UART module must be initialized before using this routine. See UART1_Init routine.
Activate UART2 module UART_Set_Active(UART1_Read, UART1_Write, UART1_Data_Ready, UART1_Tx_Idle)
Example
517
CHAPTER 7
Libraries
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 PRO for PIC USART Terminal.
program UART dim uart_rd as byte main: UART1_Init(9600) Delay_ms(100)
' Initialize UART module at 9600 bps ' Wait for UART module to stabilize
while (TRUE) ' Endless loop if (UART1_Data_Ready() <> 0) then ' If data is received, uart_rd = UART1_Read() ' read the received data, UART1_Write(uart_rd) ' and send data via UART end if wend end.
HW Connection
UART HW connection
518
Libraries
Descriptor File
Each project based on the USB HID library should include a descriptor source file which contains vendor id and name, product id and name, report length, and other relevant information. To create a descriptor file, use the integrated USB HID terminal of mikroBasic (Tools USB HID Terminal). The default name for descriptor file is USBdsc.pbas, but you may rename it. The provided code in the Examples folder works at 48MHz, and the flags should not be modified without consulting the appropriate datasheet first.
Library Routines
Hid_Enable Hid_Read Hid_Write Hid_Disable
Hid_Enable
Prototype Returns
sub procedure Hid_Enable(dim readbuff, writebuff as word)
Nothing.
Enables USB HID communication. Parameters readbuff and writebuff are the addresses of Read Buffer and the Write Buffer, respectively, which are used for Description HID communication. You can pass buffer names with the @ operator. This function needs to be called before using other routines of USB HID Library. Requires Example Nothing.
Hid_Enable(@rd, @wr)
519
CHAPTER 7
Libraries
Hid_Read
Prototype Returns Description Requires Example
sub function Hid_Read as byte
Number of characters in the Read Buffer received from the host. Receives message from host and stores it in the Read Buffer. Function returns the number of characters received in the Read Buffer. USB HID needs to be enabled before using this function. See Hid_Enable.
length = Hid_Read
Hid_Write
Prototype Returns
sub procedure Hid_Write(dim writebuff as word, dim len as byte)
Nothing.
Function sends data from Write Buffer writebuff to host. Write Buffer is the address of the parameter used in initialization; see Hid_Enable. You can pass a Description buffer name with the @ operator. Parameter len should specify a length of the data to be transmitted. Requires Example USB HID needs to be enabled before using this function. See Hid_Enable.
Hid_Write(@wr, len)
Hid_Disable
Prototype Returns
sub procedure Hid_Disable
Nothing.
Description Disables USB HID communication. Requires Example USB HID needs to be enabled before using this function. See Hid_Enable.
Hid_Disable()
520
Libraries
Library Example
The following example continually sends sequence of numbers 0..255 to the PC via Universal Serial Bus.
program hid_test dim k as byte dim userRD_buffer as byte[64] dim userWR_buffer as byte[64] sub procedure interrupt asm CALL _Hid_InterruptProc nop end asm end sub sub procedure Init_Main ' Disable all interrupts ' Disable GIE, PEIE, TMR0IE, INT0IE,RBIE INTCON = 0 INTCON2 = $F5 INTCON3 = $C0 ' Disable Priority Levels on interrupts RCON.IPEN = 0 PIE1 = 0 PIE2 = 0 PIR1 = 0 PIR2 = 0 ' Configure all ports with analog function as digital ADCON1 = ADCON1 or $0F ' Ports TRISA = TRISB = TRISC = TRISD = TRISE = LATA LATB LATC LATD LATE = = = = = 0 0 0 0 0 Configuration 0 0 $FF $FF $07
' Clear user RAM ' Banks [00 .. 07] ( 8 x 256 = 2048 Bytes )
521
CHAPTER 7
Libraries
asm LFSR MOVLW CLRF CPFSEQ BRA end asm FSR0, $000 $08 POSTINC0, 0 FSR0H, 0 $ - 2
' Timer 0 T0CON = $07; TMR0H = (65536 TMR0L = (65536 INTCON.T0IE = T0CON.TMR0ON = end sub
'** Main Program ** main: Init_Main() Hid_Enable(@userRD_buffer, @userWR_buffer) do for k = 0 to 255 ' Prepare send buffer userWR_buffer[0] = k ' Send the number via USB Hid_Write(@userWR_buffer, 1) next k loop until FALSE Hid_Disable end.
522
Libraries
HW Connection
523
CHAPTER 7
BUTTON LIBRARY
The Button library contains miscellaneous routines useful for a project development. Button
Button
Prototype Returns
sub function Button(dim byref port as byte, dim pin, time, active_state as byte) as byte
Returns 0 or 255. Function eliminates the influence of contact flickering upon pressing a button (debouncing).
Description Parameter port specifies the location of the button; parameter pin is the pin number on designated port and goes from 0..7; parameter time is a debounce period in milliseconds; parameter active_state can be either 0 or 1, and it determines if the button is active upon logical zero or logical one. Requires Button pin must be configured as input. Example reads RB0, to which the button is connected; on transition from 1 to 0 (release of button), PORTD is inverted:
while true if Button(PORTB, 0, 1, 1) then oldstate = 255 end if if oldstate and Button(PORTB, 0, 1, 0) then PORTD = not(PORTD) oldstate = 0 end if wend
Example
524
Libraries
CONVERSIONS LIBRARY
mikroBasic PRO for PIC 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 StrToInt StrToWord The following sub functions convert decimal values to BCD and vice versa: Dec2Bcd Bcd2Dec16 Dec2Bcd16
525
CHAPTER 7
Libraries
ByteToStr
Prototype 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.
dim t as word txt as string[2] ... t = 24 ByteToStr(t, txt) ' txt is " 24" (one blank here)
Example
ShortToStr
Prototype Returns
sub procedure ShortToStr(dim input as short, dim byref output as string[3])
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.
dim t as short txt as string[3] ... t = -24 ByteToStr(t, txt) ' txt is " -24" (one blank here)
Example
526
Libraries
WordToStr
Prototype Returns
sub procedure WordToStr(dim input as word, dim byref output as string[4])
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.
dim t as word txt as string[4] ... t = 437 WordToStr(t, txt) ' txt is "
Example
IntToStr
Prototype Returns
sub procedure IntToStr(dim input as integer, dim byref output as string[5]
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
Nothing.
dim input as integer txt as string[5] '... input = -4220 IntToStr(input, txt)
Example
527
CHAPTER 7
Libraries
LongintToStr
Prototype 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
Nothing.
dim input as longint txt as string[10] '... input = -12345678 IntToStr(input, txt)
Example
-12345678'
LongWordToStr
Prototype Returns
sub procedure LongWordToStr(dim input as longword, dim byref output as string[9])
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
Nothing.
dim input as longint txt as string[9] '... input = 12345678 IntToStr(input, txt)
Example
12345678'
528
Libraries
FloatToStr
Prototype
sub function FloatToStr(dim input as real, dim byref output as string[22])
Returns
3 2 1 0
if if if if
input number is NaN input number is -INF input number is +INF conversion was successful
Description
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.
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) ' txt is "-374.2" ' txt is "123.4567" ' txt is "1.234e-6"
Example
529
CHAPTER 7
Libraries
StrToInt
Prototype Returns
Integer variable.
Description Converts a string to integer Requires The string is assumed to be a correct representation of a number.
dim ii as integer
Example
StrToWord
Prototype Returns
sub function StrToWord(dim byref input as string[5]) as word
Word variable.
input string with length of max 5 chars. The string is assumed to be a correct representation of a number. dim ww as word main:
Example
ww = StrToword('65432') end.
Dec2Bcd
Prototype Returns
function Dec2Bcd (dim decnum as byte) as byte
Converted BCD value. Converts input number to its appropriate BCD representation.
Description Parameters :
decnum: number to be converted
Requires Example
Nothing.
dim a, b as byte ... a = 22 b = Dec2Bcd(a) ' b equals 34
530
Libraries
Bcd2Dec16
Prototype Returns
sub function Bcd2Dec16(dim bcdnum as word) as word
Converted decimal value. Converts 16-bit BCD numeral to its decimal equivalent.
Description Parameters :
bcdnum: 16-bit BCD numeral to be converted
Requires
Nothing.
dim a, b as word ... a = 0x1234 b = Bcd2Dec16(a)
Example
Dec2Bcd16
Prototype Returns
sub function Dec2Bcd16(dim decnum as word) as word
Description Parameters :
decnum decimal number to be converted
Requires
Nothing.
dim a, b as word ... a = 2345 b = Dec2Bcd16(a)
Example
531
CHAPTER 7
The mikroBasic PRO for PIC 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 dexp log log10 modf pow sin sinh sqrt tan tanh
532
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
Prototype Description
sub function cosh(dim x as real) as real
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.
533
CHAPTER 7
Libraries
eval_poly
Prototype Description
sub function eval_poly(dim x as real, dim byref d as array[10] of real, dim n as integer) as real
Function Calculates polynom for number x, with coefficients stored in d[], for degree n.
exp
Prototype Description
sub function exp(dim x as real) as real
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
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 Description
sub function ldexp(dim value as real, dim newexp as integer) as real
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
534
Libraries
log10
Prototype
sub function log10(dim x as real) as real
modf
Prototype Description
sub function modf(dim val as real, dim byref iptr as real) as real
The function returns the signed fractional component of val, placing its whole number component into the variable pointed to by iptr.
sub function pow(dim x as real, dim y as real) as real
pow
Prototype 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 Description
sub function sinh(dim x as real) as real
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
tan
Prototype Description
sub function tan(dim x as real) as real
The function returns the tangent of x in radians. The return value spans the allowed range of floating point in mikroBasic PRO for PIC.
tanh
Prototype Description
sub function tanh(dim x as real) as real)
535
CHAPTER 7
The mikroBasic PRO for PIC 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
536
Libraries
memchr
Prototype
sub function memchr(dim p as ^byte, 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 0xFF 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.
memcmp
Prototype
sub function memcmp(dim p1, p2 as ^byte, dim 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.
537
CHAPTER 7
Libraries
memcpy
Prototype
Description
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(dim p1, p2, as ^byte, dim 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.
memset
Prototype
sub procedure memset(dim p as ^byte, 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 Description
sub procedure strcat(dim byref s1, s2 as string[100])
The function appends the value of string s2 to string s1 and terminates s1 with a null character.
538
Libraries
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 0xFF.
strcmp
Prototype
sub function strcmp(dim byref s1, s2 as string[100]) as short
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.
strcpy
Prototype Description
sub procedure strcpy(dim byref s1, s2 as string[100])
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).
539
CHAPTER 7
Libraries
strlen
Prototype 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 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 short
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).
strncpy
Prototype
sub procedure strncpy(dim byref s1, s2 as string[100], dim size as word)
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 0xFF.
540
Libraries
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 0xFF.
strspn
Prototype
sub function strspn(dim byref s1, s2 as string[100]) as byte
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 0xFF. If s2 is a null string, the function returns 0.
541
CHAPTER 7
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 Returns
sub function Time_dateToEpoch(dim byref ts as TimeStruct) as longint
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.
dim ts1 as TimeStruct Epoch as longint ... ' what is the epoch of the date in ts ? epoch = Time_dateToEpoch(ts1)
Example
542
Libraries
Time_epochToDate
Prototype Returns
sub procedure Time_epochToDate(dim e as longint, dim byref ts as TimeStruct)
Description
Parameters :
e: UNIX time (seconds since UNIX epoch) ts: time and date structure for storing conversion output
Requires
Nothing.
dim ts2 as TimeStruct epoch as longint ... ' what date is epoch 1234567890 ? epoch = 1234567890 Time_epochToDate(epoch,ts2)
Example
Time_dateDiff
Prototype Returns
sub function Time_dateDiff(dim t1 as ^TimeStruct, dim t2 as ^TimeStruct) as longint
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)
Requires
Nothing.
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)
Example
543
CHAPTER 7
Libraries
Library Example
Demonstration of Time library routines usage for time calculations in UNIX time format.
program Time_Demo dim epoch, diff as longint '*********************************** ts1, ts2 as TimeStruct '*********************************** main: 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) ' 1148404020 ' * ' * What date is epoch 1234567890 ? ' * epoch = 1234567890 Time_epochToDate(epoch, @ts2) ' {0x1E, 0x1F, 0x17, 0x0D, 0x04, 0x02, 0x07D9) ' * ' * How much seconds between this two dates ? ' * diff = Time_dateDiff(@ts1, @ts2) ' 86163870 end.
544
Libraries
' month number, from 1 to 12 (and not from 0 time !) ' year Y2K compliant, from 1892 to 2038
545
CHAPTER 7
The mikroBasic PRO for PIC 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 Returns
sub function sinE3(dim angle_deg as word) as integer
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
546
Libraries
cosE3
Prototype Returns
sub function cosE3(dim angle_deg as word) as integer
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
547
CHAPTER 7
Libraries
548
Libraries
549