mikroC PRO for dsPIC30/33 and PIC24 is a full-featured C 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.
mikoC PRO for dsPIC Table of Contents CHAPTER 1 INTRODUCTION Introduction to mikroC PRO for dsPIC30/33 and PIC24 32 32 33 What’s new in mikroC PRO for dsPIC30/33 and PIC24 34 Software License Agreement 35 Technical Support How to Register 37 37 CHAPTER 2 mikroC 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 and Limited Warranty IMPORTANT -
mikroC PRO for dsPIC Help Help Menu Options 53 53 mikroC PRO for dsPIC30/33 and PIC24 IDE 54 Code Editor 55 Code Explorer 62 Project Manager Project Settings Library Manager 63 65 66 Statistics 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 Column Select Mode Editor Colors Auto Correct
mikoC PRO for dsPIC Advanced Edit Toolbar Find/Replace Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar 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 Graphic Lcd Bitmap Editor HID Terminal Lcd Custom Cha
mikroC PRO for dsPIC Metacharacters - Subexpressions Metacharacters - Backreferences 113 113 Keyboard Shortcuts CHAPTER 3 mikroC 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 Simulator Software Simulator Debug Windows 130 130 131 132 Software Simulator Debugger Options
mikoC PRO for dsPIC at keyword bit type 144 144 Interrupts 145 Linker Directives 147 Indirect Function Calls Built-in Routines 148 149 Code Optimization 157 Single Static Assignment Optimization 158 Common Object File Format (COFF) 161 Function Calls from Interrupt Disable Context Saving Interrupt Handling Interrupt Example Directive absolute Directive orgall Directive funcorg Lo Hi Higher Highest LoWord HiWord Delay_us Delay_ms Vdelay_ms VDelay_Advanced_ms Delay_Cyc
mikroC PRO for dsPIC COFF File Generation 161 CHAPTER 7 dsPIC30/33 and PIC24 Specifics 163 163 dsPIC Memory Organization 165 Memory Type Specifiers 168 Memory Type Qualifiers 170 Read Modify Write Problem CHAPTER 8 mikroC PRO for dsPIC30/33 and PIC24 Language Reference Lexical Elements Overview Whitespace 171 175 175 178 179 Comments 180 Tokens 181 Constants Integer Constants 182 182 Types Efficiency Nested Calls Limitations Limits of Indirect Approach Through PSV Limits
mikoC PRO for dsPIC Binary Octal 183 183 Floating Point Constants Character Constants 184 184 String Constants 186 Enumeration Constants Pointer Constants Constant Expressions Keywords Identifiers 187 187 188 189 190 Punctuators 191 Concepts Objects 195 195 Scope and Visibility 196 Name Spaces Duration 197 198 Types 199 Fundamental Types Arithmetic Types 200 200 Escape Sequences Disambiguation Line Continuation with Backslash Case Sensitivity Uniqueness and Scope
mikroC PRO for dsPIC Enumerations 201 Void Type 203 Derived Types Arrays 203 204 Pointers 206 Pointer Arithmetic 210 Structures 213 Working with Structures 216 Structure Member Access 217 Unions 219 Bit Fields 221 Enumeration Declaration Anonymous Enum Type Enumeration Scope Void Functions Generic Pointers Array Declaration Array Initialization Arrays in Expressions Multi-dimensional Arrays Pointer Declarations Null Pointers Assign an address to a Function Pointer
mikoC PRO for dsPIC Types Conversions Standard Conversions 222 223 Explicit Types Conversions (Typecasting) Declarations 224 225 Linkage 226 Storage Classes 227 Type Qualifiers 229 Typedef Specifier asm Declaration 229 230 Initialization 232 Functions 233 Function Calls and Argument Conversions 235 Ellipsis (‘...
mikroC PRO for dsPIC Bitwise Shift Operators Bitwise vs.
mikoC PRO for dsPIC Preprocessor Directives 258 Macros 259 File Inclusion 261 Preprocessor Operators 263 Conditional Compilation 264 CHAPTER 9 mikroC PRO for dsPIC30/33 and PIC24 Libraries Hardware Libraries Digital Signal Processing Libraries Standard ANSI C Libraries Miscellaneous Libraries Hardware Libraries ADC Library 266 266 267 267 268 268 269 269 CAN Library 275 MikroElektronika 12 Line Continuation with Backslash (\) Defining Macros and Macro Expansions Macros with P
mikroC PRO for dsPIC CAN_MASK Constants CAN_FILTER Constants Library Example HW Connection 285 286 286 289 CANSPI Library 290 Compact Flash Library 306 Library Dependency Tree External dependencies of CANSPI Library Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialize CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIRead CANSPIWrite CANSPI Constants CANSPI_OP_MODE Constants CANSPI_TX_MSG_FLAGS Constants CANSPI_RX_MSG_FLAGS Constants CANSPI_MASK Cons
mikoC PRO for dsPIC Cf_Fat_Set_File_Date Cf_Fat_Get_File_Date Cf_Fat_Get_File_Date_Modified Cf_Fat_Get_File_Size Cf_Fat_Get_Swap_File Library Example HW Connection 317 318 318 319 319 321 323 ECAN Library 324 EEPROM Library 343 Epson S1D13700 Graphic Lcd Library 347 Library Routines ECANxDmaChannelInit ECANxSetOperationMode ECANxGetOperationMode ECANxInitialize ECANxSelectTxBuffers ECANxFilterDisable ECANxFilterEnable ECANxSetBufferSize ECANxSetBaudRate ECANxSetMask ECANxSetFilt
mikroC PRO for dsPIC S1D13700_Fill S1D13700_GrFill S1D13700_TxtFill S1D13700_Display_GrLayer S1D13700_Display_TxtLayer S1D13700_Set_Cursor S1D13700_Display_Cursor S1D13700_Write_Char S1D13700_Write_Text S1D13700_Dot S1D13700_Line S1D13700_H_Line S1D13700_V_Line S1D13700_Rectangle S1D13700_Box S1D13700_Rectangle_Round_Edges S1D13700_Rectangle_Round_Edges_Fill S1D13700_Circle S1D13700_Circle_Fill S1D13700_Image S1D13700_PartialImage 351 352 352 352 353 353 354 354 355 355 356 356 357 357
mikoC PRO for dsPIC External dependencies of Graphic Lcd Library Glcd_Init Glcd_Set_Side Glcd_Set_X Glcd_Set_Page Glcd_Read_Data Glcd_Write_Data Glcd_Fill Glcd_Dot Glcd_Line Glcd_V_Line Glcd_H_Line Glcd_Rectangle Glcd_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 Library Example HW Connection 374 375 377 377 377 378 378 379 379 379 380 380 381 381 382 382 383 383
mikroC PRO for dsPIC Library Routines Lcd_Init Lcd_Out Lcd_Out_Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd Available Lcd Commands Library Example 399 400 401 401 401 402 402 402 403 Manchester Code Library 405 Multi Media Card Library 413 Keypad_Key_Click Library Routines Man_Receive_Init Man_Receive Man_Send_Init Man_Send Man_Synchro Man_Break Library Example Connection Example Secure Digital Card Secure Digital High Capacity Card Library Dependency Tree External dependencies of MMC Librar
mikoC PRO for dsPIC OneWire Library 432 Peripheral Pin Select Library 437 Port Expander Library 441 PS/2 Library 452 PWM Library 456 Library Routines Ow_Reset Ow_Read Ow_Write Library Example HW Connection Library Routines Unlock_IOLOCK Lock_IOLOCK PPS_Mapping Direction Parameters Input Functions Output Functions Library Dependency Tree External dependencies of Port Expander Library Library Routines Expander_Init Expander_Init_Advanced Expander_Read_Byte Expander_Write_By
mikroC PRO for dsPIC PWM_Init PWM_Set_Duty PWM_Start PWM_Stop Library Example HW Connection 457 457 458 458 458 460 PWM Motor Control Library 460 RS-485 Library 464 Software I²C Library 474 Software SPI Library 481 Software UART Library 485 Library Routines PWMx_Mc_Init PWMx_Mc_Set_Duty PWMx_Mc_Start PWMx_Mc_Stop HW Connection Library Dependency Tree External dependencies of RS-485 Library Library Routines RS485Master_Init RS485Master_Receive RS485Master_Send RS485Slave_I
mikoC PRO for dsPIC Soft_UART_Read Soft_UART_Write Soft_UART_Break Library Example 486 486 487 488 Sound Library 489 SPI Library 492 SPI Ethernet Library 499 Library Routines Sound_Init Sound_Play HW Connection Library Routines SPIx_Init SPIx_Init_Advanced SPIx_Read SPIx_Write SPI_Set_Active Library Example HW Connection Library Dependency Tree External dependencies of SPI Ethernet Library Library Routines SPIx_Write SPIx_Write SPI_Ethernet_Enable SPI_Ethernet_Disable SPI
mikroC PRO for dsPIC HW Connection 522 SPI Ethernet ENC24J600 Library 523 SPI Graphic Lcd Library 541 Library Dependency Tree External dependencies of SPI Ethernet ENC24J600 Library Library Routines SPI_Ethernet_24j600_Init SPI_Ethernet_24j600_Enable SPI_Ethernet_24j600_Disable SPI_Ethernet_24j600_doPacket SPI_Ethernet_24j600_putByte SPI_Ethernet_24j600_putBytes SPI_Ethernet_24j600_putConstBytes SPI_Ethernet_24j600_putString SPI_Ethernet_24j600_putConstString SPI_Ethernet_24j600_getByte
mikoC PRO for dsPIC SPI_Glcd_Rectangle_Round_Edges_Fill SPI_Glcd_Box SPI_Glcd_Circle SPI_Glcd_Circle_FIll SPI_Glcd_Set_Font SPI_Glcd_Write_Char SPI_Glcd_Write_Text SPI_Glcd_Image SPI_Glcd_PartialImage Library Example HW Connection 548 549 549 550 551 552 552 553 553 554 556 SPI Lcd Library 557 SPI Lcd8 (8-bit interface) Library 563 SPI T6963C Graphic Lcd Library 570 Library Dependency Tree External dependencies of SPI Lcd Library Library Routines SPI_Lcd_Config SPI_Lcd_Out SPI_Lcd
mikroC PRO for dsPIC SPI_T6963C_write_char SPI_T6963C_write_text SPI_T6963C_line SPI_T6963C_rectangle SPI_T6963C_rectangle_round_edges SPI_T6963C_rectangle_round_edges_fill SPI_T6963C_box SPI_T6963C_circle SPI_T6963C_circle_fill SPI_T6963C_image SPI_T6963C_PartialImage SPI_T6963C_sprite SPI_T6963C_set_cursor SPI_T6963C_clearBit SPI_T6963C_setBit SPI_T6963C_negBit SPI_T6963C_displayGrPanel SPI_T6963C_displayTxtPanel SPI_T6963C_setGrPanel SPI_T6963C_setTxtPanel SPI_T6963C_panelFill SPI_T6
mikoC PRO for dsPIC T6963C_box T6963C_circle T6963C_circle_fill T6963C_image T6963C_PartialImage T6963C_sprite T6963C_set_cursor T6963C_clearBit T6963C_setBit T6963C_negBit T6963C_displayGrPanel T6963C_displayTxtPanel T6963C_setGrPanel T6963C_setTxtPanel T6963C_panelFill T6963C_grFill T6963C_txtFill T6963C_cursor_height T6963C_graphics T6963C_text T6963C_cursor T6963C_cursor_blink Library Example HW Connection TFT Library External dependencies of TFT Library Library Routines TFT
mikroC PRO for dsPIC TFT_RGBToColor16bit TFT_Color16bitToRGB HW Connection 631 631 632 Touch Panel Library 633 Touch Panel TFT Library 643 UART Library 649 USB Library 662 Library Dependency Tree External dependencies of Touch Panel Library Library Routines TP_Init TP_Set_ADC_Threshold TP_Press_Detect TP_Get_Coordinates TP_Calibrate_Bottom_Left TP_Calibrate_Upper_Right TP_Get_Calibration_Consts TP_Set_Calibration_Consts Library Example Library Dependency Tree External dependenc
mikoC PRO for dsPIC HID_Read HID_Write HID_Disable USB_Interrupt_Proc USB_Polling_Proc Gen_Enable Gen_Read Gen_Write Library Example HW Connection 663 664 664 665 665 666 666 667 668 668 DSP Libraries 669 FIR Filter Library 670 IIR Filter Library 671 FFT Library 672 Bit Reverse Complex Library 676 Vectors Library 677 Matrices Library 685 Digital Signal Processing Libraries Library Routines FIR_Radix Library Routines IIR_Radix Library Dependency Tree FFT Twiddle Factor
mikroC PRO for dsPIC Matrix_Subtract Matrix_Scale Matrix_Multiply Matrix_Add 686 686 687 688 Standard ANSI C Libraries ANSI C Ctype Library 689 689 ANSI C Math Library 693 ANSI C Stdlib Library 699 Library Functions isalnum isalpha iscntrl isdigit isgraph islower ispunct isspace isupper isxdigit toupper tolower Library Functions acos asin atan atan2 ceil cos cosh exp fabs floor frexp ldexp log log10 modf pow sin sinh sqrt tan tanh Library Dependency Tree
mikoC PRO for dsPIC atof atoi atol div ldiv uldiv labs max min rand srand xtoi Div Structures 700 700 700 700 701 701 701 701 702 702 702 702 703 ANSI C String Library 704 Miscellaneous Libraries Button Library 712 712 Conversions Library 714 Library Functions memchr memcmp memcpy memmove memset strcat strchr strcmp strcpy strlen strncat strncpy strspn strncmp strstr strcspn strpbrk strrchr strtok Library Routines strrchr Library Dependency Tree Library Rout
mikroC PRO for dsPIC LongWordToStr FloatToStr WordToStrWithZeros IntToStrWithZeros LongWordToStrWithZeros LongIntToStrWithZeros ByteToHex ShortToHex WordToHex IntToHex LongWordToHex LongIntToHex Dec2Bcd Bcd2Dec Dec2Bcd16 Bcd2Dec16 Rtrim Ltrim 717 718 719 719 720 720 721 721 722 722 723 723 724 724 725 725 726 726 PrintOut Library 727 Setjmp Library 731 Sprint Library 734 Time Library 738 Trigonometry Library 742 CHAPTER 10 Tutorials 744 744 Library Dependency Tree Lib
mikoC PRO for dsPIC Managing Project 744 New Project 745 New Project 748 Customizing Projects 752 Add/Remove Files from Project 754 Source Files 756 Edit Project Source Files 759 760 Clean Project Folder Compilation 763 764 Using Microchip MPLAB® IDE with mikroElektronika compilers 766 Using MPLAB® ICD 2 Debugger Using MPLAB® Simulator 766 773 Projects New Project Wizard Steps New Project Wizard Steps Managing Project Group Add/Remove Files from Project Project Level D
mikroC PRO for dsPIC Frequently Asked Questions 778 Can I use your compilers and programmer on Windows Vista (Windows 7) ? 778 I am getting “Access is denied” error in Vista, how to solve this problem ? 778 What are differences between mikroC PRO, mikroPascal PRO and mikroBasic PRO compilers ? Why do they have different prices ? 778 Why do your PIC compilers don’t support 12F508 and some similar chips ? 778 What are limitations of demo versions of mikroElektronika’s compilers ? 778 Why do I still ge
CHAPTER 1 mikoC PRO for dsPIC INTRODUCTION The mikroC PRO for dsPIC30/33 and PIC24 is a powerful, feature-rich development tool for dsPIC30/33 and PIC24 microcontrollers. It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems, without compromising performance or control.
mikroC PRO for dsPIC Introduction to mikroC PRO for dsPIC30/33 and PIC24 dsPIC30/33 and PIC24 and C fit together well: dsPIC is designed as PIC with digital signal processing capabilities. These are Microchip’s first inherent 16-bit (data) microcontrollers. They build on the PIC’s existing strength offering hardware MAC (multiply-accumulate), barrel shifting, bit reversal, (16x16)-bit multiplication and other digital signal processing operations.
mikoC PRO for dsPIC What’s new in mikroC 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 mikroC PRO for dsPIC30/33 and PIC24, visit the following link : http://www.mikroe. com/download/eng/documents/compilers/mikroc/pro/dspic/version_history.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS AND BUSINESS INFORMATION, BUSINESS INTERRUPTION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE PRODUCT OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF MIKROELEKTRONIKA ASSOCIATES HAS BEEN ADVISED OF THE POSSIBILITY OF
mikroC PRO for dsPIC 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/mikroC 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.
mikoC PRO for dsPIC If you choose I work online registering method, following page will be opened in your default browser : MikroElektronika 38
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC CHAPTER 2 mikroC PRO for dsPIC30/33 and PIC24 Environment 41 MikroElektronika
mikoC PRO for dsPIC Main Menu Options Available Main Menu options are: Related topics: Keyboard shortcuts, Toolbars MikroElektronika 42
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC Advanced » Description Comment selected code or put single line comment if there is no selection. Uncomment selected code or remove single line comment if there is no selection. Indent selected code. Outdent selected code. Changes selected text case to lowercase. Changes selected text case to uppercase. Changes selected text case to titlercase. Find Text Dialog box for searching the document for the specified text. The search is performed in the direction specified.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC View View Menu Options View Menu contains commands for controlling the on-screen display of the current project.
mikoC PRO for dsPIC View Description Show/Hide Software Simulator / mikroICD (In-Circuit Debugger) Debug Windows. Show/Hide Toolbars. Show/Hide Bookmarks window. Show/Hide Code Explorer window. Show/Hide Library Manager window. Show/Hide Macro Editor window. Show/Hide Messages window. Show/Hide Project Manager window. Show/Hide Project Settings window. Show/Hide Routine List in active editor. Show/Hide Quick Converter window. Show/Hide View Image Preview window. View Assembly. View Listing.
mikroC PRO for dsPIC Project Project Menu Options Project Menu allows 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. Edit project settings Clean Project Folder Export Project.
mikoC PRO for dsPIC Build Build Menu Options Build Menu allows 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC Tools Tools Menu Options Tools Menu contain a number of applications designed to ease the use of compiler and included library routines. Tools Description Run mikroElektronika Programmer. Run Package Manager. Show/Hide Active Comment Editor window. Run ASCII Chart Run EEPROM Editor Generate HTML code suitable for publishing source code on the web. Run Filter Designer Tool.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC mikroC PRO for dsPIC30/33 and PIC24 IDE IDE Overview The mikroC PRO for dsPIC30/33 and PIC24 is an user-friendly and intuitive environment. For a detailed information on a certain part of IDE, simply click on it (hovering a mouse cursor above a desired IDE part will pop-up its name) : - The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Spell Checker, Auto Correct for common typos and Code Templates (Auto Complete).
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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).
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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 satifsy tastes of different users. Auto Correct Auto Correct option facilitate 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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 first error and it's location in code. Following options are available in the Code Explorer: Icon Description Expand/Collapse all nodes in tree. Locate declaration in code.
mikroC PRO for dsPIC 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 users to manage multiple projects. Several projects which together make project group may be open at the same time.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC Project Settings Following options are available in the Project Settings : - Device - select the appropriate device from the device drop-down list. - MCU Clock - enter the clock frequency value. - Build/Debugger Type - choose debugger type.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC Related topics: mikroC PRO for PIC Libraries, Creating New Library Statistics After successful compilation, you can review statistics of your code. Click the Statistics Icon . Memory Usage Windows Provides overview of RAM and ROM usage in the various forms.
mikroC PRO for dsPIC RAM Memory Usage Displays RAM memory usage in a pie-like form. Used RAM Locations Displays used RAM memory locations and their names.
mikoC PRO for dsPIC SFR Locations Displays list of used SFR locations. ROM Memory Usage Displays ROM memory space usage in a pie-like form.
mikroC PRO for dsPIC ROM Memory Constants Displays ROM memory constants and their addresses. Functions Sorts and displays functions in various ways.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC Memory Summary Displays summary of RAM and ROM memory in a pie-like form.
mikroC PRO for dsPIC Messages Window Messages Window displays various informations and notifications about the compilation process. It reports for example, time needed for preprocessing, compilation and linking; used RAM and ROM space, generated baud rate with error percentage, etc. User can filter which notifications will Messages Window display by checking Errors, Warning and Hints box. In case that errors were encountered during compiling, the compiler will report them and won’t generate a hex file.
mikoC PRO for dsPIC Quick Converter Quick Converter enables user to easily transform numbers from one base to another. User can convert integers of various sizes (8, 16 or 32 bits), signed and unsigned, using different representation (decimal, hexadecimal, binary and character). Also, Quick Converter features float point numbers conversion from/to Float Decimal, Float 32bit (IEEE), Float 32bit (Microchip) and Radix 1.15 for dsPIC family of MCUs.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC Now, navigate to the desired image file, and simply add it : Next, right click the added file, and choose Set As Preview Image : MikroElektronika 78
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC File Toolbar File Toolbar is a standard toolbar with following options: Icon Description Opens a new editor window. Open source file for editing or image file for viewing. Save changes for active window. Save changes in all opened windows. Print Preview. Print. Edit Toolbar Edit Toolbar is a standard toolbar with following options: Icon Description Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard. Paste text from clipboard.
mikroC PRO for dsPIC Advanced Edit Toolbar Advanced Edit Toolbar comes with following options: Icon Description Comment selected code or put single line comment if there is no selection Uncomment selected code or remove single line comment if there is no selection. Select text from starting delimiter to ending delimiter. Go to ending delimiter. Go to line. Indent selected code lines. Outdent selected code lines. Generate HTML code suitable for publishing current source code on the web.
mikoC PRO for dsPIC Project Toolbar Project Toolbar comes with 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 following options: Icon Description Build current project. Build all opened projects. Build and program active project. Start programmer and load current HEX file.
mikroC PRO for dsPIC Debug Toolbar Debug Toolbar comes with 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.
mikoC PRO for dsPIC Tools Toolbar Tools Toolbar comes with 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. View statistics for current project.
mikroC PRO for dsPIC Layout Toolbar Styles toolbar allows you to easily customize workspace through a number of different IDE layouts. Help Toolbar Help Toolbar provides access to information on using and registering compilers : Icon Description Open Help file. How To Register.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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 .
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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 mikroC PRO for dsPIC30/33 and PIC24 specifics). Build all files as library enables user to use compiled library (*.
mikoC PRO for dsPIC MikroElektronika 90
mikroC PRO for dsPIC 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 91 from Tools toolbar.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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 mikroC 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. It has an user-friendly visual interface for setting the filter parameters.
mikoC PRO for dsPIC Graphic Lcd Bitmap Editor The mikroC PRO for dsPIC30/33 and PIC24 includes the Graphic Lcd Bitmap Editor. Output is the mikroC PRO for dsPIC30/33 and PIC24 compatible code. You can launch it from the drop-down menu Tools › Glcd Bitmap Editor.
mikroC PRO for dsPIC HID Terminal The mikroC 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.
mikoC PRO for dsPIC Lcd Custom Character mikroC PRO for dsPIC30/33 and PIC24 includes the Lcd Custom Character. Output is mikroC PRO for dsPIC30/33 and PIC24 compatible code. You can launch it from the drop-down menu Tools › Lcd Custom Character.
mikroC PRO for dsPIC Seven Segment Editor The Seven Segment Editor is a convenient visual panel which returns decimal/hex value for any viable combination you would like to display on seven segment display. Click on the parts of seven segment image to get the requested value in the edit boxes. You can launch it from the drop-down menu Tools › Seven Segment Editor or by clicking the Seven Segment Editor Icon from Tools toolbar. UDP Terminal The mikroC PRO for dsPIC30/33 and PIC24 includes the UDP Terminal.
mikoC PRO for dsPIC USART Terminal The mikroC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC You can notice that when you start typing a name, properties pane is automatically displayed so you can edit properties if you wish. A Comment will be is created when you click button. Properties are consisted of two major categories - Attributes and Events. Attributes can be : - URL - Valid web address. - Image - Image has to be previously added to Project (Project Manager > Images). - File - File has to be previously added to Project (Project Manager > Other Files).
mikroC PRO for dsPIC 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. 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC Now, when image has been selected, we can assign an event for 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC If you click No, comment will be removed from the source code.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC Jump To Interrupt Lets you choose which interrupt you want to jump to. Requirement: Interrupt routine is included in project. You can call Jump To Interrupt by selecting Run › Jump To Interrupt from the drop-down menu, or by clicking the Jump To Interrupt Icon , from the Watch Values Window. By checking the Only Used box, you can display only the used breakpoints.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroC PRO for dsPIC30/33 and PIC24 IDE.
mikroC PRO for dsPIC 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 115 MikroElektronika
CHAPTER 3 mikoC PRO for dsPIC mikroC PRO for dsPIC30/33 and PIC24 Command Line Options Usage: mikroCdsPIC.exe [- [-]] [ [-]] [-]] Infile can be of *.c, *.mcl and *.pld type. The following parameters are valid : -P : MCU for which compilation will be done. -FO : Set oscillator [in MHz]. -SP : Add directory to the search path list. -IP : Add directory to the #include search path list.
mikroC PRO for dsPIC 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.mcpds" -SP"C:\Program Files\Mikroelektronika\mikroC PRO for dsPIC\ Defs\" : Output files generated to file path specified by filename.
CHAPTER 4 mikoC PRO for dsPIC 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 mikroC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC mikroICD Debugger Options Debugger Options Name Description Function Key Start Debugger Starts Debugger. F9 Stop Debugger Stop Debugger. Ctrl + F2 Run/Pause Debugger Run/Pause Debugger. F6 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.
mikroC PRO for dsPIC mikroICD Debugger Example Here is a step-by-step mikroICD Debugger Example. First you have to write a program.
mikoC PRO for dsPIC 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. To execute code line by line press [F8]. However, it is not recommended to use Step Over [F8] over Delay routines and routines containing delays. In this case use Run to cursor [F4] function or Run [F6] function combined with Breakpoints.
mikroC PRO for dsPIC Step Into [F7], Step Over [F8] and Step Out [Ctrl+F8] are mikroICD debugger functions that are used in stepping mode. There is also a Real-Time mode supported by the mikroICD. Functions that are used in the Real-Time mode are Run/ Pause Debugger [F6] and Run to cursor [F4]. Pressing F4 executes the code until the program reaches the cursor position line. Run(Pause) Debugger [F6] and Toggle Breakpoints [F5] are mikroICD debugger functions that are used in the RealTime mode.
mikoC PRO for dsPIC Breakpoints are divided into two groups: hardware and software breakpoints. The hardware breakpoints are placed in the MCU and provide fastest debugging. Number of hardware breakpoints is limited (4 for PIC24 and dsPIC33 family, for dsPIC30 family this number depends on the MCU used). If all hardware brekpoints are used, then the next breakpoint will be software breakpoint. These breakpoints are placed inside the mikroICD and simulate hardware breakpoints.
mikroC PRO for dsPIC mikroICD Debugger Windows Debug Windows This section provides an overview of available Debug Windows in mikroC 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. Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code.
mikoC PRO for dsPIC Also, it is possible to add all variables in the Watch Values Window by clicking button. To remove a variable from the Watch Values Window, just select the variable that you want to remove and then click the button, or press the Delete key. It is possible to remove all variables from the Watch Values Window by clicking button. You can also expand/collapse complex variables i.e. struct type variables, strings, etc, by clicking the appropriate button ( or ) beside variable name.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC Code Watch Window Note : Code Watch Window is available only when mikroICD is selected as a debugger. To show the Code Watch Window, select Debug Windows › Code from the View drop-down menu. The Code Watch Window shows code (hex format) written into the MCU. There is one action button concerning the Code Watch Window : - Reads code from the MCU and loads it up into the Code Window. Code reading is resources consuming operation so the user should wait until the reading is over.
CHAPTER 5 mikoC PRO for dsPIC Software Simulator Overview MikroElektronika 130
mikroC PRO for dsPIC Software Simulator The Source-level Software Simulator is an integral component of the mikroC 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.
mikoC PRO for dsPIC Software Simulator Debug Windows Debug Windows This section provides an overview of available Debug Windows in mikroC 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. Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code.
mikroC PRO for dsPIC Also, it is possible to add all variables in the Watch Values Window by clicking button. To remove a variable from the Watch Values Window, just select the variable that you want to remove and then click the button, or press the Delete key. It is possible to remove all variables from the Watch Values Window by clicking button. You can also expand/collapse complex variables i.e. struct type variables, strings, etc, by clicking the appropriate button ( or ) beside variable name.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC Code Watch Window Note : Code Watch Window is available only when mikroICD is selected as a debugger. To show the Code Watch Window, select Debug Windows › Code from the View drop-down menu. The Code Watch Window shows code (hex format) written into the MCU. There is one action button concerning the Code Watch Window : - Reads code from the MCU and loads it up into the Code Window. Code reading is resources consuming operation so the user should wait until the reading is over.
mikroC PRO for dsPIC Software Simulator Debugger Options Debugger Options Name Description Function Key Start Debugger Starts Debugger. F9 Stop Debugger Stop Debugger. Ctrl + F2 Run/Pause Debugger Run/Pause Debugger. F6 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.
CHAPTER 6 mikoC PRO for dsPIC mikroC PRO for dsPIC30/33 and PIC24 Specifics The following topics cover the specifics of mikroC PRO for dsPIC30/33 and PIC24 compiler: - ANSI Standard Issues - Predefined Globals and Constants - Accessing Individual Bits - Interrupts - Linker Directives - Built-in Routines - Code Optimization MikroElektronika 138
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC ANSI Standard Issues Divergence from the ANSI C Standard The mikroC PRO for dsPIC30/33 and PIC24 diverges from the ANSI C standard in a few areas. Some of these modifications are improvements intended to facilitate dsPIC programming, while others are the result of dsPIC30/33 and PIC24 hardware limitations. - Case Sensitivity. Check identifiers - The mikroC PRO for dsPIC30/33 and PIC24 treats identifiers declared with the const qualifier as “true constants” (C++ style).
mikroC PRO for dsPIC Predefined Globals and Constants To facilitate dsPIC30/33 and PIC24 programming, the mikroC PRO for dsPIC30/33 and PIC24 implements a number of predefined globals and constants. All dsPIC30/33 and PIC24 SFR registers are implicitly declared as global variables of volatile unsigned int. These identifiers have an external linkage, and are visible in the entire project. When creating a project, the mikroC PRO for dsPIC30/33 and PIC24 will include an appropriate (*.
mikoC PRO for dsPIC Accessing Individual Bits The mikroC 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 register unsigned short int Z = 1; sbit Z_bit at SR.B1; To access this bit in your code by its name, you can write something like this: // Clear Zero bit SR.
mikroC PRO for dsPIC Note : If aiming at portability, avoid this style of accessing individual bits, use the bit fields instead. See Predefined Globals and Constants for more information on register/bit names. sbit type The mikroC PRO for dsPIC30/33 and PIC24 compiler has sbit data type which provides access to registers, SFRs, variables, etc.
mikoC PRO for dsPIC 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 : extern char PORTAlias; // here in the library we can use its symbolic name char PORTAlias at PORTB; // this is where PORTAlias is fully defined ... void main() { ...
mikroC PRO for dsPIC 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 - Fixed priority within
mikoC PRO for dsPIC For the sake of backward compatibility, user may write also : void int1() org IVT_ADDR_U1RXINTERRUPT { asm nop; } which is equivalent to : void int1() iv IVT_ADDR_U1RXINTERRUPT { asm nop; } Is is recommended that interrupts are handled in this way for the sake of better readability of the user projects.
mikroC PRO for dsPIC Linker Directives The mikroC PRO for dsPIC30/33 and PIC24 uses an internal algorithm to distribute objects within memory. If you need to have a variable or routine at specific predefined address, use the linker directives absolute and org. Directive absolute Directive absolute specifies the starting address in RAM for a variable or a starting address in ROM for a constant. If the variable or constant is multi-byte, higher bytes will be stored at the consecutive locations.
mikoC PRO for dsPIC Directive funcorg You can use the #pragma funcorg directive to specify the starting address of a routine in ROM using routine name only: #pragma funcorg Related topics: Indirect Function Calls Indirect Function Calls If the linker encounters an indirect function call (by a pointer to function), it assumes that any of the functions addresses of which were taken anywhere in the program, can be called at that point.
mikroC PRO for dsPIC Built-in Routines The mikroC PRO for dsPIC30/33 and PIC24 compiler provides a set of useful built-in utility functions. The Lo, Hi, Higher, Highest, LoWord, HiWord routines are implemented as macros. If you want to use these functions you must include built_in.h header file (located in the inlclude folder of the compiler) into your project. The Delay_us and Delay_ms routines are implemented as “inline”; i.e.
mikoC PRO for dsPIC Lo Prototype #define Lo(param) ((char *)¶m)[0] Description The function returns low byte of number. The function does not interpret bit patterns of number – it merely returns 8 bits as found in register. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters Returns Requires Example Notes number: input number Low byte of number, bits 7..0. Nothing.
mikroC PRO for dsPIC Higher Prototype #define Higher(param) ((char *)¶m)[2] Description The function returns higher byte of number. The function does not interpret bit patterns of number – it merely returns 8 bits as found in register. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters Returns Requires Example Notes number: input number Higher byte of number, bits 23..16. Nothing.
mikoC PRO for dsPIC LoWord Prototype Description unsigned int LoWord(unsigned long number); The function returns low word of number. The function does not interpret bit patterns of number – it merely returns 16 bits as found in register. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters Returns Requires Example Notes number: input number Low word of number, bits 15..0. Nothing.
mikroC PRO for dsPIC Delay_us Prototype Description void Delay_us(const unsigned long time_in_us); Creates a software delay in duration of time_in_us microseconds. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters time_in_us: delay time in microseconds. Valid values: constant values, range of applicable constants depends on the oscillator frequency Returns Nothing. Requires Nothing.
mikoC PRO for dsPIC VDelay_Advanced_ms Prototype Description Parameters Returns void VDelay_Advanced_ms(unsigned time_in_ms, unsigned Current_Fosc_kHz); Creates a software delay in duration of time_in_ms milliseconds (a variable), for a given oscillator frequency. Generated delay is not as precise as the delay created by Delay_ms. Time_ms: delay time in milliseconds Current_Fosc_kHz: desiredoscillator frequency Nothing. Requires Nothing.
mikroC PRO for dsPIC Clock_kHz Prototype Description unsigned long Clock_kHz(); Function returns device clock in kHz, rounded to the nearest integer. This is an “inline” routine; code is generated in the place of the call, so the call doesn’t count against the nested call limit. Parameters None. Returns Device clock in kHz, rounded to the nearest integer. Requires Nothing. Example Notes unsigned long clk; ... clk = Clock_kHz(); None.
mikoC PRO for dsPIC Get_Fosc_Per_Cyc Prototype Description unsigned int Get_Fosc_Per_Cyc(); Function returns device’s clock per cycle, rounded to the nearest integer. Note that Get_Fosc_Per_Cyc is library function rather than a built-in routine; it is presented in this topic for the sake of convenience. Parameters None. Returns Device’s clock per cycle, rounded to the nearest integer. Requires Nothing. Example Notes unsigned int clk_per_cyc; ... clk_per_cyc = Get_Fosc_Per_Cyc(); None.
mikroC PRO for dsPIC Code Optimization Optimizer has been added to extend the compiler usability, cut down the amount of code generated and speed-up its execution. The main features are: Constant folding All expressions that can be evaluated in the compile time (i.e. constant) are being replaced by their results.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC Without SSA enabled, this example is consisted of 5 asm instructions : ;rbuild.c,10 :: if(y+k) 0x0218 0x90008E MOV [_WREG14+0], _WREG1 0x021A 0x470062 ADD _WREG14, #2, _WREG0 0x021C 0x408010 ADD _WREG1, [_WREG0], _WREG0 0x021E 0x320001 BRA Z L_main0 L__main2: ;rbuild.
mikoC PRO for dsPIC Asm code and SSA optimization If converting code from an earlier version of the compiler, which consists of mixed asm code with the C code, keep in mind that the generated code can substantially differ when SSA optimization option is enabled or disabled. This is due to the fact that SSA optimization uses certain working registers to store routine parameters (W10-W13), rather than storing them onto the function frame.
mikroC PRO for dsPIC 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. By using COFF, it is possible to import and debug code generated by mikroElektronika compilers under Microchip's MPLAB®.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC CHAPTER 7 dsPIC30/33 and PIC24 Specifics In order to get the most from the mikroC 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.
mikoC PRO for dsPIC 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 mikroC PRO for dsPIC30/33 and PIC24 is capable of handling types like char or short, dsPIC30/33 and PIC24 will generate a better code for 16-bit types, like int. Therefore, use char and short only in places where you can significantlly save RAM (e.g. for arrays char a[30]).
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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. The DMA controller can automatically copy entire blocks of data without requiring the user software to read or write the peripheral Special Function Registers (SFRs) every time a peripheral interrupt occurs.
mikoC PRO for dsPIC Memory Type Specifiers The mikroC 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.
mikroC PRO for dsPIC xdata Description This memory specifier allows user to access X Data memory space. Example xdata char x; // puts x in xdata memory space ydata Description This memory specifier allows user to access Y Data memory space. Example ydata char y; // puts y in ydata memory space dma Description This memory specifier allows user to access DMA memory space (dsPIC33F specific).
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC Read Modify Write Problem The Microchip microcontrollers use a sequence known as Read-Modify-Write (RMW) when changing an output state (1 or 0) on a pin. This can cause unexpected behavior under certain circumstances. When your program changes the state on a specific pin, for example RB0 in PORTB, the microcontroller first READs all 8 bits of the PORTB register which represents the states of all 8 pins in PORTB (RB7-RB0). The microcontroller then stores this data in the MCU.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC The second line, LATB.B1 = 1; will be decoded like in this way : READ LATB is read: STORE Since the voltage levels on MCU pins are no longer relevant, we get the expected value: Actual voltage levels on MCU pins are no longer relevant when using LATx for output MODIFY Data is modified to set the bit: WRITE LATB is written with the new data.
mikroC PRO for dsPIC CHAPTER 8 mikroC PRO for dsPIC30/33 and PIC24 Language Reference 175 MikroElektronika
mikoC PRO for dsPIC - Lexical Elements - Whitespace - Comments - Tokens - Constants - Constants Overview - Integer Constants - Floating Point Constants - Character Constants - String Constants - Enumeration Constants - Pointer Constants - Constant Expressions - Keywords - Identifiers - Punctuators - Concepts - Objects and Lvalues - Scope and Visibility - Name Spaces - Duration - Types - Fundamental Types - Arithmetic Types - Enumerations - Void Type
mikroC PRO for dsPIC - Types Conversions - Standard Conversions - Explicit Typecasting - Declarations - Introduction to Declarations - Linkage - Storage Classes - Type Qualifiers - Typedef Specifier - ASM Declaration - Initialization - Functions - Introduction to Functions - Function Calls and Argument Conversion - Operators - Introduction to Operators - Operators Precedence and Associativity - Arithmetic Operators - Relational Operators - Bitwise Operators - Logical Operators - Conditional Operator
mikoC PRO for dsPIC - Jump Statements - Break and Continue Statements - Goto Statement - Return Statement - Compound Statements (Blocks) - Preprocessor - Introduction to Preprocessor - Preprocessor Directives - Macros - File Inclusion - Preprocessor Operators - Conditional Compilation Lexical Elements Overview The following topics provide a formal definition of the mikroC PRO for dsPIC30/33 and PIC24 lexical elements.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC Comments Comments are pieces of a text used to annotate a program and technically are 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 delineate comments: the C method and the C++ method. Both are supported by mikroC PRO for dsPIC30/33 and PIC24.
mikroC PRO for dsPIC Tokens Token is the smallest element of a C program that compiler can recognize. The parser separates tokens from the input stream by creating the longest token possible using the input characters in a left–to–right scan. The mikroC PRO for dsPIC30/33 and PIC24 recognizes the following kinds of tokens: - keywords - identifiers - constants - operators - punctuators (also known as separators) Tokens can be concatenated (pasted) by means of the preprocessor operator ##.
mikoC PRO for dsPIC Constants Constants or literals are tokens representing fixed numeric or character values. The mikroC PRO for dsPIC30/33 and PIC24 supports: - integer constants - floating point constants - character constants - string constants (strings literals) - enumeration constants The data type of a constant is deduced by the compiler using such clues as a numeric value and format used in the source code.
mikroC PRO for dsPIC In the absence of any overriding suffixes, the data type of a decimal constant is derived from its value, as shown below: Value Assigned to Constant Assumed Type < -2147483648 Error: Out of range! -2147483648 – -32769 long -32768 – -129 -128 – 127 128 – 255 256 – 32767 32768 – 65535 65536 – 2147483647 int short unsigned short int unsigned int long 2147483648 – 4294967295 unsigned long > 4294967295 Error: Out of range! Hexadecimal All constants starting with 0x (or 0X) are
mikoC PRO for dsPIC Floating Point Constants A floating-point constant consists of: - Decimal integer - Decimal point - Decimal fraction - e or E and a signed integer exponent (optional) - Type suffix: f or F or l or L (optional) Either decimal integer or decimal fraction (but not both) can be omitted. Either decimal point or letter e (or E) with a signed integer exponent (but not both) can be omitted. These rules allow conventional and scientific (exponent) notations.
mikroC PRO for dsPIC For example, the octal number \777 is larger than the maximum value allowed (\377) and will generate an error. The first nonoctal or nonhexadecimal character encountered in an octal or hexadecimal escape sequence marks the end of the sequence. Note: You must use the sequence \\ to represent an ASCII backslash, as used in operating system paths.
mikoC PRO for dsPIC String Constants String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: “This is a string.” The null string, or empty string, is written like “”. A literal string is stored internally as a given sequence of characters plus a final null character. A null string is stored as a single null character.
mikroC PRO for dsPIC Enumeration Constants Enumeration constants are identifiers defined in enum type declarations. The identifiers are usually chosen as mnemonics to contribute to legibility. Enumeration size is calculated according to the enumerators (enumeration elements). They can be used in any expression where integer constants are valid. For example: enum weekdays { SUN = 0, MON, TUE, WED, THU, FRI, SAT }; The identifiers (enumerators) used must be unique within the scope of the enum declaration.
mikoC PRO for dsPIC Notes: - Pointer to constant space (Flash memory) is allocated in RAM. - Due to the previous note, it is not possible to define an extern const. - Constants of a simple type are not allocated in the Flash memory nor in RAM, but changed in the compile time, and therefore, address of a such constant can not be obtained. Constant Expressions A constant expressions can be evaluated during translation rather that runtime and accordingly may be used in any place that a constant may be.
mikroC PRO for dsPIC Keywords Keywords are words reserved for special purposes and must not be used as normal identifier names. Beside standard C keywords, all relevant SFR are defined as global variables and represent reserved words that cannot be redefined (for example: TMR0, PCL, etc). Probe the Code Assistant for specific letters (Ctrl+Space in Editor) or refer to Predefined Globals and Constants.
mikoC PRO for dsPIC - protected public register return rx sfr short signed sizeof static struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile while xdata ydata Also, the mikroC PRO for dsPIC30/33 and PIC24 includes a number of predefined identifiers used in libraries. You could replace them by your own definitions, if you want to develop your own libraries. For more information, see mikroC PRO for dsPIC30/33 and PIC24 Libraries.
mikroC PRO for dsPIC Uniqueness and Scope Although identifier names are arbitrary (according to the stated rules), if the same name is used for more than one identifier within the same scope and sharing the same name space then error arises. Duplicate names are legal for different name spaces regardless of scope rules. For more information on scope, refer to Scope and Visibility.
mikoC PRO for dsPIC Parentheses Parentheses ( ) are used to group expressions, isolate conditional expressions, and indicate function calls and function parameters: d = c * (a + b); /* override normal precedence */ if (d == z) ++x; func(); void func2(int n); /* essential with conditional statement */ /* function call, no args */ /* function declaration with parameters */ Parentheses are recommended in macro definitions to avoid potential precedence problems during an expansion: #define CUBE(x) ((x) * (x
mikroC PRO for dsPIC Semicolon Semicolon (;) is a statement terminator. Any legal C expression (including the empty expression) followed by a semicolon is interpreted as a statement, known as an expression statement. The expression is evaluated and its value is discarded. If the expression statement has no side effects, the mikroC PRO for dsPIC30/33 and PIC24 might ignore it.
mikoC PRO for dsPIC Equal Sign Equal sign (=) separates variable declarations from initialization lists: int test[5] = { 1, 2, 3, 4, 5 }; int x = 5; Equal sign is also used as an assignment operator in expressions: int a, b, c; a = b + c; For more information, see Assignment Operators. Pound Sign (Preprocessor Directive) Pound sign (#) indicates a preprocessor directive when it occurs as the first nonwhitespace character on a line.
mikroC PRO for dsPIC Concepts This section covers some basic concepts of language, essential for understanding of how C programs work. First, we need to establish the following terms that will be used throughout the help: - Objects and lvalues - Scope and Visibility - Name Spaces - Duration Objects An object is a specific region of memory that can hold a fixed or variable value (or set of values).
mikoC PRO for dsPIC Lvalues Lvalue is an object locator: an expression that designates an object. An example of lvalue expression is *P, where P is any expression evaluating to a non-null pointer. A modifiable lvalue is an identifier or expression that relates to an object that can be accessed and legally changed in memory. A const pointer to a constant, for example, is not a modifiable lvalue. A pointer to a constant can be changed (but its dereferenced value cannot).
mikroC PRO for dsPIC Technically, visibility cannot exceed a scope, but a scope can exceed visibility. See the following example: void f (int i) { int j; // auto by default j = 3; // int i and j are in scope and visible { double j; j = 0.
mikoC PRO for dsPIC Duration Duration, closely related to a storage class, defines a period during which the declared identifiers have real, physical objects allocated in memory. We also distinguish between compile-time and run-time objects. Variables, for instance, unlike typedefs and types, have real memory allocated during run time. There are two kinds of duration: static and local.
mikroC PRO for dsPIC Types The mikroC PRO for dsPIC30/33 and PIC24 is a strictly typed language, which means that every object, function, and expression must have a strictly defined type, known in the time of compilation. Note that the mikroC PRO for dsPIC30/33 and PIC24 works exclusively with numeric types.
mikoC PRO for dsPIC Fundamental Types The fudamental types represent types that cannot be divided into more basic elements, and are the model for representing elementary data on machine level. The fudamental types are sometimes referred to as unstructured types, and are used as elements in creating more complex derived or user-defined types.
mikroC PRO for dsPIC Floating-point Types The types float and double, together with the long double variant, are considered to be floating-point types. The mikroC PRO for dsPIC30/33 and PIC24’s implementation of an ANSI Standard considers all three to be the same type. Floating point in the mikroC PRO for dsPIC30/33 and PIC24 is implemented using the Microchip AN575 32-bit format (IEEE 754 compliant).
mikoC PRO for dsPIC With explicit integral initializers, you can set one or more enumerators to specific values. The initializer can be any expression yielding a positive or negative integer value (after possible integer promotions). Any subsequent names without initializers will be increased by one. These values are usually unique, but duplicates are legal. The order of constants can be explicitly re-arranged.
mikroC PRO for dsPIC Void Type void is a special type indicating the absence of any value. There are no objects of void; instead, void is used for deriving more complex types. Void Functions Use the void keyword as a function return type if the function does not return a value. void print_temp(char temp) { Lcd_Out_Cp(“Temperature:”); Lcd_Out_Cp(temp); Lcd_Chr_Cp(223); // degree character Lcd_Chr_Cp(‘C’); } Use void as a function heading if the function does not take any parameters.
mikoC PRO for dsPIC Arrays Array is the simplest and most commonly used structured type. A variable of array type is actually an array of objects of the same type. These objects represent elements of an array and are identified by their position in array. An array consists of a contiguous region of storage exactly large enough to hold all of its elements.
mikroC PRO for dsPIC Arrays in Expressions When the name of an array comes up in expression evaluation (except with operators & and sizeof), it is implicitly converted to the pointer pointing to array’s first element. See Arrays and Pointers for more information. Multi-dimensional Arrays An array is one-dimensional if it is of scalar type. One-dimensional arrays are sometimes referred to as vectors. Multidimensional arrays are constructed by declaring arrays of array type.
mikoC PRO for dsPIC Pointers Pointers are special objects for holding (or “pointing to”) memory addresses. In the mikroC 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. A pointer of type “pointer to object of type” holds the address of (that is, points to) an object of type. Since pointers are objects, you can have a pointer pointing to a pointer (and so on).
mikroC PRO for dsPIC Null Pointers A null pointer value is an address that is guaranteed to be different from any valid pointer in use in a program. Assigning the integer constant 0 to a pointer assigns a null pointer value to it. For example: int *pn = 0; /* Here’s one null pointer */ /* We can test the pointer like this: */ if ( pn == 0 ) { ... } The pointer type “pointer to void” must not be confused with the null pointer.
mikoC PRO for dsPIC Example: int addC(char x,char y){ } return x+y; int subC(char x,char y){ } return x-y; int mulC(char x,char y){ } return x*y; int divC(char x,char y){ } return x/y; int modC(char x,char y){ } return x%y; //array of pointer to functions that receive two chars and returns int int (*arrpf[])(char,char) = { addC ,subC,mulC,divC,modC}; int res; char i; void main() { for (i=0;i<5;i++){ res = arrpf[i](10,20); } } MikroElektronika 208
mikroC PRO for dsPIC Function Pointers Function Pointers are pointers, i.e. variables, which point to the address of a function. // Define a function pointer int (*pt2Function) (float, char, char); Note: Thus functions and function pointers with different calling convention (argument order, arguments type or return type is different) are incompatible with each other. Assign an address to a Function Pointer It’s quite easy to assign the address of a function to a function pointer.
mikoC PRO for dsPIC //array of pointer to functions that receive two chars and returns int int (*arrpf[])(char,char) = { addC ,subC,mulC,divC,modC}; int res; char i; void main() { for (i=0;i<5;i++){ res = arrpf[i](10,20); } } Pointer Arithmetic Pointer arithmetic in the mikroC PRO for dsPIC30/33 and PIC24 is limited to: - assigning one pointer to another, - comparing two pointers, - comparing pointer to zero, - adding/subtracting pointer and an integer value, - subtracting two pointers.
mikroC PRO for dsPIC The following statements are true: &a[i] a[i] = = a + i *(a + i) According to these guidelines, it can be written: pa = &a[4]; x = *(pa + 3); // pa points to a[4] // x = a[7] /* ..
mikoC PRO for dsPIC Pointer Addition You can use operators +, ++, and += 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).
mikroC PRO for dsPIC Pointer Subtraction Similar to addition, you can use operators -, -- , and -= to subtract an integral value from a pointer. Also, you may subtract two pointers. The difference will be equal to the distance between two pointed addresses, in bytes.
mikoC PRO for dsPIC Also, a structure can contain previously defined structure types when declaring an instance of declared structure. Here is an example: /* Structure defining a dot: */ struct Dot {float x, y;}; /* Structure defining a circle: */ struct Circle { float r; struct Dot center; } o1, o2; /* declare variables o1 and o2 of Circle */ Note that the structure tag can be omitted, but then additional objects of this type cannot be declared elsewhere.
mikroC PRO for dsPIC Untagged Structures and Typedefs If the structure tag is omitted, an untagged structure is created. The untagged structures can be used to declare the identifiers in the comma-delimited member-declarator-list to be of the given structure type (or derived from it), but additional objects of this type cannot be declared elsewhere. It is possible to create a typedef while declaring a structure, with or without tag: /* With tag: */ typedef struct mystruct { ...
mikoC PRO for dsPIC Working with Structures Structures represent user-defined types. A set of rules regarding the application of structures is strictly defined. Assignment Variables of the same structured type may be assigned one to another by means of simple assignment operator (=). This will copy the entire contents of the variable to destination, regardless of the inner complexity of a given structure.
mikroC PRO for dsPIC Structure Member Access Structure and union members are accessed using the following two selection operators: - . (period) - -> (right arrow) The operator . is called the direct member selector and it is used to directly access one of the structure’s members. Suppose that the object s is of the struct type S and m is a member identifier of the type M declared in s, then the expression s.m // direct access to member m is of the type M, and represents the member object m in S.
mikoC PRO for dsPIC Accessing Nested Structures If the structure B contains a field whose type is the structure A, the members of A can be accessed by two applications of the member selectors: struct A { int j; double x; }; struct B { int i; struct A aa; double d; } s, *sptr; ... s.i = 3; s.aa.j = 2; sptr->d = 1.23; sptr->aa.x = 3.14; // // // // assign assign assign assign 3 to 2 to 1.23 3.
mikroC PRO for dsPIC Unions Union types are derived types sharing many of syntactic and functional features of structure types. The key difference is that a union members share the same memory space. Note: The mikroC PRO for PIC supports anonymous unions. Union Declaration Unions have the same declaration as structures, with the keyword union used instead of struct: union tag { member-declarator-list }; Unlike structures’ members, the value of only one of union’s members can be stored at any time.
mikoC PRO for dsPIC Anonymous Unions Anonymous unions are unions that are declared without tag or declarator: union { member-declarator-list }; Such union declarations do not declare types; they declare an unnamed objects. The name of each union member must be unique within the scope where the union is declared. In C, an anonymous union can have a tag; it cannot have declarators. Names declared in an anonymous union are used directly, like nonmember variables.
mikroC PRO for dsPIC Bit Fields Bit fields are specified numbers of bits that may or may not have an associated identifier. Bit fields offer a way of subdividing structures into named parts of user-defined sizes. Structures and unions can contain bit fields that can be up to 16 bits. You cannot take the address of a bit field. Note: If you need to handle specific bits of 8-bit variables (char and unsigned short) or registers, you don’t need to declare bit fields.
mikoC PRO for dsPIC Bit Fields Access Bit fields can be accessed in the same way as the structure members. Use direct and indirect member selector (. and ->). For example, we could work with our previously declared myunsigned like this: // Declare a bit field Value_For_PortB: myunsigned Value_For_PortB; // Declare a pointer to mybitfield type: mybitfield *TimerControl; void main() { TimerControl = (mybitfield *) (void *) &T2CON ; T2CON, so it can be assigned } // explicit casting of pointer to ...
mikroC PRO for dsPIC Standard Conversions Standard conversions are built in the mikroC PRO for dsPIC30/33 and PIC24. These conversions are performed automatically, whenever required in the program. They can also be explicitly required by means of the typecast operator (refer to the Explicit Typecasting). The basic rule of automatic (implicit) conversion is that the operand of simpler type is converted (promoted) to the type of more complex operand.
mikoC PRO for dsPIC Here are several examples of implicit conversion: 2 + 3.1 5 / 4 * 3. 3. * 5 / 4 /* → 2. + 3.1 → 5.1 */ /* → (5/4)*3. → 1*3. → 1.*3. → 3. */ /* → (3.*5)/4 → (3.*5.)/4 → 15./4 → 15./4. → 3.75 */ Pointer Conversions Pointer types can be converted to other pointer types using the typecasting mechanism: char *str; int *ip; str = (char *)ip; More generally, the cast type* will convert a pointer to type “pointer to type”.
mikroC PRO for dsPIC Declarations A declaration introduces one or several names to a program – it informs the compiler what the name represents, what its type is, what operations are allowed with it, etc. This section reviews concepts related to declarations: declarations, definitions, declaration specifiers, and initialization.
mikoC PRO for dsPIC Declarations and Declarators The declaration contains specifier(s) followed by one or more identifiers (declarators). The declaration begins with optional storage class specifiers, type specifiers, and other modifiers. The identifiers are separated by commas and the list is terminated by a semicolon. Declarations of variable identifiers have the following pattern: storage-class [type-qualifier] type var1 [=init1], var2 [=init2], ... ; where var1, var2,...
mikroC PRO for dsPIC Linkage Rules Local names have internal linkage; the same identifier can be used in different files to signify different objects. Global names have external linkage; identifier signifies the same object throughout all program files. If the same identifier appears with both internal and external linkage within the same file, the identifier will have internal linkage. Internal Linkage Rules 1. names having file scope, explicitly declared as static, have internal linkage 2.
mikoC PRO for dsPIC Auto The auto storage-class specifier declares an automatic variable (a variable with a local lifetime). An auto variable is visible only within the block in which it is declared. The auto storage-class specifier can only be applied to names of variables declared in a block or tonames of function parameters. However, these names have automatic storage by default. Therefore the auto storage class specifier is usually redundant in a data declaration.
mikroC PRO for dsPIC Type Qualifiers The type qualifiers const and volatile are optional in declarations and do not actually affect the type of declared object. Qualifier const The const qualifier is used to indicate that variable value cannot be changed. Its value is set at initialization. The mikroC PRO for dsPIC30/33 and PIC24 treats objects declared with the const qualifier the same as literals or preprocessor constants.
mikoC PRO for dsPIC For example: /* Let’s declare a synonym for “unsigned long int” */ typedef unsigned long int Distance; /* Now, synonym “Distance” can be used as type identifier: */ Distance i; // declare variable i of unsigned long int In the typedef declaration, as in any other declaration, several types can be declared at once. For example: typedef int *Pti, Array[10]; Here, Pti is a synonym for type “pointer to int”, and Array is a synonym for type “array of 10 int elements”.
mikroC PRO for dsPIC Here is an example of using asm instructions: unsigned myvar absolute 0x2678; unsigned long myvar1; const char msg[] = “Test” absolute 0x3652; void main() org 0x11234 { myvar = 5; myvar1 = 0xABCDEFAB; 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 mo
mikoC PRO for dsPIC Initialization The initial value of a declared object can be set at the time of declaration (initialization). A part of the declaration which specifies the initialization is called initializer. Initializers for globals and static objects must be constants or constant expressions. The initializer for an automatic object can be any legal expression that evaluates to an assignment-compatible value for the type of the variable involved.
mikroC PRO for dsPIC Functions Functions are central to C programming. Functions are usually defined as subprograms which return a value based on a number of input parameters. Return value of the function can be used in expressions – technically, function call is considered to be an expression like any other. C allows a function to create results other than its return value, referred to as side effects. Often, the function return value is not used at all, depending on the side effects.
mikoC PRO for dsPIC Function Prototypes A function can be defined only once in the program, but can be declared several times, assuming that the declarations are compatible. When declaring a function, the formal argument’s identifier does not have to be specified, but its type does. This kind of declaration, commonly known as the function prototype, allows better control over argument number, type checking and type conversions.
mikroC PRO for dsPIC Here is a sample function which depends on side effects rather than return value: /* function converts Descartes coordinates (x,y) to polar (r,fi): */ #include void polar(double *r = sqrt(x * x *fi = (x == 0 && return; /* this } x, double y, double *r, double *fi) { + y * y); y == 0) ? 0 : atan2(y, x); line can be omitted */ Functions reentrancy Functions reentrancy is allowed.
mikoC PRO for dsPIC // For example, Soft_UART_Read takes the pointer to error variable, // so it can change the value of an actual argument: Soft_UART_Read(&error); // The following code would be wrong; you would pass the value // of error variable to the function: Soft_UART_Read(error); Argument Conversions If a function prototype has not been previously declared, the mikroC PRO for dsPIC30/33 and PIC24 converts integral arguments to a function call according to the integral widening (expansion) rules des
mikroC PRO for dsPIC Ellipsis (‘...’) Operator The ellipsis (‘...’) consists of three successive periods with no whitespace intervening. An ellipsis can be used in the formal argument lists of function prototypes to indicate a variable number of arguments, or arguments with varying types. For example: void func (int n, char ch, ...
mikoC PRO for dsPIC Operators Operators are tokens that trigger some computation when applied to variables and other objects in an expression.
mikroC PRO for dsPIC Operators Precedence and Associativity There are 15 precedence categories, some of them contain only one operator. Operators in the same category have equal precedence. If duplicates of operators appear in the table, the first occurrence is unary and the second binary. Each category has an associativity rule: left-to-right (→), or right-to-left (←). In the absence of parentheses, these rules resolve a grouping of expressions with operators of equal precedence.
mikoC PRO for dsPIC Binary Arithmetic Operators Division of two integers returns an integer, while remainder is simply truncated: /* for example: */ 7 / 4; /* equals 1 */ 7 * 3 / 4; /* equals 5 */ /* but: */ 7. * 3. / 4.; /* equals 5.
mikroC PRO for dsPIC Relational Operators Use relational operators to test equality or inequality of expressions. If an expression evaluates to be true, it returns 1; otherwise it returns 0. All relational operators associate from left to right.
mikoC PRO for dsPIC Bitwise Operators Use the bitwise operators to modify individual bits of numerical operands. Bitwise operators associate from left to right. The only exception is the bitwise complement operator ~ which associates from right to left.
mikroC PRO for dsPIC /* Similarly: */ 0x1234 | 0x5678; 0x1234 ^ 0x5678; ~ 0x1234; /* equals 0x567C */ /* equals 0x444C */ /* equals 0xEDCB */ Note: Operator & can also be a pointer reference operator. Refer to Pointers for more information. Bitwise Shift Operators Binary operators << and >> move the bits of the left operand by a number of positions specified by the right operand, to the left or right, respectively. Right operand has to be positive.
mikoC PRO for dsPIC Logical Operators Operands of logical operations are considered true or false, that is non-zero or zero. Logical operators always return 1 or 0. Operands in a logical expression must be of scalar type. Logical operators && and || associate from left to right. Logical negation operator ! associates from right to left.
mikroC PRO for dsPIC Logical vs. Bitwise Be aware of the principle difference between how bitwise and logical operators work. For example: 0222222 & 0555555 0222222 && 0555555 /* equals 000000 */ /* equals 1 */ ~ 0x1234 ! 0x1234 /* equals 0xEDCB */ /* equals 0 */ Conditional Operator ? : The conditional operator ? : is the only ternary operator in C. Syntax of the conditional operator is: expression1 ? expression2 : expression3 The expression1 is evaluated first.
mikoC PRO for dsPIC Assignment Operators Unlike many other programming languages, C treats value assignment as operation (represented by an operator) rather than instruction. Simple Assignment Operator For a common value assignment, a simple assignment operator (=) is used: expression1 = expression2 The expression1 is an object (memory location) to which the value of expression2 is assigned. Operand expression1 has to be lvalue and expression2 can be any expression.
mikroC PRO for dsPIC 4. Either expression1 or expression2 is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void. The type pointed to by left has all qualifiers of the type pointed to by right. 5. expression1 is a pointer and expression2 is a null pointer constant. Unary Operators Unary operators are operators that take exactly one argument.
mikoC PRO for dsPIC Unary Logical Operator The ! (logical negation) operator produces the value 0 if its operand is true (nonzero) and the value 1 if its operand is false (0). Operator ! Operation Precedence logical negation 14 The following two expressions are equivalent: !right; right == 0; Unary Bitwise Operator The result of the ~ (bitwise negation) operator is the bitwise complement of the operand.
mikroC PRO for dsPIC Sizeof Operator The prefix unary operator sizeof returns an integer constant that represents the size of memory space (in bytes) used by its operand (determined by its type, with some exceptions). The operator sizeof can take either a type identifier or an unary expression as an operand. You cannot use sizeof with expressions of function type, incomplete types, parenthesized names of such types, or with lvalue that designates a bit field object.
mikoC PRO for dsPIC Expressions Expression is a sequence of operators, operands, and punctuators that specifies a computation. Formally, expressions are defined recursively: subexpressions can be nested without formal limit. However, the compiler will report an out-ofmemory error if it can’t compile an expression that is too complex. In ANSI C, the primary expressions are: constant (also referred to as literal), identifier, and (expression), defined recursively.
mikroC PRO for dsPIC Note Do not confuse comma operator (sequence operator) with comma punctuator which separates elements in a function argument list and initializator lists. To avoid ambiguity with commas in function argument and initializer lists, use parentheses. For example, func(i, (j = 1, j + 4), k); calls the function func with three arguments (i, 5, k), not four. Statements Statements specify a flow of control as the program executes.
mikoC PRO for dsPIC Expression Statements Any expression followed by a semicolon forms an expression statement: expression; The mikroC PRO for dsPIC30/33 and PIC24 executes an expression statement by evaluating the expression. All side effects from this evaluation are completed before the next statement starts executing. Most of expression statements are assignment statements or function calls. A null statement is a special case, consisting of a single semicolon (;).
mikroC PRO for dsPIC Note: #if and #else preprocessor statements (directives) look similar to if and else statements, but have very different effects. They control which source file lines are compiled and which are ignored. Switch Statement The switch statement is used to pass control to a specific program branch, based on a certain condition. The syntax of the switch statement is: switch (expression) { case constant-expression_1 : statement_1; . . .
mikoC PRO for dsPIC Nested switch Conditional switch statements can be nested – labels case and default are then assigned to the innermost enclosing switch statement. Iteration Statements (Loops) Iteration statements allows to loop a set of statements. There are three forms of iteration statements in the mikroC PRO for dsPIC30/33 and PIC24: - while - do - for While Statement The while keyword is used to conditionally iterate a statement.
mikroC PRO for dsPIC Note that do is the only control structure in C which explicitly ends with semicolon (;). Other control structures end with statement, which means that they implicitly include a semicolon or closing brace. Here is an example of calculating scalar product of two vectors, using the do statement: s = 0; i = 0; do { s += a[i] * b[i]; i++; } while ( i < n ); For Statement The for statement implements an iterative loop.
mikoC PRO for dsPIC Jump Statements The jump statement, when executed, transfers control unconditionally. There are four such statements in the mikroC PRO for dsPIC30/33 and PIC24: - break - continue - goto - return Break and Continue Statements Break Statement Sometimes it is necessary to stop the loop within its body. Use the break statement within loops to pass control to the first statement following the innermost switch, for, while, or do block.
mikroC PRO for dsPIC Goto Statement The goto statement is used for unconditional jump to a local label — for more information on labels, refer to Labeled Statements. The syntax of the goto statement is: goto label_identifier; This will transfer control to the location of a local label specified by label_identifier. The label_identifier has to be a name of the label within the same function in which the goto statement is. The goto line can come before or after the label.
mikoC PRO for dsPIC Compound Statements (Blocks) The compound statement, or block, is a list (possibly empty) of statements enclosed in matching braces { }. Syntactically, the block can be considered to be a single statement, but it also plays a role in the scoping of identifiers. An identifier declared within the block has a scope starting at the point of declaration and ending at the closing brace. Blocks can be nested to any depth up to the limits of memory.
mikroC PRO for dsPIC For more information on including files with the #include directive, refer to File Inclusion. The mikroC PRO for dsPIC30/33 and PIC24 supports standard preprocessor directives: # (null directive) #define #elif #else #endif #error Note: #if #ifdef #ifndef #include #line #undef For the time being only funcall pragma is supported.
mikoC PRO for dsPIC A macro won’t be expanded during its own expansion (so #define MACRO MACRO won’t expand indefinitely). Here is an example: /* Here are some simple macros: */ #define ERR_MSG “Out of range!” #define EVERLOOP for( ; ; ) /* which we could use like this: */ main() { EVERLOOP { ... if (error) { Lcd_Out_Cp(ERR_MSG); break; } ...
mikroC PRO for dsPIC A macro call results in two sets of replacements. First, the macro identifier and the parenthesis-enclosed arguments are replaced by the token sequence. Next, any formal arguments occurring in the token sequence are replaced by the corresponding real arguments appearing in actual_arg_list. Like with simple macro definitions, rescanning occurs to detect any embedded macro identifiers eligible for expansion.
mikoC PRO for dsPIC The preprocessor removes the #include line and replaces it with the entire text of a header file at that point in the source code. The placement of #include can therefore influence the scope and duration of any identifiers in the included file. The difference between these two formats lies in searching algorithm employed in trying to locate the include file.
mikroC PRO for dsPIC Preprocessor Operators The # (pound sign) is a preprocessor directive when it occurs as the first non-whitespace character on a line. Also, # and ## perform operator replacement and merging during the preprocessor scanning phase. Operator # In C preprocessor, a character sequence enclosed by quotes is considered a token and its content is not analyzed. This means that macro names within quotes are not expanded.
mikoC PRO for dsPIC Conditional Compilation Conditional compilation directives are typically used to make source programs easy to change and easy to compile in different execution environments. The mikroC PRO for dsPIC30/33 and PIC24 supports conditional compilation by replacing the appropriate source-code lines with a blank line. All conditional compilation directives must be completed in the source or include file in which they have begun.
mikroC PRO for dsPIC Directives #ifdef and #ifndef The #ifdef and #ifndef directives can be used anywhere #if can be used and they can test whether an identifier is currently defined or not. The line #ifdef identifier has exactly the same effect as #if 1 if identifier is currently defined, and the same effect as #if 0 if identifier is currently undefined. The other directive, #ifndef, tests true for the “not-defined” condition, producing the opposite results.
CHAPTER 9 mikoC PRO for dsPIC mikroC PRO for dsPIC30/33 and PIC24 Libraries mikroC 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 mikroC PRO for dsPIC30/33 and PIC24 Libraries in you project.
mikroC PRO for dsPIC 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 - Software SPI Libr
mikoC PRO for dsPIC Standard ANSI C Libraries - ANSI C Ctype Library - ANSI C Math Library - ANSI C Stdlib Library - ANSI C String Library Miscellaneous Libraries - Button Library - Conversions Library - PrintOut Library - Setjmp Library - Sprint Library - Time Library - Trigonometry Library - See also Built-in Routines.
mikroC PRO for dsPIC Hardware Libraries - ADC Library - CAN Library - CANSPI Library - Compact Flash Library - DSP Libraries - 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 - S
mikoC PRO for dsPIC Library Routines - ADCx_Init - ADCx_Init_Advanced - ADCx_Get_Sample - ADCx_Read - ADC_Set_Active ADCx_Init Prototype void ADCx_Init(); Description This routines configures ADC module to work with default settings. The internal ADC module is set to: - single channel conversion - 10-bit conversion resolution - unsigned integer data format - auto-convert - VRef+ : AVdd, VRef- : AVss - instruction cycle clock - conversion clock : 32*Tcy - auto-sample time : 31TAD Parameters None.
mikroC PRO for dsPIC ADCx_Init_Advanced Prototype // dsPIC30F and PIC24FJ prototype void ADC1_Init_Advanced(unsigned Reference); // dsPIC33FJ and PIC24HJ prototype void ADCx_Init_Advanced(unsigned ADCMode, unsigned Reference); 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.
mikoC PRO for dsPIC ADCx_Get_Sample Prototype unsigned ADCx_Get_Sample(unsigned channel); Description The function enables ADC module and reads the specified analog channel input. Parameters - channel represents the channel from which the analog value is to be acquired. Returns Requires Example Notes 10-bit or 12-bit (depending on selected mode by ADCx_Init_Advanced or MCU) unsigned value from the specified channel. - The MCU with built-in ADC module.
mikroC PRO for dsPIC ADC_Set_Active Prototype void ADC_Set_Active(unsigned (*adc_gs)(unsigned)); Description Sets active ADC module. Parameters Parameters: Returns Requires - adc_gs: ADCx_Get_Sample handler. Nothing. 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 Notes // Activate ADC2 module ADC_Set_Active(ADC2_Get_Sample); None.
mikoC PRO for dsPIC ADC HW connection MikroElektronika 274
mikroC PRO for dsPIC CAN Library The mikroC 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.
mikoC PRO for dsPIC CANxSetOperationMode Prototype void CANxSetOperationMode(unsigned int mode, unsigned int WAIT); 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.
mikroC PRO for dsPIC CANxInitialize Prototype void CANxInitialize(unsigned int SJW, unsigned int BRP, unsigned int PHSEG1, unsigned int PHSEG2, unsigned int PROPSEG, unsigned int CAN_CONFIG_FLAGS); Description Initializes the CAN module.
mikoC PRO for dsPIC CANxSetBaudRate Prototype void CANxSetBaudRate(unsigned int SJW, unsigned int BRP, unsigned int PHSEG1, unsigned int PHSEG2, unsigned int PROPSEG, unsigned int CAN_CONFIG_FLAGS); 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.
mikroC PRO for dsPIC CANxSetMask Prototype void CANxSetMask(unsigned int CAN_MASK, long val, unsigned int CAN_CONFIG_ FLAGS); 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. This value is bit-adjusted to appropriate buffer mask registers - CAN_CONFIG_FLAGS: selects type of message to filter.
mikoC PRO for dsPIC CANxSetFilter Prototype void CANxSetFilter(unsigned int CAN_FILTER, long val, unsigned int CAN_ CONFIG_FLAGS); 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. This value is bit-adjusted to appropriate filter registers - CAN_CONFIG_FLAGS: selects type of message to filter.
mikroC PRO for dsPIC CANxRead Prototype unsigned int CANxRead(unsigned long *id, char *data_, unsigned int *dataLen, unsigned int *CAN_RX_MSG_FLAGS); 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 retrieved and
mikoC PRO for dsPIC CANxWrite Prototype unsigned int CANxWrite(long id, char *data_, unsigned int DataLen, unsigned int CAN_TX_MSG_FLAGS); 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC _CAN_CONFIG_MSG_BITS _CAN_CONFIG_ALL_MSG _CAN_CONFIG_VALID_XTD_MSG _CAN_CONFIG_VALID_STD_MSG _CAN_CONFIG_ALL_VALID_MSG = = = = = 0x60, 0xFF, 0xDF, 0xBF, 0x9F; // // // // X11XXXXX X10XXXXX X01XXXXX X00XXXXX You may use bitwise AND (&) to form config byte out of these values. For example: 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; ...
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC CAN_FILTER Constants CAN_FILTER constants define filter codes. Function CANxSetFilter expects one of these as its argument: Copy Code To Clipboard const unsigned int _CAN_FILTER_B1_F1 _CAN_FILTER_B1_F2 _CAN_FILTER_B2_F1 _CAN_FILTER_B2_F2 _CAN_FILTER_B2_F3 _CAN_FILTER_B2_F4 = = = = = = 0, 1, 2, 3, 4, 5; Library Example The example demonstrates CAN protocol. The 1st node initiates the communication with the 2nd node by sending some data to its address.
mikroC PRO for dsPIC RxTx_Data[0] = 9; CAN2Initialize(1,3,3,3,1,Can_Init_Flags); // set initial data to be sent // initialize CAN2 CAN2SetOperationMode(_CAN_MODE_CONFIG,0xFF); // set CONFIGURATION mode CAN2SetMask(_CAN_MASK_B1,-1,_CAN_CONFIG_MATCH_MSG_TYPE & _CAN_CONFIG_XTD_MSG); // set all mask1 bits to ones CAN2SetMask(_CAN_MASK_B2,-1,_CAN_CONFIG_MATCH_MSG_TYPE & _CAN_CONFIG_XTD_MSG); // set all mask2 bits to ones CAN2SetFilter(_CAN_FILTER_B2_F3,3,_CAN_CONFIG_XTD_MSG); // set id of filter B1_F1 to 3 C
mikoC PRO for dsPIC Code for the second CAN node: Copy Code To Clipboard unsigned int Can_Init_Flags, Can_Send_Flags, Can_Rcv_Flags; // can flags unsigned int Rx_Data_Len; // received data length in bytes char RxTx_Data[8]; // can rx/tx data buffer char Msg_Rcvd; // reception flag unsigned long Tx_ID, Rx_ID; // can rx and tx ID void main() { ADPCFG = 0xFFFF; PORTB = 0; TRISB = 0; Can_Init_Flags = 0; Can_Send_Flags = 0; Can_Rcv_Flags = 0; // // clear flags // Can_Send_Flags = _CAN_TX_PRIORITY_0 & _CAN_TX_X
mikroC PRO for dsPIC HW Connection Example of interfacing CAN transceiver with MCU and CAN bus 289 MikroElektronika
mikoC PRO for dsPIC CANSPI Library The SPI module is available with a number of the dsPIC30/33 and PIC24 MCUs. The mikroC 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. In the mikroC PRO for dsPIC30/33 and PIC24, each routine of the CAN library has its own CANSPI counterpart with identical syntax. For more information on Controller Area Network, consult the CAN Library.
mikroC PRO for dsPIC Library Routines - CANSPISetOperationMode - CANSPIGetOperationMode - CANSPIInitialize - CANSPISetBaudRate - CANSPISetMask - CANSPISetFilter - CANSPIRead - CANSPIWrite CANSPISetOperationMode Prototype void CANSPISetOperationMode(char mode, char WAIT); Description Sets the CANSPI module to requested mode. Parameters mode: CANSPI module operation mode. Valid values: CANSPI_OP_MODE constants. See CANSPI_ OP_MODE constants. WAIT: CANSPI mode switching verification request.
mikoC PRO for dsPIC CANSPIGetOperationMode Prototype char CANSPIGetOperationMode(); 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.
mikroC PRO for dsPIC Requires Global variables : - CanSpi_CS: Chip Select line - CanSpi_Rst: Reset line - CanSpi_CS_Direction: Direction of the Chip Select pin - CanSpi_Rst_Direction: Direction of the Reset pin must be defined before using this function. The CANSPI routines are supported only by MCUs with the SPI module. The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines. MCU has to be properly connected to mikroElektronika’s CANSPI Extra Board or similar hardware.
mikoC PRO for dsPIC CANSPISetBaudRate Prototype Returns void CANSPISetBaudRate(char SJW, char BRP, char PHSEG1, char PHSEG2, char PROPSEG, char CANSPI_CONFIG_FLAGS); Nothing. Description Sets the CANSPI module baud rate. Due to complexity of the CAN protocol, you can not simply force a bps value. Instead, use this function when the CANSPI module is in Config mode. SAM, SEG2PHTS and WAKFIL bits are set according to CANSPI_CONFIG_FLAGS value. Refer to datasheet for details.
mikroC PRO for dsPIC CANSPISetMask Prototype void CANSPISetMask(unsigned short CANSPI_MASK, long value, unsigned short CANSPI_CONFIG_FLAGS); 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.
mikoC PRO for dsPIC CANSPISetFilter Prototype void CANSPISetFilter(unsigned short CANSPI_FILTER, long value, unsigned short CANSPI_CONFIG_FLAGS); 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.
mikroC PRO for dsPIC CANSPIRead Prototype unsigned short CANSPIRead(long *id, unsigned short *data, unsigned short *datalen, unsigned short *CANSPI_RX_MSG_FLAGS); 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 the dataLen paramete
mikoC PRO for dsPIC CANSPIWrite Prototype unsigned short CANSPIWrite(long id, unsigned short *data, unsigned short datalen, unsigned short CANSPI_TX_MSG_FLAGS); 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 - CANSPI_TX_MSG_FLAGS: message flags.
mikroC PRO for dsPIC Copy Code To Clipboard const unsigned int _CANSPI_MODE_BITS _CANSPI_MODE_NORMAL _CANSPI_MODE_SLEEP _CANSPI_MODE_LOOP _CANSPI_MODE_LISTEN _CANSPI_MODE_CONFIG = = = = = = 0xE0, 0x00, 0x20, 0x40, 0x60, 0x80; // Use this to access opmode bits CANSPI_CONFIG_FLAGS Constants The CANSPI_CONFIG_FLAGS constants define flags related to the CANSPI module configuration.
mikoC PRO for dsPIC You may use bitwise AND (&) to form config byte out of these values. For example: Copy Code To Clipboard init = _CANSPI_CONFIG_SAMPLE_THRICE & _CANSPI_CONFIG_PHSEG2_PRG_ON & _CANSPI_CONFIG_STD_MSG & _CANSPI_CONFIG_DBL_BUFFER_ON & _CANSPI_CONFIG_VALID_XTD_MSG & _CANSPI_CONFIG_LINE_FILTER_OFF; ...
mikroC PRO for dsPIC Copy Code To Clipboard const unsigned int _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 = = = = = = = 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, // Use this to access filter bits = = = = = 0x08, // Set if Overflowed else cleared 0x10, // Set if invalid else cleared 0x20, // Set if
mikoC PRO for dsPIC Library Example This is a simple demonstration of CANSPI Library routines usage. First node initiates the communication with the second node by sending some data to its address. The second node responds by sending back the data incremented by 1. First node then does the same and sends incremented data back to second node, etc.
mikroC PRO for dsPIC CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF); // Set NORMAL mode RxTx_Data[0] = 9; // Set initial data to be sent Tx_ID = 12111; // Set transmit ID CANSPIWrite(Tx_ID, RxTx_Data, 1, Can_Send_Flags); // Send initial message while(1) { // Endless loop Msg_Rcvd = CANSPIRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // Receive message if ((Rx_ID == 3u) && Msg_Rcvd) { // If message received check id PORTB = RxTx_Data[0]; // Id correct, output data at PORTB RxTx_Data[0]++;
mikoC PRO for dsPIC _CANSPI_CONFIG_DBL_BUFFER_ON & _CANSPI_CONFIG_VALID_XTD_MSG & _CANSPI_CONFIG_LINE_FILTER_OFF; SPI1_Init(); CANSPIInitialize(1,3,3,3,1,Can_Init_Flags); // Initialize SPI1 module // Initialize CANSPI module CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF); // Set CONFIGURATION mode CANSPISetMask(_CANSPI_MASK_B1,-1,_CANSPI_CONFIG_XTD_MSG); // Set all mask1 bits to ones CANSPISetMask(_CANSPI_MASK_B2,-1,_CANSPI_CONFIG_XTD_MSG); // Set all mask2 bits to ones CANSPISetFilter(_CANSPI_FILTER_
mikroC PRO for dsPIC HW Connection Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface 305 MikroElektronika
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC External dependencies of Compact Flash Library The following variables must be defined in all projects using Description : Compact Flash Library: Example : extern sfr unsigned int CF_ Compact Flash Data Port. Data_Port; char CF_Data_Port at PORTF; extern sfr sbit CF_WE; Write Enable signal line. sbit CF_WE at RD6_bit; extern sfr sbit CF_CD1; Chip Detect signal line. extern sfr sbit CF_A2; Address pin 2. extern sfr sbit CF_A0; Address pin 0.
mikoC PRO for dsPIC Library Routines - Cf_Init - Cf_Detect - Cf_Enable - Cf_Disable - Cf_Read_Init - Cf_Read_Byte - Cf_Write_Init - Cf_Write_Byte - Cf_Read_Sector - Cf_Write_Sector Routines for file handling: - Cf_Fat_Init - Cf_Fat_QuickFormat - Cf_Fat_Assign - Cf_Fat_Reset - Cf_Fat_Read - Cf_Fat_Rewrite - Cf_Fat_Append - Cf_Fat_Delete - Cf_Fat_Write - Cf_Fat_Set_File_Date - Cf_Fat_Get_File_Date - Cf_Fat_Get_File_Date_Modified - Cf_Fat_Get_File_Size - Cf_Fat_Get_Swap_File The following routine is for the in
mikroC PRO for dsPIC Cf_Init Prototype void Cf_Init(); Description Initializes ports appropriately for communication with CF card. Parameters None. Returns Nothing.
mikoC PRO for dsPIC Cf_Detect Prototype unsigned int Cf_Detect(); 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: do asm nop; while (!Cf_Detect()); dsPIC30 family MCU and CF card voltage levels are different.
mikroC PRO for dsPIC Cf_Read_Init Prototype void Cf_Read_Init(unsigned long address, unsigned short sector_count); 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.
mikoC PRO for dsPIC Cf_Write_Byte Prototype void Cf_Write_Byte(unsigned short data_); Description Writes a byte to Compact Flash sector buffer location currently pointed to by writing pointers. These pointers will be autoicremented upon reading. When sector buffer is full, its contents will be transfered to appropriate flash memory sector. Parameters - data_: byte to be written. Returns Nothing. Requires The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.
mikroC PRO for dsPIC Cf_Fat_Init Prototype unsigned int Cf_Fat_Init(); 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()) { ... } // Init the FAT library None.
mikoC PRO for dsPIC Cf_Fat_Assign Prototype unsigned int Cf_Fat_Assign(char *filename, char file_cre_attr); 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.
mikroC PRO for dsPIC Cf_Fat_Reset Prototype void Cf_Fat_Reset(unsigned long *size); 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. Example Notes File must be previously assigned. See Cf_Fat_Assign. unsigned long size; ... Cf_Fat_Reset(size); None.
mikoC PRO for dsPIC Cf_Fat_Rewrite Prototype void 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. Example Notes The file must be previously assigned. See Cf_Fat_Assign. // open file for writing Cf_Fat_Rewrite(); None.
mikroC PRO for dsPIC Cf_Fat_Write Prototype void Cf_Fat_Write(char *fdata, unsigned data_len); 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. Example Notes File must be open for writing.
mikoC PRO for dsPIC Cf_Fat_Get_File_Date Prototype void Cf_Fat_Get_File_Date(unsigned int *year, unsigned short *month, unsigned short *day, unsigned short *hours, unsigned short *mins); 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.
mikroC PRO for dsPIC Cf_Fat_Get_File_Size Prototype unsigned long Cf_Fat_Get_File_Size(); 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 Notes unsigned long my_file_size; ... my_file_size = Cf_Fat_Get_File_Size(); None.
mikoC PRO for dsPIC Parameters Returns Requires Example Notes Bit Mask Description 0 0x01 Read Only 1 0x02 Hidden 2 0x04 System 3 0x08 Volume Label 4 0x10 Subdirectory 5 0x20 Archive 6 0x40 Device (internal use only, never found on disk) 7 0x80 Not used - Number of the start sector for the newly created swap file, if there was enough free space on CF card to create file of required size. - 0 - otherwise. CF card and CF library must be initialized for file operations.
mikroC PRO for dsPIC Library Example The following example writes 512 bytes at sector no.620, and then reads the data and sends it over UART1 for a visual check. Hardware configurations in this example are made for the dsPICPRO2 board and dsPIC30F6014A.
mikoC PRO for dsPIC SignalPort = 0x03; Delay_ms(1000); for (i=0; i<=511; i++) Cf_Write_Byte(i); // Notify that write has started SignalPort = 0x07; Delay_ms(1000); // Notify that write end and read start Cf_Read_Init(590,1); // // // // // // for (i=0; i<=511; i++) { SignalPort = Cf_Read_Byte(); Delay_ms(5); } Delay_ms(1000); // Write 512 bytes to sector 590 Initialize read from sector address 590 for 1 sector Read 512 bytes from sector address 590 Read one byte at time and display readings on signa
mikroC PRO for dsPIC HW Connection Pin diagram of CF memory card 323 MikroElektronika
mikoC PRO for dsPIC ECAN Library The mikroC 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.
mikroC PRO for dsPIC ECANxDmaChannelInit Prototype unsigned ECANxDmaChannelInit(unsigned DmaChannel, unsigned ChannelDir, void *DmaRamBuffAdd); 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.
mikoC PRO for dsPIC ECANxGetOperationMode Prototype unsigned int ECANxGetOperationMode(); 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.
mikroC PRO for dsPIC ECANxInitialize Prototype void ECANxInitialize(unsigned int SJW, unsigned int BRP, unsigned int PHSEG1, unsigned int PHSEG2, unsigned int PROPSEG, unsigned int ECAN_CONFIG_ FLAGS); Description Initializes the ECAN module.
mikoC PRO for dsPIC ECANxSelectTxBuffers Prototype unsigned ECANxSelectTxBuffers(unsigned txselect); 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.
mikroC PRO for dsPIC ECANxFilterEnable Prototype void ECANxFilterEnable(unsigned flten); 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.
mikoC PRO for dsPIC ECANxSetBaudRate Prototype void ECANxSetBaudRate(unsigned int SJW, unsigned int BRP, unsigned int PHSEG1, unsigned int PHSEG2, unsigned int PROPSEG, unsigned int ECAN_CONFIG_ FLAGS); 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.
mikroC PRO for dsPIC ECANxSetMask Prototype void ECANxSetMask(unsigned int ECAN_MASK, long val, unsigned int ECAN_ CONFIG_FLAGS); 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.
mikoC PRO for dsPIC ECANxSetFilter Prototype void ECANxSetFilter(unsigned int ECAN_FILTER, long val, unsigned int ECAN_ FILTER_MASK, unsigned int ECAN_FILTER_RXBUFF, unsigned int ECAN_CONFIG_ FLAGS); 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.
mikroC PRO for dsPIC ECANxRead Prototype unsigned int ECANxRead(unsigned long *id, char *data, unsigned int *dataLen, unsigned int *ECAN_RX_MSG_FLAGS); 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 dataLen pointer - Message flags are r
mikoC PRO for dsPIC ECANxWrite Prototype unsigned int ECANxWrite(long id, char *Data, unsigned int DataLen, unsigned int ECAN_TX_MSG_FLAGS); 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..8 - ECAN_TX_MSG_FLAGS: message flags.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC 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); // initialize ECAN1 ECAN_TX_MSG_FLAGS Constants ECAN_TX_MSG_FLAGS are flags related to transmission of ECAN message.
mikroC PRO for dsPIC Copy Code To Clipboard const unsigned int _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 = = = = = = = = = = = = = = = = = 0x000F, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
mikoC PRO for dsPIC Copy Code To Clipboard const unsigned int _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 = = = = = = = = = = = = = = = = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15; ECAN_RX_BUFFER Constants The ECAN_RX_BUFFER constants define RX bufer codes codes.
mikroC PRO for dsPIC 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. Code for the first ECAN node: Copy Code To Clipboard #include “ECAN_Defs.
mikoC PRO for dsPIC IEC2bits.C1IE = 1; C1INTEbits.TBIE = 1; C1INTEbits.
mikroC PRO for dsPIC ECAN1Write(Tx_ID, RxTx_Data, 1, Can_Send_Flags); // send initial message while (1) { // endless loop Msg_Rcvd = ECAN1Read(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // receive message if ((Rx_ID == 3u) && Msg_Rcvd) { // if message received check id PORTB = RxTx_Data[0]; // id correct, output data at PORTB RxTx_Data[0]++ ; // increment received data Delay_ms(10); ECAN1Write(Tx_ID, RxTx_Data, 1, Can_Send_Flags); // send incremented data back } } } Code for the second ECAN node:
mikoC PRO for dsPIC /* Enable ECAN1 Interrupt */ IEC2bits.C1IE = 1; C1INTEbits.TBIE = 1; C1INTEbits.
mikroC PRO for dsPIC HW Connection Example of interfacing ECAN transceiver with MCU and bus EEPROM Library EEPROM data memory is available with a number of dsPIC30 family and some PIC24 family MCU's. The mikroC PRO for dsPIC30/33 and PIC24 includes a library for comfortable work with MCU's internal EEPROM. Important : Only PIC24F08KA102 and PIC24F16KA102 of PIC24 family of MCUs have EEPROM memory.
mikoC PRO for dsPIC EEPROM_Erase Prototype void EEPROM_Erase(unsigned long address); 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 Notes unsigned long eeAddr = 0x7FFC80; ... EEPROM_Erase(eeAddr); 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.
mikroC PRO for dsPIC EEPROM_Write Prototype void EEPROM_Write(unsigned long address, unsigned int data_); 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 Notes unsigned int eeWrite = 0xAAAA; unsigned long wrAddr = 0x7FFC30; ... EEPROM_Write(wrAddr, eeWrite); Specified memory location will be erased before writing starts.
mikoC PRO for dsPIC ADPCFG = 0xFFFF; // Disable analog inputs TRISB = 0; LATB = 0xFFFF; eeAddr = 0x7FFC00; eeData = 0; // PORTB as output // Start address of EEPROM // Data to be written while (eeData <= 0x00FF) { EEPROM_Write(eeAddr, eeData++); while(WR_bit); LATB = EEPROM_Read(eeAddr); // // // // // eeAddr += 2; } Delay_ms(30); Delay_ms(1000); eeData = 0xAAAA; for (i=0; i<16; i++){ dArr[i] = eeData; eeData = ~eeData; } // Wait 1 second.
mikroC PRO for dsPIC Epson S1D13700 Graphic Lcd Library The mikroC 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.
mikoC PRO for dsPIC Library Routines - S1D13700_Init - S1D13700_Write_Command - S1D13700_Write_Parameter - S1D13700_Read_Parameter - S1D13700_Fill - S1D13700_GrFill - S1D13700_TxtFill - S1D13700_Display_GrLayer - S1D13700_Display_TxtLayer - S1D13700_Set_Cursor - S1D13700_Display_Cursor - S1D13700_Write_Char - S1D13700_Write_Text - S1D13700_Dot - S1D13700_Line - S1D13700_H_Line - S1D13700_V_Line - S1D13700_Rectangle - S1D13700_Box - S1D13700_Rectangle_Round_Edges - S1D13700_Rectangle_Round_Edges_Fill - S1D13
mikroC PRO for dsPIC S1D13700_Init Prototype void S1D13700_Init(unsigned int width, unsigned char height); Returns Nothing. Description Initializes S1D13700 Graphic Lcd controller. Parameters : Requires - width: width of the Glcd panel. - height: height of the Glcd panel. Global variables : - S1D13700_Data_Port: Data Bus Port. - S1D13700_WR: Write signal pin. - S1D13700_RD: Read signal pin. - S1D13700_A0: Command/Data signal pin. - S1D13700_RES: Reset signal pin.
mikoC PRO for dsPIC S1D13700_Write_Command Prototype void S1D13700_Write_Command(char command); 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_OFF Turn the display off. S1D13700_DISP_ON Turn the display on. S1D13700_SCROLL Setup text and graphics address regions.
mikroC PRO for dsPIC S1D13700_Write_Parameter Prototype void S1D13700_Write_Parameter(char parameter); Returns Nothing. Description Writes a parameter to S1D13700 controller. Parameters : Requires - parameter: parameter to be written. Glcd module needs to be initialized. See the S1D13700_Init routine. Previously, a command must be sent through S1D13700_Write_Command routine.
mikoC PRO for dsPIC S1D13700_GrFill Prototype void S1D13700_GrFill(char d); 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 void S1D13700_TxtFill(char d); Returns Nothing. Description Fill current text panel with appropriate value (0 to clear).
mikroC PRO for dsPIC S1D13700_Display_TxtLayer Prototype void S1D13700_Display_TxtLayer(char mode); 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 S1D13700_LAYER_FLASH_2Hz S1D13700_LAYER_FLASH_16Hz Turn on graphic layer. Turn on graphic layer and flash it at the rate of 2 Hz. Turn on graphic layer and flash it at the rate of 16 Hz.
mikoC PRO for dsPIC S1D13700_Display_Cursor Prototype void S1D13700_Display_Cursor(char mode); 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 S1D13700_CURSOR_FLASH_16Hz Turn on graphic layer and flash it at the rate of 2 Hz. Turn on graphic layer and flash it at the rate of 16 Hz.
mikroC PRO for dsPIC S1D13700_Write_Text Prototype Returns void S1D13700_Write_Text(unsigned char *str, unsigned char x, unsigned char y, char mode); 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.
mikoC PRO for dsPIC S1D13700_Line Prototype Returns void S1D13700_Line(unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, unsigned char pcolor); 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 S1D13700_BLACK S1D13700_WHITE Description Black color. White color.
mikroC PRO for dsPIC S1D13700_V_Line Prototype Returns void S1D13700_V_Line(unsigned int y_start, unsigned int y_end, unsigned int x_pos, unsigned short color); 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.
mikoC PRO for dsPIC S1D13700_Box Prototype Returns void S1D13700_Rectangle(unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, unsigned char pcolor); 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.
mikroC PRO for dsPIC S1D13700_Rectangle_Round_Edges_Fill Prototype Returns void S1D13700_Rectangle_Round_Edges_Fill(unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, unsigned short round_radius, unsigned short color); 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.
mikoC PRO for dsPIC S1D13700_Circle_Fill Prototype Returns void S1D13700_Circle_Fill(unsigned int x_center, unsigned int y_center, unsigned int radius, unsigned short color); 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 S1D13700_BLACK S1D13700_WHITE Description Black color. White color.
mikroC PRO for dsPIC S1D13700_PartialImage Prototype Returns void S1D13700_PartialImage(unsigned int x_left, unsigned int y_top, unsigned int width, unsigned int height, unsigned int picture_width, unsigned int picture_height, code const unsigned short * image); Nothing. Description Displays a partial area of the image on a desired location. Parameters : - x_left: x coordinate of the desired location (upper left coordinate). - y_top: y coordinate of the desired location (upper left coordinate).
mikoC PRO for dsPIC 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".
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC FLASH_Erase32 Prototype void FLASH_Erase32(unsigned long address); 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. Example //--- erase the 32-instruction block, starting from address 0x006000 FLASH_Erase32(0x006000); Notes The user should take care about the address alignment (see the explanation at the beginning of this page).
mikroC PRO for dsPIC FLASH_Write_Compact Prototype void FLASH_Write_Compact(unsigned bytes); long address, void *data_, unsigned 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.
mikoC PRO for dsPIC FLASH_Write_Loadlatch4 Prototype void 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.
mikroC PRO for dsPIC FLASH_Write_Loadlatch4_Compact Prototype void FLASH_Write_Loadlatch4_Compact(); Description Loads the current RTSP write latch with data (4 instructions, 8 addresses, 12 bytes). The data is filled in the “compact” mode. Parameters None. Returns Nothing. Requires The block to be written to must be erased first, either from the user code FLASH_Erase32, or during the programming of MCU.
mikoC PRO for dsPIC FLASH_Write_DoWrite Prototype void 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.
mikroC PRO for dsPIC FLASH_Read4_Compact Prototype void* FLASH_Read4_Compact(unsigned long address, void *write_to); 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.
mikoC PRO for dsPIC FLASH_Write Prototype void FLASH_Write(unsigned long address, unsigned int *data_); 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.
mikroC PRO for dsPIC FLASH_Read Prototype unsigned int* FLASH_Read(unsigned long address, unsigned int *write_to, unsigned NoWords); 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 Example Notes Address of RAM buffer for storing read data.
mikoC PRO for dsPIC Library Example In this example written for dsPIC30F4013, various read/write tecniques to/from the on-chip FLASH memory are shown. Flash memory is mapped to address space 3:2, meaning 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'.
mikroC PRO for dsPIC UART1_Init(9600); UART1_Write_Text("Start"); UART1_Write(10); UART1_Write(13); while(cArr2[i]) { bb = cArr2[i++]; UART1_Write(bb); } // } //--- now for some non-compact flash-write pv1 = iArr; //--- erase the block first FLASH_Erase32(0x006100); FLASH_Write_Init(0x006100, pv1); FLASH_Write_Loadlatch4(); FLASH_Write_Loadlatch4(); FLASH_Write_DoWrite(); Graphic Lcd Library The mikroC PRO for dsPIC30/33 and PIC24 provides a library for operating Graphic Lcd 128x64 (with commonly used S
mikoC PRO for dsPIC External dependencies of Graphic Lcd Library The following variables must be defined in all projects using Graphic Description : Lcd Library: extern sfr sbit GLCD_D0; Data 0 line. extern sfr sbit GLCD_D2; Data 2 line. extern sfr sbit GLCD_D4; Data 4 line. extern sfr sbit GLCD_D6; Data 6 line. extern sfr sbit GLCD_CS1; Chip Select 1 line. extern sfr sbit GLCD_RS; Register select line. extern sfr sbit GLCD_EN; Enable line.
mikroC PRO for dsPIC 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 void Glcd_Init(); Description Initializes the Glcd m
mikoC PRO for dsPIC Requires - GLCD_EN : Enable signal pin - GLCD_RST : Reset signal pin - GLCD_D0_Direction : Direction of the Data pin 0 - GLCD_D1_Direction : Direction of the Data pin 1 - GLCD_D2_Direction : Direction of the Data pin 2 - GLCD_D3_Direction : Direction of the Data pin 3 - GLCD_D4_Direction : Direction of the Data pin 4 - GLCD_D5_Direction : Direction of the Data pin 5 - GLCD_D6_Direction : Direction of the Data pin 6 - GLCD_D7_Direction : Direction of the Data pin 7 - GLCD_CS1_Direction :
mikroC PRO for dsPIC Glcd_Set_Side Prototype void Glcd_Set_Side(unsigned short x_pos); 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.
mikoC PRO for dsPIC Glcd_Read_Data Prototype unsigned short Glcd_Read_Data(); Description Reads data from from the current location of Glcd memory and moves to the next location. Parameters None. Returns One byte from Glcd memory, formatted as a word (16-bit). Requires Glcd needs to be initialized, see Glcd_Init routine. Glcd side, x-axis position and page should be set first. See functions Glcd_Set_Side, Glcd_Set_X, and Glcd_Set_Page. Example Notes unsigned int data_; ...
mikroC PRO for dsPIC Glcd_Fill Prototype void Glcd_Fill(unsigned short pattern); 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.
mikoC PRO for dsPIC Glcd_V_Line Prototype void Glcd_V_Line(unsigned short y_start, unsigned short y_end, unsigned short x_pos, unsigned short color); 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..
mikroC PRO for dsPIC Glcd_Rectangle Prototype void Glcd_Rectangle(unsigned short x_upper_left, unsigned short y_upper_ left, unsigned short x_bottom_right, unsigned short y_bottom_right, unsigned short color); 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.
mikoC PRO for dsPIC Glcd_Rectangle_Round_Edges_Fill Prototype void Glcd_Rectangle_Round_Edges_Fill(unsigned short x_upper_left, unsigned short y_upper_left, unsigned short x_bottom_right, unsigned short y_bottom_ right, unsigned short round_radius, unsigned short color); 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.
mikroC PRO for dsPIC Glcd_Circle Prototype void Glcd_Circle(int x_center, int y_center, int radius, unsigned short color); Description Draws a circle on Glcd.1 Parameters - x_center: x coordinate of the circle center. Valid values: 0..127 - y_center: y coordinate of the circle center. Valid values: 0..63 - radius: radius size - color: color parameter. Valid values: 0..2 The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot. Returns Nothing.
mikoC PRO for dsPIC Glcd_Set_Font Prototype void Glcd_Set_Font(const char *activeFont, unsigned unsigned short aFontHeight, unsigned int aFontOffs); short aFontWidth, 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.
mikroC PRO for dsPIC Glcd_Write_Char Prototype void Glcd_Write_Char(unsigned short character, unsigned short x_pos, unsigned short page_num, unsigned short color); 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..
mikoC PRO for dsPIC Glcd_Image Prototype void Glcd_Image(code const unsigned short *image); 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 mikroC 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.
mikroC PRO for dsPIC Library Example The following drawing demo tests advanced routines of the Glcd library.
mikoC PRO for dsPIC Glcd_Init(); Glcd_Fill(0x00); // Initialize GLCD // Clear GLCD while(1) { #ifdef COMPLETE_EXAMPLE Glcd_Image(truck_bmp); delay2S(); delay2S(); #endif // Draw image Glcd_Fill(0x00); // Clear GLCD Glcd_Box(62,40,124,56,1); Glcd_Rectangle(5,5,84,35,1); Glcd_Line(0, 0, 127, 63, 1); delay2S(); // Draw box // Draw rectangle // Draw line for(ii = 5; ii < 60; ii+=5 ){ Delay_ms(250); Glcd_V_Line(2, 54, ii, 1); Glcd_H_Line(2, 120, ii, 1); } // Draw horizontal and vertical lines delay2S()
mikroC PRO for dsPIC Glcd_Set_Font(font5x7, 5, 7, 32); someText = "5x7 Font"; Glcd_Write_Text(someText, 5, 4, 2); delay2S(); } } // Change font // Write string Glcd_Set_Font(FontSystem5x7_v2, 5, 7, 32); // Change font someText = "5x7 Font (v2)"; Glcd_Write_Text(someText, 5, 6, 2); // Write string delay2S(); #endif HW Connection Glcd HW connection 389 MikroElektronika
mikoC PRO for dsPIC 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 mikroC 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.
mikroC PRO for dsPIC I2Cx_Start Prototype void 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 Notes // Issue START signal I2C1_Start(); I²C library routines require you to specify the module you want to use.
mikoC PRO for dsPIC I2Cx_Is_Idle Prototype unsigned I2Cx_Is_Idle(); 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 unsigned char data_; ... if !(I2C1_Is_Idle) I2C1_Write(data_); ...
mikroC PRO for dsPIC I2Cx_Write Prototype unsigned I2Cx_Write(unsigned char data_); 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.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC Keypad Library The mikroC 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 Description : Library: extern sfr keypadPort; unsigned int Keypad Port.
mikoC PRO for dsPIC Keypad_Key_Press Prototype unsigned Keypad_Key_Press(); Description Reads the key from keypad when key gets pressed. Parameters None. Returns The code of a pressed key (1..16). If no key is pressed, returns 0. Requires Example Notes Port needs to be initialized for working with the Keypad library, see Keypad_Init. unsigned kp; ...
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC HW Connection 4x4 Keypad connection scheme MikroElektronika 398
mikroC PRO for dsPIC Lcd Library The mikroC 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.
mikoC PRO for dsPIC Lcd_Init Prototype void Lcd_Init(); Description Initializes Lcd module. Parameters None. Returns Nothing.
mikroC PRO for dsPIC Lcd_Out Prototype void Lcd_Out(unsigned int row, unsigned int column, char *text); 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.
mikoC PRO for dsPIC Lcd_Chr_Cp Prototype void Lcd_Chr_Cp(char out_char); 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. Example // Write character “e” at current cursor position: Lcd_Chr_Cp(‘e’); Notes None Lcd_Cmd Prototype void Lcd_Cmd(char out_char); Description Sends command to Lcd.
mikroC PRO for dsPIC Library Example The following code demonstrates usage of the Lcd Library routines: Copy Code To Clipboard // LCD module connections sbit LCD_RS at LATD0_bit; sbit LCD_EN at LATD1_bit; sbit LCD_D4 at LATB0_bit; sbit LCD_D5 at LATB1_bit; sbit LCD_D6 at LATB2_bit; sbit LCD_D7 at LATB3_bit; sbit LCD_RS_Direction at TRISD0_bit; sbit LCD_EN_Direction at TRISD1_bit; sbit LCD_D4_Direction at TRISB0_bit; sbit LCD_D5_Direction at TRISB1_bit; sbit LCD_D6_Direction at TRISB2_bit; sbit LCD_D7_Direct
mikoC PRO for dsPIC // Moving text for(i=0; i<4; i++) { Lcd_Cmd(_LCD_SHIFT_RIGHT); Move_Delay(); } while(1) { for(i=0; i<8; i++) { Lcd_Cmd(_LCD_SHIFT_LEFT); Move_Delay(); } } } for(i=0; i<8; i++) { Lcd_Cmd(_LCD_SHIFT_RIGHT); Move_Delay(); } // Move text to the right 4 times // Endless loop // Move text to the left 7 times // Move text to the right 7 times Lcd HW connection MikroElektronika 404
mikroC PRO for dsPIC Manchester Code Library The mikroC PRO for dsPIC30/33 and PIC24 provides a library for handling Manchester coded signals.
mikoC PRO for dsPIC 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 unsigned int Man_Receive_Init(); 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.
mikroC PRO for dsPIC Man_Receive Prototype unsigned char Man_Receive(unsigned int *error); 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 unsigned int data = 0, error = 0; ...
mikoC PRO for dsPIC Man_Send Prototype void Man_Send(unsigned char tr_data); Description Sends one byte. Parameters - tr_data: data to be sent Returns Nothing. Requires To use this function, the user must prepare the MCU for sending. See Man_Send_Init routine. Example Notes unsigned int msg; ... Man_Send(msg); Baud rate used is 500 bps. Man_Synchro Prototype unsigned int Man_Synchro(); Description Measures half of the manchester bit length with 10us resolution. Parameters None.
mikroC PRO for dsPIC Man_Break Prototype void 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.
mikoC PRO for dsPIC Library Example The following code is code for the Manchester receiver, it shows how to use the Manchester Library for receiving data: Copy Code To Clipboard // LCD module connections sbit LCD_RS at LATD0_bit; sbit LCD_EN at LATD1_bit; sbit LCD_D4 at LATB0_bit; sbit LCD_D5 at LATB1_bit; sbit LCD_D6 at LATB2_bit; sbit LCD_D7 at LATB3_bit; sbit LCD_RS_Direction at TRISD0_bit; sbit LCD_EN_Direction at TRISD1_bit; sbit LCD_D4_Direction at TRISB0_bit; sbit LCD_D5_Direction at TRISB1_bit; sbit
mikroC PRO for dsPIC do { } temp = Man_Receive(&error); // Attempt byte receive if (error) { // If error occured Lcd_Chr_CP('?'); // Write question mark on LCD ErrorCount++; // Update error counter if (ErrorCount > 20) { // In case of multiple errors temp = Man_Synchro(); // Try to synchronize again //Man_Receive_Init(); // Alternative, try to Initialize Receiver again ErrorCount = 0; // Reset error counter } } else { // No error occured if (temp != 0x0E) // If "End" byte was received(see Transmitter exam
mikoC PRO for dsPIC } } while (character) { Man_Send(character); Delay_ms(90); index++; character = s1[index]; } Man_Send(0x0E); Delay_ms(1000); // // // // // String ends with zero Send character Wait for a while Increment index variable Take next char from string // Send "end" byte Connection Example Simple Transmitter connection Simple Receiver connection MikroElektronika 412
mikroC PRO for dsPIC 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. mikroC PRO for dsPIC30/33 and PIC24 provides a library for accessing data on Multi Media Card via SPI communication. This library also supports SD (Secure Digital) and high capacity SDHC (Secure Digital High Capacity) memory cards .
mikoC PRO for dsPIC Library Dependency Tree External dependencies of MMC Library The following variable must be defined in all projects using MMC Description : library: extern sfr Select; sbit extern sfr sbit Select_Direction; Mmc_Chip_ Chip select pin. Example : sbit Mmc_Chip_Select at LATF0_ bit; Mmc_Chip_ Direction of the chip select sbit Mmc_Chip_Select_Direction at TRISF0_bit; pin.
mikroC PRO for dsPIC Mmc_Init Prototype unsigned int Mmc_Init(); 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.
mikoC PRO for dsPIC Mmc_Read_Sector Prototype unsigned int Mmc_Read_Sector(unsigned long sector, char *dbuff); Description The function reads one sector (512 bytes) from MMC card. Parameters - sector: MMC/SD card sector to be read. - dbuff: buffer of minimum 512 bytes in length for data storage. Returns Requires Example Notes - 0 - if reading was successful - 1 - if an error occurred MMC/SD card must be initialized. See Mmc_Init.
mikroC PRO for dsPIC Mmc_Read_Cid Prototype unsigned int Mmc_Read_Cid(char *data_cid); Description The function reads 16-byte CID register. Parameters - data_cid: buffer of minimum 16 bytes in length for storing CID register content. Returns Requires Example Notes - 0 - if CID register was read successfully - 1 - if there was an error while reading MMC/SD card must be initialized. See Mmc_Init. unsigned int error; char dataBuffer[16]; ... error = Mmc_Read_Cid(dataBuffer); None.
mikoC PRO for dsPIC Mmc_Fat_Init Prototype unsigned int Mmc_Fat_Init(); Description Initializes MMC/SD card, reads MMC/SD FAT16 boot sector and extracts necessary data needed by the library. Parameters None.
mikroC PRO for dsPIC Mmc_Fat_QuickFormat Prototype unsigned int Mmc_Fat_QuickFormat(char *mmc_fat_label); 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.
mikoC PRO for dsPIC Mmc_Fat_Assign Prototype unsigned int Mmc_Fat_Assign(char *filename, char file_cre_attr); 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.
mikroC PRO for dsPIC Mmc_Fat_Reset Prototype void Mmc_Fat_Reset(unsigned long *size); 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. The file must be previously assigned.
mikoC PRO for dsPIC Mmc_Fat_Rewrite Prototype void Mmc_Fat_Rewrite(); Description Opens the currently assigned file for writing. If the file is not empty its content will be erased. Parameters None. Returns Nothing. Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. The file must be previously assigned. See Mmc_Fat_Assign. Example Notes // open file for writing Mmc_Fat_Rewrite(); None.
mikroC PRO for dsPIC Mmc_Fat_Write Prototype void Mmc_Fat_Write(char *fdata, unsigned data_len); 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. The file must be opened for writing.
mikoC PRO for dsPIC Mmc_Fat_Get_File_Date Prototype void Mmc_Fat_Get_File_Date(unsigned int *year, unsigned short *month, unsigned short *day, unsigned short *hours, unsigned short *mins); 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.
mikroC PRO for dsPIC Mmc_Fat_Get_File_Date_Modified Prototype void Mmc_Fat_Get_File_Date_Modified(unsigned int *year, unsigned short *month, unsigned short *day, unsigned short *hours, unsigned short *mins); 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.
mikoC PRO for dsPIC Mmc_Fat_Get_Swap_File Prototype unsigned long Mmc_Fat_Get_Swap_File(unsigned filename, char file_attr); long sectors_cnt, char* 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. Therefore, it is recommended to erase such file if it already exists before calling this function.
mikroC PRO for dsPIC Requires MMC/SD card and MMC library must be initialized for file operations. See Mmc_Fat_Init. Example //-------------- Tries to create a swap file, whose size will be at least 100 sectors. //If it succeeds, it sends the No.
mikoC PRO for dsPIC // Creates many new files and writes data to them void M_Create_Multiple_Files() { for(loop2 = 'B'; loop2 <= 'Z'; loop2++) { UART1_Write(loop2); // signal the progress filename[7] = loop2; // set filename Mmc_Fat_Set_File_Date(2005,6,21,10,35,0); // Set file date & time info Mmc_Fat_Assign(&filename, 0xA0); // find existing file or create a new one Mmc_Fat_Rewrite(); // To clear file and start with new data for(loop = 1; loop <= 44; loop++) { file_contents[0] = loop / 10 + 48; file_conte
mikroC PRO for dsPIC // Deletes a file. If file doesn't exist, it will first be created // and then deleted.
mikoC PRO for dsPIC } else { //--- file was not found - signal it UART1_Write(0x55); Delay_ms(1000); UART1_Write(0x55); } // Tries to create a swap file, whose size will be at least 100 // sectors (see Help for details) void M_Create_Swap_File() { unsigned int i; for(i=0; i<512; i++) Buffer[i] = i; size = Mmc_Fat_Get_Swap_File(5000, "mikroE.
mikroC PRO for dsPIC U1MODEbits.ALTIO = 1; // Switch Rx and Tx pins on their alternate locations. // This is used to free the pins for other module, namely the SPI. //--- init the FAT library if (!Mmc_Fat_Init()) { // reinitialize spi at higher speed SPI1_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, _SPI_PRESCALE_SEC_1, _SPI_PRESCALE_ PRI_4, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ACTIVE_2_IDLE); //--- Test start UART1_Write_Line("Test Start."); //--- Test routines.
mikoC PRO for dsPIC OneWire Library The OneWire library provides routines for communication via the Dallas OneWire protocol, e.g. with DS18x20 digital thermometer. OneWire is a Master/Slave protocol, and all communication cabling required is a single wire. OneWire enabled devices should have open collector drivers (with single pull-up resistor) on the shared data line. Slave devices on the OneWire bus can even get their power supply from data line. For detailed schematic see device datasheet.
mikroC PRO for dsPIC Ow_Read Prototype unsigned short Ow_Read(unsigned int *port, unsigned int pin); 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 unsigned short read_data; ... read_data = Ow_Read(&PORTF, 6); Notes None.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC text[1] = (temp_whole/10)%10 + 48; text[2] = temp_whole%10 + 48; // Extract tens digit // Extract ones digit // extract temp_fraction and convert it to unsigned int temp_fraction = temp2write << (4-RES_SHIFT); temp_fraction &= 0x000F; temp_fraction *= 625; // convert temp_fraction to characters text[4] = temp_fraction/1000 + 48; text[5] = (temp_fraction/100)%10 + 48; text[6] = (temp_fraction/10)%10 + 48; text[7] = temp_fraction%10 + 48; } // // // // Extract Extract Extract Extract
mikoC PRO for dsPIC HW Connection Example of DS1820 connection MikroElektronika 436
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC PPS_Mapping Prototype unsigned PPS_Mapping(unsigned unsigned short funct_name); short rp_num, unsigned short direction, 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.
mikroC PRO for dsPIC _QEA1 _QEA2 _QEB1 _QEB2 _SCK1IN _SCK2IN _SCK3IN _SDI1 _SDI2 _SDI3 _SS1IN _SS2IN _SS3IN QEI1 Phase A QEI2 Phase A QEI1 Phase B QEI2 Phase B SPI1 Clock Input SPI2 Clock Input SPI3 Clock Input SPI1 Data Input SPI2 Data Input SPI3 Data Input SPI1 Slave Select Input SPI2 Slave Select Input SPI3 Slave Select Input _T1CK _T2CK _T3CK _T4CK _T5CK _U1CTS _U2CTS _U3CTS _U4CTS _U1RX _U2RX _U3RX _U4RX Timer1 External Clock Timer2 External Clock Timer3 External Clock Timer4 External Clock Timer
mikoC PRO for dsPIC _OC9 _OCFA _OCFB _PWM4H _PWM4L _REFCLKO _SCK1OUT _SCK2OUT _SCK3OUT _SDO1 _SDO2 _SDO3 _SS1OUT _SS2OUT _SS3OUT _SYNCI1 _SYNCI2 _SYNCO1 _U1RTS _U2RTS _U3RTS _U4RTS _U1TX _U2TX _U3TX _U4TX _UPDN _UPDN1 _UPDN2 MikroElektronika Output Compare 9 Output Compare Fault A Output Compare Fault B RPn tied to PWM output pins associated with PWM Generator 4 RPn tied to PWM output pins associated with PWM Generator 4 REFCLK output signal SPI1 Clock Output SPI2 Clock Output SPI3 Clock Output SPI1
mikroC PRO for dsPIC Port Expander Library The mikroC 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.
mikoC PRO for dsPIC Expander_Init Prototype void Expander_Init(char ModuleAddress); 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.
mikroC PRO for dsPIC Expander_Init_Advanced Prototype void Expander_Init_Advanced(char *rstPort, char rstPin, char haen); 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.
mikoC PRO for dsPIC Expander_Read_Byte Prototype char Expander_Read_Byte(char ModuleAddress, char RegAddress); Description The function reads byte from Port Expander. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - RegAddress: Port Expander’s internal register address Returns Byte read. Requires Port Expander must be initialized. See Expander_Init. Example // Read a byte from Port Expander’s register char read_data; ...
mikroC PRO for dsPIC Expander_Read_PortB Prototype char Expander_Read_PortB(char ModuleAddress); 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.
mikoC PRO for dsPIC Expander_Write_PortA Prototype void Expander_Write_PortA(char ModuleAddress, char Data_); 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.
mikroC PRO for dsPIC Expander_Write_PortAB Prototype void Expander_Write_PortAB(char ModuleAddress, unsigned int Data_); 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. Requires Port Expander must be initialized.
mikoC PRO for dsPIC Expander_Set_DirectionPortB Prototype void Expander_Set_DirectionPortB(char ModuleAddress, char Data_); 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.
mikroC PRO for dsPIC Expander_Set_PullUpsPortB Prototype void Expander_Set_PullUpsPortB(char ModuleAddress, char Data_); Description The function sets Port Expander’s PortB pull up/down resistors. Parameters - ModuleAddress: Port Expander hardware address, see schematic at the bottom of this page - Data: data for choosing pull up/down resistors configuration. Each bit corresponds to the appropriate pin of the PortB register. Set bit enables pull-up for corresponding pin. Returns Nothing.
mikoC PRO for dsPIC 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.
mikroC PRO for dsPIC HW Connection Port Expander HW connection 451 MikroElektronika
mikoC PRO for dsPIC PS/2 Library The mikroC 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.
mikroC PRO for dsPIC Ps2_Config Prototype void 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.
mikoC PRO for dsPIC 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 454
mikroC PRO for dsPIC Library Example This simple example reads values of the pressed keys on the PS/2 keyboard and sends them via UART.
mikoC PRO for dsPIC HW Connection Example of PS2 keyboard connection PWM Library The CCP module is available with a number of dsPIC30/33 and PIC24 MCUs. mikroC 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.
mikroC PRO for dsPIC PWM_Init Prototype unsigned int PWM_Init(unsigned long freq_hz, unsigned int enable_channel_x, unsigned int timer_prescale, unsigned int use_timer_x); // 30F1010 and dsPIC33FJ06GS101/102/202 prototype unsigned int PWM_Init(unsigned long freq_hz, unsigned int enable_channel_x, unsigned int timer_prescale); Description Initializes the PWM module with duty ratio 0.
mikoC PRO for dsPIC PWM_Start Prototype void PWM_Start(char enable_channel_x); 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 Notes // start PWM at channel 1 PWM_Start(1); Number of available PWM channels depends on MCU. Refer to MCU datasheet for details.
mikroC PRO for dsPIC pwm_period1 = PWM_Init(5000 , 1, 1, 2); pwm_period2 = PWM_Init(10000, 2, 1, 3); PWM_Start(1); PWM_Start(2); PWM_Set_Duty(current_duty, 1); PWM_Set_Duty(current_duty1, 2); while (1) { if (RB0_bit) { Delay_ms(20); current_duty++; if (current_duty > pwm_period1) { possible pwm_period1 value current_duty = 0; } PWM_Set_Duty(current_duty, 1); } if (RB1_bit) { Delay_ms(20); current_duty--; if (current_duty > pwm_period1) { possible pwm_period1 value (overflow) current_duty = pwm_period1; } PW
mikoC PRO for dsPIC HW Connection PWM demonstration PWM Motor Control Library The PWM Motor Control module is available with a number of dsPIC30/33 MCUs. The mikroC 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.
mikroC PRO for dsPIC PWMx_Mc_Init Prototype unsigned int PWMx_Mc_Init(unsigned int freq_hz, unsigned int pair_output_ mode, unsigned int enable_output_x, unsigned int clock_prescale_output_ postscale); 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.
mikoC PRO for dsPIC PWMx_Mc_Set_Duty Prototype void PWM1_Mc_Set_Duty(unsigned duty, unsigned channel); // For dsPIC 33FJ MCUs that have PWM2 module : void PWM2_Mc_Set_Duty(unsigned duty); 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.
mikroC PRO for dsPIC PWMx_Mc_Stop Prototype void 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. - PWM library routines require you to specify the module you want to use.
mikoC PRO for dsPIC HW Connection PWM Motor Control demonstration RS-485 Library RS-485 is a multipoint communication which allows multiple devices to be connected to a single bus. The mikroC PRO for dsPIC30/33 and PIC24 provides a set of library routines for comfortable work with RS485 system using Master/ Slave architecture. Master and Slave devices interchange packets of information. Each of these packets contains synchronization bytes, CRC byte, address byte and the data.
mikroC PRO for dsPIC Library Dependency Tree External dependencies of RS-485 Library The following variable must be defined in all projects using RS-485 Description : Library: Example : extern sfr sbit RS485_rxtx_ Control RS-485 Transmit/ sbit RS485_rxtx_pin at RF2_bit; pin; Receive operation mode extern sfr sbit RS485_rxtx_ Direction of the RS-485 sbit RS485_rxtx_pin_direction at pin_direction; TRISF2_bit; Transmit/Receive pin Library Routines - RS485Master_Init - RS485Master_Receive - RS485Master_Sen
mikoC PRO for dsPIC RS485Master_Receive Prototype void RS485Master_Receive(char *data_buffer); 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..
mikroC PRO for dsPIC RS485Slave_Init Prototype void RS485Slave_Init(char Slave_address); 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.
mikoC PRO for dsPIC RS485Slave_Receive Prototype void RS485Slave_Receive(char *data_buffer); 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..
mikroC PRO for dsPIC Library Example This is a simple demonstration of RS485 Library routines usage. Master sends message to Slave with address 160 and waits for a response. The Slave accepts data, increments it and sends it back to the Master. Master then does the same and sends incremented data back to Slave, etc. Master displays received data on PORTB, while error on receive (0xAA) and number of consecutive unsuccessful retries are displayed on PORTD.
mikoC PRO for dsPIC URXISEL1_U2STA_bit = 0; URXISEL1_U2STA_bit = 0; NSTDIS_bit = 1; U2RXIF_bit = 0; U2RXIE_bit = 1; // no nesting of interrupts // ensure interrupt not pending // enable intterupt while (1){ cnt++; if (dat[5]) { PORTD = 0xAA; } if (dat[4]) { cnt = 0; dat[4] = 0; j = dat[3]; for (i = 1; i <= dat[3]; i++) { PORTB = dat[i-1]; } dat[0] = dat[0]+1; Delay_ms(1); RS485Master_Send(dat,1,160); } } if (cnt > 100000) { PORTD ++; cnt = 0; RS485Master_Send(dat,1,160); if (PORTD > 10) RS485Master_Send
mikroC PRO for dsPIC void main() { ADPCFG = 0xFFFF; 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 (1) { if (dat[5]) { PORTD = 0xAA; dat[5] = 0; } if (dat[4]) { dat[4] = 0; j = dat[3]; for (i = 1;
mikoC PRO for dsPIC HW Connection Example of interfacing PC to dsPIC MCU via RS485 bus with LTC485 as RS-485 transceiver MikroElektronika 472
mikroC PRO for dsPIC Message format and CRC calculations Q: How is CRC checksum calculated on RS485 master side? Copy Code To Clipboard START_BYTE = 0x96; // 10010110 STOP_BYTE = 0xA9; // 10101001 PACKAGE: -------START_BYTE 0x96 ADDRESS DATALEN [DATA1] [DATA2] [DATA3] CRC STOP_BYTE 0xA9 // if exists // if exists // if exists DATALEN bits -----------bit7 = 1 MASTER SENDS 0 SLAVE SENDS bit6 = 1 ADDRESS WAS XORed 0 ADDRESS UNCHANGED bit5 = 0 FIXED bit4 = 1 DATA3 (if exists) 0 DATA3 (if exists) bit3 = 1 DATA2
mikoC PRO for dsPIC Software I²C Library The mikroC 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.
mikroC PRO for dsPIC Soft_I2C_Init Prototype void 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.
mikoC PRO for dsPIC Soft_I2C_Read Prototype unsigned short Soft_I2C_Read(unsigned int ack); 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.
mikroC PRO for dsPIC Soft_I2C_Stop Prototype void Soft_I2C_Stop(); Description Issues STOP signal. Parameters None. Returns Nothing. Requires Soft I²C must be configured before using this function. See Soft_I2C_Init routine.
mikoC PRO for dsPIC Soft_I2C_Break Prototype void 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC //-------------------- Formats date and time void Transform_Time() { seconds = ((seconds & 0xF0) >> 4)*10 + (seconds & 0x0F); minutes = ((minutes & 0xF0) >> 4)*10 + (minutes & 0x0F); hours = ((hours & 0xF0) >> 4)*10 + (hours & 0x0F); year = (day & 0xC0) >> 6; day = ((day & 0x30) >> 4)*10 + (day & 0x0F); month = ((month & 0x10) >> 4)*10 + (month & 0x0F); } // // // // // // Transform Transform Transform Transform Transform Transform seconds months hours year day month //--------------
mikroC PRO for dsPIC Software SPI Library The mikroC 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.
mikoC PRO for dsPIC Soft_SPI_Init Prototype void 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.
mikroC PRO for dsPIC Soft_SPI_Read Prototype unsigned short Soft_SPI_Read(char sdata); Description This routine performs 3 operations simultaneously. It provides clock for the Software SPI bus, reads a byte and sends a byte. Parameters - sdata: data to be sent. Returns Byte received via the SPI bus. Requires Soft SPI must be initialized before using this function. See Soft_SPI_Init routine. Example Notes unsigned short data_read; char data_send; ...
mikoC PRO for dsPIC unsigned int value; void InitMain() { TRISB0_bit = 1; TRISB1_bit = 1; Chip_Select = 1; Chip_Select_Direction = 0; Soft_SPI_Init(); } // // // // // Set RB0 pin as input Set RB1 pin as input Deselect DAC Set CS# pin as Output Initialize Soft_SPI // DAC increments (0..4095) --> output voltage (0..
mikroC PRO for dsPIC Software UART Library The mikroC 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.
mikoC PRO for dsPIC Soft_UART_Read Prototype char Soft_UART_Read(char *error); 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.
mikroC PRO for dsPIC Soft_UART_Break Prototype void 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.
mikoC PRO for dsPIC 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 mikroC PRO for dsPIC30/33 and PIC24 USART communication terminal, launch it from the dropdown menu Tools › USART Terminal or simply click the USART Terminal Icon .
mikroC PRO for dsPIC Sound Library The mikroC 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).
mikoC PRO for dsPIC Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker.
mikroC PRO for dsPIC while (1) { if (Button(&PORTB,7,1,1)) Tone1(); while (RB7_bit); } } // RB7 plays Tone1 // Wait for button to be released if (Button(&PORTB,6,1,1)) Tone2(); while (RB6_bit); // RB6 plays Tone2 if (Button(&PORTB,5,1,1)) Tone3(); while (RB5_bit); // RB5 plays Tone3 if (Button(&PORTB,4,1,1)) Melody2(); while (RB4_bit); // RB4 plays Melody2 if (Button(&PORTB,3,1,1)) Melody(); while (RB3_bit); // RB3 plays Melody // Wait for button to be released // Wait for button to be released
mikoC PRO for dsPIC SPI Library The SPI module is available with all dsPIC30/33 and PIC24 MCUs. mikroC 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.
mikroC PRO for dsPIC SPIx_Init Prototype void 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. Requires MCU must have the SPI1 module.
mikoC PRO for dsPIC SPIx_Init_Advanced Prototype void SPIx_Init_Advanced(unsigned master_mode, unsigned mode16, unsigned sec_prescaler, unsigned pri_prescaler, unsigned slave_select, unsigned data_sample, unsigned clock_idle, unsigned edge); 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.
mikroC PRO for dsPIC 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.
mikoC PRO for dsPIC SPIx_Read Prototype unsigned SPIx_Read(unsigned buffer); 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.
mikroC PRO for dsPIC SPI_Set_Active Prototype void SPI_Set_Active(unsigned (unsigned)); (*read_ptr)(unsigned), void(*write_ptr) Description Sets the active SPI module which will be used by the SPIx_Read and SPIx_Write routines. Parameters Parameters : Returns Requires - read_ptr: SPI1_Read handler - write_ptr: SPI1_Write handler Nothing. Routine is available only for MCUs with multiple SPI modules. Used SPI module must be initialized before using this function.
mikoC PRO for dsPIC // Send Low Byte temp = valueDAC; SPI1_Write(temp); } // Store valueDAC[7..0] to temp[7..
mikroC PRO for dsPIC SPI Ethernet Library The ENC28J60 is a stand-alone Ethernet controller with an industry standard Serial Peripheral Interface (SPI). It is designed to serve as an Ethernet network interface for any controller equipped with SPI. The ENC28J60 meets all of the IEEE 802.3 specifications. It incorporates a number of packet filtering schemes to limit incoming packets. It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calculations.
mikoC PRO for dsPIC External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Description : Ethernet Library: extern sfr sbit SPI_Ethernet_ ENC28J60 chip select pin. CS; extern sfr sbit SPI_Ethernet_ ENC28J60 reset pin. RST; Example : sbit SPI_Ethernet_CS at LATF1_ bit; sbit SPI_Ethernet_Rst at LATF0_ bit; extern sfr sbit SPI_Ethernet_ Direction of the ENC28J60 sbit SPI_Ethernet_CS_Direction CS_Direction; at TRISF1_bit; chip select pin.
mikroC PRO for dsPIC Library Routines - SPI_Ethernet_Init - SPI_Ethernet_Enable - SPI_Ethernet_Disable - SPI_Ethernet_doPacket - SPI_Ethernet_putByte - SPI_Ethernet_putBytes - SPI_Ethernet_putString - SPI_Ethernet_putConstString - SPI_Ethernet_putConstBytes - SPI_Ethernet_getByte - SPI_Ethernet_getBytes - SPI_Ethernet_UserTCP - SPI_Ethernet_UserUDP - SPI_Ethernet_getIpAddress - SPI_Ethernet_getGwIpAddress - SPI_Ethernet_getDnsIpAddress - SPI_Ethernet_getIpMask - SPI_Ethernet_confNetwork - SPI_Ethernet_arpRe
mikoC PRO for dsPIC SPIx_Write Parameters - mac: RAM buffer containing valid MAC address. - ip: RAM buffer containing valid IP address. - fullDuplex: ethernet duplex mode switch. Valid values: 0 (half duplex mode) and 1 (full duplex mode). Returns Received data.
mikroC PRO for dsPIC SPI_Ethernet_Enable Prototype void SPI_Ethernet_Enable(unsigned char enFlt); 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.
mikoC PRO for dsPIC SPI_Ethernet_Disable Prototype void SPI_Ethernet_Disable(unsigned char disFlt); 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.
mikroC PRO for dsPIC SPI_Ethernet_doPacket Prototype unsigned int SPI_Ethernet_doPacket(); 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.
mikoC PRO for dsPIC SPI_Ethernet_putBytes Prototype void SPI_Ethernet_putBytes(unsigned char *ptr, unsigned int n); 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.
mikroC PRO for dsPIC SPI_Ethernet_putConstString Prototype unsigned int SPI_Ethernet_putConstString(const unsigned char *ptr); Description This is MAC module routine. It stores whole const string (excluding null termination) into ENC28J60 RAM starting from current ENC28J60 write pointer (EWRPT) location. Parameters - ptr: const string to be written into ENC28J60 RAM. Returns Requires Example Notes Number of bytes written into ENC28J60 RAM. Ethernet module has to be initialized. See SPI_Ethernet_Init.
mikoC PRO for dsPIC SPI_Ethernet_UserTCP Prototype unsigned int SPI_Ethernet_UserTCP(unsigned char *remoteHost, unsigned int remotePort, unsigned int localPort, unsigned int reqLength, TEthPktFlags *flags); Description This is TCP module routine. It is internally called by the library. The user accesses to the TCP request by using some of the SPI_Ethernet_get routines. The user puts data in the transmit buffer by using some of the SPI_Ethernet_put routines.
mikroC PRO for dsPIC SPI_Ethernet_UserUDP Prototype unsigned int SPI_Ethernet_UserUDP(unsigned char *remoteHost, unsigned int remotePort, unsigned int localPort, unsigned int reqLength, TEthPktFlags *flags); 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.
mikoC PRO for dsPIC SPI_Ethernet_getIpAddress Prototype unsigned char * SPI_Ethernet_getIpAddress(); 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 unsigned char ipAddr[4]; // user IP address buffer ...
mikroC PRO for dsPIC SPI_Ethernet_confNetwork Prototype void SPI_Ethernet_confNetwork(char *dnsIpAddr); *ipMask, char *gwIpAddr, char 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.
mikoC PRO for dsPIC SPI_Ethernet_sendUDP Prototype unsigned int SPI_Ethernet_sendUDP(unsigned char *destIP, sourcePort, unsigned int destPort, unsigned char *pkt, pktLen); unsigned unsigned int int Description This is UDP module routine. It sends an UDP packet on the network. Parameters - destIP: remote host IP address. - sourcePort: local UDP source port number. - destPort: destination UDP port number. - pkt: packet to transmit. - pktLen: length in bytes of packet to transmit.
mikroC PRO for dsPIC SPI_Ethernet_initDHCP Prototype unsigned int SPI_Ethernet_initDHCP(unsigned char tmax); 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.
mikoC PRO for dsPIC SPI_Ethernet_doDHCPLeaseTime Prototype unsigned int SPI_Ethernet_doDHCPLeaseTime(); Description This is DHCP module routine. It takes care of IP address lease time by decrementing the global lease time library counter. When this time expires, it’s time to contact DHCP server and renew the lease. Parameters None. Returns Requires Example Notes - 0 - lease time has not expired yet. - 1 - lease time has expired, it’s time to renew it. Ethernet module has to be initialized.
mikroC PRO for dsPIC Library Example This code shows how to use the Ethernet mini library : - the board will reply to ARP & ICMP echo requests - the board will reply to UDP requests on any port : - returns the request in upper char with a header made of remote host IP & port number - the board will reply to HTTP requests on port 80, GET method with pathnames : - / will return the HTML main page - /s will return board status as text string - /t0 ...
mikoC PRO for dsPIC Reload