mikroBasic PRO for PIC32™ Manual Compiler mikroBasic PRO for PIC32 is a full-featured compiler for PIC32 MCUs from Microchip. It is designed for developing, building and debugging PIC32-based embedded applications. This development environment has a wide range of features such as: easy-to-use IDE, very compact and efficient code, many hardware and software libraries, comprehensive documentation, software simulator, COFF file generation, SSA optimization (up to 30% code reduction) and many more.
mikoBasic PRO for PIC32 Table of Contents CHAPTER 1 INTRODUCTION Introduction to mikroBasic PRO for PIC32 30 30 31 Software License Agreement 32 Technical Support How to Register 34 34 CHAPTER 2 mikroBasic PRO for PIC32 Environment Main Menu Options File 38 38 38 39 40 Edit 41 Features Where to Start mikroElektronika Associates License Statement and Limited Warranty IMPORTANT - READ CAREFULLY LIMITED WARRANTY HIGH RISK ACTIVITIES GENERAL PROVISIONS Who Gets the License Key
mikroBasic PRO for PIC32 mikroBasic PRO for PIC32 IDE 51 Code Editor 52 Code Explorer 59 Project Manager Project Settings Library Manager 60 62 63 Routine List Statistics 65 65 Messages Window Quick Converter Macro Editor Image Preview Toolbars 72 73 73 74 76 IDE Overview Editor Settings Auto Save Highlighter Spelling Comment Style Code Folding Code Assistant Parameter Assistant Bookmarks Go to Line Column Select Mode Editor Colors Auto Correct Auto Complete (Code Tem
mikoBasic PRO for PIC32 Advanced Edit Toolbar Find/Replace Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar 78 78 79 79 80 80 81 81 82 82 Customizing IDE Layout 83 Options 85 Integrated Tools 88 Active Comments 96 Docking Windows Saving Layout Auto Hide Code editor Tools Output settings Active Comments Editor ASCII Chart EEPROM Editor Graphic Lcd Bitmap Editor HID Terminal Interrupt Assistant Lcd Cu
mikroBasic PRO for PIC32 Metacharacters - Subexpressions Metacharacters - Backreferences 110 110 Keyboard Shortcuts CHAPTER 3 mikroBasic PRO for PIC32 Command Line Options CHAPTER 4 mikroICD (In-Circuit Debugger) Introduction mikroICD Debugger Options 111 113 113 115 115 115 117 mikroICD Debugger Example mikroICD Debugger Windows 118 122 CHAPTER 5 Software Simulator Overview Software Simulator Software Simulator Debug Windows 127 127 128 129 Software Simulator Debugger Options 134
mikoBasic PRO for PIC32 bit type Interrupts Configuring Interrupts Single Vector Mode Multi Vector Mode 140 141 141 141 141 Interrupt Priorities Interrupts and Register Sets 142 142 Interrupt Coding Requirements Interrupt Service Routine Function Calls from Interrupt Interrupt Example 142 142 143 144 Register Set Selection in Single Vector Mode Interrupts and Register Sets 142 142 Linker Directives 145 Built-in Routines 146 Directive absolute Directive org Directive orgall
mikroBasic PRO for PIC32 DoGetDateTime DoGetVersion KVA0_TO_KVA1 KVA1_TO_KVA0 KVA_TO_PA PA_TO_KVA0 PA_TO_KVA1 CP0_GET CP0_SET EnableInterrupts DisableInterrupts 159 159 160 160 160 161 161 161 162 162 162 Code Optimization 164 Single Static Assignment Optimization 165 CHAPTER 7 PIC32 Specifics 168 168 PIC32 Memory Organization 170 Memory Type Specifiers 173 Read Modify Write Problem CHAPTER 8 mikroBasic PRO for PIC32 Language Reference Lexical Elements Overview Whitespace
mikoBasic PRO for PIC32 Newline Character Whitespace in Strings 181 181 Comments Tokens 182 182 Literals 183 Keywords Identifiers 185 187 Punctuators 188 Program Organization 190 Token Extraction Example Long and Unsigned Suffixes Floating Point Literals Character Literals String Literals Case Sensitivity Uniqueness and Scope Identifier Examples Brackets Parentheses Comma Colon Dot Organization of Main Module Organization of Other Modules Note: Sub functions and sub
mikroBasic PRO for PIC32 Functions Calling a function Procedures Forward declaration Functions reentrancy 199 199 200 201 202 Types 203 Simple Types Derived Types Arrays 203 204 204 Strings 205 Pointers 207 @ Operator Pointer Arithmetic 209 210 Structures 212 Types Conversions 214 Typedef Specifier Type Qualifiers 216 216 Operators 217 Arithmetic Operators 218 Relational Operators 219 Bitwise Operators 220 Type Categories Array Declaration Constant Arrays M
mikoBasic PRO for PIC32 Logical Operations on Bit Level Unsigned and Conversions Signed and Conversions Bitwise Shift Operators 220 221 221 221 Boolean Operators Unary Operators 222 222 Sizeof Operator 223 Expressions Expression Evaluation Statements Assignment Statements Conditional Statements If Statement 224 224 225 225 226 226 Select Case Statement 227 Iteration Statements (Loops) For Statement 228 228 While Statement Do Statement Jump Statements Break and Continue Stateme
mikroBasic PRO for PIC32 Explicit Path 237 CHAPTER 9 mikroBasic PRO for PIC32 Libraries Hardware Libraries Miscellaneous Libraries Hardware Libraries ADC Library 239 239 240 240 241 241 CANSPI Library 245 Compact Flash Library 261 Directive absolute Directive org Directive orgall Library Routines ADCx_Init ADCx_Init_Advanced ADCx_Get_Sample ADCx_Read Library Example Library Dependency Tree External dependencies of CANSPI Library Library Routines CANSPISetOperationMode CANSPIG
mikoBasic PRO for PIC32 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_Date_Modified Cf_Fat_Get_File_Size Cf_Fat_Get_Swap_File Library Example HW Connection Epson S1D13700 Graphic Lcd Library External dependencies of the Epson S1D13700 Graphic Lcd Library Library
mikroBasic PRO for PIC32 S1D13700_Circle_Fill S1D13700_Image S1D13700_PartialImage 294 294 295 Flash Memory Library 296 Graphic Lcd Library 298 I²C Library 312 Keypad Library 318 Library Routines Flash_Write_Word Flash_Write_Row Flash_Erase_Page Library Dependency Tree External dependencies of Graphic Lcd Library Glcd_Init Glcd_Set_Side Glcd_Set_X Glcd_Set_Page Glcd_Read_Data Glcd_Write_Data Glcd_Fill Glcd_Dot Glcd_Line Glcd_V_Line Glcd_H_Line Glcd_Rectangle Glcd_Rectangl
mikoBasic PRO for PIC32 Library Routines Keypad_Init Keypad_Key_Press Keypad_Key_Click Library Example HW Connection 318 318 319 319 320 321 Lcd Library 322 Manchester Code Library 328 Memory Manager Library 336 Multi Media Card Library 338 Library Dependency Tree External dependencies of Lcd Library Library Routines Lcd_Init Lcd_Out Lcd_Out_Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd Available Lcd Commands Library Example External dependencies of Manchester Code Library Library Routines
mikroBasic PRO for PIC32 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_Date_Modified Mmc_Fat_Get_File_Size Mmc_Fat_Get_Swap_File Library Example HW Connection 342 343 344 345 346 346 347 347 347 348 348 349 350 350 351 352 356 OneWire Library 357 Port Expander Library 359 PS/2 Library 370 Library Routines Ow_Reset Ow_
mikoBasic PRO for PIC32 Library Routines Ps2_Config Ps2_Key_Read Special Function Keys Library Example HW Connection 370 371 371 372 373 374 PWM Library 374 RS-485 Library 379 Software I²C Library 389 Software SPI Library 395 Software UART Library 399 Library Routines PWM_Init PWM_Init_Advanced PWM_Set_Duty PWM_Start PWM_Stop Library Example HW Connection Library Dependency Tree External dependencies of RS-485 Library Library Routines RS485Master_Init RS485Master_Receive
mikroBasic PRO for PIC32 Library Routines Soft_UART_Init Soft_UART_Read Soft_UART_Write Soft_UART_Break Library Example 399 399 400 400 401 402 Sound Library 403 SPI Library 407 SPI Ethernet Library 415 Library Routines Sound_Init Sound_Play HW Connection Library Routines SPIx_Init SPIx_Init_Advanced SPIx_Read SPIx_Write SPI_Set_Active Library Example HW Connection Library Dependency Tree External dependencies of SPI Ethernet Library Library Routines SPI_Ethernet_Init SPI_E
mikoBasic PRO for PIC32 SPI_Ethernet_initDHCP SPI_Ethernet_doDHCPLeaseTime SPI_Ethernet_renewDHCP Library Example HW Connection 431 431 432 432 439 SPI Ethernet ENC24J600 Library 440 SPI Graphic Lcd Library 459 Library Dependency Tree External dependencies of SPI Ethernet ENC24J600 Library Library Routines SPI_Ethernet_24j600_Init SPI_Ethernet_24j600_Enable SPI_Ethernet_24j600_Disable SPI_Ethernet_24j600_doPacket SPI_Ethernet_24j600_putByte SPI_Ethernet_24j600_putBytes SPI_Ethernet_24j
mikroBasic PRO for PIC32 SPI_Glcd_Line SPI_Glcd_V_Line SPI_Glcd_H_Line SPI_Glcd_Rectangle SPI_Glcd_Rectangle_Round_Edges SPI_Glcd_Rectangle_Round_Edges_Fill SPI_Glcd_Box SPI_Glcd_Circle SPI_Glcd_Circle_FIll SPI_Glcd_Set_Font SPI_Glcd_Write_Char SPI_Glcd_Write_Text SPI_Glcd_Image SPI_Glcd_PartialImage Library Example HW Connection 464 464 465 465 466 466 467 467 468 469 470 470 471 471 472 474 SPI Lcd Library 475 SPI Lcd8 (8-bit interface) Library 481 SPI T6963C Graphic Lcd Library
mikoBasic PRO for PIC32 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_rectangle_round_edges SPI_T6963C_rectangle_round_edges_fill SPI_T6963C_box SPI_T6963C_circle SPI_T6963C_circle_fill SPI_T6963C_image SPI_T6963C_PartialImage SPI_T6963C_sprite SPI_T6963C_set_cursor SPI_T6963C_clearBit SPI_T6963C_setBit SPI_T6963C_negBit SPI_T6
mikroBasic PRO for PIC32 T6963C_write_char T6963C_write_text T6963C_line T6963C_rectangle T6963C_rectangle_round_edges T6963C_rectangle_round_edges_fill T6963C_box T6963C_circle T6963C_circle_fill T6963C_image T6963C_PartialImage 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 Library Exampl
mikoBasic PRO for PIC32 TFT_Circle TFT_Image TFT_Partial_Image TFT_Image_Jpeg TFT_RGBToColor16bit TFT_Color16bitToRGB HW Connection 548 548 549 549 550 550 551 Touch Panel Library 552 Touch Panel TFT Library 557 UART Library 563 USB Library 573 MikroElektronika 22 Library Dependency Tree External dependencies of Touch Panel Library Library Routines TP_Init TP_Set_ADC_Threshold TP_Press_Detect TP_Get_Coordinates TP_Calibrate_Bottom_Left TP_Calibrate_Upper_Right TP_Get_Calibrat
mikroBasic PRO for PIC32 USB HID Class Descriptor File Library Routines HID_Enable HID_Read HID_Write HID_Disable USB_Interrupt_Proc USB_Polling_Proc Gen_Enable Gen_Read Gen_Write Library Example HW Connection 573 573 573 574 574 574 575 575 576 576 577 577 578 578 Miscellaneous Libraries Button Library 579 579 C Type Library 581 Conversions Library 584 Library Routines Button Library Functions isalnum isalpha iscntrl isdigit isgraph islower ispunct isspace isupper isx
mikoBasic PRO for PIC32 LongIntToStrWithZeros ByteToHex ShortToHex WordToHex IntToHex LongWordToHex LongIntToHex StrToInt StrToWord Bcd2Dec Dec2Bcd Bcd2Dec16 Dec2Bcd16 590 590 591 591 592 592 593 593 594 594 595 595 595 Setjmp Library 596 String Library 598 Time Library 606 MikroElektronika 24 Library Routines Setjmp Longjmp Library Example Library Functions memchr memcmp memcpy memmove memset strcat strcat2 strchr strcmp strcpy strlen strncat strncpy strspn strn
mikroBasic PRO for PIC32 Time_dateToEpoch Time_epochToDate Time_dateDiff Library Example 606 607 607 608 Trigon Library 609 Trigonometry Library 614 CHAPTER 10 Tutorials Managing Project 615 615 615 New Project 616 Customizing Projects 620 Source Files 622 Library Functions acos asin atan atan2 ceil cos cosh eval_poly exp fabs floor frexp ldexp log log10 modf pow sin sinh sqrt tan tanh Library Routines sinE3 cosE3 Projects New Project Wizard Steps Mana
mikoBasic PRO for PIC32 Opening an existing file Printing an open file Saving file Saving file under a different name Closing file Search Paths Paths for Source Files (.
mikroBasic PRO for PIC32 27 MikroElektronika
CHAPTER 1 mikoBasic PRO for PIC32 INTRODUCTION mikroBasic PRO for PIC32 is a powerful, feature-rich development tool for PIC32 microcontrollers. It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems, without compromising performance or control.
mikroBasic PRO for PIC32 Introduction to mikroBasic PRO for PIC32 The PIC32 is a 32-bit family of general purpose microcontrollers. This is the Microchip’s first inherent 32-bit (data) microcontroller family. It builds upon the MIPS M4K 32-bit core, offering high-performance hardware multiply/divide unit, programmable user and kernel memory partition through an unified 4GB virtual memory space, with powerful peripherals to address a wide range of applications.
mikoBasic PRO for PIC32 Software License Agreement mikroElektronika Associates License Statement and Limited Warranty IMPORTANT - READ CAREFULLY This license statement and limited warranty constitute a legal agreement (“License Agreement”) between you (either as an individual or a single entity) and mikroElektronika (“mikroElektronika Associates”) for software product (“Software”) identified above, including any software, media, and accompanying on-line or printed documentation.
mikroBasic PRO for PIC32 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 POSSIBILI
mikoBasic PRO for PIC32 Technical Support The latest software can be downloaded free of charge via Internet (you might want to bookmark the page so you could check news, patches, and upgrades later on): http://www.pic32compilers.com/ . 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.
mikroBasic PRO for PIC32 If you choose I work online registering method, following page will be opened in your default browser: 33 MikroElektronika
mikoBasic PRO for PIC32 Fill out the registration form, select your distributor, and click the Submit button. If you choose I work offline registering method, following window will be opened: Fill out the registration form, select your distributor, and click the Submit button. 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.
mikroBasic PRO for PIC32 Important: - The license key is valid until you format your hard disk. In case you need to format the hard disk, you should request a new activation key. - Please keep the activation program in a safe place. Every time you upgrade the compiler you should start this program again in order to reactivate the license.
CHAPTER 2 mikoBasic PRO for PIC32 mikroBasic PRO for PIC32 Environment MikroElektronika 36
mikroBasic PRO for PIC32 Main Menu Options Available Main Menu options are: Related topics: Keyboard shortcuts, Toolbars 37 MikroElektronika
mikoBasic PRO for PIC32 File File Menu Options The File menu is the main entry point for manipulation with the source files. File Description Open a new editor window. Open source file for editing or image file for viewing. Reopen recently used file. Save changes for active editor. Save the active source file with the different name or change the file type. Close active source file. Close all opened files. Print Preview. Print. Exit IDE.
mikroBasic PRO for PIC32 Edit Edit Menu Options The Edit Menu contains commands for editing the contents of the current document. Edit Description Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard. Paste text from clipboard. Delete selected text. Select all text in active editor. Find text in active editor. Find next occurence of text in active editor. Find previous occurence of text in active editor. Replace text in active editor.
mikoBasic PRO for PIC32 Advanced » Description Comment selected code or put single line comment if there is no selection. Uncomment selected code or remove single line comment if there is no selection. Indent selected code. Outdent selected code. Changes selected text case to lowercase. Changes selected text case to uppercase. Changes selected text case to titlercase. Find Text Dialog box for searching the document for the specified text. The search is performed in the direction specified.
mikroBasic PRO for PIC32 Find In Files Dialog box for searching for a text string in current file, all opened files, or in files on a disk. The string to search for is specified in the Text to find field. If Search in directories option is selected, The files to search are specified in the Files mask and Path fields. Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned.
mikoBasic PRO for PIC32 View View Menu Options View Menu contains commands for controlling the on-screen display of the current project.
mikroBasic PRO for PIC32 View Description Show/Hide Software Simulator / mikroICD (In-Circuit Debugger) Debug Windows. Show/Hide Toolbars. Show/Hide Bookmarks window. Show/Hide Code Explorer window. Show/Hide Library Manager window. Show/Hide Macro Editor window. Show/Hide Messages window. Show/Hide Project Manager window. Show/Hide Project Settings window. Show/Hide Routine List in active editor. Show/Hide Quick Converter window. Show/Hide View Image Preview window. View Assembly. View Listing.
mikoBasic PRO for PIC32 Project Project Menu Options Project Menu allows the user to easily manipulate current project. Project Description Open New Project Wizard Open existing project. Open project group. Open recently used project or project group. Save current project. Save active project file with the different name. Close active project. Close project group. Add file to project. Remove file from project. Edit search paths.
mikroBasic PRO for PIC32 Build Build Menu Options Build Menu allows the user to easily manage building and compiling process. Build Description Build active project. Rebuild all sources in active project. Build all projects. Stop building all projects. Build and program active project.
mikoBasic PRO for PIC32 Run Run Menu Options Run Menu is used to debug and test compiled code on a software or harware level. Run Description Start Software Simulator or mikroICD (In-Circuit Debugger). Stop Debugger. Run/Pause Debugger. Step Into. Step Over. Step Out. Run To Cursor. Jump to interrupt in current project. Toggle Breakpoint. Clear Breakpoints. Toggle between source and disassembly.
mikroBasic PRO for PIC32 Tools Tools Menu Options Tools Menu contains a number of applications designed to ease the use of compiler and included library routines. Tools Description Run mikroElektronika Programmer. Run Package Manager. Show/Hide Active Comment Editor window. Run ASCII Chart Run EEPROM Editor Generate HTML code suitable for publishing source code on the web.
mikoBasic PRO for PIC32 Help Help Menu Options Help Description Оpen Help File. Оpen 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.
mikroBasic PRO for PIC32 mikroBasic PRO for PIC32 IDE IDE Overview The mikroBasic PRO for PIC32 is an user-friendly and intuitive environment. For a detailed information on a certain part of IDE, simply click on it (hovering a mouse cursor above a desired IDE part will pop-up its name): - The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Spell Checker, Auto Correct for common typos and Code Templates (Auto Complete).
mikoBasic PRO for PIC32 Code Editor The Code Editor is advanced text editor fashioned to satisfy needs of professionals. General code editing is the same as working with any standard text-editor, including familiar Copy, Paste and Undo actions, common for Windows environment. Available Code Editor options are: Editor Settings, Editor Colors, Auto Correct, Auto Complete and Style.
mikroBasic PRO for PIC32 Auto Save Auto Save is a function which saves an opened project automatically, helping to reduce the risk of data loss in case of a crash or freeze. Autosaving is done in time intervals defined by the user. Highlighter Highlighting is a convenient feature for spotting brackets which notate begin or end of a routine, by making them visually distinct.
mikoBasic PRO for PIC32 Another way of folding/unfolding code subsections is by using Alt+← and Alt+→. If you place a mouse cursor over the tooltip box, the collapsed text will be shown in a tooltip style box. 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).
mikroBasic PRO for PIC32 Column Select Mode This mode changes the operation of the editor for selecting text. When column select mode is used, highlighted text is based on the character column position of the first character selected to the column of the last character of text selected. Text selected in this mode does not automatically include all text between the start and end position, but includes all text in the columns between the first and last character selected.
mikoBasic PRO for PIC32 Editor Colors option allows user to set, change and save text and color settings organized in schemes. Schemes represent custom graphical appearance that can be applied to GUI (Graphical User Interface) to satisfy tastes of different users. Auto Correct Auto Correct option facilitates the user in such a fashion that it automatically corrects common typing or spelling errors as it types. This option is already set up to automatically correct some words.
mikroBasic PRO for PIC32 The user can easily add its common typos by entering original typo, for example btye, to the Original box, and replacement, byte, to the Replacement box, and just click "Add" button. Next time when the typo occurs, it will be automatically corrected. Auto Complete (Code Templates) Auto Complete option saves lots of keystrokes for commonly used phrases by automatically completing user's typing.
mikoBasic PRO for PIC32 The user can insert the Code Template by typing the name of the template (for instance, dow), then press Ctrl+J and the Code Editor will automatically generate a code: You can add your own templates to the list by entering the desired keyword, description and code of your template in appropriate boxes.
mikroBasic PRO for PIC32 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 double clicking it, or pressing the Enter button. Also, besides the list of defined and declared objects, code explorer displays message about the first error and it's location in code. The following options are available in the Code Explorer: Icon Description Expand/Collapse all nodes in tree. Locate declaration in code.
mikoBasic PRO for PIC32 Routine List Routine list diplays list of routines, and enables filtering routines by name. Routine list window can be accessed by pressing Ctrl+L. You can jump to a desired routine by double clicking on it, or pressing the Enter button. Also, you can sort routines by size or by address. Project Manager Project Manager is IDE feature which allows the users to manage multiple projects. Several projects which together make project group may be open at the same time.
mikroBasic PRO for PIC32 Following options are available in the Project Manager: Icon Description Save project Group. Open project group. Close the active project. Close project group. Add project to the project group. Remove project from the project group. Add file to the active project. Remove selected file from the project. Build the active project. Run mikroElektronika’s Flash programmer. For details about adding and removing files from project see Add/Remove Files from Project.
mikoBasic PRO for PIC32 Project Settings The following options are available in the Project Settings window: - Device - select the appropriate device from the device drop-down list. - MCU Clock - enter the clock frequency value. - Build/Debugger Type - choose debugger type.
mikroBasic PRO for PIC32 Library Manager Library Manager enables simple handling libraries being used in a project. Library Manager window lists all libraries (extension .emcl) 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.
mikoBasic PRO for PIC32 Managing libraries using Package Manager The Package Manager is a tool which enables users to easily install their own libraries in the mikroIDE. Libraries are distributed in the form of a package, which is an archive composed of one or more files, containing libraries. For more information on Package Manager, visit our website. Upon package installation, a new node with the package name will be created in the Library Manager.
mikroBasic PRO for PIC32 Routine List Routine list diplays list of routines, and enables filtering routines by name. Routine list window can be accessed by pressing Ctrl+L. You can jump to a desired routine by double clicking on it, or pressing the Enter button. Also, you can sort routines by size or by address. Statistics After successful compilation, you can review statistics of your code. Click the Statistics Icon . Memory Usage Windows Provides overview of RAM and ROM usage in the various forms.
mikoBasic PRO for PIC32 Variables Displays variables sorted by addresses. Used RAM Locations Displays used RAM memory locations and their names.
mikroBasic PRO for PIC32 SFR Locations Displays list of used SFR locations. ROM Memory Usage Displays ROM memory space usage in a pie-like form.
mikoBasic PRO for PIC32 ROM Memory Constants Displays ROM memory constants and their addresses. Functions Sorts and displays functions in various ways.
mikroBasic PRO for PIC32 Functions Sorted By Name Chart Sorts and displays functions by their name, in the ascending order. Functions Sorted By Size Chart Sorts and displays functions by their sizes in a chart-like form.
mikoBasic PRO for PIC32 Functions Sorted By Addresses Sorts and displays functions by their addresses, in the ascending order. Function Tree Displays Function Tree with the relevant data for each function.
mikroBasic PRO for PIC32 Memory Summary Displays summary of RAM and ROM memory in a pie-like form.
mikoBasic PRO for PIC32 Messages Window Messages Window displays various informations and notifications about the compilation process. It reports for example, time needed for preprocessing, compilation and linking; used RAM and ROM space, generated baud rate with error percentage, etc. User can filter which notifications will Messages Window display by checking Errors, Warning and Hints box. In case that errors were encountered during compiling, the compiler will report them and won’t generate a hex file.
mikroBasic PRO for PIC32 Quick Converter Quick Converter enables the user to easily transform numbers from one base to another. User can convert integers of various sizes (8, 16 or 32 bits), signed and unsigned, using different representation (decimal, hexadecimal, binary and character). Also, Quick Converter features float point numbers conversion from/to Float Decimal, Float 32bit (IEEE), Float 32bit (Microchip) and Radix 1.15 for dsPIC family of MCUs.
mikoBasic PRO for PIC32 The Macro offers the following commands: Icon Description Starts ‘recording’ keystrokes for later playback. Stops capturing keystrokes that was started when the Start Recording command was selected. Allows a macro that has been recorded to be replayed. New macro. Delete macro.
mikroBasic PRO for PIC32 Now, navigate to the desired image file, and simply add it: Next, right click the added file, and choose Set As Preview Image: 73 MikroElektronika
mikoBasic PRO for PIC32 Once you have added the image, it will appear in the Image Preview Window: Also, you can add multiple images to the Image Files node, but only the one that is set will be automatically displayed in the Image Preview Window upon opening the project. By changing the Image Preview Window size, displayed image will be fit by its height in such a way that its proportions will remain intact.
mikroBasic PRO for PIC32 File Toolbar File Toolbar is a standard toolbar with the following options: Icon Description Opens a new editor window. Open source file for editing or image file for viewing. Save changes for active window. Save changes in all opened windows. Print Preview. Print. Edit Toolbar Edit Toolbar is a standard toolbar with the following options: Icon Description Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard.
mikoBasic PRO for PIC32 Advanced Edit Toolbar Advanced Edit Toolbar comes with the following options: Icon Description Comment selected code or put a 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.
mikroBasic PRO for PIC32 Project Toolbar Project Toolbar comes with the following options: Icon Description New project. Open Project Save Project Edit project settings. Close current project. Clean project folder. Add File To Project Remove File From Project Build Toolbar Build Toolbar comes with the following options: Icon Description Build current project. Build all opened projects. Build and program active project. Start programmer and load current HEX file.
mikoBasic PRO for PIC32 Debug Toolbar Debug Toolbar comes with the following options: Icon Description Start Software Simulator or mikroICD (In-Circuit Debugger). Run/Pause Debugger. Stop Debugger. Step Into. Step Over. Step Out. Run To Cursor. Toggle Breakpoint. View Breakpoints Window Clear Breakpoints. View Watch Window View Stopwatch Window Styles Toolbar Styles toolbar allows you to easily change colors of your workspace.
mikroBasic PRO for PIC32 Tools Toolbar Tools Toolbar comes with the following default options: Icon Description Run USART Terminal EEPROM ASCII Chart Seven Segment Editor. Open Active Comment editor. Options menu Tip : The Tools toolbar can easily be customized by adding new tools in Options menu window. View Toolbar View Toolbar provides access to assembly code, listing file and statistics windows. Icon Description Open assembly code in editor. Open listing file in editor.
mikoBasic PRO for PIC32 Layout Toolbar Styles toolbar allows you to easily customize workspace through a number of different IDE layouts. Icon Description Delete the selected layout. Save the current layout. Set the selected layout. Help Toolbar Help Toolbar provides access to information on using and registering compilers: Icon Description Open Help file. How To Register.
mikroBasic PRO for PIC32 Customizing IDE Layout Docking Windows You can increase the viewing and editing space for code, depending on how you arrange the windows in the IDE. Step 1: Click the window you want to dock, to give it focus. Step 2: Drag the tool window from its current location. A guide diamond appears. The four arrows of the diamond point towards the four edges of the IDE.
mikoBasic PRO for PIC32 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 .
mikroBasic PRO for PIC32 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. Options Options menu consists of three tabs: Code Editor, Tools and Output settings.
mikoBasic PRO for PIC32 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 PIC32 specifics). Build all files as library enables user to use compiled library (*.
mikroBasic PRO for PIC32 85 MikroElektronika
mikoBasic PRO for PIC32 Integrated Tools Active Comments Editor Active Comments Editor is a tool, particularly useful when working with Lcd display. You can launch it from the dropdown menu Tools › Active Comments Editor or by clicking the Active Comment Editor Icon MikroElektronika from Tools toolbar.
mikroBasic PRO for PIC32 ASCII Chart The ASCII Chart is a handy tool, particularly useful when working with Lcd display. You can launch it from the dropdown menu Tools › ASCII chart or by clicking the View ASCII Chart Icon 87 from Tools toolbar.
mikoBasic PRO for PIC32 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 you run mikroElektronika programmer software from mikroBasic PRO for PIC32 IDE - project_name.hex file will be loaded automatically while ihex file must be loaded manually.
mikroBasic PRO for PIC32 Graphic Lcd Bitmap Editor The mikroBasic PRO for PIC32 includes the Graphic Lcd Bitmap Editor. Output is the mikroBasic PRO for PIC32 compatible code. You can launch it from the drop-down menu Tools › Glcd Bitmap Editor.
mikoBasic PRO for PIC32 HID Terminal The mikroBasic PRO for PIC32 includes the HID communication terminal for USB communication. You can launch it from the drop-down menu Tools › HID Terminal. Interrupt Assistant mikroBasic PRO for PIC32 includes the Interrupt Assistant that assist user in configuring interrupts. Output is the code for the configured interrupt routine. You can launch it from the drop-down menu Tools › Interrupt Assistant.
mikroBasic PRO for PIC32 Lcd Custom Character mikroBasic PRO for PIC32 includes the Lcd Custom Character. Output is mikroBasic PRO for PIC32 compatible code. You can launch it from the drop-down menu Tools › Lcd Custom Character.
mikoBasic PRO for PIC32 Seven Segment Editor The Seven Segment Editor is a convenient visual panel which returns decimal/hex value for any viable combination you would like to display on seven segment display. Click on the parts of seven segment image to get the requested value in the edit boxes. You can launch it from the drop-down menu Tools › Seven Segment Editor or by clicking the Seven Segment Editor Icon from Tools toolbar. UDP Terminal The mikroBasic PRO for PIC32 includes the UDP Terminal.
mikroBasic PRO for PIC32 USART Terminal The mikroBasic PRO for PIC32 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.
mikoBasic PRO for PIC32 Active Comments The idea of Active Comments is to make comments alive and give old fashioned comments new meaning and look. From now on, you can assign mouse event on your comments and ‘tell’ your comments what to do on each one. For example, on left mouse click, open some web address in your browser, on mouse over show some picture and on mouse double click open some file.
mikroBasic PRO for PIC32 You can notice that when you start typing a name, properties pane is automatically displayed so you can edit properties if you wish. A Comment will be is created when you click button. Properties are consisted of two major categories - Attributes and Events. Attributes can be: - URL - Valid web address. - Image - Image has to be previously added to Project (Project Manager > Images). - File - File has to be previously added to Project (Project Manager > Other Files).
mikoBasic PRO for PIC32 First three event types can have one of the following three actions: 1. OpenUrl - Opens entered URL in default Web browser. 2. OpenFile - Opens a file within a default program associated with the file extension (defined by Windows). 3. None - Does nothing. The fourth event, OnMouseOver, has only 2 actions: 1. PreviewImage - Shows image when cursor is moved over a comment. 2. None - Does nothing. Attributes are tightly bounded with events.
mikroBasic PRO for PIC32 You can see the contents of the created XML file by expanding Active Comment Editor: As we mentioned above you can add image or file which are already included in project. If the the desired image or file aren't added, you can do it directly from here by clicking the 97 or button.
mikoBasic PRO for PIC32 Next file dialog will be opened: There, you should select the desired image to be added. In our example, Easy_GSM_GPRS.jpg image will be added.
mikroBasic PRO for PIC32 Now, when image has been selected, we can assign an event to it. For example, OnMouseOver will be used for PreviewImage action, and OnLeftClick + Alt will be assigned to OpenUrl action: Now we can save our changes to Active Comment by clicking the Save button. Note: Setting file attributes is same as for image, so it won't be explained separately.
mikoBasic PRO for PIC32 There is another way to add an active comment to an active project. You can do it simply by typing a comment in old fashion way, except with ac: prefix. So it would look like this: Notice that when you stop typing, Add Comment To Project button will show. By clicking on it, you will open Active Comment Editor and comment name will be already set, so you need only to adjust attributes and settings.
mikroBasic PRO for PIC32 If you click No, comment will be removed from the source code.
mikoBasic PRO for PIC32 Now click again Rename button. Now you have renamed your Active Comment in such a way that its filename, source code name are changed: Deleting Active Comment Deleting active comment works similar like renaming it. By clicking on delete button, you will remove an active comment from both code and Project Manager.
mikroBasic PRO for PIC32 Export Project This option is very convenient and finds its use in relocating your projects from one place to another (e.g. from your work computer to your home computer). Often, project contains complicated search paths (files involved within your project could be in a different folders, even on different hard disks), so it is very likely that some files will be forgotten during manual relocation.
mikoBasic PRO for PIC32 Jump To Interrupt Lets you choose which interrupt you want to jump to. Requirement: Interrupt routine is included in project. You can call Jump To Interrupt by selecting Run › Jump To Interrupt from the drop-down menu, or by clicking the Jump To Interrupt Icon , from the Watch Values Window. By checking the Only Used box, you can display only the used breakpoints.
mikroBasic PRO for PIC32 Regular Expressions Introduction Regular Expressions are a widely-used method of specifying patterns of text to search for. Special metacharacters allow you to specify, for instance, that a particular string you are looking for, occurs at the beginning, or end of a line, or contains n recurrences of a certain character. Simple matches Any single character matches itself, unless it is a metacharacter with a special meaning described below.
mikoBasic PRO for PIC32 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 precede it with a backslash.
mikroBasic PRO for PIC32 Metacharacters - Predefined classes \w - an alphanumeric character (including "_") \W - a nonalphanumeric character \d - a numeric character \D - a non-numeric character \s - any space (same as [\t\n\r\f]) \S - a non space You may use \w, \d and \s within custom character classes. Example: so on.
mikoBasic PRO for PIC32 Examples: count.*r ß- matches strings like 'counter', 'countelkjdflkj9r' and 'countr' count.+r - matches strings like 'counter', 'countelkjdflkj9r' but not 'countr' count.?r - matches strings like 'counter', 'countar' and 'countr' but not 'countelkj9r' counte{2}r - matches string 'counteer' counte{2,}r - matches strings like 'counteer', 'counteeer', 'counteeer' etc.
mikroBasic PRO for PIC32 Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroBasic PRO for PIC32 IDE.
mikoBasic PRO for PIC32 Ctrl+F5 Add to Watch List Ctrl+F8 Step Out Alt+D Disassembly View Shift+F5 Open Watch Window Ctrl+Shift+A Show Advanced Breakpoints MikroElektronika 110
mikroBasic PRO for PIC32 CHAPTER 3 mikroBasic PRO for PIC32 Command Line Options Usage: mBPIC32.exe [- [-]] [ [-]] [-]] Infile can be of *.mbas, *.emcl and *.pld type. The following parameters are valid: -P : MCU for which compilation will be done. -FO : Set oscillator [in MHz]. -SP : Add directory to the search path list. -N : Output files generated to file path specified by filename.
mikoBasic PRO for PIC32 Example: mBPIC32.exe -MSF -DBG -p32MX460F512L -Y -DL -O11111114 -fo80 -N”C:\Lcd\Lcd.mbp32” -SP”C:\ Program Files\Mikroelektronika\mikroBasic PRO for PIC32\Defs” -SP”C:\Program Files\Mikroelektronika\mikroBasic PRO for PIC32\Uses” -SP”C:\ Lcd\” “__Lib_Math.emcl” “__Lib_MathDouble.emcl” “__Lib_System.emcl” “__Lib_Delays.emcl” “__Lib_LcdConsts.emcl” “__Lib_Lcd. emcl” “Lcd.mbas” Parameters used in the example: -MSF : Short Message Format; used for internal purposes by IDE.
mikroBasic PRO for PIC32 CHAPTER 4 mikroICD (In-Circuit Debugger) Introduction The mikroICD is a highly effective tool for a Real-Time debugging on hardware level. The mikroICD debugger enables you to execute the mikroBasic PRO for PIC32 program on a host PIC32 microcontroller and view variable values, Special Function Registers (SFR), RAM, CODE and EEPROM memory along with the mikroICD code execution on hardware.
mikoBasic PRO for PIC32 If you have appropriate hardware and software for using the mikroICD select mikroICD Debug Build Type before compiling the project. Now, compile the project by pressing Ctrl + F9, or by pressing Build Icon on Build Toolbar. Run the mikroICD by selecting Run › Start Debugger from the drop-down menu or by clicking the Start Debugger Icon . Starting the Debugger makes more options available: Step Into, Step Over, Run to Cursor, etc.
mikroBasic PRO for PIC32 mikroICD Debugger Options Debugger Options Name Start Debugger Description Starts Debugger. Run/Pause Debugger Run/Pause Debugger. Stop Debugger Stop Debugger. Function Key F9 F6 Ctrl + F2 Step Into Executes the current program line, then halts. If the executed program line calls another routine, the debugger steps into the routine and halts after executing the first instruction within it. F7 Step Over Executes the current program line, then halts.
mikoBasic PRO for PIC32 mikroICD Debugger Example Here is a step-by-step mikroICD Debugger Example. First you have to write a program.
mikroBasic PRO for PIC32 After successful compilation and MCU programming press F9 to start the mikroICD. After the mikroICD initialization a blue active line should appear. We will debug the program line by line. Pressing [F8] we are executing code line by line. However, it is not 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.
mikoBasic PRO for PIC32 Step Into [F7], Step Over [F8] and Step Out [Ctrl+F8] are mikroICD debugger functions that are used in stepping mode. There is also a Real-Time mode supported by the mikroICD. Functions that are used in the Real-Time mode are Run/Pause Debugger [F6] and Run to cursor [F4]. Pressing F4 executes the code until the program reaches the cursor position line. Run(Pause) Debugger [F6] and Toggle Breakpoints [F5] are mikroICD debugger functions that are used in the RealTime mode.
mikroBasic PRO for PIC32 Breakpoints are divided into two groups: hardware and software breakpoints. The hardware breakpoints are placed in the MCU and provide fastest debugging. Number of hardware breakpoints is limited to 8 (6 instruction, 2 data). If all hardware brekpoints are used, then the next breakpoint will be software breakpoint. These breakpoints are placed inside the mikroICD and simulate hardware breakpoints. Software breakpoints are much slower than hardware breakpoints.
mikoBasic PRO for PIC32 mikroICD Debugger Windows Debug Windows This section provides an overview of available Debug Windows in mikroBasic PRO for PIC32: - Breakpoints Window - Watch Values Window - RAM Window - Stopwatch Window - EEPROM Watch Window - Code Watch Window 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.
mikroBasic PRO for PIC32 Also, it is possible to add all variables in the Watch Values Window by clicking button. To remove a variable from the Watch Values Window, just select the variable that you want to remove and then click the button, or press the Delete key. It is possible to remove all variables from the Watch Values Window by clicking button. You can also expand/collapse complex variables i.e.
mikoBasic PRO for PIC32 RAM Window The RAM Window is available from the drop-down menu, View › Debug Windows › RAM. The RAM Window displays the map of MCU’s RAM, with recently changed items colored red. The user can edit and change the values in the RAM window. mikroICD Specific: RAM window content will be written to the MCU before the next instruction execution. Stopwatch Window The Software Simulator Stopwatch Window is available from the drop-down menu, View › Debug Windows › Stopwatch.
mikroBasic PRO for PIC32 Notes: - 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. - Stopwatch is available only when Software Simulator is selected as a debugger. EEPROM Watch Window Note: EEPROM Watch Window is available only when mikroICD is selected as a debugger.
mikoBasic PRO for PIC32 Code Watch Window Note: Code Watch Window is available only when mikroICD is selected as a debugger. To show the Code Watch Window, select Debug Windows › Code from the View drop-down menu. The Code Watch Window shows code (hex format) written into the MCU. There is one action button concerning the Code Watch Window: - Reads code from the MCU and loads it up into the Code Window. Code reading is resources consuming operation so the user should wait until the reading is over.
mikroBasic PRO for PIC32 CHAPTER 5 Software Simulator Overview 125 MikroElektronika
mikoBasic PRO for PIC32 Software Simulator The Source-level Software Simulator is an integral component of the mikroBasic PRO for PIC32 environment. It is designed to simulate operations of the Microchip PIC32 MCUs and assist the users in debugging code written for these devices.
mikroBasic PRO for PIC32 Software Simulator Debug Windows Debug Windows This section provides an overview of available Debug Windows in mikroBasic PRO for PIC32: - Breakpoints Window - Watch Values Window - RAM Window - Stopwatch Window - EEPROM Watch Window - Code Watch Window 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.
mikoBasic PRO for PIC32 Also, it is possible to add all variables in the Watch Values Window by clicking button. To remove a variable from the Watch Values Window, just select the variable that you want to remove and then click the button, or press the Delete key. It is possible to remove all variables from the Watch Values Window by clicking button. You can also expand/collapse complex variables i.e. struct type variables, strings, etc, by clicking the appropriate button ( or ) beside variable name.
mikroBasic PRO for PIC32 RAM Window The RAM Window is available from the drop-down menu, View › Debug Windows › RAM. The RAM Window displays the map of MCU’s RAM, with recently changed items colored red. The user can edit and change the values in the RAM window. mikroICD Specific: RAM window content will be written to the MCU before the next instruction execution. Stopwatch Window The Software Simulator Stopwatch Window is available from the drop-down menu, View › Debug Windows › Stopwatch.
mikoBasic PRO for PIC32 Notes: - 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. - Stopwatch is available only when Software Simulator is selected as a debugger. EEPROM Watch Window Note: EEPROM Watch Window is available only when mikroICD is selected as a debugger.
mikroBasic PRO for PIC32 Code Watch Window Note: Code Watch Window is available only when mikroICD is selected as a debugger. To show the Code Watch Window, select Debug Windows › Code from the View drop-down menu. The Code Watch Window shows code (hex format) written into the MCU. There is one action button concerning the Code Watch Window: - Reads code from the MCU and loads it up into the Code Window. Code reading is resources consuming operation so the user should wait until the reading is over.
mikoBasic PRO for PIC32 Software Simulator Debugger Options Debugger Options Name Start Debugger Description Starts Debugger. Run/Pause Debugger Run/Pause Debugger. Stop Debugger Stop Debugger. Function Key F9 F6 Ctrl + F2 Step Into Executes the current program line, then halts. If the executed program line calls another routine, the debugger steps into the routine and halts after executing the first instruction within it. F7 Step Over Executes the current program line, then halts.
mikroBasic PRO for PIC32 CHAPTER 6 mikroBasic PRO for PIC32 Specifics The following topics cover the specifics of mikroBasic PRO for PIC32 compiler: - Basic Standard Issues - Predefined Globals and Constants - Accessing Individual Bits - Interrupts - Linker Directives - Built-in Routines - Code Optimization 133 MikroElektronika
mikoBasic PRO for PIC32 GOTO Table If a certain routine is allocated on the address higher than 64kB and can not be accessed directly, a GOTO table is created just after the Interrupt Vector Table to enable this routine call. GOTO table comprises of addresses of those routines that are allocated on the addresses higher than 64kB. So, whenever a call is made to a routine which is not directly accessible, it jumps to an assigned GOTO table block which contains address of a desired routine.
mikroBasic PRO for PIC32 - sbit - bit - iv Related topics: Keywords, PIC32 Specific Predefined Globals and Constants To facilitate PIC32 programming, the mikroBasic PRO for PIC32 implements a number of predefined globals and constants. All PIC32 SFRs are implicitly declared as global variables of volatile word. These identifiers have an external linkage, and are visible in the entire project. When creating a project, the mikroBasic PRO for PIC32 will include an appropriate (*.
mikoBasic PRO for PIC32 Accessing Individual Bits The mikroBasic PRO for PIC32 allows you to access individual bits of 16-bit variables. It also supports sbit and bit data types. Lets use the Zero bit as an example. This bit is defined in the definition file of the particular MCU as: const Z = 1 dim Z_bit as sbit at SR.B1 To access this bit in your code by its name, you can write something like this: ‘ Clear Zero Bit SR.
mikroBasic PRO for PIC32 See Predefined Globals and Constants for more information on register/bit names. sbit type The mikroBasic PRO for PIC32 compiler has sbit data type which provides access to registers, SFRs, variables, etc. You can declare a sbit varible in a unit in such way that it points to a specific bit in SFR register: module MyModule dim Abit as sbit sfr external ‘ Abit is precisely defined in some external file, for example in the main program unit ... implements .... end.
mikoBasic PRO for PIC32 at keyword You can use the keyword “at” to make an alias to a variable, for example, you can write a library without using register names, and later in the main program to define those registers, for example: module MyModule dim PORTAlias as byte external ‘ here in the library we can use its symbolic name ... implements ... end. program MyProgram ... dim PORTAlias byte as at PORTB ‘ this is where PORTAlias is fully defined ... main: ... end.
mikroBasic PRO for PIC32 Interrupts The PIC32MX generates interrupt requests in response to interrupt events from peripheral modules. The Interrupt module exists external to the CPU logic and prioritizes the interrupt events before presenting them to the CPU. The PIC32MX Interrupts module includes the following features: - Up to 96 interrupt sources. - Up to 64 interrupt vectors. - Single and Multi-Vector mode operations. - Five external interrupts with edge polarity control. - Interrupt proximity timer.
mikoBasic PRO for PIC32 Interrupt Priorities In the Multi Vector Mode, the user is able to assign a group priority and group subpriority level to each of the interrupt vectors. The user-selectable priority levels range from 1 (the lowest priority) to 7 (the highest). If an interrupt priority is set to zero, the interrupt vector is disabled for both interrupt and wake-up purposes. Interrupt vectors with a higher priority level preempt lower priority interrupts.
mikroBasic PRO for PIC32 where: - iv - reserved word that inform the compiler that it is an interrupt service routine. - IVT_ADC - appropriate Interrupt Vector. - ilevel 7 - Interrupt priority level 7. - ics Interrupt Context Saving; Interrupt Context Saving can be performed in several ways: 1. ICS_SOFT - Context saving is carried out by the software. 2. ICS_SRS - Shadow Register set is use for context saving. 3. ICS_OFF - No context saving 4.
mikoBasic PRO for PIC32 Interrupt Example Here is a simple example of handling the interrupts from Timer1 (if no other interrupts are allowed): program Timer1_interrupt sub procedure Timer1Int() iv IVT_TIMER_1 ilevel 7 ics ICS_SRS T1IF_bit = 0 ‘ Clear T1IF LATB = not PORTB ‘ Invert PORTB end sub main: AD1PCFG = 0xFFFF TRISB = 0 LATB = 0xAAAA ‘ Initialize AN pins as digital ‘ initialize PORTB as output ‘ Initialize PORTB value TMR1 = 0 PR1 = 65000 ‘ reset timer value to zero ‘ Load period register T1IP0_
mikroBasic PRO for PIC32 Linker Directives mikroBasic PRO for PIC32 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. When using these directives, be sure to use them in proper memory segments, i.e. for functions it is the KSEG0 and for variables it is the KSEG1. Linker directives are used with the virtual addresses.
mikoBasic PRO for PIC32 org directive can be used with main routine too. For example: program Led_Blinking main: org 0x800 ... end ‘ main procedure starts at 0x800 Directive orgall Use the orgall directive to specify the address above which all routines and constants will be placed. Example: main: orgall(0x200) ‘ All the routines, constants in main program will be above the address 0x200 ... end. Built-in Routines The mikroBasic PRO for PIC32 compiler provides a set of useful built-in utility functions.
mikroBasic PRO for PIC32 - Delay_us - Delay_ms - Vdelay_ms - Vdelay_Advanced_ms - Delay_Cyc - Delay_Cyc_long - Clock_kHz - Clock_MHz - Get_Fosc_kHz - Get_Fosc_Per_Cyc - Reset - ClrWdt - DisableContextSaving - SetFuncCall - SetOrg - DoGetDateTime - DoGetVersion - KVA0_TO_KVA1 - KVA1_TO_KVA0 - KVA_TO_PA - PA_TO_KVA0 - PA_TO_KVA1 - CP0_Get - CP0_Set - EnableInterrupts - DisableInterrupts 145 MikroElektronika
mikoBasic PRO for PIC32 Lo Prototype Description sub function Lo(dim number as longint) as byte Function returns the lowest byte of number. Function does not interpret bit patterns of number – it merely returns 8 bits as found in register. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters Returns Requires Example Notes - number: input number Lowest 8 bits (byte) of number, bits 7..0.
mikroBasic PRO for PIC32 Higher Prototype Description sub function Higher(dim number as longint) as byte 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. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters Returns Requires Example Notes - number: input value Returns next to the highest byte of number, bits 16..
mikoBasic PRO for PIC32 LoWord Prototype Description sub function LoWord(dim val as longint) as word The function returns low word of val. The function does not interpret bit patterns of val – it merely returns 16 bits as found in register. Parameters: Parameters Returns Requires Example Notes - val: input value number Low word of val, bits 15..0. Nothing. d = 0x12345678; tmp = LoWord(d); // Equals 0x5678 LoWord(d) = 0xAAAA; // d equals 0x1234AAAA None.
mikroBasic PRO for PIC32 Inc Prototype Description Parameters Returns sub procedure Inc(dim byref par as longint) Increases parameter par by 1. - par: value which will be incremented by 1 Nothing. Requires Nothing. Example p = 4 Inc(p) Notes ‘ p is now 5 None. Dec Prototype Description Parameters Returns sub procedure Inc(dim byref par as longint) Increases parameter par by 1. - par: value which will be incremented by 1 Nothing. Requires Nothing.
mikoBasic PRO for PIC32 Ord Prototype Description sub function Ord(dim character as char) as byte Function returns ASCII code of the character. This is an “inline” routine; the code is generated in the place of the call. Parameters Returns Requires - character: input character ASCII code of the character. Nothing. Example c = Ord(“A”) Notes None. ‘ returns 65 SetBit Prototype Description sub procedure SetBit(dim byref register_ as word, dim rbit as byte) Function sets the bit rbit of register_.
mikroBasic PRO for PIC32 TestBit Prototype Description sub function TestBit(dim register_, rbit as byte) as byte Function tests if the bit rbit of register is set. If set, function returns 1, otherwise returns 0. Parameter rbit needs to be a variable or literal with value 0..7. See Predefined globals and constants for more information on register identifiers. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit.
mikroBasic PRO for PIC32 Delay_ms Prototype Description sub procedure Delay_ms(const time_in_ms as longword) Creates a software delay in duration of time_in_ms milliseconds. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters time_in_ms: delay time in milliseconds. Valid values: constant values, range of applicable constants depends on the oscillator frequency Returns Nothing. Requires Nothing.
mikoBasic PRO for PIC32 VDelay_Advanced_ms Prototype Description sub procedure VDelay_advanced_ms(dim time_ms, Current_Fosc_kHz as word) Creates a software delay in duration of time_in_ms milliseconds (a variable), for a given oscillator frequency. Generated delay is not as precise as the delay created by Delay_ms. Note that Vdelay_ms is library function rather than a built-in routine; it is presented in this topic for the sake of convenience.
mikroBasic PRO for PIC32 Clock_kHz Prototype Description sub function Clock_kHz() as longint Function returns device clock in kHz, rounded to the nearest integer. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters None. Returns Device clock in kHz, rounded to the nearest integer. Requires Nothing. Example clk = Clock_kHz(); Notes None.
mikoBasic PRO for PIC32 Get_Fosc_Per_Cyc Prototype Description sub function Get_Fosc_Per_Cyc() as word Function returns device’s clock per cycle, rounded to the nearest integer. Note that Get_Fosc_Per_Cyc is library function rather than a built-in routine; it is presented in this topic for the sake of convenience. Parameters None. Returns Device’s clock per cycle, rounded to the nearest integer. Requires Nothing. Example dim clk_per_cyc as word ... clk_per_cyc = Get_Fosc_Per_Cyc() Notes None.
mikoBasic PRO for PIC32 DisableContextSaving Prototype Description sub procedure DisableContextSaving() Use the DisableContextSaving() to instruct the compiler not to automatically perform contextswitching. This means that no register will be saved/restored by 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. Parameters None. Returns Nothing.
mikroBasic PRO for PIC32 SetOrg Prototype Description Parameters Returns sub procedure SetOrg(dim RoutineName as string, dim address as longint) Use the SetOrg() routine to specify the starting address of a routine in ROM. - RoutineName: routine name - address: starting address Nothing. Requires This routine must be called from main. Example SetOrg(UART1_Write, 0x1234) Notes None.
mikoBasic PRO for PIC32 KVA0_TO_KVA1 Prototype Description sub function KVA0_TO_KVA1(dim Address as longword) as longword Function converts virtual address from KSEG0 to the virtual address in the KSEG1. Parameters Desired Virtual address in the KSEG0. Returns Virtual address in the KSEG1. Requires Nothing. Example address = KVA0_TO_KVA1(0x9FC00000) Notes None.
mikroBasic PRO for PIC32 PA_TO_KVA0 Prototype Description sub function PA_TO_KVA0(dim Address as longword) as longword Function converts physical address to the virtual address in the KSEG0. Parameters Desired physical address. Returns Appropriate virtual address in the KSEG0. Requires Nothing. Example address = PA_TO_KVA0(0x1D000000) Notes None.
mikoBasic PRO for PIC32 CP0_SET Prototype Description Parameters Returns sub procedure longword) CP0_SET(dim const register as TCP0REG, dim as Value Function sets the value of the coprocessor register or part of the register, based upon the register argument. - register: Register or register part, must be a constant from the enumerated built-in constants list, which can be found at the bottom of this page. - value: Register Value. Nothing. Requires Nothing.
mikroBasic PRO for PIC32 Copressor Register Fields CP0_HWRENA_MASK CP0_STATUS_IE CP0_STATUS_EXL CP0_STATUS_ERL CP0_STATUS_UM CP0_STATUS_IM0 CP0_STATUS_IM1 CP0_STATUS_IPL CP0_STATUS_IM2 CP0_STATUS_IM3 CP0_STATUS_IM4 CP0_STATUS_IM5 CP0_STATUS_IM6 CP0_STATUS_IM7 CP0_STATUS_CEE CP0_STATUS_NMI _CPO_STATUS_SR CP0_STATUS_TS CP0_STATUS_BEV CP0_STATUS_RE CP0_STATUS_FR CP0_STATUS_RP CP0_STATUS_CU0 CP0_STATUS_CU1 CP0_STATUS_CU2 CP0_STATUS_CU3 CP0_INTCTL_VS CP0_INTCTL_IPPCI CP0_INTCTL_IPTI
mikoBasic PRO for PIC32 Code Optimization Optimizer has been added to extend the compiler usability, cut down the amount of code generated and speed-up its execution. The main features are: Constant folding All expressions that can be evaluated in the compile time (i.e. constant) are being replaced by their results.
mikroBasic PRO for PIC32 Single Static Assignment Optimization Introduction In compiler design, static single assignment form (often abbreviated as SSA form or SSA) is an intermediate representation (IR) in which every variable is assigned exactly once. An SSA-based compiler modifies the program representation so that every time a variable is assigned in the original program, a new version of the variable is created.
mikoBasic PRO for PIC32 0x9D000004 0x9D000008 L__SSA_Test7: 0x10400002 0x70000000 BEQ NOP R2, R0, L__SSA_Test2 Without SSA enabled, sub procedure SSA_Test this example is consisted of 5 asm instructions : ;Example.
mikroBasic PRO for PIC32 Asm code and SSA optimization If converting code from an earlier version of the compiler, which consists of mixed asm code with the C code, keep in mind that the generated code can substantially differ when SSA optimization option is enabled or disabled. This is due to the fact that SSA optimization uses certain working registers to store routine parameters (W10-W13), rather than storing them onto the function frame.
CHAPTER 7 mikoBasic PRO for PIC32 PIC32 Specifics In order to get the most from the mikroBasic PRO for PIC32 compiler, the user should be familiar with certain aspects of PIC32 MCU. This knowledge is not essential, but it can provide a better understanding of the PIC32’s capabilities and limitations, and their impact on the code writing as well.
mikroBasic PRO for PIC32 Types Efficiency First of all, the user should know that PIC32’s ALU, which performs arithmetic operations, is optimized for working with 32-bit types. Also, it performs hardware multiplication and division on the integer level, so the floating multiplication and division is slower and consumes more memory comparing it to the integer. The PIC32 supports 64-bit data types, but they are less efficient. They provide higher precision, but lack the code size and the execution.
mikoBasic PRO for PIC32 PIC32 Memory Organization The PIC32MX microcontrollers provide 4 GB of unified virtual memory address space. All memory regions, including program memory, data memory, SFRs and Configuration registers reside in this address space at their respective unique addresses. The program and data memories can be optionally partitioned into user and kernel memories. In addition, the data memory can be made executable, allowing the PIC32MX to execute from data memory.
mikroBasic PRO for PIC32 PIC32MX Memory Layout The PIC32MX microcontrollers implement two address spaces: virtual and physical. All hardware resources, such as program memory, data memory and peripherals, are located at their respective physical addresses. Peripherals, such as DMA and Flash controllers, use physical addresses and access memory independently of the CPU. Virtual addresses are exclusively used by the CPU to fetch and execute instructions.
mikoBasic PRO for PIC32 As it can be seem, the entire 4 GB virtual address space is divided into two primary regions: User and Kernel space. The lower 2 GB of space called USEG/KUSEG, and the upper 2 GB are divided into KSEG0, KSEG1, KSEG2 and KSEG3. Virtual vs Physical Addresses The PIC32MX’s CPU uses virtual addresses to address the peripherals, which means that to access the PIC32MX’s peripherals we (and the CPU) must be operating within the virtual boundaries of KSEG1.
mikroBasic PRO for PIC32 Memory Type Specifiers The mikroBasic PRO for PIC32 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 (reserved for compiler purposes only) - sfr code Description The code memory type may be used for allocating constants in program memory.
mikoBasic PRO for PIC32 Read Modify Write Problem The Microchip microcontrollers use a sequence known as Read-Modify-Write (RMW) when changing an output state (1 or 0) on a pin. This can cause unexpected behavior under certain circumstances. When your program changes the state on a specific pin, for example RB0 in PORTB, the microcontroller first READs all 8 bits of the PORTB register which represents the states of all 8 pins in PORTB (RB7-RB0). The microcontroller then stores this data in the MCU.
mikroBasic PRO for PIC32 Actual voltage levels on MCU pins are relevant. MODIFY Data is modified to set the RB0 bit: WRITE PORTB is written with the modified data. The output driver for RB0 turns on, and the capacitor starts to charge: The second line, PORTB.
mikoBasic PRO for PIC32 To correct the problem in the code, insert a delay after each PORTB.Bx = 1 line, or modify the entire PORTB register in a single line PORTB = 0b00000011. This problem can be avoided by using LATx register when writing to ports, rather than using PORTx registers. Writing to a LATx register is equivalent to writing to a PORTx register, but readings from LATx registers return the data value held in the port latch, regardless of the state of the actual pin.
mikroBasic PRO for PIC32 The second line, LATB.B1 = 1; will be decoded like in this way: READ LATB is read: STORE Since the voltage levels on MCU pins are no longer relevant, we get the expected value: Actual voltage levels on MCU pins are no longer relevant when using LATx for output MODIFY Data is modified to set the bit: WRITE LATB is written with the new data.
CHAPTER 8 mikroBasic PRO for Language Reference MikroElektronika mikoBasic PRO for PIC32 PIC32 176
mikroBasic PRO for PIC32 - 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 Precedenc
mikoBasic PRO for PIC32 - 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 Lexical Elements Overview The following topics provide a formal definit
mikoBasic PRO for PIC32 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 word and dim dim tmp j as as byte word are lexically equivalent and parse identically.
mikroBasic PRO for PIC32 Comments Comments are pieces of text used to annotate a program, and are technically another form of whitespace. Comments are for the programmer’s use only; they are stripped from the source text before parsing. Use the apostrophe to create a comment: ‘ Any text between an apostrophe and the end of the ‘ line constitutes a comment. May span one line only. There are no multi-line comments in mikroBasic PRO for PIC32.
mikroBasic PRO for PIC32 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. Long and Unsigned Suffixes 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.
mikoBasic PRO for PIC32 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.
mikoBasic PRO for PIC32 Keywords Keywords are special-purpose words which cannot be used as normal identifier names. Beside standard BASIC keywords, all relevant SFR are defined as global variables and represent reserved words that cannot be redefined (for example: P0, TMR1, T1CON, etc). Probe Code Assistant for specific letters (Ctrl+Space in Editor) or refer to Predefined Globals and Constants.
mikroBasic PRO for PIC32 - 184 forward goto helper idata if ilevel implementation implements in index inherited initialization inline interface io is iv label library message mod name near nil nodefault not object of on operator or org out overload override package packed pascal pdata platform private procedure program property protected public published raise read readonly record register MikroElektronika
mikroBasic PRO for PIC32 - reintroduce repeat requires rx safecall sbit sealed set sfr shl shr small stdcall stored string threadvar to try type unit until uses var virtual volatile while with write writeonly xdata xor ydata Also, mikroBasic PRO for PIC32 includes a number of predefined identifiers used in libraries. You can replace them by your own definitions, if you plan to develop your own libraries. For more information, see mikroBasic PRO for PIC32 Libraries.
mikoBasic PRO for PIC32 Uniqueness and Scope Although identifier names are arbitrary (within the rules stated), errors result if the same name is used for more than one identifier within the same scope. Simply, duplicate names are illegal within the same scope. For more information, refer to Scope and Visibility. Identifier Examples Here are some valid identifiers: temperature_V1 Pressure no_hit dat2string SUM3 _vtext … and here are some invalid identifiers: 7temp %higher int j23.07.
mikroBasic PRO for PIC32 Parentheses Parentheses ( ) are used to group expressions, isolate conditional expressions, and indicate function calls and function parameters: d = c * (a + b) if (d = z) then ... func() sub function func2(dim n as word) ‘ ‘ ‘ ‘ Override normal precedence Useful with conditional statements Function call, no arguments Function declaration w/ parameters For more information, refer to Operators Precedence and Associativity, Expressions and Functions and Procedures.
mikoBasic PRO for PIC32 Program Organization mikroBasic PRO for PIC32 imposes strict program organization. Below you can find models for writing legible and organized source files. For more information on file inclusion and scope, refer to Modules and to Scope and Visibility. Organization of Main Module Basically, the main source file has two sections: declaration and program body. Declarations should be in their proper place in the code, organized in an orderly manner.
mikroBasic PRO for PIC32 Organization of Other Modules Modules other than main start with the keyword module. Implementation section starts with the keyword implements. Follow the model presented below: module include ‘******************************************************** ‘* Interface (globals): ‘******************************************************** ‘ symbols declarations symbol ... ‘ constants declarations const ... ‘ structures declarations structure ...
mikoBasic PRO for PIC32 ‘ 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] ... 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.
mikroBasic PRO for PIC32 Name Spaces Name space is a scope within which an identifier must be unique. The mikroBasic PRO for PIC32 uses two distinct categories of identifiers: 1. Global variables are visible throughout the whole unit, from the place of declaration. Also. they can be seen in other units, if they are declared above the Implementation section. 2. Local variables, parameters, types, function results - must be unique within the block in which they are declared.
mikoBasic PRO for PIC32 Here’s an example: program MyProgram include “utils” include “strings” include “MyUnit” ... For the given module name, the compiler will check for the presence of .emcl and .mbas files, in order specified by search paths. - If both .mbas and .emcl 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 .emcl, then .mbas file will be recompiled and new .emcl will be created, overwriting the old .emcl.
mikroBasic PRO for PIC32 Interface Section Part of the module above the keyword implements is referred to as interface section. Here, you can place global declarations (constants, variables, labels, routines, structures) for the project. Do not define routines in the interface section. Instead, state the prototypes of routines (from implementation section) that you want to be visible outside the module. Prototypes must exactly match the declarations.
mikoBasic PRO for PIC32 For example, lets create a project which will calculate circle area and will have sub function and sub procedure definition in two different modules, and a call to these routines in the third, separate module. So, the project will be consisted of the main module, Main_Module.mpas and First_Module.mpas and Second_ Module.mpas modules. In the Main_Module we will define routine called r_squared (calculates radius squared).
mikroBasic PRO for PIC32 sub procedure CircleArea() ‘ Definition of the CircleArea routine dim res as real res = r_square(5) ‘ Calculate r*r pi_r_square(res) ‘ Calculate pi*r*r end sub end. Variables and PIC32 Every declared variable consumes part of RAM memory. Data type of variable determines not only the allowed range of values, but also the space a variable occupies in RAM memory. Bear in mind that operations using different types of variables take different time to be completed.
mikoBasic PRO for PIC32 Labels Labels serve as targets for 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 PIC32. 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.
mikroBasic PRO for PIC32 ‘... main: if cnt > MAXALLOWED then cnt = 0 PORT.1 = 0 MYDELAY end if Note: Symbols do not support macro expansion in a way the C preprocessor does. Functions and Procedures Functions and procedures, collectively referred to as routines, are subprograms (self-contained statement blocks) which perform a certain task based on a number of input parameters. When executed, a function returns value while procedure does not.
mikoBasic PRO for PIC32 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.
mikroBasic PRO for PIC32 Example Here’s an example procedure which transforms its input time parameters, preparing them for output on Lcd: sub procedure time_prep(dim byref sec, min, sec = ((sec and $F0) >> 4)*10 + (sec and min = ((min and $F0) >> 4)*10 + (min and hr = ((hr and $F0) >> 4)*10 + (hr and end sub hr as byte) $0F) $0F) $0F) 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.
mikoBasic PRO for PIC32 program Volume dim Volume as word sub function First(dim a as word, dim b as word) as word forward sub function Second(dim c as word) as word dim tmp as word tmp = First(2, 3) result = tmp * c end sub sub function First(dim a, b as word) as word result = a * b end sub main: Volume = Second(4) end. Functions reentrancy Functions reentrancy is allowed. Remember that the PIC32 have memory limitations that can vary between MCUs.
mikroBasic PRO for PIC32 Types Basic is strictly typed language, which means that every variable and constant need to have a strictly defined type, known at the time of compilation. The type serves: - to determine the 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.
mikoBasic PRO for PIC32 Derived Types The derived types are also known as structured types. They are used as elements in creating more complex userdefined types. The derived types include: - arrays - pointers - structures Arrays An array represents an indexed collection of elements of the same type (called the base type). Since each element has a unique index, arrays, unlike sets, can meaningfully contain the same value more than once.
mikroBasic PRO for PIC32 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. Multi-dimensional Arrays Multidimensional arrays are constructed by declaring arrays of array type. These arrays are stored in memory in such way that the right most subscript changes fastest, i.e. arrays are stored “in rows”.
mikoBasic PRO for PIC32 Be careful when handling strings in this way, since overwriting the end of a string will cause an unpredictable behavior. Array of string is declared in this manner: typedef str as string[5] ‘ first, declare str as a string of 5 elements dim buffer as str[5] ‘ now, declare buffer as a array of str elements String Concatenating mikroBasic PRO for PIC32 allows you to concatenate strings by means of plus operator.
mikroBasic PRO for PIC32 Pointers A pointer is a data type which holds a memory address. While a variable accesses that memory address directly, a pointer can be thought of as a reference to that memory address. To declare a pointer data type, add a carat prefix (^) before type. For example, in order to create a pointer to an integer, write: ^integer In order to access data at the pointer’s memory location, add a carat after the variable name.
mikoBasic PRO for PIC32 This leads to equality of the following declarations: dim ptr1 as ^const byte ‘ ptr1 pointer in data space pointing to a byte in code space const ptr1 as ^byte ‘ ptr1 pointer in data space pointing to a byte in code space Therefore, when declaring a pointer within constant declaration block, const qualifier refers to pointed object, not to pointer itself. Notes: - Pointer to constant space (Flash memory) is allocated in RAM.
mikroBasic PRO for PIC32 Sample = MyPtr^(1, 2, 3) ‘ Perform function call via pointer, call Func1, the return value is 3 MyPtr = @Func2 ‘ MyPtr now points to Func2 Sample = MyPtr^(1, 2, 3) ‘ Perform function call via pointer, call Func2, the return value is 5 MyPtr = @Func3 ‘ MyPtr now points to Func3 Sample = MyPtr^(1, 2, 3) ‘ Perform function call via pointer, call Func3, the return value is 0 end. @ Operator The @ operator constructs a pointer to its operand.
mikoBasic PRO for PIC32 Pointer Arithmetic Pointer arithmetic in the mikroBasic PRO for PIC32 is limited to: - assigning one pointer to another, - comparing two pointers, - comparing pointer to zero, - adding/subtracting pointer and an integer value, - subtracting two pointers. Assignment and Comparison The simple assignment operator (=) can be used to assign value of one pointer to another if they are of the same type. Assigning the integer constant 0 to a pointer assigns a null pointer value to it.
mikroBasic PRO for PIC32 Pointer Addition You can use Inc to add an integral value to a pointer. The result of addition is defined only if the pointer points to an element of an array and if the result is a pointer pointing to the same array (or one element beyond it). If a pointer is declared to point to type, adding an integral value n to the pointer increments the pointer value by n * sizeof(type) as long as the pointer remains within the legal range (first element to one beyond the last element).
mikoBasic PRO for PIC32 For example: dim a as byte[10] ptr as ^byte ‘ array a containing 10 elements of type byte ‘ pointer to byte main: ptr = @a[6] ptr = ptr - 3 ptr^ = 6 Dec(ptr) end. ‘ ‘ ‘ ‘ ptr is pointer to byte, pointing to a[6] ptr-3 is a pointer pointing to a[3] a[3] now equals 6 ptr now points to the previous element of array a: a[2] Also, you may subtract two pointers.
mikroBasic PRO for PIC32 For example, the following declaration creates a structure type called Dot: structure Dot dim x as float dim y as float end structure Each Dot contains two members: x and y coordinates; memory is allocated when you instantiate the structure, like this: dim m, n as Dot This variable declaration creates two instances of Dot, called m and n. A member can be of the previously defined structure type.
mikoBasic PRO for PIC32 Types Conversions Conversion of variable of one type to a variable of another type is typecasting. mikroBasic PRO for PIC32 supports both implicit and explicit conversions for built-in types.
mikroBasic PRO for PIC32 Explicit Conversion Explicit conversion can be executed at any point by inserting type keyword (byte, word, short, integer, longint, or float) ahead of the expression to be converted. The expression must be enclosed in parentheses. Explicit conversion can be performed only on the operand left of the assignment operator. Special case is the conversion between signed and unsigned types.
mikoBasic PRO for PIC32 Typedef Specifier The specifier typedef introduces a synonym for a specified type. The typedef declarations are used to construct shorter or more convenient names for types already defined by the language or declared by the user. The specifier typedef stands first in the declaration: typedef synonym as The typedef keyword assigns synonym to . The synonym needs to be a valid identifier.
mikroBasic PRO for PIC32 Qualifier volatile The qualifier volatile implies that a variable may change its value during runtime independently from the program. Use the volatile modifier to indicate that a variable can be changed by a background routine, an interrupt routine, or I/O port. Declaring an object to be volatile warns the compiler not to make assumptions concerning the value of an object while evaluating expressions in which it occurs because the value could be changed at any moment.
mikoBasic PRO for PIC32 Arithmetic Operators Arithmetic operators are used to perform mathematical computations. They have numerical operands and return numerical results. Since the char operators are technically bytes, they can be also used as unsigned operands in arithmetic operations. All arithmetic operators associate from left to right.
mikroBasic PRO for PIC32 Relational Operators Use relational operators to test equality or inequality of expressions. All relational operators return TRUE or FALSE. All relational operators associate from left to right. Relational Operators Overview Operator Operation == equal <> not equal > greater than < less than >= greater than or equal <= less than or equal Relational Operators in Expressions The equal sign (=) can also be an assignment operator, depending on context.
mikoBasic PRO for PIC32 Bitwise Operators 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.
mikroBasic PRO for PIC32 Unsigned and Conversions If a number is converted from less complex to more complex data type, the upper bytes are filled with zeroes. If a number is converted from more complex to less complex data type, the data is simply truncated (the upper bytes are lost). For example: dim a dim b ‘ ...
mikoBasic PRO for PIC32 Boolean Operators Although mikroBasic PRO for PIC32 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 Operation and logical AND xor logical exclusive OR (XOR) or logical OR not logical negation Unary Operators Unary operators are operators that take exactly one argument.
mikroBasic PRO for PIC32 See Pointers for more details on this subject Note: Besides these, sizeof and explicit conversion unary operators are supported also. Sizeof Operator The prefix unary operator sizeof returns an integer constant that represents the size of memory space (in bytes) used by its operand (determined by its type, with some exceptions). The operator sizeof can take either a type identifier or an unary expression as an operand.
mikoBasic PRO for PIC32 Expressions An expression is a sequence of operators, operands and punctuators that returns a value. The primary expressions include: literals, constants, variables and function calls. From them, using operators, more complex expressions can be created. Formally, expressions are defined recursively: subexpressions can be nested up to the limits of memory.
mikroBasic PRO for PIC32 if b*5 then... ‘ byte level - general rule will not give same result as a = b * 5 if a then... ‘ word level - general rule + left side exception if b*5 exceeds byte range. Explicit Typecasting Any expression can be evaluated at specific level by using explicit typecasting. Having in mind previous example, in order to get same calculation in conditional and assignment expression, the following should be done: if word(b*5) then...
mikoBasic PRO for PIC32 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.
mikroBasic PRO for PIC32 In order to force the compiler to interpret our example the other way around, we have to write it explicitly: if expression1 then if expression2 then statement1 end if else statement2 end if Select Case Statement Use the select case statement to pass control to a specific program branch, based on a certain condition. The select case statement consists of selector expression (condition) and list of possible values.
mikoBasic PRO for PIC32 Also, you can group values together for a match. Simply separate the items by commas: select case reg case 0 opmode = 0 case 1,2,3,4 opmode = 1 case 5,6,7 opmode = 2 end select Nested switch Note that the select case statements can be nested – values are then assigned to the innermost enclosing select case statement. Iteration Statements (Loops) Iteration statements let you loop a set of statements.
mikroBasic PRO for PIC32 If final_value is a complex expression whose value can not be calculated in compile time and number of loop iterations is not to be changed inside the loop by the means of final_value, it should be calculated outside the for statement and result should be passed as for statement’s final_value. statement_list is a list of statements that do not change the value of counter.
mikoBasic PRO for PIC32 Do Statement The do statement executes until the condition becomes true. The syntax of the do statement is: do statements loop until expression statements are executed repeatedly until expression evaluates true. expression is evaluated after each iteration, so the loop will execute statements at least once.
mikroBasic PRO for PIC32 end if Delay_ms(1000) wend ‘ Now we can work with CF card ...
mikoBasic PRO for PIC32 Here is a simple example: sub procedure Proc1() dim error as byte ... ‘ we’re doing something here if error = TRUE then return end if ... ‘ some code, which won’t be executed if error is true end sub Note: Return statements performs the same as exit statement except in functions. If breaking out of a function with return statement, return value will not be specified. In such cases exit statement should be used.
mikroBasic PRO for PIC32 Gosub Statement Use the gosub statement to unconditionally jump to a local label — for more information, refer to Labels. The syntax of the gosub statement is: gosub label_name ... label_name: ... return This will transfer control to the location of a local label specified by label_name. Also, the calling point is remembered. Upon encountering the return statement, program execution will continue with the next statement (line) after gosub.
mikoBasic PRO for PIC32 - Accessing local variable: _. - Accessing routine parameter: FARG__.
mikroBasic PRO for PIC32 Directives Directives are words of special significance which provide additional functionality regarding compilation and output. The following directives are at your disposal: - Compiler directives for conditional compilation, - Linker directives for object distribution in memory. Compiler Directives Any line in source code with leading # is taken as a compiler directive. The initial # can be preceded or followed by whitespace (excluding new lines).
mikoBasic PRO for PIC32 Here is an example: ‘ Uncomment the appropriate flag for your application: ‘#DEFINE resolution10 ‘#DEFINE resolution12 #IFDEF resolution10 THEN // #ELSE #IFDEF resolution12 THEN // #ELSE // #ENDIF #ENDIF Unlike #IFDEF, #IFNDEF checks if flag is not defined by means of #DEFINE, thus producing the opposite results.
mikroBasic PRO for PIC32 Explicit Path mikroBasic PRO for PIC32 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. When using these directives, be sure to use them in proper memory segments, i.e. for functions it is the KSEG0 and for variables it is the KSEG1. Linker directives are used with the virtual addresses.
mikoBasic PRO for PIC32 In first case, compiler will recognize your attempt, but in order to save Flash space, and boost performance, it will automatically replace all instances of this constant in code with it’s literal value. In the second case your constant will be placed in Flash in the exact location specified. To place a routine on a specific address in Flash memory you should write the following: sub procedure proc(dim par as word) org 0x9D000000 ‘ Procedure will start at the address 0x9D000000; ...
mikroBasic PRO for PIC32 CHAPTER 9 mikroBasic Libraries PRO for PIC32 mikroBasic PRO for PIC32 provides a set of libraries which simplify the initialization and use of PIC32 and their modules: Use Library manager to include mikroBasic PRO for PIC32 Libraries in you project.
mikoBasic PRO for PIC32 Hardware Libraries - ADC Library - CANSPI Library - Compact Flash Library - Epson S1D13700 Graphic Lcd Library - Flash Memory Library - Graphic Lcd Library - I²C Library - Keypad Library - Lcd Library - Manchester Code Library - Memory Manager Library - Multi Media Card Library - OneWire Library - Peripheral Pin Select Library - Port Expander Library - PS/2 Library - PWM Library - RS-485 Library - Software I²C Library - Software SPI Library - Software UART Library - Sound Library -
mikroBasic PRO for PIC32 Hardware Libraries - ADC Library - CANSPI Library - Compact Flash Library - Epson S1D13700 Graphic Lcd Library - Flash Memory Library - Graphic Lcd Library - I²C Library - Keypad Library - Lcd Library - Manchester Code Library - Memory Manager Library - Multi Media Card Library - OneWire Library - Peripheral Pin Select Library - Port Expander Library - PS/2 Library - PWM Library - RS-485 Library - Software I²C Library - Software SPI Library - Software UART Library - Sound Library -
mikoBasic PRO for PIC32 Library Routines - ADCx_Init - ADCx_Init_Advanced - ADCx_Get_Sample - ADCx_Read ADCx_Init Prototype sub procedure ADC1_Init() Description This routines configures ADC module to work with default settings. The internal ADC module is set to: - single channel conversion - 10-bit conversion resolution - unsigned integer data format - auto-convert - VRef+ : AVdd, VRef- : AVss - instruction cycle clock - conversion clock : 32*Tcy - auto-sample time : 31TAD Parameters None.
mikroBasic PRO for PIC32 ADCx_Get_Sample Prototype sub function ADC1_Get_Sample(dim channel as word) as word Description The function enables ADC module and reads the specified analog channel input. Parameters - channel represents the channel from which the analog value is to be acquired. Returns Requires Example Notes 10-bit unsigned value from the specified channel. - The MCU with built-in ADC module. - Prior to using this routine, ADC module needs to be initialized.
mikoBasic PRO for PIC32 Library Example This code snippet reads analog value from the channel 1 and sends readings as a text over UART1.
mikroBasic PRO for PIC32 CANSPI Library The SPI module is available with a number of the PIC32 MCUs. The mikroBasic PRO for PIC32 provides a library (driver) for working with mikroElektronika’s CANSPI Add-on boards (with MCP2515 or MCP2510) via SPI interface. The CAN is a very robust protocol that has error detection and signalization, self–checking and fault confinement. Faulty CAN data and remote frames are re-transmitted automatically, similar to the Ethernet.
mikoBasic PRO for PIC32 Library Routines - CANSPISetOperationMode - CANSPIGetOperationMode - CANSPIInit - CANSPISetBaudRate - CANSPISetMask - CANSPISetFilter - CANSPIRead - CANSPIWrite CANSPISetOperationMode Prototype sub procedure CANSPISetOperationMode(dim mode as byte, dim WAIT as byte) Description Sets the CANSPI module to requested mode. Parameters mode: CANSPI module operation mode. Valid values: CANSPI_OP_MODE constants. See CANSPI_ OP_MODE constants.
mikroBasic PRO for PIC32 CANSPIGetOperationMode Prototype sub function CANSPIGetOperationMode() as byte Description The function returns current operation mode of the CANSPI module. Check CANSPI_OP_MODE constants or device datasheet for operation mode codes. Parameters None. Returns Current operation mode. 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.
mikoBasic PRO for PIC32 Requires Global variables: - CanSpi_CS: Chip Select line - CanSpi_Rst: Reset line - CanSpi_CS_Direction: Direction of the Chip Select pin - CanSpi_Rst_Direction: Direction of the Reset pin 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 SPIx_Init and SPIx_Init_Advanced routines. MCU has to be properly connected to mikroElektronika’s CANSPI Extra Board or similar hardware.
mikroBasic PRO for PIC32 CANSPISetBaudRate Prototype Returns sub procedure CANSPISetBaudRate(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CANSPI_CONFIG_FLAGS as byte) Nothing. Description Sets the CANSPI module baud rate. Due to complexity of the CAN protocol, you can not simply force a bps value. Instead, use this function when the CANSPI module is in Config mode. SAM, SEG2PHTS and WAKFIL bits are set according to CANSPI_CONFIG_FLAGS value. Refer to datasheet for details.
mikoBasic PRO for PIC32 CANSPISetMask Prototype sub procedure CANSPISetMask(dim CANSPI_MASK as byte, dim val as longint, dim CANSPI_CONFIG_FLAGS as byte) Description Configures mask for advanced filtering of messages. The parameter value is bit-adjusted to the appropriate mask registers. Parameters - CANSPI_MASK: CAN module mask number. Valid values: CANSPI_MASK constants. See CANSPI_ MASK constants. - val: mask register value.
mikroBasic PRO for PIC32 CANSPISetFilter Prototype sub procedure CANSPISetFilter(dim CAN_FILTER as byte, dim val as longint, dim CANSPI_CONFIG_FLAGS as byte) Description Configures message filter. The parameter value is bit-adjusted to the appropriate filter registers. Parameters - CANSPI_FILTER: CAN module filter number. Valid values: CANSPI_FILTER constants. See CANSPI_FILTER constants. - val: filter register value.
mikoBasic PRO for PIC32 CANSPIRead Prototype sub function CANSPIRead(dim byref id as longint, dim byref Data_ as byte[8], dim byref DataLen as byte, dim byref CAN_RX_MSG_FLAGS as byte) as byte Description 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 data parameter - Message length is retrieved and stored to location pr
mikroBasic PRO for PIC32 CANSPIWrite Prototype sub function CANSPIWrite(dim id as longint, dim byref Data_ as byte[8], dim DataLen, CANSPI_TX_MSG_FLAGS as byte) as byte Description If at least one empty Transmit Buffer is found, the function sends message in the queue for transmission. Parameters - id: CAN message identifier. Valid values: 11 or 29 bit values, depending on message type (standard or extended) - Data: data to be sent - DataLen: data length. Valid values: 0..
mikoBasic PRO for PIC32 Copy Code To Clipboard const _CANSPI_MODE_BITS _CANSPI_MODE_NORMAL _CANSPI_MODE_SLEEP _CANSPI_MODE_LOOP _CANSPI_MODE_LISTEN _CANSPI_MODE_CONFIG as as as as as as byte byte byte byte byte byte = = = = = = $E0 0 $20 $40 $60 $80 Use this to access opmode bits CANSPI_CONFIG_FLAGS Constants The CANSPI_CONFIG_FLAGS constants define flags related to the CANSPI module configuration.
mikroBasic PRO for PIC32 You may use bitwise and to form config byte out of these values. For example: Copy Code To Clipboard init = _CANSPI_CONFIG_SAMPLE_THRICE _CANSPI_CONFIG_PHSEG2_PRG_ON _CANSPI_CONFIG_STD_MSG _CANSPI_CONFIG_DBL_BUFFER_ON _CANSPI_CONFIG_VALID_XTD_MSG _CANSPI_CONFIG_LINE_FILTER_OFF ...
mikoBasic PRO for PIC32 Copy Code To Clipboard const _CANSPI_RX_FILTER_BITS _CANSPI_RX_FILTER_1 _CANSPI_RX_FILTER_2 _CANSPI_RX_FILTER_3 _CANSPI_RX_FILTER_4 _CANSPI_RX_FILTER_5 _CANSPI_RX_FILTER_6 _CANSPI_RX_OVERFLOW _CANSPI_RX_INVALID_MSG _CANSPI_RX_XTD_FRAME _CANSPI_RX_RTR_FRAME _CANSPI_RX_DBL_BUFFERED buffered as as as as as as as byte byte byte byte byte byte byte = = = = = = = $07 $00 $01 $02 $03 $04 $05 ‘ Use this to access filter bits as as as as as byte byte byte byte byte = = = = = $08 $10
mikroBasic PRO for PIC32 Library Example The code is a simple demonstration of CANSPI protocol. This node initiates the communication with the 2nd node by sending some data to its address. The 2nd node responds by sending back the data incremented by 1. This (1st) node then does the same and sends incremented data back to the 2nd node, etc.
mikoBasic PRO for PIC32 CANSPISetMask(_CANSPI_MASK_B2,-1,_CANSPI_CONFIG_XTD_MSG) ‘ set all mask2 bits to ones CANSPISetFilter(_CANSPI_FILTER_B2_F4,ID_2nd,_CANSPI_CONFIG_XTD_MSG) ‘ set id of filter B2_F4 to 2nd node ID CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF) ‘ set NORMAL mode ‘ Set initial data to be sent RxTx_Data[0] = 9 CANSPIWrite(ID_1st, 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) ‘ rec
mikroBasic PRO for PIC32 Can_Init_Flags = 0 Can_Send_Flags = 0 Can_Rcv_Flags = 0 ‘ ‘ clear flags ‘ Can_Send_Flags = _CANSPI_TX_PRIORITY_0 and _CANSPI_TX_XTD_FRAME and _CANSPI_TX_NO_RTR_FRAME ‘ form value to be used ‘ with CANSPIWrite Can_Init_Flags = _CANSPI_CONFIG_SAMPLE_THRICE and _CANSPI_CONFIG_PHSEG2_PRG_ON and _CANSPI_CONFIG_XTD_MSG and _CANSPI_CONFIG_DBL_BUFFER_ON and _CANSPI_CONFIG_VALID_XTD_MSG and _CANSPI_CONFIG_LINE_FILTER_OFF ‘ form value to be used ‘ with CANSPIInit ‘ Initialize SPI1 modul
mikoBasic PRO for PIC32 HW Connection Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface MikroElektronika 258
mikroBasic PRO for PIC32 Compact Flash Library The Compact Flash Library provides routines for accessing data on Compact Flash card (abbr. CF further in text). CF cards are widely used memory elements, commonly used with digital cameras. Great capacity and excellent access time of only a few microseconds make them very attractive for microcontroller applications. In CF card, data is divided into sectors. One sector usually comprises 512 bytes.
mikoBasic PRO for PIC32 External dependencies of Compact Flash Library The following variables must be defined in all projects Description: using Compact Flash Library: Example: dim CF_Data_Port as byte sfr external Compact Flash Data Port. dim CF_Data_Port as byte at PORTD Ready signal line. dim CF_RDY as sbit at RB7_bit Write Enable signal line. dim CF_WE as sbit at LATB6_bit Output Enable signal line. dim CF_OE as sbit at LATB5_bit Chip Detect signal line.
mikroBasic PRO for PIC32 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_Date_Modified - Cf_Fat_Get_File_Size - Cf_Fat_Get_Swap_File The following routine is for t
mikoBasic PRO for PIC32 Cf_Init Prototype sub procedure Cf_Init() Description Initializes ports appropriately for communication with CF card. Parameters None. Returns Nothing.
mikroBasic PRO for PIC32 Cf_Detect Prototype sub function CF_Detect() as word Description Checks for presence of CF card by reading the chip detect pin. Parameters None. Returns Requires Example Notes - 1 - if CF card was detected - 0 - otherwise 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 PIC32 family MCU and CF card voltage levels are different.
mikoBasic PRO for PIC32 Cf_Read_Init Prototype sub procedure Cf_Read_Init(dim address as longword, dim sectcnt as byte) Description Initializes CF card for reading. Parameters - address: the first sector to be prepared for reading operation. - sector_count: number of sectors to be prepared for reading operation. Returns Nothing. Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
mikroBasic PRO for PIC32 Cf_Write_Byte Prototype sub procedure Cf_Write_Byte(dim data_ as byte) Description 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 contents will be transfered to appropriate flash memory sector. Parameters - data_: byte to be written. Returns Nothing. Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
mikoBasic PRO for PIC32 Cf_Fat_Init Prototype sub function Cf_Fat_Init() as word Description Initializes CF card, reads CF FAT16 boot sector and extracts necessary data needed by the library. Parameters None. Returns Requires Example Notes - 0 - if CF card was detected and successfully initialized - 1 - if FAT16 boot sector was not found - 255 - if card was not detected Nothing. ‘ init the FAT library if (Cf_Fat_Init() = 0) then ... end if None.
mikroBasic PRO for PIC32 Cf_Fat_Assign Prototype sub function Cf_Fat_Assign(dim byref filename as char[12], dim file_cre_attr as byte) as word Description Assigns file for file operations (read, write, delete...). All subsequent file operations will be applied over the assigned file. Parameters - filename: name of the file that should be assigned for file operations. The file name should be in DOS 8.3 (file_name.extension) format.
mikoBasic PRO for PIC32 Cf_Fat_Reset Prototype sub procedure Cf_Fat_Reset(dim byref size as longword) Description Opens currently assigned file for reading. Parameters - size: buffer to store file size to. After file has been open for reading its size is returned through this parameter. Returns Nothing. 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. Example Notes dim size as longword ...
mikroBasic PRO for PIC32 Cf_Fat_Rewrite Prototype sub procedure Cf_Fat_Rewrite() Description Opens currently assigned file for writing. If the file is not empty its content will be erased. Parameters None. Returns Nothing. Requires CF card and CF library must be initialized for file operations. See Cf_Fat_Init. The file must be previously assigned. See Cf_Fat_Assign. Example Notes ‘ open file for writing Cf_Fat_Rewrite() None.
mikoBasic PRO for PIC32 Cf_Fat_Write Prototype sub procedure Cf_Fat_Write(dim byref fdata as byte[512], dim data_len as word) Description Writes requested number of bytes to currently assigned file opened for writing. Parameters - fdata: data to be written. - data_len: number of bytes to be written. Returns Nothing. 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 writing.
mikroBasic PRO for PIC32 Cf_Fat_Get_File_Date Prototype sub procedure Cf_Fat_Get_File_Date(dim byref year as word, dim byref month as byte, dim byref day as byte, dim byref hours as byte, dim byref mins as byte) Description 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.
mikoBasic PRO for PIC32 Cf_Fat_Get_File_Size Prototype sub function Cf_Fat_Get_File_Size() as longword Description This function reads size of currently assigned file in bytes. Parameters None. Returns Size of the currently assigned file in bytes. 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. Example dim my_file_size as longword ... my_file_size = Cf_Fat_Get_File_Size() Notes None.
mikroBasic PRO for PIC32 Parameters Returns Requires Example Notes Bit Mask Description 0 0x01 Read Only 1 0x02 Hidden 2 0x04 System 3 0x08 Volume Label 4 0x10 Subdirectory 5 0x20 Archive 6 0x40 Device (internal use only, never found on disk) 7 0x80 Not used - 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. CF card and CF library must be initialized for file operations.
mikoBasic PRO for PIC32 Copy Code To Clipboard program CF_Fat16_Test dim ‘ set compact flash pinout Cf_Data_Port as byte at PORTE 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 CF_RDY_direction CF_WE_direction CF_OE_direction CF_CD1_direction CF_CE1_direction CF_A2_direction CF_A1_direction CF_A0_direction ‘ eof compact flash RD7_bit LATD6_bit LATD5_bit RD4_bit LATD3_bit LATD2_bit LATD1_bit LATD0_bit as sbit as
mikroBasic PRO for PIC32 file_contents[0] = loop1 div 10 + 48 file_contents[1] = loop1 mod 10 + 48 Cf_Fat_Write(file_contents, LINE_LEN-1) next loop1 end sub ‘ write data to the assigned file ‘-------------- Creates many new files and writes data to them sub procedure M_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_Set_File_Date(2005,6,21,10,35,0) ‘ Set file date & time info Cf_Fat_Assign(filename, 0xA0
mikoBasic PRO for PIC32 end sub ‘-------------- Deletes a file. If file doesn’t exist, it will first be created ‘ and then deleted.
mikroBasic PRO for PIC32 Delay_ms(1000) UART1_Write(0x55) end if end sub ‘-------------- Tries to create a swap file, whose size will be at least 100 ‘ sectors (see Help for details) sub procedure M_Create_Swap_File() dim i as word for i=0 to 511 Buffer[i] = i next i size = Cf_Fat_Get_Swap_File(5000, “mikroE.txt”, 0x20) for details ‘ see help on this function if (size <> 0) then LongIntToStr(size, err_txt) UART1_Write_Line(err_txt) for i=0 to 4999 Cf_Write_Sector(size, Buffer) Inc(size) UART1_Write(“.
mikoBasic PRO for PIC32 ‘--- Test start UART1_Write_Line(“Test Start.”) M_Create_New_File() #IFDEF COMPLETE_EXAMPLE M_Create_Multiple_Files() M_Open_File_Rewrite() M_Open_File_Append() M_Open_File_Read() M_Delete_File() M_Test_File_Exist() M_Create_Swap_File() #ENDIF UART1_Write_Line(“Test End.”) else UART1_Write_Line(err_txt) ‘ Note: Cf_Fat_Init tries to initialize a card more than once. ‘ If card is not present, initialization may last longer (depending on clock speed) end if end.
mikroBasic PRO for PIC32 Epson S1D13700 Graphic Lcd Library The mikroBasic PRO for PIC32 provides a library for working with Glcds based on Epson S1D13700 controller. The S1D13700 Glcd is capable of displaying both text and graphics on an LCD panel. The S1D13700 Glcd allows layered text and graphics, scrolling of the display in any direction, and partitioning of the display into multiple screens.
mikoBasic PRO for PIC32 Library Routines - S1D13700_Init - S1D13700_Write_Command - S1D13700_Write_Parameter - S1D13700_Read_Parameter - S1D13700_Fill - S1D13700_GrFill - S1D13700_TxtFill - S1D13700_Display_GrLayer - S1D13700_Display_TxtLayer - S1D13700_Set_Cursor - S1D13700_Display_Cursor - S1D13700_Write_Char - S1D13700_Write_Text - S1D13700_Dot - S1D13700_Line - S1D13700_H_Line - S1D13700_V_Line - S1D13700_Rectangle - S1D13700_Box - S1D13700_Rectangle_Round_Edges - S1D13700_Rectangle_Round_Edges_Fill - S
mikroBasic PRO for PIC32 S1D13700_Init Prototype sub procedure S1D13700_Init(dim width as word, dim height as word) Returns Nothing. Description Initializes S1D13700 Graphic Lcd controller. Parameters: Requires - width: width of the Glcd panel. - height: height of the Glcd panel. Global variables: - S1D13700_Data_Port: Data Bus Port. - S1D13700_WR: Write signal pin. - S1D13700_RD: Read signal pin. - S1D13700_A0: Command/Data signal pin. - S1D13700_RES: Reset signal pin.
mikoBasic PRO for PIC32 S1D13700_Write_Command Prototype sub procedure S1D13700_Write_Command(dim command as byte) Returns Nothing. Description Writes a command to S1D13700 controller. Parameters: - command: command to be issued: Value Description S1D13700_SYSTEM_SET General system settings. S1D13700_POWER_SAVE Enter into power saving mode. S1D13700_DISP_ON Turn the display on. S1D13700_DISP_OFF Turn the display off. S1D13700_SCROLL Setup text and graphics address regions.
mikroBasic PRO for PIC32 S1D13700_Write_Parameter Prototype sub procedure S1D13700_Write_Parameter(dim parameter as byte) Returns Nothing. Description Writes a parameter to S1D13700 controller. Parameters: Requires - parameter: parameter to be written. Glcd module needs to be initialized. See the S1D13700_Init routine. Previously, a command must be sent through S1D13700_Write_Command routine.
mikoBasic PRO for PIC32 S1D13700_GrFill Prototype sub procedure S1D13700_GrFill(dim d as byte) Returns Nothing. Description Fill graphic layer with appropriate value (0 to clear). Parameters: Requires Example - d: value to fill graphic layer with. Glcd module needs to be initialized. See the S1D13700_Init routine. ‘ clear current graphic panel S1D13700_GrFill(0) S1D13700_TxtFill Prototype sub procedure S1D13700_TxtFill(dim d as byte) Returns Nothing.
mikroBasic PRO for PIC32 S1D13700_Display_TxtLayer Prototype sub procedure S1D13700_Display_TxtLayer(dim mode as byte) Returns Nothing. Description Display selected text layer. Parameters: - mode: text layer mode. Valid values: Value Description S1D13700_LAYER_OFF Turn off graphic layer. S1D13700_LAYER_ON Turn on graphic layer. S1D13700_LAYER_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz. S1D13700_LAYER_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.
mikoBasic PRO for PIC32 S1D13700_Display_Cursor Prototype sub procedure S1D13700_Display_Cursor(dim mode as byte) Returns Nothing. Description Displays cursor. Parameters: - mode: mode parameter. Valid values: Value Description S1D13700_CURSOR_OFF Turn off graphic layer. S1D13700_CURSOR_ON Turn on graphic layer. S1D13700_CURSOR_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz. S1D13700_CURSOR_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.
mikroBasic PRO for PIC32 S1D13700_Write_Text Prototype Returns sub procedure S1D13700_Write_Text(dim byref str as string, dim x, y as word, dim mode as byte) Nothing. Description 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 (column). - y: text position on y-axis (row). - mode: mode parameter.
mikoBasic PRO for PIC32 S1D13700_Line Prototype Returns sub procedure S1D13700_Line(dim x0, y0, x1, y1 as word, dim pcolor as byte) Nothing. Description Draws a line from (x0, y0) to (x1, y1). Parameters: - 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: Value Description S1D13700_BLACK Black color. S1D13700_WHITE White color.
mikroBasic PRO for PIC32 S1D13700_V_Line Prototype Returns sub procedure S1D13700_V_Line(dim y_start, y_end, x_pos as word, dim color as byte) Nothing. Description Draws a horizontal line. Parameters: - y_start: y coordinate of the line start. - y_end: y coordinate of the line end. - x_pos: line position on the x axis. - pcolor: color parameter. Valid values: Value Description S1D13700_BLACK Black color. S1D13700_WHITE White color. Requires Glcd module needs to be initialized.
mikoBasic PRO for PIC32 S1D13700_Box Prototype sub procedure S1D13700_Box(dim x0, y0, x1, y1 as word, dim pcolor as byte) Returns Nothing. Description Draws a rectangle on Glcd. Parameters: - 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: Value Description S1D13700_BLACK Black color.
mikroBasic PRO for PIC32 S1D13700_Rectangle_Round_Edges_Fill Prototype Returns sub procedure S1D13700_Rectangle_Round_Edges_Fill(dim x_upper_left as word, dim y_upper_left as word, dim x_bottom_right as word, dim y_bottom_right as word, dim round_radius as word, dim color as byte) Nothing. Description Draws a filled rounded edge rectangle on Glcd. Parameters: - x_upper_left: x coordinate of the upper left rectangle corner. - y_upper_left: y coordinate of the upper left rectangle corner.
mikoBasic PRO for PIC32 S1D13700_Circle_Fill Prototype Returns sub procedure S1D13700_Circle_Fill(dim x_center as word, dim y_center as word, dim radius as word, dim color as byte) Nothing. Description Draws a filled circle on Glcd. Parameters: - x_center: x coordinate of the circle center. - y_center: y coordinate of the circle center. - radius: radius size. - color: color parameter. Valid values: Value Description S1D13700_BLACK Black color. S1D13700_WHITE White color.
mikroBasic PRO for PIC32 S1D13700_PartialImage Prototype Returns sub procedure S1D13700_PartialImage(dim x_left, y_top, width, picture_width, picture_height as word, dim image as ^const byte) height, Nothing. Description Displays a partial area of the image on a desired location. Parameters: - x_left: x coordinate of the desired location (upper left coordinate). - y_top: y coordinate of the desired location (upper left coordinate). - width: desired image width. - height: desired image height.
mikoBasic PRO for PIC32 Flash Memory Library This library provides routines for accessing microcontroller’s (internal) Flash memory. The program Flash array for the PIC32MX device is built up of a series of rows. A row contains 128 32-bit instruction words or 512 bytes. A group of 8 rows compose a page; which, therefore, contains 8 ՠ512 = 4096 bytes or 1024 instruction words. A page of Flash is the smallest unit of memory that can be erased at a single time.
mikroBasic PRO for PIC32 Flash_Write_Word Prototype sub procedure FLASH_Erase32(dim flash_address as longint) Description Writes one 32-bit word in the program Flash memory on the designated address. Parameters - address: address of the FLASH memory word - wdata: data to be written Returns Nothing. Requires Nothing. Example Notes None.
mikoBasic PRO for PIC32 Graphic Lcd Library mikroBasic PRO for PIC32 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.
mikroBasic PRO for PIC32 External dependencies of Graphic Lcd Library The following variables must be defined in all projects using Graphic Lcd Description: Library: Example: dim GLCD_D0 as sbit sfr external dim GLCD_D0 as sbit at RB0_bit dim GLCD_D1 as sbit sfr external dim GLCD_D2 as sbit sfr external dim GLCD_D3 as sbit sfr external dim GLCD_D4 as sbit sfr external dim GLCD_D5 as sbit sfr external dim GLCD_D6 as sbit sfr external dim GLCD_D7 as sbit sfr external dim GLCD_CS1 as sbit sfr external dim
mikoBasic PRO for PIC32 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_Rectangle_Round_Edges - Glcd_Rectangle_Round_Edges_Fill - Glcd_Box - Glcd_Circle - Glcd_Circle_Fill - Glcd_Set_Font - Glcd_Write_Char - Glcd_Write_Text - Glcd_Image - Glcd_PartialImage Glcd_Init Prototype sub procedure Glcd_Init() Description Initializes
mikroBasic PRO for PIC32 Requires - GLCD_EN : Enable signal pin - GLCD_RST : Reset signal pin - GLCD_D0_Direction : Direction of the Data pin 0 - GLCD_D1_Direction : Direction of the Data pin 1 - GLCD_D2_Direction : Direction of the Data pin 2 - GLCD_D3_Direction : Direction of the Data pin 3 - GLCD_D4_Direction : Direction of the Data pin 4 - GLCD_D5_Direction : Direction of the Data pin 5 - GLCD_D6_Direction : Direction of the Data pin 6 - GLCD_D7_Direction : Direction of the Data pin 7 - GLCD_CS1_Direct
mikoBasic PRO for PIC32 Glcd_Set_Side Prototype sub procedure Glcd_Set_Side(dim x_pos as byte) Description Selects Glcd side. Refer to the Glcd datasheet for detailed explanation. Parameters - x_pos: Specifies position on x-axis of the Glcd. Valid values: 0..127. Values from 0 to 63 specify the left side, values from 64 to 127 specify the right side of the Glcd. Returns Nothing. Requires Glcd needs to be initialized, see Glcd_Init routine.
mikroBasic PRO for PIC32 Glcd_Read_Data Prototype sub function Glcd_Read_Data() as byte Description Reads data from from the current location of Glcd memory and moves to the next location. Parameters None. Returns One byte from Glcd memory, formatted as a word (16-bit). Requires Glcd needs to be initialized, see Glcd_Init routine. Glcd side, x-axis position and page should be set first. See functions Glcd_Set_Side, Glcd_Set_X, and Glcd_Set_Page. Example Notes dim data_ as byte ...
mikoBasic PRO for PIC32 Glcd_Fill Prototype sub procedure Glcd_Fill(dim pattern as byte) Description Fills Glcd memory with the byte pattern. To clear the Glcd screen, use Glcd_Fill(0). To fill the screen completely, use Glcd_Fill(0xFF). Parameters - pattern: byte to fill Glcd memory with. Returns Nothing. Requires Glcd needs to be initialized, see Glcd_Init routine. Example Glcd_Fill(0) Notes None.
mikroBasic PRO for PIC32 Glcd_V_Line Prototype sub procedure Glcd_V_Line(dim y_start, y_end, x_pos, color as byte) Description Draws a vertical line on Glcd. Parameters - y_start: y coordinate of the line start. Valid values: 0..63 - y_end: y coordinate of the line end. Valid values: 0..63 - x_pos: x coordinate of vertical line. Valid values: 0..127 - color: color parameter. Valid values: 0..2 Returns The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Nothing.
mikoBasic PRO for PIC32 Glcd_Rectangle Prototype sub procedure Glcd_Rectangle(dim x_upper_left, right, y_bottom_right, color as byte) y_upper_left, x_bottom_ Description Draws a rectangle on Glcd. Parameters - x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127 - y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..63 - x_bottom_right: x coordinate of the lower right rectangle corner. Valid values: 0..
mikroBasic PRO for PIC32 Glcd_Rectangle_Round_Edges_Fill Prototype sub procedure Glcd_Rectangle_Round_Edges_Fill(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 radius as byte, dim color as byte) Description Draws a filled rounded edge rectangle on Glcd with color. 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..
mikoBasic PRO for PIC32 Glcd_Circle Prototype sub procedure Glcd_Circle(dim x_center, y_center, radius as integer, dim color as byte) Description Draws a circle on Glcd.1 Parameters - x_center: x coordinate of the circle center. Valid values: 0..127 - y_center: y coordinate of the circle center. Valid values: 0..63 - radius: radius size - color: color parameter. Valid values: 0..2 Returns The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot. Nothing.
mikroBasic PRO for PIC32 Glcd_Set_Font Prototype sub procedure Glcd_Set_Font(dim byref const activeFont aFontWidth, aFontHeight as byte, dim aFontOffs as byte) as byte, dim Description 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.
mikoBasic PRO for PIC32 Glcd_Write_Char Prototype sub procedure Glcd_Write_Char(dim character, x_pos, page_num, color as byte) Description Prints character on the Glcd. Parameters - character: character to be written - x_pos: character starting position on x-axis. Valid values: 0..(127-FontWidth) - page_num: the number of the page on which character will be written. Valid values: 0..7 - color: color parameter. Valid values: 0..
mikroBasic PRO for PIC32 Glcd_Image Prototype sub procedure Glcd_Image(dim byref constimage as byte) Description Displays bitmap on Glcd. Parameters - image: image to be displayed. Bitmap array can be located in both code and RAM memory (due to the mikroBasic PRO for PIC32 pointer to const and pointer to RAM equivalency). Returns Nothing. Requires Glcd needs to be initialized, see Glcd_Init routine.
mikoBasic PRO for PIC32 I²C Library The I²C full master I²C module is available with a number of the PIC32 MCU models. The mikroBasic PRO for PIC32 provides a library which supports the master I²C mode. Important: - I²C library routines require you to specify the module you want to use. To select the desired I²C module, simply change the letter x in the routine prototype for a number from 1 to 3. - Number of I²C modules per MCU differs from chip to chip.
mikroBasic PRO for PIC32 I2Cx_Init_Advanced Prototype sub procedure I2Cx_Init_Advanced(dim Fclk_Khz, scl as dword) Description This function configures and initializes the desired I²C module using Peripheral Bus Clock and default initialization settings. As per the I²C standard, SCL clock may be 100 kHz or 400 kHz. However, the user can specify any clock rate up to 1 MHz. Parameters - Fclk_Khz: Peripheral Bus Clock frequency in kHz. - scl: requested serial clock rate. Returns Nothing.
mikoBasic PRO for PIC32 I2Cx_Restart Prototype sub procedure I2Cx_Restart() Description Issues repeated START signal. Parameters None. Returns Nothing. Requires MCU with at least one I²C module. Used I²C module must be initialized before using this function. See I2Cx_Init routine. Example Notes ‘ Issue RESTART signal I2C1_Restart() - I²C library routines require you to specify the module you want to use.
mikroBasic PRO for PIC32 I2Cx_Read Prototype sub function I2Cx_Read(dim ack as word) as byte Description Reads a byte from the I²C bus. Parameters - ack: acknowledge signal parameter. If the ack = 0, acknowledge signal will be sent after reading, otherwise the not acknowledge signal will be sent. Returns Received data. Requires MCU with at least one I²C module. Used I²C module must be initialized before using this function. See I2Cx_Init routine.
mikoBasic PRO for PIC32 I2Cx_Stop Prototype sub procedure I2Cx_Stop() Description Issues STOP signal. Parameters None. Returns Nothing. Requires MCU with at least one I²C module. Used I²C module must be initialized before using this function. See I2Cx_Init routine. Example Notes ‘ Issue STOP signal I2C1_Stop() - I²C library routines require you to specify the module you want to use. To select the desired I²C module, simply change the letter x in the routine prototype for a number from 1 to 5.
mikroBasic PRO for PIC32 I2C2_Stop() end sub main: CHECON = 0x30 AD1PCFG = 0xFFFFFFFF LATB = 0 TRISB = 0 TRISD = 0 LATD = 0 ‘ ‘ ‘ ‘ Set PORTB value to zero Configure PORTB as output Configure PORTB as output Set PORTB value to zero EEPROM_24C02_Init() b = 0x00 for i = 0x00 to 0x80 EEPROM_24C02_WrSingle(i,b) Inc(b) Delay_ms(5) next i ‘ performs I2C initialization for i = 0x00 to 0x80 LATD = i LATB = EEPROM_24C02_RdSingle(i) Delay_ms(100) next i end.
mikoBasic PRO for PIC32 Keypad Library mikroBasic PRO for PIC32 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.
mikroBasic PRO for PIC32 Keypad_Key_Press Prototype sub function Keypad_Key_Press() as word Description Reads the key from keypad when key gets pressed. Parameters None. Returns The code of a pressed key (1..16). If no key is pressed, returns 0. Requires Example Notes Port needs to be initialized for working with the Keypad library, see Keypad_Init. dim kp as word ...
mikoBasic PRO for PIC32 Library Example The following code can be used for testing the keypad. It is written for keypad_4x3 or _4x4. The code returned by the keypad functions (1..16) is transformed into ASCII codes [0..9,A..F], and then sent via UART1.
mikroBasic PRO for PIC32 case kp case kp case kp case kp case kp case kp case kp case kp case kp case kp case kp 6 = 53 7 = 54 8 = 66 9 = 55 10 = 56 11 = 57 12 = 67 13 = 42 14 = 48 15 = 35 16 = 68 ‘ 5 ‘ 6 ‘ B ‘ 7 ‘ 8 ‘ 9 ‘ C ‘ * ‘ 0 ‘ # ‘ D end select UART1_Write_Text(“Key pressed: “) UART1_Write(kp) UART1_Write(10) UART1_Write(13) wend end.
mikoBasic PRO for PIC32 Lcd Library mikroBasic PRO for PIC32 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.
mikroBasic PRO for PIC32 Lcd_Init Prototype sub procedure Lcd_Init() Description Initializes Lcd module. Parameters None. Returns Nothing.
mikoBasic PRO for PIC32 Lcd_Out Prototype sub procedure Lcd_Out(dim row, column as word, dim byref text as string) Description Prints text on Lcd starting from specified position. Both string variables and literals can be passed as a text. Parameters - row: starting position row number - column: starting position column number - text: text to be written Returns Nothing. Requires The Lcd module needs to be initialized. See Lcd_Init routine.
mikroBasic PRO for PIC32 Lcd_Chr_Cp Prototype sub procedure Lcd_Chr_Cp(dim out_char as byte) Description Prints character on Lcd at current cursor position. Both variables and literals can be passed as a character. Parameters - out_char: character to be written Returns Nothing. Requires The Lcd module needs to be initialized. See Lcd_Init routine.
mikoBasic PRO for PIC32 Library Example The following code demonstrates usage of the Lcd Library routines: Copy Code To Clipboard // LCD module dim LCD_RS as dim LCD_EN as dim LCD_D4 as dim LCD_D5 as dim LCD_D6 as dim LCD_D7 as connections sbit at LATB2_bit sbit at LATB3_bit sbit at LATB4_bit sbit at LATB5_bit sbit at LATB6_bit sbit at LATB7_bit dim LCD_RS_Direction as sbit at dim LCD_EN_Direction as sbit at dim LCD_D4_Direction as sbit at dim LCD_D5_Direction as sbit at dim LCD_D6_Direction as sbit at di
mikroBasic PRO for PIC32 Lcd_Cmd(_LCD_SHIFT_RIGHT) Move_Delay() next i while TRUE for i = 0 to 7 Lcd_Cmd(_LCD_SHIFT_LEFT) Move_Delay() next i for i = 0 to 7 Lcd_Cmd(_LCD_SHIFT_RIGHT) Move_Delay() next i wend end.
mikoBasic PRO for PIC32 Manchester Code Library mikroBasic PRO for PIC32 provides a library for handling Manchester coded signals.
mikroBasic PRO for PIC32 Library Routines - Man_Receive_Init - Man_Receive - Man_Send_Init - Man_Send - Man_Synchro - Man_Break The following routines are for the internal use by compiler only: - Manchester_0 - Manchester_1 - Manchester_Out Man_Receive_Init Prototype sub function Man_Receive_Init() as word Description The function configures Receiver pin. After that, the function performs synchronization procedure in order to retrieve baud rate out of the incoming signal. Parameters None.
mikoBasic PRO for PIC32 Man_Receive Prototype sub function Man_Receive(dim byref error as word) as byte Description The function extracts one byte from incoming signal. Parameters - error: error flag. If signal format does not match the expected, the error flag will be set to non-zero. Returns A byte read from the incoming signal. Requires To use this function, the user must prepare the MCU for receiving. See Man_Receive_Init routines. Example dim data_, error as word ...
mikroBasic PRO for PIC32 Man_Send Prototype sub procedure Man_Send(dim data as byte) Description Sends one byte. Parameters - tr_data: data to be sent Returns Nothing. Requires To use this function, the user must prepare the MCU for sending. See Man_Send_Init routine. Example Notes dim msg as byte ... Man_Send(msg) Baud rate used is 500 bps. Man_Synchro Prototype sub function Man_Synchro() as word Description Measures half of the manchester bit length with 10us resolution. Parameters None.
mikoBasic PRO for PIC32 Man_Break Prototype sub procedure Man_Break() Description Man_Receive is blocking routine and it can block the program flow. Call this routine from interrupt to unblock the program execution. This mechanism is similar to WDT. Parameters None. Returns Nothing. Requires Nothing.
mikroBasic PRO for PIC32 Library Example The following code is code for the Manchester receiver, it shows how to use the Manchester Library for receiving data: Copy Code To Clipboard // LCD module dim LCD_RS as LCD_EN as LCD_D4 as LCD_D5 as LCD_D6 as LCD_D7 as connections sbit at LATB2_bit sbit at LATB3_bit sbit at LATB4_bit sbit at LATB5_bit sbit at LATB6_bit sbit at LATB7_bit dim 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_Direct
mikoBasic PRO for PIC32 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 ‘ Reset error counter end if else ‘ No error occured if (temp <> 0x0E) then ‘ If “End” byte was received(see Transmi
mikroBasic PRO for PIC32 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.
mikoBasic PRO for PIC32 Memory Manager Library This library provides routines for manipulating dynamic memory allocation. Dynamic memory allocation (also known as heap-based memory allocation) is the allocation of memory storage for use in a program during the runtime of that program. Dynamically allocated memory exists until it is released. This is in contrast to static memory allocation, which has a fixed duration. It is said that an object so allocated has a dynamic lifetime.
mikroBasic PRO for PIC32 FreeMem Prototype sub procedure FreeMem(dim byref P as ^longword, dim ActualSize as word) Description FreeMem destroys the variable referenced by P and returns its memory to the heap. Parameters - P: variable of any pointer type previously assigned by the Getmem sub procedure. - ActualSize: specifies the size in bytes of the dynamic variable to dispose of and should be the same as the one used to Getmem. Returns Nothing. Requires Nothing.
mikoBasic PRO for PIC32 Multi Media Card Library The Multi Media Card (MMC) is a Flash memory card standard. MMC cards are currently available in sizes up to and including 32 GB and are used in cellular phones, digital audio players, digital cameras and PDA’s. mikroBasic PRO for PIC32 provides a library for accessing data on Multi Media Card via SPI communication. This library also supports SD (Secure Digital) and high capacity SDHC (Secure Digital High Capacity) memory cards.
mikroBasic PRO for PIC32 Library Dependency Tree External dependencies of MMC Library The following variable must be defined in all projects using MMC library: Description: Example: dim Mmc_Chip_Select as sbit sfr external Chip select pin. dim Mmc_Chip_Select as sbit at LATF0_ bit dim Mmc_Chip_Select_Direction as sbit sfr external Direction of the chip select pin.
mikoBasic PRO for PIC32 Mmc_Init Prototype sub function Mmc_Init() as word Description Initializes MMC through hardware SPI interface. Mmc_Init needs to be called before using other functions of this library. Parameters None. Returns Requires - 0 - if MMC/SD card was detected and successfully initialized - 1 - otherwise The appropriate hardware SPI module must be previously initialized.
mikroBasic PRO for PIC32 Mmc_Read_Sector Prototype sub function Mmc_Read_Sector(dim sector as longword, dim byref dbuff as byte[512]) as word Description The function reads one sector (512 bytes) from MMC card. Parameters - sector: MMC/SD card sector to be read. - dbuff: buffer of minimum 512 bytes in length for data storage. Returns Requires Example Notes - 0 - if reading was successful - 1 - if an error occurred MMC/SD card must be initialized. See Mmc_Init.
mikoBasic PRO for PIC32 Mmc_Read_Cid Prototype sub function Mmc_Read_Cid(dim byref data_cid as byte[16]) as byte Description The function reads 16-byte CID register. Parameters - data_cid: buffer of minimum 16 bytes in length for storing CID register content. Returns Requires Example Notes - 0 - if CID register was read successfully - 1 - if there was an error while reading MMC/SD card must be initialized. See Mmc_Init. dim error as word dataBuffer as byte[512] ...
mikroBasic PRO for PIC32 Mmc_Fat_Init Prototype sub function Mmc_Fat_Init() as word Description Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by the library. Parameters None.
mikoBasic PRO for PIC32 Mmc_Fat_QuickFormat Prototype sub function Mmc_Fat_QuickFormat(dim byref mmc_fat_label as string[11]) as word Description Formats to FAT16 and initializes MMC/SD card. Parameters - mmc_fat_label: volume label (11 characters in length). If less than 11 characters are provided, the label will be padded with spaces.
mikroBasic PRO for PIC32 Mmc_Fat_Assign Prototype sub function Mmc_Fat_Assign(dim byref filename as char[11], dim file_cre_attr as byte) as word Description 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. File name should be in DOS 8.3 (file_name.extension) format.
mikoBasic PRO for PIC32 Mmc_Fat_Reset Prototype sub procedure Mmc_Fat_Reset(dim byref size as longword) Description Procedure resets the file pointer (moves it to the start of the file) of the assigned file, so that the file can be read. Parameters - size: buffer to store file size to. After file has been opened for reading, its size is returned through this parameter. Returns Nothing. Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init.
mikroBasic PRO for PIC32 Mmc_Fat_Rewrite Prototype sub procedure Mmc_Fat_Rewrite() Description Opens the currently assigned file for writing. If the file is not empty its content will be erased. Parameters None. Returns Nothing. Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign. Example Notes ‘ open file for writing Mmc_Fat_Rewrite() None.
mikoBasic PRO for PIC32 Mmc_Fat_Write Prototype sub procedure Mmc_Fat_Write(dim byref fdata as byte[512], dim data_len as word) Description Writes requested number of bytes to the currently assigned file opened for writing. Parameters - fdata: data to be written. - data_len: number of bytes to be written. Returns Nothing. 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.
mikroBasic PRO for PIC32 Mmc_Fat_Get_File_Date Prototype sub procedure Mmc_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) Description Reads time/date attributes of the currently assigned file. Parameters - year: buffer to store year attribute to. Upon function execution year attribute is returned through this parameter. - month: buffer to store month attribute to.
mikoBasic PRO for PIC32 Mmc_Fat_Get_File_Date_Modified Prototype sub procedure Mmc_Fat_Get_File_Date_Modified(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) Description Retrieves the last modification date/time for the currently selected file. Seconds are not being retrieved since they are written in 2-sec increments. Parameters - year: buffer to store year attribute to.
mikroBasic PRO for PIC32 Mmc_Fat_Get_Swap_File Prototype sub function Mmc_Fat_Get_Swap_File(dim sectors_cnt as longword, dim byref filename as string[11], dim file_attr as byte) as longword Description 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.
mikoBasic PRO for PIC32 Example Notes ‘-------------- 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 ... size = Mmc_Fat_Get_Swap_File(1000, “mikroE.txt”, 0x20) if (size <> 0) 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 Long File Names (LFN) are not supported.
mikroBasic PRO for PIC32 ‘ UART write text and new line (carriage return + line feed) sub procedure UART_Write_Line( dim byref uart_text as string ) UART1_Write_Text(uart_text) UART1_Write(13) UART1_Write(10) end sub ‘-------------- Creates new file and writes some data to it sub procedure M_Create_New_File() filename[7] = “A” ‘ Set filename for single-file tests Mmc_Fat_Set_File_Date(2011,1,12,11,9,0) ‘ Set file date & time info Mmc_Fat_Assign(filename, 0xA0) ‘ Will not find file and then create file Mmc_F
mikoBasic PRO for PIC32 Mmc_Fat_Append() file_contents = “ for mikroElektronika 2009” file_contents[26] = 10 Mmc_Fat_Write(file_contents, 27) end sub ‘ ‘ ‘ ‘ Prepare file for append Prepare file for append LF Write data to assigned file ‘-------------- Opens an existing file, reads data from it and puts it to USART sub procedure M_Open_File_Read() filename[7] = “B” Mmc_Fat_Assign(filename, 0) Mmc_Fat_Reset(size) ‘ To read file, sub procedure returns size of file while size > 0 Mmc_Fat_Read(character) UAR
mikroBasic PRO for PIC32 ByteToStr(month_, outstr) UART1_Write_Text(outstr) WordToStr(day, outstr) UART1_Write_Text(outstr) WordToStr(hour_, outstr) UART1_Write_Text(outstr) WordToStr(minute_, outstr) UART1_Write_Text(outstr) ‘--- get file size fsize = Mmc_Fat_Get_File_Size LongWordToStr(longint(fsize), outstr) UART_Write_Line(outstr) else ‘--- file was not found - signal it UART1_Write(0x55) Delay_ms(1000) UART1_Write(0x55) end if end sub ‘-------------- Tries to create a swap file, whose size will be at l
mikoBasic PRO for PIC32 Delay_ms(10) UART_Write_Line(“MCU-Started”) ‘ MCU present report ‘--- set up SPI for the file read SPI2_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, 64, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_ MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ACTIVE_2_IDLE) Delay_ms(10) ‘ use fat16 quick format instead of init routine if a formatting is needed if Mmc_Fat_Init() = 0 then ‘ reinitialize spi at higher speed SPI2_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, 8, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_ MIDDLE, _SPI_CLK_IDLE_HIGH
mikroBasic PRO for PIC32 OneWire Library The OneWire library provides routines for communication via the Dallas OneWire protocol, e.g. with DS18x20 digital thermometer. OneWire is a Master/Slave protocol, and all communication cabling required is a single wire. OneWire enabled devices should have open collector drivers (with single pull-up resistor) on the shared data line. Slave devices on the OneWire bus can even get their power supply from data line. For detailed schematic see device datasheet.
mikoBasic PRO for PIC32 Ow_Read Prototype sub function Ow_Read(dim byref port as word, dim pin as word) as byte Description Reads one byte of data via the OneWire bus. Parameters - port: OneWire bus port - pin: OneWire bus pin Returns Data read from an external device over the OneWire bus. Requires Devices compliant with the Dallas OneWire protocol. Example ‘ Read a byte from the One-Wire Bus connected to pin RF6 dim read_data as byte ... read_data = Ow_Read(PORTF, 6) Notes None.
mikroBasic PRO for PIC32 Port Expander Library mikroBasic PRO for PIC32 provides a library for communication with the Microchip’s Port Expander MCP23S17 via SPI interface. Connections of the PIC32 MCU and MCP23S17 is given on the schematic at the bottom of this page. Important: - The library uses the SPI module for communication. User must initialize the appropriate SPI module before using the Port Expander Library.
mikoBasic PRO for PIC32 Expander_Init Prototype sub procedure Expander_Init(dim ModuleAddress as byte) Description 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 Returns Nothing.
mikroBasic PRO for PIC32 Expander_Init_Advanced Prototype sub procedure Expander_Init_Advanced(dim byref rstPort, rstPin, haen as byte)p> Description Initializes Port Expander using SPI communication. Parameters - rstPort: Port Expander’s reset port - rstPin: Port Expander’s reset pin - haen: Port Expander’s hardware address Returns Nothing.
mikoBasic PRO for PIC32 Expander_Read_Byte Prototype sub function Expander_Read_Byte(dim ModuleAddress, RegAddress as byte) as byte Description The function reads byte from Port Expander. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - RegAddress: Port Expander’s internal register address Returns Byte read. Requires Port Expander must be initialized. See Expander_Init. Example ‘ Read a byte from Port Expander’s register dim read_data as byte ...
mikroBasic PRO for PIC32 Expander_Read_PortB Prototype sub function Expander_Read_PortB(dim ModuleAddress as byte) as byte Description The function reads byte from Port Expander’s PortB. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Returns Byte read. Requires Port Expander must be initialized. See Expander_Init. Port Expander’s PortB should be configured as input. See Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines.
mikoBasic PRO for PIC32 Expander_Write_PortA Prototype sub procedure Expander_Write_PortA(dim ModuleAddress, Data as byte) Description The function writes byte to Port Expander’s PortA. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data to be written Returns Nothing. Requires Port Expander must be initialized. See Expander_Init. Port Expander’s PortA should be configured as output.
mikroBasic PRO for PIC32 Expander_Write_PortAB Prototype sub procedure Expander_Write_PortAB(dim ModuleAddress as byte, dim Data as word) Description The function writes word to Port Expander’s ports. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data to be written. Data to be written to PortA are passed in Data’s higher byte. Data to be written to PortB are passed in Data’s lower byte Returns Nothing.
mikoBasic PRO for PIC32 Expander_Set_DirectionPortB Prototype sub procedure Expander_Set_DirectionPortB(dim ModuleAddress, Data as byte) Description The function sets Port Expander’s PortB direction. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data to be written to the PortB direction register. Each bit corresponds to the appropriate pin of the PortB register. Set bit designates corresponding pin as input.
mikroBasic PRO for PIC32 Expander_Set_PullUpsPortB Prototype sub procedure Expander_Set_PullUpsPortB(dim ModuleAddress, Data as byte) Description The function sets Port Expander’s PortB pull up/down resistors. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data for choosing pull up/down resistors configuration. Each bit corresponds to the appropriate pin of the PortB register. Set bit enables pull-up for corresponding pin. Returns Nothing.
mikoBasic PRO for PIC32 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.
mikroBasic PRO for PIC32 HW Connection Port Expander HW connection 367 MikroElektronika
mikoBasic PRO for PIC32 PS/2 Library The mikroBasic PRO for PIC32 provides a library for communication with the common PS/2 keyboard. Important: - The library does not utilize interrupts for data retrieval, and requires the oscillator clock to be at least 6MHz. - The pins to which a PS/2 keyboard is attached should be connected to the pull-up resistors. - Although PS/2 is a two-way communication bus, this library does not provide MCU-to-keyboard communication; e.g.
mikroBasic PRO for PIC32 Ps2_Config Prototype sub procedure Ps2_Config() Description Initializes the MCU for work with the PS/2 keyboard. Parameters None. Returns Nothing. Requires Global variables: - PS2_Data: Data signal line - PS2_Clock: Clock signal line - PS2_Data_Direction: Direction of the Data pin - PS2_Clock_Direction: Direction of the Clock pin must be defined before using this function.
mikoBasic PRO for PIC32 Special Function Keys Key Value returned F1 1 F2 2 F3 3 F4 4 F5 5 F6 6 F7 7 F8 8 F9 9 F10 10 F11 11 F12 12 Enter 13 Page Up 14 Page Down 15 Backspace 16 Insert 17 Delete 18 Windows 19 Ctrl 20 Shift 21 Alt 22 Print Screen 23 Pause 24 Caps Lock 25 End 26 Home 27 Scroll Lock 28 Num Lock 29 Left Arrow 30 Right Arrow 31 Up Arrow 32 Down Arrow 33 Escape 34 Tab 35 MikroElektronika 370
mikroBasic PRO for PIC32 Library Example This simple example reads values of the pressed keys on the PS/2 keyboard and sends them via UART.
mikoBasic PRO for PIC32 HW Connection Example of PS2 keyboard connection PWM Library The CCP module is available with a number of PIC32 MCUs. mikroBasic PRO for PIC32 provides a library which simplifies using of the PWM HW Module. Important : PWM module uses either Timer2 or Timer3 module.
mikroBasic PRO for PIC32 PWM_Init Prototype sub function PWM_Init(dim freq_hz as longword, dim enable_channel_x, timer_ prescale, use_timer_x as word) as word Description Initializes the PWM module with duty ratio 0. Parameters - freq_hz: PWM frequency in Hz (refer to device datasheet for correct values in respect with Fosc) - enable_channel_x: number of PWM channel to be initialized. Refer to MCU’s datasheet for available PWM channels - timer_prescale: timer prescaler parameter.
mikoBasic PRO for PIC32 PWM_Set_Duty Prototype sub procedure PWM_Set_Duty(dim duty, channel as word) Description The function changes PWM duty ratio. Parameters - duty: PWM duty ratio. Valid values: 0 to timer period returned by the PWM_Init function. - channel: number of PWM channel to change duty to. Returns Nothing. Requires MCU must have the HW PWM Module. PWM channel must be properly initialized. See PWM_Init routine. Example ‘ Set channel 1 duty ratio to 50%: dim pwm_period1 as word ...
mikroBasic PRO for PIC32 Library Example The example changes PWM duty ratio on channels 1 and 2 continuously.
mikoBasic PRO for PIC32 if RB2_bit = 1 then Delay_ms(1) current_duty1 = current_duty1 + 5 if (current_duty1 > pwm_period2) then possible pwm_period2 value current_duty1 = 0 end if PWM_Set_Duty(current_duty1, 2) end if if RB3_bit = 1 then Delay_ms(1) current_duty1 = current_duty1 - 5 if (current_duty1 > pwm_period2) then possible pwm_period1 value (overflow) current_duty1 = pwm_period2 end if PWM_Set_Duty(current_duty1, 2) end if Delay_ms(1) wend end.
mikroBasic PRO for PIC32 RS-485 Library RS-485 is a multipoint communication which allows multiple devices to be connected to a single bus. mikroBasic PRO for PIC32 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.
mikoBasic PRO for PIC32 Library Routines - RS485Master_Init - RS485Master_Receive - RS485Master_Send - RS485Slave_Init - RS485Slave_Receive - RS485Slave_Send RS485Master_Init Prototype sub procedure RS485Master_Init() Description Initializes MCU as a Master for RS-485 communication. Parameters None. Returns Nothing. Requires Global variables: - RS485_rxtx_pin - this pin is connected to RE/DE input of RS-485 transceiver(see schematic at the bottom of this page).
mikroBasic PRO for PIC32 RS485Master_Receive Prototype sub procedure RS485Master_Receive(dim byref data as byte[10]) Description 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. Data will be stored in the following manner: - data_buffer[0..
mikoBasic PRO for PIC32 RS485Slave_Init Prototype sub procedure RS485Slave_Init(dim slave_address as byte) Description Initializes MCU as a Slave for RS-485 communication. Parameters - Slave_address: Slave address Returns Nothing. Requires Global variables: - RS485_rxtx_pin - this pin is connected to RE/DE input of RS-485 transceiver(see schematic at the bottom of this page). RE/DE signal controls RS-485 transceiver operation mode.
mikroBasic PRO for PIC32 RS485Slave_Receive Prototype sub procedure RS485Slave_Receive(dim byref data as byte[20]) Description 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 manner: - data_buffer[0..
mikoBasic PRO for PIC32 Library Example The example demonstrates RS-485 communication. Master sends message to Slave with address 160 and waits for a response. After the response is received, the first byte of received data is incremented and sent back to the Slave. The received data is displayed on PORTB while error on receiving (0xAA) and number of consecutive unsuccessful retries are displayed on PORTD. Hardware configurations in this example are made for the LV-32MX v6 board and PIC32MX460F512L.
mikroBasic PRO for PIC32 MVEC_bit = 1 asm ei R0 end asm ‘ Interrupt controller configured for multi vectored mode ‘ Enable all interrupts U2RXIE_bit = 1 ‘ enable intterupt RS485Master_Send(dat,1,160) while (TRUE) Inc(cnt) if (dat[5] <> 0) then PORTD = 0xAA end if if (dat[4] <> 0) then cnt = 0 dat[4] = 0 j = dat[3] for i = 1 to dat[3] PORTB = dat[i-1] next i dat[0] = dat[0]+1 Delay_ms(1) RS485Master_Send(dat,1,160) end if if (cnt > 100000) then Inc(PORTD) cnt = 0 RS485Master_Send(dat,1,160) if (PORTD > 1
mikoBasic PRO for PIC32 main: CHECON = 0x32 AD1PCFG = 0xFFFF TRISB TRISD PORTB PORTD = = = = 0 0 0 0 UART2_Init(19200) Delay_ms(100) RS485Slave_Init(160) dat[0] dat[1] dat[2] dat[4] dat[5] dat[6] = = = = = = 0xAA 0xF0 0x0F 0 0 0 U2IP0_bit = 1 U2IP1_bit = 1 U2IP2_bit = 1 ‘ initialize UART2 module ‘ Intialize MCU as slave, address 160 ‘ ensure that message received flag is 0 ‘ ensure that error flag is 0 ‘ set interrupt ‘ priority ‘ to 7 URXISEL1_U2STA_bit = 0 ‘ 0x = Interrupt flag bit is set when a
mikroBasic PRO for PIC32 HW Connection Example of interfacing PC to PIC32 MCU via RS485 bus with LTC485 as RS-485 transceiver 385 MikroElektronika
mikoBasic PRO for PIC32 Message format and CRC calculations Q: How is CRC checksum calculated on RS485 master side? Copy Code To Clipboard _START_BYTE = 0x96; ‘ 10010110 _STOP_BYTE = 0xA9; ‘ 10101001 PACKAGE: -------_START_BYTE 0x96 ADDRESS DATALEN [DATA1] [DATA2] [DATA3] CRC _STOP_BYTE 0xA9 ‘ if exists ‘ if exists ‘ if exists DATALEN bits -----------bit7 = 1 MASTER SENDS 0 SLAVE SENDS bit6 = 1 ADDRESS WAS XORed with 1, IT WAS EQUAL TO 0 ADDRESS UNCHANGED bit5 = 0 FIXED bit4 = 1 DATA3 (if exists) WAS XORe
mikroBasic PRO for PIC32 Software I²C Library The mikroBasic PRO for PIC32 provides routines for implementing Software I²C communication. These routines are hardware independent and can be used with any MCU. The Software I²C library enables you to use MCU as Master in I²C communication. Multi-master mode is not supported. Important: - This library implements time-based activities, so interrupts need to be disabled when using Software I²C.
mikoBasic PRO for PIC32 Soft_I2C_Init Prototype sub procedure Soft_I2C_Init() Description Configures the software I²C module. Parameters None. Returns Nothing. Requires Global variables: - Soft_I2C_Scl: Soft I²C clock line - Soft_I2C_Sda: Soft I²C data line - Soft_I2C_Scl_Pin_Direction: Direction of the Soft I²C clock pin - Soft_I2C_Sda_Pin_Direction: Direction of the Soft I²C data pin must be defined before using this function.
mikroBasic PRO for PIC32 Soft_I2C_Read Prototype sub function Soft_I2C_Read(dim ack as word) as byte Description Reads one byte from the slave. Parameters - ack: acknowledge signal parameter. If the ack==0 not acknowledge signal will be sent after reading, otherwise the acknowledge signal will be sent. Returns One byte from the Slave. Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine. Also, START signal needs to be issued in order to use this function.
mikoBasic PRO for PIC32 Soft_I2C_Break Prototype sub procedure Soft_I2C_Break() Description All Software I²C Library functions can block the program flow (see note at the top of this page). Calling this routine from interrupt will unblock the program execution. This mechanism is similar to WDT. Parameters None. Returns Nothing. Requires Nothing.
mikroBasic PRO for PIC32 Library Example The example demonstrates use of the Software I²C Library. The dPIC32 MCU is connected (SCL, SDA pins) to PCF8583 RTC (real-time clock). Program sends date/time to RTC.
mikoBasic PRO for PIC32 seconds minutes hours year day month_ end sub = = = = = = ((seconds and 0xF0) >> 4)*10 + (seconds and 0x0F) ((minutes and 0xF0) >> 4)*10 + (minutes and 0x0F) ((hours and 0xF0) >> 4)*10 + (hours and 0x0F) (day and 0xC0) >> 6 ((day and 0x30) >> 4)*10 + (day and 0x0F) ((month_ and 0x10) >> 4)*10 + (month_ and 0x0F) ‘ ‘ ‘ ‘ ‘ ‘ Transform Transform Transform Transform Transform Transform seconds months hours year day month ‘-------------------- Output values to LCD sub procedure Dis
mikroBasic PRO for PIC32 Software SPI Library The mikroBasic PRO for PIC32 provides routines for implementing Software SPI communication. These routines are hardware independent and can be used with any MCU. The Software SPI Library provides easy communication with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc. Library configuration: - SPI to Master mode - Clock value = 20 kHz. - Data sampled at the middle of interval. - Clock idle state low.
mikoBasic PRO for PIC32 Soft_SPI_Init Prototype sub procedure Soft_SPI_Init() Description Routine initializes the software SPI module. Parameters None. Returns Nothing. Requires Global variables: - SoftSpi_SDI: Data in line - SoftSpi_SDO: Data out line - SoftSpi_CLK: Data clock line - SoftSpi_SDI_Direction: Direction of the Data in pin - SoftSpi_SDO_Direction: Direction of the Data out pin - SoftSpi_CLK_Direction: Direction of the Data clock pin must be defined before using this function.
mikroBasic PRO for PIC32 Soft_SPI_Read Prototype sub function Soft_SPI_Read(dim data_ as byte) as byte Description This routine performs 3 operations simultaneously. It provides clock for the Software SPI bus, reads a byte and sends a byte. Parameters - sdata: data to be sent. Returns Byte received via the SPI bus. Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init routine. Example dim data_read, data_send as byte ...
mikoBasic PRO for PIC32 dim value as word sub procedure InitMain() TRISB0_bit = 1 TRISB1_bit = 1 Chip_Select = 1 Chip_Select_Direction = 0 Soft_Spi_Init() end sub ‘ ‘ ‘ ‘ ‘ Set RB0 pin as input Set RB1 pin as input Deselect DAC Set CS# pin as Output Initialize Soft_SPI ‘ DAC increments (0..4095) --> output voltage (0..
mikroBasic PRO for PIC32 Software UART Library mikroBasic PRO for PIC32 provides library which implements Software UART communication. These routines are hardware independent and can be used with any MCU. The Software UART Library provides easy communication with other devices via the RS232 protocol. Important: The Software UART library implements time-based activities, so interrupts need to be disabled when using it.
mikoBasic PRO for PIC32 Soft_UART_Read Prototype sub function Soft_UART_Read(dim byref error as byte) as byte Description The function receives a byte via software UART. This is a blocking function call (waits for start bit). Programmer can unblock it by calling Soft_UART_ Break routine. Parameters - error: Error flag. Error code is returned through this variable. Values : - 0 - no error - 1 - stop bit error - 255 - user abort, Soft_UART_Break called Returns Byte received via UART.
mikroBasic PRO for PIC32 Soft_UART_Break Prototype sub procedure Soft_UART_Break() Description Soft_UART_Read is blocking routine and it can block the program flow. Calling Soft_UART_Break routine from the interrupt will unblock the program execution. This mechanism is similar to WDT. Parameters None. Returns Nothing. Requires Nothing.
mikoBasic PRO for PIC32 Library Example This example demonstrates simple data exchange via software UART. If MCU is connected to the PC, you can test the example from the mikroBasic PRO for PIC32 USART communication terminal, launch it from the drop-down menu Tools › USART Terminal or simply click the USART Terminal Icon .
mikroBasic PRO for PIC32 Sound Library mikroBasic PRO for PIC32 provides a Sound Library to supply users with routines necessary for sound signalization in their applications. Sound generation needs additional hardware, such as piezo-speaker (example of piezo-speaker interface is given on the schematic at the bottom of this page).
mikoBasic PRO for PIC32 Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker.
mikroBasic PRO for PIC32 TRISB = 0xF8 ‘ Configure RB7..RB3 as input Sound_Init(PORTD, 3) Sound_Play(880, 1000) while TRUE if (Button(PORTB,7,1,1)) then Tone1() while (RB7_bit <> 0) nop wend end if ‘ endless loop ‘ If PORTB.7 is pressed play Tone1 if (Button(PORTB,6,1,1)) then Tone2() while (RB6_bit <> 0) nop wend end if ‘ If PORTB.
mikoBasic PRO for PIC32 HW Connection Example of Sound Library MikroElektronika 404
mikroBasic PRO for PIC32 SPI Library The SPI module is available with all PIC32 MCUs. mikroBasic PRO for PIC32 provides a library for initializing the Slave mode and initializing and comfortable work with the Master mode. The PIC32 can easily communicate with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc. Important: - SPI library routines require you to specify the module you want to use.
mikoBasic PRO for PIC32 SPIx_Init Prototype sub procedure SPIx_Init() Description Configures and initializes the SPI module with default settings. Default settings: - Master mode. - 8-bit data mode. - Serial clock set to System clock/64. - Slave Select disabled. - Input data sampled in the middle of interval. - Clock idle state low. - Serial output data changes on transition from idle clock state to active clock state Parameters None. Returns Nothing. Requires MCU must have the SPI1 module.
mikroBasic PRO for PIC32 SPIx_Init_Advanced Prototype sub procedure SPIx_Init_Advanced(dim master_mode, data_mode, clock_divider, slave_select, data_sample, clock_idle, edge as word) Description Configures and initializes the SPI module with user defined settings. Parameters Parameters master_mode, data_mode, clock_divider, slave_select, data_sample, clock_idle and determine the working mode for SPI. The master_mode parameter determines the working mode for SPI module.
mikoBasic PRO for PIC32 Parameters The parameter clock_idle determines the behaviour of the SPI clock (CLK) line in IDLE phase. Clock Polarity Description Predefined library const IDLE state is Lo, ACTIVE state is Hi IDLE state is Hi, ACTIVE state is Lo _SPI_CLK_IDLE_LOW _SPI_CLK_IDLE_HIGH The parameter edge determines on which clock edge data is considered to be valid.
mikroBasic PRO for PIC32 SPIx_Read Prototype sub function SPIx_Read(dim data_out as word) as word Description Reads one word or byte (depending on mode set by init routines) from the SPI bus. Parameters - data_out: dummy data for clock generation (see device Datasheet for SPI modules implementation details) Returns Received data. Requires Routine requires at least one SPI module. Used SPI module must be initialized before using this function. See the SPIx_Init and SPIx_Init_ Advanced routines.
mikoBasic PRO for PIC32 SPI_Set_Active Prototype sub procedure SPI_Set_Active(dim read_ptr as ^TSpi_Rd_Ptr, dim write_ptr as ^TSpi_Wr_Ptr) Description Sets the active SPI module which will be used by the SPIx_Read and SPIx_Write routines. Parameters Parameters: Returns Requires - read_ptr: SPI1_Read handler - write_ptr: SPI1_Write handler Nothing. Routine is available only for MCUs with multiple SPI modules. Used SPI module must be initialized before using this function.
mikroBasic PRO for PIC32 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: CHECON = 0x32 AD1PCFG = 0xFFFF TRISB = 0xF8 ‘ Plays Melody2 ‘ Configure AN pins as digital I/O ‘ Configure RB7..
mikoBasic PRO for PIC32 while (RB3_bit <> 0) nop wend end if wend ‘ Wait for button to be released end.
mikroBasic PRO for PIC32 SPI Ethernet Library The ENC28J60 is a stand-alone Ethernet controller with an industry standard Serial Peripheral Interface (SPI). It is designed to serve as an Ethernet network interface for any controller equipped with SPI. The ENC28J60 meets all of the IEEE 802.3 specifications. It incorporates a number of packet filtering schemes to limit incoming packets. It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calculations.
mikoBasic PRO for PIC32 External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Ethernet Description: Library: Example: dim SPI_Ethernet_CS as sbit sfr external dim SPI_Ethernet_CS as sbit at RC1_ bit dim SPI_Ethernet_RST as sbit sfr external dim SPI_Ethernet_CS_Direction as sbit sfr external dim SPI_Ethernet_RST_Direction as sbit sfr external ENC28J60 chip select pin. ENC28J60 reset pin. Direction of the ENC28J60 chip select pin.
mikroBasic PRO for PIC32 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_getIpAddress - SPI_Ethernet_getGwIpAddress - SPI_Ethernet_getDnsIpAddress - SPI_Ethernet_getIpMask - SPI_Ethernet_confNetwork - SPI_Ethernet_a
mikoBasic PRO for PIC32 Parameters - mac: RAM buffer containing valid MAC address. - ip: RAM buffer containing valid IP address. - fullDuplex: ethernet duplex mode switch. Valid values: 0 (half duplex mode) and 1 (full duplex mode). Returns Nothing. Requires Global variables: - SPI_Ethernet_CS: Chip Select line - SPI_Ethernet_CS_Direction: Direction of the Chip Select pin - SPI_Ethernet_RST: Reset line - SPI_Ethernet_RST_Direction: Direction of the Reset pin must be defined before using this function.
mikroBasic PRO for PIC32 SPI_Ethernet_Enable Prototype sub procedure SPI_Ethernet_Enable(dim enFlt as byte) Description 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.
mikoBasic PRO for PIC32 SPI_Ethernet_Disable Prototype sub procedure SPI_Ethernet_Disable(dim disFlt as byte) Description 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.
mikroBasic PRO for PIC32 SPI_Ethernet_doPacket Prototype sub function SPI_Ethernet_doPacket() as byte Description 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 processing. - upon UDP request the SPI_Ethernet_UserUDP function is called for further processing. Parameters None.
mikoBasic PRO for PIC32 SPI_Ethernet_putBytes Prototype sub procedure SPI_Ethernet_putBytes(dim ptr as ^byte, dim n as word) Description This is MAC module routine. It stores requested number of bytes into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location. Parameters - ptr: RAM buffer containing bytes to be written into ENC28J60 RAM. - n: number of bytes to be written. Returns Nothing. Requires Ethernet module has to be initialized. See SPI_Ethernet_Init.
mikroBasic PRO for PIC32 SPI_Ethernet_putConstString Prototype sub function SPI_Ethernet_putConstString(const ptr as ^byte) as word Description This is MAC module routine. It stores whole const string (excluding null termination) into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location. Parameters - ptr: const string to be written into ENC28J60 RAM. Returns Requires Example Notes Number of bytes written into ENC28J60 RAM. Ethernet module has to be initialized.
mikoBasic PRO for PIC32 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, dim byref flags as TEthPktFlags) as word Description This is TCP module routine. It is internally called by the library. The user accesses to the TCP 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.
mikroBasic PRO for PIC32 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, dim byref flags as TEthPktFlags) as word Description 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.
mikoBasic PRO for PIC32 SPI_Ethernet_setUserHandlers Prototype sub procedure SPI_Ethernet_setUserHandlers(dim TCPHandler as ^TSPI_Ethernet_ UserTCP, dim UDPHandler as ^TSPI_Ethernet_UserUDP) Description Sets pointers to User TCP and UDP handler function implementations, which are automatically called by SPI Ethernet library. Parameters - TCPHandler: TCP request handler - UDPHandler: UDP request handler. Returns Nothing.
mikroBasic PRO for PIC32 SPI_Ethernet_getDnsIpAddress Prototype sub function SPI_Ethernet_getDnsIpAddress() as word Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address. Parameters None. Returns Pointer to the global variable holding DNS IP address. Requires Ethernet module has to be initialized. See SPI_Ethernet_Init. Example Notes dim dnsIpAddr as byte[4] ‘ user DNS IP address buffer ...
mikoBasic PRO for PIC32 SPI_Ethernet_confNetwork Prototype sub procedure SPI_Ethernet_confNetwork(dim byref ipMask, gwIpAddr, dnsIpAddr as byte[4]) Description Configures network parameters (IP subnet mask, gateway IP address, DNS IP address) when DHCP is not used. Parameters - ipMask: IP subnet mask. - gwIpAddr gateway IP address. - dnsIpAddr: DNS IP address. Returns Nothing. Requires Ethernet module has to be initialized. See SPI_Ethernet_Init. Example dim ipMask as gwIpAddr as dnsIpAddr as ...
mikroBasic PRO for PIC32 SPI_Ethernet_arpResolve Prototype sub function SPI_Ethernet_arpResolve(dim byref ip as byte[4], dim tmax as byte) as word Description 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_enc28j60LibDef.mbas” file in the compiler’s Uses folder.
mikoBasic PRO for PIC32 SPI_Ethernet_dnsResolve Prototype sub function SPI_Ethernet_dnsResolve(dim byref host as string, dim tmax as byte) as word Description 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 - host: host name to be resolved.
mikroBasic PRO for PIC32 SPI_Ethernet_initDHCP Prototype sub function SPI_Ethernet_initDHCP(dim tmax as byte) as byte Description 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.
mikoBasic PRO for PIC32 SPI_Ethernet_renewDHCP Prototype sub function SPI_Ethernet_renewDHCP(dim tmax as byte) as byte Description This is DHCP module routine. It sends IP address lease time renewal request to DHCP server. Parameters - tmax: time in seconds to wait for an reply. Returns Requires Example Notes - 1 - upon success (lease time was renewed). - 0 - otherwise (renewal request timed out). Ethernet module has to be initialized. See SPI_Ethernet_Init. while true ...
mikroBasic PRO for PIC32 SPI_Ethernet_Rst_Direction as sbit at TRISF0_bit SPI_Ethernet_CS_Direction as sbit at TRISF1_bit ‘ end ethernet NIC definitions dim myMacAddr myIpAddr gwIpAddr ipMask dnsIpAddr as as as as as byte[6] byte[4] byte[4] byte[4] byte[4] ‘ ‘ ‘ ‘ ‘ my MAC address my IP address gateway (router) IP address network mask (for example : 255.255.255.
mikoBasic PRO for PIC32 const indexPage2 as string[470] = “
”+ “ |