mikroC PRO for PIC32™ Manual Compiler mikroC PRO for PIC32 is a full-featured C compiler for PIC32 MCUs from Microchip. It is designed for developing, building and debugging PIC32-based embedded applications. This development environment has a wide range of features such as: easy-to-use IDE, very compact and efficient code, many hardware and software libraries, comprehensive documentation, software simulator, COFF file generation, SSA optimization (up to 30% code reduction) and many more.
mikoC PRO for PIC32 Table of Contents CHAPTER 1 INTRODUCTION Introduction to mikroC PRO for PIC32 30 30 31 Software License Agreement 32 Technical Support How to Register 34 34 CHAPTER 2 mikroC PRO for PIC32 Environment Main Menu Options File 38 38 38 39 40 Edit 41 Features Where to Start mikroElektronika Associates License Statement and Limited Warranty IMPORTANT - READ CAREFULLY LIMITED WARRANTY HIGH RISK ACTIVITIES GENERAL PROVISIONS Who Gets the License Key How to Get L
mikroC PRO for PIC32 mikroC PRO for PIC32 IDE 51 Code Editor 52 Code Explorer 59 Project Manager Project Settings Library Manager 60 62 63 Routine List Statistics 65 65 Messages Window Quick Converter Macro Editor Image Preview Toolbars 72 73 73 74 76 IDE Overview Editor Settings Auto Save Highlighter Spelling Comment Style Code Folding Code Assistant Parameter Assistant Bookmarks Go to Line Column Select Mode Editor Colors Auto Correct Auto Complete (Code Templates)
mikoC PRO for PIC32 Find/Replace Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar 78 79 79 80 80 81 81 82 82 Customizing IDE Layout 83 Options 85 Integrated Tools 88 Active Comments 96 Docking Windows Saving Layout Auto Hide Code editor Tools Output settings Active Comments Editor ASCII Chart EEPROM Editor Graphic Lcd Bitmap Editor HID Terminal Interrupt Assistant Lcd Custom Character Seven Segment
mikroC PRO for PIC32 Metacharacters - Backreferences 110 Keyboard Shortcuts CHAPTER 3 mikroC PRO for PIC32 Command Line Options CHAPTER 4 mikroICD (In-Circuit Debugger) Introduction mikroICD Debugger Options 111 113 113 115 115 115 117 mikroICD Debugger Example mikroICD Debugger Windows 118 122 CHAPTER 5 Software Simulator Overview Software Simulator Software Simulator Debug Windows 127 127 128 129 Software Simulator Debugger Options 134 CHAPTER 6 mikroC PRO for PIC32 Specifics AN
mikoC PRO for PIC32 Interrupts Configuring Interrupts Single Vector Mode Multi Vector Mode 141 141 141 141 Interrupt Priorities Interrupts and Register Sets 142 142 Interrupt Coding Requirements Interrupt Service Routine Function Calls from Interrupt Interrupt Example 142 142 143 144 Register Set Selection in Single Vector Mode Interrupts and Register Sets 142 142 Linker Directives 145 Indirect Function Calls Built-in Routines 146 147 Code Optimization 158 Directive absolute
mikroC PRO for PIC32 Constant propagation Copy propagation Value numbering "Dead code" ellimination Stack allocation Local vars optimization Better code generation and local optimization 158 158 158 158 158 158 158 Single Static Assignment Optimization 159 CHAPTER 7 PIC32 Specifics 162 162 PIC32 Memory Organization 164 Memory Type Specifiers 167 Read Modify Write Problem CHAPTER 8 mikroC PRO for PIC32 Language Reference Lexical Elements Overview Whitespace 168 172 172 175 176 Co
mikoC PRO for PIC32 Hexadecimal Binary Octal 180 180 180 Floating Point Constants Character Constants 181 181 String Constants 183 Enumeration Constants Pointer Constants Constant Expressions Keywords Identifiers 184 184 185 186 187 Punctuators 188 Concepts Objects 192 192 Scope and Visibility 193 Name Spaces Duration 194 195 Types 196 Fundamental Types Arithmetic Types 197 197 Escape Sequences Disambiguation Line Continuation with Backslash Case Sensitivity Uni
mikroC PRO for PIC32 Floating-point Types 198 Enumerations 198 Void Type 200 Derived Types Arrays 200 201 Pointers 203 Pointer Arithmetic 207 Structures 210 Working with Structures 213 Structure Member Access 214 Unions 216 Bit Fields 218 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 Function Poi
mikoC PRO for PIC32 Bit Fields Declaration Bit Fields Access 218 219 Types Conversions Standard Conversions 219 220 Explicit Types Conversions (Typecasting) Declarations 221 222 Linkage 223 Storage Classes 224 Type Qualifiers 226 Typedef Specifier asm Declaration 226 227 Initialization 229 Functions 230 Function Calls and Argument Conversions 232 Ellipsis (‘...
mikroC PRO for PIC32 Relational Operators in Expressions 239 Bitwise Operators 240 Logical Operators 242 Conditional Operator ? : 243 Assignment Operators 244 Unary Operators 245 Sizeof Operator 247 Expressions Comma Expressions Statements Labeled Statements Expression Statements Selection Statements If Statement 248 248 249 249 250 250 250 Switch Statement 251 Iteration Statements (Loops) 252 Do Statement For Statement Jump Statements Break and Continue Statements 2
mikoC PRO for PIC32 Goto Statement Return Statement Compound Statements (Blocks) Preprocessor Preprocessor Directives 255 255 256 256 256 Macros 257 File Inclusion 259 Preprocessor Operators 261 Conditional Compilation 262 CHAPTER 9 mikroC PRO for PIC32 Libraries Hardware Libraries Standard ANSI C Libraries Miscellaneous Libraries Hardware Libraries ADC Library 264 264 265 266 266 267 267 CANSPI Library 271 Line Continuation with Backslash (\) Defining Macros and Macro Expans
mikroC PRO for PIC32 CANSPI_OP_MODE Constants CANSPI_CONFIG_FLAGS Constants CANSPI_TX_MSG_FLAGS Constants CANSPI_RX_MSG_FLAGS Constants CANSPI_MASK Constants CANSPI_FILTER Constants Library Example HW Connection 279 280 281 281 282 282 283 286 Compact Flash Library 287 Epson S1D13700 Graphic Lcd Library 307 Library Dependency Tree External dependencies of Compact Flash Library Library Routines Cf_Init Cf_Detect Cf_Enable Cf_Disable Cf_Read_Init Cf_Read_Byte Cf_Write_Init Cf_Write_B
mikoC PRO for PIC32 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 312 312 313 313 314 314 315 315 316 316 317 317 318 318 319 319 320 320 321 Flash Memor
mikroC PRO for PIC32 Glcd_Image Glcd_PartialImage 337 337 I²C Library 338 Keypad Library 344 Lcd Library 348 Manchester Code Library 354 Memory Manager Library 362 Library Routines I2Cx_Init I2Cx_Init_Advanced I2Cx_Start I2Cx_Restart I2Cx_Is_Idle I2Cx_Read I2Cx_Write I2Cx_Stop Library Example External dependencies of Keypad Library Library Routines Keypad_Init Keypad_Key_Press Keypad_Key_Click Library Example HW Connection Library Dependency Tree Keypad_Key_Click Librar
mikoC PRO for PIC32 Heap_Init malloc free LargestFreeMemBlock TotalFreeMemSize 362 362 363 363 363 Multi Media Card Library 364 OneWire Library 383 Port Expander Library 385 Secure Digital Card Secure Digital High Capacity Card Library Dependency Tree External dependencies of MMC Library Library Routines Mmc_Init Mmc_Read_Sector Mmc_Write_Sector Mmc_Read_Cid Mmc_Read_Csd Mmc_Fat_Init Mmc_Fat_QuickFormat Mmc_Fat_Assign Mmc_Fat_Reset Mmc_Fat_Read Mmc_Fat_Rewrite Mmc_Fat_Append
mikroC PRO for PIC32 Expander_Read_PortB Expander_Read_PortAB Expander_Write_PortA Expander_Write_PortB Expander_Write_PortAB Expander_Set_DirectionPortA Expander_Set_DirectionPortB Expander_Set_DirectionPortAB Expander_Set_PullUpsPortA Expander_Set_PullUpsPortB Expander_Set_PullUpsPortAB Library Example HW Connection 389 389 390 390 391 391 392 392 392 393 393 394 395 PS/2 Library 396 PWM Library 400 RS-485 Library 405 Software I²C Library 415 External dependencies of PS/2 Librar
mikoC PRO for PIC32 Soft_I2C_Init Soft_I2C_Start Soft_I2C_Read Soft_I2C_Write Soft_I2C_Stop Soft_I2C_Break Library Example 416 416 417 417 417 418 419 Software SPI Library 421 Software UART Library 425 Sound Library 430 SPI Library 433 SPI Ethernet Library 441 External dependencies of Software SPI Library Library Routines Soft_SPI_Init Soft_SPI_Read Soft_SPI_Write Library Example Library Routines Soft_UART_Init Soft_UART_Read Soft_UART_Write Soft_UART_Break Library Example
mikroC PRO for PIC32 SPI_Ethernet_putString SPI_Ethernet_putConstString SPI_Ethernet_getByte SPI_Ethernet_getBytes SPI_Ethernet_UserTCP SPI_Ethernet_UserUDP SPI_Ethernet_getIpAddress Ethernet_getGwIpAddress SPI_Ethernet_getDnsIpAddress SPI_Ethernet_getIpMask SPI_Ethernet_confNetwork SPI_Ethernet_arpResolve SPI_Ethernet_sendUDP SPI_Ethernet_dnsResolve SPI_Ethernet_initDHCP SPI_Ethernet_doDHCPLeaseTime SPI_Ethernet_renewDHCP Library Example HW Connection SPI Ethernet ENC24J600 Library Li
mikoC PRO for PIC32 SPI Graphic Lcd Library 484 SPI Lcd Library 500 SPI Lcd8 (8-bit interface) Library 506 Library Dependency Tree External dependencies of SPI Lcd Library Library Routines SPI_Glcd_Init SPI_Glcd_Set_Side SPI_Glcd_Set_Page SPI_Glcd_Set_X SPI_Glcd_Read_Data SPI_Glcd_Write_Data SPI_Glcd_Fill SPI_Glcd_Dot SPI_Glcd_Line SPI_Glcd_V_Line SPI_Glcd_H_Line SPI_Glcd_Rectangle SPI_Glcd_Rectangle_Round_Edges SPI_Glcd_Rectangle_Round_Edges_Fill SPI_Glcd_Box SPI_Glcd_Circle SPI
mikroC PRO for PIC32 SPI_Lcd8_Out SPI_Lcd8_Out_Cp SPI_Lcd8_Chr SPI_Lcd8_Chr_Cp SPI_Lcd8_Cmd Available SPI Lcd8 Commands Library Example SPI T6963C Graphic Lcd Library Library Dependency Tree External dependencies of SPI T6963C Graphic Lcd Library Library Routines SPI_T6963C_config SPI_T6963C_writeData SPI_T6963C_writeCommand SPI_T6963C_setPtr SPI_T6963C_waitReady SPI_T6963C_fill SPI_T6963C_dot SPI_T6963C_write_char SPI_T6963C_write_text SPI_T6963C_line SPI_T6963C_rectangle SPI_T6963C
mikoC PRO for PIC32 HW Connection 535 T6963C Graphic Lcd Library 536 TFT Library 561 MikroElektronika 22 Library Dependency Tree External dependencies of T6963C Graphic Lcd Library Library Routines T6963C_init T6963C_writeData T6963C_writeCommand T6963C_setPtr T6963C_waitReady T6963C_fill T6963C_dot T6963C_write_char T6963C_write_text T6963C_line T6963C_rectangle T6963C_rectangle_round_edges T6963C_rectangle_round_edges_fill T6963C_box T6963C_circle T6963C_circle_fill T6963C_im
mikroC PRO for PIC32 TFT_Set_Index TFT_Write_Command TFT_Write_Data TFT_Set_Active TFT_Set_Font TFT_Write_Char TFT_Write_Text TFT_Fill_Screen TFT_Dot TFT_Set_Pen TFT_Set_Brush TFT_Line TFT_H_Line TFT_V_Line TFT_Rectangle TFT_Rectangle_Round_Edges TFT_Circle TFT_Image TFT_Partial_Image TFT_Image_Jpeg TFT_RGBToColor16bit TFT_Color16bitToRGB HW Connection 564 564 564 565 566 567 567 568 569 570 571 573 574 574 574 575 575 575 576 576 577 577 578 Touch Panel Library 579 Touch Panel T
mikoC PRO for PIC32 TP_TFT_Set_Calibration_Consts HW Connection 588 589 UART Library 590 USB Library 600 Standard ANSI C Libraries ANSI C Ctype Library 606 606 ANSI C Math Library 610 Library Routines UARTx_Init UARTx_Init_Advanced UARTx_Data_Ready UARTx_Tx_Idle UARTx_Read UARTx_Read_Text UARTx_Write UARTx_Write_Text UART_Set_Active Library Example HW Connection USB HID Class Descriptor File Library Routines HID_Enable HID_Read HID_Write HID_Disable USB_Interrupt_Proc US
mikroC PRO for PIC32 Library Functions acos asin atan atan2 ceil cos cosh exp fabs floor frexp ldexp log log10 modf pow sin sinh sqrt tan tanh 610 610 611 611 611 611 611 612 612 612 612 612 613 613 613 613 613 614 614 614 614 614 ANSI C Stdlib Library 615 ANSI C String Library 620 Library Dependency Tree Library Functions abs atof atoi atol div ldiv uldiv labs max min rand srand xtoi Div Structures Library Functions memchr memcmp memcpy memmove memset str
mikoC PRO for PIC32 strchr strcmp strcpy strlen strncat strncpy strspn strncmp strstr strcspn strpbrk strrchr strtok 622 623 623 623 624 624 624 625 625 625 626 626 627 Miscellaneous Libraries Button Library 628 628 Conversions Library 630 PrintOut Library 642 Library Routines Button Library Dependency Tree Library Routines ByteToStr ShortToStr WordToStr IntToStr LongToStr LongWordToStr FloatToStr WordToStrWithZeros IntToStrWithZeros LongWordToStrWithZeros LongIntToSt
mikroC PRO for PIC32 PrintOut 642 Setjmp Library 646 Sprint Library 649 Time Library 653 Trigonometry Library 656 CHAPTER 10 Tutorials Managing Project 657 657 657 New Project 658 New Project 661 Customizing Projects 665 Add/Remove Files from Project 667 Source Files 669 Library Routines Setjmp Longjmp Library Example Library Dependency Tree Functions sprintf sprintl sprinti Library Example Library Routines Time_dateToEpoch Time_epochToDate Time_dateDiff Libr
mikoC PRO for PIC32 Closing file Search Paths Paths for Source Files (.c) Paths for Header Files (.h) 670 670 671 671 Edit Project Source Files 672 673 Clean Project Folder Compilation 676 677 Creating New Library 678 Frequently Asked Questions 679 Managing Source Files Creating new source file Opening an existing file Printing an open file Saving file Saving file under a different name Closing file Search Paths Paths for Source Files (.c) Paths for Header Files (.
mikroC PRO for PIC32 29 MikroElektronika
CHAPTER 1 mikoC PRO for PIC32 INTRODUCTION The mikroC PRO for PIC32 is a powerful, feature-rich development tool for PIC32 microcontrollers. It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems, without compromising performance or control.
mikroC PRO for PIC32 Introduction to mikroC PRO for PIC32 The PIC32 is a 32-bit family of general purpose microcontrollers. This is the Microchip’s first inherent 32-bit (data) microcontroller family. It builds upon the MIPS M4K 32-bit core, offering high-performance hardware multiply/divide unit, programmable user and kernel memory partition through an unified 4GB virtual memory space, with powerful peripherals to address a wide range of applications.
mikoC PRO for PIC32 Software License Agreement mikroElektronika Associates License Statement and Limited Warranty IMPORTANT - READ CAREFULLY This license statement and limited warranty constitute a legal agreement (“License Agreement”) between you (either as an individual or a single entity) and mikroElektronika (“mikroElektronika Associates”) for software product (“Software”) identified above, including any software, media, and accompanying on-line or printed documentation.
mikroC PRO for PIC32 IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS AND BUSINESS INFORMATION, BUSINESS INTERRUPTION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE PRODUCT OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF MIKROELEKTRONIKA ASSOCIATES HAS BEEN ADVISED OF THE POSSIBILITY O
mikoC PRO for PIC32 Technical Support The latest software can be downloaded free of charge via Internet (you might want to bookmark the page so you could check news, patches, and upgrades later on): http://www.pic32compilers.com/ . In case you encounter any problem, you are welcome to our support forums at www.mikroe.com/forum/. Here, you may also find helpful information, hardware tips, and practical code snippets.
mikroC PRO for PIC32 If you choose I work online registering method, following page will be opened in your default browser: 35 MikroElektronika
mikoC PRO for PIC32 Fill out the registration form, select your distributor, and click the Submit button. If you choose I work offline registering method, following window will be opened: Fill out the registration form, select your distributor, and click the Submit button. This will start your e-mail client with message ready for sending. Review the information you have entered, and add the comment if you deem it necessary. Please, do not modify the subject line.
mikroC PRO for PIC32 Important: - The license key is valid until you format your hard disk. In case you need to format the hard disk, you should request a new activation key. - Please keep the activation program in a safe place. Every time you upgrade the compiler you should start this program again in order to reactivate the license.
CHAPTER 2 mikoC PRO for PIC32 mikroC PRO for PIC32 Environment MikroElektronika 38
mikroC PRO for PIC32 Main Menu Options Available Main Menu options are: Related topics: Keyboard shortcuts, Toolbars 39 MikroElektronika
mikoC PRO for PIC32 File File Menu Options The File menu is the main entry point for manipulation with the source files. File Description Open a new editor window. Open source file for editing or image file for viewing. Reopen recently used file. Save changes for active editor. Save the active source file with the different name or change the file type. Close active source file. Close all opened files. Print Preview. Print. Exit IDE.
mikroC PRO for PIC32 Edit Edit Menu Options The Edit Menu contains commands for editing the contents of the current document. Edit Description Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard. Paste text from clipboard. Delete selected text. Select all text in active editor. Find text in active editor. Find next occurence of text in active editor. Find previous occurence of text in active editor. Replace text in active editor.
mikoC PRO for PIC32 Advanced » Description Comment selected code or put single line comment if there is no selection. Uncomment selected code or remove single line comment if there is no selection. Indent selected code. Outdent selected code. Changes selected text case to lowercase. Changes selected text case to uppercase. Changes selected text case to titlercase. Find Text Dialog box for searching the document for the specified text. The search is performed in the direction specified.
mikroC PRO for PIC32 Find In Files Dialog box for searching for a text string in current file, all opened files, or in files on a disk. The string to search for is specified in the Text to find field. If Search in directories option is selected, The files to search are specified in the Files mask and Path fields. Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned.
mikoC PRO for PIC32 View View Menu Options View Menu contains commands for controlling the on-screen display of the current project.
mikroC PRO for PIC32 View Description Show/Hide Software Simulator / mikroICD (In-Circuit Debugger) Debug Windows. Show/Hide Toolbars. Show/Hide Bookmarks window. Show/Hide Code Explorer window. Show/Hide Library Manager window. Show/Hide Macro Editor window. Show/Hide Messages window. Show/Hide Project Manager window. Show/Hide Project Settings window. Show/Hide Routine List in active editor. Show/Hide Quick Converter window. Show/Hide View Image Preview window. View Assembly. View Listing.
mikoC PRO for PIC32 Project Project Menu Options Project Menu allows the user to easily manipulate current project. Project Description Open New Project Wizard Open existing project. Open project group. Open recently used project or project group. Save current project. Save active project file with the different name. Close active project. Close project group. Add file to project. Remove file from project. Edit search paths. Edit project settings Clean Project Folder Export Project.
mikroC PRO for PIC32 Build Build Menu Options Build Menu allows the user to easily manage building and compiling process. Build Description Build active project. Rebuild all sources in active project. Build all projects. Stop building all projects. Build and program active project.
mikoC PRO for PIC32 Run Run Menu Options Run Menu is used to debug and test compiled code on a software or harware level. Run Description Start Software Simulator or mikroICD (In-Circuit Debugger). Stop Debugger. Run/Pause Debugger. Step Into. Step Over. Step Out. Run To Cursor. Jump to interrupt in current project. Toggle Breakpoint. Clear Breakpoints. Toggle between source and disassembly.
mikroC PRO for PIC32 Tools Tools Menu Options Tools Menu contains a number of applications designed to ease the use of compiler and included library routines. Tools Description Run mikroElektronika Programmer. Run Package Manager. Show/Hide Active Comment Editor window. Run ASCII Chart Run EEPROM Editor Generate HTML code suitable for publishing source code on the web.
mikoC PRO for PIC32 Help Help Menu Options Help Description Оpen Help File. Оpen Code Migration Document. Check if new compiler version is available. Open mikroElektronika Support Forums in a default browser. Open mikroElektronika Web Page in a default browser. Information on how to register Open About window.
mikroC PRO for PIC32 mikroC PRO for PIC32 IDE IDE Overview The mikroC PRO for PIC32 is an user-friendly and intuitive environment. For a detailed information on a certain part of IDE, simply click on it (hovering a mouse cursor above a desired IDE part will pop-up its name): - The Code Editor features adjustable Syntax Highlighting, Code Folding, Code Assistant, Parameters Assistant, Spell Checker, Auto Correct for common typos and Code Templates (Auto Complete).
mikoC PRO for PIC32 Code Editor The Code Editor is advanced text editor fashioned to satisfy needs of professionals. General code editing is the same as working with any standard text-editor, including familiar Copy, Paste and Undo actions, common for Windows environment. Available Code Editor options are: Editor Settings, Editor Colors, Auto Correct, Auto Complete and Style.
mikroC PRO for PIC32 Auto Save Auto Save is a function which saves an opened project automatically, helping to reduce the risk of data loss in case of a crash or freeze. Autosaving is done in time intervals defined by the user. Highlighter Highlighting is a convenient feature for spotting brackets which notate begin or end of a routine, by making them visually distinct.
mikoC PRO for PIC32 Another way of folding/unfolding code subsections is by using Alt+← and Alt+→. If you place a mouse cursor over the tooltip box, the collapsed text will be shown in a tooltip style box. Code Assistant If you type the first few letters of a word and then press Ctrl+Space, all valid identifiers matching the letters you have typed will be prompted in a floating panel (see the image below).
mikroC PRO for PIC32 Column Select Mode This mode changes the operation of the editor for selecting text. When column select mode is used, highlighted text is based on the character column position of the first character selected to the column of the last character of text selected. Text selected in this mode does not automatically include all text between the start and end position, but includes all text in the columns between the first and last character selected.
mikoC PRO for PIC32 Editor Colors option allows user to set, change and save text and color settings organized in schemes. Schemes represent custom graphical appearance that can be applied to GUI (Graphical User Interface) to satisfy tastes of different users. Auto Correct Auto Correct option facilitates the user in such a fashion that it automatically corrects common typing or spelling errors as it types. This option is already set up to automatically correct some words.
mikroC PRO for PIC32 The user can easily add its common typos by entering original typo, for example btye, to the Original box, and replacement, byte, to the Replacement box, and just click "Add" button. Next time when the typo occurs, it will be automatically corrected. Auto Complete (Code Templates) Auto Complete option saves lots of keystrokes for commonly used phrases by automatically completing user's typing.
mikoC PRO for PIC32 The user can insert the Code Template by typing the name of the template (for instance, dow), then press Ctrl+J and the Code Editor will automatically generate a code: You can add your own templates to the list by entering the desired keyword, description and code of your template in appropriate boxes.
mikroC PRO for PIC32 Code Explorer The Code Explorer gives clear view of each item declared inside the source code. You can jump to a declaration of any item by double clicking it, or pressing the Enter button. Also, besides the list of defined and declared objects, code explorer displays message about the first error and it's location in code. The following options are available in the Code Explorer: Icon Description Expand/Collapse all nodes in tree. Locate declaration in code.
mikoC PRO for PIC32 Routine List Routine list diplays list of routines, and enables filtering routines by name. Routine list window can be accessed by pressing Ctrl+L. You can jump to a desired routine by double clicking on it, or pressing the Enter button. Also, you can sort routines by size or by address. Project Manager Project Manager is IDE feature which allows the users to manage multiple projects. Several projects which together make project group may be open at the same time.
mikroC PRO for PIC32 Following options are available in the Project Manager: Icon Description Save project Group. Open project group. Close the active project. Close project group. Add project to the project group. Remove project from the project group. Add file to the active project. Remove selected file from the project. Build the active project. Run mikroElektronika’s Flash programmer. For details about adding and removing files from project see Add/Remove Files from Project.
mikoC PRO for PIC32 Project Settings The following options are available in the Project Settings window: - Device - select the appropriate device from the device drop-down list. - MCU Clock - enter the clock frequency value. - Build/Debugger Type - choose debugger type.
mikroC PRO for PIC32 Library Manager Library Manager enables simple handling libraries being used in a project. Library Manager window lists all libraries (extension .emcl) which are instantly stored in the compiler Uses folder. The desirable library is added to the project by selecting check box next to the library name.
mikoC PRO for PIC32 Managing libraries using Package Manager The Package Manager is a tool which enables users to easily install their own libraries in the mikroIDE. Libraries are distributed in the form of a package, which is an archive composed of one or more files, containing libraries. For more information on Package Manager, visit our website. Upon package installation, a new node with the package name will be created in the Library Manager.
mikroC PRO for PIC32 Routine List Routine list diplays list of routines, and enables filtering routines by name. Routine list window can be accessed by pressing Ctrl+L. You can jump to a desired routine by double clicking on it, or pressing the Enter button. Also, you can sort routines by size or by address. Statistics After successful compilation, you can review statistics of your code. Click the Statistics Icon . Memory Usage Windows Provides overview of RAM and ROM usage in the various forms.
mikoC PRO for PIC32 Variables Displays variables sorted by addresses. Used RAM Locations Displays used RAM memory locations and their names.
mikroC PRO for PIC32 SFR Locations Displays list of used SFR locations. ROM Memory Usage Displays ROM memory space usage in a pie-like form.
mikoC PRO for PIC32 ROM Memory Constants Displays ROM memory constants and their addresses. Functions Sorts and displays functions in various ways.
mikroC PRO for PIC32 Functions Sorted By Name Chart Sorts and displays functions by their name, in the ascending order. Functions Sorted By Size Chart Sorts and displays functions by their sizes in a chart-like form.
mikoC PRO for PIC32 Functions Sorted By Addresses Sorts and displays functions by their addresses, in the ascending order. Function Tree Displays Function Tree with the relevant data for each function.
mikroC PRO for PIC32 Memory Summary Displays summary of RAM and ROM memory in a pie-like form.
mikoC PRO for PIC32 Messages Window Messages Window displays various informations and notifications about the compilation process. It reports for example, time needed for preprocessing, compilation and linking; used RAM and ROM space, generated baud rate with error percentage, etc. The 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.
mikroC PRO for PIC32 Quick Converter Quick Converter enables the user to easily transform numbers from one base to another. The user can convert integers of various sizes (8, 16 or 32 bits), signed and unsigned, using different representation (decimal, hexadecimal, binary and character). Also, Quick Converter features float point numbers conversion from/to Float Decimal, Float 32bit (IEEE), Float 32bit (Microchip) and Radix 1.15 for PIC32 family of MCUs.
mikoC PRO for PIC32 The Macro offers the following commands: Icon Description Starts ‘recording’ keystrokes for later playback. Stops capturing keystrokes that was started when the Start Recording command was selected. Allows a macro that has been recorded to be replayed. New macro. Delete macro.
mikroC PRO for PIC32 Now, navigate to the desired image file, and simply add it: Next, right click the added file, and choose Set As Preview Image: 75 MikroElektronika
mikoC PRO for PIC32 Once you have added the image, it will appear in the Image Preview Window: Also, you can add multiple images to the Image Files node, but only the one that is set will be automatically displayed in the Image Preview Window upon opening the project. By changing the Image Preview Window size, displayed image will be fit by its height in such a way that its proportions will remain intact.
mikroC PRO for PIC32 File Toolbar File Toolbar is a standard toolbar with the following options: Icon Description Opens a new editor window. Open source file for editing or image file for viewing. Save changes for active window. Save changes in all opened windows. Print Preview. Print. Edit Toolbar Edit Toolbar is a standard toolbar with the following options: Icon Description Undo last change. Redo last change. Cut selected text to clipboard. Copy selected text to clipboard. Paste text from clipboard.
mikoC PRO for PIC32 Advanced Edit Toolbar Advanced Edit Toolbar comes with the following options: Icon Description Comment selected code or put a single line comment if there is no selection Uncomment selected code or remove single line comment if there is no selection. Select text from starting delimiter to ending delimiter. Go to ending delimiter. Go to line. Indent selected code lines. Outdent selected code lines. Generate HTML code suitable for publishing current source code on the web.
mikroC PRO for PIC32 Project Toolbar Project Toolbar comes with the following options: Icon Description New project. Open Project Save Project Edit project settings. Close current project. Clean project folder. Add File To Project Remove File From Project Build Toolbar Build Toolbar comes with the following options: Icon Description Build current project. Build all opened projects. Build and program active project. Start programmer and load current HEX file.
mikoC PRO for PIC32 Debug Toolbar Debug Toolbar comes with the following options: Icon Description Start Software Simulator or mikroICD (In-Circuit Debugger). Run/Pause Debugger. Stop Debugger. Step Into. Step Over. Step Out. Run To Cursor. Toggle Breakpoint. View Breakpoints Window Clear Breakpoints. View Watch Window View Stopwatch Window Styles Toolbar Styles toolbar allows you to easily change colors of your workspace.
mikroC PRO for PIC32 Tools Toolbar Tools Toolbar comes with the following default options: Icon Description Run USART Terminal EEPROM ASCII Chart Seven Segment Editor. Open Active Comment editor. Options menu Tip : The Tools toolbar can easily be customized by adding new tools in Options menu window. View Toolbar View Toolbar provides access to assembly code, listing file and statistics windows. Icon Description Open assembly code in editor. Open listing file in editor.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 Customizing IDE Layout Docking Windows You can increase the viewing and editing space for code, depending on how you arrange the windows in the IDE. Step 1: Click the window you want to dock, to give it focus. Step 2: Drag the tool window from its current location. A guide diamond appears. The four arrows of the diamond point towards the four edges of the IDE.
mikoC PRO for PIC32 Step 3: Move the pointer over the corresponding portion of the guide diamond. An outline of the window appears in the designated area. Step 4: To dock the window in the position indicated, release the mouse button. Tip : To move a dockable window without snapping it into place, press CTRL while dragging it. Saving Layout Once you have a window layout that you like, you can save the layout by typing the name for the layout and pressing the Save Layout Icon .
mikroC PRO for PIC32 When an auto-hidden window loses focus, it automatically slides back to its tab on the edge of the IDE. While a window is auto-hidden, its name and icon are visible on a tab at the edge of the IDE. To display an auto-hidden window, move your pointer over the tab. The window slides back into view and is ready for use. Options Options menu consists of three tabs: Code Editor, Tools and Output settings.
mikoC PRO for PIC32 Output settings By modifying Output Settings, user can configure the content of the output files. You can enable or disable, for example, generation of ASM and List file. Also, user can choose optimization level, and compiler specific settings, which include case sensitivity, dynamic link for string literals setting (described in mikroC PRO for PIC32 specifics). Build all files as library enables user to use compiled library (*.
mikroC PRO for PIC32 87 MikroElektronika
mikoC PRO for PIC32 Integrated Tools Active Comments Editor Active Comments Editor is a tool, particularly useful when working with Lcd display. You can launch it from the dropdown menu Tools › Active Comments Editor or by clicking the Active Comment Editor Icon MikroElektronika from Tools toolbar.
mikroC PRO for PIC32 ASCII Chart The ASCII Chart is a handy tool, particularly useful when working with Lcd display. You can launch it from the dropdown menu Tools › ASCII chart or by clicking the View ASCII Chart Icon 89 from Tools toolbar.
mikoC PRO for PIC32 EEPROM Editor The EEPROM Editor is used for manipulating MCU's EEPROM memory. You can launch it from the drop-down menu Tools › EEPROM Editor. When you run mikroElektronika programmer software from mikroC PRO for PIC32 IDE - project_name.hex file will be loaded automatically while ihex file must be loaded manually.
mikroC PRO for PIC32 Graphic Lcd Bitmap Editor The mikroC PRO for PIC32 includes the Graphic Lcd Bitmap Editor. Output is the mikroC PRO for PIC32 compatible code. You can launch it from the drop-down menu Tools › Glcd Bitmap Editor.
mikoC PRO for PIC32 HID Terminal The mikroC PRO for PIC32 includes the HID communication terminal for USB communication. You can launch it from the drop-down menu Tools › HID Terminal. Interrupt Assistant mikroC PRO for PIC32 includes the Interrupt Assistant that assist user in configuring interrupts. Output is the code for the configured interrupt routine. You can launch it from the drop-down menu Tools › Interrupt Assistant.
mikroC PRO for PIC32 Lcd Custom Character mikroC PRO for PIC32 includes the Lcd Custom Character. Output is mikroC PRO for PIC32 compatible code. You can launch it from the drop-down menu Tools › Lcd Custom Character.
mikoC PRO for PIC32 Seven Segment Editor The Seven Segment Editor is a convenient visual panel which returns decimal/hex value for any viable combination you would like to display on seven segment display. Click on the parts of seven segment image to get the requested value in the edit boxes. You can launch it from the drop-down menu Tools › Seven Segment Editor or by clicking the Seven Segment Editor Icon from Tools toolbar. UDP Terminal The mikroC PRO for PIC32 includes the UDP Terminal.
mikroC PRO for PIC32 USART Terminal The mikroC PRO for PIC32 includes the USART communication terminal for RS232 communication. You can launch it from the drop-down menu Tools › USART Terminal or by clicking the USART Terminal Icon 95 from Tools toolbar.
mikoC PRO for PIC32 Active Comments The idea of Active Comments is to make comments alive and give old fashioned comments new meaning and look. From now on, you can assign mouse event on your comments and 'tell' your comments what to do on each one. For example, on left mouse click, open some web address in your browser, on mouse over show some picture and on mouse double click open some file.
mikroC PRO for PIC32 You can notice that when you start typing a name, properties pane is automatically displayed so you can edit properties if you wish. A Comment will be is created when you click button. Properties are consisted of two major categories - Attributes and Events. Attributes can be: - URL - Valid web address. - Image - Image has to be previously added to Project (Project Manager > Images). - File - File has to be previously added to Project (Project Manager > Other Files).
mikoC PRO for PIC32 First three event types can have one of the following three actions: 1. OpenUrl - Opens entered URL in default Web browser. 2. OpenFile - Opens a file within a default program associated with the file extension (defined by Windows). 3. None - Does nothing. The fourth event, OnMouseOver, has only 2 actions: 1. PreviewImage - Shows image when cursor is moved over a comment. 2. None - Does nothing. Attributes are tightly bounded with events.
mikroC PRO for PIC32 You can see the contents of the created XML file by expanding Active Comment Editor: As we mentioned above you can add image or file which are already included in project. If the the desired image or file aren't added, you can do it directly from here by clicking the 99 or button.
mikoC PRO for PIC32 Next file dialog will be opened: There, you should select the desired image to be added. In our example, Easy_GSM_GPRS.jpg image will be added.
mikroC PRO for PIC32 Now, when image has been selected, we can assign an event to it. For example, OnMouseOver will be used for PreviewImage action, and OnLeftClick + Alt will be assigned to OpenUrl action: Now we can save our changes to Active Comment by clicking the Save button. Note: Setting file attributes is same as for image, so it won't be explained separately.
mikoC PRO for PIC32 There is another way to add an active comment to an active project. You can do it simply by typing a comment in old fashion way, except with ac: prefix. So it would look like this: Notice that when you stop typing, Add Comment To Project button will show. By clicking on it, you will open Active Comment Editor and comment name will be already set, so you need only to adjust attributes and settings.
mikroC PRO for PIC32 If you click No, comment will be removed from the source code.
mikoC PRO for PIC32 Now click again Rename button. Now you have renamed your Active Comment in such a way that its filename, source code name are changed: Deleting Active Comment Deleting active comment works similar like renaming it. By clicking on delete button, you will remove an active comment from both code and Project Manager.
mikroC PRO for PIC32 Export Project This option is very convenient and finds its use in relocating your projects from one place to another (e.g. from your work computer to your home computer). Often, project contains complicated search paths (files involved within your project could be in a different folders, even on different hard disks), so it is very likely that some files will be forgotten during manual relocation.
mikoC PRO for PIC32 Jump To Interrupt Lets you choose which interrupt you want to jump to. Requirement: Interrupt routine is included in project. You can call Jump To Interrupt by selecting Run › Jump To Interrupt from the drop-down menu, or by clicking the Jump To Interrupt Icon , from the Watch Values Window. By checking the Only Used box, you can display only the used breakpoints.
mikroC PRO for PIC32 Regular Expressions Introduction Regular Expressions are a widely-used method of specifying patterns of text to search for. Special metacharacters allow you to specify, for instance, that a particular string you are looking for, occurs at the beginning, or end of a line, or contains n recurrences of a certain character. Simple matches Any single character matches itself, unless it is a metacharacter with a special meaning described below.
mikoC PRO for PIC32 Examples: count[aeiou]r finds strings 'countar', 'counter', etc. but not 'countbr', 'countcr', etc. count[^aeiou]r finds strings 'countbr', 'countcr', etc. but not 'countar', 'counter', etc. Within a list, the "-" character is used to specify a range, so that a-z represents all characters between "a" and "z", inclusive. If you want "-" itself to be a member of a class, put it at the start or end of the list, or precede it with a backslash.
mikroC PRO for PIC32 Metacharacters - Predefined classes \w - an alphanumeric character (including "_") \W - a nonalphanumeric character \d - a numeric character \D - a non-numeric character \s - any space (same as [\t\n\r\f]) \S - a non space You may use \w, \d and \s within custom character classes. Example: so on.
mikoC PRO for PIC32 Examples: count.*r ß- matches strings like 'counter', 'countelkjdflkj9r' and 'countr' count.+r - matches strings like 'counter', 'countelkjdflkj9r' but not 'countr' count.?r - matches strings like 'counter', 'countar' and 'countr' but not 'countelkj9r' counte{2}r - matches string 'counteer' counte{2,}r - matches strings like 'counteer', 'counteeer', 'counteeer' etc.
mikroC PRO for PIC32 Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroC PRO for PIC32 IDE.
mikoC PRO for PIC32 Ctrl+F5 Add to Watch List Ctrl+F8 Step Out Alt+D Disassembly View Shift+F5 Open Watch Window Ctrl+Shift+A Show Advanced Breakpoints MikroElektronika 112
mikroC PRO for PIC32 CHAPTER 3 mikroC PRO for PIC32 Command Line Options Usage: mikroCPIC32.exe [- [-]] [ [-]] [-]] Infile can be of *.c, *.emcl and *.pld type. The following parameters are valid: -P : MCU for which compilation will be done. -FO : Set oscillator [in MHz]. -SP : Add directory to the search path list. -N : Output files generated to file path specified by filename. -B : Save compiled binary files (*.
mikoC PRO for PIC32 Example: mikroCPIC32.exe -MSF -DBG -p32MX460F512L -Y -DL -O11111114 -fo80 -N”C:\Lcd\Lcd.mcp32” -SP”C:\Program Files\Mikroelektronika\mikroC PRO for PIC32\Defs” -SP”C:\Program Files\Mikroelektronika\mikroC PRO for PIC32\Uses” -SP”C:\ Lcd\” “Lcd.c” “__Lib_Math.emcl” “__Lib_MathDouble.emcl” “__Lib_System.emcl” “__Lib_Delays.emcl” “__Lib_LcdConsts.emcl” “__Lib_Lcd. emcl” Parameters used in the example: -MSF : Short Message Format; used for internal purposes by IDE.
mikroC PRO for PIC32 CHAPTER 4 mikroICD (In-Circuit Debugger) Introduction The mikroICD is a highly effective tool for a Real-Time debugging on hardware level. The mikroICD debugger enables you to execute the mikroC PRO for PIC32 program on a host PIC32 microcontroller and view variable values, Special Function Registers (SFR), RAM, CODE and EEPROM memory along with the mikroICD code execution on hardware.
mikoC PRO for PIC32 If you have appropriate hardware and software for using the mikroICD select mikroICD Debug Build Type before compiling the project. Now, compile the project by pressing Ctrl + F9, or by pressing Build Icon on Build Toolbar. Run the mikroICD by selecting Run › Start Debugger from the drop-down menu or by clicking the Start Debugger Icon . Starting the Debugger makes more options available: Step Into, Step Over, Run to Cursor, etc.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 mikroICD Debugger Example Here is a step-by-step mikroICD Debugger Example. First you have to write a program.
mikroC PRO for PIC32 After successful compilation and MCU programming press F9 to start the mikroICD. After the mikroICD initialization a blue active line should appear. We will debug the program line by line. 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.
mikoC PRO for PIC32 Step Into [F7], Step Over [F8] and Step Out [Ctrl+F8] are mikroICD debugger functions that are used in stepping mode. There is also a Real-Time mode supported by the mikroICD. Functions that are used in the Real-Time mode are Run/Pause Debugger [F6] and Run to cursor [F4]. Pressing F4 executes the code until the program reaches the cursor position line. Run(Pause) Debugger [F6] and Toggle Breakpoints [F5] are mikroICD debugger functions that are used in the RealTime mode.
mikroC PRO for PIC32 Breakpoints are divided into two groups: hardware and software breakpoints. The hardware breakpoints are placed in the MCU and provide fastest debugging. Number of hardware breakpoints is limited to 8 (6 instruction, 2 data). If all hardware brekpoints are used, then the next breakpoint will be software breakpoint. These breakpoints are placed inside the mikroICD and simulate hardware breakpoints. Software breakpoints are much slower than hardware breakpoints.
mikoC PRO for PIC32 mikroICD Debugger Windows Debug Windows This section provides an overview of available Debug Windows in mikroC PRO for PIC32: - Breakpoints Window - Watch Values Window - RAM Window - Stopwatch Window - EEPROM Watch Window - Code Watch Window Breakpoints Window The Breakpoints window manages the list of currently set breakpoints in the project. Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code.
mikroC PRO for PIC32 Also, it is possible to add all variables in the Watch Values Window by clicking button. To remove a variable from the Watch Values Window, just select the variable that you want to remove and then click the button, or press the Delete key. It is possible to remove all variables from the Watch Values Window by clicking button. You can also expand/collapse complex variables i.e. struct type variables, strings, etc, by clicking the appropriate button ( or ) beside variable name.
mikoC PRO for PIC32 RAM Window The RAM Window is available from the drop-down menu, View › Debug Windows › RAM. The RAM Window displays the map of MCU’s RAM, with recently changed items colored red. The user can edit and change the values in the RAM window. mikroICD Specific: RAM window content will be written to the MCU before the next instruction execution. Stopwatch Window The Software Simulator Stopwatch Window is available from the drop-down menu, View › Debug Windows › Stopwatch.
mikroC PRO for PIC32 Notes: - The user can change the clock in the Stopwatch Window, which will recalculate values for the latest specified frequency. - Changing the clock in the Stopwatch Window does not affect actual project settings – it only provides a simulation. - Stopwatch is available only when Software Simulator is selected as a debugger. EEPROM Watch Window Note: EEPROM Watch Window is available only when mikroICD is selected as a debugger.
mikoC PRO for PIC32 Code Watch Window Note: Code Watch Window is available only when mikroICD is selected as a debugger. To show the Code Watch Window, select Debug Windows › Code from the View drop-down menu. The Code Watch Window shows code (hex format) written into the MCU. There is one action button concerning the Code Watch Window: - Reads code from the MCU and loads it up into the Code Window. Code reading is resources consuming operation so the user should wait until the reading is over.
mikroC PRO for PIC32 CHAPTER 5 Software Simulator Overview 127 MikroElektronika
mikoC PRO for PIC32 Software Simulator The Source-level Software Simulator is an integral component of the mikroC PRO for PIC32 environment. It is designed to simulate operations of the Microchip PIC32 MCUs and assist the users in debugging code written for these devices.
mikroC PRO for PIC32 Software Simulator Debug Windows Debug Windows This section provides an overview of available Debug Windows in mikroC PRO for PIC32: - Breakpoints Window - Watch Values Window - RAM Window - Stopwatch Window - EEPROM Watch Window - Code Watch Window Breakpoints Window The Breakpoints window manages the list of currently set breakpoints in the project. Doubleclicking the desired breakpoint will cause cursor to navigate to the corresponding location in source code.
mikoC PRO for PIC32 Also, it is possible to add all variables in the Watch Values Window by clicking button. To remove a variable from the Watch Values Window, just select the variable that you want to remove and then click the button, or press the Delete key. It is possible to remove all variables from the Watch Values Window by clicking button. You can also expand/collapse complex variables i.e. struct type variables, strings, etc, by clicking the appropriate button ( or ) beside variable name.
mikroC PRO for PIC32 RAM Window The RAM Window is available from the drop-down menu, View › Debug Windows › RAM. The RAM Window displays the map of MCU’s RAM, with recently changed items colored red. The user can edit and change the values in the RAM window. mikroICD Specific: RAM window content will be written to the MCU before the next instruction execution. Stopwatch Window The Software Simulator Stopwatch Window is available from the drop-down menu, View › Debug Windows › Stopwatch.
mikoC PRO for PIC32 Notes: - The user can change the clock in the Stopwatch Window, which will recalculate values for the latest specified frequency. - Changing the clock in the Stopwatch Window does not affect actual project settings – it only provides a simulation. - Stopwatch is available only when Software Simulator is selected as a debugger. EEPROM Watch Window Note: EEPROM Watch Window is available only when mikroICD is selected as a debugger.
mikroC PRO for PIC32 Code Watch Window Note: Code Watch Window is available only when mikroICD is selected as a debugger. To show the Code Watch Window, select Debug Windows › Code from the View drop-down menu. The Code Watch Window shows code (hex format) written into the MCU. There is one action button concerning the Code Watch Window: - Reads code from the MCU and loads it up into the Code Window. Code reading is resources consuming operation so the user should wait until the reading is over.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 CHAPTER 6 mikroC PRO for PIC32 Specifics The following topics cover the specifics of mikroC PRO for PIC32 compiler: - ANSI Standard Issues - Predefined Globals and Constants - Accessing Individual Bits - Interrupts - Linker Directives - Built-in Routines - Code Optimization 135 MikroElektronika
mikoC PRO for PIC32 ANSI Standard Issues Divergence from the ANSI C Standard The mikroC PRO for PIC32 diverges from the ANSI C standard in a few areas. Some of these modifications are improvements intended to facilitate PIC32 programming, while others are the result of PIC32 hardware limitations. - Case Sensitivity. Check identifiers - The mikroC PRO for PIC32 treats identifiers declared with the const qualifier as “true constants” (C++ style).
mikroC PRO for PIC32 Predefined Globals and Constants To facilitate PIC32 programming, the mikroC PRO for PIC32 implements a number of predefined globals and constants. All PIC32 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 PIC32 will include an appropriate (*.
mikoC PRO for PIC32 Accessing Individual Bits The mikroC PRO for PIC32 allows you to access individual bits of 32-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 PIC32 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 PIC32 compiler has sbit data type which provides access to registers, SFRs, variables, etc.
mikoC PRO for PIC32 at keyword You can use the keyword "at" to make an alias to a variable, for example, you can write a library without using register names, and later in the main program to define those registers, for example: 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 PIC32 Interrupts The PIC32MX generates interrupt requests in response to interrupt events from peripheral modules. The Interrupt module exists external to the CPU logic and prioritizes the interrupt events before presenting them to the CPU. The PIC32MX Interrupts module includes the following features: - Up to 96 interrupt sources. - Up to 64 interrupt vectors. - Single and Multi-Vector mode operations. - Five external interrupts with edge polarity control. - Interrupt proximity timer.
mikoC PRO for PIC32 Interrupt Priorities In the Multi Vector Mode, the user is able to assign a group priority and group subpriority level to each of the interrupt vectors. The user-selectable priority levels range from 1 (the lowest priority) to 7 (the highest). If an interrupt priority is set to zero, the interrupt vector is disabled for both interrupt and wake-up purposes. Interrupt vectors with a higher priority level preempt lower priority interrupts.
mikroC PRO for PIC32 where: - iv - reserved word that inform the compiler that it is an interrupt service routine. - IVT_ADC - appropriate Interrupt Vector. - ilevel 7 - Interrupt priority level 7. - ics Interrupt Context Saving; Interrupt Context Saving can be performed in several ways: 1. ICS_SOFT - Context saving is carried out by the software. 2. ICS_SRS - Shadow Register set is use for context saving. 3. ICS_OFF - No context saving 4.
mikoC PRO for PIC32 Interrupt Example Here is a simple example of handling the interrupts from Timer1 (if no other interrupts are allowed): void Timer1_interrupt() iv IVT_TIMER_1 ilevel 7 ics ICS_SRS { T1IF_bit = 0; // Clear T1IF LATB = ~ PORTB; // Invert PORTB } void main() { AD1PCFG = 0xFFFF; TRISB = 0; LATB = 0xAAAA; } // Initialize AN pins as digital // initialize PORTB as output // Initialize PORTB value TMR1 = 0; PR1 = 65535; // reset timer value to zero // Load period register T1IP0_bit = 1; T1I
mikroC PRO for PIC32 Linker Directives The mikroC PRO for PIC32 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. When using these directives, be sure to use them in proper memory segments, i.e. for functions it is the KSEG0 and for variables it is the KSEG1. Linker directives are used with the virtual addresses.
mikoC PRO for PIC32 Directive org Directive org specifies a starting address of a routine in ROM. Directive org is appended to the function definition. Directives applied to non-defining declarations will be ignored, with an appropriate warning issued by the linker. Here is a simple example: void func(int par) org 0xBD000000 { // Function will start at address 0xBD000000 asm nop; } It is possible to use org directive with functions that are defined externally (such as library functions).
mikroC PRO for PIC32 Note: The #pragma funcall directive can help the linker to optimize function frame allocation in the compiled stack. Related topics: Linker Directives Built-in Routines The mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 KVA_TO_PA Prototype Description unsigned long KVA_TO_PA(const unsigned long Address); Function converts virtual address from any Kernel segment to the appropriate physical address. Parameters Desired Virtual address. Returns Appropriate physical address. Requires Nothing. Example KVA_TO_PA(0xBFC00000); Notes None. PA_TO_KVA0 Prototype Description unsigned long PA_TO_KVA0(const unsigned long Address); Function converts physical address to the virtual address in the KSEG0.
mikoC PRO for PIC32 CP0_SET Prototype Description Parameters Returns void CP0_SET(TCPOReg register, unsigned long value); Function sets the value of the coprocessor register or part of the register, based upon the register argument. - register: Register or register part, must be a constant from the enumerated built-in constants list, which can be found at the bottom of this page. - value: Register Value. Nothing. Requires Nothing. Example CP0_SET(CP0_CONFIG, 0x1A2C0000); Notes None.
mikroC PRO for PIC32 Copressor Register Fields CP0_HWRENA_MASK CP0_STATUS_IE CP0_STATUS_EXL CP0_STATUS_ERL CP0_STATUS_UM CP0_STATUS_IM0 CP0_STATUS_IM1 CP0_STATUS_IPL CP0_STATUS_IM2 CP0_STATUS_IM3 CP0_STATUS_IM4 CP0_STATUS_IM5 CP0_STATUS_IM6 CP0_STATUS_IM7 CP0_STATUS_CEE CP0_STATUS_NMI _CPO_STATUS_SR CP0_STATUS_TS CP0_STATUS_BEV CP0_STATUS_RE CP0_STATUS_FR CP0_STATUS_RP CP0_STATUS_CU0 CP0_STATUS_CU1 CP0_STATUS_CU2 CP0_STATUS_CU3 CP0_INTCTL_VS CP0_INTCTL_IPPCI CP0_INTCTL_IPTI CP0_
mikoC PRO for PIC32 Code Optimization Optimizer has been added to extend the compiler usability, cut down the amount of code generated and speed-up its execution. The main features are: Constant folding All expressions that can be evaluated in the compile time (i.e. constant) are being replaced by their results.
mikroC PRO for PIC32 Single Static Assignment Optimization Introduction In compiler design, static single assignment form (often abbreviated as SSA form or SSA) is an intermediate representation (IR) in which every variable is assigned exactly once. An SSA-based compiler modifies the program representation so that every time a variable is assigned in the original program, a new version of the variable is created.
mikoC PRO for PIC32 Without SSA enabled, this example is consisted of 5 asm instructions: ;Example.
mikroC PRO for PIC32 Asm code and SSA optimization If converting code from an earlier version of the compiler, which consists of mixed asm code with the C code, keep in mind that the generated code can substantially differ when SSA optimization option is enabled or disabled. This is due to the fact that SSA optimization uses certain working registers to store routine parameters (W10-W13), rather than storing them onto the function frame.
CHAPTER 7 mikoC PRO for PIC32 PIC32 Specifics In order to get the most from the mikroC PRO for PIC32 compiler, the user should be familiar with certain aspects of PIC32 MCU. This knowledge is not essential, but it can provide a better understanding of the PIC32’s capabilities and limitations, and their impact on the code writing as well.
mikroC PRO for PIC32 Types Efficiency First of all, the user should know that PIC32’s ALU, which performs arithmetic operations, is optimized for working with 32-bit types. Also, it performs hardware multiplication and division on the integer level, so the floating multiplication and division is slower and consumes more memory comparing it to the integer. The PIC32 supports 64-bit data types, but they are less efficient. They provide higher precision, but lack the code size and the execution.
mikoC PRO for PIC32 PIC32 Memory Organization The PIC32MX microcontrollers provide 4 GB of unified virtual memory address space. All memory regions, including program memory, data memory, SFRs and Configuration registers reside in this address space at their respective unique addresses. The program and data memories can be optionally partitioned into user and kernel memories. In addition, the data memory can be made executable, allowing the PIC32MX to execute from data memory.
mikroC PRO for PIC32 PIC32MX Memory Layout The PIC32MX microcontrollers implement two address spaces: virtual and physical. All hardware resources, such as program memory, data memory and peripherals, are located at their respective physical addresses. Peripherals, such as DMA and Flash controllers, use physical addresses and access memory independently of the CPU. Virtual addresses are exclusively used by the CPU to fetch and execute instructions.
mikoC PRO for PIC32 As it can be seem, the entire 4 GB virtual address space is divided into two primary regions: User and Kernel space. The lower 2 GB of space called USEG/KUSEG, and the upper 2 GB are divided into KSEG0, KSEG1, KSEG2 and KSEG3. Virtual vs Physical Addresses The PIC32MX’s CPU uses virtual addresses to address the peripherals, which means that to access the PIC32MX’s peripherals we (and the CPU) must be operating within the virtual boundaries of KSEG1.
mikroC PRO for PIC32 Memory Type Specifiers The mikroC PRO for PIC32 supports usage of all memory areas. Each variable may be explicitly assigned to a specific memory space by including a memory type specifier in the declaration, or implicitly assigned. The following memory type specifiers can be used: - code - data - rx (reserved for compiler purposes only) - sfr code Description The code memory type may be used for allocating constants in program memory.
mikoC PRO for PIC32 Read Modify Write Problem The Microchip microcontrollers use a sequence known as Read-Modify-Write (RMW) when changing an output state (1 or 0) on a pin. This can cause unexpected behavior under certain circumstances. When your program changes the state on a specific pin, for example RB0 in PORTB, the microcontroller first READs all 8 bits of the PORTB register which represents the states of all 8 pins in PORTB (RB7-RB0). The microcontroller then stores this data in the MCU.
mikroC PRO for PIC32 Actual voltage levels on MCU pins are relevant. MODIFY Data is modified to set the RB0 bit: WRITE PORTB is written with the modified data. The output driver for RB0 turns on, and the capacitor starts to charge: The second line, PORTB.
mikoC PRO for PIC32 To correct the problem in the code, insert a delay after each PORTB.Bx = 1 line, or modify the entire PORTB register in a single line PORTB = 0b00000011. This problem can be avoided by using LATx register when writing to ports, rather than using PORTx registers. Writing to a LATx register is equivalent to writing to a PORTx register, but readings from LATx registers return the data value held in the port latch, regardless of the state of the actual pin.
mikroC PRO for PIC32 The second line, LATB.B1 = 1; will be decoded like in this way: READ LATB is read: STORE Since the voltage levels on MCU pins are no longer relevant, we get the expected value: Actual voltage levels on MCU pins are no longer relevant when using LATx for output MODIFY Data is modified to set the bit: WRITE LATB is written with the new data.
CHAPTER 8 mikoC PRO for PIC32 mikroC PRO for PIC32 Language Reference MikroElektronika 172
mikroC PRO for PIC32 - 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 Typ
mikoC PRO for PIC32 - 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
mikroC PRO for PIC32 - 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 PIC32 lexical elements.
mikoC PRO for PIC32 Whitespace Whitespace is a collective name given to spaces (blanks), horizontal and vertical tabs, newline characters and comments. Whitespace can serve to indicate where tokens start and end, but beyond this function, any surplus whitespace is discarded.
mikroC PRO for PIC32 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 PIC32. You should also follow the guidelines on the use of whitespace and delimiters in comments, discussed later in this topic to avoid other portability problems.
mikoC PRO for PIC32 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 PIC32 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 ##.
mikroC PRO for PIC32 Constants Constants or literals are tokens representing fixed numeric or character values. The mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 int -128 – 127 short 128 – 255 unsigned short 256 – 32767 int 32768 – 65535 unsigned int 65536 – 2147483647 long 2147483648 – 4294967295 unsigned long > 4294967295 Error: Out of range! Hexadecimal All constants starting with 0x (or 0
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 - 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 PIC32 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 PIC32 Libraries.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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) * (
mikoC PRO for PIC32 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 PIC32 might ignore it.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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).
mikroC PRO for PIC32 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).
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 Types The mikroC PRO for PIC32 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 PIC32 works exclusively with numeric types.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 PIC32’s implementation of an ANSI Standard considers all three to be the same type. Floating point in the mikroC PRO for PIC32 is implemented using the Microchip AN575 32-bit format (IEEE 754 compliant). An overview of the floating-point types is shown in the table below: float Type Size in bytes 4 double 4 Range 45 -1.5 * 10 .. +3.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 Pointers Pointers are special objects for holding (or “pointing to”) memory addresses. In the mikroC PRO for PIC32, 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).
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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); } } 205 MikroElektronika
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 //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 PIC32 is limited to: - assigning one pointer to another, - comparing two pointers, - comparing pointer to zero, - adding/subtracting pointer and an integer value, - subtracting two pointers.
mikoC PRO for PIC32 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] /* ..
mikroC PRO for PIC32 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).
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 { ...
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 64 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.
mikroC PRO for PIC32 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 ...
mikoC PRO for PIC32 Standard Conversions Standard conversions are built in the mikroC PRO for PIC32. 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. Then, the type of the result is that of more complex operand.
mikroC PRO for PIC32 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”.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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,...
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 PIC32 treats objects declared with the const qualifier the same as literals or preprocessor constants.
mikroC PRO for PIC32 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”.
mikoC PRO for PIC32 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 mov
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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. Remember that the PIC32 has stack and memory limitations which can varies greatly between MCUs.
mikroC PRO for PIC32 // 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 PIC32 converts integral arguments to a function call according to the integral widening (expansion) rules described in Stan
mikoC PRO for PIC32 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, ...
mikroC PRO for PIC32 Operators Operators are tokens that trigger some computation when applied to variables and other objects in an expression.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 Arithmetic Operators Arithmetic operators are used to perform mathematical computations. They have numerical operands and return numerical results. The type char technically represents small integers, so the char variables can be used as operands in arithmetic operations. All arithmetic operators associate from left to right.
mikoC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 /* 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 logical negation Precedence 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 PIC32 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 PIC32 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 PIC32 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 PIC32 Expression Statements Any expression followed by a semicolon forms an expression statement: expression; The mikroC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32: - while - do - for While Statement The while keyword is used to conditionally iterate a statement.
mikroC PRO for PIC32 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 PIC32 Jump Statements The jump statement, when executed, transfers control unconditionally. There are four such statements in the mikroC PRO for PIC32: - 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 PIC32 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 PIC32 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 PIC32 For more information on including files with the #include directive, refer to File Inclusion. The mikroC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 mikroC PRO for PIC32 Libraries mikroC PRO for PIC32 provides a set of libraries which simplify the initialization and use of PIC32 and their modules: Use Library manager to include mikroC PRO for PIC32 Libraries in you project.
mikroC PRO for PIC32 Hardware Libraries - ADC Library - CANSPI Library - Compact Flash Library - Epson S1D13700 Graphic Lcd Library - Flash Memory Library - Graphic Lcd Library - I²C Library - Keypad Library - Lcd Library - Manchester Code Library - Memory Manager Library - Multi Media Card Library - OneWire Library - Port Expander Library - PS/2 Library - PWM Library - RS-485 Library - Software I²C Library - Software SPI Library - Software UART Library - Sound Library - SPI Library - SPI Ethernet Library
mikoC PRO for PIC32 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 PIC32 Hardware Libraries - ADC Library - CANSPI Library - Compact Flash Library - Epson S1D13700 Graphic Lcd Library - Flash Memory Library - Graphic Lcd Library - I²C Library - Keypad Library - Lcd Library - Manchester Code Library - Memory Manager Library - Multi Media Card Library - OneWire Library - Port Expander Library - PS/2 Library - PWM Library - RS-485 Library - Software I²C Library - Software SPI Library - Software UART Library - Sound Library - SPI Library - SPI Ethernet Library
mikoC PRO for PIC32 Library Routines - ADCx_Init - ADCx_Init_Advanced - ADCx_Get_Sample - ADCx_Read 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. Returns Nothing.
mikroC PRO for PIC32 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 unsigned value from the specified channel. - The MCU with built-in ADC module. - Prior to using this routine, ADC module needs to be initialized. See ADCx_Init and ADCx_Init_ Advanced.
mikoC PRO for PIC32 Library Example This code snippet reads analog value from the channel 1 and sends readings as a text over UART1.
mikroC PRO for PIC32 CANSPI Library The SPI module is available with a number of the PIC32 MCUs. The mikroC PRO for PIC32 provides a library (driver) for working with mikroElektronika’s CANSPI Add-on boards (with MCP2515 or MCP2510) via SPI interface. Important: - Consult the CAN standard about CAN bus termination resistance. - An effective CANSPI communication speed depends on SPI and certainly is slower than “real” CAN. - The library uses the SPI module for communication.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 Requires Global variables: - CanSpi_CS: Chip Select line - CanSpi_Rst: Reset line - CanSpi_CS_Direction: Direction of the Chip Select pin - CanSpi_Rst_Direction: Direction of the Reset pin must be defined before using this function. The CANSPI routines are supported only by MCUs with the SPI module. The SPI module needs to be initialized. See the SPIx_Init and SPIx_Init_Advanced routines. MCU has to be properly connected to mikroElektronika’s CANSPI Extra Board or similar hardware.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 parameter
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 You may use bitwise AND (&) to form config byte out of these values. For example: Copy Code To Clipboard init = _CANSPI_CONFIG_SAMPLE_THRICE & _CANSPI_CONFIG_PHSEG2_PRG_ON & _CANSPI_CONFIG_STD_MSG & _CANSPI_CONFIG_DBL_BUFFER_ON & _CANSPI_CONFIG_VALID_XTD_MSG & _CANSPI_CONFIG_LINE_FILTER_OFF; ...
mikoC PRO for PIC32 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 = = = = = = = 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, // Use this to access filter bits _CANSPI_RX_OVERFLOW = 0x08, // Set if Overflowed else cleared _CANSPI_RX_INVALID_MSG = 0x10, // Set if invalid else cleared _CANSPI_RX_XTD_FRAME = 0x20, // Set if XTD message else cleared _CANSPI_RX_RTR_FRAME = 0x
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 CANSPISetOperationMode(_CANSPI_MODE_NORMAL,0xFF); // set NORMAL mode // Set initial data to be sent RxTx_Data[0] = 9; CANSPIWrite(ID_1st, RxTx_Data, 1, Can_Send_Flags); // send initial message while(1) { // endless loop Msg_Rcvd = CANSPIRead(&Rx_ID , RxTx_Data , &Rx_Data_Len, &Can_Rcv_Flags); // receive message if ((Rx_ID == ID_2nd) && Msg_Rcvd) { // if message received check id PORTB = RxTx_Data[0]; // id correct, output data at PORTC RxTx_Data[0]++ ; // increment received data Delay_
mikroC PRO for PIC32 Can_Init_Flags = _CANSPI_CONFIG_SAMPLE_THRICE & _CANSPI_CONFIG_PHSEG2_PRG_ON & _CANSPI_CONFIG_XTD_MSG & _CANSPI_CONFIG_DBL_BUFFER_ON & _CANSPI_CONFIG_VALID_XTD_MSG & _CANSPI_CONFIG_LINE_FILTER_OFF; // form value to be used // with CANSPIInit // Initialize SPI2 module SPI2_Init(); Delay_ms(10); CANSPIInitialize(1,3,3,3,1,Can_Init_Flags); // initialize external CANSPI module CANSPISetOperationMode(_CANSPI_MODE_CONFIG,0xFF); // set CONFIGURATION mode CANSPISetMask(_CANSPI_MASK_B1,-1,_CAN
mikoC PRO for PIC32 HW Connection Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface MikroElektronika 286
mikroC PRO for PIC32 Compact Flash Library The Compact Flash Library provides routines for accessing data on Compact Flash card (abbr. CF further in text). CF cards are widely used memory elements, commonly used with digital cameras. Great capacity and excellent access time of only a few microseconds make them very attractive for microcontroller applications. In CF card, data is divided into sectors. One sector usually comprises 512 bytes.
mikoC PRO for PIC32 External dependencies of Compact Flash Library The following variables must be defined in all projects Description: using Compact Flash Library: Example: extern sfr unsigned int CF_Data_Port; Compact Flash Data Port. char CF_Data_Port at PORTF; Ready signal line.
mikroC PRO for PIC32 Library Routines - Cf_Init - Cf_Detect - Cf_Enable - Cf_Disable - Cf_Read_Init - Cf_Read_Byte - Cf_Write_Init - Cf_Write_Byte - Cf_Read_Sector - Cf_Write_Sector Routines for file handling: - Cf_Fat_Init - Cf_Fat_QuickFormat - Cf_Fat_Assign - Cf_Fat_Reset - Cf_Fat_Read - Cf_Fat_Rewrite - Cf_Fat_Append - Cf_Fat_Delete - Cf_Fat_Write - Cf_Fat_Set_File_Date - Cf_Fat_Get_File_Date - Cf_Fat_Get_File_Date_Modified - Cf_Fat_Get_File_Size - Cf_Fat_Get_Swap_File The following routine is for the i
mikoC PRO for PIC32 Cf_Init Prototype void Cf_Init(); Description Initializes ports appropriately for communication with CF card. Parameters None. Returns Nothing.
mikroC PRO for PIC32 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()); PIC32 family MCU and CF card voltage levels are different.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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. File must be previously assigned. See Cf_Fat_Assign. Example Notes unsigned long size; ... Cf_Fat_Reset(size); None.
mikroC PRO for PIC32 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. The file must be previously assigned. See Cf_Fat_Assign. Example Notes // open file for writing Cf_Fat_Rewrite(); None.
mikoC PRO for PIC32 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. File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 Parameters Returns Requires Example Notes 301 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.
mikoC PRO for PIC32 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 LV-32MX v6 development system and PIC32MX460F512L.
mikroC PRO for PIC32 } Cf_Fat_Write(file_contents, LINE_LEN-1); } // write data to the assigned file // 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 Cf_Fat_Set_File_Date(2005,6,21,10,35,0); // Set file date & time info Cf_Fat_Assign(&filename, 0xA0); // find existing file or create a new one Cf_Fat_Rewrite(); // To clear file and start with new data
mikoC PRO for PIC32 // Deletes a file. If file doesn’t exist, it will first be created // and then deleted.
mikroC PRO for PIC32 } } // 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 = Cf_Fat_Get_Swap_File(5000, “mikroE.txt”, 0x20); for details // see help on this function if (size) { LongToStr((signed long)size, err_txt); UART1_Write_Line(err_txt); } } for(i=0; i<5000; i++) { Cf_Write_Sector(size++, Buffer); UART1_Write(‘.’); } // Main.
mikoC PRO for PIC32 } else { UART1_Write_Line(err_txt); // Note: Cf_Fat_Init tries to initialize a card more than once.
mikroC PRO for PIC32 Epson S1D13700 Graphic Lcd Library The mikroC PRO for PIC32 provides a library for working with Glcds based on Epson S1D13700 controller. The S1D13700 Glcd is capable of displaying both text and graphics on an LCD panel. The S1D13700 Glcd allows layered text and graphics, scrolling of the display in any direction, and partitioning of the display into multiple screens.
mikoC PRO for PIC32 Library Routines - S1D13700_Init - S1D13700_Write_Command - S1D13700_Write_Parameter - S1D13700_Read_Parameter - S1D13700_Fill - S1D13700_GrFill - S1D13700_TxtFill - S1D13700_Display_GrLayer - S1D13700_Display_TxtLayer - S1D13700_Set_Cursor - S1D13700_Display_Cursor - S1D13700_Write_Char - S1D13700_Write_Text - S1D13700_Dot - S1D13700_Line - S1D13700_H_Line - S1D13700_V_Line - S1D13700_Rectangle - S1D13700_Box - S1D13700_Rectangle_Round_Edges - S1D13700_Rectangle_Round_Edges_Fill - S1D13
mikroC PRO for PIC32 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. - S1D13700_CS: Chip Select signal pin.
mikoC PRO for PIC32 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_ON Turn the display on. S1D13700_DISP_OFF Turn the display off. S1D13700_SCROLL Setup text and graphics address regions.
mikroC PRO for PIC32 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 PIC32 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 PIC32 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 Turn on graphic layer. S1D13700_LAYER_FLASH_2Hz Turn on graphic layer and flash it at the rate of 2 Hz. S1D13700_LAYER_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.
mikoC PRO for PIC32 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 Turn on graphic layer and flash it at the rate of 2 Hz. S1D13700_CURSOR_FLASH_16Hz Turn on graphic layer and flash it at the rate of 16 Hz.
mikroC PRO for PIC32 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 PIC32 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 Description S1D13700_BLACK Black color. S1D13700_WHITE White color.
mikroC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 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 Description S1D13700_BLACK Black color. S1D13700_WHITE White color.
mikroC PRO for PIC32 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 PIC32 Flash Memory Library This library provides routines for accessing microcontroller’s (internal) Flash memory. The program Flash array for the PIC32MX device is built up of a series of rows. A row contains 128 32-bit instruction words or 512 bytes. A group of 8 rows compose a page; which, therefore, contains 8 × 512 = 4096 bytes or 1024 instruction words. A page of Flash is the smallest unit of memory that can be erased at a single time.
mikroC PRO for PIC32 Flash_Write_Word Prototype void Flash_Write_Word(unsigned long address, unsigned long wdata); Description Writes one 32-bit word in the program Flash memory on the designated address. Parameters - address: address of the FLASH memory word - wdata: data to be written Returns Nothing. Requires Nothing. Example Notes None.
mikoC PRO for PIC32 Graphic Lcd Library The mikroC PRO for PIC32 provides a library for operating Graphic Lcd 128x64 (with commonly used Samsung KS108/ KS107 controller). For creating a custom set of Glcd images use Glcd Bitmap Editor Tool.
mikroC PRO for PIC32 External dependencies of Graphic Lcd Library The following variables must be defined in all projects using Graphic Lcd Description: Library: Example: extern sfr sbit GLCD_D0; sbit GLCD_D0 at LATB0_bit; extern sfr sbit GLCD_D1; extern sfr sbit GLCD_D2; extern sfr sbit GLCD_D3; extern sfr sbit GLCD_D4; extern sfr sbit GLCD_D5; extern sfr sbit GLCD_D6; extern sfr sbit GLCD_D7; extern sfr sbit GLCD_CS1; extern sfr sbit GLCD_CS2; extern sfr sbit GLCD_RS; extern sfr sbit GLCD_RW; extern
mikoC PRO for PIC32 Library Routines Basic routines: - Glcd_Init - Glcd_Set_Side - Glcd_Set_X - Glcd_Set_Page - Glcd_Read_Data - Glcd_Write_Data Advanced routines: - Glcd_Fill - Glcd_Dot - Glcd_Line - Glcd_V_Line - Glcd_H_Line - Glcd_Rectangle - Glcd_Rectangle_Round_Edges - Glcd_Rectangle_Round_Edges_Fill - Glcd_Box - Glcd_Circle - Glcd_Circle_Fill - Glcd_Set_Font - Glcd_Write_Char - Glcd_Write_Text - Glcd_Image - Glcd_PartialImage Glcd_Init Prototype void Glcd_Init(); Description Initializes the Glcd mo
mikroC PRO for PIC32 Requires - GLCD_EN : Enable signal pin - GLCD_RST : Reset signal pin - GLCD_D0_Direction : Direction of the Data pin 0 - GLCD_D1_Direction : Direction of the Data pin 1 - GLCD_D2_Direction : Direction of the Data pin 2 - GLCD_D3_Direction : Direction of the Data pin 3 - GLCD_D4_Direction : Direction of the Data pin 4 - GLCD_D5_Direction : Direction of the Data pin 5 - GLCD_D6_Direction : Direction of the Data pin 6 - GLCD_D7_Direction : Direction of the Data pin 7 - GLCD_CS1_Direction
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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_; ...
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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..
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 Returns The parameter color determines the color of the circle line: 0 white, 1 black, and 2 inverts each dot. Nothing.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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..
mikroC PRO for PIC32 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 PIC32 pointer to const and pointer to RAM equivalency). Returns Nothing. Requires Glcd needs to be initialized, see Glcd_Init routine.
mikoC PRO for PIC32 I²C Library The I²C full master I²C module is available with a number of the PIC32 MCU models. The mikroC PRO for PIC32 provides a library which supports the master I²C mode. Important: - I²C library routines require you to specify the module you want to use. To select the desired I²C module, simply change the letter x in the routine prototype for a number from 1 to 5. - Number of I²C modules per MCU differs from chip to chip.
mikroC PRO for PIC32 I2Cx_Init_Advanced Prototype void I2Cx_Init_Advanced(unsigned long Fclk_Khz, unsigned long scl); Description This function configures and initializes the desired I²C module using Peripheral Bus Clock and default initialization settings. As per the I²C standard, SCL clock may be 100 kHz or 400 kHz. However, the user can specify any clock rate up to 1 MHz. Parameters - Fclk_Khz: Peripheral Bus Clock frequency in kHz. - scl: requested serial clock rate. Returns Nothing.
mikoC PRO for PIC32 I2Cx_Restart Prototype void I2Cx_Restart(); Description Issues repeated START signal. Parameters None. Returns Nothing. Requires MCU with at least one I²C module. Used I²C module must be initialized before using this function. See I2Cx_Init routine. Example Notes // Issue RESTART signal I2C1_Restart(); - I²C library routines require you to specify the module you want to use.
mikroC PRO for PIC32 I2Cx_Read Prototype unsigned char I2Cx_Read(unsigned ack); Description Reads a byte from the I²C bus. Parameters - ack: acknowledge signal parameter. If the ack = 0, acknowledge signal will be sent after reading, otherwise the not acknowledge signal will be sent. Returns Received data. Requires MCU with at least one I²C module. Used I²C module must be initialized before using this function. See I2Cx_Init routine. Also, START signal needs to be issued in order to use this function.
mikoC PRO for PIC32 I2Cx_Stop Prototype void I2Cx_Stop(); Description Issues STOP signal. Parameters None. Returns Nothing. Requires MCU with at least one I²C module. Used I²C module must be initialized before using this function. See I2Cx_Init routine. Example Notes // Issue STOP signal I2C1_Stop(); - I²C library routines require you to specify the module you want to use. To select the desired I²C module, simply change the letter x in the routine prototype for a number from 1 to 5.
mikroC PRO for PIC32 } unsigned short i; char b; void main(){ CHECON = 0x30; AD1PCFG = 0xFFFFFFFF; LATB = 0; TRISB = 0; TRISD = 0; LATD = 0; } // // // // Set PORTB value to zero Configure PORTB as output Configure PORTB as output Set PORTD value to zero EEPROM_24C02_Init(); // performs I2C initialization b = 0x00; for(i = 0x00; i<0x80; i++) { EEPROM_24C02_WrSingle(i,b); b++; delay_ms(5); } for(i = 0x00; i < 0x80; i++){ LATD = i; LATB = EEPROM_24C02_RdSingle(i); delay_ms(100); } 343 MikroElektronika
mikoC PRO for PIC32 Keypad Library The mikroC PRO for PIC32 provides a library for working with 4x4 keypad. The library routines can also be used with 4x1, 4x2, or 4x3 keypad. For connections explanation see schematic at the bottom of this page. External dependencies of Keypad Library The following variable must be defined in all projects using Keypad Library: Description: Example: extern sfr keypadPort; Keypad Port.
mikroC PRO for PIC32 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; ...
mikoC PRO for PIC32 Library Example The following code can be used for testing the keypad. It is written for keypad_4x3 or _4x4. The code returned by the keypad functions (1..16) is transformed into ASCII codes [0..9,A..F], and then sent via UART1.
mikroC PRO for PIC32 } } UART1_Write_Text(“Key pressed: “); UART1_Write(kp); UART1_Write(10); UART1_Write(13); } while (1); // Send value of pressed button to UART HW Connection 4x4 Keypad connection scheme 347 MikroElektronika
mikoC PRO for PIC32 Lcd Library The mikroC PRO for PIC32 provides a library for communication with Lcds (with HD44780 compliant controllers) through the 4-bit interface. An example of Lcd connections is given on the schematic at the bottom of this page. For creating a set of custom Lcd characters use Lcd Custom Character Tool.
mikroC PRO for PIC32 Lcd_Init Prototype void Lcd_Init(); Description Initializes Lcd module. Parameters None. Returns Nothing.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 Library Example The following code demonstrates usage of the Lcd Library routines: Copy Code To Clipboard // LCD module connections sbit LCD_RS at LATB2_bit; sbit LCD_EN at LATB3_bit; sbit LCD_D4 at LATB4_bit; sbit LCD_D5 at LATB5_bit; sbit LCD_D6 at LATB6_bit; sbit LCD_D7 at LATB7_bit; sbit LCD_RS_Direction at TRISB2_bit; sbit LCD_EN_Direction at TRISB3_bit; sbit LCD_D4_Direction at TRISB4_bit; sbit LCD_D5_Direction at TRISB5_bit; sbit LCD_D6_Direction at TRISB6_bit; sbit LCD_D7_Directi
mikroC PRO for PIC32 } } } for(i=0; i<8; i++) { Lcd_Cmd(_LCD_SHIFT_RIGHT); Move_Delay(); } // Move text to the right 7 times Lcd HW connection 353 MikroElektronika
mikoC PRO for PIC32 Manchester Code Library The mikroC PRO for PIC32 provides a library for handling Manchester coded signals.
mikroC PRO for PIC32 Library Routines - Man_Receive_Init - Man_Receive - Man_Send_Init - Man_Send - Man_Synchro - Man_Break The following routines are for the internal use by compiler only: - Manchester_0 - Manchester_1 - Manchester_Out Man_Receive_Init Prototype 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.
mikoC PRO for PIC32 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 unsigned int data = 0, error = 0; ...
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 Library Example The following code is code for the Manchester receiver, it shows how to use the Manchester Library for receiving data: Copy Code To Clipboard // LCD module connections sbit LCD_RS at LATB2_bit; sbit LCD_EN at LATB3_bit; sbit sbit sbit sbit LCD_D4 LCD_D5 LCD_D6 LCD_D7 at at at at LATB4_bit; LATB5_bit; LATB6_bit; LATB7_bit; sbit LCD_RS_Direction at TRISB2_bit; sbit LCD_EN_Direction at TRISB3_bit; sbit LCD_D4_Direction at TRISB4_bit; sbit LCD_D5_Direction at TRISB5_bit;
mikoC PRO for PIC32 break; if (error) break; } do { // We got the starting sequence // Exit so we do not loop forever byte_rcvd = Man_Receive(&error); // if (error) { // Lcd_Chr_CP(‘?’); // ErrorCount++; // if (ErrorCount > 20) { // Man_Synchro(); // //Man_Receive_Init(); // Alternative, ErrorCount = 0; // } } Attempt byte receive If error occured Write question mark on LCD Update error counter In case of multiple errors Try to synchronize again try to Initialize Receiver again Reset error counter else
mikroC PRO for PIC32 } AD1PCFG = 0xFFFF; TRISB = 0; LATB = 0; // Configure AN pins as digital I/O Man_Send_Init(); // Initialize transmitter while (1) { Man_Send(0x0B); Delay_ms(100); // Endless loop // Send “start” byte // Wait for a while } character = s1[0]; index = 0; while (character) { Man_Send(character); Delay_ms(90); index++; character = s1[index]; } Man_Send(0x0E); Delay_ms(1000); // // // // // // // Take first char from string Initialize index variable String ends with zero Send chara
mikoC PRO for PIC32 Memory Manager Library This library provides routines for manipulating dynamic memory allocation. Dynamic memory allocation (also known as heap-based memory allocation) is the allocation of memory storage for use in a program during the runtime of that program. Dynamically allocated memory exists until it is released. This is in contrast to static memory allocation, which has a fixed duration. It is said that an object so allocated has a dynamic lifetime.
mikroC PRO for PIC32 free Prototype void free(char * P, unsigned ActualSize); Description This function is used to free memory block allocated by malloc. Parameters - P: pointer to the memory block - ActualSize: actual size of the memory block. Returns Nothing. Requires Nothing.
mikoC PRO for PIC32 Multi Media Card Library The Multi Media Card (MMC) is a Flash memory card standard. MMC cards are currently available in sizes up to and including 32 GB and are used in cellular phones, digital audio players, digital cameras and PDA’s. mikroC PRO for PIC32 provides a library for accessing data on Multi Media Card via SPI communication. This library also supports SD (Secure Digital) and high capacity SDHC (Secure Digital High Capacity) memory cards .
mikroC PRO for PIC32 Library Dependency Tree External dependencies of MMC Library The following variable must be defined in all projects using MMC library: Description: Example: extern Select; Chip select pin. sbit Mmc_Chip_Select at LATF0_bit; Direction of the chip select pin.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 Mmc_Fat_Write(file_contents, LINE_LEN-1); // write data to the assigned file } } // 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(2011,1,12,11,9,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
mikoC PRO for PIC32 // Deletes a file. If file doesn’t exist, it will first be created // and then deleted.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 //--- Test start UART1_Write_Line(“Test Start.”); //--- Test routines. Uncomment them one-by-one to test certain features M_Create_New_File(); #ifdef COMPLETE_EXAMPLE M_Create_Multiple_Files(); M_Open_File_Rewrite(); M_Open_File_Append(); M_Open_File_Read(); M_Delete_File(); M_Test_File_Exist(); M_Create_Swap_File(); #endif UART1_Write_Line(“Test End.”); } else { UART1_Write_Line(err_txt); // Note: Mmc_Fat_Init tries to initialize a card more than once.
mikroC PRO for PIC32 OneWire Library The OneWire library provides routines for communication via the Dallas OneWire protocol, e.g. with DS18x20 digital thermometer. OneWire is a Master/Slave protocol, and all communication cabling required is a single wire. OneWire enabled devices should have open collector drivers (with single pull-up resistor) on the shared data line. Slave devices on the OneWire bus can even get their power supply from data line. For detailed schematic see device datasheet.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 Port Expander Library The mikroC PRO for PIC32 provides a library for communication with the Microchip’s Port Expander MCP23S17 via SPI interface. Connections of the PIC32 MCU and MCP23S17 is given on the schematic at the bottom of this page. Important: - The library uses the SPI module for communication. User must initialize the appropriate SPI module before using the Port Expander Library.
mikoC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 Library Example The example demonstrates how to communicate with Port Expander MCP23S17. Note that Port Expander pins A2 A1 A0 are connected to GND so Port Expander Hardware Address is 0.
mikroC PRO for PIC32 HW Connection Port Expander HW connection 395 MikroElektronika
mikoC PRO for PIC32 PS/2 Library The mikroC PRO for PIC32 provides a library for communication with the common PS/2 keyboard. Important: - The library does not utilize interrupts for data retrieval, and requires the oscillator clock to be at least 6MHz. - The pins to which a PS/2 keyboard is attached should be connected to the pull-up resistors. - Although PS/2 is a two-way communication bus, this library does not provide MCU-to-keyboard communication; e.g.
mikroC PRO for PIC32 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 PIC32 Special Function Keys Key Value returned F1 1 F2 2 F3 3 F4 4 F5 5 F6 6 F7 7 F8 8 F9 9 F10 10 F11 11 F12 12 Enter 13 Page Up 14 Page Down 15 Backspace 16 Insert 17 Delete 18 Windows 19 Ctrl 20 Shift 21 Alt 22 Print Screen 23 Pause 24 Caps Lock 25 End 26 Home 27 Scroll Lock 28 Num Lock 29 Left Arrow 30 Right Arrow 31 Up Arrow 32 Down Arrow 33 Escape 34 Tab 35 MikroElektronika 398
mikroC PRO for PIC32 Library Example This simple example reads values of the pressed keys on the PS/2 keyboard and sends them via UART.
mikoC PRO for PIC32 HW Connection Example of PS2 keyboard connection PWM Library The CCP module is available with a number of PIC32 MCUs. mikroC PRO for PIC32 provides a library which simplifies using of the PWM HW Module. Important : PWM module uses either Timer2 or Timer3 module.
mikroC PRO for PIC32 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); Description Initializes the PWM module with duty ratio 0. Parameters - freq_hz: PWM frequency in Hz (refer to device datasheet for correct values in respect with Fosc) - enable_channel_x: number of PWM channel to be initialized. Refer to MCU’s datasheet for available PWM channels - timer_prescale: timer prescaler parameter.
mikoC PRO for PIC32 PWM_Set_Duty Prototype void PWM_Set_Duty(unsigned duty, unsigned channel); Description The function changes PWM duty ratio. Parameters - duty: PWM duty ratio. Valid values: 0 to timer period returned by the PWM_Init function. - channel: number of PWM channel to change duty to. Returns Nothing. Requires MCU must have the HW PWM Module. PWM channel must be properly initialized. See PWM_Init routine. Example Notes // Set channel 1 duty ratio to 50%: unsigned int pwm_period1; ...
mikroC PRO for PIC32 Library Example The example changes PWM duty ratio on channels 1 and 2 continuously. If LEDs are connected to channels 1 and 2, a gradual change of emitted light will be noticeable.
mikoC PRO for PIC32 if (RB2_bit) { Delay_ms(1); current_duty1 = current_duty1 + 5; if (current_duty1 > pwm_period2) { then possible pwm_period2 value current_duty1 = 0; } PWM_Set_Duty(current_duty1, 2); } if (RB3_bit) { Delay_ms(1); current_duty1 = current_duty1 - 5; if (current_duty1 > pwm_period2) { possible pwm_period1 value (overflow) current_duty1 = pwm_period2; } PWM_Set_Duty(current_duty1, 2); } } } Delay_ms(1); // button on RB2 pressed // increment current_duty // if we increase current_duty1 gr
mikroC PRO for PIC32 RS-485 Library RS-485 is a multipoint communication which allows multiple devices to be connected to a single bus. The mikroC PRO for PIC32 provides a set of library routines for comfortable work with RS485 system using Master/Slave architecture. Master and Slave devices interchange packets of information. Each of these packets contains synchronization bytes, CRC byte, address byte and the data. Each Slave has unique address and receives only packets addressed to it.
mikoC PRO for PIC32 Library Routines - RS485Master_Init - RS485Master_Receive - RS485Master_Send - RS485Slave_Init - RS485Slave_Receive - RS485Slave_Send RS485Master_Init Prototype void RS485Master_Init(); Description Initializes MCU as a Master for RS-485 communication. Parameters None. Returns Nothing. Requires Global variables: - RS485_rxtx_pin - this pin is connected to RE/DE input of RS-485 transceiver(see schematic at the bottom of this page).
mikroC PRO for PIC32 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..
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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..
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 URXISEL1_U2STA_bit = 0; received U2RXIF_bit = 0; // 0x = Interrupt flag bit is set when a character is // ensure interrupt not pending MVEC_bit = 1; asm ei R0; // Interrupt controller configured for multi vectored mode // Enable all interrupts U2RXIE_bit = 1; // enable intterupt RS485Master_Send(dat,1,160); 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
mikoC PRO for PIC32 } RS485Slave_Receive(dat); U2RXIF_bit = 0; // ensure interrupt not pending void main() { CHECON = 0x32; AD1PCFG = 0xFFFF; TRISB TRISD PORTB PORTD = = = = 0; 0; 0; 0; UART2_Init(19200); Delay_ms(100); RS485Slave_Init(160); dat[0] dat[1] dat[2] dat[4] dat[5] dat[6] = = = = = = 0xAA; 0xF0; 0x0F; 0; 0; 0; U2IP0_bit = 1; U2IP1_bit = 1; U2IP2_bit = 1; // initialize UART2 module // Intialize MCU as slave, address 160 // ensure that message received flag is 0 // ensure that error fla
mikroC PRO for PIC32 HW Connection Example of interfacing PC to PIC32 MCU via RS485 bus with LTC485 as RS-485 transceiver 413 MikroElektronika
mikoC PRO for PIC32 Message format and CRC calculations Q: How is CRC checksum calculated on RS485 master side? Copy Code To Clipboard START_BYTE = 0x96; // 10010110 STOP_BYTE = 0xA9; // 10101001 PACKAGE: -------START_BYTE 0x96 ADDRESS DATALEN [DATA1] [DATA2] [DATA3] CRC STOP_BYTE 0xA9 // if exists // if exists // if exists DATALEN bits -----------bit7 = 1 MASTER SENDS 0 SLAVE SENDS bit6 = 1 ADDRESS WAS XORed 0 ADDRESS UNCHANGED bit5 = 0 FIXED bit4 = 1 DATA3 (if exists) 0 DATA3 (if exists) bit3 = 1 DATA2
mikroC PRO for PIC32 Software I²C Library The mikroC PRO for PIC32 provides routines for implementing Software I²C communication. These routines are hardware independent and can be used with any MCU. The Software I²C library enables you to use MCU as Master in I²C communication. Multi-master mode is not supported. Important: - This library implements time-based activities, so interrupts need to be disabled when using Software I²C.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 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.
mikoC PRO for PIC32 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 PIC32 Library Example The example demonstrates use of the Software I²C Library. The PIC32 MCU is connected (SCL, SDA pins) to PCF8583 RTC (real-time clock). Program sends date/time to RTC.
mikoC PRO for PIC32 } seconds minutes hours year day month = = = = = = ((seconds & 0xF0) >> 4)*10 + (seconds & 0x0F); ((minutes & 0xF0) >> 4)*10 + (minutes & 0x0F); ((hours & 0xF0) >> 4)*10 + (hours & 0x0F); (day & 0xC0) >> 6; ((day & 0x30) >> 4)*10 + (day & 0x0F); ((month & 0x10) >> 4)*10 + (month & 0x0F); // // // // // // Transform Transform Transform Transform Transform Transform seconds months hours year day month //-------------------- Output values to LCD void Display_Time() { (day / (day % (
mikroC PRO for PIC32 Software SPI Library The mikroC PRO for PIC32 provides routines for implementing Software SPI communication. These routines are hardware independent and can be used with any MCU. The Software SPI Library provides easy communication with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc. Library configuration: - SPI to Master mode - Clock value = 20 kHz. - Data sampled at the middle of interval. - Clock idle state low. - Data sampled at the middle of interval.
mikoC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 Software UART Library The mikroC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 Library Example This example demonstrates simple data exchange via software UART. If MCU is connected to the PC, you can test the example from the mikroC PRO for PIC32 USART communication terminal, launch it from the drop-down menu Tools › USART Terminal or simply click the USART Terminal Icon .
mikroC PRO for PIC32 void main() { CHECON = 0x32; AD1PCFG = 0xFFFF; TRISB = 0xF8; LATB = 0; Sound_Init(&PORTD, 3); Sound_Play(880, 1000); while (1) { if (Button(&PORTB,7,1,1)) Tone1(); while (RB7_bit); } } // Configure AN pins as digital // Configure RB7..
mikoC PRO for PIC32 Sound Library The mikroC PRO for PIC32 provides a Sound Library to supply users with routines necessary for sound signalization in their applications. Sound generation needs additional hardware, such as piezo-speaker (example of piezo-speaker interface is given on the schematic at the bottom of this page).
mikroC PRO for PIC32 Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker.
mikoC PRO for PIC32 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 (RB4_bit); // RB3 plays Melody // Wait for button to be released // Wait for button to be released
mikroC PRO for PIC32 SPI Library The SPI module is available with all PIC32 MCUs. mikroC PRO for PIC32 provides a library for initializing the Slave mode and initializing and comfortable work with the Master mode. The PIC32 can easily communicate with other devices via SPI: A/D converters, D/A converters, MAX7219, LTC1290, etc. Important: - SPI library routines require you to specify the module you want to use.
mikoC PRO for PIC32 SPIx_Init Prototype void SPIx_Init(); Description Configures and initializes the SPI module with default settings. Default settings: - Master mode. - 8-bit data mode. - Serial clock set to System clock/64. - Slave Select disabled. - Input data sampled in the middle of interval. - Clock idle state low. - Serial output data changes on transition from idle clock state to active clock state Parameters None. Returns Nothing. Requires MCU must have the SPI1 module.
mikroC PRO for PIC32 SPIx_Init_Advanced Prototype void SPIx_Init_Advanced(unsigned master_mode, unsigned data_mode, unsigned clock_divider, 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, data_mode, clock_divider, slave_select, data_sample, clock_idle and determine the working mode for SPI.
mikoC PRO for PIC32 Parameters The parameter clock_idle determines the behaviour of the SPI clock (CLK) line in IDLE phase. Clock Polarity Description Predefined library const IDLE state is Lo, ACTIVE state is Hi IDLE state is Hi, ACTIVE state is Lo _SPI_CLK_IDLE_LOW _SPI_CLK_IDLE_HIGH The parameter edge determines on which clock edge data is considered to be valid.
mikroC PRO for PIC32 SPIx_Read Prototype unsigned SPIx_Read(unsigned long 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.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 // Send Low Byte temp = valueDAC; SPI2_Write(temp); } Chip_Select = 1; // Store valueDAC[7..0] to temp[7..
mikoC PRO for PIC32 HW Connection SPI HW connection MikroElektronika 440
mikroC PRO for PIC32 SPI Ethernet Library The ENC28J60 is a stand-alone Ethernet controller with an industry standard Serial Peripheral Interface (SPI). It is designed to serve as an Ethernet network interface for any controller equipped with SPI. The ENC28J60 meets all of the IEEE 802.3 specifications. It incorporates a number of packet filtering schemes to limit incoming packets. It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calculations.
mikoC PRO for PIC32 External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Ethernet Description: Library: Example: extern CS; sfr sbit SPI_Ethernet_ ENC28J60 chip select pin. sbit SPI_Ethernet_CS at LATF1_bit; sfr sbit SPI_Ethernet_ ENC28J60 reset pin. sbit SPI_Ethernet_Rst at LATF0_bit; extern sfr sbit SPI_Ethernet_CS_ Direction; Direction of the ENC28J60 chip select pin.
mikroC PRO for PIC32 Library Routines - SPI_Ethernet_Init - SPI_Ethernet_Enable - SPI_Ethernet_Disable - SPI_Ethernet_doPacket - SPI_Ethernet_putByte - SPI_Ethernet_putBytes - SPI_Ethernet_putString - SPI_Ethernet_putConstString - SPI_Ethernet_putConstBytes - SPI_Ethernet_getByte - SPI_Ethernet_getBytes - SPI_Ethernet_UserTCP - SPI_Ethernet_UserUDP - SPI_Ethernet_getIpAddress - SPI_Ethernet_getGwIpAddress - SPI_Ethernet_getDnsIpAddress - SPI_Ethernet_getIpMask - SPI_Ethernet_confNetwork - SPI_Ethernet_arpRe
mikoC PRO for PIC32 Parameters - mac: RAM buffer containing valid MAC address. - ip: RAM buffer containing valid IP address. - fullDuplex: ethernet duplex mode switch. Valid values: 0 (half duplex mode) and 1 (full duplex mode). Returns Nothing. Requires Global variables: - SPI_Ethernet_CS: Chip Select line - SPI_Ethernet_CS_Direction: Direction of the Chip Select pin - SPI_Ethernet_RST: Reset line - SPI_Ethernet_RST_Direction: Direction of the Reset pin must be defined before using this function.
mikroC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 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 PIC32 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 Number of bytes written into ENC28J60 RAM. Ethernet module has to be initialized. See SPI_Ethernet_Init.
mikoC PRO for PIC32 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 PIC32 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 PIC32 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 PIC32 SPI_Ethernet_getIpMask Prototype unsigned char * SPI_Ethernet_getIpMask(); Description This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask. Parameters None. Returns Pointer to the global variable holding IP subnet mask. Requires Ethernet module has to be initialized. See SPI_Ethernet_Init. Example unsigned char IpMask[4]; // user IP subnet mask buffer ...
mikoC PRO for PIC32 SPI_Ethernet_arpResolve Prototype unsigned char *SPI_Ethernet_arpResolve(unsigned char *ip, unsigned char tmax); Description This is ARP module routine. It sends an ARP request for given IP address and waits for ARP reply. If the requested IP address was resolved, an ARP cash entry is used for storing the configuration. ARP cash can store up to 3 entries. For ARP cash structure refer to “eth_enc28j60LibDef.h” header file in the compiler’s Uses folder.
mikroC PRO for PIC32 SPI_Ethernet_dnsResolve Prototype unsigned char * SPI_Ethernet_dnsResolve(unsigned char *host, unsigned char tmax); Description This is DNS module routine. It sends an DNS request for given host name and waits for DNS reply. If the requested host name was resolved, it’s IP address is stored in library global variable and a pointer containing this address is returned by the routine. UDP port 53 is used as DNS port. Parameters - host: host name to be resolved.
mikoC PRO for PIC32 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.
mikroC PRO for PIC32 SPI_Ethernet_renewDHCP Prototype unsigned int SPI_Ethernet_renewDHCP(unsigned char tmax); Description This is DHCP module routine. It sends IP address lease time renewal request to DHCP server. Parameters - tmax: time in seconds to wait for an reply. Returns Requires - 1 - upon success (lease time was renewed). - 0 - otherwise (renewal request timed out). Ethernet module has to be initialized. See SPI_Ethernet_Init. Example while(1) { ...
mikoC PRO for PIC32 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 ...
mikroC PRO for PIC32