mikroPascal PRO for dsPIC30/33 and PIC24 is a full-featured compiler for dsPIC30, dsPIC33 and PIC24 MCUs from Microchip. It is designed for developing, building and debugging dsPIC30/33 and PIC24based embedded applications. This development environment has a wide range of features such as: easy-to-use IDE, very compact and efficient code, many hardware and software libraries, comprehensive documentation, software simulator, COFF file generation, SSA optimization (up to 30% code reduction) and many more.
mikoPascal PRO for dsPIC30/33 and PIC24 Table of Contents CHAPTER 1 INTRODUCTION Introduction to mikroPascal PRO for dsPIC30/33 and PIC24 32 32 33 What’s new in mikroPascal PRO for dsPIC30/33 and PIC24 34 Software License Agreement 35 Technical Support How to Register 37 37 CHAPTER 2 mikroPascal PRO for dsPIC30/33 and PIC24 Environment Main Menu Options File 41 41 42 43 Edit 44 Features Where to Start Compiler Changes IDE Changes mikroElektronika Associates License Statement
mikroPascal PRO for dsPIC30/33 and PIC24 Help Help Menu Options 53 53 mikroPascal PRO for dsPIC30/33 and PIC24 IDE 54 Code Editor 55 Code Explorer 62 Project Manager Project Settings Library Manager 63 65 66 Routine List Statistics 68 68 Messages Window Quick Converter Macro Editor Image Preview Toolbars 75 76 76 77 79 IDE Overview Editor Settings Auto Save Highlighter Spelling Comment Style Code Folding Code Assistant Parameter Assistant Bookmarks Go to Line Colum
mikoPascal 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 80 80 81 81 82 82 83 83 84 84 85 85 Customizing IDE Layout 86 Options 88 Integrated Tools 91 Active Comments 99 Docking Windows Saving Layout Auto Hide Code editor Tools Output settings Active Comments Editor ASCII Chart EEPROM Editor Filter Designer G
mikroPascal PRO for dsPIC30/33 and PIC24 Metacharacters - Iterators Metacharacters - Alternatives Metacharacters - Subexpressions Metacharacters - Backreferences 112 113 113 113 Keyboard Shortcuts CHAPTER 3 mikroPascal PRO for dsPIC30/33 and PIC24 Command Line Options CHAPTER 4 mikroICD (In-Circuit Debugger) Introduction mikroICD Debugger Options 114 116 116 118 118 118 120 mikroICD Debugger Example mikroICD Debugger Windows 121 125 CHAPTER 5 Software Simulator Overview Software Simulat
mikoPascal PRO for dsPIC30/33 and PIC24 Interrupts 144 Linker Directives 146 Built-in Routines 148 Code Optimization 161 Function Calls from Interrupt Interrupt Handling Interrupt Example Directive absolute Directive org 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 Get_Fosc_kHz Get_Fosc_Per_Cyc Reset ClrWdt DisableContextSaving(
mikroPascal PRO for dsPIC30/33 and PIC24 Local vars optimization Better code generation and local optimization 161 161 Single Static Assignment Optimization 162 Common Object File Format (COFF) 165 CHAPTER 7 dsPIC30/33 and PIC24 Specifics 167 167 dsPIC Memory Organization 169 Memory Type Specifiers 172 Memory Type Qualifiers 174 Read Modify Write Problem CHAPTER 8 mikroPascal PRO for dsPIC30/33 and PIC24 Language Reference Lexical Elements Overview Whitespace 175 179 179 181 182
mikoPascal PRO for dsPIC30/33 and PIC24 Tokens 183 Literals 184 Keywords Identifiers 187 190 Punctuators 190 Program Organization 192 Scope and Visibility 194 Name Spaces Units 195 196 Variables 198 Constants Labels Functions and Procedures 200 200 201 Types 204 Simple Types Derived Types 205 205 Token Extraction Example Integer Literals Floating Point Literals Character Literals String Literals Case Sensitivity Uniqueness and Scope Identifier Examples Brackets
mikroPascal PRO for dsPIC30/33 and PIC24 Arrays 205 Strings 207 Pointers 208 Pointer Arithmetic 211 Records 213 Types Conversions 215 Typedef Specifier Type Qualifiers 217 217 Qualifier volatile Operators 217 218 Arithmetic Operators 218 Relational Operators 219 Bitwise Operators 220 Boolean Operators Unary Operators 222 222 Sizeof Operator 223 Array Declaration Constant Arrays Multi-dimensional Arrays String Concatenating Pointers and memory spaces Function P
mikoPascal PRO for dsPIC30/33 and PIC24 Sizeof Applied to Expression Sizeof Applied to Type 223 223 Expressions 224 Statements Assignment Statements Compound Statements (Blocks) Conditional Statements If Statement 225 226 226 226 227 Case Statement 227 Iteration Statements For Statement 229 229 While Statement Repeat Statement Jump Statements Break and Continue Statements 230 230 231 231 Exit Statement Goto Statement asm Statement 232 232 233 With Statement Directives Compi
mikroPascal PRO for dsPIC30/33 and PIC24 Library Routines ADCx_Init ADCx_Init_Advanced ADCx_Get_Sample ADCx_Read ADC_Set_Active Library Example HW Connection 243 243 244 245 245 246 246 247 CAN Library 248 CANSPI Library 263 Library Routines CANxSetOperationMode CANxGetOperationMode CANxInitialize CANxSetBaudRate CANxSetMask CANxSetFilter CANxRead CANxWrite CAN Constants CAN_OP_MODE Constants CAN_CONFIG_FLAGS Constants CAN_TX_MSG_FLAGS Constants CAN_RX_MSG_FLAGS Constants CAN_M
mikoPascal PRO for dsPIC30/33 and PIC24 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 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_Dat
mikroPascal PRO for dsPIC30/33 and PIC24 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 311 311 312 312 313 313 314 315 319 EEPROM Library 319 Epson S1D13700 Graphic Lcd Library 323 Flash Memory Library 338 Library Routines EEPROM_Erase EEPROM_Erase_Block EEPROM_Read EEPROM_Write EEPROM_Write_Block Library Example External de
mikoPascal PRO for dsPIC30/33 and PIC24 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_Compact FLASH_Write_DoWrite FLASH_Read4 FLASH_Read4_Compact PIC24 and dsPIC33 Functions FLASH_Erase FLASH_Write FLASH_Write_Compact FLASH_Read FLASH_Read_Compact Library Example
mikroPascal PRO for dsPIC30/33 and PIC24 Glcd_Image Glcd_PartialImage Library Example HW Connection 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 dependencies of Keypad Library Library Routines Keypad_Init Keypad_Key_Press Keypad_Key_Click Library Example HW Connection Library Dependency Tree
mikoPascal PRO for dsPIC30/33 and PIC24 Multi Media Card Library 389 OneWire Library 409 Peripheral Pin Select Library 414 Port Expander Library 418 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_Assign Mmc_Fat_Reset Mmc_Fat_Read Mmc_Fat_Rewrite Mmc_Fat_Append Mmc_Fat_Delete Mmc_Fat_Writ
mikroPascal PRO for dsPIC30/33 and PIC24 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 Expander_Set_DirectionPortA Expander_Set_DirectionPortB Expander_Set_DirectionPortAB Expander_Set_PullUpsPortA Expander_Set_PullUpsPortB Expander_Set_PullUpsPortAB HW Connection 419 420 420 421 421 422 422 423 423 424 424 425 425 425 426 426 428 PS/2
mikoPascal PRO for dsPIC30/33 and PIC24 RS485Master_Send RS485Slave_Init RS485Slave_Receive RS485Slave_Send Library Example HW Connection Message format and CRC calculations 443 444 445 445 446 449 450 Software I²C Library 451 Software SPI Library 457 Software UART Library 461 Sound Library 465 SPI Library 469 External dependencies of Software I²C Library Library Routines Soft_I2C_Init Soft_I2C_Start Soft_I2C_Read Soft_I2C_Write Soft_I2C_Stop Soft_I2C_Break Library Example E
mikroPascal PRO for dsPIC30/33 and PIC24 SPI Ethernet Library 476 SPI Ethernet ENC24J600 Library 501 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_putConstString SPI_Ethernet_getByte SPI_Ethernet_getBytes SPI_Ethernet_UserTCP SPI_Ethernet_UserUDP SPI_Ethernet_se
mikoPascal PRO for dsPIC30/33 and PIC24 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_24j600_arpResolve SPI_Ethernet_24j600_sendUDP SPI_Ethernet_24j600_dnsResolve SPI_Ethernet_24j600_initDHCP SPI_Ethernet_24j600_doDHCPLeaseTime SPI_Ethernet_24j600_renewDHCP Library Example
mikroPascal PRO for dsPIC30/33 and PIC24 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 535 536 536 537 537 537 538 538 539 539 SPI Lcd8 (8-bit interface) Library 541 SPI T6963C Graphic Lcd Library 547 Library Dependency Tree External dependencies of SPI Lcd Library Library Routines SPI_Lcd8_Config SPI_Lcd8_Out SPI_Lcd8_Out_Cp SPI_Lcd8_Chr SPI_Lcd8_Chr_Cp SPI_Lcd8
mikoPascal PRO for dsPIC30/33 and PIC24 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 HW Connection T6963C Graphic Lcd Library Library Dependency Tree External dependencies of T6963C Graphic Lcd Library Li
mikroPascal PRO for dsPIC30/33 and PIC24 T6963C_txtFill T6963C_cursor_height T6963C_graphics T6963C_text T6963C_cursor T6963C_cursor_blink Library Example HW Connection 583 583 584 584 584 585 585 589 TFT Library 590 Touch Panel Library 608 External dependencies of TFT Library 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_Dot TFT_Set_Pen TFT_Set_Brush TFT_Line TFT_H_Line T
mikoPascal PRO for dsPIC30/33 and PIC24 TP_Set_Calibration_Consts Library Example 612 612 Touch Panel TFT Library 616 UART Library 622 USB Library 632 Digital Signal Processing Libraries 637 FIR Filter Library 638 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_Coordinates TP_TFT_Calibrate_Min TP_TFT_Calibrate_Max TP_TFT_Get_Calibration_Consts TP_TFT_Set_Calibration_Cons
mikroPascal PRO for dsPIC30/33 and PIC24 FIR_Radix 638 IIR Filter Library 639 FFT Library 640 Bit Reverse Complex Library 644 Vectors Library 645 Matrix Library Matrices Library 652 652 Miscellaneous Libraries Button Library 656 656 C Type Library 658 Library Routines IIR_Radix Library Dependency Tree FFT Twiddle Factors: TwiddleCoeff_64 TwiddleCoeff_128 TwiddleCoeff_256 TwiddleCoeff_512 Library Routines BitReverseComplex Library Routines Vector_Set Vector_Power Vecto
mikoPascal PRO for dsPIC30/33 and PIC24 iscntrl isdigit isgraph islower ispunct isspace isupper isxdigit toupper tolower 658 659 659 659 659 659 660 660 660 660 Conversions Library 661 Setjmp Library 673 String Library 675 MikroElektronika 26 Library Dependency Tree Library Routines ByteToStr ShortToStr WordToStr IntToStr LongintToStr LongWordToStr FloatToStr WordToStrWithZeros IntToStrWithZeros LongWordToStrWithZeros LongIntToStrWithZeros ByteToHex ShortToHex WordToHex
mikroPascal PRO for dsPIC30/33 and PIC24 memcpy memmove memset strcat strcat2 strchr strcmp strcpy strlen strncat strncpy strspn strncmp strstr strcspn strpbrk strrchr ltrim rtrim strappendpre strappendsuf length 676 677 677 677 678 678 678 679 679 679 679 680 680 680 681 681 681 681 682 682 682 682 Time Library 683 Trigon Library 687 Library Routines Time_dateToEpoch Time_epochToDate Time_dateDiff Library Example TimeStruct type definition Library Routines acos asin a
mikoPascal PRO for dsPIC30/33 and PIC24 modf pow sin sinh sqrt tan tanh 690 690 690 690 690 691 691 Trigonometry Library 692 CHAPTER 10 Tutorials Managing Project 693 693 693 New Project 694 Customizing Projects 698 Source Files 700 Edit Project Clean Project Folder Compilation 702 703 704 Creating New Library 705 Using Microchip MPLAB® IDE with mikroElektronika compilers 706 Using MPLAB® ICD 2 Debugger Using MPLAB® Simulator Frequently Asked Questions 706 713 718 L
mikroPascal PRO for dsPIC30/33 and PIC24 I am getting “Access is denied” error in Vista, how to solve this problem ? 718 What are differences between mikroC PRO, mikroPascal PRO and mikroBasic PRO compilers?718 Why do they have different prices ? 718 Why do your PIC compilers don’t support 12F508 and some similar chips ? 718 What are limitations of demo versions of mikroElektronika’s compilers ? 718 Why do I still get demo limit error when I purchased and installed license key ? 718 I have bought licen
mikoPascal PRO for dsPIC30/33 and PIC24 CHAPTER 1 INTRODUCTION mikroPascal PRO for dsPIC30/33 and PIC24 is a powerful, feature-rich development tool for the 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Introduction to mikroPascal PRO for dsPIC30/33 and PIC24 dsPIC30/33 and PIC24 and mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 What’s new in mikroPascal 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 mikroPascal PRO for dsPIC30/33 and PIC24, visit the following link: http://www.mikroe.com/download/eng/documents/compilers/mikropascal/pro/dspic/version_history.
mikroPascal 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.
mikoPascal 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 O
mikroPascal 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/mikroPascal 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.
mikoPascal 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
mikroPascal 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 CHAPTER 2 mikroPascal PRO for dsPIC30/33 and PIC24 Environment 39 MikroElektronika
mikoPascal PRO for dsPIC30/33 and PIC24 Main Menu Options Available Main Menu options are: Related topics: Keyboard shortcuts, Toolbars MikroElektronika 40
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 View View Menu Options View Menu contains commands for controlling the on-screen display of the current project.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 mikroPascal PRO for dsPIC30/33 and PIC24 IDE IDE Overview The mikroPascal PRO for dsPIC30/33 and PIC24 is an user-friendly and intuitive environment.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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).
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 The 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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 .
mikroPascal 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 ROM Memory Constants Displays ROM memory constants and their addresses. Functions Sorts and displays functions in various ways.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Memory Summary Displays summary of RAM and ROM memory in a pie-like form.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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 .
mikoPascal 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. Options Options menu consists of three tabs: Code Editor, Tools and Output settings.
mikroPascal 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 mikroPascal PRO for dsPIC30/33 and PIC24 specifics). Build all files as library enables user to use compiled library (*.
mikoPascal PRO for dsPIC30/33 and PIC24 MikroElektronika 88
mikroPascal 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.
mikoPascal 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.
mikroPascal 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 mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Graphic Lcd Bitmap Editor The mikroPascal PRO for dsPIC30/33 and PIC24 includes the Graphic Lcd Bitmap Editor. Output is the mikroPascal PRO for dsPIC30/33 and PIC24 compatible code. You can launch it from the drop-down menu Tools › Glcd Bitmap Editor.
mikroPascal PRO for dsPIC30/33 and PIC24 HID Terminal The mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Lcd Custom Character mikroPascal PRO for dsPIC30/33 and PIC24 includes the Lcd Custom Character. Output is mikroPascal PRO for dsPIC30/33 and PIC24 compatible code. You can launch it from the drop-down menu Tools › Lcd Custom Character.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 USART Terminal The mikroPascal 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.
mikroPascal 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.
mikoPascal 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).
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 If you click No, comment will be removed from the source code.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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 interrupts.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroPascal PRO for dsPIC30/33 and PIC24 IDE.
mikroPascal 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
mikoPascal PRO for dsPIC30/33 and PIC24 CHAPTER 3 mikroPascal PRO for dsPIC30/33 and PIC24 Command Line Options Usage: mPdsPIC.exe [- [-]] [ [-]] [-]] Infile can be of *.c, *.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.
mikroPascal 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.mppds” -SP”C:\Program Files\Mikroelektronika\mikroPascal PRO for dsPIC\Defs”: Output files generated to file path specified by filename.
mikoPascal 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 mikroPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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 they 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.
mikroPascal PRO for dsPIC30/33 and PIC24 mikroICD Debugger Windows Debug Windows This section provides an overview of available Debug Windows in mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CHAPTER 5 Software Simulator Overview MikroElektronika 128
mikroPascal PRO for dsPIC30/33 and PIC24 Software Simulator The Source-level Software Simulator is an integral component of the mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Software Simulator Debug Windows Debug Windows This section provides an overview of available Debug Windows in mikroPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CHAPTER 6 mikroPascal PRO for dsPIC30/33 and PIC24 Specifics The following topics cover the specifics of mikroPascal PRO for dsPIC30/33 and PIC24 compiler: - Predefined Globals and Constants - Accessing Individual Bits - Interrupts - Linker Directives - Built-in Routines - Code Optimization - Common Object File Format (COFF) MikroElektronika 136
mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Predefined Globals and Constants To facilitate dsPIC30/33 and PIC24 programming, the mikroPascal 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 mikroPascal PRO for dsPIC30/33 and PIC24 will include an appropriate (*.
mikoPascal PRO for dsPIC30/33 and PIC24 Accessing Individual Bits The mikroPascal 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; var Z_bit : sbit at SR.B1; To access this bit in your code by its name, you can write something like this: // Clear Zero Bit SR.
mikroPascal PRO for dsPIC30/33 and PIC24 sbit type The mikroPascal PRO for dsPIC30/33 and PIC24 compiler has sbit data type which provides access to bit-addressable SFRs. You can declare a sbit varible in a unit in such way that it points to a specific bit in SFR register: unit MyUnit; var Abit: sbit; sfr; external; // Abit is precisely defined in some external file, for example in the main program unit ... implementation .... end.
mikoPascal 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: unit MyUnit; var PORTAlias: byte; external; // here in the library we can use its symbolic name ... implementation ... end. program MyProgram; ... var PORTAlias: byte at PORTB; // this is where PORTAlias is fully defined ... begin ... end.
mikroPascal 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 - Fi
mikoPascal PRO for dsPIC30/33 and PIC24 For the sake of backward compatibility, user may write also: procedure int1(); org IVT_ADDR_U1RXINTERRUPT; begin asm nop; end; end; which is equivalent to: procedure int1(); iv IVT_ADDR_U1RXINTERRUPT; begin asm nop; end; end; It is recommended that interrupts are handled in this way for the sake of better readability of the user projects.
mikroPascal PRO for dsPIC30/33 and PIC24 Linker Directives mikroPascal PRO for dsPIC30/33 and PIC24 uses an internal algorithm to distribute objects within memory. If you need to have a variable, constant or a 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.
mikoPascal PRO for dsPIC30/33 and PIC24 procedure proc(par : byte); org 0x200; begin // Procedure will start at address 0x200; ... end; org directive can be used with main routine too. For example: program Led_Blinking; begin 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: begin orgall(0x200); // All the routines, constants in main program will be above the address 0x200 .
mikroPascal PRO for dsPIC30/33 and PIC24 Built-in Routines mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Lo Prototype Description function Lo(number: longint): 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Higher Prototype Description function Higher(number: longint): 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.
mikoPascal PRO for dsPIC30/33 and PIC24 LoWord Prototype Description function LoWord(val : longint) : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Inc Prototype Description Parameters Returns procedure Inc(var par : 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 procedure Dec(var par : longint); Decreases parameter par by 1. - par: value which will be decremented by 1 Nothing. Requires Nothing.
mikoPascal PRO for dsPIC30/33 and PIC24 Ord Prototype Description function Ord(const character : char) : byte; Function returns ASCII code of the character. This is an “inline” routine; the code is generated in the place of the call. Parameters Returns Requires - character: input character ASCII code of the character. Nothing. Example c := Ord(‘A’); Notes None. // returns 65 SetBit Prototype Description procedure SetBit(var register_ : word; rbit : byte); Function sets the bit rbit of register_.
mikroPascal PRO for dsPIC30/33 and PIC24 TestBit Prototype Description function TestBit(register_, rbit : byte) : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Vdelay_ms Prototype Description Parameters Returns Requires Example Notes procedure VDelay_ms(Time_ms : 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. Nothing. var pause : word; ... VDelay_ms(pause); // ~ one second pause None.
mikroPascal PRO for dsPIC30/33 and PIC24 Delay_Cyc Prototype procedure Delay_Cyc(x: word; y: word); Description Creates a delay based on MCU clock. Delay lasts for x*16384 + y MCU clock cycles. Parameters Returns 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Clock_MHz Prototype Description function Clock_MHz() : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Reset Prototype Description 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 procedure ClrWdt(); This procedure is equal to assembler instruction clrwdt. None. Returns Nothing. Requires Nothing. Example ClrWdt(); // Clears WDT Notes None.
mikoPascal PRO for dsPIC30/33 and PIC24 SetFuncCall Prototype Description procedure SetFuncCall(FuncName: 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.
mikroPascal PRO for dsPIC30/33 and PIC24 GetDateTime Prototype Description Parameters function DoGetDateTime() : string; Use the GetDateTime() 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 := GetDateTime(); Notes None. DoGetVersion Prototype Description Parameters function GetVersion() : string; Use the GetVersion() to get the current version of compiler. None.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 0x0102 0x320001 BRA Z L__SSA2 L__SSA_Test6: ;Example.mpas,36 :: nop; 0x0104 0x000000 NOP Without SSA enabled, sub procedure SSA_Test this example is consisted of 5 asm instructions: ;Example.mpas,34 :: if (y+k) then 0x0102 0x97B8CE MOV [W14-8], W1 0x0104 0x57006A SUB W14, #10, W0 0x0106 0x408010 ADD W1, [W0], W0 0x0108 0x320001 BRA Z L__SSA2 L__SSA_Test6: ;Example.
mikroPascal 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 Pascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CHAPTER 7 dsPIC30/33 and PIC24 Specifics In order to get the most from the mikroPascal 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.
mikroPascal 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 mikroPascal 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. Therefore use byte, char and short only in places where you can significantlly save RAM (e.g.
mikoPascal 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.
mikroPascal 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Memory Type Specifiers The mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 xdata Description This memory specifier allows user to access X Data memory space. Example var y : char; xdata; // puts x in xdata memory space ydata Description This memory specifier allows user to access Y Data memory space. Example var y : char; ydata; // puts y in ydata memory space dma Description This memory specifier allows user to access DMA memory space (dsPIC33F specific).
mikroPascal 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.
mikoPascal 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).
mikroPascal 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CHAPTER 8 mikroPascal PRO for dsPIC30/33 and PIC24 Language Reference MikroElektronika 177
mikroPascal PRO for dsPIC30/33 and PIC24 - Lexical Elements - Whitespace - Comments - Tokens - Literals - Keywords - Identifiers - Punctuators - Program Organization - Program Organization - Scope and Visibility - Units - Variables - Constants - Labels - Functions and Procedures - Functions - Procedures - Types - Simple Types - Arrays - Strings - Pointers - Introduction to Pointers - Function Pointers - Pointer Arithmetic - Records - Types Conversions - Implicit Conversion - Exp
mikoPascal PRO for dsPIC30/33 and PIC24 - Statements - Introduction to Statements - Assignment Statements - Compound Statements (Blocks) - Conditional Statements - If Statement - Case Statement - Iteration Statements (Loops) - For Statement - While Statement - Repeat Statement - Jump Statements - Break and Continue Statements - Exit Statement - Goto Statement - asm Statement - Directives - Compler Directives - Linker Directives Lexical Elements Overview The following topics pr
mikroPascal 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 var i : char; j : word; and var i : char; j : word; are lexically equivalent and parse identically.
mikoPascal PRO for dsPIC30/33 and PIC24 Comments Comments are pieces of a 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. There are two ways to create comments in mikroPascal. You can use multi-line comments which are enclosed with braces or (* and *): { All text between left and right brace constitutes a comment. May span multiple lines.
mikoPascal PRO for dsPIC30/33 and PIC24 Token Extraction Example Here is an example of token extraction. Take a look at the following example code sequence: end_flag := 0; First, note that end_flag would be parsed as a single identifier, rather than as the keyword end followed by the identifier _flag.
mikroPascal PRO for dsPIC30/33 and PIC24 Floating Point Literals A floating-point value consists of: - Decimal integer - Decimal point - Decimal fraction - e or E and a signed integer exponent (optional) You can omit either decimal integer or decimal fraction (but not both). Negative floating constants are taken as positive constants with the unary operator minus (-) prefixed. mikroPascal PRO for dsPIC30/33 and PIC24 limits floating-point constants to the range of ±1.17549435082 * 10-38 .. ±6.
mikoPascal PRO for dsPIC30/33 and PIC24 Here are several string literals: ‘Hello world!’ // message, 12 chars long ‘Temperature is stable’ // message, 21 chars long ‘ ‘ // two spaces, 2 chars long ‘C’ // letter, 1 char long ‘’ // null string, 0 chars long The apostrophe itself cannot be a part of the string literal, i.e. there is no escape sequence. You can use the built-in function Chr to print an apostrophe: Chr(39). Also, see String Splicing.
mikroPascal PRO for dsPIC30/33 and PIC24 Keywords Keywords are special-purpose words which cannot be used as normal identifier names. Beside standard PASCAL keywords, all relevant SFRs are defined as global variables and represent reserved words that cannot be redefined (for example: W0, TMR1, T1CON, etc). Probe the Code Assistant for specific letters (Ctrl+Space in Editor) or refer to Predefined Globals and Constants.
mikoPascal PRO for dsPIC30/33 and PIC24 - forward goto helper idata if ilevel implementation implements in index inherited initialization inline interface io is 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
mikroPascal 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, mikroPascal 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.
mikoPascal 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 get 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Brackets Brackets [ ] indicate single and multidimensional array subscripts: var alphabet : array[1..30] of byte; // ... alphabet[3] := ‘c’; For more information, refer to Arrays. Parentheses Parentheses ( ) are used to group expressions, isolate conditional expressions and indicate function calls and function declarations: d := c * (a + b); if (d = z) then ...
mikoPascal PRO for dsPIC30/33 and PIC24 Colon Colon (:) is used in declarations to separate identifier list from type identifier. For example: var i, j : byte; k : word; In the program, use the colon to indicate a labeled statement: start: nop; ... goto start; For more information, refer to Labels. Dot Dot (.) indicates an access to a field of a record. For example: person.surname := ‘Smith’; For more information, refer to Records. Dot is a necessary part of floating point literals.
mikroPascal PRO for dsPIC30/33 and PIC24 { types declarations } type ... { variables declarations } var Name[, Name2...] : [^]type; [absolute 0x123;] [external;] [volatile;] [register;] [sfr;] { labels declarations } label ... { procedures declarations } procedure procedure_name(parameter_list); { local declarations } begin ... end; { functions declarations } function function_name(parameter_list) : return_type; { local declarations } begin ...
mikoPascal PRO for dsPIC30/33 and PIC24 { functions prototypes } function function_name([var] [const] ParamName : [^]type; [var] [const] ParamName2, ParamName3 : [^]type) : [^]type; //******************************************************** //* Implementation: //******************************************************** implementation { constants declarations } const ... { types declarations } type ... { variables declarations } var Name[, Name2...
mikroPascal PRO for dsPIC30/33 and PIC24 Place of declaration Scope Identifier is declared in the declaration of a program, function, or procedure Scope extends from the point where it is declared to the end of the current block, including all blocks enclosed within that scope. Identifiers in the outermost scope (file scope) of the main unit are referred to as globals, while other identifiers are locals.
mikoPascal PRO for dsPIC30/33 and PIC24 Units In mikroPascal PRO for dsPIC30/33 and PIC24, each project consists of a single project file and one or more unit files. Project file, with extension .mppds contains information about the project, while unit files, with extension .mpas, contain the actual source code.
mikroPascal PRO for dsPIC30/33 and PIC24 Nothing should precede the keyword program except comments. After the program name, you can optionally place the uses clause. Place all global declarations (constants, variables, types, labels, routines) before the keyword begin. Other Units Units other than main start with the keyword unit. Newly created blank unit contains the bare-bones: unit MyUnit; implementation end. Other than comments, nothing should precede the keyword unit.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 In the First_Unit we will define and declare routine called pi_r_squared (calculates pi multiplied by the radius squared): unit First_Unit; procedure pi_r_squared(rr : real); // Declaration of the pi_r_squared routine implementation procedure pi_r_squared(rr : real); var res : real; // Definition of the pi_r_squared routine begin res := rr*3.14; end; end. In the Second_Unit we will make a call to the routines defined externally (r_squared and pi_r_squared).
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Note: Label should be followed by end of line (CR) otherwise compiler will report an error. label loop; ... loop: Beep; // compiler will report an error loop: // compiler will report an error 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 a value while procedure does not.
mikoPascal PRO for dsPIC30/33 and PIC24 Example Here’s a simple function which calculates xn based on input parameters x and n (n > 0): function power(x, n : byte) : longint; var i : byte; begin i := 0; result := 1; if n > 0 then for i := 1 to n do result := result*x; end; Now we could call it to calculate, say, 312: tmp := power(3, 12); Procedures Procedure is declared like this: procedure procedure_name(parameter_list); { local declarations } begin { procedure body } end; procedure_name represents a proc
mikroPascal PRO for dsPIC30/33 and PIC24 Example: This example shows how to declare a function which returns a complex type. program Example; type TCircle = record // Record CenterX, CenterY: word; Radius: byte; end; var MyCircle: TCircle; // Global variable function DefineCircle(x, y: word; r: byte): TCircle; // DefineCircle function returns a Record begin result.CenterX := x; result.CenterY := y; result.
mikoPascal PRO for dsPIC30/33 and PIC24 result := a * b; end; begin Volume := Second(4); end. Functions reentrancy Functions reentrancy is allowed. Remember that the dsPIC30/33 and PIC24 have memory limitations that can vary between MCUs. Types Pascal is strictly typed language, which means that every variable and constant need to have a strictly defined type, known at the time of compilation.
mikoPascal 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 mikroPascal PRO for dsPIC30/33 and PIC24 has 16 bits. Here is an overview of simple types in mikroPascal 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 ..
mikroPascal PRO for dsPIC30/33 and PIC24 Here are a few examples of array declaration: var weekdays : array[1..7] of byte; samples : array[50] of word; begin // Now we can access elements of array variables, for example: samples[0] := 1; if samples[37] = 0 then ... Constant Arrays Constant array is initialized by assigning it a comma-delimited sequence of values within parentheses. For example: // Declare a constant array which holds number of days in each month: const MONTHS : array[1..
mikoPascal 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_name : string[length] The specifier length is a number of characters the string consists of. The string is stored internally as the given sequence of characters plus a final null character (zero) which is introduced to terminate the string. It does not count against the string’s total length. A null string (‘’) is stored as a single null character.
mikroPascal PRO for dsPIC30/33 and PIC24 Here is an example: var msg : string[20]; res_txt : string[5]; res, channel : word; begin //... // 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.
mikoPascal 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.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 program example; var w ptr_b ptr_arr arr : word; : ^byte; : ^array[10] of byte; : array[10] of byte; begin ptr_b := @arr; // @ operator will return ^byte w := @arr; // @ operator will return ^byte ptr_arr := @arr; // @ operator will return ^array[10] of byte end. If F is a routine (a function or procedure), @F returns a pointer to F.
mikroPascal 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).
mikoPascal PRO for dsPIC30/33 and PIC24 For example: var a : array[10] of byte; ptr : ^byte; begin ptr := @a[6]; ptr := ptr - 3; ptr^ := 6; Dec(ptr); end. // // // // // array a containing 10 elements of type byte // pointer to byte 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Note: In mikroPascal PRO for dsPIC30/33 and PIC24, you cannot use the record construction directly in variable declarations, i.e. without type. For example, the following declaration creates a record type called Dot: type TDot = record x, y : real; end; Each Dot contains two fields: x and y coordinates. Memory is allocated when you instantiate the structure, like this: var m, n: TDot; This variable declaration creates two instances of Dot, called m and n.
mikoPascal PRO for dsPIC30/33 and PIC24 Types Conversions Conversion of variable of one type to a variable of another type is typecasting. mikroPascal PRO for dsPIC30/33 and PIC24 supports both implicit and explicit conversions for built-in types.
mikroPascal 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 real) ahead of an expression to be converted. The expression must be enclosed in parentheses. Explicit conversion can be performed only on the operand right of the assignment operator. Special case is conversion between signed and unsigned types.
mikoPascal PRO for dsPIC30/33 and PIC24 Typedef Specifier The specifier type introduces a synonym for a specified type. The type declarations are used to construct shorter or more convenient names for types already defined by the language or declared by the user. The specifier type stands first in the declaration: type synonym = ; The type keyword assigns synonym to . The synonym needs to be a valid identifier.
mikroPascal PRO for dsPIC30/33 and PIC24 Operators Operators are tokens that trigger some computation when being applied to variables and other objects in an expression. There are four types of operators in mikroPascal PRO for dsPIC30/33 and PIC24: - Arithmetic Operators - Bitwise Operators - Boolean Operators - Relational Operators Operators Precedence and Associativity There are 4 precedence categories in mikroPascal PRO for dsPIC30/33 and PIC24.
mikoPascal PRO for dsPIC30/33 and PIC24 Division by Zero If 0 (zero) is used explicitly as the second operand (i.e. x div 0), the compiler will report an error and will not generate code. But in case of implicit division by zero: x div y, where y is 0 (zero), the result will be the maximum integer (i.e 255, if the result is byte type; 65536, if the result is word type, etc.). Unary Arithmetic Operators Operator - can be used as a prefix unary operator to change sign of a signed value.
mikroPascal PRO for dsPIC30/33 and PIC24 Bitwise Operators Use bitwise operators to modify individual bits of numerical operands. Bitwise operators associate from left to right. The only exception is the bitwise complement operator not which associates from right to left.
mikoPascal PRO for dsPIC30/33 and PIC24 Unsigned and Conversions If a number is converted from less complex to more complex data type, the upper bytes are filled with zeroes. If a number is converted from more complex to less complex data type, the data is simply truncated (the upper bytes are lost). For example: var ...
mikroPascal PRO for dsPIC30/33 and PIC24 With shift right (shr), right most bits are discarded, and the “freed” bits on the left are assigned zeroes (in case of unsigned operand) or the value of the sign bit (in case of signed operand). Shifting operand to the right by n positions is equivalent to dividing it by 2n. Boolean Operators Although mikroPascal PRO for dsPIC30/33 and PIC24 does not support boolean type, you have Boolean operators at your disposal for building complex conditional expressions.
mikoPascal PRO for dsPIC30/33 and PIC24 Address and Indirection Operator In the mikroPascal PRO for dsPIC30/33 and PIC24, address of an object in memory can be obtained by means of an unary operator @. To reach the pointed object, we use an indirection operator ^ on a pointer. See Pointers section for more details.
mikroPascal PRO for dsPIC30/33 and PIC24 If the operand is a parameter declared as array type or function type, sizeof gives the size of the pointer. When applied to records, sizeof gives the total number of bytes, including any padding. The operator sizeof cannot be applied to a function. 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.
mikroPascal 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: dword; b: 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 If Statement Use the keyword if to implement a conditional statement. The syntax of the if statement has the following form: if expression then statement1 [else statement2] If expression evaluates to true then statement1 executes. If expression is false then statement2 executes. The expression must convert to a boolean type; otherwise, the condition is ill-formed. The else keyword with an alternate statement (statement2) is optional.
mikroPascal PRO for dsPIC30/33 and PIC24 selector is an expression which should evaluate as integral value. values can be literals, constants, or expressions, and statements can be any statements. The else clause is optional. If using the else branch, note that there should never be a semicolon before the keyword else. First, the selector expression (condition) is evaluated. Afterwards the case statement compares it against all available values.
mikoPascal PRO for dsPIC30/33 and PIC24 Iteration Statements Iteration statements let you loop a set of statements. There are three forms of iteration statements in mikroPascal PRO for dsPIC30/33 and PIC24: - for - while...do - do You can use the statements break and continue to control the flow of a loop statement. break terminates the statement in which it occurs, while continue begins executing the next iteration of the sequence.
mikroPascal PRO for dsPIC30/33 and PIC24 While Statement Use the while keyword to conditionally iterate a statement. The syntax of the while statement is: while expression do statement statement is executed repeatedly as long as expression evaluates true. The test takes place before the statement is executed. Thus, if expression evaluates false on the first pass, the loop does not execute.
mikroPascal PRO for dsPIC30/33 and PIC24 Jump Statements The jump statement, when executed, transfers control unconditionally. There are four such statements in mikroPascal PRO for dsPIC30/33 and PIC24: - break - continue - exit - goto 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 repeat block).
mikoPascal 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: procedure Proc1(); var error: byte; begin ... // we’re doing something here if error = TRUE then exit; ...
mikoPascal PRO for dsPIC30/33 and PIC24 asm Statement mikroPascal 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).
mikroPascal 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 c
mikroPascal PRO for dsPIC30/33 and PIC24 begin x_center := 50; y_center := 60; radius := 10; end; end. Directives Directives are words of special significance which provide additional functionality regarding compilation and output. The following directives are at your disposal: - Compiler directives for conditional compilation, - Linker directives for object distribution in memory.
mikoPascal PRO for dsPIC30/33 and PIC24 Directives #IFDEF and #IFNDEF are terminated with the #ENDIF directive and can have an optional #ELSE clause: {$IFDEF flag} {$ELSE} {$ENDIF} First, #IFDEF checks if flag is defined by means of #DEFINE. If so, only will be compiled. Otherwise, will be compiled. #ENDIF ends the conditional sequence.
mikroPascal PRO for dsPIC30/33 and PIC24 Linker Directives mikroPascal PRO for dsPIC30/33 and PIC24 uses an internal algorithm to distribute objects within memory. If you need to have a variable, constant or a 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.
mikoPascal PRO for dsPIC30/33 and PIC24 To place a routine on a specific address in Flash memory you should write the following: procedure proc(par : byte); org 0x200; begin // Procedure will start at address 0x200; ... end; org directive can be used with main routine too. For example: program Led_Blinking; begin 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.
mikroPascal PRO for dsPIC30/33 and PIC24 CHAPTER 9 mikroPascal PRO for dsPIC30/33 and PIC24 Libraries mikroPascal 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 mikroPascal PRO for dsPIC30/33 and PIC24 Libraries in you project.
mikoPascal 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
mikroPascal 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.
mikoPascal 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
mikroPascal PRO for dsPIC30/33 and PIC24 Library Routines - ADCx_Init - ADCx_Init_Advanced - ADCx_Get_Sample - ADCx_Read - ADC_Set_Active ADCx_Init Prototype procedure ADCx_Init(); Description This routines configures ADC module to work with default settings.
mikoPascal PRO for dsPIC30/33 and PIC24 ADCx_Init_Advanced Prototype // dsPIC30F and PIC24FJ prototype procedure ADC1_Init_Advanced(Reference : word); // dsPIC33FJ and PIC24HJ prototype procedure ADCx_Init_Advanced(ADCMode : word; Reference : word); 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.
mikroPascal PRO for dsPIC30/33 and PIC24 ADCx_Get_Sample Prototype function ADCx_Get_Sample(channel : word) : 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 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.
mikoPascal PRO for dsPIC30/33 and PIC24 ADC_Set_Active Prototype procedure ADC_Set_Active(adc_gs : ^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.
mikroPascal PRO for dsPIC30/33 and PIC24 HW Connection ADC HW connection 245 MikroElektronika
mikoPascal PRO for dsPIC30/33 and PIC24 CAN Library mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 CANxSetOperationMode Prototype procedure CANxSetOperationMode(mode, WAIT : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CANxInitialize Prototype procedure CANxInitialize(SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CAN_CONFIG_ FLAGS : word); Description Initializes the CAN module.
mikroPascal PRO for dsPIC30/33 and PIC24 CANxSetBaudRate Prototype procedure CANxSetBaudRate(SJW, BRP, PHSEG1, PHSEG2, PROPSEG, CAN_CONFIG_ FLAGS : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CANxSetMask Prototype procedure CANxSetMask(CAN_MASK : word; val : longint; CAN_CONFIG_FLAGS : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 CANxSetFilter Prototype procedure CANxSetFilter(CAN_FILTER : word; val : longint; CAN_CONFIG_FLAGS : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CANxRead Prototype function CANxRead(var id : longint; var data : array[1] of byte; dataLen, CAN_RX_MSG_FLAGS : word) : 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 - Message flags are
mikroPascal PRO for dsPIC30/33 and PIC24 CANxWrite Prototype function CANxWrite(id : longint; var data_ : array[1] of byte; dataLen, CAN_TX_MSG_FLAGS : word) : 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..8 - CAN_RX_MSG_FLAGS: message flags.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 _CAN_CONFIG_MATCH_TYPE_BIT _CAN_CONFIG_ALL_VALID_MSG _CAN_CONFIG_MATCH_MSG_TYPE : word = 0x20; : word = 0xDF; : 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; ...
mikoPascal 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.
mikroPascal 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 : : : : : : word word word word word word = = = = = = 0; 1; 2; 3; 4; 5; Library Example The example demonstrates CAN protocol.
mikoPascal 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
mikroPascal PRO for dsPIC30/33 and PIC24 Can_Rcv_Flags := 0; 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
mikoPascal PRO for dsPIC30/33 and PIC24 HW Connection Example of interfacing CAN transceiver with MCU and CAN bus MikroElektronika 260
mikroPascal PRO for dsPIC30/33 and PIC24 CANSPI Library The SPI module is available with a number of the dsPIC30/33 and PIC24 MCUs. The mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 External dependencies of CANSPI Library The following variables must be defined Description: in all projects using CANSPI Library: Example: var CanSpi_CS external; : sbit; sfr; Chip Select line. var CanSpi_CS : sbit at LATF0_bit; : sbit; sfr; Reset line. var CanSpi_Rst bit; var CanSpi_Rst external; var CanSpi_CS_Direction : sbit; sfr; external; var CanSpi_Rst_Direction : sbit; sfr; external; Direction of the Chip Select pin. Direction of the Reset pin.
mikroPascal PRO for dsPIC30/33 and PIC24 CANSPIGetOperationMode Prototype function CANSPIGetOperationMode() : 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 CANSPISetBaudRate Prototype procedure CANSPISetBaudRate(SJW, CONFIG_FLAGS : char); Returns Nothing. BRP, PHSEG1, PHSEG2, PROPSEG, CANSPI_ 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CANSPISetMask Prototype procedure CANSPISetMask(CANSPI_MASK : byte; val : longint; CANSPI_CONFIG_ FLAGS : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 CANSPISetFilter Prototype procedure CANSPISetFilter(CAN_FILTER : as byte, val : longint, 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CANSPIRead Prototype function CANSPIRead(var id : longint; var Data_ : array[8] of byte; var DataLen: byte; var CAN_RX_MSG_FLAGS : byte) : byte; Description If at least one full Receive Buffer is found, it will be processed in the following way: - Message ID is retrieved and stored to location provided by the id parameter - Message data is retrieved and stored to a buffer provided by the data parameter - Message length is retrieved and stored to location provided by
mikroPascal PRO for dsPIC30/33 and PIC24 CANSPIWrite Prototype function CANSPIWrite(id : longint; var Data_ : array[8] of byte; DataLen, CANSPI_TX_MSG_FLAGS : byte) : 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..
mikoPascal 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 : : : : : : 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.
mikroPascal 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 and _CANSPI_CONFIG_PHSEG2_PRG_ON and _CANSPI_CONFIG_STD_MSG and _CANSPI_CONFIG_DBL_BUFFER_ON and _CANSPI_CONFIG_VALID_XTD_MSG and _CANSPI_CONFIG_LINE_FILTER_OFF; ...
mikoPascal 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 : : : : : : : byte byte byte byte byte byte byte = = = = = = = $07; $00; $01; $02; $03; $04; $05; // Use this to access filter bits : : : : : byte byte byte byte byte = = = =
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 CANSPISetFilter(_CANSPI_FILTER_B2_F4,ID_2nd,_CANSPI_CONFIG_XTD_MSG);// set id of filter B2_F4 to 2nd node ID CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF); // set NORMAL mode // Set initial data to be sent RxTx_Data[0] := 9; CANSPIWrite(ID_1st, RxTx_Data, 1, Can_Send_Flags); // send initial message while (TRUE) do begin // 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
mikroPascal 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_
mikoPascal PRO for dsPIC30/33 and PIC24 HW Connection Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface MikroElektronika 276
mikroPascal 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.
mikoPascal 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: var CF_Data_Port external; var CF_RDY external; : : byte; sbit; sfr; Compact Flash Data Port. var CF_Data_Port : byte at PORTD; sfr; Ready signal line. var CF_RDY : sbit at RB7_bit; Write Enable signal line.
mikroPascal 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
mikoPascal PRO for dsPIC30/33 and PIC24 Cf_Init Prototype procedure Cf_Init(); Description Initializes ports appropriately for communication with CF card. Parameters None. Returns Nothing.
mikroPascal PRO for dsPIC30/33 and PIC24 Cf_Detect Prototype function CF_Detect() : 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) do nop; dsPIC30 family MCU and CF card voltage levels are different.
mikoPascal PRO for dsPIC30/33 and PIC24 Cf_Read_Init Prototype procedure Cf_Read_Init(address : dword; sectcnt : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Cf_Write_Byte Prototype procedure Cf_Write_Byte(data_ : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Cf_Fat_Init Prototype function Cf_Fat_Init(): 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 begin ... end None.
mikroPascal PRO for dsPIC30/33 and PIC24 Cf_Fat_Assign Prototype function Cf_Fat_Assign(var filename: array[12] of char; file_cre_attr: byte): 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Cf_Fat_Reset Prototype procedure Cf_Fat_Reset(var size: dword); 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 var size : dword; ...
mikroPascal PRO for dsPIC30/33 and PIC24 Cf_Fat_Rewrite Prototype 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Cf_Fat_Write Prototype procedure Cf_Fat_Write(var fdata: array[512] of byte; data_len: 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Cf_Fat_Get_File_Date Prototype procedure Cf_Fat_Get_File_Date(var year: word; var month: byte; var day: byte; var hours: byte; var mins: 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. Upon function execution month attribute is returned through this parameter.
mikoPascal PRO for dsPIC30/33 and PIC24 Cf_Fat_Get_File_Size Prototype function Cf_Fat_Get_File_Size(): dword; 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 var my_file_size : dword; ... my_file_size := Cf_Fat_Get_File_Size(); Notes None.
mikroPascal PRO for dsPIC30/33 and PIC24 Parameters Returns Requires Example Notes 291 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 // UART write text and new line (carriage return + line feed) procedure UART1_Write_Line( var uart_text : string ); begin UART1_Write_Text(uart_text); UART1_Write(13); UART1_Write(10); end; //-------------- Creates new file and writes some procedure M_Create_New_File(); begin filename[7] := ‘A’; Cf_Fat_Set_File_Date(2005,6,21,10,35,0); // Cf_Fat_Assign(filename, 0xA0); // Cf_Fat_Rewrite(); // for loop:=1 to 90 do // begin UART1_Write(‘.
mikoPascal PRO for dsPIC30/33 and PIC24 end; file_contents[0] := byte(loop div 10 + 48); file_contents[1] := byte(loop mod 10 + 48); Cf_Fat_Write(file_contents, LINE_LEN-1); end; // write data to the assigned file //-------------- Opens an existing file and appends data to it // (and alters the date/time stamp) procedure M_Open_File_Append(); begin 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’; /
mikroPascal PRO for dsPIC30/33 and PIC24 // filename[7] := ‘F’; // uncomment this line to search for file that DOES NOT exist if Cf_Fat_Assign(filename, 0) <> 0 then begin //--- file has been found - get its date Cf_Fat_Get_File_Date(year,month,day,hour,minute); UART1_Write_Text(‘ created: ‘); 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(mi
mikoPascal PRO for dsPIC30/33 and PIC24 if (size <> 0) then begin LongIntToStr(size, err_txt); UART1_Write_Line(err_txt); for i:=0 to 4999 do begin Cf_Write_Sector(size, Buffer); Inc(size); UART1_Write(‘.’); end; end; end; //-------------- Main.
mikroPascal PRO for dsPIC30/33 and PIC24 HW Connection Pin diagram of CF memory card 297 MikroElektronika
mikoPascal PRO for dsPIC30/33 and PIC24 ECAN Library mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 ECANxDmaChannelInit Prototype function ECANxDmaChannelInit(DmaChannel DmaRamBuffAdd : word) : word; : word; ChannelDir : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 ECANxGetOperationMode Prototype function ECANxGetOperationMode() : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 ECANxInitialize Prototype procedure ECANxInitialize(SJW, BRP, PHSEG1, PHSEG2, PROPSEG, ECAN_CONFIG_ FLAGS : word); Description Initializes the ECAN module.
mikoPascal PRO for dsPIC30/33 and PIC24 ECANxSelectTxBuffers Prototype function ECANxSelectTxBuffers(txselect : word) : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 ECANxFilterEnable Prototype procedure ECANxFilterEnable(flten : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 ECANxSetBaudRate Prototype procedure ECANxSetBaudRate(SJW, BRP, PHSEG1, PHSEG2, PROPSEG, ECAN_CONFIG_ FLAGS : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 ECANxSetMask Prototype procedure ECANxSetMask(ECAN_MASK : word; val : longint; ECAN_CONFIG_FLAGS : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 ECANxSetFilter Prototype procedure ECANxSetFilter(ECAN_FILTER : word; val : longint; ECAN_FILTER_ MASK : word; ECAN_FILTER_RXBUFF : word; ECAN_CONFIG_FLAGS : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 ECANxRead Prototype function ECANxRead(var id : longint; var data: array[8] of byte; var dataLen : word; var ECAN_RX_MSG_FLAGS : word) : 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 location pointed by the dataLe
mikoPascal PRO for dsPIC30/33 and PIC24 ECANxWrite Prototype function ECANxWrite(id : longint; var Data : array[8] of byte; DataLen, ECAN_TX_MSG_FLAGS : word) : 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..
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 You may use bitwise and to form config word out of these values. 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.
mikroPascal 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 : : : : : : : : : : : : : : : : : word word word word word word word word word word word word word word word word word = = = = = = = = = = = = = =
mikoPascal 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 : : : : : : : : : : : : : : : : 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;
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 IFS3 := 0; IFS4 := 0; {* Enable ECAN1 Interrupt *} IEC2.C1IE := 1; C1INTE.TBIE := 1; C1INTE.
mikroPascal PRO for dsPIC30/33 and PIC24 while TRUE do // endless loop begin 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 begin 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; end; end.
mikoPascal PRO for dsPIC30/33 and PIC24 {* Clear Interrupt Flags *} IFS0 IFS1 IFS2 IFS3 IFS4 := := := := := 0; 0; 0; 0; 0; {* Enable ECAN1 Interrupt *} IEC2.C1IE := 1; C1INTE.TBIE := 1; C1INTE.
mikroPascal PRO for dsPIC30/33 and PIC24 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 begin 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; end; end.
mikoPascal PRO for dsPIC30/33 and PIC24 EEPROM_Erase Prototype procedure EEPROM_Erase(address : 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 var eeAddr : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 EEPROM_Write Prototype procedure EEPROM_Write(address : longint; data_ : 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 var wrAddr : longint; eeData : word; ... eeData := 0xAAAA; wrAddr := 0x7FFC30; EEPROM_Write(wrAddr, eeData); Notes Specified memory location will be erased before writing starts.
mikoPascal PRO for dsPIC30/33 and PIC24 begin ADPCFG := 0xFFFF; // Disable analog inputs TRISB := 0; LATB := 0xFFFF; eeAddr := 0x7FFC00; eeData := 0; // PORTB as output while (eeData <= 0x00FF) do begin Eeprom_Write(eeAddr, eeData); Inc(eeData); while (WR_bit) do ; 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Epson S1D13700 Graphic Lcd Library The mikroPascal 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.
mikoPascal 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_Roun
mikroPascal PRO for dsPIC30/33 and PIC24 S1D13700_Init Prototype procedure S1D13700_Init(width : word; height : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 S1D13700_Write_Command Prototype procedure S1D13700_Write_Command(command : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 S1D13700_Write_Parameter Prototype procedure S1D13700_Write_Parameter(parameter : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 S1D13700_GrFill Prototype procedure S1D13700_GrFill(d : 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 procedure S1D13700_TxtFill(d : byte); Returns Nothing.
mikroPascal PRO for dsPIC30/33 and PIC24 S1D13700_Display_TxtLayer Prototype procedure S1D13700_Display_TxtLayer(mode : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 S1D13700_Display_Cursor Prototype procedure S1D13700_Display_Cursor(mode : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 S1D13700_Write_Text Prototype procedure S1D13700_Write_Text(var str : string; x, y : word; mode : byte); Returns 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.
mikoPascal PRO for dsPIC30/33 and PIC24 S1D13700_Line Prototype procedure S1D13700_Line(x0, y0, x1, y1 : word; pcolor : byte); Returns 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.
mikroPascal PRO for dsPIC30/33 and PIC24 S1D13700_V_Line Prototype procedure S1D13700_V_Line(y_start, y_end, x_pos : word; color : byte); Returns 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.
mikoPascal PRO for dsPIC30/33 and PIC24 S1D13700_Box Prototype procedure S1D13700_Box(x0, y0, x1, y1 : word; pcolor : byte); Returns Nothing. Description Draws a rectangle on Glcd. Parameters: - x0: x coordinate of the upper left rectangle corner. - y0: y coordinate of the upper left rectangle corner. - x1: x coordinate of the lower right rectangle corner. - y1: y coordinate of the lower right rectangle corner. - pcolor: color parameter. Valid values: Value Description S1D13700_BLACK Black color.
mikroPascal PRO for dsPIC30/33 and PIC24 S1D13700_Rectangle_Round_Edges_Fill Prototype procedure S1D13700_Rectangle_Round_Edges_Fill(x_upper_left : word; y_upper_ left : word; x_bottom_right : word; y_bottom_right : word; round_radius : word; color : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 S1D13700_Circle_Fill Prototype Returns procedure S1D13700_Circle_Fill(x_center: word; color : byte); word; y_center: word; radius: 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.
mikroPascal PRO for dsPIC30/33 and PIC24 S1D13700_PartialImage Prototype procedure S1D13700_PartialImage(x_left, y_top, width, width, picture_height : word; const image : ^byte); Returns Nothing. height, picture_ 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.
mikoPascal 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”.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 dsPIC30 Functions FLASH_Erase32 Prototype procedure FLASH_Erase32(flash_address : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 FLASH_Write_Compact Prototype procedure FLASH_Write_Compact(flash_address : longint; data_address : word; bytes : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 FLASH_Write_Loadlatch4 Prototype 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.
mikroPascal PRO for dsPIC30/33 and PIC24 FLASH_Write_Loadlatch4_Compact Prototype procedure 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.
mikoPascal PRO for dsPIC30/33 and PIC24 FLASH_Write_DoWrite Prototype 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.
mikroPascal PRO for dsPIC30/33 and PIC24 FLASH_Read4_Compact Prototype procedure FLASH_Read4_Compact(flash_address : longint; write_to : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 FLASH_Write Prototype procedure FLASH_Write(address : longint; var data_ : array[64] of word); 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.
mikroPascal PRO for dsPIC30/33 and PIC24 FLASH_Read Prototype procedure FLASH_Read(address : longint; var write_to : array[100] of word; NoWords : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Copy Code To Clipboard program Flash_Test; var WriteWordArr : array[8] of word; WriteByteArr : array[32] of byte; ReadByteArr : array[40] of byte; ReadWordArr : array[20] of word; pw : ^word; pb : ^byte; i : word; temp_byte : byte; begin // Initialize arrays WriteWordArr[0] := ‘*’; WriteWordArr[1] := ‘m’; WriteWordArr[2] := ‘i’; WriteWordArr[3] := ‘k’; WriteWordArr[4] := ‘r’; WriteWordArr[5] := ‘o’; WriteWordArr[6] := ‘E’; WriteWordArr[7] := ‘*’; WriteByteArr[0] := ‘m
mikroPascal PRO for dsPIC30/33 and PIC24 FLASH_Read4_Compact(0x006010, pb); pb := pb + 12; pb^ := 0; //termination UART1_Init(9600); UART1_Write(10); UART1_Write(13); UART1_Write_Text(‘Start’); UART1_Write(10); UART1_Write(13); i := 0; while(ReadByteArr[i]) do begin temp_byte := ReadByteArr[i]; UART1_Write(temp_byte); Inc(i); end; //--- now for some non-compact flash-write pw := @WriteWordArr; //--- erase the block first FLASH_Erase32(0x006100); FLASH_Write_Init(0x006100, pw); FLASH_Write_Loadlatch4(); FLAS
mikoPascal 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: var GLCD_D0 : sbit; sfr; external; Data 0 line.
mikroPascal 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 procedure Glcd_Init(); Descripti
mikoPascal 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 -
mikroPascal PRO for dsPIC30/33 and PIC24 Glcd_Set_Side Prototype procedure Glcd_Set_Side(x_pos: 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Glcd_Read_Data Prototype function Glcd_Read_Data() : 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 var data_ : byte; ...
mikroPascal PRO for dsPIC30/33 and PIC24 Glcd_Fill Prototype procedure Glcd_Fill(pattern: 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 // Clear screen Glcd_Fill(0); Notes None.
mikoPascal PRO for dsPIC30/33 and PIC24 Glcd_V_Line Prototype procedure Glcd_V_Line(y_start, y_end, x_pos, color: byte); Description Draws a vertical line on Glcd. Parameters - y_start: y coordinate of the line start. Valid values: 0..63 - y_end: y coordinate of the line end. Valid values: 0..63 - x_pos: x coordinate of vertical line. Valid values: 0..127 - color: color parameter. Valid values: 0..2 Returns The parameter color determines the line color: 0 white, 1 black, and 2 inverts each dot. Nothing.
mikroPascal PRO for dsPIC30/33 and PIC24 Glcd_Rectangle Prototype procedure Glcd_Rectangle(x_upper_left, bottom_right, color: byte); y_upper_left, x_bottom_right, y_ 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..
mikoPascal PRO for dsPIC30/33 and PIC24 Glcd_Rectangle_Round_Edges_Fill Prototype procedure Glcd_Rectangle_Round_Edges_Fill(x_upper_left: byte; y_upper_left: byte; x_bottom_right: byte; y_bottom_right: byte; radius: byte; color: byte); Description Draws a filled rounded edge rectangle on Glcd with color. Parameters - x_upper_left: x coordinate of the upper left rectangle corner. Valid values: 0..127 - y_upper_left: y coordinate of the upper left rectangle corner. Valid values: 0..
mikroPascal PRO for dsPIC30/33 and PIC24 Glcd_Circle Prototype procedure Glcd_Circle(x_center, y_center, radius: integer; color: 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..2 Returns The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot. Nothing.
mikoPascal PRO for dsPIC30/33 and PIC24 Glcd_Set_Font Prototype procedure Glcd_Set_Font(const activeFont: ^byte; aFontWidth, aFontHeight : byte; aFontOffs : byte); 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Glcd_Write_Char Prototype procedure Glcd_Write_Char(character, x_pos, page_num, color : 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..
mikoPascal PRO for dsPIC30/33 and PIC24 Glcd_Image Prototype procedure Glcd_Image(const image: ^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 mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Library Example The following drawing demo tests advanced routines of the Glcd library.
mikoPascal PRO for dsPIC30/33 and PIC24 ADPCFG := 0xFFFF; // Configure AN pins as digital Glcd_Init(); Glcd_Fill(0x00); // Initialize GLCD // Clear GLCD while TRUE do begin {$IFDEF COMPLETE_EXAMPLE} Glcd_Image(@truck_bmp); Delay2S(); delay2S(); {$ENDIF} // Draw image Glcd_Fill(0x00); // Clear GLCD Glcd_Box(62,40,124,63,1); Glcd_Rectangle(5,5,84,35,1); Glcd_Line(0, 0, 127, 63, 1); Delay2S(); counter := 5; // Draw box // Draw rectangle // Draw line while (counter <= 59) do begin Delay_ms(250); Glcd_
mikroPascal PRO for dsPIC30/33 and PIC24 someText := ‘5x7 Font’; Glcd_Write_Text(someText, 5, 4, 2); delay2S(); end.
mikoPascal 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 mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 I2Cx_Start Prototype 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.
mikoPascal PRO for dsPIC30/33 and PIC24 I2Cx_Is_Idle Prototype function I2Cx_Is_Idle() : 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 var data_ : byte; ... if !(I2C1_Is_Idle) I2C1_Write(data_); ...
mikroPascal PRO for dsPIC30/33 and PIC24 I2Cx_Write Prototype function I2Cx_Write(data_ : byte) : 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Keypad Library mikroPascal 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: var keypadPort : word; sfr; external; Keypad Port.
mikoPascal PRO for dsPIC30/33 and PIC24 Keypad_Key_Press Prototype function Keypad_Key_Press(): 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 var kp : word; ...
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 end; UART1_Write_Text(‘Key pressed: ‘); UART1_Write(kp); UART1_Write(10); UART1_Write(13); end; // Send value of pressed button to UART end.
mikroPascal PRO for dsPIC30/33 and PIC24 Lcd Library mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Lcd_Init Prototype procedure Lcd_Init(); Description Initializes Lcd module. Parameters None. Returns Nothing.
mikroPascal PRO for dsPIC30/33 and PIC24 Lcd_Out Prototype procedure Lcd_Out(row, column: word; var text: 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Lcd_Chr_Cp Prototype procedure Lcd_Chr_Cp(out_char: 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.
mikroPascal 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 var LCD_RS : sbit at LATD0_bit; var LCD_EN : sbit at LATD1_bit; var LCD_D4 : sbit at LATB0_bit; var LCD_D5 : sbit at LATB1_bit; var LCD_D6 : sbit at LATB2_bit; var LCD_D7 : sbit at LATB3_bit; var LCD_RS_Direction : sbit at var LCD_EN_Direction : sbit at var LCD_D4_Direction : sbit at var LCD_D5_Direction : sbit at var
mikoPascal PRO for dsPIC30/33 and PIC24 // Moving text for i:=0 to 3 do begin Lcd_Cmd(_LCD_SHIFT_RIGHT); Move_Delay(); end; // Move text to the right 4 times while TRUE do begin for i:=0 to 6 do begin Lcd_Cmd(_LCD_SHIFT_LEFT); Move_Delay(); end; // Endless loop // Move text to the left 7 times for i:=0 to 6 do // Move text to the right 7 times begin Lcd_Cmd(_LCD_SHIFT_RIGHT); Move_Delay(); end; end; end.
mikroPascal PRO for dsPIC30/33 and PIC24 Manchester Code Library The mikroPascal PRO for dsPIC30/33 and PIC24 provides a library for handling Manchester coded signals.
mikoPascal 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 function Man_Receive_Init() : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Man_Receive Prototype function Man_Receive(var error : word) : 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 Notes var data_, error : word; ...
mikoPascal PRO for dsPIC30/33 and PIC24 Man_Send Prototype procedure Man_Send(tr_data : 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 var msg : byte; ... Man_Send(msg); Notes Baud rate used is 500 bps. Man_Synchro Prototype function Man_Synchro(): word; Description Measures half of the manchester bit length with 10us resolution. Parameters None.
mikroPascal PRO for dsPIC30/33 and PIC24 Man_Break Prototype 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.
mikoPascal 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 var LCD_RS : sbit at LATD0_bit; LCD_EN : sbit at LATD1_bit; LCD_D4 : sbit at LATB0_bit; LCD_D5 : sbit at LATB1_bit; LCD_D6 : sbit at LATB2_bit; LCD_D7 : sbit at LATB3_bit; var LCD_RS_Direction : sbit at LCD_EN_Direction : sbit at LCD_D4_Direction : sbit at LC
mikroPascal PRO for dsPIC30/33 and PIC24 end; repeat begin byte_rcvd := Man_Receive(error); // Attempt byte receive if (error <> 0) then // If error occured begin Lcd_Chr_CP(‘?’); // Write question mark on LCD Inc(ErrorCount); // Update error counter if (ErrorCount > 20) then // In case of multiple errors begin Man_Synchro(); // Try to synchronize again //Man_Receive_Init(); // Alternative, try to Initialize Receiver again ErrorCount := 0; // Reset error counter end; end end.
mikoPascal PRO for dsPIC30/33 and PIC24 begin Man_Send(0x0B); Delay_ms(100); end.
mikroPascal 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. mikroPascal PRO for dsPIC30/33 and PIC24 provides a library for accessing data on Multi Media Card via SPI communication.
mikoPascal 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: var Mmc_Chip_Select : sbit; sfr; external; Chip select pin. var Mmc_Chip_Select : sbit at LATF0_ bit; var Mmc_Chip_Select_Direction : sbit; sfr; external; Direction of the chip select pin.
mikroPascal PRO for dsPIC30/33 and PIC24 Mmc_Init Prototype function Mmc_Init(): 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Mmc_Read_Sector Prototype function Mmc_Read_Sector(sector: dword; var dbuff: array[512] of byte): 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Mmc_Read_Cid Prototype function Mmc_Read_Cid(var data_cid: array[16] of byte): word; 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 var error : word; dataBuffer : array[16] of byte; ...
mikoPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_Init Prototype function Mmc_Fat_Init(): word; Description Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by the library. Parameters None.
mikroPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_QuickFormat Prototype function Mmc_Fat_QuickFormat(var mmc_fat_label : string[11]) : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_Assign Prototype function Mmc_Fat_Assign(var filename: array[12] of char; file_cre_attr: byte): 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_Reset Prototype procedure Mmc_Fat_Reset(var size: dword); 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_Rewrite Prototype 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_Write Prototype procedure Mmc_Fat_Write(var fdata: array[512] of byte; data_len: 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_Get_File_Date Prototype procedure Mmc_Fat_Get_File_Date(var year: word; var month: byte; var day: byte; var hours: byte; var mins: 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. Upon function execution month attribute is returned through this parameter.
mikroPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_Get_File_Date_Modified Prototype procedure Mmc_Fat_Get_File_Date_Modified(var year: word; var month: byte; var day: byte; var hours: byte; var mins: 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. Upon function execution year attribute is returned through this parameter.
mikoPascal PRO for dsPIC30/33 and PIC24 Mmc_Fat_Get_Swap_File Prototype function Mmc_Fat_Get_Swap_File(sectors_cnt: dword; var filename : string[11]; file_attr : byte) : dword; 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Example Notes //-------------- Try to create a swap file with archive atribute, whose size will be at least 1000 sectors. // If it succeeds, it sends No. of start sector over UART var size : dword; ... size := Mmc_Fat_Get_Swap_File(1000, ‘mikroE.txt’, 0x20); if (size <> 0) then begin UART1_Write(0xAA); UART1_Write(Lo(size)); UART1_Write(Hi(size)); UART1_Write(Higher(size)); UART1_Write(Highest(size)); UART1_Write(0xAA); end; Long File Names (LFN) are not supported.
mikoPascal PRO for dsPIC30/33 and PIC24 buffer : array[512] of byte; // UART write text and new line (carriage return + line feed) procedure UART_Write_Line( var uart_text : string ); begin UART1_Write_Text(uart_text); UART1_Write(13); UART1_Write(10); end; //-------------- Creates new file and writes some procedure M_Create_New_File(); begin filename[7] := ‘A’; // Mmc_Fat_Set_File_Date(2005,6,21,10,35,0); // Mmc_Fat_Assign(filename, 0xA0); // Mmc_Fat_Rewrite; // for loop:=1 to 99 do // begin UART1_Write(‘.
mikroPascal PRO for dsPIC30/33 and PIC24 end; //-------------- Opens an existing file and appends data to it // (and alters the date/time stamp) procedure M_Open_File_Append(); begin filename[7] := ‘B’; Mmc_Fat_Assign(filename, 0); Mmc_Fat_Set_File_Date(2009, 1, 23, 17, 22, 0); Mmc_Fat_Append(); // Prepare file for append file_contents := ‘ for mikroElektronika 2007’; // Prepare file for append file_contents[26] := 10; // LF Mmc_Fat_Write(file_contents, 27); // Write data to assigned file end; //-----------
mikoPascal PRO for dsPIC30/33 and PIC24 UART1_Write_Text(outstr); WordToStr(hour, outstr); UART1_Write_Text(outstr); WordToStr(minute, outstr); UART1_Write_Text(outstr); //--- file has been found - get its modified date Mmc_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(
mikroPascal PRO for dsPIC30/33 and PIC24 //-------------- Main.
mikoPascal PRO for dsPIC30/33 and PIC24 HW Connection Pin diagram of MMC memory card MikroElektronika 406
mikoPascal PRO for dsPIC30/33 and PIC24 OneWire Library The OneWire library provides routines for communication via the Dallas OneWire protocol, for example with DS18x20 digital thermometer. OneWire is a Master/Slave protocol, and all communication cabling required is a single wire. OneWire enabled devices should have open collector drivers (with single pull-up resistor) on the shared data line. Slave devices on the OneWire bus can even get their power supply from data line.
mikroPascal PRO for dsPIC30/33 and PIC24 Ow_Read Prototype function Ow_Read(var port : word; pin : word): 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 var read_data : byte; ... read_data := Ow_Read(PORTF, 6); Notes None.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 else text[0] := ‘0’; 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 shl (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_frac
mikoPascal PRO for dsPIC30/33 and PIC24 HW Connection Example of DS1820 connection MikroElektronika 411
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 PPS_Mapping Prototype function PPS_Mapping (rp_num, input_output, funct_name : byte) : word; 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.
mikroPascal 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 T
mikoPascal 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
mikroPascal PRO for dsPIC30/33 and PIC24 Port Expander Library mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Expander_Init Prototype procedure Expander_Init(ModuleAddress : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Expander_Init_Advanced Prototype procedure Expander_Init_Advanced(var rstPort : byte; rstPin : byte; haen : byte); 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Expander_Write_Byte Prototype procedure Expander_Write_Byte(ModuleAddress, RegAddress, Data : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Expander_Read_PortB Prototype function Expander_Read_PortB(ModuleAddress : byte) : byte; Description The function reads byte from Port Expander’s PortB. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page Returns Byte read. Requires Port Expander must be initialized. See Expander_Init. Port Expander’s PortB should be configured as input. See Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines.
mikoPascal PRO for dsPIC30/33 and PIC24 Expander_Write_PortA Prototype procedure Expander_Write_PortA(ModuleAddress, Data : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Expander_Write_PortAB Prototype procedure Expander_Write_PortAB(ModuleAddress : byte; Data : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Expander_Set_DirectionPortB Prototype procedure Expander_Set_DirectionPortB(ModuleAddress, Data : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Expander_Set_PullUpsPortB Prototype procedure Expander_Set_PullUpsPortB(ModuleAddress, Data : 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 HW Connection Port Expander HW connection 426 MikroElektronika
mikoPascal PRO for dsPIC30/33 and PIC24 PS/2 Library The mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Ps2_Config Prototype 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.
mikoPascal 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 429
mikroPascal 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.
mikoPascal 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. mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 PWM_Init Prototype function PWM_Init(freq_hz : longint; enable_channel_x, timer_prescale, use_ timer_x : word) : word; // 30F1010 and dsPIC33FJ06GS101/102/202 prototype function PWM_Init(freq_hz : longint; enable_channel_x, timer_prescale) : word; Description Initializes the PWM module with duty ratio 0.
mikoPascal PRO for dsPIC30/33 and PIC24 PWM_Start Prototype procedure PWM_Start(enable_channel_x : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 PWM_Start(1); PWM_Start(2); PWM_Set_Duty(current_duty, 1); PWM_Set_Duty(current_duty1, 2); // Set current duty for PWM1 // Set current duty for PWM2 while (TRUE) do begin if RB0_bit = 1 then begin Delay_ms(20); Inc(current_duty); if (current_duty > pwm_period1) then then possible pwm_period1 value current_duty := 0; PWM_Set_Duty(current_duty, end; 1); // endless loop // button on RB0 pressed // increment current_duty // if we increase current_duty greater // rese
mikoPascal 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. mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 PWMx_Mc_Init Prototype function PWMx_Mc_Init(freq_hz, pair_output_mode, enable_output_x, clock_ prescale_output_postscale : word) : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 PWMx_Mc_Set_Duty Prototype procedure PWM1_Mc_Set_Duty(duty, channel : word); // For dsPIC 33FJ MCUs that have PWM2 module : procedure PWM2_Mc_Set_Duty(duty : 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. Requires The dsPIC30/33 MCU must have the Motor Control PWM module.
mikroPascal PRO for dsPIC30/33 and PIC24 PWMx_Mc_Stop Prototype 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.
mikoPascal PRO for dsPIC30/33 and PIC24 if (RB1_bit) then // Button on RB1 pressed begin Delay_ms(20); Dec(current_duty); // Decrement current_duty if (current_duty > pwm_period) then // If we decrease current_duty greater then possible pwm_period value (overflow) begin current_duty := pwm_period; // set current_duty to max possible value end; PWM1_MC_Set_Duty(current_duty, 1); // Set newly acquired duty ratio end; Delay_ms(5); // Slow down change pace a little end; end.
mikroPascal 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: var RS485_rxtx_pin : sbit; sfr; external; Control RS-485 Transmit/Receive operation mode var RS485_rxtx_pin : sbit at RF2_ bit; var RS485_rxtx_pin_direction sbit; sfr; external; : Direction of the RS-485 Transmit/ Receive pin var RS485_rxtx_pin_direction : sbit at TRISF2_bit; Library Routines - R
mikoPascal PRO for dsPIC30/33 and PIC24 RS485Master_Receive Prototype procedure RS485Master_Receive(var data : array[10] of byte); 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..
mikroPascal PRO for dsPIC30/33 and PIC24 RS485Slave_Init Prototype procedure RS485Slave_Init(slave_address : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 RS485Slave_Receive Prototype procedure RS485Slave_Receive(var data_buffer : array[20] of byte); 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..
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 while (TRUE) do begin Inc(cnt); if (dat[5] <> 0) then PORTD := 0xAA; if (dat[4] <> 0) then begin cnt := 0; dat[4] := 0; j := dat[3]; for i := 1 to dat[3] do PORTB := dat[i-1]; dat[0] := dat[0]+1; Delay_ms(1); RS485Master_Send(dat,1,160); end; // upon completed valid message receiving // data[4] is set to 255 // if an error detected, signal it // by setting portd to 0xAA // if message received successfully // clear message received flag // show data on PORTB // send b
mikroPascal 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) do begin if (dat[5] <> 0) then begin PORTD := 0xAA; dat[5] := 0; end; if (dat[4] <> 0) then
mikoPascal 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 447
mikroPascal 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 const START_BYTE : byte = 0x96; const STOP_BYTE : byte = 0xA9; PACKAGE: -------START_BYTE 0x96 ADDRESS DATALEN [DATA1] [DATA2] [DATA3] CRC STOP_BYTE 0xA9 // 10010110 // 10101001 // if exists // if exists // if exists DATALEN bits -----------bit7 = 1 MASTER SENDS 0 SLAVE SENDS bit6 = 1 ADDRESS WAS XORed 0 ADDRESS UNCHANGED bit5 = 0 FIXED bit4 = 1 DATA3
mikoPascal PRO for dsPIC30/33 and PIC24 Software I²C Library The mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Soft_I2C_Init Prototype 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Soft_I2C_Read Prototype function Soft_I2C_Read(ack : word) : byte; Description Reads one byte from the slave. Parameters - ack: acknowledge signal parameter. If the ack==0 not acknowledge signal will be sent after reading, otherwise the acknowledge signal will be sent. Returns One byte from the Slave. Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine. Also, START signal needs to be issued in order to use this function.
mikroPascal PRO for dsPIC30/33 and PIC24 Soft_I2C_Break Prototype 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.
mikoPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 //-------------------- Formats date and time procedure Transform_Time(); begin seconds := ((seconds and 0xF0) shr 4)*10 + (seconds and 0x0F);// Transform seconds minutes := ((minutes and 0xF0) shr 4)*10 + (minutes and 0x0F);// Transform months hours := ((hours and 0xF0) shr 4)*10 + (hours and 0x0F); // Transform hours year := (day and 0xC0) shr 6; // Transform year day := ((day and 0x30) shr 4)*10 + (day and 0x0F); // Transform day month := ((month and 0x10) shr 4)*1
mikoPascal PRO for dsPIC30/33 and PIC24 Software SPI Library The mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 Soft_SPI_Init Prototype procedure Soft_SPI_Init(); Description Routine initializes the software SPI module. Parameters None. Returns Nothing. Requires Global variables: - SoftSpi_SDI: Data in line - SoftSpi_SDO: Data out line - SoftSpi_CLK: Data clock line - SoftSpi_SDI_Direction: Direction of the Data in pin - SoftSpi_SDO_Direction: Direction of the Data out pin - SoftSpi_CLK_Direction: Direction of the Data clock pin must be defined before using this function.
mikoPascal PRO for dsPIC30/33 and PIC24 Soft_SPI_Write Prototype procedure Soft_SPI_Write(sdata : 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(0xAA); Notes None Library Example This code demonstrates using library routines for Soft_SPI communication.
mikroPascal PRO for dsPIC30/33 and PIC24 begin Chip_Select := 0; // Select DAC chip // Send High Byte temp := word(valueDAC shr 8) and 0x0F; // Store valueDAC[11..8] to temp[3..0] temp := temp or 0x30; // Define DAC setting, see MCP4921 datasheet Soft_SPI_Write(temp); // Send high byte via Soft SPI // Send Low Byte temp := valueDAC; Soft_SPI_Write(temp); Chip_Select := 1; end; // Store valueDAC[7..0] to temp[7..
mikoPascal PRO for dsPIC30/33 and PIC24 Software UART Library The mikroPascal PRO for dsPIC30/33 and PIC24 provides routines for implementing Software UART communication. These routines are hardware independent and can be used with any MCU. The Software UART Library provides easy communication with other devices via the RS232 protocol. Important: The Software UART library implements time-based activities, so interrupts need to be disabled when using it.
mikroPascal PRO for dsPIC30/33 and PIC24 Soft_UART_Read Prototype function Soft_UART_Read(var error : byte) : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Soft_UART_Break Prototype 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.
mikroPascal 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 mikroPascal 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 .
mikoPascal PRO for dsPIC30/33 and PIC24 Sound Library The mikroPascal 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).
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 end; end; begin ADPCFG := 0xFFFF; // Configure AN pins as digital I/O TRISB // Configure RB7..
mikroPascal PRO for dsPIC30/33 and PIC24 HW Connection Example of Sound Library 466 MikroElektronika
mikoPascal PRO for dsPIC30/33 and PIC24 SPI Library The SPI module is available with all dsPIC30/33 and PIC24 MCUs. mikroPascal 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.
mikroPascal PRO for dsPIC30/33 and PIC24 SPIx_Init Prototype 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.
mikoPascal PRO for dsPIC30/33 and PIC24 SPIx_Init_Advanced Prototype procedure SPIx_Init_Advanced(master_mode, mode16, sec_prescaler, prescaler, slave_select, data_sample, clock_idle, edge: word); pri_ 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. The master_mode parameter determines the working mode for SPI module.
mikroPascal 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.
mikoPascal PRO for dsPIC30/33 and PIC24 SPIx_Read Prototype function SPIx_Read(data_out: word): word; Description Reads one word or byte (depending on mode set by init routines) from the SPI bus. Parameters - data_out: dummy data for clock generation (see device Datasheet for SPI modules implementation details) Returns Received data. Requires Routine requires at least one SPI module. Used SPI module must be initialized before using this function. See the SPIx_Init and SPIx_Init_ Advanced routines.
mikroPascal PRO for dsPIC30/33 and PIC24 SPI_Set_Active Prototype procedure SPI_Set_Active(read_ptr : ^TSPI_Rd_Ptr; write_ptr : ^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.
mikoPascal PRO for dsPIC30/33 and PIC24 temp := word(valueDAC shr 8) and 0x0F; // Store valueDAC[11..8] to temp[3..0] temp := temp or 0x30; // Define DAC setting, see MCP4921 datasheet SPI1_Write(temp); // Send high byte via SPI // Send Low Byte temp := valueDAC; SPI1_Write(temp); Chip_Select := 1; end; // Store valueDAC[7..0] to temp[7..
mikroPascal 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.
mikoPascal 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: var SPI_Ethernet_CS external; var SPI_Ethernet_CS LATF1_bit; var SPI_Ethernet_RST external; : : sbit; sfr; ENC28J60 chip select pin. sbit; sfr; ENC28J60 reset pin.
mikroPascal PRO for dsPIC30/33 and PIC24 - SPI_Ethernet_dnsResolve - SPI_Ethernet_initDHCP - SPI_Ethernet_doDHCPLeaseTime - SPI_Ethernet_renewDHCP SPI_Ethernet_Init Prototype procedure SPI_Ethernet_Init(mac: ^byte; ip: ^byte; fullDuplex: 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.
mikoPascal PRO for dsPIC30/33 and PIC24 Example // SPI Ethernet module connections var SPI_Ethernet_RST : sbit at RF0_bit; var SPI_Ethernet_CS : sbit at RF1_bit; var SPI_Ethernet_RST_Direction : sbit at TRISF0_bit; var SPI_Ethernet_CS_Direction : sbit at TRISF1_bit; const SPI_Ethernet_HALFDUPLEX = 0; const SPI_Ethernet_FULLDUPLEX = 1; var myMacAddr : array[6] of byte; // my MAC address myIpAddr : array[4] of byte; // my IP addr ...
mikroPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_Enable Prototype procedure SPI_Ethernet_Enable(enFlt : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_Disable Prototype procedure SPI_Ethernet_Disable(disFlt : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_doPacket Prototype function SPI_Ethernet_doPacket() : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_putBytes Prototype procedure SPI_Ethernet_putBytes(ptr : ^byte; n : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_putString Prototype function SPI_Ethernet_putString(ptr : ^byte) : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_getBytes Prototype procedure SPI_Ethernet_getBytes(ptr : ^byte; addr : word; n : 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. - addr: ENC28J60 RAM start address.
mikroPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_UserUDP Prototype function SPI_Ethernet_UserUDP(var remoteHost : array[4] of byte; remotePort, destPort, reqLength : word; var flags: TEthPktFlags) : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_getIpAddress Prototype function SPI_Ethernet_getIpAddress() : 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 var ipAddr : array[4] of byte; // user IP address buffer ...
mikroPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_getDnsIpAddress Prototype function SPI_Ethernet_getDnsIpAddress() : 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 var dnsIpAddr : array[4] of byte; // user DNS IP address buffer ...
mikoPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_confNetwork Prototype procedure SPI_Ethernet_confNetwork(var array[4] of byte); ipMask, gwIpAddr, dnsIpAddr : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_arpResolve Prototype function SPI_Ethernet_arpResolve(var ip : array[4] of byte; tmax : byte) : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_dnsResolve Prototype function SPI_Ethernet_dnsResolve(var host : string; tmax : byte) : 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.
mikroPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_initDHCP Prototype function SPI_Ethernet_initDHCP(tmax : byte) : 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.
mikoPascal PRO for dsPIC30/33 and PIC24 SPI_Ethernet_renewDHCP Prototype function SPI_Ethernet_renewDHCP(tmax : byte) : 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 do begin ...
mikroPascal PRO for dsPIC30/33 and PIC24 gwIpAddr ipMask dnsIpAddr : array[4] of byte; // gateway (router) IP address : array[4] of byte; // network mask (for example : 255.255.255.0) : array[4] of byte; // DNS server IP address {************************************************************ * ROM constant strings *} const httpHeader : string[30] = ‘HTTP/1.
mikoPascal PRO for dsPIC30/33 and PIC24 ‘str=””;’+ ‘for(i=0;i<4;i++)’+ ‘{str+=”
LED #”+i+” | ”;’+ ‘if(PORTD&(1<ON”;}’+ ‘else {str+=”OFF”;}’+ ‘str+=” | Toggle |
”;}’+ ‘document.write(str);’+ ‘’+ ‘’+ ‘This is HTTP request #