mikroBasic PRO for dsPIC30/33 and PIC24 is a full-featured Basic compiler for dsPIC30, dsPIC33 and PIC24 MCUs from Microchip. It is designed for developing, building and debugging dsPIC30/33 and PIC24-based embedded applications.
mikoBasic PRO for dsPIC30/33 and PIC24 Table of Contents CHAPTER 1 INTRODUCTION Introduction to mikroBasic PRO for dsPIC30/33 and PIC24 30 30 31 What’s new in mikroBasic PRO for dsPIC30/33 and PIC24 32 Software License Agreement 33 Technical Support How to Register 35 35 CHAPTER 2 mikroBasic PRO for dsPIC30/33 and PIC24 Environment Main Menu Options File 39 39 40 41 Edit 42 Features Where to Start Compiler Changes IDE Changes mikroElektronika Associates License Statement and
mikroBasic PRO for dsPIC30/33 and PIC24 Help Help Menu Options 51 51 mikroBasic PRO for dsPIC30/33 and PIC24 IDE 52 Code Editor 53 Code Explorer 60 Project Manager Project Settings Library Manager 61 63 64 Routine List Statistics 66 66 Messages Window Quick Converter Macro Editor Image Preview Toolbars 73 74 74 75 77 IDE Overview Editor Settings Auto Save Highlighter Spelling Comment Style Code Folding Code Assistant Parameter Assistant Bookmarks Go to Line Column
mikoBasic PRO for dsPIC30/33 and PIC24 File Toolbar Edit Toolbar 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 83 83 Customizing IDE Layout 84 Options 86 Integrated Tools 89 Active Comments 97 Docking Windows Saving Layout Auto Hide Code editor Tools Output settings Active Comments Editor ASCII Chart EEPROM Editor Filter Designer Gr
mikroBasic PRO for dsPIC30/33 and PIC24 Metacharacters - Word boundaries Metacharacters - Iterators Metacharacters - Alternatives Metacharacters - Subexpressions Metacharacters - Backreferences 110 110 111 111 111 Keyboard Shortcuts CHAPTER 3 mikroBasic PRO for dsPIC30/33 and PIC24 Command Line Options CHAPTER 4 mikroICD (In-Circuit Debugger) Introduction mikroICD Debugger Options 112 114 114 116 116 116 118 mikroICD Debugger Example mikroICD Debugger Windows 119 123 CHAPTER 5 Software
mikoBasic PRO for dsPIC30/33 and PIC24 Accessing Individual Bits 140 Interrupts 143 Linker Directives 145 Built-in Routines 147 Code Optimization 160 sbit type at keyword bit type Function Calls from Interrupt Interrupt Handling Interrupt Example Directive absolute Directive orgall Directive orgall Lo Hi Higher Highest LoWord HiWord Inc Dec Chr Ord SetBit ClearBit TestBit Delay_us Delay_ms Vdelay_ms VDelay_advanced_ms Delay_Cyc Delay_Cyc_Long Clock_kHz Clock_MHz
mikroBasic PRO for dsPIC30/33 and PIC24 Copy propagation Value numbering "Dead code" ellimination Stack allocation Local vars optimization Better code generation and local optimization 160 160 160 160 160 160 Single Static Assignment Optimization 161 Common Object File Format (COFF) 164 CHAPTER 7 dsPIC30/33 and PIC24 Specifics 166 166 dsPIC Memory Organization 168 Memory Type Specifiers 171 Memory Type Qualifiers 173 Read Modify Write Problem CHAPTER 8 mikroBasic PRO for dsPIC30
mikoBasic PRO for dsPIC30/33 and PIC24 Whitespace 181 Comments Tokens 182 182 Literals 183 Keywords Identifiers 185 188 Punctuators 189 Program Organization 190 Scope and Visibility 192 Name Spaces Modules 193 194 Variables 196 Constants Labels Symbols Functions and Procedures 198 198 199 200 Newline Character Whitespace in Strings Token Extraction Example Integer Literals Floating Point Literals Character Literals String Literals Case Sensitivity Uniqueness and
mikroBasic PRO for dsPIC30/33 and PIC24 Types 203 Simple Types Derived Types Arrays 204 204 204 Strings 206 Pointers 207 Pointer Arithmetic 210 Structures 213 Types Conversions 214 Typedef Specifier Type Qualifiers 216 216 Qualifier volatile Operators 217 217 Arithmetic Operators 217 Relational Operators 219 Bitwise Operators 219 Boolean Operators 221 Type Categories Array Declaration Constant Arrays Multi-dimensional Arrays String Concatenating Pointers and
mikoBasic PRO for dsPIC30/33 and PIC24 Unary Operators 222 Sizeof Operator 223 Expressions 224 Statements Assignment Statements Conditional Statements If Statement 225 226 226 226 Select Case Statement 227 Iteration Statements For Statement 228 229 While Statement Do Statement Jump Statements Break and Continue Statements 229 230 231 231 Exit Statement Return Statement Goto Statement Gosub Statement asm Statement 232 232 232 233 234 Directives Compiler Directives 235 23
mikroBasic PRO for dsPIC30/33 and PIC24 Hardware Libraries Digital Signal Processing Libraries Miscellaneous Libraries Hardware Libraries ADC Library 240 240 241 242 242 CAN Library 248 CANSPI Library 263 Library Routines ADCx_Init ADCx_Init_Advanced ADCx_Get_Sample ADCx_Read ADC_Set_Active Library Example Library Routines CANxSetOperationMode CANxGetOperationMode CANxInitialize CANxSetBaudRate CANxSetMask CANxSetFilter CANxRead CANxWrite CAN Constants CAN_OP_MODE Constants C
mikoBasic PRO for dsPIC30/33 and PIC24 CANSPI_TX_MSG_FLAGS Constants CANSPI_RX_MSG_FLAGS Constants CANSPI_MASK Constants CANSPI_FILTER Constants Library Example HW Connection 273 273 274 274 275 278 Compact Flash Library 279 ECAN Library 300 Library Dependency Tree External dependencies of Compact Flash Library 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 Cf_Fat_Init Cf_Fat_QuickFormat
mikroBasic PRO for dsPIC30/33 and PIC24 ECANxSetBaudRate ECANxSetMask ECANxSetFilter ECANxRead ECANxWrite ECAN Constants ECAN_OP_MODE Constants ECAN_CONFIG_FLAGS Constants ECAN_TX_MSG_FLAGS Constants ECAN_RX_MSG_FLAGS Constants ECAN_MASK Constants ECAN_FILTER Constants ECAN_RX_BUFFER Constants Library Example HW Connection 306 307 308 309 310 311 311 311 312 312 313 313 314 315 319 EEPROM Library 319 Epson S1D13700 Graphic Lcd Library 323 Library Routines EEPROM_Erase EEPROM_Erase_B
mikoBasic PRO for dsPIC30/33 and PIC24 S1D13700_Rectangle_Round_Edges_Fill S1D13700_Circle S1D13700_Circle_Fill S1D13700_Image S1D13700_PartialImage 335 335 336 336 337 Flash Memory Library 338 Graphic Lcd Library 349 dsPIC30: PIC24 and dsPIC33: 24F04KA201 and 24F16KA102 Family Specifics: Library Routines dsPIC30 Functions PIC24 and dsPIC33 Functions dsPIC30 Functions FLASH_Erase32 FLASH_Write_Block FLASH_Write_Compact FLASH_Write_Init FLASH_Write_Loadlatch4 FLASH_Write_Loadlatch4
mikroBasic PRO for dsPIC30/33 and PIC24 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 Library Example HW Connection 358 358 359 359 360 361 361 362 362 363 365 I²C Library 366 Keypad Library 371 Lcd Library 375 Manchester Code Library 381 Library Routines I2Cx_Init I2Cx_Start I2Cx_Restart I2Cx_Is_Idle I2Cx_Read I2Cx_Write I2Cx_Stop Library Example HW Connection External depen
mikoBasic PRO for dsPIC30/33 and PIC24 Man_Receive Man_Send_Init Man_Send Man_Synchro Man_Break Library Example Connection Example 383 383 384 384 385 386 388 Multi Media Card Library 389 OneWire Library 408 Peripheral Pin Select Library 413 Secure Digital Card Secure Digital High Capacity Card Library Dependency Tree External dependencies of MMC Library Library Routines Mmc_Init Mmc_Read_Sector Mmc_Write_Sector Mmc_Read_Cid Mmc_Read_Csd Mmc_Fat_Init Mmc_Fat_QuickFormat Mmc_Fat
mikroBasic PRO for dsPIC30/33 and PIC24 Direction Parameters Input Functions Output Functions 414 414 415 Port Expander Library 417 PS/2 Library 428 PWM Library 432 PWM Motor Control Library 436 Library Dependency Tree External dependencies of Port Expander Library Library Routines Expander_Init Expander_Init_Advanced Expander_Read_Byte Expander_Write_Byte Expander_Read_PortA Expander_Read_PortB Expander_Read_PortAB Expander_Write_PortA Expander_Write_PortB Expander_Write_PortAB
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection 440 RS-485 Library 440 Software I²C Library 450 Software SPI Library 456 Software UART Library 460 Sound Library 464 SPI Library 468 Library Dependency Tree External dependencies of RS-485 Library Library Routines RS485Master_Init RS485Master_Receive RS485Master_Send RS485Slave_Init RS485Slave_Receive RS485Slave_Send Library Example HW Connection Message format and CRC calculations External dependencies of Software I²C Lib
mikroBasic PRO for dsPIC30/33 and PIC24 SPIx_Init_Advanced SPIx_Read SPIx_Write SPI_Set_Active Library Example HW Connection 470 472 472 473 473 474 SPI Ethernet Library 475 SPI Ethernet ENC24J600 Library 500 Library Dependency Tree External dependencies of SPI Ethernet Library Library Routines SPI_Ethernet_Init SPI_Ethernet_Enable SPI_Ethernet_Disable SPI_Ethernet_doPacket SPI_Ethernet_putByte SPI_Ethernet_putBytes SPI_Ethernet_putConstBytes SPI_Ethernet_putString SPI_Ethernet_put
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_putBytes SPI_Ethernet_24j600_putConstBytes SPI_Ethernet_24j600_putString SPI_Ethernet_24j600_putConstString SPI_Ethernet_24j600_getByte SPI_Ethernet_24j600_getBytes SPI_Ethernet_24j600_UserTCP SPI_Ethernet_24j600_UserUDP SPI_Ethernet_24j600_setUserHandlers SPI_Ethernet_24j600_getIpAddress SPI_Ethernet_24j600_getGwIpAddress SPI_Ethernet_24j600_getDnsIpAddress SPI_Ethernet_24j600_getIpMask SPI_Ethernet_24j600_confNetwork SPI_Ethernet_24j
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_PartialImage Library Example HW Connection 530 531 533 SPI Lcd Library 534 SPI Lcd8 (8-bit interface) Library 540 SPI T6963C Graphic Lcd Library 546 Library Dependency Tree External dependencies of SPI Lcd Library Library Routines SPI_Lcd_Config SPI_Lcd_Out SPI_Lcd_Out_Cp SPI_Lcd_Chr SPI_Lcd_Chr_Cp SPI_Lcd_Cmd Available SPI Lcd Commands Library Example Default Pin Configuration Library Dependency Tree External dependencies of SPI Lc
mikoBasic PRO for dsPIC30/33 and PIC24 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_T6963C_displayGrPanel SPI_T6963C_displayTxtPanel SPI_T6963C_setGrPanel SPI_T6963C_setTxtPanel SPI_T6963C_panelFill SPI_T6963C_grFill SPI_T6963C_txtFill SPI_T6963C_cursor_height SPI_T6963C_graphics SPI_T6963C_text SPI_T6963C_cursor SPI_T6963C_cursor_blink Library Example
mikroBasic PRO for dsPIC30/33 and PIC24 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 Example HW Connection 580 580 581 581 581 582 582 582 583 583 583 584 584 588 TFT Library 589 Touch Panel Library 607 External dependencies of TFT Library Library Routines TFT_Init TFT_Set_Index TFT_Write_Command TFT_Write_Dat
mikoBasic PRO for dsPIC30/33 and PIC24 TP_Set_ADC_Threshold TP_Press_Detect TP_Get_Coordinates TP_Calibrate_Bottom_Left TP_Calibrate_Upper_Right TP_Get_Calibration_Consts TP_Set_Calibration_Consts Library Example 608 609 609 610 610 610 611 611 Touch Panel TFT Library 615 UART Library 621 USB Library 631 MikroElektronika 24 Library Dependency Tree External dependencies of Touch Panel TFT Library Library Routines TP_TFT_Init TP_TFT_Set_ADC_Threshold TP_TFT_Press_Detect TP_TFT_Get_C
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example HW Connection 635 635 Digital Signal Processing Libraries 636 FIR Filter Library 637 IIR Filter Library 638 FFT Library 639 Bit Reverse Complex Library 643 Vectors Library 644 Matrices Library 651 Miscellaneous Libraries Button Library 655 655 Digital Signal Processing Libraries Library Routines FIR_Radix Library Routines IIR_Radix Library Dependency Tree FFT Twiddle Factors: TwiddleCoeff_64 TwiddleCoeff_128 Twidd
mikoBasic PRO for dsPIC30/33 and PIC24 Button 656 C Type Library 657 Conversions Library 660 Setjmp Library 672 Library Functions isalnum isalpha iscntrl isdigit isgraph islower ispunct isspace isupper isxdigit toupper tolower Library Dependency Tree Library Routines ByteToStr ShortToStr WordToStr WordToStrWithZeros IntToStr LongintToStr LongWordToStr FloatToStr WordToStrWithZeros IntToStrWithZeros LongWordToStrWithZeros LongIntToStrWithZeros ByteToHex ShortToHex Wo
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example 673 String Library 674 Time Library 682 Trigon Library 686 Library Functions memchr memcmp memcmp memcpy memmove memset strcat strcat2 strchr strcmp strcpy strlen strncat strncpy strspn strncmp strstr strcspn strpbrk strrchr ltrim rtrim strappendpre strappendsuf length Library Routines Time_dateToEpoch Time_epochToDate Time_dateDiff Library Example TimeStruct type definition Library Routines acos asin atan
mikoBasic PRO for dsPIC30/33 and PIC24 fabs floor frexp log ldexp log10 modf pow sin sinh sqrt tan tanh 688 688 688 688 688 689 689 689 689 689 689 690 690 Trigonometry Library 691 CHAPTER 10 Tutorials Managing Project 692 692 692 New Project 693 New Project 696 Customizing Projects 700 Add/Remove Files from Project 702 Source Files 704 Edit Project 706 Clean Project Folder 708 Library Routines sinE3 cosE3 Projects New Project Wizard Steps New Project Wizar
mikroBasic PRO for dsPIC30/33 and PIC24 Compilation 709 Creating New Library 710 Using Microchip MPLAB® IDE with mikroElektronika compilers 711 Using MPLAB® ICD 2 Debugger Using MPLAB® Simulator Frequently Asked Questions 711 718 723 Output Files Assembly View Multiple Library Versions Debugging Your Code 709 709 710 711 Can I use your compilers and programmer on Windows Vista (Windows 7) ? 723 I am getting “Access is denied” error in Vista, how to solve this problem ? 723 What are di
mikoBasic PRO for dsPIC30/33 and PIC24 CHAPTER 1 INTRODUCTION mikroBasic PRO for dsPIC30/33 and PIC24 is a powerful, feature-rich development tool for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 Introduction to mikroBasic PRO for dsPIC30/33 and PIC24 dsPIC30/33 and PIC24 and mikroBasic PRO for dsPIC30/33 and PIC24 fit together well: dsPIC is designed as a PIC with digital signal processing capabilities. These are Microchip’s first inherent 16-bit (data) microcontrollers.
mikoBasic PRO for dsPIC30/33 and PIC24 What’s new in mikroBasic PRO for dsPIC30/33 and PIC24 IDE build 4.60 Command line build 4.60 New features and enhancements in the following areas will boost your productivity by helping you complete many tasks more easily and in less time. For a complete version history of mikroBasic PRO for dsPIC30/33 and PIC24 2010, visit the following link: http://www.mikroe.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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
mikroBasic PRO for dsPIC30/33 and PIC24 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): www.mikroe.com/en/compilers/mikrobasic PRO/dspic/download.htm . 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.
mikoBasic PRO for dsPIC30/33 and PIC24 If you choose I work online registering method, following page will be opened in your default browser: MikroElektronika 36
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 CHAPTER 2 mikroBasic PRO for dsPIC30/33 and PIC24 Environment 39 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 Main Menu Options Available Main Menu options are: Related topics: Keyboard shortcuts, Toolbars MikroElektronika 40
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 View View Menu Options View Menu contains commands for controlling the on-screen display of the current project.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 acrive project. Build all projects. Stop building of all projects. Build and program active project.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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. Run Filter Designer Tool.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 mikroBasic PRO for dsPIC30/33 and PIC24 IDE IDE Overview The mikroBasic PRO for dsPIC30/33 and PIC24 is an user-friendly and intuitive environment.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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).
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Manager Library Manager enables simple handling libraries being used in a project. Library Manager window lists all libraries (extension .mcl) which are instantly stored in the compiler Uses folder. The desirable library is added to the project by selecting check box next to the library name.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 .
mikroBasic PRO for dsPIC30/33 and PIC24 RAM Memory Usage Displays RAM memory usage in a pie-like form. Used RAM Locations Displays used RAM memory locations and their names.
mikoBasic PRO for dsPIC30/33 and PIC24 SFR Locations Displays list of used SFR locations. ROM Memory Usage Displays ROM memory space usage in a pie-like form.
mikroBasic PRO for dsPIC30/33 and PIC24 ROM Memory Constants Displays ROM memory constants and their addresses. Functions Sorts and displays functions in various ways.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Memory Summary Displays summary of RAM and ROM memory in a pie-like form.
mikroBasic PRO for dsPIC30/33 and PIC24 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. The user can filter which notifications will Messages Window display by checking Errors, Warning and Hints box.
mikoBasic PRO for dsPIC30/33 and PIC24 Quick Converter Quick Converter enables the user to easily transform numbers from one base to another. The 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Now, navigate to the desired image file, and simply add it: Next, right click the added file, and choose Set As Preview Image: MikroElektronika 76
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 .
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 specifics). Build all files as library enables user to use compiled library (*.
mikoBasic PRO for dsPIC30/33 and PIC24 MikroElektronika 88
mikroBasic PRO for dsPIC30/33 and PIC24 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 89 from Tools toolbar.
mikoBasic PRO for dsPIC30/33 and PIC24 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 MikroElektronika from Tools toolbar.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 IDE - project_ name.hex file will be loaded automatically while ihex file must be loaded manually. Filter Designer The Filter designer is a tool for designing FIR and IIR filters.
mikoBasic PRO for dsPIC30/33 and PIC24 Graphic Lcd Bitmap Editor The mikroBasic PRO for dsPIC30/33 and PIC24 includes the Graphic Lcd Bitmap Editor. Output is the mikroBasic PRO for dsPIC30/33 and PIC24 compatible code. You can launch it from the drop-down menu Tools › Glcd Bitmap Editor.
mikroBasic PRO for dsPIC30/33 and PIC24 HID Terminal The mikroBasic PRO for dsPIC30/33 and PIC24 includes the HID communication terminal for USB communication. You can launch it from the drop-down menu Tools › HID Terminal.
mikoBasic PRO for dsPIC30/33 and PIC24 Lcd Custom Character mikroBasic PRO for dsPIC30/33 and PIC24 includes the Lcd Custom Character. Output is mikroBasic PRO for dsPIC30/33 and PIC24 compatible code. You can launch it from the drop-down menu Tools › Lcd Custom Character.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 USART Terminal The mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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).
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 MikroElektronika or button.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 If you click No, comment will be removed from the source code.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroBasic PRO for dsPIC30/33 and PIC24 IDE.
mikroBasic PRO for dsPIC30/33 and PIC24 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 113 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 CHAPTER 3 mikroBasic PRO for dsPIC30/33 and PIC24 Command Line Options Usage: mBdsPIC.exe [- [-]] [ [-]] [-]] Infile can be of *.mbas, *.mcl and *.pld type. The following parameters and some more (see manual) are valid: -P : MCU for which compilation will be done. -FO : Set oscillator [in MHz]. -SP : Add directory to the search path list.
mikroBasic PRO for dsPIC30/33 and PIC24 Parameters used in the example: -MSF: Short Message Format; used for internal purposes by IDE. -DBG: Generate debug info. -p30F4013: MCU 30F4013 selected. -Y: Dynamic link for string literals enabled. -DL: All files built as libraries. -O11111114: Miscellaneous output options. -fo80: Set oscillator frequency [in MHz]. -N”C:\Lcd\Lcd.mbpds” -SP”C:\Program Files\Mikroelektronika\mikroBasic PRO for dsPIC\Defs”: Output files generated to file path specified by filename.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 program on a host dsPIC30/33 or PIC24 microcontroller and view variable values, Special Function Registers (SFR), RAM, CODE and EEPROM memory along with the mikroICD code execution on hardware.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 mikroICD Debugger Example Here is a step-by-step mikroICD Debugger Example. First you have to write a program.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 (4 for PIC24 and dsPIC33 family, for dsPIC30 family this number depends on the MCU used). 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.
mikroBasic PRO for dsPIC30/33 and PIC24 mikroICD Debugger Windows Debug Windows This section provides an overview of available Debug Windows in mikroBaisc PRO for dsPIC30/33 and PIC24: - 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 CHAPTER 5 Software Simulator Overview MikroElektronika 128
mikroBasic PRO for dsPIC30/33 and PIC24 Software Simulator The Source-level Software Simulator is an integral component of the mikroBasic PRO for dsPIC30/33 and PIC24 environment. It is designed to simulate operations of the Microchip dsPIC30/33 and PIC24 MCUs and assist the users in debugging code written for these devices.
mikoBasic PRO for dsPIC30/33 and PIC24 Software Simulator Debug Windows Debug Windows This section provides an overview of available Debug Windows in mikroBasic PRO for dsPIC30/33 and PIC24: - 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 Software Simulator Debugger Options Debugger Options Name Start Debugger Run/Pause Debugger Stop Debugger Description Function Key Starts Debugger. F9 Run/Pause Debugger. F6 Stop Debugger. 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.
mikoBasic PRO for dsPIC30/33 and PIC24 CHAPTER 6 mikroBasic PRO for dsPIC30/33 and PIC24 Specifics The following topics cover the specifics of mikroBasic PRO for dsPIC30/33 and PIC24 compiler: - Basic Standard Issues - Predefined Globals and Constants - Accessing Individual Bits - Interrupts - Linker Directives - Built-in Routines - Code Optimization MikroElektronika 136
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Basic Standard Issues Divergence from the Basic Standard - Function recursion is not supported because of no easily-usable stack and limited memory dsPIC Specific C Language Extensions mikroBasic PRO for dsPIC30/33 and PIC24 has additional set of keywords that do not belong to the standard Basic language keywords: - code data rx sfr at sbit bit iv Related topics: Keywords, dsPIC Specifics MikroElektronika 138
mikroBasic PRO for dsPIC30/33 and PIC24 Predefined Globals and Constants To facilitate dsPIC30/33 and PIC24 programming, the mikroBasic PRO for dsPIC30/33 and PIC24 implements a number of predefined globals and constants. All dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 will include an appropriate (*.
mikoBasic PRO for dsPIC30/33 and PIC24 Accessing Individual Bits The mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 sbit type The mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 Interrupts The dsPIC30/33 and PIC24 interrupt controller module reduces numerous peripheral interrupt request signals to a single interrupt request signal to the dsPIC30/33 and PIC24 CPU and has the following features: - Up to 8 processor exceptions and software traps - 7 user-selectable priority levels - Interrupt Vector Table (IVT) with up to 62 vectors (dsPIC30) or up to 118 vectors (dsPIC33 and PIC24) - A unique vector for each interrupt or exception source - Fix
mikoBasic PRO for dsPIC30/33 and PIC24 For the sake of backward compatibility, user may write also: sub procedure int1() org IVT_ADDR_U1RXINTERRUPT asm nop end asm end sub which is equivalent to: sub procedure int1() iv IVT_ADDR_U1RXINTERRUPT asm nop end asm end sub Is is recommended that interrupts are handled in this way for the sake of better readability of the user projects.
mikroBasic PRO for dsPIC30/33 and PIC24 Linker Directives mikroBasic PRO for dsPIC30/33 and PIC24 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. Directive absolute Directive absolute specifies the starting address in RAM for a variable. If the variable is multi-byte, higher bytes will be stored at the consecutive locations.
mikoBasic PRO for dsPIC30/33 and PIC24 sub procedure proc(dim par as word) org 0x200 ‘ Procedure will start at the address 0x200; ... end sub 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 .
mikroBasic PRO for dsPIC30/33 and PIC24 Built-in Routines The mikroBasic PRO for dsPIC30/33 and PIC24 compiler provides a set of useful built-in utility functions. Built-in functions do not have any special requirements. You can use them in any part of your project. The Delay_us and Delay_ms routines are implemented as “inline”; i.e. code is generated in the place of a call, so the call doesn’t count against the nested call limit.
mikoBasic PRO for dsPIC30/33 and PIC24 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 value Lowest 8 bits (byte) of number, bits 7..0.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 Dec(dim byref par as longint) Decreases parameter par by 1. - par: value which will be decremented by 1 Nothing. Requires Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Vdelay_ms Prototype Description Parameters Returns sub procedure Vdelay_ms(dim time_in_ms as word) Creates a software delay in duration of Time_ms milliseconds. Generated delay is not as precise as the delay created by Delay_ms. Time_ms: delay time in milliseconds Nothing. Requires Nothing. Example pause = 1000 ‘ ... Vdelay_ms(pause) Notes ‘ ~ one second pause None.
mikroBasic PRO for dsPIC30/33 and PIC24 Delay_Cyc Prototype Description Parameters Returns sub procedure Delay_Cyc(dim x, y as word) Creates a delay based on MCU clock. Delay lasts for x*16384 + y MCU clock cycles. x: NumberOfCycles divided by 16384 y: remainder of the NumberOfCycles/16384 division Nothing. Requires Nothing. Example Delay_Cyc(1, 10) Notes Delay_Cyc is a library function rather than a built-in routine; it is presented in this topic for the sake of convenience.
mikoBasic PRO for dsPIC30/33 and PIC24 Clock_MHz Prototype Description sub function Clock_MHz() as word Returns device clock in MHz, rounded to the nearest integer. This is an “inline” routine; the code is generated in the place of the call. Parameters None. Returns Device clock in MHz, rounded to the nearest integer. Requires Nothing. Example clk = Clock_MHz() Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 Reset Prototype Description sub procedure Reset() This procedure is equal to assembler instruction reset. Parameters None. Returns Nothing. Requires Nothing. Example Reset() ‘ Resets the MCU Notes None. ClrWdt Prototype Description Parameters sub procedure ClrWdt() This procedure is equal to assembler instruction clrwdt. None. Returns Nothing. Requires Nothing. Example ClrWdt() ‘ Clears WDT Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 SetFuncCall Prototype Description sub procedure SetFuncCall(dim FuncName as string) If the linker encounters an indirect function call (by a pointer to function), it assumes that any routine whose address was taken anywhere in the program can be called at that point if it’s prototype matches the pointer declaration.
mikroBasic PRO for dsPIC30/33 and PIC24 DoGetDateTime Prototype Description Parameters sub function DoGetDateTime() as string Use the DoGetDateTime() to get date and time of compilation as string in your code. None. Returns String with date and time when this routine is compiled. Requires Nothing. Example str = DoGetDateTime() Notes None. DoGetVersion Prototype Description Parameters sub function DoGetVersion() as string Use the DoGetVersion() to get the current version of compiler. None.
mikoBasic PRO for dsPIC30/33 and PIC24 Code Optimization Optimizer has been added to extend the compiler usability, cut down the amount of code generated and speed-up its execution. The main features are: Constant folding All expressions that can be evaluated in the compile time (i.e. are constant) are being replaced by their results.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 0x0102 0x320001 L__SSA_Test6: ;Example.mbas,31 :: 0x0104 0x000000 BRA Z NOP L__SSA_Test2 nop Without SSA enabled, sub procedure SSA_Test this example is consisted of 5 asm instructions : ;Example.mbas,29 :: 0x0102 0x97B8CE 0x0104 0x57006A 0x0106 0x408010 0x0108 0x320001 L__SSA_Test6: ;Example.
mikroBasic PRO for dsPIC30/33 and PIC24 Asm code and SSA optimization If converting code from an earlier version of the compiler, which consists of mixed asm code with the Basic 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Common Object File Format (COFF) COFF File Format The Common Object File Format (COFF) is a specific file format suitable for code debugging. The COFF incorporates symbolic procedure, function, variable and constant names information; line number information, breakpoints settings, code highlighter and all the necessary information for effective and fast debugging.
mikroBasic PRO for dsPIC30/33 and PIC24 2. When the project is opened, go to Tools › Options › Output settings, and check the “Generate COFF file” option, and click the OK button: 3. Now, compile the project. In the messages window, appropriate message on COFF file generation should appear: 4. Generated COFF file will be created in the project folder, with the .cof extension.
mikoBasic PRO for dsPIC30/33 and PIC24 CHAPTER 7 dsPIC30/33 and PIC24 Specifics In order to get the most from the mikroBasic PRO for dsPIC30/33 and PIC24 compiler, the user should be familiar with certain aspects of dsPIC30/33 and PIC24 MCU. This knowledge is not essential, but it can provide a better understanding of the dsPIC30/33 and PIC24’s capabilities and limitations, and their impact on the code writing as well.
mikroBasic PRO for dsPIC30/33 and PIC24 Types Efficiency First of all, the user should know that dsPIC30/33 and PIC24’s ALU, which performs arithmetic operations, is optimized for working with 16-bit types. Although mikroBasic PRO for dsPIC30/33 and PIC24 is capable of handling types like byte, char or short, dsPIC30/33 and PIC24 will generate a better code for 16-bit types word and integer type so use byte, char and short only in places where you can significantlly save RAM (e.g.
mikoBasic PRO for dsPIC30/33 and PIC24 dsPIC Memory Organization The dsPIC microcontroller’s memory is divided into Program Memory and Data Memory. Program Memory (ROM) is used for permanent saving program being executed, while Data Memory (RAM) is used for temporarily storing and keeping intermediate results and variables. Program Memory (ROM) Program Memory (ROM) is used for permanent saving program code being executed, and it is divided into several sections, as on the picture below.
mikroBasic PRO for dsPIC30/33 and PIC24 Data Memory (RAM) Data memory consists of: - SFR Memory Space - X and Y Data RAM - DMA RAM (only for dsPIC33F Family) - Unimplemented Memory Space Data Memory (RAM) Organization 1. PIC24F Data Memory Organization 2. dsPIC33F Data Memory Organization SFR Memory Space The first 2kB of data memory is allocated to the Special Function Registers (SFRs). The SFRs are control and status register for core and peripheral functions in the dsPIC.
mikoBasic PRO for dsPIC30/33 and PIC24 DMA RAM Every dsPIC33F device contains a portion of dual ported DMA RAM located at the end of Y data space. Direct Memory Access (DMA) is a very efficient mechanism of copying data between peripheral SFRs and buffers or variables stored in RAM, with minimal CPU intervention.
mikroBasic PRO for dsPIC30/33 and PIC24 Memory Type Specifiers The mikroBasic PRO for dsPIC30/33 and PIC24 supports usage of all memory areas. Each variable may be explicitly assigned to a specific memory space by including a memory type specifier in the declaration, or implicitly assigned. The following memory type specifiers can be used: - code data rx sfr xdata ydata dma code Description The code memory type may be used for allocating constants in program memory.
mikoBasic PRO for dsPIC30/33 and PIC24 xdata Description This memory specifier allows user to access X Data memory space. Example dim y as char xdata ‘ puts x in xdata memory space ydata Description This memory specifier allows user to access Y Data memory space. Example dim y as char ydata ‘ puts y in ydata memory space dma Description This memory specifier allows user to access DMA memory space (dsPIC33F specific).
mikroBasic PRO for dsPIC30/33 and PIC24 Memory Type Qualifiers In addition to the standard storage qualifiers(const, volatile) the compiler introduces storage qualifiers of near and far. Near Memory Qualifier 1. Data Memory Objects The qualifier near is used to denote that a variable is allocated in near data space (the first 8 kB of Data memory). Such variables can sometimes be accessed more efficiently than variables not allocated (or not known to be allocated) in near data space.
mikoBasic PRO for dsPIC30/33 and PIC24 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).
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 The second line, LATB.B1 = 1 will be decoded 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.
mikoBasic PRO for dsPIC30/33 and PIC24 CHAPTER 8 mikroBasic PRO for dsPIC30/33 and PIC24 Language Reference MikroElektronika 178
mikroBasic PRO for dsPIC30/33 and PIC24 - 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 - Type Conversions - Implicit Conversion - Explicit Conversion - Operators - Introduction to Operators - Ope
mikoBasic PRO for dsPIC30/33 and PIC24 - 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 - Compler Directives - Linker Directives Lexical Elements Overview The following topics provide a
mikroBasic PRO for dsPIC30/33 and PIC24 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, the two sequences dim tmp as byte dim j as word and dim dim tmp j as as byte word are lexically equivalent and parse identically.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 Literals Literals are tokens representing fixed numeric or character values. The data type of a constant is deduced by the compiler using such clues as numeric value and format used in the source code. Integer Literals Integral values can be represented in decimal, hexadecimal or binary notation. In decimal notation, numerals are represented as a sequence of digits (without commas, spaces or dots), with optional prefix + or - operator to indicate the sign.
mikoBasic PRO for dsPIC30/33 and PIC24 2e-5 3E+10 .09E34 ‘ = 2.0 * 10^-5 ‘ = 3.0 * 10^10 ‘ = 0.09 * 10^34 Character Literals Character literal is one character from the extended ASCII character set, enclosed with quotes (for example, “A”). Character literal can be assigned to variables of byte and char type (variable of byte will be assigned the ASCII value of the character). Also, you can assign character literal to a string variable.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 - 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 186
mikroBasic PRO for dsPIC30/33 and PIC24 - 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 dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Identifiers Identifiers are arbitrary names of any length given to functions, variables, symbolic constants, user-defined data types and labels. All these program elements will be referred to as objects throughout the help (don’t be confused with the meaning of object in object-oriented programming). Identifiers can contain letters from a to z and A to Z, the underscore character “_” and digits from 0 to 9. First character must be a letter or an underscore, i.e.
mikroBasic PRO for dsPIC30/33 and PIC24 Punctuators The mikroBasic PRO for dsPIC30/33 and PIC24 punctuators (also known as separators) are: - [ ] – Brackets - ( ) – Parentheses - , – Comma - : – Colon - . – Dot Brackets Brackets [ ] indicate single and multidimensional array subscripts: dim alphabet as byte[30] ‘ ... alphabet[2] = “c” For more information, refer to Arrays.
mikoBasic PRO for dsPIC30/33 and PIC24 Colon Colon (:) is used to indicate a labeled statement: start: nop ‘... goto start For more information, refer to Labels. Dot Dot (.) indicates access to a structure member. For example: person.surname = “Smith” For more information, refer to Structures. Dot is a necessary part of floating point literals. Also, dot can be used for accessing individual bits of registers in mikroBasic PRO for dsPIC30/33 and PIC24.
mikroBasic PRO for dsPIC30/33 and PIC24 ‘ structures declarations structure ... ‘ variables declarations dim Name[, Name2...] as [^]type [absolute 0x123] [external] [volatile] [register] [sfr] ‘ procedures declarations sub procedure procedure_name(...) ... end sub ‘ functions declarations sub function function_name(...) as return_type ...
mikoBasic PRO for dsPIC30/33 and PIC24 ‘ procedures prototypes sub procedure sub_procedure_name([dim byref] [const] ParamName as [^]type, [dim byref] [const] ParamName2, ParamName3 as [^]type) ‘ functions prototypes sub function sub_function_name([dim byref] [const] ParamName as [^]type, [dim byref] [const] ParamName2, ParamName3 as [^]type) as [^]type ‘******************************************************** ‘* Implementation: ‘******************************************************** implements ‘ constants
mikroBasic PRO for dsPIC30/33 and PIC24 Place of declaration Scope Identifier is declared in the declaration section of the main module, out of any function or procedure Scope extends from the point where it is declared to the end of the current file, including all routines enclosed within that scope. These identifiers have a file scope and are referred to as globals. Identifier is declared in the function or procedure Scope extends from the point where it is declared to the end of the current routine.
mikoBasic PRO for dsPIC30/33 and PIC24 Modules In mikroBasic PRO for dsPIC30/33 and PIC24, each project consists of a single project file and one or more module files. The project file, with extension .mbpds contains information on the project, while modules, with extension .mbas, contain the actual source code. See Program Organization for a detailed look at module arrangement.
mikroBasic PRO for dsPIC30/33 and PIC24 program MyProject ‘ main procedure main: ‘ Place program code here end. Other than comments, nothing should precede the keyword program. After the program name, you can optionally place the include clauses. Place all global declarations (constants, variables, labels, routines, structures) before the label main. Other Modules Modules other than main start with the keyword module. Newly created blank module contains the bare-bones: module MyModule implements end.
mikoBasic PRO for dsPIC30/33 and PIC24 Variables Variable is an object whose value can be changed during the runtime. Every variable is declared under unique name which must be a valid identifier. This name is used for accessing the memory location occupied by a variable. Variables are declared in the declaration part of the file or routine — each variable needs to be declared before being used.
mikroBasic PRO for dsPIC30/33 and PIC24 In the First_Module we will define and declare routine called pi_r_squared (calculates pi multiplied by the radius squared): module First_Module sub procedure pi_r_square(dim rr as float) ‘ Declaration of the pi_r_square routine implements sub procedure pi_r_square(dim rr as float) dim res as float res = rr*3.14 end sub ‘ Definition of the pi_r_square routine end.
mikoBasic PRO for dsPIC30/33 and PIC24 Constants Constant is a data whose value cannot be changed during the runtime. Using a constant in a program consumes no RAM memory. Constants can be used in any expression, but cannot be assigned a new value. Constants are declared in the declaration part of a program or routine. You can declare any number of constants after the keyword const: const constant_name [as type] = value Every constant is declared under unique constant_name which must be a valid identifier.
mikroBasic PRO for dsPIC30/33 and PIC24 Symbols mikroBasic PRO fordsPIC30/33 and PIC24 symbols allow you to create simple macros without parameters. You can replace any line of code with a single identifier alias. Symbols, when properly used, can increase code legibility and reusability. Symbols need to be declared at the very beginning of the module, right after the module name and (optional) include clauses. Check Program Organization for more details.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 Now we could call it to calculate, say, 312: tmp = power(3, 12) Procedures Procedure is declared like this: sub procedure procedure_name(parameter_list) [ local declarations ] procedure body end sub procedure_name represents a procedure’s name and can be any valid identifier. Within parentheses, parameter_ list is a formal parameter list similar to variable declaration.
mikoBasic PRO for dsPIC30/33 and PIC24 Example: This example shows how to declare a function which returns a complex type. program Example structure TCircle ‘ Structure dim CenterX, CenterY as word dim Radius as byte end structure dim MyCircle as TCircle ‘ Global variable sub function DefineCircle(dim x, y as word, dim r as byte) as TCircle ‘ DefineCircle function returns a Structure result.CenterX = x result.CenterY = y result.
mikroBasic PRO for dsPIC30/33 and PIC24 Functions reentrancy Functions reentrancy is allowed. Remember that the dsPIC30/33 and PIC24 have memory limitations that can vary between MCUs. 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Simple Types Simple types represent types that cannot be divided into more basic elements and are the model for representing elementary data on machine level. Basic memory unit in mikroBasic PRO for dsPIC30/33 and PIC24 has 16 bits. Here is an overview of simple types in mikroBasic PRO for dsPIC30/33 and PIC24: Type Size Range bit 1–bit 0 or 1 sbit 1–bit 0 or 1 byte, char 8–bit 0 .. 255 short 8–bit -127 .. 128 word 16–bit 0 ..
mikroBasic PRO for dsPIC30/33 and PIC24 Here are a few examples of array declaration: dim weekdays as byte[7] dim samples as word[50] main: ‘ Now we can access elements of array variables, for example: samples[0] = 1 if samples[37] = 0 then ‘ ... Constant Arrays Constant array is initialized by assigning it a comma-delimited sequence of values within parentheses.
mikoBasic PRO for dsPIC30/33 and PIC24 Strings A string represents a sequence of characters equivalent to an array of char. It is declared like this: string[string_length] The specifier string_length is a number of characters a string consists of. The string is stored internally as the given sequence of characters plus a final null character (zero). This appended “stamp” does not count against string’s total length. A null string (“”) is stored as a single null character.
mikroBasic PRO for dsPIC30/33 and PIC24 Here is an example: dim msg as string[20] res_txt as string[5] res, channel as word main: ‘... ‘ Get result of ADC res = Adc_Read(channel) ‘ Create string out of numeric result WordToStr(res, res_txt) ‘ Prepare message for output msg = “Result is “ + ‘ Text “Result is” res_txt ‘ Result of ADC ‘... Notes: - In current version plus operator for concatenating strings will accept at most two operands.
mikoBasic PRO for dsPIC30/33 and PIC24 Pointers and memory spaces Pointers can point to data in any available memory space. Pointers can reside in any available memory space except in program (code) memory space.
mikroBasic PRO for dsPIC30/33 and PIC24 Example: Example demonstrates the usage of function pointers. It is shown how to declare a procedural type, a pointer to function and finally how to call a function via pointer.
mikoBasic PRO for dsPIC30/33 and PIC24 program example dim w as word ptr_b as ^byte ptr_arr as ^byte[10] arr as byte[10] main: ptr_b = @arr ‘ @ operator will return ^byte w = @arr ‘ @ operator will return ^byte ptr_arr = @arr ‘ @ operator will return ^byte[10] end. If F is a routine (a function or procedure), @F returns a pointer to F.
mikroBasic PRO for dsPIC30/33 and PIC24 Note: Comparing pointers pointing to different objects/arrays can be performed at programmer’s own responsibility — a precise overview of data’s physical storage is required. 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).
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 Structures A structure represents a heterogeneous set of elements. Each element is called a member; the declaration of a structure type specifies a name and type for each member. The syntax of a structure type declaration is structure structname dim member1 as type1 ‘... dim membern as typen end structure where structname is a valid identifier, each type denotes a type, and each member is a valid identifier.
mikoBasic PRO for dsPIC30/33 and PIC24 Types Conversions Conversion of variable of one type to a variable of another type is typecasting. mikroBasic PRO for dsPIC30/33 and PIC24 supports both implicit and explicit conversions for built-in types.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 Arithmetic Operators Overview Operator Operation Operands Result + addition byte, short, word, integer, longint, longword, float - subtraction byte, short, word, integer, longint, longword, float byte, short, word, integer, longint, longword, float * multiplication / division, floating-point byte, short, word, integer, longint, longword, float div division, rounds down to nearest integer mod modulus, returns the remainder of integer division (cannot
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 Logical Operations on Bit Level and 0 1 or 0 1 xor 0 1 0 0 0 0 0 1 0 0 1 1 0 1 1 1 1 1 1 0 not 0 1 1 0 The bitwise operators and, or, and xor perform logical operations on the appropriate pairs of bits of their operands. The operator not complements each bit of its operand. For example: $1234 and $5678 ‘ equals $1230 ‘ because ..
mikroBasic PRO for dsPIC30/33 and PIC24 Signed and Conversions If number is converted from less complex to more complex data type, the upper bytes are filled with ones if sign bit is 1 (number is negative); the upper bytes are filled with zeroes if sign bit is 0 (number is positive). If number is converted from more complex to less complex data type, the data is simply truncated (the upper bytes are lost). For example: dim a dim b ‘ ...
mikoBasic PRO for dsPIC30/33 and PIC24 Unary Operators Unary operators are operators that take exactly one argument. Unary Arithmetic Operator Operator - can be used as a prefix unary operator to change sign of a signed value. Unary prefix operator + can be used also, but it doesn’t affect data. For example: b = -a Unary Bitwise Operator The result of the not (bitwise negation) operator is the bitwise complement of the operand.
mikroBasic PRO for dsPIC30/33 and PIC24 Sizeof Operator The prefix unary operator sizeof returns an integer constant that represents the size of memory space (in bytes) used by its operand (determined by its type, with some exceptions). The operator sizeof can take either a type identifier or an unary expression as an operand. You cannot use sizeof with expressions of function type, incomplete types, parenthesized names of such types, or with lvalue that designates a bit field object.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 Conditional expressions Conditional expressions may differ from the same code in assignment expressions (due to left side exception). Example: a as longword b as byte 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Assignment Statements Assignment statements have the following form: variable = expression The statement evaluates expression and assigns its value to variable. All the rules of implicit conversion are applied. Variable can be any declared variable or array element, and expression can be any expression. Do not confuse the assignment with relational operator = which tests for equality.
mikroBasic PRO for dsPIC30/33 and PIC24 The compiler treats the construction in this way: if expression1 then if expression2 then statement1 else statement2 end if end if In order to force the compiler to interpret our example the other way around, we have to write it explicitly: if expression1 then if expression2 then statement1 end if else statement2 end if Select Case Statement Use the select case statement to pass control to a specific program branch, based on a certain condition.
mikoBasic PRO for dsPIC30/33 and PIC24 Here is a simple example of the select case statement: select case operator case “*” res = n1 * n2 case “/” res = n1 / n2 case “+” res = n1 + n2 case “-” res = n1 - n2 case else res = 0 cnt = cnt + 1 end select Also, you can group values together for a match.
mikroBasic PRO for dsPIC30/33 and PIC24 For Statement The for statement implements an iterative loop and requires you to specify the number of iterations. The syntax of the for statement is: for counter = initial_value to final_value [step step_value] statement_list next counter counter is a variable which increments with each iteration of the loop. Before the first iteration, counter is set to initial_value and will increment until it reaches final_value.
mikoBasic PRO for dsPIC30/33 and PIC24 Here is an example of calculating scalar product of two vectors, using the while statement: s = 0 i = 0 while i < n s = s + a[i] * b[i] i = i + 1 wend Probably the easiest way to create an endless loop is to use the statement: while TRUE ‘ ... wend 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.
mikroBasic PRO for dsPIC30/33 and PIC24 Jump Statements The jump statement, when executed, transfers control unconditionally. There are five such statements in mikroBasic PRO for dsPIC30/33 and PIC24: - break - continue - exit - goto - gosub Break and Continue Statements Break Statement Sometimes, you might need to stop the loop from within its body. Use the break statement within loops to pass control to the first statement following the innermost loop (for, while, or do).
mikoBasic PRO for dsPIC30/33 and PIC24 Exit Statement The exit statement allows you to break out of a routine (function or procedure). It passes the control to the first statement following the routine call. Here is a simple example: sub procedure Proc1() dim error as byte ... ‘ we’re doing something here if error = TRUE then exit end if ...
mikroBasic PRO for dsPIC30/33 and PIC24 Label and goto statement must belong to the same block. Hence it is not possible to jump into or out of a procedure or function. You can use goto to break out from any level of nested control structures. Never jump into a loop or other structured statement, since this can have unpredictable effects. The use of goto statement is generally discouraged as practically every algorithm can be realized without it, resulting in legible structured programs.
mikoBasic PRO for dsPIC30/33 and PIC24 asm Statement mikroBasic PRO for dsPIC30/33 and PIC24 allows embedding assembly in the source code by means of the asm statement. Note that you cannot use numerals as absolute addresses for register variables in assembly instructions. You may use symbolic names instead (listing will display these names as well as addresses).
mikroBasic PRO for dsPIC30/33 and PIC24 asm MOV _myvar, w0 ; move myvar to W0 nop MOV #6, W0 ; move literal 6 to W0 MOV W0, _myvar ; move contents of W0 to myvar MOV #lo_addr(_myvar), w1 ; retrieve low address word of _myvar and move it to W1 (0x2678 -> W1) MOV #hi_addr(_myvar), W1 ; retrieve high address word of _myvar and move it to W1 (0x0000 -> W1) MOV #lo_addr(_proc), W0 ; retrieve hi address byte of routine proc and move it to W0 (0x0001 -> W1) MOV #lo_addr(_msg), W0 ; retrieve low address word of co
mikoBasic PRO for dsPIC30/33 and PIC24 Directives #DEFINE and #UNDEFINE Use directive #DEFINE to define a conditional compiler constant (“flag”). You can use any identifier for a flag, with no limitations. No conflicts with program identifiers are possible because the flags have a separate name space. Only one flag can be set per directive. For example: #DEFINE extended_format Use #UNDEFINE to undefine (“clear”) previously defined flag.
mikroBasic PRO for dsPIC30/33 and PIC24 Include Directive #I The #I parameter directive instructs mikroBasic PRO for dsPIC30/33 and PIC24 to include the named text file in the compilation. In effect, the file is inserted in the compiled text right after the #I filename directive.
mikoBasic PRO for dsPIC30/33 and PIC24 Directive org Directive org specifies the starting address of a constant or a routine in ROM. It is appended to the constant or a routine declaration.
mikroBasic PRO for dsPIC30/33 and PIC24 CHAPTER 9 mikroBasic PRO for dsPIC30/33 and PIC24 Libraries mikroBasic PRO for dsPIC30/33 and PIC24 provides a set of libraries which simplify the initialization and use of dsPIC30/33 and PIC24 and their modules: Use Library manager to include mikroBasic PRO for dsPIC30/33 and PIC24 Libraries in you project.
mikoBasic PRO for dsPIC30/33 and PIC24 Hardware Libraries - ADC Library - CAN Library - CANSPI Library - Compact Flash Library - Enhanced CAN Library - EEPROM Library - Epson S1D13700 Graphic Lcd Library - Flash Memory Library - Graphic Lcd Library - I²C Library - Keypad Library - Lcd Library - Manchester Code Library - Multi Media Card Library - OneWire Library - Peripheral Pin Select Library - Port Expander Library - PS/2 Library - PWM Library - PWM Motor Library - RS-485 Library - Software I²C Library -
mikroBasic PRO for dsPIC30/33 and PIC24 Miscellaneous Libraries - Button Library - C Type Library - Conversions Library - Setjmp Library - String Library - Time Library - Trigon Library - Trigonometry Library See also Built-in Routines.
mikoBasic PRO for dsPIC30/33 and PIC24 Hardware Libraries - ADC Library - CAN Library - CANSPI Library - Compact Flash Library - Enhanced CAN Library - EEPROM Library - Epson S1D13700 Graphic Lcd Library - Flash Memory Library - Graphic Lcd Library - I²C Library - Keypad Library - Lcd Library - Manchester Code Library - Multi Media Card Library - OneWire Library - Peripheral Pin Select Library - Port Expander Library - PS/2 Library - PWM Library - PWM Motor Library - RS-485 Library - Software I²C Library -
mikroBasic PRO for dsPIC30/33 and PIC24 Library Routines - ADCx_Init - ADCx_Init_Advanced - ADCx_Get_Sample - ADCx_Read - ADC_Set_Active ADCx_Init Prototype sub procedure ADCx_Init() Description This routines configures ADC module to work with default settings.
mikoBasic PRO for dsPIC30/33 and PIC24 ADCx_Init_Advanced Prototype ‘ dsPIC30F and PIC24FJ prototype sub procedure ADC1_Init_Advanced(dim Reference as word) ‘ dsPIC33FJ and PIC24HJprototype sub procedureADCx_Init_Advanced(dim word) ADCMode as word, dim Reference as Description This routine configures the internal ADC module to work with user defined settings. Parameters - ADCMode: resolution of the ADC module. - Reference: voltage reference used in ADC process.
mikroBasic PRO for dsPIC30/33 and PIC24 ADCx_Get_Sample Prototype sub function ADCx_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 or 12-bit (depending on selected mode by ADCx_Init_Advanced or MCU) unsigned value from the specified channel. - The MCU with built-in ADC module.
mikoBasic PRO for dsPIC30/33 and PIC24 ADC_Set_Active Prototype sub procedure ADC_Set_Active(dim adc_gs as ^TADC_Get_Sample) Description Sets active ADC module. Parameters Parameters: - adc_gs: ADCx_Get_Sample handler. Returns Nothing. Requires Routine is available only for MCUs with multiple ADC modules. Used ADC module must be initialized before using this routine. See ADCx_Init and ADCx_Init_ Advanced routines. Example ‘ Activate ADC2 module ADC_Set_Active(@ADC2_Get_Sample) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 ADC HW connection 247 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 CAN Library mikroBasic PRO for dsPIC30/33 and PIC24 provides a library (driver) for working with the dsPIC30F CAN module. 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. Data transfer rates depend on distance.
mikroBasic PRO for dsPIC30/33 and PIC24 CANxSetOperationMode Prototype sub procedure CANxSetOperationMode(dim mode, WAIT as word) Description Sets the CAN module to requested mode. Parameters - mode: CAN module operation mode. Valid values: CAN_OP_MODE constants. See CAN_OP_MODE constants. - WAIT: CAN mode switching verification request. If WAIT == 0, the call is non-blocking. The function does not verify if the CAN module is switched to requested mode or not.
mikoBasic PRO for dsPIC30/33 and PIC24 CANxInitialize Prototype sub procedure CANxInitialize(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CAN_ CONFIG_FLAGS as word) Description Initializes the CAN module.
mikroBasic PRO for dsPIC30/33 and PIC24 CANxSetBaudRate Prototype sub procedure CANxSetBaudRate(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CAN_ CONFIG_FLAGS as word) Description Sets CAN baud rate. Due to complexity of the CAN protocol, you can not simply force a bps value. Instead, use this function when CAN is in Config mode. Refer to datasheet for details. SAM, SEG2PHTS and WAKFIL bits are set according to CAN_CONFIG_FLAGS value. Refer to datasheet for details.
mikoBasic PRO for dsPIC30/33 and PIC24 CANxSetMask Prototype sub procedure CANxSetMask(dim CAN_MASK as word, dim val as longint, dim CAN_CONFIG_FLAGS as word) Description Function sets mask for advanced filtering of messages. Given value is bit adjusted to appropriate buffer mask registers. Parameters - CAN_MASK: CAN module mask number. Valid values: CAN_MASK constants. See CAN_MASK constants. - val: mask register value.
mikroBasic PRO for dsPIC30/33 and PIC24 CANxSetFilter Prototype sub procedure CANxSetFilter(dim CAN_FILTER as word, dim val as longint, dim CAN_CONFIG_FLAGS as word) Description Function sets message filter. Given value is bit adjusted to appropriate buffer mask registers. Parameters - CAN_FILTER: CAN module filter number. Valid values: CAN_FILTER constants. See CAN_FILTER constants. - val: filter register value.
mikoBasic PRO for dsPIC30/33 and PIC24 CANxRead Prototype sub function CANxRead(dim byref id as longint, dim byref data as byte[1], dim dataLen, CAN_RX_MSG_FLAGS as word) as word 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 pointed by id pointer - Message data is retrieved and stored to array pointed by data pointer - Message length is retrieved and stored to location pointed by dataLen pointer - Messa
mikroBasic PRO for dsPIC30/33 and PIC24 CANxWrite Prototype sub function CANxWrite(dim id as longint, dim byref data_ as byte[1], dim dataLen, CAN_TX_MSG_FLAGS as word) as word 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 dsPIC30/33 and PIC24 CAN Constants There is a number of constants predefined in CAN library. To be able to use the library effectively, you need to be familiar with these. You might want to check the example at the end of the chapter. CAN_OP_MODE Constants CAN_OP_MODE constants define CAN operation mode.
mikroBasic PRO for dsPIC30/33 and PIC24 _CAN_CONFIG_MATCH_TYPE_BIT _CAN_CONFIG_ALL_VALID_MSG _CAN_CONFIG_MATCH_MSG_TYPE as word = 0x20 as word = 0xDF as word = 0xFF ‘ XX0XXXXX ‘ XX1XXXXX You may use bitwise and to form config byte out of these values. For example: Copy Code To Clipboard init = _CAN_CONFIG_SAMPLE_THRICE _CAN_CONFIG_PHSEG2_PRG_ON _CAN_CONFIG_STD_MSG _CAN_CONFIG_DBL_BUFFER_ON _CAN_CONFIG_VALID_XTD_MSG _CAN_CONFIG_LINE_FILTER_OFF ...
mikoBasic PRO for dsPIC30/33 and PIC24 CAN_RX_MSG_FLAGS Constants CAN_RX_MSG_FLAGS are flags related to reception of CAN message. If a particular bit is set; corresponding meaning is TRUE or else it will be FALSE.
mikroBasic PRO for dsPIC30/33 and PIC24 CAN_FILTER Constants CAN_FILTER constants define filter codes. Function CANxSetFilter expects one of these as its argument: Copy Code To Clipboard const _CAN_FILTER_B1_F1 _CAN_FILTER_B1_F2 _CAN_FILTER_B2_F1 _CAN_FILTER_B2_F2 _CAN_FILTER_B2_F3 _CAN_FILTER_B2_F4 as as as as as as word word word word word word = = = = = = 0 1 2 3 4 5 Library Example The example demonstrates CAN protocol.
mikoBasic PRO for dsPIC30/33 and PIC24 RxTx_Data[0] = 9 CAN1Initialize(1,3,3,3,1,Can_Init_Flags) CAN1SetOperationMode(_CAN_MODE_CONFIG,0xFF) ‘ initialize CAN ‘ set CONFIGURATION mode CAN1SetMask(_CAN_MASK_B1, -1, _CAN_CONFIG_MATCH_MSG_TYPE and _CAN_CONFIG_XTD_MSG) ‘ set all mask1 bits to ones CAN1SetMask(_CAN_MASK_B2, -1, _CAN_CONFIG_MATCH_MSG_TYPE and _CAN_CONFIG_XTD_MSG) ‘ set all mask2 bits to ones CAN1SetFilter(_CAN_FILTER_B2_F3,ID_2nd,_CAN_CONFIG_XTD_MSG) ‘ set id of filter B2_F3 to 2nd node ID CAN1S
mikroBasic PRO for dsPIC30/33 and PIC24 Can_Send_Flags = Can_Init_Flags _CAN_TX_PRIORITY_0 and _CAN_TX_XTD_FRAME and _CAN_TX_NO_RTR_FRAME = _CAN_CONFIG_SAMPLE_THRICE and _CAN_CONFIG_PHSEG2_PRG_ON and _CAN_CONFIG_XTD_MSG and _CAN_CONFIG_DBL_BUFFER_ON and _CAN_CONFIG_MATCH_MSG_TYPE and _CAN_CONFIG_LINE_FILTER_OFF CAN1Initialize(1,3,3,3,1,Can_Init_Flags) CAN1SetOperationMode(_CAN_MODE_CONFIG,0xFF) ‘ form value to be used ‘ with CANSendMessage ‘ form value to be used ‘ with CANInitialize ‘ initialize CAN
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection Example of interfacing CAN transceiver with MCU and CAN bus MikroElektronika 262
mikroBasic PRO for dsPIC30/33 and PIC24 CANSPI Library The SPI module is available with a number of the dsPIC30/33 and PIC24 MCUs. The mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 CANSPISetBaudRate Prototype sub procedure CANSPISetBaudRate(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CANSPI_CONFIG_FLAGS as byte) Returns 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 = =
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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) ‘ receive message if ((Rx_ID = ID_2nd) and Msg_Rcvd) then ‘ if message received check id PORTB = RxTx_Data[0] ‘ id correct, output data at PORTD Inc(RxTx_Data[0]) ‘ increment received
mikroBasic PRO for dsPIC30/33 and PIC24 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 module SPI1_Init() CANSPIInitialize(1,3,3,3,1,Can_Init_Flags) ‘ in
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface MikroElektronika 278
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 External dependencies of Compact Flash Library The following variables must be defined in all projects using Compact Flash Description: Library: Example: dim CF_Data_Port external Compact Flash Data Port. dim CF_Data_Port as byte at PORTD Ready signal line.
mikroBasic PRO for dsPIC30/33 and PIC24 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 r
mikoBasic PRO for dsPIC30/33 and PIC24 Cf_Init Prototype sub procedure Cf_Init() Description Initializes ports appropriately for communication with CF card. Parameters None. Returns Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30 family MCU and CF card voltage levels are different.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dim size as longword ...
mikroBasic PRO for dsPIC30/33 and PIC24 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 ‘ open file for writing Cf_Fat_Rewrite() Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 Parameters Returns Requires 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 dsPIC30/33 and PIC24 Library Example This project consists of several blocks that demonstrate various aspects of usage of the Cf_Fat16 library.
mikroBasic PRO for dsPIC30/33 and PIC24 ‘ UART write text and new line (carriage return + line feed) sub procedure UART1_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” Cf_Fat_Set_File_Date(2005,6,21,10,35,0) ‘ Set file date & time info Cf_Fat_Assign(filename, 0xA0) ‘ Will not find file and then create file Cf_Fat_Rewrite() ‘ To clear
mikoBasic PRO for dsPIC30/33 and PIC24 filename[7] = “B” Cf_Fat_Assign(filename, 0) Cf_Fat_Set_File_Date(2009, 1, 23, 17, 22, 0) Cf_Fat_Append file_contents = “ for mikroElektronika 2007” ‘ Prepare file for append file_contents[26] = 10 ‘ LF Cf_Fat_Write(file_contents, 27) ‘ Write data to assigned file end sub ‘-------------- Opens an existing file, reads data from it and puts it to USART sub procedure M_Open_File_Read() filename[7] = “B” Cf_Fat_Assign(filename, 0) Cf_Fat_Reset(size) ‘ To read file, procedu
mikroBasic PRO for dsPIC30/33 and PIC24 ‘--- file has been found - get its modified date Cf_Fat_Get_File_Date_Modified(year, month_, day, hour_, minute_) UART1_Write_Text(“ modified: “) WordToStr(year, outstr) UART1_Write_Text(outstr) 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 = Cf_Fat_Get_File_Size LongIntToStr(fsize, outstr)
mikoBasic PRO for dsPIC30/33 and PIC24 ‘-------------- Main.
mikroBasic PRO for dsPIC30/33 and PIC24 HW Connection Pin diagram of CF memory card 299 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 ECAN Library mikroBasic PRO for dsPIC30/33 and PIC24 provides a library (driver) for working with the dsPIC33FJ and pic24HJ ECAN module. ECAN is a very robust protocol that has error detection and signalling, self–checking and fault confinement. Faulty ECAN data and remote frames are re-transmitted automatically, similar to the Ethernet. Data transfer rates depend on distance.
mikroBasic PRO for dsPIC30/33 and PIC24 ECANxDmaChannelInit Prototype sub function ECANxDmaChannelInit(dim DmaChannel as word, dim ChannelDir as word, dim DmaRamBuffAdd as word) as word Description The function preforms initialization of the DMA module for ECAN. Parameters - DmaChannel: DMA Channel number. Valid values: 0..7. - ChannelDir: transfer direction. Valid values: 1 (DMA RAM to peripheral) and 0 (peripheral to DMA RAM). - DmaRamBuffAdd: DMA RAM buffer address.
mikoBasic PRO for dsPIC30/33 and PIC24 ECANxGetOperationMode Prototype sub function ECANxGetOperationMode() as word Description The function returns current operation mode of the ECAN module. See ECAN_OP_MODE constants or device datasheet for operation mode codes. Parameters None. Returns Current operation mode. Requires The ECAN routines are supported only by MCUs with the ECAN module. Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
mikroBasic PRO for dsPIC30/33 and PIC24 ECANxInitialize Prototype sub procedure ECANxInitialize(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, ECAN_ CONFIG_FLAGS as word) Description Initializes the ECAN module.
mikoBasic PRO for dsPIC30/33 and PIC24 ECANxSelectTxBuffers Prototype sub function ECANxSelectTxBuffers(dim txselect as word) as word Description The function designates the ECAN module’s transmit buffers. Parameters - txselect: transmit buffer select. By setting bits in the txselect lower byte corresponding buffers are enabled for transmition. The ECAN module supports up to 8 transmit buffers. Also, by clearing bits in the txselect lower byte corresponding buffers are enabled for reception.
mikroBasic PRO for dsPIC30/33 and PIC24 ECANxFilterEnable Prototype sub procedure ECANxFilterEnable(dim flten as word) Description The function enables receive filters. Parameters - flten: filter enable selection parameter. Each bit corresponds to appropriate filter. By setting bit the corresponding filter will be enabled. Returns Nothing. Requires The ECAN routines are supported only by MCUs with the ECAN module. Microcontroller must be connected to ECAN transceiver which is connected to the ECAN bus.
mikoBasic PRO for dsPIC30/33 and PIC24 ECANxSetBaudRate Prototype sub procedure ECANxSetBaudRate(dim SJW, BRP, PHSEG1, PHSEG2, PROPSEG, ECAN_ CONFIG_FLAGS as word) Description Sets ECAN module baud rate. Due to complexity of the ECAN protocol, you can not simply force the bps value. Instead, use this function when ECAN is in Config mode. Refer to datasheet for details. SAM, SEG2PHTS and WAKFIL bits are set according to the ECAN_CONFIG_FLAGS value.
mikroBasic PRO for dsPIC30/33 and PIC24 ECANxSetMask Prototype sub procedure ECANxSetMask(dim ECAN_MASK as word, dim val as longint, dim ECAN_CONFIG_FLAGS as word) Description The function configures appropriate mask for advanced message filtering. Parameters - ECAN_MASK: ECAN module mask number. Valid values: ECAN_MASK constants. See ECAN_MASK constants. - val: mask register value. This value is bit-adjusted to appropriate buffer mask registers - ECAN_CONFIG_FLAGS: selects type of messages to filter.
mikoBasic PRO for dsPIC30/33 and PIC24 ECANxSetFilter Prototype sub procedure ECANxSetFilter(dim ECAN_FILTER as word, dim val as longint, dim ECAN_FILTER_MASK as word, dim ECAN_FILTER_RXBUFF as word, dim ECAN_ CONFIG_FLAGS as word) Description The function configures and enables appropriate message filter. Parameters - ECAN_FILTER: ECAN module filter number. Valid values: ECAN_FILTER constants. See ECAN_ FILTER constants. - val: filter register value.
mikroBasic PRO for dsPIC30/33 and PIC24 ECANxRead Prototype sub function ECANxRead(dim byref id as longint, dim byref data as byte[8], dim byref dataLen as word, dim byref ECAN_RX_MSG_FLAGS as word) as word 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 pointed by the id pointer - Message data is retrieved and stored to array pointed by the data pointer - Message length is retrieved and stored to locatio
mikoBasic PRO for dsPIC30/33 and PIC24 ECANxWrite Prototype sub function ECANxWrite(dim id as longint, dim byref Data as byte[8], dim DataLen, ECAN_TX_MSG_FLAGS as word) as word Description If at least one empty Transmit Buffer is found, the function sends message in the queue for transmission. Parameters - id: ECAN message identifier. Valid values: all 11 or 29 bit values, depending on message type (standard or extended) - Data: data to be sent - DataLen: data length. Valid values: 0..
mikroBasic PRO for dsPIC30/33 and PIC24 ECAN Constants There is a number of constants predefined in the ECAN library. You need to be familiar with them in order to be able to use the library effectively. Check the example at the end of the chapter. ECAN_OP_MODE Constants The ECAN_OP_MODE constants define ECAN operation mode.
mikoBasic PRO for dsPIC30/33 and PIC24 You may use bitwise and to adjust the appropriate flags. For example: Copy Code To Clipboard init = _ECAN_CONFIG_SAMPLE_THRICE _ECAN_CONFIG_PHSEG2_PRG_ON _ECAN_CONFIG_STD_MSG _ECAN_CONFIG_MATCH_MSG_TYPE _ECAN_CONFIG_LINE_FILTER_OFF ... ECAN1Initialize(1, 1, 3, 3, 1, init) and and and and ‘ initialize ECAN1 ECAN_TX_MSG_FLAGS Constants ECAN_TX_MSG_FLAGS are flags related to transmission of ECAN message.
mikroBasic PRO for dsPIC30/33 and PIC24 const _ECAN_RX_FILTER_BITS _ECAN_RX_FILTER_0 _ECAN_RX_FILTER_1 _ECAN_RX_FILTER_2 _ECAN_RX_FILTER_3 _ECAN_RX_FILTER_4 _ECAN_RX_FILTER_5 _ECAN_RX_FILTER_6 _ECAN_RX_FILTER_7 _ECAN_RX_FILTER_8 _ECAN_RX_FILTER_9 _ECAN_RX_FILTER_10 _ECAN_RX_FILTER_11 _ECAN_RX_FILTER_12 _ECAN_RX_FILTER_13 _ECAN_RX_FILTER_14 _ECAN_RX_FILTER_15 as as as as as as as as as as as as as as as as as word word word word word word word word word word word word word word word word word = = = = = =
mikoBasic PRO for dsPIC30/33 and PIC24 Copy Code To Clipboard const _ECAN_FILTER_0 _ECAN_FILTER_1 _ECAN_FILTER_2 _ECAN_FILTER_3 _ECAN_FILTER_4 _ECAN_FILTER_5 _ECAN_FILTER_6 _ECAN_FILTER_7 _ECAN_FILTER_8 _ECAN_FILTER_9 _ECAN_FILTER_10 _ECAN_FILTER_11 _ECAN_FILTER_12 _ECAN_FILTER_13 _ECAN_FILTER_14 _ECAN_FILTER_15 as as as as as as as as as as as as as as as as word word word word word word word word word word word word word word word word = = = = = = = = = = = = = = = = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example The example demonstrates ECAN protocol. The 1st 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. The 1st node then does the same and sends incremented data back to the 2nd node, etc.
mikoBasic PRO for dsPIC30/33 and PIC24 IFS2 = 0 IFS3 = 0 IFS4 = 0 ‘ Enable ECAN1 Interrupt IEC2.C1IE = 1 C1INTE.TBIE = 1 C1INTE.
mikroBasic PRO for dsPIC30/33 and PIC24 ECAN1Write(ID_1st, RxTx_Data, 1, Can_Send_Flags) ‘ send initial message while TRUE ‘ endless loop Msg_Rcvd = ECAN1Read(Rx_ID , RxTx_Data , Rx_Data_Len, Can_Rcv_Flags) ‘ receive message if ((Rx_ID = ID_2nd) and (Msg_Rcvd <> 0)) <> 0 then ‘ if message received check id PORTB = RxTx_Data[0] ‘ id correct, output data at PORTB Inc(RxTx_Data[0]) Delay_ms(10) ECAN1Write(ID_1st, RxTx_Data, 1, Can_Send_Flags) ‘ send incremented data back end if wend end.
mikoBasic PRO for dsPIC30/33 and PIC24 AD1PCFGH = 0xFFFF AD1PCFGL = 0xFFFF AD2PCFGL = 0xFFFF ‘ ‘ all ports digital I/O ‘ ‘ Clear Interrupt Flags IFS0 IFS1 IFS2 IFS3 IFS4 = = = = = 0 0 0 0 0 ‘ Enable ECAN1 Interrupt IEC2.C1IE = 1 C1INTE.TBIE = 1 C1INTE.
mikroBasic PRO for dsPIC30/33 and PIC24 while TRUE Msg_Rcvd = ECAN1Read(Rx_ID, RxTx_Data, Rx_Data_Len, Can_Rcv_Flags) ‘ receive message if ((Rx_ID = ID_1st) and (Msg_Rcvd <> 0) <> 0) then ‘ if message received check id PORTB = RxTx_Data[0] ‘ id correct, output data at PORTB Inc(RxTx_Data[0]) ‘ increment received data ECAN1Write(ID_2nd, RxTx_Data, 1, Can_Send_Flags) ‘ send incremented data back end if wend end.
mikoBasic PRO for dsPIC30/33 and PIC24 EEPROM_Erase Prototype sub procedure EEPROM_Erase(dim address as longint) Description Erases a single (16-bit) location from EEPROM memory. Parameters - address: address of the EEPROM memory location to be erased. Returns Nothing. Requires Nothing. Example dim eeAddr as longint ... eeAddr = 0x7FFC80 EEPROM_Erase(eeAddr) Notes CPU is not halted for the Data Erase cycle. The user can poll WR bit, use NVMIF or Timer IRQ to detect the end of erase sequence.
mikroBasic PRO for dsPIC30/33 and PIC24 EEPROM_Write Prototype sub procedure EEPROM_Write(dim address as longint, dim data_ as word) Description Writes data to specified address. Parameters - address: address of the EEPROM memory location to be written. - data: data to be written. Returns Nothing. Requires Nothing. Example dim wrAddr as longint eeData as word ... eeData = 0xAAAA wrAddr = 0x7FFC30 EEPROM_Write(wrAddr, eeData) Notes Specified memory location will be erased before writing starts.
mikoBasic PRO for dsPIC30/33 and PIC24 main: ADPCFG = 0xFFFF ‘ Disable analog inputs TRISB = 0 LATB = 0xFFFF eeAddr = 0x7FFC00 eeData = 0 ‘ PORTB as output while (eeData <= 0x00FF) Eeprom_Write(eeAddr, eeData) Inc(eeData) while (WR_bit) nop wend LATB = Eeprom_Read(eeAddr) eeAddr = eeAddr + 2 ‘ Start address of EEPROM ‘ Data to be written ‘ Write data into EEPROM ‘ Wait for write to finish, ‘ then, read the just-written data.
mikroBasic PRO for dsPIC30/33 and PIC24 Epson S1D13700 Graphic Lcd Library The mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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
mikroBasic PRO for dsPIC30/33 and PIC24 S1D13700_Init Prototype sub procedure S1D13700_Init(dim width as word, dim height as word) Returns Nothing. Description Initializes S1D13700 Graphic Lcd controller. Parameters: - width: width of the Glcd panel. - height: height of the Glcd panel. Requires 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 S1D13700_Write_Parameter Prototype sub procedure S1D13700_Write_Parameter(dim parameter as byte) Returns Nothing. Description Writes a parameter to S1D13700 controller. Parameters: - parameter: parameter to be written. Requires 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 S1D13700_Rectangle_Round_Edges_Fill Prototype 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) Returns 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 S1D13700_PartialImage Prototype sub procedure S1D13700_PartialImage(dim x_left, y_top, width, picture_width, picture_height as word, dim image as ^const byte) Returns Nothing. height, 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Flash Memory Library This library provides routines for accessing microcontroller’s (internal) Flash memory. On the dsPIC30/33 and PIC24, Flash memory is mapped to address space 3:2, which means that every 3 consecutive bytes of Flash have 2 consecutive address locations available. That is why mikroE’s library allows data to be written to flash in two ways: “regular” and “compact”.
mikroBasic PRO for dsPIC30/33 and PIC24 24F04KA201 and 24F16KA102 Family Specifics: - These MCU’s have their Flash memory organized into memory blocks of 32 instructions (96 bytes), unlike other PIC24 devices. - Erasing can be done only in 32-instructions (64 addresses, 96 bytes) memory blocks, which means that the block start address should be a multiply of 64 (i.e. have 6 lower bits set to zero). - Data is read and written in 32-instructions (64 addresses, 96 bytes) blocks.
mikoBasic PRO for dsPIC30/33 and PIC24 dsPIC30 Functions FLASH_Erase32 Prototype sub procedure FLASH_Erase32(dim flash_address as longint) Description Erases one block (32 instructions, 64 addresses, 96 bytes)from the program FLASH memory. Parameters - address: starting address of the FLASH memory block Returns Nothing. Requires Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 FLASH_Write_Compact Prototype sub procedure FLASH_Write_Compact(dim flash_address as longint, dim data_ address as word, dim bytes as word) Description Fills a portion of Flash memory using the dsPIC30 RTSP module, in the “compact” manner. In this way, several blocks of RTSP’s latch can be written in one pass. One latch block contains 4 instructions (8 addresses, 12 bytes). Up to 8 latch blocks can be written in one round, resulting in a total of 8*12 = 96 bytes.
mikoBasic PRO for dsPIC30/33 and PIC24 FLASH_Write_Loadlatch4 Prototype sub procedure FLASH_Write_Loadlatch4() Description Loads the current RTSP write latch with data (4 instructions, 8 addresses, 12 bytes). The data is filled in the “regular” mode. Parameters None. Returns Nothing. Requires The block to be written to must be erased first, either from the user code FLASH_Erase32, or during the programming of MCU.
mikroBasic PRO for dsPIC30/33 and PIC24 FLASH_Write_Loadlatch4_Compact Prototype void FLASH_Write_Loadlatch4_Compact(); Description Loads the current RTSP write latch with data (4 instructions, 8 addresses, 12 bytes). The data is filled in the “compact” mode. Parameters None. Returns Nothing. Requires The block to be written to must be erased first, either from the user code FLASH_Erase32, or during the programming of MCU.
mikoBasic PRO for dsPIC30/33 and PIC24 FLASH_Write_DoWrite Prototype sub procedure FLASH_Write_DoWrite() Description Commits the FLASH write operation. Parameters None. Returns Nothing. Requires The block to be written to must be erased first, either from the user code FLASH_Erase32, or during the programming of MCU.
mikroBasic PRO for dsPIC30/33 and PIC24 FLASH_Read4_Compact Prototype sub procedure FLASH_Read4_Compact(dim flash_address as longint, dim write_to as word) Description Reads one latch row (4 instructions, 8 addresses) in the “compact” mode. Parameters - address: starting address of the FLASH memory block to be read - write_to: starting address of RAM buffer for storing read data Returns Starting address of RAM buffer for storing read data. Requires Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 FLASH_Write Prototype sub procedure word[64]) FLASH_Write(dim address as longint, dim byref data_ as Description Fills one writeable block of Flash memory (64 instructions, 128 addresses, 192 bytes) in the “regular” mode. Addresses and data are being mapped 1-on-1. This also means that 3rd byte of each program location remains unused. Parameters - address: starting address of the FLASH memory block - data_: data to be written Returns Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 FLASH_Read Prototype sub procedure FLASH_Read(dim address as longint, dim byref write_to as word[100], dim NoWords as word) Description Reads required number of words from the flash memory in the “regular” mode. Parameters - address: starting address of the FLASH memory block to be read - write_to: starting address of RAM buffer for storing read data - NoWords: number of words to be read Returns Requires Address of RAM buffer for storing read data.
mikoBasic PRO for dsPIC30/33 and PIC24 Copy Code To Clipboard program Flash_Test dim WriteWordArr as word[8] WriteByteArr as byte[32] ReadByteArr as byte[40] RealongwordArr as word[20] pw as ^word pb as ^byte i as word temp_byte as byte main: ‘ Initialize arrays WriteWordArr[0] = “*” WriteWordArr[4] = “r” WriteByteArr[0] = “m” WriteByteArr[4] = “o” WriteByteArr[8] = “k” WriteByteArr[12] = “n” WriteByteArr[16] = “ “ WriteByteArr[20] = “s” WriteByteArr[24] = “x” WriteByteArr[28] = “l” WriteWordArr[1] = “m” W
mikroBasic PRO for dsPIC30/33 and PIC24 UART1_Write_Text(“Start”) UART1_Write(10) UART1_Write(13) i = 0 while(ReadByteArr[i]) temp_byte = ReadByteArr[i] UART1_Write(temp_byte) Inc(i) wend ‘--- now for some non-compact flash-write pw = @WriteWordArr ‘--- erase the block first FLASH_Erase32(0x006100) FLASH_Write_Init(0x006100, pw) FLASH_Write_Loadlatch4() FLASH_Write_Loadlatch4() FLASH_Write_DoWrite() ‘--- read non-compact format pw = @RealongwordArr[0] FLASH_Read4(0x006100, pw) pw = pw + 4 FLASH_Read4(0x0061
mikoBasic PRO for dsPIC30/33 and PIC24 External dependencies of Graphic Lcd Library The following variables must be defined in all projects using Graphic Lcd Library: Description: Example: dim GLCD_D0 as sbit sfr external Data 0 line.
mikroBasic PRO for dsPIC30/33 and PIC24 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() Descrip
mikoBasic PRO for dsPIC30/33 and PIC24 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 - G
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dim data_ as byte ...
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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..
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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. 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..
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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..
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 pointer to const and pointer to RAM equivalency). Returns Nothing. Requires Glcd needs to be initialized, see Glcd_Init routine.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example The following drawing demo tests advanced routines of the Glcd library.
mikoBasic PRO for dsPIC30/33 and PIC24 Glcd_Init() Glcd_Fill(0x00) while TRUE #IFDEF COMPLETE_EXAMPLE Glcd_Image(@truck_bmp) Delay2S() delay2S() #ENDIF Glcd_Fill(0x00) Glcd_Box(62,40,124,63,1) Glcd_Rectangle(5,5,84,35,1) Glcd_Line(0, 0, 127, 63, 1) Delay2S() counter = 5 while (counter <= 59) Delay_ms(250) Glcd_V_Line(2, 54, counter, 1) Glcd_H_Line(2, 120, counter, 1) Counter = counter + 5 wend ‘ Initialize GLCD ‘ Clear GLCD ‘ Draw image ‘ Clear Glcd ‘ Draw box ‘ Draw rectangle ‘ Draw line ‘ Draw horizonta
mikroBasic PRO for dsPIC30/33 and PIC24 delay2S() Glcd_Set_Font(@FontSystem5x7_v2, 5, 7, 32) someText = “5x7 Font (v2)” Glcd_Write_Text(someText, 51, 6, 2) delay2S() #ENDIF wend end.
mikoBasic PRO for dsPIC30/33 and PIC24 I²C Library The I²C full master I²C module is available with a number of the dsPIC30/33 and PIC24 MCU models. The mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 I2Cx_Start Prototype sub procedure I2Cx_Start() Description Determines if the I²C bus is free and issues 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 ‘ Issue START signal I2C1_Start() Notes I²C library routines require you to specify the module you want to use.
mikoBasic PRO for dsPIC30/33 and PIC24 I2Cx_Is_Idle Prototype sub function I2Cx_Is_Idle() as word Description Waits for the I²C bus to become free. This is a blocking function. Parameters None. Returns Requires - 0 if I²C bus is free. - 1 if I²C bus is not free. 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 dim data_ as byte ... if I2C1_Is_Idle() then I2C1_Write(data_) end if ...
mikroBasic PRO for dsPIC30/33 and PIC24 I2Cx_Write Prototype sub function I2Cx_Write(dim data_ as byte) as word Description Sends data byte via the I²C bus. Parameters - data_: data to be sent Returns Requires - 0 if there were no errors. - 1 if write collision was detected on the I²C bus. MCU with at least one I²C module. Used I²C module must be initialized before using this function. See I2Cx_Init routine. Also, START signal needs to be issued in order to use this function. See I2Cx_Start.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Example This code demonstrates working with the I²C library. Program sends data to EEPROM (data is written at the address 2). After that, program reads data from the same EEPROM address and displays it on PORTB for visual check. See the figure below how to interface the 24C02 to dsPIC30/33 and PIC24.
mikroBasic PRO for dsPIC30/33 and PIC24 Keypad Library mikroBasic PRO for dsPIC30/33 and PIC24 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. External dependencies of Keypad Library The following variable must be defined in all projects using Keypad Library: Description: Example: dim keypadPort as word sfr external Keypad Port.
mikoBasic PRO for dsPIC30/33 and PIC24 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 Port needs to be initialized for working with the Keypad library, see Keypad_Init. Example dim kp as word ...
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 case kp case kp case kp case kp case kp case kp case kp case kp case kp case kp 7 = 54 8 = 66 9 = 55 10 = 56 11 = 57 12 = 67 13 = 42 14 = 48 15 = 35 16 = 68 ‘ 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.
mikroBasic PRO for dsPIC30/33 and PIC24 Lcd Library mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Lcd_Init Prototype sub procedure Lcd_Init() Description Initializes Lcd module. Parameters None. Returns Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example The following code demonstrates usage of the Lcd Library routines: Copy Code To Clipboard program Lcd_Test ‘ LCD module connections dim LCD_RS as sbit at LATD0_bit dim LCD_EN as sbit at LATD1_bit dim LCD_D4 as sbit at LATB0_bit dim LCD_D5 as sbit at LATB1_bit dim LCD_D6 as sbit at LATB2_bit dim LCD_D7 as sbit at LATB3_bit dim LCD_RS_Direction as sbit dim LCD_EN_Direction as sbit dim LCD_D4_Direction as sbit dim LCD_D5_Direction as sbit dim LCD_D6_Dir
mikoBasic PRO for dsPIC30/33 and PIC24 Delay_ms(500) ‘ Moving text for i = 0 to 4 Lcd_Cmd(_LCD_SHIFT_RIGHT) Move_Delay() next i while TRUE for i = 0 to 8 Lcd_Cmd(_LCD_SHIFT_LEFT) Move_Delay() next i for i = 0 to 8 Lcd_Cmd(_LCD_SHIFT_RIGHT) Move_Delay() next i wend end.
mikroBasic PRO for dsPIC30/33 and PIC24 Manchester Code Library mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for handling Manchester coded signals.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 ...
mikoBasic PRO for dsPIC30/33 and PIC24 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 dim msg as byte ... Man_Send(msg) Notes 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 program Manchester_Receiver ‘ LCD module connections dim LCD_RS as sbit at LATD0_bit LCD_EN as sbit at LATD1_bit LCD_D4 as sbit at LATB0_bit LCD_D5 as sbit at LATB1_bit LCD_D6 as sbit at LATB2_bit LCD_D7 as sbit at LATB3_bit dim LCD_RS_Direction as sbit LCD_EN_Direction as sbit LCD_D4_Direction as sbit LCD_D5_Dire
mikroBasic PRO for dsPIC30/33 and PIC24 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 rece
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 provides a library for accessing data on Multi Media Card via SPI communication.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 - 0 - if reading was successful - 1 - if an error occurred MMC/SD card must be initialized. See Mmc_Init.
mikroBasic PRO for dsPIC30/33 and PIC24 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 - 0 - if CID register was read successfully - 1 - if there was an error while reading MMC/SD card must be initialized. See Mmc_Init. Example dim error as word dataBuffer as byte[512] ...
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 ‘ open file for writing Mmc_Fat_Rewrite() Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 Example ‘-------------- 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 Notes Long File Names (LFN) are not supported.
mikoBasic PRO for dsPIC30/33 and PIC24 ‘ 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(2005,6,21,10,35,0) ‘ Set file date & time info Mmc_Fat_Assign(filename, 0xA0) ‘ Will not find file and then cr
mikroBasic PRO for dsPIC30/33 and PIC24 file_contents[26] = 10 Mmc_Fat_Write(file_contents, 27) end sub ‘ 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, procedure returns size of file while size > 0 Mmc_Fat_Read(character) UART1_Write(character) ‘ Write data to UART Dec(size) wend end sub ‘-------------- Deletes a file.
mikoBasic PRO for dsPIC30/33 and PIC24 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 LongIntToStr(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 least 100 ‘ sectors (see Help for details) sub procedure M_Create_Swap_
mikroBasic PRO for dsPIC30/33 and PIC24 ‘--- set up USART for the file read SPI1_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, _SPI_PRESCALE_SEC_1, _SPI_PRESCALE_ PRI_64, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ ACTIVE_2_IDLE) UART1_Init(19200) Delay_ms(100) U1MODE.ALTIO = 1 ‘ Initialize UART module at 9600 bps ‘ Wait for UART module to stabilize ‘ Switch Rx and Tx pins on their alternate locations. ‘ This is used to free the pins for other module, namely the SPI.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Example This example reads the temperature using DS18x20 connected to pin RF6. After reset, MCU obtains temperature from the sensor and prints it on the Lcd. Be sure to set Fosc appropriately in your project, to pull-up RF6 line and to turn off the PORTF leds.
mikroBasic PRO for dsPIC30/33 and PIC24 text[1] = (temp_whole div 10)mod 10 + 48 text[2] = temp_whole mod 10 + 48 ‘ Extract tens digit ‘ Extract ones digit ‘ Extract temp_fraction and convert it to unsigned int temp_fraction = word(temp2write << (4-RES_SHIFT)) temp_fraction = temp_fraction and 0x000F temp_fraction = temp_fraction * 625 ‘ Convert text[4] = text[5] = text[6] = text[7] = temp_fraction to characters word(temp_fraction div 1000) + 48 word((temp_fraction div 100)mod 10 + 48) word((temp_fractio
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection Example of DS1820 connection MikroElektronika 412
mikroBasic PRO for dsPIC30/33 and PIC24 Peripheral Pin Select Library The Peripheral Pin Select library enables user to have more than one digital peripheral multiplexed on a single pin. Users may independently map the input and/or output of any one of many digital peripherals to any one of these I/O pins. The peripherals managed by the Peripheral Pin Select library are all digital only peripherals.
mikoBasic PRO for dsPIC30/33 and PIC24 PPS_Mapping Prototype sub function PPS_Mapping(dim rp_num, input_output, funct_name as byte) Description Sets desired internal MCU module to be mapped on the requested pins. Parameters - rp_num: Remappable pin number. Consult the appropriate datasheet for adequate values. - direction: Sets requested pin to be used as an input or output. See Direction Parameters for adequate values. - funct_name: Selects internal MCU module function for usage.
mikroBasic PRO for dsPIC30/33 and PIC24 _QEA1 QEI1 Phase A _T1CK Timer1 External Clock _QEA2 QEI2 Phase A _T2CK Timer2 External Clock _QEB1 QEI1 Phase B _T3CK Timer3 External Clock _QEB2 QEI2 Phase B _T4CK Timer4 External Clock _SCK1IN SPI1 Clock Input _T5CK Timer5 External Clock _SCK2IN SPI2 Clock Input _U1CTS UART1 Clear To Send _SCK3IN SPI3 Clock Input _U2CTS UART2 Clear To Send _SDI1 SPI1 Data Input _U3CTS UART3 Clear To Send _SDI2 SPI2 Data Input _U4CTS UART4 Clear To
mikoBasic PRO for dsPIC30/33 and PIC24 _OC9 Output Compare 9 _OCFA Output Compare Fault A _OCFB Output Compare Fault B _PWM4H RPn tied to PWM output pins associated with PWM Generator 4 _PWM4L RPn tied to PWM output pins associated with PWM Generator 4 _REFCLKO REFCLK output signal _SCK1OUT SPI1 Clock Output _SCK2OUT SPI2 Clock Output _SCK3OUT SPI3 Clock Output _SDO1 SPI1 Data Output _SDO2 SPI2 Data Output _SDO3 SPI3 Data Output _SS1OUT SPI1 Slave Select Output _SS2OUT SPI2 Slave
mikroBasic PRO for dsPIC30/33 and PIC24 Port Expander Library mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for communication with the Microchip’s Port Expander MCP23S17 via SPI interface. Connections of the dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 Expander_Write_Byte Prototype sub procedure Expander_Write_Byte(dim ModuleAddress, RegAddress, Data as byte) Description Routine writes a byte to Port Expander. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - RegAddress: Port Expander’s internal register address - Data: data to be written Returns Byte read. Requires Port Expander must be initialized. See Expander_Init.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 HW Connection Port Expander HW connection 427 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 PS/2 Library The mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 430
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example This simple example reads values of the pressed keys on the PS/2 keyboard and sends them via UART.
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection Example of PS2 keyboard connection PWM Library The CCP module is available with a number of dsPIC30/33 and PIC24 MCUs. mikroBasic PRO for dsPIC30/33 and PIC24 provides a library which simplifies using of the PWM HW Module. Important: PWM module uses either Timer2 or Timer3 module.
mikroBasic PRO for dsPIC30/33 and PIC24 PWM_Init Prototype sub function PWM_Init(dim freq_hz as longint, dim enable_channel_x, timer_ prescale, use_timer_x as word) as word ‘ 30F1010 and dsPIC33FJ06GS101/102/202 prototype sub function PWM_Init(dim freq_hz as longint, dim enable_channel_x, timer_ prescale) as word Description Initializes the PWM module with duty ratio 0.
mikoBasic PRO for dsPIC30/33 and PIC24 PWM_Start Prototype sub procedure PWM_Start(dim enable_channel_x as byte) Description Starts PWM at requested channel. Parameters - enable_channel_x: number of PWM channel Returns Nothing. Requires MCU must have the HW PWM Module. PWM channel must be properly configured. See the PWM_Init and PWM_Set_Duty routines. Example ‘ start PWM at channel 1 PWM_Start(1) Notes Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
mikroBasic PRO for dsPIC30/33 and PIC24 pwm_period1 = PWM_Init(5000 , 1, 1, 2) pwm_period2 = PWM_Init(10000, 2, 1, 3) PWM_Start(1) PWM_Start(2) PWM_Set_Duty(current_duty, 1) PWM_Set_Duty(current_duty1, 2) while (TRUE) if RB0_bit = 1 then Delay_ms(20) Inc(current_duty) if (current_duty > pwm_period1) then possible pwm_period1 value current_duty = 0 end if PWM_Set_Duty(current_duty, 1) end if if RB1_bit = 1 then Delay_ms(20) Dec(current_duty) if (current_duty > pwm_period1) then possible pwm_period1 value (ov
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection PWM demonstration PWM Motor Control Library The PWM Motor Control module is available with a number of dsPIC30/33 MCUs. mikroBasic PRO for dsPIC30/33 and PIC24 provides a library which simplifies using the PWM Motor Control module. Important: - Number of PWM modules per MCU differs from chip to chip. Please, read the appropriate datasheet before utilizing this library. - PWM library routines require you to specify the module you want to use.
mikroBasic PRO for dsPIC30/33 and PIC24 PWMx_Mc_Init Prototype sub function PWMx_Mc_Init(dim freq_hz, pair_output_mode, enable_output_x, clock_prescale_output_postscale as word) as word Description Initializes the Motor Control PWM module with duty ratio 0. The function calculates timer period, writes it to the MCU’s PTPER register and returns it as the function result.
mikoBasic PRO for dsPIC30/33 and PIC24 PWMx_Mc_Set_Duty Prototype sub procedure PWM1_Mc_Set_Duty(dim duty, channel as word) ‘ For dsPIC 33FJ MCUs that have PWM2 module : sub procedure PWM2_Mc_Set_Duty(dim duty as word) Description The function changes PWM duty ratio. Parameters - duty: PWM duty ratio. Valid values: 0 to timer period returned by the PWMx_Mc_Init function. - channel: number of PWM channel to change duty to. Returns Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 PWMx_Mc_Stop Prototype sub procedure PWMx_Mc_Stop() Description Stops the Motor Control PWM module. Parameters None. Returns Nothing. Requires The dsPIC30/33 MCU must have the Motor Control PWM module. Example ‘ stop the Motor Control PWM1 module PWM1_Mc_Stop() Notes - Number of PWM modules per MCU differs from chip to chip. Please, read the appropriate datasheet before utilizing this library.
mikoBasic PRO for dsPIC30/33 and PIC24 if (current_duty > pwm_period) then possible pwm_period value (overflow) current_duty = pwm_period end if PWM1_MC_Set_Duty(current_duty, end if Delay_ms(5) wend end.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Dependency Tree External dependencies of RS-485 Library The following variable must be defined in all projects using RS-485 Library: Description: Example: dim RS485_rxtx_pin as sbit sfr external Control RS-485 Transmit/Receive operation mode dim RS485_rxtx_pin as sbit at RF2_ bit dim RS485_rxtx_pin_direction as sbit sfr external Direction of the RS-485 Transmit/ Receive pin dim RS485_rxtx_pin_direction as sbit at TRISF2_bit Library Routines - RS485Ma
mikoBasic PRO for dsPIC30/33 and PIC24 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..
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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..
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example The example demonstrates working with the dsPIC as a Master node in 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.
mikoBasic PRO for dsPIC30/33 and PIC24 U2RXIE_bit = 1 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 > 10) then RS485Master_Send(dat,1,50) end if end if wend end.
mikroBasic PRO for dsPIC30/33 and PIC24 PORTB PORTD TRISB TRISD = = = = 0 0 0 0 UART2_Init(9600) Delay_ms(100) ‘ initialize UART2 module RS485Slave_Init(160) ‘ Intialize MCU as slave, address 160 dat[0] dat[1] dat[2] dat[4] dat[5] dat[6] = = = = = = 0xAA 0xF0 0x0F 0 0 0 URXISEL1_U2STA_bit = 0 URXISEL1_U2STA_bit = 0 NSTDIS_bit = 1 U2RXIF_bit = 0 U2RXIE_bit = 1 while (TRUE) if (dat[5] <> 0) then PORTD = 0xAA dat[5] = 0 end if if (dat[4] <> 0) then dat[4] = 0 j = dat[3] for i = 1 to dat[3] PORTB = da
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection Example of interfacing PC to dsPIC MCU via RS485 bus with LTC485 as RS-485 transceiver MikroElektronika 448
mikroBasic PRO for dsPIC30/33 and PIC24 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
mikoBasic PRO for dsPIC30/33 and PIC24 Software I²C Library The mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Example The example demonstrates use of the Software I²C Library. The dsPIC30/33 or PIC24 MCU is connected (SCL, SDA pins) to PCF8583 RTC (real-time clock). Program sends date/time to RTC.
mikroBasic PRO for dsPIC30/33 and PIC24 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 s
mikoBasic PRO for dsPIC30/33 and PIC24 Software SPI Library The mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 Soft_SPI_Init Prototype sub procedure Soft_SPI_Init() Description Routine initializes the software SPI module. Parameters None. Returns Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 Soft_SPI_Write Prototype sub procedure Soft_SPI_Write(dim data_ as byte) Description This routine sends one byte via the Software SPI bus. Parameters - sdata: data to be sent. Returns Nothing. Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init. Example ‘ Write a byte to the Soft SPI bus Soft_SPI_Write($AA) Notes None Library Example This code demonstrates using library routines for Soft_SPI communication.
mikroBasic PRO for dsPIC30/33 and PIC24 ‘ Send High Byte temp = word(valueDAC >> 8) and 0x0F temp = temp or 0x30 Soft_SPI_Write(temp) ‘ Send Low Byte temp = valueDAC Soft_SPI_Write(temp) Chip_Select = 1 end sub ‘ Store valueDAC[11..8] to temp[3..0] ‘ Define DAC setting, see MCP4921 datasheet ‘ Send high byte via Soft SPI ‘ Store valueDAC[7..0] to temp[7..
mikoBasic PRO for dsPIC30/33 and PIC24 Software UART Library mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 USART communication terminal, launch it from the drop-down menu Tools › USART Terminal or simply click the USART Terminal Icon .
mikoBasic PRO for dsPIC30/33 and PIC24 Sound Library mikroBasic PRO for dsPIC30/33 and PIC24 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).
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker.
mikoBasic PRO for dsPIC30/33 and PIC24 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 ‘ Wait for button to be released if (Button(PORTB,6,1,1)) then Tone2() while (RB6_bit <> 0) nop wend end if ‘ If PORTB.6 is pressed play Tone1 if (Button(PORTB,5,1,1)) then Tone3() while (RB5_bit <> 0) nop wend end if ‘ If PORTB.
mikroBasic PRO for dsPIC30/33 and PIC24 HW Connection Example of Sound Library 467 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 SPI Library The SPI module is available with all dsPIC30/33 and PIC24 MCUs. mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for initializing the Slave mode and initializing and comfortable work with the Master mode. The dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 - secondary prescaler 1:1 - primary prescaler 64:1 - Slave Select disabled - input data sampled in the middle of interval - clock idle state low - Serial output data changes on transition from active clock state to idle clock state Parameters None. Returns Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 SPIx_Init_Advanced Prototype sub procedure SPIx_Init_Advanced(dim master_mode, mode16, sec_prescaler, pri_prescaler, slave_select, data_sample, clock_idle, edge as word) Description Configures and initializes the SPI module with user defined settings. Parameters Parameters master_mode, mode16, sec_prescaler, pri_prescaler, slave_select, data_ sample, clock_idle and determine the working mode for SPI.
mikroBasic PRO for dsPIC30/33 and PIC24 Parameters The parameter slave_select determines whether the Slave Select (SS) pin is used in communication. Valid in the Slave Mode only. Slave Select Enable/Disable Description Predefined library const SS used for the Slave mode SS not used for the Slave mode _SPI_SS_ENABLE _SPI_SS_DISABLE The parameter data_sample determines the sample moment (phase) of input data.
mikoBasic PRO for dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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: - read_ptr: SPI1_Read handler - write_ptr: SPI1_Write handler Returns Nothing. Requires Routine is available only for MCUs with multiple SPI modules. Used SPI module must be initialized before using this function.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI1_Write(temp) ‘ Send high byte via SPI ‘ Send Low Byte temp = valueDAC SPI1_Write(temp) ‘ Store valueDAC[7..0] to temp[7..
mikroBasic PRO for dsPIC30/33 and PIC24 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.
mikoBasic PRO for dsPIC30/33 and PIC24 External dependencies of SPI Ethernet Library The following variables must be defined in all Description: projects using SPI Ethernet Library: Example: dim SPI_Ethernet_CS external dim SPI_Ethernet_CS RC1_bit as sbit sfr ENC28J60 chip select pin. as sbit sfr ENC28J60 reset pin. dim SPI_Ethernet_CS_Direction sbit sfr external as Direction of the ENC28J60 chip select pin. as Direction of the ENC28J60 reset pin.
mikroBasic PRO for dsPIC30/33 and PIC24 - SPI_Ethernet_dnsResolve - SPI_Ethernet_initDHCP - SPI_Ethernet_doDHCPLeaseTime - SPI_Ethernet_renewDHCP SPI_Ethernet_Init Prototype sub procedure SPI_Ethernet_Init(dim mac as ^byte, dim ip as ^byte, dim fullDuplex as byte) Description This is MAC module routine. It initializes ENC28J60 controller. This function is internaly splited into 2 parts to help linker when coming short of memory.
mikoBasic PRO for dsPIC30/33 and PIC24 Example ‘ mE ehternet NIC pinout dim SPI_Ethernet_RST as sbit at LATF0_bit dim SPI_Ethernet_CS as sbit at LATF1_bit dim SPI_Ethernet_RST_Direction as sbit at TRISF0_bit dim SPI_Ethernet_CS_Direction as sbit at TRISF1_bit ‘ end mE ehternet NIC pinout const SPI_Ethernet_HALFDUPLEX = 0 const SPI_Ethernet_FULLDUPLEX = 1 myMacAddr as myIpAddr as ...
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 SPI_Ethernet_putString Prototype sub function SPI_Ethernet_putString(dim ptr as ^byte) as word Description This is MAC module routine. It stores whole string (excluding null termination) into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location. Parameters - ptr: string to be written into ENC28J60 RAM. Returns Requires Number of bytes written into ENC28J60 RAM. Ethernet module has to be initialized. See SPI_Ethernet_Init.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_getBytes Prototype sub procedure SPI_Ethernet_getBytes(dim ptr as ^byte, dim addr as word, dim n as word) Description This is MAC module routine. It fetches equested number of bytes from ENC28J60 RAM starting from given address. If value of 0xFFFF is passed as the address parameter, the reading will start from current ENC28J60 read pointer (ERDPT) location. Parameters - ptr: buffer for storing bytes read from ENC28J60 RAM.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 SPI_Ethernet_getIpAddress Prototype sub function SPI_Ethernet_getIpAddress() as word Description This routine should be used when DHCP server is present on the network to fetch assigned IP address. Parameters None. Returns Pointer to the global variable holding IP address. Requires Ethernet module has to be initialized. See SPI_Ethernet_Init. Example Notes dim ipAddr as byte[4] ‘ user IP address buffer ...
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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.
mikroBasic PRO for dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 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 dsPIC30/33 and PIC24 gwIpAddr ipMask dnsIpAddr as byte[4] as byte[4] as byte[4] ‘ gateway (router) IP address ‘ network mask (for example : 255.255.255.0) ‘ DNS server IP address ‘ ************************************************************ ‘ * ROM constant strings ‘ * const httpHeader as string[31] = “HTTP/1.
mikoBasic PRO for dsPIC30/33 and PIC24 “str=”+chr(34)+chr(34)+”; “+ “for(i=0;i<4;i++)”+ “{str+=”+chr(34)+”
LED #”+chr(34)+”+i+”+chr(34)+” | ”+chr(34)+”; “+ “if(PORTD&(1<ON”+chr(34)+”;}”+ “else {str+=”+chr(34)+”OFF”+chr(34)+”;}”+ “str+=”+chr(34)+” | Toggl e |
”+chr(34)+”;}”+ “document.mikroBasic PRO for dsPIC30/33 and PIC24 ‘ get 10 first bytes only of the request, the rest does not matter here for i = 0 to 10 getRequest[i] = Spi_Ethernet_getByte() next i getRequest[i] = 0 ‘ copy httpMethod to ram for use in memcmp routine for i = 0 to 4 txt[i] = httpMethod[i] next i if(memcmp(@getRequest, @txt, 5) <> 0) then result = 0 exit end if Inc(httpCounter) ‘ only GET method is supported here ‘ one more request done if(getRequest[5] = “s”) then ‘ if request path name starts with s, store dynam
mikoBasic PRO for dsPIC30/33 and PIC24 ‘ add PORTD value (LEDs) to reply txt = “var PORTD=” result = result + Spi_Ethernet_putString(@txt) WordToStr(PORTD, dyna) result = result + Spi_Ethernet_putString(@dyna) txt = “;” result = result + Spi_Ethernet_putString(@txt) ‘ add HTTP requests counter to reply WordToStr(httpCounter, dyna) txt = “var REQ=” result = result + Spi_Ethernet_putString(@txt) result = result + Spi_Ethernet_putString(@dyna) txt = “;” result = result + Spi_Ethernet_putString(@txt) else if(ge
mikroBasic PRO for dsPIC30/33 and PIC24 dim txt as string[5] result = 0 ‘ reply is made of the remote host IP address in human readable format byteToStr(remoteHost[0], dyna) ‘ first IP address byte dyna[3] = “.” byteToStr(remoteHost[1], txt) ‘ second dyna[4] = txt[0] dyna[5] = txt[1] dyna[6] = txt[2] dyna[7] = “.” byteToStr(remoteHost[2], txt) ‘ second dyna[8] = txt[0] dyna[9] = txt[1] dyna[10] = txt[2] dyna[11] = “.
mikoBasic PRO for dsPIC30/33 and PIC24 main: ADPCFG = 0xFFFD ‘ Set AN pins as digital I/O except AN0 and AN1 PORTB = 0 TRISB = 0xFFFF ‘ set PORTB as input for buttons and adc PORTD = 0 TRISD = 0 ‘ set PORTD as output ADC1_Init() httpCounter = 0 ‘ set mac address myMacAddr[0] = 0x00 myMacAddr[1] = 0x14 myMacAddr[2] = 0xA5 myMacAddr[3] = 0x76 myMacAddr[4] = 0x19 myMacAddr[5] = 0x3F ‘ set IP address myIpAddr[0] = 192 myIpAddr[1] = 168 myIpAddr[2] = 20 myIpAddr[3] = 60 ‘ set gateway address gwIpAddr[0] =
mikroBasic PRO for dsPIC30/33 and PIC24 SPI1_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, _SPI_PRESCALE_SEC_1, _SPI_PRESCALE_PRI_4, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_ IDLE_2_ACTIVE) SPI_Ethernet_Init(myMacAddr, myIpAddr, _SPI_Ethernet_FULLDUPLEX) ‘ init ethernet module SPI_Ethernet_setUserHandlers(@SPI_Ethernet_UserTCP, @SPI_Ethernet_UserUDP) ‘ set user handlers ‘ dhcp will not be used here, so use preconfigured addresses SPI_Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr) while
mikoBasic PRO for dsPIC30/33 and PIC24 SPI Ethernet ENC24J600 Library The ENC24J600 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 ENC24J600 meets all of the IEEE 802.3 specifications applicable to 10Base-T and 100Base-TX Ethernet. It incorporates a number of packet filtering schemes to limit incoming packets.
mikroBasic PRO for dsPIC30/33 and PIC24 External dependencies of SPI Ethernet ENC24J600 Library The following variables must be defined in all projects using SPI Ethernet Description: ENC24J600 Library: Example: dim SPI_Ethernet_24j600_CS sbit sfr external dim SPI_Ethernet_24j600_CS as sbit at RC1_bit as dim SPI_Ethernet_24j600_CS_ Direction as sbit sfr external ENC24J600 chip select pin. Direction of the ENC24J600 chip select pin.
mikoBasic PRO for dsPIC30/33 and PIC24 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_24j600_putString - SPI_Ethernet_24j600_putConstString - SPI_Ethernet_24j600_putConstBytes - SPI_Ethernet_24j600_getByte - SPI_Ethernet_24j600_getBytes - SPI_Ethernet_24j600_UserTCP - SPI_Ethernet_24j600_UserUDP - SPI_Ethernet_24j600_setUserHandlers - SPI_Ethernet
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_Init Prototype sub procedure SPI_Ethernet_24j600_Init(dim mac as ^byte, dim ip as ^byte, dim fullDuplex as byte) Description This is MAC module routine. It initializes ENC24J600 controller. This function is internally splited into 2 parts to help linker when coming short of memory. ENC24J600 controller settings (parameters not mentioned here are set to default): - receive buffer start address : 0x0000. - receive buffer end address : 0x19AD.
mikoBasic PRO for dsPIC30/33 and PIC24 Returns Nothing. Requires Global variables: - SPI_Ethernet_24j600_CS: Chip Select line - SPI_Ethernet_24j600_CS_Direction: Direction of the Chip Select pin - SPI_Ethernet_24j600_RST: Reset line - SPI_Ethernet_24j600_RST_Direction: Direction of the Reset pin must be defined before using this function. The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_Enable Prototype sub procedure SPI_Ethernet_24j600_Enable(dim enFlt as word) Description This is MAC module routine. This routine enables appropriate network traffic on the ENC24J600 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.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_Disable Prototype sub procedure SPI_Ethernet_24j600_Disable(dim disFlt as word) Description This is MAC module routine. This routine disables appropriate network traffic on the ENC24J600 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.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_doPacket Prototype sub function SPI_Ethernet_24j600_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_24j600_UserTCP function is called for further processing. - upon UDP request the SPI_Ethernet_24j600_UserUDP function is called for further processing.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_putBytes Prototype sub procedure SPI_Ethernet_24j600_putBytes(dim ptr as ^byte, dim n as word) Description This is MAC module routine. It stores requested number of bytes into ENC24J600 RAM starting from current ENC24J600 write pointer (EWRPT) location. Parameters - ptr: RAM buffer containing bytes to be written into ENC24J600 RAM. - n: number of bytes to be written. Returns Nothing. Requires Ethernet module has to be initialized.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_putString Prototype sub function SPI_Ethernet_24j600_putString(dim ptr as ^byte) as word Description This is MAC module routine. It stores whole string (excluding null termination) into ENC24J600 RAM starting from current ENC24J600 write pointer (EWRPT) location. Parameters - ptr: string to be written into ENC24J600 RAM. Returns Requires Number of bytes written into ENC24J600 RAM. Ethernet module has to be initialized.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_getBytes Prototype sub procedure SPI_Ethernet_24j600_getBytes(dim ptr as ^byte, dim addr as word, dim n as word) Description This is MAC module routine. It fetches equested number of bytes from ENC24J600 RAM starting from given address. If value of 0xFFFF is passed as the address parameter, the reading will start from current ENC24J600 read pointer (ERDPT) location. Parameters - ptr: buffer for storing bytes read from ENC24J600 RAM.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_UserUDP Prototype sub function SPI_Ethernet_24j600_UserUDP(dim byref remoteHost as byte[4], dim remotePort as word, dim destPort as word, dim reqLength as word, dim byref flags as TEthJ600PktFlags) 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_24j600_get routines.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_getIpAddress Prototype sub function SPI_Ethernet_24j600_getIpAddress() as word Description This routine should be used when DHCP server is present on the network to fetch assigned IP address. Parameters None. Returns Pointer to the global variable holding IP address. Requires Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init. Example dim ipAddr as byte[4] ‘ user IP address buffer ...
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_getIpMask Prototype sub function SPI_Ethernet_24j600_getIpMask() 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_24j600_Init. Available for PIC18 family MCUs only.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_arpResolve Prototype sub function SPI_Ethernet_24j600_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. Parameters - ip: IP address to be resolved. - tmax: time in seconds to wait for an reply.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_dnsResolve Prototype sub function SPI_Ethernet_24j600_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.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_initDHCP Prototype sub function SPI_Ethernet_24j600_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.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Ethernet_24j600_renewDHCP Prototype sub function SPI_Ethernet_24j600_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 517 - 1 - upon success (lease time was renewed). - 0 - otherwise (renewal request timed out). Ethernet module has to be initialized. See SPI_Ethernet_24j600_Init.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Example This code shows how to use the Ethernet mini library: -the board will reply to ARP & ICMP echo requests -the board will reply to UDP requests on any port : - returns the request in upper char with a header made of remote host IP & port number -the board will reply to HTTP requests on port 80, GET method with pathnames: - / will return the HTML main page - /s will return board status as text string - /t0 ...
mikroBasic PRO for dsPIC30/33 and PIC24 SPI Graphic Lcd Library mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for operating Graphic Lcd 128x64 (with commonly used Samsung KS108/KS107 controller) via SPI interface. For creating a custom set of Glcd images use Glcd Bitmap Editor Tool. Important: - When using this library with dsPIC33 and PIC24 family MCUs be aware of their voltage incompatibility with certain number of Samsung KS0108 based Glcd modules.
mikoBasic PRO for dsPIC30/33 and PIC24 - 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 SPI_Glcd_Init Prototype sub procedure SPI_Glcd_Init() Description Initializes the Glcd module via SPI interface.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Set_Side Prototype sub procedure SPI_Glcd_Set_Side(dim x_pos as byte) Description Selects Glcd side. Refer to the Glcd datasheet for detail explanation. Parameters - x_pos: position on x-axis. Valid values: 0..127 The parameter x_pos specifies the Glcd side: values from 0 to 63 specify the left side, values from 64 to 127 specify the right side. Returns Nothing. Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Read_Data Prototype sub function SPI_Glcd_Read_Data() as byte Description Reads data from the current location of Glcd memory and moves to the next location. Returns One byte from Glcd memory. Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine. Glcd side, x-axis position and page should be set first. See the functions SPI_Glcd_Set_Side, SPI_ Glcd_Set_X, and SPI_Glcd_Set_Page. Parameters None.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Dot Prototype sub procedure SPI_Glcd_Dot(dim x_pos, y_pos, color as byte) Description Draws a dot on Glcd at coordinates (x_pos, y_pos). Parameters - x_pos: x position. Valid values: 0..127 - y_pos: y position. Valid values: 0..63 - color: color parameter. Valid values: 0..2 Returns The parameter color determines the dot state: 0 clears dot, 1 puts a dot, and 2 inverts dot state. Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_V_Line Prototype sub procedure SPI_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..
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Rectangle Prototype sub procedure SPI_Glcd_Rectangle(dim x_upper_left, y_upper_left, x_bottom_ right, y_bottom_right, color as byte) 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..
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Rectangle_Round_Edges_Fill Prototype sub procedure SPI_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..
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Circle Prototype sub procedure SPI_Glcd_Circle(dim x_center, y_center, radius as integer, dim color as byte) Description Draws a circle on Glcd. 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..
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Set_Font Prototype sub procedure SPI_Glcd_Set_Font(dim activeFont as LongInt, dim aFontWidth, aFontHeight as byte, dim aFontOffs as word) Description Sets font that will be used with SPI_Glcd_Write_Char and SPI_Glcd_Write_Text routines. Parameters None. Returns - 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.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Write_Char Prototype sub procedure byte) SPI_Glcd_Write_Char(dim chr1, x_pos, page_num, color as Description Prints character on Glcd. Parameters - chr1: character to be written - x_pos: character starting position on x-axis. Valid values: 0..(127-FontWidth) - page_num: the number of the page on which character will be written. Valid values: 0..7 - color: color parameter. Valid values: 0..
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Glcd_Image Prototype sub procedure SPI_Glcd_Image(dim byref const image 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 dsPIC30/33 and PIC24 pointer to const and pointer to RAM equivalency). Returns Nothing. Requires Glcd needs to be initialized for SPI communication, see SPI_Glcd_Init routine.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example The example demonstrates how to communicate to KS0108 Glcd via the SPI module, using serial to parallel convertor MCP23S17.
mikoBasic PRO for dsPIC30/33 and PIC24 Delay2s() #IFDEF COMPLETE_EXAMPLE SPI_Glcd_Fill(0x00) SPI_Glcd_Set_Font(@Character8x7, 8, 7, 32) SPI_Glcd_Write_Text(“mikroE”, 1, 7, 2) #ENDIF for counter = 1 to 10 SPI_Glcd_Circle(63,32, 3*counter, 1) next counter Delay2s() ‘ Clear Glcd ‘ Choose font ‘ Write string ‘ Draw circles #IFDEF COMPLETE_EXAMPLE SPI_Glcd_Box(10,20, 70,63, 2) Delay2s() ‘ Draw box SPI_Glcd_Fill(0xFF) ‘ Fill Glcd SPI_Glcd_Set_Font(@Character8x7, 8, 7, 32) someText = “8x7 Font” SPI_Glcd_Writ
mikroBasic PRO for dsPIC30/33 and PIC24 HW Connection SPI Glcd HW connection 533 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 SPI Lcd Library The mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for communication with Lcd (with HD44780 compliant controllers) in 4-bit mode via SPI interface. For creating a custom set of Lcd characters use Lcd Custom Character Tool. Important: - When using this library with dsPIC33 and PIC24 family MCUs be aware of their voltage incompatibility with certain number of Lcd modules. So, additional external power supply for these modules may be required.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Lcd_Config Prototype sub procedure SPI_Lcd_Config(dim DeviceAddress as byte) Description Initializes the Lcd module via SPI interface. Parameters - DeviceAddress: SPI expander hardware address, see schematic at the bottom of this page Returns Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Lcd_Out_Cp Prototype sub procedure SPI_Lcd_Out_CP(dim byref text as string) Description Prints text on the Lcd at current cursor position. Both string variables and literals can be passed as a text. Parameters - text: text to be written Returns Nothing. Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routine. Example ‘ Write text “Here!” at current cursor position: SPI_Lcd_Out_CP(“Here!”) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Lcd_Cmd Prototype sub procedure SPI_Lcd_Cmd(dim out_char as byte) Description Sends command to Lcd. Parameters - out_char: command to be sent Returns Nothing. Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd_Config routine. Example ‘ Clear Lcd display: SPI_Lcd_Cmd(_LCD_CLEAR) Notes Predefined constants can be passed to the routine, see Available SPI Lcd Commands.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Example Default Pin Configuration Use SPI_Lcd_Init for default pin settings (see the first figure below).
mikroBasic PRO for dsPIC30/33 and PIC24 Lcd HW connection by default initialization (using SPI_Lcd_Init) 539 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 SPI Lcd8 (8-bit interface) Library The mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for communication with Lcd (with HD44780 compliant controllers) in 8-bit mode via SPI interface. For creating a custom set of Lcd characters use Lcd Custom Character Tool. Important: - When using this library with dsPIC33 and PIC24 family MCUs be aware of their voltage incompatibility with certain number of Lcd modules.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Lcd8_Config Prototype sub procedure SPI_Lcd8_Config(dim DeviceAddress as byte) Description Initializes the Lcd module via SPI interface. Parameters - DeviceAddress: SPI expander hardware address, see schematic at the bottom of this page Returns Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_Lcd8_Out_Cp Prototype sub procedure SPI_Lcd8_Out_CP(dim byref text as string) Description Prints text on Lcd at current cursor position. Both string variables and literals can be passed as a text. Parameters - text: text to be written Returns Nothing. Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine. Example ‘ Write text “Here!” at current cursor position: SPI_Lcd8_Out_Cp(“Here!”) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_Lcd8_Cmd Prototype sub procedure SPI_Lcd8_Cmd(dim out_char as byte) Description Sends command to Lcd. Parameters - out_char: command to be sent Returns Nothing. Requires Lcd needs to be initialized for SPI communication, see SPI_Lcd8_Config routine. Example ‘ Clear Lcd display: SPI_Lcd8_Cmd(_LCD_CLEAR) Notes Predefined constants can be passed to the routine, see Available SPI Lcd8 Commands.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Example This example demonstrates how to communicate Lcd in 8-bit mode via the SPI module, using serial to parallel convertor MCP23S17.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI Lcd8 HW connection 545 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 SPI T6963C Graphic Lcd Library The mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for working with Glcds based on TOSHIBA T6963C controller via SPI interface. The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules. It is capable of controlling displays with a resolution up to 240x128.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Routines - SPI_T6963C_config - SPI_T6963C_writeData - SPI_T6963C_writeCommand - SPI_T6963C_setPtr - SPI_T6963C_waitReady - SPI_T6963C_fill - SPI_T6963C_dot - SPI_T6963C_write_char - SPI_T6963C_write_text - SPI_T6963C_line - SPI_T6963C_rectangle - SPI_T6963C_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_
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_config Prototype sub procedure SPI_T6963C_config(dim width, height, DeviceAddress as byte, dim wr, rd, cd, rst as byte) fntW as word, dim Description Initializes T6963C Graphic Lcd controller. Display RAM organization: The library cuts RAM into panels: a complete panel is one graphics panel followed by a text panel (see schematic below).
mikroBasic PRO for dsPIC30/33 and PIC24 Example ‘ Port Expander module connections dim SPExpanderRST as sbit at LATF0_bit SPExpanderCS as sbit at LATF1_bit SPExpanderRST_Direction as sbit at TRISF0_bit SPExpanderCS_Direction as sbit at TRISF1_bit ‘ End Port Expander module connections ... ‘ Initialize SPI module SPI1_Init() SPI_T6963C_Config(240, 64, 8, 0, 0, 1, 3, 4) Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_setPtr Prototype sub procedure SPI_T6963C_setPtr(dim p as word, dim c as byte) Description Sets the memory pointer p for command p. Parameters - p: address where command should be written - c: command to be written Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine. Example SPI_T6963C_setPtr(SPI_T6963C_grHomeAddr POINTER_SET) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_dot Prototype sub procedure SPI_T6963C_dot(dim x, y as integer, dim color as byte) Description Writes a char in the current text panel of Glcd at coordinates (x, y). Returns Requires - x: dot position on x-axis - y: dot position on y-axis - color: color parameter. Valid values: SPI_T6963C_BLACK and SPI_T6963C_WHITE Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine. Example SPI_T6963C_dot(x0, y0, SPI_T6963C_BLACK) Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_write_text Prototype sub procedure SPI_T6963C_write_text(dim byref str as byte[10], dim x, y, mode as byte) 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 - y: text position on y-axis - mode: mode parameter.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_rectangle Prototype sub procedure SPI_T6963C_rectangle(dim x0, y0, x1, y1 as integer, dim pcolor as byte) 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.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_rectangle_round_edges_fill Prototype sub procedure SPI_T6963C_rectangle_round_edges_fill(dim x0 as integer, dim y0 as integer, dim x1 as integer, dim y1 as integer, dim radius as integer, dim pcolor as byte) Description Draws a filled rounded edge rectangle on Glcd.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_circle Prototype sub procedure SPI_T6963C_circle(dim x, y as integer, dim r as longint, dim pcolor as word) Description Draws a circle on the Glcd. Parameters - x: x coordinate of the circle center - y: y coordinate of the circle center - r: radius size - pcolor: color parameter. Valid values: SPI_T6963C_BLACK and SPI_T6963C_WHITE Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_PartialImage Prototype sub procedure SPI_T6963C_PartialImage(dim x_left, y_top, width, height, picture_width, picture_height as word, const image as ^byte) 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.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_set_cursor Prototype sub procedure SPI_T6963c_set_cursor(dim x, y as byte) Description Sets cursor to row x and column y. Parameters - x: cursor position row number - y: cursor position column number Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine. Example SPI_T6963c_set_cursor(cposx, cposy) Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_negBit Prototype sub procedure SPI_T6963C_negBit(dim b as byte) Description Negates control port bit(s). Parameters - b: bit mask. The function will negate bit x on control port if bit x in bit mask is set to 1. Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine. Example ‘ negate bits 0 and 1 on control port SPI_T6963C_negBit(0x0003) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_setGrPanel Prototype sub procedure SPI_T6963C_setGrPanel(dim n as word) Description Compute start address for selected graphic panel and set appropriate internal pointers. All subsequent graphic operations will be preformed at this graphic panel. Parameters - n: graphic panel number. Valid values: 0 and 1. Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_grFill Prototype sub procedure SPI_T6963C_grFill(dim v as word) Description Fill current graphic panel with appropriate value (0 to clear). Parameters - v: value to fill graphic panel with. Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine. Example ‘ clear current graphic panel SPI_T6963C_grFill(0) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_graphics Prototype sub procedure SPI_T6963C_graphics(dim n as word) Description Enable/disable graphic displaying. Parameters - n: graphic enable/disable parameter. Valid values: 0 (disable graphic dispaying) and 1 (enable graphic displaying). Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine. Example ‘ enable graphic displaying SPI_T6963C_graphics(1) Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 SPI_T6963C_cursor_blink Prototype sub procedure SPI_T6963C_cursor_blink(dim n as word) Description Enable/disable cursor blinking. Parameters - n: cursor blinking enable/disable parameter. Valid values: 0 (disable cursor blinking) and 1 (enable cursor blinking). Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See SPI_T6963C_Config routine. Example ‘ enable cursor blinking SPI_T6963C_cursor_blink(1) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 TRISB11_bit = 1 TRISB12_bit = 1 ‘ Set RB11 as input ‘ Set RB12 as input panel = 0 i = 0 curs = 0 cposx = 0 cposy = 0 ‘ Initialize SPI module SPI1_Init() ‘ ‘ If Port Expander Library uses SPI2 module ‘ Pass pointer to SPI Read function of used SPI module ‘ Initialize SPI module used with PortExpander ‘ SPI2_Init_Advanced(_SPI_MASTER, _SPI_FCY_DIV2, _SPI_CLK_HI_TRAILING) ‘ ‘ ‘ ‘ ‘ ‘ ‘ ‘ ‘ * * * * * * * * * init display for 240 pixel width and 128 pixel height 8 bits
mikoBasic PRO for dsPIC30/33 and PIC24 ‘ * Draw a cross SPI_T6963C_line(0, 0, 239, 127, SPI_T6963C_WHITE) SPI_T6963C_line(0, 127, 239, 0, SPI_T6963C_WHITE) ‘ * Draw solid boxes SPI_T6963C_box(0, 0, 239, 8, SPI_T6963C_WHITE) SPI_T6963C_box(0, 119, 239, 127, SPI_T6963C_WHITE) ‘ * Draw circles #IFDEF COMPLETE_EXAMPLE SPI_T6963C_circle(120, 64, SPI_T6963C_circle(120, 64, SPI_T6963C_circle(120, 64, SPI_T6963C_circle(120, 64, SPI_T6963C_circle(120, 64, SPI_T6963C_circle(120, 64, SPI_T6963C_circle(120, 64, 1
mikroBasic PRO for dsPIC30/33 and PIC24 ‘ * If RB11 is pressed, display text and graphic panels else if (RB11_bit <> 0) then SPI_T6963C_graphics(1) SPI_T6963C_text(1) Delay_ms(300) ‘ * If RB12 is pressed, change cursor else if(RB12_bit <> 0) then Inc(curs) if (curs = 3) then curs = 0 end if select case curs case 0 ‘ no cursor SPI_T6963C_cursor(0) case 1 ‘ blinking cursor SPI_T6963C_cursor(1) SPI_T6963C_cursor_blink(1) case 2 ‘ non blinking cursor SPI_T6963C_cursor(1) SPI_T6963C_cursor_blink(0) end select
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection SPI T6963C Glcd HW connection MikroElektronika 566
mikroBasic PRO for dsPIC30/33 and PIC24 T6963C Graphic Lcd Library The mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for working with Glcds based on TOSHIBA T6963C controller. The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules. It is capable of controlling displays with a resolution up to 240x128. Because of its low power and small outline it is most suitable for mobile applications such as PDAs, MP3 players or mobile measurement equipment.
mikoBasic PRO for dsPIC30/33 and PIC24 External dependencies of T6963C Graphic Lcd Library The following variables must be defined in all projects using T6963C Graphic Lcd library: Description: Example: dim T6963C_dataPort as byte sfr external T6963C Data Port. dim T6963C_dataPort as byte at PORTB Write signal. dim T6963C_ctrlwr as sbit at LATF2_bit Read signal. dim T6963C_ctrlrd as sbit at LATF1_bit Command/Data signal. dim T6963C_ctrlcd as sbit at LATF0_bit Reset signal.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Routines - T6963C_init - T6963C_writeData - T6963C_writeCommand - T6963C_setPtr - T6963C_waitReady - T6963C_fill - T6963C_dot - T6963C_write_char - T6963C_write_text - T6963C_line - T6963C_rectangle - T6963C_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 - T696
mikoBasic PRO for dsPIC30/33 and PIC24 T6963C_init Prototype sub procedure T6963C_init(dim width, height, fntW as word, dim byref data as word, dim byref cntrl as word, dim wr, rd, cd, rst as word) Description Initalizes the Graphic Lcd controller. Display RAM organization: The library cuts the RAM into panels: a complete panel is one graphics panel followed by a text panel (see schematic below).
mikroBasic PRO for dsPIC30/33 and PIC24 Example ‘ T6963C module connections dim T6963C_dataPort as byte at PORTB ‘ DATA port dim T6963C_ctrlwr as sbit at LATF2_bit dim T6963C_ctrlrd as sbit at LATF1_bit dim T6963C_ctrlcd as sbit at LATF0_bit ‘ CD dim T6963C_ctrlrst as sbit at LATF4_bit dim T6963C_ctrlwr_Direction as sbit at TRISF2_bit direction dim T6963C_ctrlrd_Direction as sbit at TRISF1_bit direction dim T6963C_ctrlcd_Direction as sbit at TRISF0_bit signal direction dim T6963C_ctrlrst_Direction as sbi
mikoBasic PRO for dsPIC30/33 and PIC24 T6963C_writeCommand Prototype sub procedure T6963C_writeCommand(dim mydata as byte) Description Writes command to T6963C controller. Parameters - mydata: command to be written Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine. Example T6963C_writeCommand(T6963C_CURSOR_POINTER_SET) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 T6963C_fill Prototype sub procedure T6963C_fill(dim v as byte, dim start, len as word) Description Fills controller memory block with given byte. Parameters - v: byte to be written - start: starting address of the memory block - len: length of the memory block in bytes Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine. Example T6963C_fill(0x33,0x00FF,0x000F) Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 T6963C_write_char Prototype sub procedure T6963C_write_char(dim c, x, y, mode as byte) Description Writes a char in the current text panel of Glcd at coordinates (x, y). Parameters - c: char to be written - x: char position on x-axis - y: char position on y-axis - mode: mode parameter.
mikroBasic PRO for dsPIC30/33 and PIC24 T6963C_write_text Prototype sub procedure T6963C_write_char(dim byref str as byte[10], dim x, y, mode as byte) 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 - y: text position on y-axis - mode: mode parameter.
mikoBasic PRO for dsPIC30/33 and PIC24 T6963C_rectangle Prototype sub procedure T6963C_rectangle(dim x0, y0, x1, y1 as integer, dim pcolor as byte) 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: T6963C_BLACK and T6963C_WHITE Returns Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 T6963C_rectangle_round_edges_fill Prototype sub procedure T6963C_rectangle_round_edges_fill(dim x0, y0, x1, y1, radius as integer, dim pcolor as byte) Description Draws a filled rounded edge rectangle on Glcd.
mikoBasic PRO for dsPIC30/33 and PIC24 T6963C_circle_fill Prototype sub procedure T6963C_circle_fill(dim x, y as integer, dim r as longint, dim pcolor as byte) Description Draws a filled circle on Glcd. Parameters - x: x coordinate of the circle center - y: y coordinate of the circle center - r: radius size - pcolor: color parameter. Valid values: T6963C_BLACK and T6963C_WHITE Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
mikroBasic PRO for dsPIC30/33 and PIC24 T6963C_PartialImage Prototype sub procedure T6963C_PartialImage(dim x_left, y_top, width, height, picture_ width, picture_height as word, const image as ^byte) 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 dsPIC30/33 and PIC24 T6963C_set_cursor Prototype sub procedure T6963C_set_cursor(dim x, y as byte) Description Sets cursor to row x and column y. Parameters - x: cursor position row number - y: cursor position column number Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine. Example T6963C_set_cursor(cposx, cposy) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 T6963C_setGrPanel Prototype sub procedure T6963C_setGrPanel(dim n as word) Description Compute start address for selected graphic panel and set appropriate internal pointers. All subsequent graphic operations will be preformed at this graphic panel. Parameters - n: graphic panel number. Valid values: 0 and 1. Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine.
mikoBasic PRO for dsPIC30/33 and PIC24 T6963C_grFill Prototype sub procedure T6963C_grFill(dim v as word) Description Fill current graphic panel with appropriate value (0 to clear). Parameters - v: value to fill graphic panel with. Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine. Example ‘ clear current graphic panel T6963C_grFill(0) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 T6963C_graphics Prototype sub procedure T6963C_graphics(dim n as word) Description Enable/disable graphic displaying. Parameters - n: graphic enable/disable parameter. Valid values: 0 (disable graphic dispaying) and 1 (enable graphic displaying). Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine. Example ‘ enable graphic displaying T6963C_graphics(1) Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 T6963C_cursor_blink Prototype sub procedure T6963C_cursor_blink(dim n as word) Description Enable/disable cursor blinking. Parameters - n: cursor blinking enable/disable parameter. Valid values: 0 (disable cursor blinking) and 1 (enable cursor blinking). Returns Nothing. Requires Toshiba Glcd module needs to be initialized. See the T6963C_init routine. Example ‘ enable cursor blinking T6963C_cursor_blink(1) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 txt, txt1 as string[29] main: txt1 = “ EINSTEIN WOULD HAVE LIKED mE” txt = “ GLCD LIBRARY DEMO, WELCOME !” #DEFINE COMPLETE_EXAMPLE ADPCFG = 0xFFFF ‘ comment this line to make simpler/smaller example ‘ initialize AN pins as digital TRISB8_bit = 1 TRISB9_bit = 1 TRISB10_bit = 1 TRISB11_bit = 1 TRISB12_bit = 1 ‘ ‘ ‘ ‘ ‘ T6963C_ctrlce_Direction = 0 T6963C_ctrlce = 0 T6963C_ctrlfs_Direction = 0 T6963C_ctrlfs = 0 T6963C_ctrlmd_Direction = 0 T6963C_ctrlmd = 0 Set Set S
mikoBasic PRO for dsPIC30/33 and PIC24 ‘ * Draw a cross T6963C_line(0, 0, 239, 127, T6963C_WHITE) T6963C_line(0, 127, 239, 0, T6963C_WHITE) ‘ * Draw solid boxes T6963C_box(0, 0, 239, 8, T6963C_WHITE) T6963C_box(0, 119, 239, 127, T6963C_WHITE) ‘ * Draw circles #IFDEF COMPLETE_EXAMPLE T6963C_circle(120, 64, 10, T6963C_WHITE) T6963C_circle(120, 64, 30, T6963C_WHITE) T6963C_circle(120, 64, 50, T6963C_WHITE) T6963C_circle(120, 64, 70, T6963C_WHITE) T6963C_circle(120, 64, 90, T6963C_WHITE) T6963C_circle(120,
mikroBasic PRO for dsPIC30/33 and PIC24 if (RB11_bit <> 0) then T6963C_graphics(1) T6963C_text(1) Delay_ms(300) ‘ * If RB12 is pressed, change cursor else if(RB12_bit <> 0) then Inc(curs) if (curs = 3) then curs = 0 end if select case curs case 0 ‘ no cursor T6963C_cursor(0) case 1 ‘ blinking cursor T6963C_cursor(1) T6963C_cursor_blink(1) case 2 ‘ non blinking cursor T6963C_cursor(1) T6963C_cursor_blink(0) end select Delay_ms(300) end if end if end if #IFDEF COMPLETE_EXAMPLE end if #ENDIF end if ‘ * Move
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection T6963C Glcd HW connection MikroElektronika 588
mikroBasic PRO for dsPIC30/33 and PIC24 TFT Library Thin film transistor liquid crystal display (TFT-LCD) is a variant of liquid crystal display (LCD) which uses thin-film transistor (TFT) technology to improve image quality (e.g., addressability, contrast). TFT LCD is one type of active matrix LCD, though all LCD-screens are based on TFT active matrix addressing.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Routines - TFT_Init - TFT_Set_Index - TFT_Write_Command - TFT_Write_Data - TFT_Set_Active - TFT_Set_Font - TFT_Write_Char - TFT_Write_Text - TFT_Fill_Screen - TFT_Set_Pen - TFT_Set_Brush - TFT_Dot - TFT_Line - TFT_H_Line - TFT_V_Line - TFT_Rectangle - TFT_Rectangle_Round_Edges - TFT_Circle - TFT_Image - TFT_PartialImage - TFT_Image_Jpeg - TFT_RGBToColor16bit - TFT_Color16bitToRGB MikroElektronika 590
mikroBasic PRO for dsPIC30/33 and PIC24 TFT_Init Prototype sub procedure TFT_Init(dim display_width, display_height as word) Returns Nothing Description Initializes TFT display in the 8-bit working mode.
mikoBasic PRO for dsPIC30/33 and PIC24 TFT_Set_Index Prototype sub procedure TFT_Set_Index(dim index as byte) Returns Nothing Description Accesses register space of the controller and sets the desired register. Parameters: Requires Example - index: desired register number. TFT module needs to be initialized. See the TFT_Init routine.
mikroBasic PRO for dsPIC30/33 and PIC24 TFT_Set_Active Prototype sub procedure TFT_Set_Active(dim Set_Index_Ptr as ^TTFT_Set_Index_Ptr, dim Write_Command_Ptr as ^TTFT_Write_Command_Ptr, dim Write_Data_Ptr as ^TTFT_ Write_Data_Ptr) Returns Nothing Description This function sets appropriate pointers to a user-defined basic routines in order to enable multiple working modes. Parameters: - Set_Index_Ptr: Set_Index handler. - Write_Command_Ptr: _Write_Command handler. - Write_Data_Ptr: Write_Data handler.
mikoBasic PRO for dsPIC30/33 and PIC24 TFT_Set_Font Prototype Returns sub procedure TFT_Set_Font(dim activeFont as ^far const byte, dim font_color as word, dim font_orientation as byte) Nothing Description Sets font, its color and font orientation. Parameters: - activeFont: desired font. Currently, only TFT_defaultFont (Tahoma14x16) is supported.
mikroBasic PRO for dsPIC30/33 and PIC24 TFT_Write_Char Prototype sub procedure TFT_Write_Char(dim ch, x, y as word) Returns Nothing. Description Writes a char on the TFT at coordinates (x, y). Requires Example - c: char to be written. - x: char position on x-axis. - y: char position on y-axis. TFT module needs to be initialized. See the TFT_Init routine. TFT_Write_Char(“A”,22,23) TFT_Write_Text Prototype sub procedure TFT_Write_Text(dim byref text as string, dim x, y as word) Returns Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 TFT_Fill_Screen Prototype sub procedure TFT_Fill_Screen(dim color as word) Returns Nothing. Description Fills screen memory block with given color.
mikroBasic PRO for dsPIC30/33 and PIC24 TFT_Dot Prototype sub procedure TFT_Dot(dim x, y as integer, dim color as word) Returns Nothing. Description Draws a dot on the TFT at coordinates (x, y). Parameters: - x: dot position on x-axis. - y: dot position on y-axis. - color: color parameter.
mikoBasic PRO for dsPIC30/33 and PIC24 TFT_Set_Pen Prototype sub procedure TFT_Set_Pen(dim pen_color as word, dim pen_width as byte) Returns Nothing. Description Sets color and thickness parameter for drawing line, circle and rectangle elements. Parameters: - pen_color: Sets color.
mikroBasic PRO for dsPIC30/33 and PIC24 TFT_Set_Brush Prototype sub procedure TFT_Set_Brush(dim brush_enabled as byte, dim brush_color as word, dim gradient_enabled, gradient_orientation as byte, dim gradient_ color_from, gradient_color_to as word) Returns Nothing. Description Sets color and gradient which will be used to fill circles or rectangles. Parameters: - brush_enabled: enable brush fill. Value Description 1 Enable brush fill. 0 Disable brush fill. - brush_color: set brush fill color.
mikoBasic PRO for dsPIC30/33 and PIC24 Description - gradient_enabled: enable gradient Value Description 1 Enable gradient. 0 Disable gradient. - gradient_orientation: sets gradient orientation: Value Description LEFT_TO_RIGHT Left to right gradient orientation TOP_TO_BOTTOM Top to bottom gradient orientation - gradient_color_from: sets the starting gradient color.
mikroBasic PRO for dsPIC30/33 and PIC24 Description - gradient_color_to: sets the ending gradient color.
mikoBasic PRO for dsPIC30/33 and PIC24 TFT_H_Line Prototype sub procedure TFT_H_Line(dim x_start, x_end, y_pos as integer) Returns Nothing. Description Draws a horizontal line on TFT. Parameters: - x_start: x coordinate of the line start. - x_end: x coordinate of the line end. - y_pos: y coordinate of horizontal line. Requires TFT module needs to be initialized. See the TFT_Init routine.
mikroBasic PRO for dsPIC30/33 and PIC24 TFT_Rectangle_Round_Edges Prototype sub procedure TFT_Rectangle_Round_Edges(dim x_upper_left, y_upper_left, x_ bottom_right, y_bottom_right, round_radius as word) Returns Nothing. Description Draws a rounded edge rectangle on TFT. Parameters: - x_upper_left: x coordinate of the upper left rectangle corner. - y_upper_left: y coordinate of the upper left rectangle corner. - x_bottom_right: x coordinate of the lower right rectangle corner.
mikoBasic PRO for dsPIC30/33 and PIC24 TFT_Partial_Image Prototype Returns sub procedure TFT_Partial_Image(dim left, top, width, height as word, dim image as far const byte, dim stretch as byte) Nothing. Description Displays a partial area of the image on a desired location. Parameters: - left: left coordinate of the image. - top: top coordinate of the image. - width: desired image width. - height: desired image height. - image: image to be displayed. Bitmap array is located in code memory.
mikroBasic PRO for dsPIC30/33 and PIC24 TFT_RGBToColor16bit Prototype Returns sub function TFT_RGBToColor16bit(dim rgb_red, rgb_green, rgb_blue as byte) as word Returns a color value in the following bit-order : 5 bits red, 6 bits green and 5 bits blue color. Description Converts 5:6:5 RGB format into true color format. Parameters: - rgb_red: red component of the image. - rgb_green: green component of the image. - rgb_blue: blue component of the image. Requires TFT module needs to be initialized.
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection TFT HW connection MikroElektronika 606
mikroBasic PRO for dsPIC30/33 and PIC24 Touch Panel Library The mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for working with Touch Panel. Library Dependency Tree External dependencies of Touch Panel Library The following variables must be defined in all projects using Touch Panel Library: Description: Example: dim DriveA as sbit sfr external DriveA line.
mikoBasic PRO for dsPIC30/33 and PIC24 TP_Init Prototype sub procedure TP_Init(dim display_width as word, dim display_height as word, dim readX_ChNo as byte, dim readY_ChNo as byte) Description Initialize touch panel display. Default touch panel ADC threshold value is set to 3900. Parameters - display_width: set display width. - display_height: set display height. - readX_ChNo: read X coordinate from desired ADC channel. - readY_ChNo: read Y coordinate from desired ADC channel. Returns Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 TP_Press_Detect Prototype sub function TP_Press_Detect() as byte Description Detects if the touch panel has been pressed. Parameters None. Returns Requires - 1 - if touch panel is pressed. - 0 - otherwise. Global variables: - DriveA: DriveA. - DriveB: DriveB. - DriveA_Direction: Direction of DriveA pin. - DriveB_Direction: Direction of DriveB pin. must be defined before using this function.
mikoBasic PRO for dsPIC30/33 and PIC24 TP_Calibrate_Bottom_Left Prototype sub procedure TP_Calibrate_Bottom_Left() Description Calibrate bottom left corner of the touch Panel. Parameters None. Returns Nothing. Requires Nothing. Example TP_Calibrate_Bottom_Left() Notes None. ‘ Calibration of bottom left corner TP_Calibrate_Upper_Right Prototype sub procedure TP_Calibrate_Upper_Right() Description Calibrate upper right corner of the touch panel. Parameters None. Returns Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 TP_Set_Calibration_Consts Prototype sub procedure TP_Set_Calibration_Consts(dim x_min as word, dim x_max as word, dim y_min as word, dim y_max as word) Description Sets calibration constants. Parameters - x_min: x coordinate of the bottom left corner of the working area. - x_max: x coordinate of the upper right corner of the working area. - y_min: y coordinate of the bottom left corner of the working area.
mikoBasic PRO for dsPIC30/33 and PIC24 dim GLCD_CS1_Direction as sbit GLCD_CS2_Direction as sbit GLCD_RS_Direction as sbit GLCD_RW_Direction as sbit GLCD_EN_Direction as sbit GLCD_RST_Direction as sbit ‘ eEnd Glcd module connections at at at at at at TRISB4_bit TRISB5_bit TRISF0_bit TRISF1_bit TRISF4_bit TRISF5_bit ‘ Touch Panel module connections dim DriveA as sbit at LATC13_bit DriveB as sbit at LATC14_bit DriveA_Direction as sbit at TRISC13_bit DriveB_Direction as sbit at TRISC14_bit ‘ end Touch Panel
mikroBasic PRO for dsPIC30/33 and PIC24 Initialize() Glcd_Fill(0) Glcd_Write_Text(“CALIBRATION”,12,3,1) Delay_ms(1000) Glcd_Fill(0) Calibrate() Glcd_Fill(0) ‘ Clear GLCD ‘ Clear GLCD Glcd_Write_Text(“WRITE ON SCREEN”, 20, 5, 1) Delay_ms(1000) Glcd_Fill(0) Glcd_V_Line(0,7,0,1) Glcd_Write_Text(clear_msg,1,0,0) Glcd_V_Line(0,7,97,1) Glcd_Write_Text(erase_msg,98,0,0) ‘ Pen Menu: Glcd_Rectangle(41,0,52,9,1) Glcd_Box(45,3,48,6,1) Glcd_Rectangle(63,0,70,7,1) Glcd_Box(66,3,67,4,1) Glcd_Rectangle(80,0,86,6,1) Glcd
mikoBasic PRO for dsPIC30/33 and PIC24 Glcd_Write_Text(write_msg,98,0,0) end if end if ‘ If write/erase is pressed if ((x_coord > 96) and (y_coord < 8)) then if (write_erase) then write_erase = 0 Glcd_Write_Text(write_msg,98,0,0) Delay_ms(500) else write_erase = 1 Glcd_Write_Text(erase_msg,98,0,0) Delay_ms(500) end if ‘ If pen size is selected if ((x_coord >= 41) and (x_coord <= 52) and (y_coord <= 9)) then pen_size = 3 end if if ((x_coord >= 63) and (x_coord <= 70) and (y_coord <= 7)) then pen_size = 2 end
mikroBasic PRO for dsPIC30/33 and PIC24 Touch Panel TFT Library The mikroBasic PRO for dsPIC30/33 and PIC24 provides a library for working with Touch Panel for TFT. Library Dependency Tree External dependencies of Touch Panel TFT Library The following variables must be defined in all projects using Touch Panel TFT Library: Description: Example: dim DriveX_Left as sbit sfr external DriveX_Left line. dim DriveX_Right as sbit sfr external dim DriveX_Left LATB13_bit DriveX_Right line.
mikoBasic PRO for dsPIC30/33 and PIC24 TP_TFT_Init Prototype sub procedure TP_TFT_Inits(dim display_width as word, dim display_height as word, dim readX_ChNo as byte, dim readY_ChNo as byte) Description Initialize TFT touch panel display. Default touch panel ADC threshold value is set to 900. Parameters - display_width: set display width. - display_height: set display height. - readX_ChNo: read X coordinate from desired ADC channel. - readY_ChNo: read Y coordinate from desired ADC channel.
mikroBasic PRO for dsPIC30/33 and PIC24 TP_TFT_Press_Detect Prototype sub function TP_TFT_Press_Detect() as byte Description Detects if the touch panel has been pressed. Parameters None. Returns Requires - 1 - if touch panel is pressed. - 0 - otherwise. Global variables: - DriveX_Left: DriveX_Left pin. - DriveX_Right: DriveX_Right pin. - DriveY_Up: DriveY_Up pin. - DriveY_Down: DriveY_Down pin. - DriveX_Left_Direction: Direction of DriveX_Left pin.
mikoBasic PRO for dsPIC30/33 and PIC24 TP_TFT_Get_Coordinates Prototype sub function TP_TFT_Get_Coordinates(dim byref x_coordinate as word, dim byref y_coordinate as word) as byte Description Get touch panel coordinates and store them in x_coordinate and y_coordinate parameters. Parameters - x_coordinate: x coordinate of the place of touch. - y_coordinate: y coordinate of the place of touch. Returns Requires Example Notes - 1 - if reading is within display dimension range.
mikroBasic PRO for dsPIC30/33 and PIC24 TP_TFT_Get_Calibration_Consts Prototype sub procedure TP_TFT_Get_Calibration_Consts(dim byref x_min as word, dim byref x_max as word, dim byref y_min as word, dim byref y_max as word) Description Gets calibration constants after calibration is done and stores them in x_min, x_max, y_min and y_max parameters. Parameters - x_min: x coordinate of the bottom left corner of the working area. - x_max: x coordinate of the upper right corner of the working area.
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection Touch Panel TFT HW connection MikroElektronika 620
mikroBasic PRO for dsPIC30/33 and PIC24 UART Library The UART hardware module is available with a number of dsPIC30/33 and PIC24 MCUs. The mikroBasic PRO for dsPIC30/33 and PIC24 UART Library provides comfortable work with the Asynchronous (full duplex) mode. Important: - UART library routines require you to specify the module you want to use. To select the desired UART module, simply change the letter x in the routine prototype for a number from 1 to 4.
mikoBasic PRO for dsPIC30/33 and PIC24 UARTx_Init Prototype sub procedure UARTx_Init(dim baud_rate as longint) Description Configures and initializes the UART module.
mikroBasic PRO for dsPIC30/33 and PIC24 UARTx_Init_Advanced Prototype ‘ dsPIC30 prototype sub procedure UARTx_Init_Advanced(dim baud_rate as longint, dim parity, stop_bits as word) ‘ dsPIC33 and PIC24 prototype sub procedure UARTx_Init_Advanced(dim baud_rate as longint, dim parity, stop_bits as word, dim high_low_speed as word) Description Configures and initializes the UART module with user defined settings. Parameters - baud_rate: requested baud rate - parity: parity and data selection parameter.
mikoBasic PRO for dsPIC30/33 and PIC24 Returns Nothing. Requires Routine requires the UART module.
mikroBasic PRO for dsPIC30/33 and PIC24 UARTx_Tx_Idle Prototype sub function UARTx_Tx_Idle() as word Description Use the function to test if the transmit shift register is empty or not. Parameters None. Returns - 1 if the data has been transmitted - 0 otherwise Requires Routine requires at least one UART module. Used UART module must be initialized before using this routine. See UARTx_Init and UARTx_Init_ Advanced routines.
mikoBasic PRO for dsPIC30/33 and PIC24 UARTx_Read_Text Prototype sub procedure UARTx_Read_Text(dim byref output, delimiter as string; dim Attempts as byte) Description Reads characters received via UART until the delimiter sequence is detected. The read sequence is stored in the parameter output; delimiter sequence is stored in the parameter delimiter. This is a blocking call: the delimiter sequence is expected, otherwise the procedure exits (if the delimiter is not found).
mikroBasic PRO for dsPIC30/33 and PIC24 UARTx_Write Prototype sub procedure UARTx_Write(dim data_ as word) Description The function transmits a byte via the UART module. Parameters - data_: data to be sent Returns Nothing. Requires Routine requires at least one UART module. Used UART module must be initialized before using this routine. See UARTx_Init and UARTx_Init_ Advanced routines. Example dim data_ as byte ...
mikoBasic PRO for dsPIC30/33 and PIC24 UART_Set_Active Prototype sub procedure UART_Set_Active (dim read_ptr as ^TUART_Rd_Ptr, dim write_ ptr as ^TUART_Wr_Ptr, dim ready_ptr as ^TUART_Rdy_Ptr, dim tx_idle_ptr as ^TUART_TX_Idle_Ptr) Description Sets active UART module which will be used by UARTx_Data_Ready, UARTx_Read and UARTx_ Write routines.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example This example demonstrates simple data exchange via UART. If MCU is connected to the PC, you can test the example from the mikroBasic PRO for dsPIC30/33 and PIC24 USART communication terminal, launch it from the drop-down menu Tools › USART Terminal or simply click the USART Terminal Icon .
mikoBasic PRO for dsPIC30/33 and PIC24 HW Connection RS232 HW connection MikroElektronika 630
mikroBasic PRO for dsPIC30/33 and PIC24 USB Library Universal Serial Bus (USB) provides a serial bus standard for connecting a wide variety of devices, including computers, cell phones, game consoles, PDA’s, etc. USB Library contains HID routines that support HID class devices, and also the generic routines that can be used with vendor specified drivers. USB HID Class The HID class consists primarily of devices that are used by humans to control the operation of computer systems.
mikoBasic PRO for dsPIC30/33 and PIC24 HID_Enable Prototype sub procedure HID_Enable(dim readbuff as ^byte, dim writebuff as ^byte) Description Enables USB HID communication. Parameters - readbuff: Read Buffer. - writebuff: Write Buffer. These parameters are used for HID communication. Returns Nothing. Requires Nothing. Example HID_Enable(@readbuff,@writebuff) Notes This function needs to be called before using other routines of USB HID Library.
mikroBasic PRO for dsPIC30/33 and PIC24 HID_Disable Prototype sub procedure HID_Disable() Description Disables USB HID communication. Parameters None. Returns Nothing. Requires USB HID needs to be enabled before using this function. See HID_Enable. Example HID_Disable() Notes None. USB_Interrupt_Proc Prototype sub procedure USB_Interrupt_Proc() Description This routine is used for servicing various USB bus events. Should be called inside USB interrupt routine. Parameters None.
mikoBasic PRO for dsPIC30/33 and PIC24 Gen_Enable Prototype sub procedure Gen_Enable(dim readbuff as ^byte, dim writebuff as ^byte) Description Initialize the USB module of the MCU. Parameters Returns - readbuff: Read Buffer. - writebuff: Write Buffer. Nothing. Requires USB needs to be enabled before using this function. See HID_Enable. Example Gen_Enable(@readbuff,@writebuff) Notes None.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example This example establishes connection with the HID terminal that is active on the PC. Upon connection establishment, the HID Device Name will appear in the respective window. After that software will wait for data and it will return received data back. Examples uses USBdsc.mbas descriptor file, which is in the same folder, and can be created by the HID Terminal.
mikoBasic PRO for dsPIC30/33 and PIC24 Digital Signal Processing Libraries mikroBasic PRO for dsPIC30/33 and PIC24 includes various libraries for DSP engine. All DSP routines work with fractional Q15 format.
mikroBasic PRO for dsPIC30/33 and PIC24 FIR Filter Library mikroBasic PRO for dsPIC30/33 and PIC24 includes a library for finite impulse response (FIR) filter. All routines work with fractional Q15 format. A finite impulse response (FIR) filter is a type of a digital filter, whose impulse response (the filter’s response to a delta function) is finite because it settles to zero in a finite number of sample intervals.
mikoBasic PRO for dsPIC30/33 and PIC24 IIR Filter Library mikroBasic PRO for dsPIC30/33 and PIC24 includes a library for Infinite Impulse Response (IIR) filter. All routines work with fractional Q15 format. A infinite impulse response (IIR) filter is a type of a digital filter, whose impulse response (the filter’s response to a delta function) is non-zero over an infinite length of time.
mikroBasic PRO for dsPIC30/33 and PIC24 FFT Library mikroBasic PRO for dsPIC30/33 and PIC24 includes a library for FFT calculation. All routines work with fractional Q15 format. Library Dependency Tree Library Routines - FFT FFT Prototype sub procedure FFT(dim log2N as word, dim TwiddleFactorsAddress as longint, dim byref Samples as word[1024]) Description Function applies FFT transformation to input samples, input samples must be in Y data space.
mikoBasic PRO for dsPIC30/33 and PIC24 Twiddle Factors: TwiddleCoeff_64 const TwiddleCoeff_64 as word[64] 0x7FFF, 0x0000, 0x7F62, 0xF374, 0x7642, 0xCF04, 0x70E3, 0xC3A9, 0x5A82, 0xA57E, 0x5134, 0x9D0E, 0x30FC, 0x89BE, 0x2528, 0x8583, 0x0000, 0x8000, 0xF374, 0x809E, 0xCF04, 0x89BE, 0xC3A9, 0x8F1D, 0xA57E, 0xA57E, 0x9D0E, 0xAECC, 0x89BE, 0xCF04, 0x8583, 0xDAD8, = ( 0x7D8A, 0x6A6E, 0x471D, 0x18F9, 0xE707, 0xB8E3, 0x9592, 0x8276, 0xE707, 0xB8E3, 0x9592, 0x8276, 0x8276, 0x9592, 0xB8E3, 0xE707, 0x7A7D, 0x62F2,
mikroBasic PRO for dsPIC30/33 and PIC24 0x18F9, 0x0C8C, 0x0000, 0xF374, 0xE707, 0xDAD8, 0xCF04, 0xC3A9, 0xB8E3, 0xAECC, 0xA57E, 0x9D0E, 0x9592, 0x8F1D, 0x89BE, 0x8583, 0x8276, 0x809E, 0x8276, 0x809E, 0x8000, 0x809E, 0x8276, 0x8583, 0x89BE, 0x8F1D, 0x9592, 0x9D0E, 0xA57E, 0xAECC, 0xB8E3, 0xC3A9, 0xCF04, 0xDAD8, 0xE707, 0xF374, 0x15E2, 0x096B, 0xFCDC, 0xF055, 0xE3F4, 0xD7D9, 0xCC21, 0xC0E9, 0xB64C, 0xAC65, 0xA34C, 0x9B17, 0x93DC, 0x8DAB, 0x8894, 0x84A3, 0x81E2, 0x8059, 0x81E2, 0x8059, 0x800A, 0x80F6, 0x831
mikoBasic PRO for dsPIC30/33 and PIC24 0x12C8, 0x0C8C, 0x0648, 0x0000, 0xF9B8, 0xF374, 0xED38, 0xE707, 0xE0E6, 0xDAD8, 0xD4E1, 0xCF04, 0xC946, 0xC3A9, 0xBE32, 0xB8E3, 0xB3C0, 0xAECC, 0xAA0A, 0xA57E, 0xA129, 0x9D0E, 0x9930, 0x9592, 0x9236, 0x8F1D, 0x8C4A, 0x89BE, 0x877B, 0x8583, 0x83D6, 0x8276, 0x8163, 0x809E, 0x8027, 0x8163, 0x809E, 0x8027, 0x8000, 0x8027, 0x809E, 0x8163, 0x8276, 0x83D6, 0x8583, 0x877B, 0x89BE, 0x8C4A, 0x8F1D, 0x9236, 0x9592, 0x9930, 0x9D0E, 0xA129, 0xA57E, 0xAA0A, 0xAECC, 0xB3C0, 0xB8E3,
mikroBasic PRO for dsPIC30/33 and PIC24 Bit Reverse Complex Library mikroBasic PRO for dsPIC30/33 and PIC24 includes a Bit Reverse Complex Library for DSP engine. All routines work with fractional Q15 format. Library Routines - BitReverseComplex BitReverseComplex Prototype sub procedure word[1024]) BitReverseComplex(dim log2N as word, dim byref ReIm as Description This function does Complex (in-place) Bit Reverse re-organization. Parameters - N: buffer length (must be the power of 2).
mikoBasic PRO for dsPIC30/33 and PIC24 Vectors Library mikroBasic PRO for dsPIC30/33 and PIC24 includes a library for working and using vectors. All routines work with fractional Q15 format.
mikroBasic PRO for dsPIC30/33 and PIC24 Vector_Power Prototype sub function Vector_Power(dim N as word, dim byref srcV as word[1024]) as word Description Function returns result of power value (powVal) in radix point 1.15 Parameters - N: number elements in vector(s) - srcV: pointer to source vector Returns Requires Example Nothing. dim vec1 as word[3] Vector_Power(3, vec1) Notes - [W0..
mikoBasic PRO for dsPIC30/33 and PIC24 Vector_Scale Prototype sub procedure Vector_Scale(dim N as word, dim ScaleValue as integer, dim byref SrcVector, DestVector as word[1024]) Description This function does vector scaling with scale value. dstV[n] = sclVal * srcV[n], n є [0, numElems-1] Parameters - N: buffer length SrcVector: original vector DestVector: scaled vector ScaleValue: scale value Returns Nothing. Requires Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 Vector_Multiply Prototype sub procedure Vector_Multiply(dim byref v1, v2, dest as word[1024], dim numElems as word) Description This function does multiplication of two vectors. dstV[n] = srcV1[n] * srcV2[n], n є [0, numElems-1] Parameters - numElems: number elements in vector(s) (must be less or equal to minimum size of two vectors) v1: first vector v2: second vector dest: result vector Returns Nothing. Requires Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 Vector_Max Prototype sub function Vector_Max(dim byref Vector as word[1024], dim numElems as word, dim byref MaxIndex as word) as word Description This function find maximal value in vector. maxVal = max (srcV[n]), n є [0, numElems-1] If srcV[i] = srcV[j] = maxVal, and i < j, then maxIndex = j. Parameters - Vector: original vector - numElems: number of elements in vector(s) - MaxIndex: index of maximum value Returns Minimum value (maxVal). Requires Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 Vector_Correlate Prototype sub procedure Vector_Correlate(dim byref v1, v2, dest as word[1024], dim numElemsV1, dim numElemsV2 as word) Description Function calculates Vector correlation (using convolution).
mikoBasic PRO for dsPIC30/33 and PIC24 Vector_Convolve Prototype sub procedure Vector_Convolve(dim byref v1, v2, dest as word[1024], dim numElemsV1, numElemsV2 as word) Description Function calculates Vector using convolution. , n є [0, M) , n є [M, N) , n є [N, N+M-1) Parameters - v1: first vector v2: second vector numElemsV1: number of the first vector elements numElemsV2: number of the second vector elements dest: result vector Returns Nothing. Requires Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 Matrices Library mikroBasic PRO for dsPIC30/33 and PIC24 includes a library for operating and working with matrices. All routines work with fractional Q15 format. Library Routines Matrix_Transpose Matrix_Subtract Matrix_Scale Matrix_Multiply Matrix_Add Matrix_Transpose Prototype sub procedure Matrix_Transpose(dim byref src, dest as word[1024], dim numRows, numCols as word) Description Function does matrix transposition.
mikoBasic PRO for dsPIC30/33 and PIC24 Matrix_Subtract Prototype sub procedure Matrix_Subtract(dim byref src1, src2, dest as word[1024], dim numRows, numCols as word) Description Function does matrix subtraction. dstM[i][j] = srcM1[i][j] - srcM2[i][j] Parameters - src1: first matrix src2: second matrix dest: result matrix numRows: number of rows in the source matrix numCols: number of cols in the source matrix Returns Nothing. Requires Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 Matrix_Multiply Prototype sub procedure Matrix_Multiply(dim byref src1, src2, dest as word[256], dim numRows1, numCols2, numCols1Rows2 as word) Description Function does matrix multiplication.
mikoBasic PRO for dsPIC30/33 and PIC24 Matrix_Add Prototype sub procedure Matrix_Add(dim byref src1, src2, dest as word[1024], dim numRows, numCols as word) Description Function does matrix addition. dstM[i][j] = srcM1[i][j] + srcM2[i][j] Parameters - src1: first matrix src2: second matrix dest: result matrix numRows1: number of rows in the first matrix numCols2: number of columns in the second matrix Returns Nothing. Requires Nothing. Example dim mx1 as word[6] mx2 as word[6] mx3 as word[6] ...
mikroBasic PRO for dsPIC30/33 and PIC24 Miscellaneous Libraries - Button Library - Conversions Library - C Type Library - Setjmp Library - String Library - Time Library - Trigon Library - Trigonometry Library Button Library The Button Library provides routines for detecting button presses and debouncing (eliminating the influence of contact flickering upon pressing a button) Library Routines - Button 655 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 Button Prototype sub function Button(dim byref port as word, dim pin as byte, dim time as word, dim ActiveState as byte) as word Description The function eliminates the influence of contact flickering upon pressing a button (debouncing). The Button pin is tested just after the function call and then again after the debouncing period has expired. If the pin was in the active state in both cases then the function returns 255 (true).
mikroBasic PRO for dsPIC30/33 and PIC24 C Type Library The mikroBasic PRO for dsPIC30/33 and PIC24 provides a set of library functions for testing and mapping characters. Library Functions - isalnum - isalpha - iscntrl - isdigit - isgraph - islower - ispunct - isspace - isupper - isxdigit - toupper - tolower isalnum Prototype sub function isalnum(dim character as byte) as byte Description Function returns 0xFF if the character is alphanumeric (A-Z, a-z, 0-9), otherwise returns zero.
mikoBasic PRO for dsPIC30/33 and PIC24 isdigit Prototype sub function isdigit(dim character as byte) as word Description Function returns 0xFF if the character is a digit (0-9), otherwise returns zero. Example res = isdigit(“o”) res = isdigit(“1”) ‘ returns 0xFF ‘ returns 0 isgraph Prototype sub function isgraph(dim character as byte) as word Description Function returns 0xFF if the character is a printable, excluding the space (decimal 32), otherwise returns zero.
mikroBasic PRO for dsPIC30/33 and PIC24 isupper Prototype sub function isupper(dim character as byte) as word Description Function returns 0xFF if the character is an uppercase letter (A-Z), otherwise returns zero. Example res = isupper(“A”) res = isupper(“a”) ‘ returns 0xFF ‘ returns 0 isxdigit Prototype sub function isxdigit(dim character as byte) as word/p> Description Function returns 0xFF if the character is a hex digit (0-9, A-F, a-f), otherwise returns zero.
mikoBasic PRO for dsPIC30/33 and PIC24 Conversions Library mikroBasic PRO for dsPIC30/33 and PIC24 Conversions Library provides routines for numerals to strings and BCD/ decimal conversions.
mikroBasic PRO for dsPIC30/33 and PIC24 ByteToStr Prototype sub procedure ByteToStr(dim input as byte, dim byref output as string[3]) Description Converts input byte to a string. The output string is right justified and remaining positions on the left (if any) are filled with blanks. Parameters - input: byte to be converted - output: destination string Returns Nothing. Requires Nothing. Example Notes dim t as byte txt as string[3] ... t = 24 ByteToStr(t, txt) ‘ txt is “ 24” (one blank here) None.
mikoBasic PRO for dsPIC30/33 and PIC24 WordToStr Prototype sub procedure WordToStr(dim input as word, dim byref output as string[5]) Description Converts input word to a string. The output string is right justified and the remaining positions on the left (if any) are filled with blanks. Parameters - input: word to be converted - output: destination string Returns Nothing. Requires Nothing. Example Notes dim t as word txt as string[5] ...
mikroBasic PRO for dsPIC30/33 and PIC24 IntToStr Prototype sub procedure string[6]) IntToStr(dim input integer, as dim byref output as Description Converts input integer number to a string. The output string is right justified and the remaining positions on the left (if any) are filled with blanks. Parameters - input: integer number to be converted - output: destination string Returns Nothing. Requires Nothing. Example Notes dim input as integer txt as string[6] ...
mikoBasic PRO for dsPIC30/33 and PIC24 LongWordToStr Prototype sub procedure LongWordToStr(dim input as longword, dim byref output as string[10]) Description Converts input double word number to a string. The output string is right justified and the remaining positions on the left (if any) are filled with blanks. Parameters - input: double word number to be converted - output: destination string Returns Nothing. Requires Nothing. Example Notes dim input as longint txt as string[10] ...
mikroBasic PRO for dsPIC30/33 and PIC24 WordToStrWithZeros Prototype sub procedure WordToStrWithZeros(dim input as word, dim byref output as string[5]) Description Converts input word to a string. The output string is right justified and the remaining positions on the left (if any) are filled with zeros. Parameters - input: word to be converted - output: destination string Returns Nothing. Requires Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 LongWordToStrWithZeros Prototype sub procedure LongWordToStrWithZeros(dim input as longword, dim byref output as string[10]) Description Converts input dword to a string. The output string is right justified and the remaining positions on the left (if any) are filled with zeros. Parameters - input: word to be converted - output: destination string Returns Nothing. Requires Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 ByteToHex Prototype dim procedure ByteToHex(dim input as byte, dim byref output as string[2]) Description Converts input number to a string containing the number’s hexadecimal representation. The output string is right justified and remaining positions on the left (if any) are filled with zeros. Parameters - input: byte to be converted - output: destination string Returns Nothing. Requires Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 WordToHex Prototype sub procedure WordToHex(dim input as word, dim byref output as string[4]) Description Converts input number to a string containing the number’s hexadecimal representation. The output string is right justified and remaining positions on the left (if any) are filled with zeros. Parameters - input: word to be converted - output: destination string Returns Nothing. Requires Nothing.
mikroBasic PRO for dsPIC30/33 and PIC24 LongWordToHex Prototype sub procedure LongWordToHex(dim input as longword, dim byref output as string[8]) Description Converts input number to a string containing the number’s hexadecimal representation. The output string is right justified and remaining positions on the left (if any) are filled with zeros. Parameters - input: double word number to be converted - output: destination string Returns Example Notes Nothing.
mikoBasic PRO for dsPIC30/33 and PIC24 StrToInt Prototype sub function StrToInt(dim byref input as string[6]) as integer Description Converts a string to an integer. Parameters - input: string to be converted Returns Integer variable. Requires Input string is assumed to be the correct representation of a number. The conversion will end with the first character which is not a decimal digit. Example Notes dim ii as integer main: ... ii = StrToInt(“-1234”) end. None.
mikroBasic PRO for dsPIC30/33 and PIC24 Dec2Bcd Prototype sub function Dec2Bcd(dim decnum as byte) as byte Description Converts input number to its appropriate BCD representation. Parameters - decnum: number to be converted Returns Converted BCD value. Requires Nothing. Example Notes dim a, b as byte ... a = 22 b = Dec2Bcd(a) ‘ b equals 34 None. Bcd2Dec16 Prototype sub function Bcd2Dec16(dim bcdnum as word) as word Description Converts 16-bit BCD numeral to its decimal equivalent.
mikoBasic PRO for dsPIC30/33 and PIC24 Setjmp Library The Setjmp library contains functions and types definitions for bypassing the normal function call and return discipline.
mikroBasic PRO for dsPIC30/33 and PIC24 Library Example Example demonstrates function cross calling using setjmp and longjmp functions. When called, Setjmp() saves its calling environment in its buf argument for later use by the Longjmp(). Longjmp(), on the other hand, restores the environment saved by the most recent invocation of the Setjmp() with the corresponding buf argument.
mikoBasic PRO for dsPIC30/33 and PIC24 String Library mikroBasic PRO for dsPIC30/33 and PIC24 includes a library which automatizes string related tasks.
mikroBasic PRO for dsPIC30/33 and PIC24 memcmp Prototype sub function memcmp(dim p1, p2 as ^byte, dim n as word) as integer Description The function returns a positive, negative, or zero value indicating the relationship of first n words of memory areas starting at addresses p1 and p2.
mikoBasic PRO for dsPIC30/33 and PIC24 memmove Prototype sub procedure memmove(dim p1, p2, as ^byte, dim nn as word) Description The function copies nn words from the memory area starting at the address p2 to the memory area starting at p1. If these memory buffers overlap, the Memmove function ensures that the words in p2 are copied to p1 before being overwritten.
mikroBasic PRO for dsPIC30/33 and PIC24 strcat2 Prototype sub procedure strcat2(dim byref l, s1, s2 as string) Description The procedure adjoins string s2 at the end of the string s1, or at the first null character of the s1, and places the result string into l string.
mikoBasic PRO for dsPIC30/33 and PIC24 strcpy Prototype sub procedure strcpy(dim byref s1, s2 as string) Description The function copies the value of the string s2 to the string s1 and appends a null character to the end of s1. Example txt = “mikroElektronika” txt_sub = “mikr” strcpy(txt,txt_sub) ‘ copies string ‘txt_sub’ to ‘txt’ strlen Prototype sub function strlen(dim byref s as string) as word Description The function returns the length, in words, of the string s.
mikroBasic PRO for dsPIC30/33 and PIC24 strspn Prototype sub function strspn(dim byref s1, s2 as string) as word Description The function searches the string s1 for characters not found in the s2 string. Example The function returns the index of first character located in s1 that does not match a character in s2. If the first character in s1 does not match a character in s2, a value of 0 is returned.
mikoBasic PRO for dsPIC30/33 and PIC24 strcspn Prototype sub function strcspn(dim byref s1, s2 as string) as word Description The function searches the string s1 for any of the characters in the string s2. Example The function returns the index of the first character located in s1 that matches any character in s2. If the first character in s1 matches a character in s2, a value of 0 is returned.
mikroBasic PRO for dsPIC30/33 and PIC24 rtrim Prototype sub procedure rtrim(dim byref astring as string) Description The procedure trims the trailing spaces of the string. Example txt = “mikroE “ rtrim(txt) ‘ trims the trailing 2 spaces of the ‘txt’ string and adds terminating null character to the result strappendpre Prototype sub procedure strappendpre(dim letter as char, dim byref s1 as string) Description The procedure appends character at the beginning of the string.
mikoBasic PRO for dsPIC30/33 and PIC24 Time Library The Time Library contains functions and type definitions for time calculations in the UNIX time format which counts the number of seconds since the “epoch”. This is very convenient for programs that work with time intervals: the difference between two UNIX time values is a real-time difference measured in seconds. What is the epoch? Originally it was defined as the beginning of 1970 GMT.
mikroBasic PRO for dsPIC30/33 and PIC24 Time_epochToDate Prototype sub procedure TimeStruct) Time_epochToDate(dim e as longint, dim byref ts as Description Converts the UNIX time to time and date. Parameters - e: UNIX time (seconds since UNIX epoch) - ts: time and date structure for storing conversion output Returns Nothing. Requires Nothing. Example dim ts2 as TimeStruct epoch as longint ... ‘ what date is epoch 1234567890 ? epoch = 1234567890 Time_epochToDate(epoch,ts2) Notes None.
mikoBasic PRO for dsPIC30/33 and PIC24 Library Example Demonstration of Time library routines usage for time calculations in UNIX time format. Copy Code To Clipboard program Time_Demo ‘* ‘* simple time structure ‘* structure TimeStruct dim ss as byte ‘ seconds dim mn as byte ‘ minutes dim hh as byte ‘ hours dim md as byte ‘ day in month, from 1 to 31 dim wd as byte ‘ day in week, monday=0, tuesday=1, ....
mikroBasic PRO for dsPIC30/33 and PIC24 ‘* diff = Time_dateDiff(@ts1, @ts2) ‘ diff = 86163870 end. TimeStruct type definition structure TimeStruct dim ss as byte dim mn as byte dim hh as byte dim md as byte dim wd as byte dim mo as byte C time !) dim yy as word end structure 685 ‘ ‘ ‘ ‘ ‘ ‘ seconds minutes hours day in month, from 1 to 31 day in week, monday=0, tuesday=1, ....
mikoBasic PRO for dsPIC30/33 and PIC24 Trigon Library The mikroBasic PRO for dsPIC30/33 and PIC24 provides a set of library functions for floating point math handling. See also Predefined Globals and Constants for the list of predefined math constants.
mikroBasic PRO for dsPIC30/33 and PIC24 atan Prototype sub function atan(dim arg as float) as float Description Function computes the arc tangent of parameter f; that is, the value whose tangent is f. The return value is in radians, between -Π/2 and Π/2 (inclusive). Example res = atan(1.0) ‘ res = 7.853982e-1 atan2 Prototype sub function atan2(dim y as float, dim x as float) as float Description This is the two-argument arc tangent function.
mikoBasic PRO for dsPIC30/33 and PIC24 exp Prototype sub function exp(dim x as float) as float Description Function returns the value of e — the base of natural logarithms — raised to the power x (i.e. ex). Example res = exp(0.5) ‘ res = 1.648721 fabs Prototype sub function fabs(dim d as float) as float Description Function returns the absolute (i.e. positive) value of d. Example res = fabs(-1.3) ‘ res = 1.
mikroBasic PRO for dsPIC30/33 and PIC24 log10 Prototype sub function log10(dim x as float) as float Description Function returns the base-10 logarithm of x (i.e. log10(x)). Example res = log10(100.) ‘ res = 2.000000 modf Prototype sub function modf(dim val as float, dim byref iptr as float) as float Description Returns argument val split to the fractional part (function return val) and integer part (in number iptr). Example res = modf(6.25, iptr) ‘ res = 0.25, iptr = 6.
mikoBasic PRO for dsPIC30/33 and PIC24 tan Prototype sub function tan(dim x as float) as float Description Function returns the tangent of x in radians. The return value spans the allowed range of floating point in the mikroBasic PRO for dsPIC30/33 and PIC24. Example res = tan(PI/4.) ‘ res = 0.999998 tanh Prototype sub function tanh(dim x as float) as float) Description Function returns the hyperbolic tangent of x, defined mathematically as sinh(x)/cosh(x). Example res = tanh(-PI/4.
mikroBasic PRO for dsPIC30/33 and PIC24 Trigonometry Library The mikroBasic PRO for dsPIC30/33 and PIC24 implements fundamental trigonometry functions. These functions are implemented as look-up tables. Trigonometry functions are implemented in integer format in order to save memory.
mikoBasic PRO for dsPIC30/33 and PIC24 CHAPTER 10 Tutorials Managing Project Projects The mikroBasic PRO for dsPIC30/33 and PIC24 organizes applications into projects, consisting of a single project file (extension .mbpds) and one or more source files (extension .mbas). mikroBasic PRO for dsPIC30/33 and PIC24 IDE allows you to manage multiple projects (see Project Manager). Source files can be compiled only if they are part of a project.
mikroBasic PRO for dsPIC30/33 and PIC24 New Project The easiest way to create a project is by means of the New Project Wizard, drop-down menu Project › New Project or by clicking the New Project Icon from Project Toolbar.
mikoBasic PRO for dsPIC30/33 and PIC24 Step Two - Enter the oscillator frequency value: Step Three - Specify the location where your project will be saved: MikroElektronika 694
mikroBasic PRO for dsPIC30/33 and PIC24 Step Four - Add project file to the project if they are avaiable at this point.
mikoBasic PRO for dsPIC30/33 and PIC24 Step Six - Click Finish button to create your New Project: Related topics: Project Manager, Project Settings New Project The easiest way to create a project is by means of the New Project Wizard, drop-down menu Project › New Project or by clicking the New Project Icon from Project Toolbar.
mikroBasic PRO for dsPIC30/33 and PIC24 Step One - Select the device from the device drop-down list: Step Two - Enter the oscillator frequency value: 697 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 Step Three - Specify the location where your project will be saved: Step Four - Add project file to the project if they are avaiable at this point.
mikroBasic PRO for dsPIC30/33 and PIC24 Step Five - Select inital Library Manager state: Step Six - Click Finish button to create your New Project: Related topics: Project Manager, Project Settings 699 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 Customizing Projects You can change basic project settings in the Project Settings window, like chip and oscillator frequency. Any change in the Project Setting Window affects currently active project only, so in case more than one project is open, you have to ensure that exactly the desired project is set as active one in the Project Manager. Also, you can change configuration bits of the selected chip in the Edit Project window.
mikroBasic PRO for dsPIC30/33 and PIC24 The list of relevant files is stored in the project file (extension .mbpds). To add a file to the project, click the Add File to Project Icon or press Insert button on your keyboard. Each added source file must be self-contained, i.e. it must have all necessary definitions after preprocessing. To remove file(s) from the project, click the Remove File from Project Icon keyboard.
mikoBasic PRO for dsPIC30/33 and PIC24 Add/Remove Files from Project The project can contain the following file types: - .mbas source files - .mcl binary files - .pld project level defines files - image files - .ihex EEPROM files - .hex, .asm and .lst files, see output files. These files can not be added or removed from project. - other files The list of relevant files is stored in the project file (extension .mbpds).
mikroBasic PRO for dsPIC30/33 and PIC24 Project Level Defines: Project Level Defines (.pld) files can also be added to project. Project level define files enable you to have defines that are visible in all source files in the project. A file must contain one definition per line in the following form: ANALOG DEBUG TEST For example, lets make a project level define named pld_test. First of all, create a new file with the .pld extension, pld_test_file.pld.
mikoBasic PRO for dsPIC30/33 and PIC24 Source Files Source files containing source code should have the extension .mbas. The list of source files relevant to the application is stored in project file with extension .mbpds, along with other project information. You can compile source files only if they are part of the project. Managing Source Files Creating new source file To create a new source file, do the following: 1.
mikroBasic PRO for dsPIC30/33 and PIC24 Closing file 1. Make sure that the tab containing the file that you want to close is the active tab. 2. Select File › Close from the drop-down menu, or right click the tab of the file that you want to close and select Close option from the context menu. 3. If the file has been changed since it was last saved, you will be prompted to save your changes. Search Paths You can specify your own custom search paths: select Project › Edit Search Paths...
mikoBasic PRO for dsPIC30/33 and PIC24 Paths for Source Files (.mbas) You can specify either absolute or relative path to the source file. If you specify a relative path, mikroBasic PRO for dsPIC30/33 and PIC24 will look for the file in following locations, in this particular order: 1. the project folder (folder which contains the project file .mbpds), 2. your custom search paths, 3. mikroBasic PRO for dsPIC30/33 and PIC24 installation folder > Uses folder.
mikroBasic PRO for dsPIC30/33 and PIC24 Search Paths You can specify your own custom search paths: select Project › Edit Search Paths... option from the drop-down menu: Following options are available: Icon Description Add Search Path. Remove Search Path. Purge Invalid Paths. Paths for Source Files (.mbas) You can specify either absolute or relative path to the source file.
mikoBasic PRO for dsPIC30/33 and PIC24 Clean Project Folder This menu gives you option to choose which files from your current project you want to delete. Files marked in bold can be easily recreated by building a project. Other files should be marked for deletion only with a great care, because IDE cannot recover them.
mikroBasic PRO for dsPIC30/33 and PIC24 Compilation When you have created the project and written the source code, it’s time to compile it. Select Project › Build from the drop-down menu, or click the Build Icon from the Build Toolbar. If more more than one project is open you can compile all open projects by selecting Project › Build All Projects from the drop-down menu, or click the Build All Projects Icon from the Build Toolbar. Progress bar will appear to inform you about the status of compiling.
mikoBasic PRO for dsPIC30/33 and PIC24 Creating New Library mikroBasic PRO for dsPIC30/33 and PIC24 allows you to create your own libraries. In order to create a library in mikroBasic PRO for dsPIC30/33 and PIC24 follow the steps bellow: 1. Create a new source file, see Managing Source Files 2. Save the file in one of the subfolders of the compiler’s Uses folder: DriveName:\Program Files\Mikroelektronika\mikroBasic PRO for dsPIC\Uses\ 3. Write a code for your library and save it. 4.
mikroBasic PRO for dsPIC30/33 and PIC24 Using Microchip MPLAB® IDE with mikroElektronika compilers This new feature will boost your productivity by enabling you to import your code in a non-mikroElektronika enironment - Microchip’s MPLAB®. With the introduction of COFF File in mikroElektronika compiler, it is possible to debug and analyze your code through a software or hardware simulator. Debugging Your Code If your program has been built correctly, the compiler should generate a .hex file and a .
mikoBasic PRO for dsPIC30/33 and PIC24 7.
mikroBasic PRO for dsPIC30/33 and PIC24 8. Put the J11 and J10 Jumpers in the correct position, as showed in the picture below: 9. Next, open MPLAB®, and select the appropriate device by choosing Configure › Select Device... : 10. After device selection, click on the File › Import. Open file dialog box should appear. Then, go to the project folder and open the generated HEX file, UART.hex.
mikoBasic PRO for dsPIC30/33 and PIC24 11. Next, click the File › Import. Open file dialog box should appear. Then, go to the project folder and open the generated COFF file, UART.
mikroBasic PRO for dsPIC30/33 and PIC24 12. Then, select the MPLAB® ICD 2 from the Debugger › Select Tool menu for hardware debugging: 13. Complete the MPLAB® ICD 2 Setup Wizard from the Debugger menu (if needed).
mikoBasic PRO for dsPIC30/33 and PIC24 14.
mikroBasic PRO for dsPIC30/33 and PIC24 15.
mikoBasic PRO for dsPIC30/33 and PIC24 16. Now, you can start debugging the code by clicking Step Over button on the Debug toolbar, or by pressing F8: Related topics: COFF File, Using MPLAB® Simulator Using MPLAB® Simulator Note: It is assumed that MPLAB® is previously installed. 1. First of all, start mikroBasic PRO for dsPIC30/33 and PIC24 Help and open the desired project. In this example, UART project for EasydsPIC4A board and dsPIC30F4013 will be opened. 2.
mikroBasic PRO for dsPIC30/33 and PIC24 719 MikroElektronika
mikoBasic PRO for dsPIC30/33 and PIC24 5. After device selection, click on the File › Import. Open file dialog box should appear. Then, go to the project folder and open the generated COFF file, UART.
mikroBasic PRO for dsPIC30/33 and PIC24 6.
mikoBasic PRO for dsPIC30/33 and PIC24 7.
mikroBasic PRO for dsPIC30/33 and PIC24 Frequently Asked Questions This is a list of frequently asked questions about using mikroElektronika compilers. If your question is not answered on this page, please contact mikroElektronika Support Desk.
mikoBasic PRO for dsPIC30/33 and PIC24 I have bought license for the older version, do I have to pay license for the new version of the compiler ? No, once you pay for the license key you get a lifetime license. When we release a new major release of the compiler, you might need to repeat registration procedure from your new compiler and you will get new license free of charge.
mikroBasic PRO for dsPIC30/33 and PIC24 I need this project finished, can you help me ? We currently do not do custom projects, however, we can give you some directions when you start working on your project and come to a problem. Also, our forum is very active community and as you can find there experts in different fields, we encourage you to look for help there.
If you have any questions, comments or business proposals, do not hesitate to contact us at office@mikroe.com If you are experiencing some problems with any of our products or just need additional information, please place your ticket at www.mikroe.com/en/support If you want to learn more about our products, please visit our website at www.mikroe.