Home
User manual - MikroElektronika
Contents
1. Initialize SPI module SPI1 Init SPI T6963C Config 240 64 SPI T6963C writeData Rens Noting Example sr rese wriremataWdata o OOO O OOOO S moes noe OOOO SPI T6963C writeCommand Prototype void SPI T6963C writeCommand unsigned char data Writes command to T6963C controller via SPI interface data command to be written Toshiba Glcd module needs to be initialized See SPI T6963C oes routine eee SPI T6963C writeCommand SPI T6963C CURSOR POINTER SE MikroElektronika 916 mikroC PRO for PIC32 SPI T6963C setPtr Prototype void SPI T6963C setPtr unsigned int p unsigned char c Description Sets the memory pointer p for command p Parameters p address where command should be written c command to be written Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C setPtr SPI T6963C grHomeAddr start SPI T6963C ADDRESS POINTER _ Br SPI_T6963C_waitReady SP _T6963C_fil Prototype void SPI T6963C fill unsigned char v unsigned int start unsigned int len Description Fills controller memory block with given byte Parameters v byte to be written start starting address of the memory block len length of the memory block in bytes 91 MikroElektronika mikoC PRO for PIC32 SPI T6963C dot Prototype void SPI T6963C dot int x int y unsigned char color
2. oy 7j EEPROM File oe Active Commn amp 7j Output Files Add Project 25 RS485 N gt Other Files Close Project Ctrl K Add File To Project ove File From Project rill at R M Build Ctrl F9 amp mE Programmer Fil MikroElektronika A mikroC PRO for PIC32 Now navigate to the desired image file and simply add it Ez Project Manager 1 1 RS485 Master Example mcp32 zu Hegg Siac we amp RS485_Master_Example mcp32 Bg 6 Sources RS485 Master Example c gt Header Files Binaries Project Level Defines g 2 Image Files gt EEPROM Files Active Comments Files S 7j Output Files RS5485 Master Example hex gt Other Files Next right click the added file and choose Set As Preview Image Project Manager 1 1 R5485 Master Example mcp32 320 SA TASTE m aR RS485_Master_Example mcp32 E Sources B R5485 Master Example c j Header Files Binaries Project Level Defines a Image Files Cj EEPROM Fies Mi Seve Project Group t Active Comments Fi Close Project Ctri K Ba Output Files B Add Project R5485_Master o 00 E Other Files G Remove vin GY Add File To Project ef Remove File From Project M Build Ctrl F9 amp mE Programmer F11 Set As Preview Image Ctrl Alt P 15 MikroElektronika mikoC PRO for PIC32 Once you
3. Add Image To Project Add File To Project MikroElektronika 98 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 drop down menu Tools gt ASCII chart or by clicking the View ASCII Chart Icon from Tools toolbar Ascii Chart NUL SOH STX ETX EOT ENQ ACK BEL BS LF VT 0 1 2 3 4 5 6 7 9 10 11 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC 16 17 16 19 20 21 22 23 24 25 2 PAI E 3 35 36 38 39 041 9 49 gt co e of OF o g 0 103 104 105 AT DEC 102 HEX 0x66 t BIN 0110 0110 9 89 MikroElektronika 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 MikroElektronika EEPROM Editor Addr 0000 0010 0020 0030 0040 0050 0060 0070 0080 0090 YyyyyyyyyyyyyyyY YYyyYyyyyyyYYYYyY yyyyyy yyyyyy yYyyyyyyvyyyvyvvyyy YyyyyyyyyyyYyyyY YyYyyyyyyyyyyvyyy Yyyyyyyvyyvyyvyyy YyyyYyyyyyyyyYYyY Yyyyyyyvyyyyvyyyy MikroElektronika mikroC PRO for PIC32 Graphic Lcd Bitmap Editor The mikroC PRO for PIC32 includes the Graphic Lcd Bitmap Editor Output is the m
4. define putString SPI Ethernet putString MikroElektronika 460 mikroC PRO for PIC32 this function is called by the library the user accesses to the HTTP request by successive calls to Spi Ethernet getByte the user puts data in the transmit buffer by successive calls to Spi Ethernet putByte the function must return the length in bytes of the HTTP reply or 0 if nothing to transmit if you don t need to reply to HTTP requests just define this function with a return 0 as single statement ad unsigned int SPI Ethernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength TEthPktFlags flags unsigned int len my reply length should we close tcp socket after response is sent library closes tcp socket by default if canCloseTCP flag is not reset here flags canCloseTCP 0 0 do not close socket otherwise close socket if localPort 80 I listen only to web request on port 80 return 0 get 10 first bytes only of the request the rest does not matter here for len 0 len lt 10 len t getRequest len SPI Ethernet getByte getRequest len 0 len 0 if memcmp getRequest httpMethod 5 only GET method is supported here return 0 httpCounter one more request done if getRequest 5 s if request path name starts with s store dynamic data in
5. MikroElektronika 330 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 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw a vertical line between dots 10 5 and 10 25 Gled V Line 5 25 10 1 None Glcd H Line Prototype void Glcd H Line unsigned short x start unsigned short x end unsigned short y pos unsigned short color Description Draws a horizontal line on Glcd Parameters x start x coordinate of the line start Valid values 0 127 x end X coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw a horizontal line between dots 10 20 and 50 20 Gled H Line 10 50 20 1 None 33l MikroElektronika mikoC PRO
6. isi OOO eiii o Import Project Ctrl I xport Project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings MikroElektronika 46 mikroC PRO for PIC32 Build Build Menu Options Build Menu allows the user to easily manage building and compiling process M Build Ctrl F9 Rebuild All Sources Alt F9 Build All Projects Shift F9 Stop Build All Ctrl F12 Build Program Ctrl Fi1 Bua Beso A Build ct Fs Build active project Rebuild All Sources Ak r Rebuild all sources in active project d Build all Projects shift F9 Build all projects Stop Build All Ctr F12 Stop building all projects Sa Build Program ctr F11 Build and program active project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings a MikroElektronika mikoC PRO for PIC32 Run Run Menu Options Run Menu is used to debug and test compiled code on a software or harware level Start Debugger F9 5h Stop Debugger Ctrl F2 Run Pause Debugger F6 Step Into F7 Step Over F8 Step Out Ctri F8 Run To Cursor F4 4 Jump To Interrupt F2 Toggle Breakpoint F5 Clear Breakpoints Shift Ctrl F5 Disassembly mode Alt D Ra a v 8 5 R
7. Draws a filled rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 Glcd Rectangle Round Edges Fill 5 5 void Glcd Box unsigned short x upper left unsigned short y upper left unsigned short x bottom right unsigned short y bottom right unsigned short color Draws a box on Glcd Parameters x upper left x coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right x coordinate of the lower right box corner Valid values 0 127 y bottom right y coordinate of the lower right box corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the box fill O white 1 black and 2 inverts each dot Nothing Glcd needs to be initialized see Glcd Init routine Draw a box between dots 5 15 and 20 40 Gled Box 5 15 20 40 1 None MikroElektronika mikoC PRO for PIC32 Glcd Circle Prototype void Glcd Circle int x center int y center int radius unsigned short color Draws a circle on Glcd 1 Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle line O white 1 black and 2 inverts each dot Glcd
8. Function used for text moving Delay ms 500 You can change the moving speed here void main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital Tf Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE _ SPI CLK IDLE LOW SPI ACTIVE 2 IDLE SPI Lcd Config 0 Initialize Lcd over SPI interface SPI Lcd Cmd LCD CLEAR Clear display SPI Lcd Cmd LCD CURSOR OFF Turn cursor off SPI Lcd Out 1 6 mikroE Print text to Lcd Ist row 6th column SPI Lcd Chr CP Append SPI Lcd Out 2 1 text Print text to Lcd 2nd row 1st column SPI Lcd Out 3 1 mikroE For Lcd with more than two rows SPI Lcd Out 4 15 mikroE For Lcd with more than two rows Delay ms 2000 Moving text for i 0 i 4 itt Move text to the right 4 times Spi Lcd Cmd LCD SHIFT RIGHT Move Delay while 1 Endless loop for i 0 i lt 8 itt Move text to the left 7 times Spi Lcd Cmd LCD SHIFT LEFT Move Delay for i 0 i 8 itt Move text to the right 7 times Spi Lcd Cmd LCD SHIFT RIGHT Move Delay MikroElektronika 504 mikroC PRO for PIC32 Contrast Adjustment Lcd HW connection by default initialization usin
9. LCD COG 2X16 Lcd HW connection mikoC PRO for PIC32 Manchester Code Library The mikroC PRO for PIC32 provides a library for handling Manchester coded signals The Manchester code is a code in which data and clock signals are combined to form a single self synchronizing data stream each encoded bit contains a transition at the midpoint of a bit period the direction of transition determines whether the bit is O or 1 the second half is the true bit value and the first half is the complement of the true bit value as shown in the figure below Manchester RF Send Byte format St1 St2 Ctr B7 B6 B5 B4 B3 62 61 B0 Bi phase coding Lf n 1 0 2 4ms Example of transmission 11000100011 Important The Manchester receive routines are blocking calls Man Receive Init andMan Synchro This means that MCU will wait until the task has been performed e g byte is received synchronization achieved etc Manchester code library implements time based activities so interrupts need to be disabled when using it External dependencies of Manchester Code Library The following variables must be defined in all projects using Manchester Code Description Library extern sfr sbit MANRXPIN Sbit MANRXPIN at RFO bit extern sfr sbit MANTXPIN Sbit MANTXPIN at LATFI bit extern sfr sbit MANRXPIN i a 1 sbit MANRXPIN Direction at TRISFO Direction of the Receive pin Direction bit extern sfr sbit
10. MikroElektronika 154 mikroC PRO for PIC32 KVA TO PA Prototype unsigned long KVA TO PA const unsigned long Address Function converts virtual address from any Kernel segment to the appropriate physical address Desired Virtual address Retums Appropriate physical address O OC OoOo Example va ro Pa toxsroo0000 O OO OOOO Moes None OOO PA TO KVAO Retums Appropriate vrtuat adcressinthe KSEGD SSCS example Pa To ooa SSCS moes oe OoOo PA_TO_KVA1 PRetums VruwadiesinteKSEGI OOOO Example Pa ro Kvar omo000000 Moes None Ooo CPO GET Prototype unsigned long CPO GET TCPOReg register Description Function returns the value of the coprocessor Ee or part of the register based upon the argument entered Parameters Parameter must be a constant from the enumerated built in constants list which can be found at the bottom of this page Returns Value of the coprocessor register or part of the register unsigned long register value register value CPO GET CP CONFIG 155 MikroElektronika mikoC PRO for PIC32 CPO SET Prototype void CPO SET TCPOReg register unsigned long value Function sets the value of the coprocessor register or part of the register based upon the register argument Parameters register Register or register part must be a constant from the enumerated built in constants list which can be found at the bottom o
11. Writes a char in the current text panel of Glcd at coordinates x y x dot position on x axis y dot position on y axis color color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C dot x0 y0 SPI T6963C BLACK SPI T6963C write char Prototype void SPI T6963C write char unsigned char c unsigned char x unsigned char y unsigned char mode Writes a char in the current text panel of Glcd at coordinates x y Parameters c char to be written x char position on x axis y char position on y axis mode mode parameter Valid values SPI T6963C ROM MODE OR SPI T6963C ROM MODE XOR SPI T6963C ROM MODE AND and SPI T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more detai
12. EINSTEIN WOULD HAVE LIKED mE char txt GLCD LIBRARY DEMO WELCOME char txt2 Partial image demo unsigned char panel Current panel unsigned int xy General purpose register unsigned char curs Cursor visibility unsigned int cposx cposy Cursor x y position CHECON 0x32 ADIPCFG OxFFFF TRISB8 bit 1 Set RB8 as input TRISB9 bit 1 Set RB9 as input TRISB10 bit 1 Set RB10 as input TRISB11 bit 1 Set RB11 as input TRISB12 bit 1 Set RB12 as input TRISB13 bit 1 Set RC13 as input T6963C ctrlce Direction 0 T6963C ctrlce 0 Enable T6963C T6963C ctrlfs Direction 0 T6963C ctrlfs 0 Font Select 8x8 T6963C ctrlmd Direction 0 T6963C ctrlmd 0 Column number select Initialize T6963C T6963C init 240 128 8 Jp Enable both graphics and text display at the same time mr T6963C graphics 1 T6963C text 1 panel 0 i 0 curs 0 cposx cposy 0 Text messages ua T6963C write text txt T6963C write text txtl 0 0 0 T6963C ROM MODE XOR 15 T6963C ROM MODE MikroElektronika mikoC PRO for PIC32 Cursor wd T6963C cursor height 8 8 T6963C set cursor 0 0 T6963C cursor 0 Cu Draw solid boxes gr T6963C box 0 0 239 8 T6963C WHIT T6963C box 0 119 239 127 T6963C Draw rectangles ay fifdef LINE DEMO T6963C rectangle 0 0 239 127 T T6963C rec
13. Ps2 Config ums 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 PS2 pinout definition sbit PS2 Data at RBO bit sbit PSZ Clock at RBI bit sbit PS2 Data Direction at TRISBO bit sbit PS2 Clock Direction at TRISB1 bit End of PS2 pinout definition Ps2 Config Init PS 2 Keyboard Ps2 Key Read Prototype unsigned int Ps2 Key Read unsigned short value unsigned short special unsigned short pressed The function retrieves information on key pressed Parameters value holds the value of the key pressed For characters numerals punctuation marks and space value will store the appropriate ASCII code Routine recognizes the function of Shift and Caps Lock and behaves appropriately For special function keys see Special Function Keys Table special is a flag for special function keys F1 Enter Esc etc If key pressed is one of these special Will be set to 1 otherwise O pressed is set to 1 if the key is pressed and 0 if it is released 1 if reading of a key from the keyboard was successful 0 if no key was pressed PS 2 keyboard needs to be initialized See Ps2 Config routine unsigned short keydata 0 special 0 down 0 Press Enter to continue do if Ps2 Key Read
14. 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 Direction at TRISB7 bit End LCD module connections Reads time and date information from RTC PCF8583 void Read Time Soft_I2C_Star Soft I2C Writ t0 Issue start signal e 0 Soft I2C Write 2 t e 0 xA0 Address PCF8583 see PCF8583 datasheet Start from address 2 Soft I2C Star Issue repeated start signal Soft I2C Writ xAl Address PCF8583 for reading R W 1 seconds Soft I2C Read 1 Read seconds byte minutes Soft I2C Read 1 Read minutes byte hours Soft I2C Read 1 Read hours byte day Soft I2C Read 1 Read year day byte month Soft I2C Read 0 Read weekday month byte Soft I2C Stop Issue stop signal f meme ER SaaS es Formats date and time void Transform Time 419 MikroElektronika mikoC PRO for PIC32 seconds amp OxOF minutes amp OxOF hours amp OxOF day amp OxOF month amp OxOF seconds seconds amp OxF0 gt gt 4 10 4 minutes minutes amp OxFO gt gt 4 10 4 hours hours amp OxFO gt gt
15. text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Write text Here at current cursor position SPI Leds Out Cp Here SPI Lcd8 Chr Prototype void SPI Lcd8 Chr unsigned short row unsigned short column char out char Prints character on Lcd at specified position Both variables and literals can be passed as character Parameters row writing position row number column Writing position column number out char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Write character i bw row 2 column 3 SPT Leds Cbhr 2 3g Y MikroElektronika 508 mikroC PRO for PIC32 SPI Lcd8 Chr Cp Description Prints character on Lcd at current cursor position Both variables and literals can be passed as character Parameters out char character to be written Nothing Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Print e at current cursor position M s AE Write character e at current cursor position SPI Lcd8 Chr Cp e SPI Lcd8 Cmd Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Clear Lcd display SPI Lcd8 Cmd LCD CLEAR Predefined constants can be passed to the routine see Available SPI Lcd8 Commands 509 MikroElektronika mikoC PRO for PIC32
16. 289 MikroElektronika mikoC PRO for PIC32 HW Connection f vec3 g PIC32MX460F512L 5 3288 5g2z00 999o 990z9 35228 8825 Szateanaggaore VCC3 OSCELATOR 1 oVCC3 ovcca3 o 3 E 4 pons J mop Shielded twisted pair 7 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 Routines for file handling the Cf Fat routines are not performed directly but successively through 512B buffer Important Routines for file handling can be used only with FAT16 file system Library functions create and read files from the root directory only Library functions populate both FAT1 and FAT2 tables when writing to files but the file data is being read from the FAT1 table only i e there is no recovery if the FAT1 table gets corrupted If MMC SD card has Master Boot Record MBR the library will work with the first available primary logical partition that has non zero size If MMC SD ca
17. 64 64 64 64 64 f 64 L 64 Draw filled circles ad ifdef FILL DEMO T6963C circle T6963C circl T6963C circl T6963C circl T6963C circl T6963C circl T6963C circl T6963C circl T6963C circl T6963C circl T6963C circl T6963C circl fendif Hi Hs an H H H l H H t H H j 00000000000 Delay ms 1000 T6963C sprite 76 4 Delay ms 1000 T6963C_setGrPanel 1 T m L6963C image mikroE Delay ms 1000 ifdef PARTIAL IMAGE DEMO T6963C grFill 0 32 957 120 120 120 1207 120 120 L2 120 120 120 E20 10 30 50 70 90 319 130 64 64 64 64 64 64 64 64 64 64 64 64 60 T6963C_WHITE 55 T6963C BLAC 50 T6963C WHIT 45 T6963C BLAC 40 T6963C WHIT 35 T6963C BLAC 30 T6963C WHIT 25 T6963C BLAC 20 T6963C WHIT 15 T6963C BLACK 10 T6963C WHITE T6963C WHITI T6963C WHIT T6963C WHIT T6963C WHITI T6963C WHIT T6963C WHI T6963C WHIT Ej Ed Ed DH Hd d d N S N S N S A S 5 T6963C BLACK einstein 88 119 240x128 bmp T6963C displayGrPanel 1 T6963C Partiallmage 0 0 64 64 240 image Delay ms 1000 T6963C graphics 0 fendif T m L6963C image mikroE T6963C graphics 1 240x128 bmp T6
18. Function prototype Identifiers declared within the list of parameter declarations in a function prototype not as a part of a function definition have a function prototype scope This scope ends at the end of the function prototype Visibility The visibility of an identifier is a region of the program source code from which an identifier s associated object can be legally accessed Scope and visibility usually coincide though there are circumstances under which an object becomes temporarily hidden by the appearance of a duplicate identifier the object still exists but the original identifier cannot be used to access it until the scope of the duplicate identifier ends 193 MikroElektronika 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 nested block double j j is local name in the nested block j 0 1 i and double j are visible int j 3 in scope but hidden double j out of scope j t 1 int j visible and 4 i and j are both out of scope Name Spaces Name space is a scope within which an identifier must be unique The mikroC PRO for PIC32 uses four distinct categories of identifiers 1 goto label names must be unique within the function in which they are declared 2 Structure union and enumeration tags mu
19. MAC address behind the IP address the requested IP address was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet 24600 Init unsigned char IpAddr 4 192 168 ly Dole Z7 IP address SPI Ethernet 243600 arpResolve IpAddr 5 get MAC address behind the above IP address wait 5 secs for the response The Ethernet services are not stopped while this routine waits for ARP reply The incoming packets will be processed normaly during this time SPI Ethernet 24j600 sendUDP Prototype unsigned int SPI Ethernet 243600 sendUDP unsigned char destIP unsigned int sourcePort unsigned int destPort unsigned char pkt unsigned int pktLen This is UDP module routine It sends an UDP packet on the network Parameters dest IP remote host IP address sourcePort local UDP source port number destPort destination UDP port number pkt packet to transmit pktLen length in bytes of packet to transmit 1 UDP packet was sent successfully 0 otherwise Ethernet module has to be initialized See SPI Ethernet 24j600 Init unsigned char IpAddr 4 192 168 1 1 remote IP address Ethernet 24j600 sendUDP IpAddr 10001 10001 Hello 5 send Hello message to the above IP address from UDP port 10001 to UDP port 10001 MikroElektronika 480 mikroC PRO for PIC32 SPI Ethernet 24j600 dnsResolve Prototype unsigned char SPI Ethernet 245600 d
20. Not all of the standard functions have been included The functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC32 programming Be sure to skim through the description before using standard C functions Library Functions memchr memcmp memcpy memmove memset strcat strchr strcmp strcpy strlen strncat strncpy strspn strncmp strstr strcspn strpbrk strrchr strtok memchr Prototype void memchr void p char n unsigned int v Description Function locates the first occurrence of char n in the initial v bytes of memory area starting at the address The function returns the pointer to this location or 0 if the n was not found For parameter you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example amp mystring or amp PORTB char txt mikroElektronika res memohr txt e 16 example locates first occurrence of the letter e in the string txt in the first 16 characters of the string MikroElektronika 620 mikroC PRO for PIC32 memcmp Prototype int memcmp void s1 void s2 int n Description Function compares the first n characters of objects pointed to by s1 and s2 and returns zero if the objects are equal or returns a difference between the first d
21. 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 Parameters ip IP address to be resolved tmax time in seconds to wait for an reply MAC address behind the IP address the requested IP address was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init unsigned char IpAddr 4 192 168 1 1 IP address SPI Ethernet arpResolve IpAddr 5 get MAC address behind the above IP address wait 5 secs for the response The Ethernet services are not stopped while this routine waits for ARP reply The incoming packets will be processed normaly during this time SPI Ethernet sendUDP PI Prototype unsigned int SPI Ethernet sendUDP unsigned char destIP unsigned int sourcePort unsigned int destPort unsigned char pkt unsigned int pktLen This is UDP module routine It sends an UDP packet on the network Parameters dest IP remote host IP address sourcePort local UDP source port number destPort destination UDP port number pkt packet to transmit pktLen length in
22. A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens each of which is delimited by a character from the string pointed to by s2 The first call in the sequence has s1 as its first argument and is followed by calls with a null pointer as their first argument The separator string pointed to by s2 may be different from call to call The first call in the sequence searches the string pointed to by s1 for the first character that is not contained in the current separator string pointed to by s2 If no such character is found then there are no tokens in the string pointed to by s1 and the strtok function returns a null pointer If such character is found it is the start of the first token The strtok function then searches from there for a character that is contained in the current separator string If no such character is found the current token extends to the end of the string pointed to by si and subsequent searches for a token will return a null pointer If such a character is found it is overwritten by a null character which terminates the current token The strtok function saves a pointer to the following character from which the next search for a token will start Each subsequent call with a null pointer as the value of the first argument starts searching from the saved pointer and behaves as described above char x 10 void main strepy x strtok mrkroEl s
23. The file must be previously assigned See Mmc Fat Assign P inque long my file size my Abe size Mmc Fat Get File Size MikroElektronika 316 mikroC PRO for PIC32 Mmc Fat Get Swap File Prototype Parameters MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init unsigned long Mmc Fat Get Swap File unsigned long sectors cnt char filename char file attr 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 If it is not erased and there is still enough space for a new swap file this function will delete it after allocating new memory space for a new swap file The purpose of the swap file is to make reading and writing to MMC SD media as fast as possible by using the Mmc Read Sector and Mmc Write Sector functions directly without potentially damaging the FAT system The swap file can be considered as a window on the media where the user can freely write read data It s main purpose in this library is to be used for fast data acquisition when the time critical acquisition has finished the data can be re written into a normal file and formatted in the most suitable way sectors cnt number of co
24. returns 0 MikroElektronika 608 mikroC PRO for PIC32 toupper Prototype unsigned int toupper char character If the character is a lowercase letter a z the function returns an uppercase letter Otherwise the function returns an unchanged input parameter res toupper a returns A res toupper B returns B tolower Prototype unsigned int tolower char character If the character is an uppercase letter A Z function returns a lowercase letter Otherwise function returns an unchanged input parameter res tolower A returns a res tolower b returns b 609 MikroElektronika mikoC PRO for PIC32 ANSI C Math Library The mikroC PRO for PIC32 provides a set of standard ANSI C library functions for floating point math handling Important Not all of the standard functions have been included The functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC32 programming Be sure to skim through the description before using standard C functions Library Functions acos asin atan atan2 ceil COS cosh exp fabs floor frexp Idexp log log10 modf pow sin sinh sqrt tan tanh acos Prototype double acos double x Description Function returns the arc cosine of parameter x that is the value whose cosine is x The i
25. Delta 80 881 413 404407ms Stopwatch 2 103 943 273 105197 16 ms Reset To Zero MikroElektronika 124 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 mikrolCD is selected as a debugger To show the EEPROM Watch Window select Debug Windows EEPROM from the View drop down menu The EEPROM Watch Window shows current content of the MCU s internal EEPROM memory There are two action buttons concerning the EEPROM Watch Window Read EEPROM Reads data from MCU s internal EEPROM memory and loads it up into the EEPROM window Write EEPROM Writes data from the EEPROM window into MCU s internal EEPROM memory EEPROM Watch Read EEPROM Write EEPROM narn STATUS Idle 125 MikroElektronika mikoC PRO for PIC32 Code Watch Window Note Code Watch Window is available only when mikrolCD 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 Win
26. E Y LCD SHIFT RIGHT LCD SHIFT LEFT Move Delay for i 0 SPI Lcd8 Cmd Move Delay i 8 itt LCD SHIFT RIGHT ER SPI 8 BIT 4 SPI SS DISABLE Lr ti Pod Pid Pd SPI DATA SAMPLE MIDDLE _ Initialize Lcd over SPI interface Clear display Turn cursor off Print text to Led Append Print text to Lcd 2nd ist For Lcd with more than For Lcd with more than the right Move text to Endless loop Move text to Move text to 6th ist the left 7 times column column two rows two rows 4 times the right 7 times ult MikroElektronika mikoC PRO for PIC32 5K SPI Lcd8 HW connection PIC32MX460F512L 5 MikroElektronika 912 mikroC PRO for PIC32 SPI T6963C Graphic Lcd Library The mikroC PRO for PIC32 provides a library for working with Gleds based on TOSHIBA T6963C controller via SPI interface The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules It is capable of controlling displays with a resolution up to 240x128 Because of its low power and small outline it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement equipment Although this controller is small it has a capability of displaying and merging text and graphics and it manages all interfacing signals
27. Interrupt Assistant x void interrupt i w ilevel 4 ics SOFT OK MikroElektronika 92 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 MikroElektronika LCD Custom Char Generator E Pi B Save Load Fillall Clearall Invert Preview const char character 0 4 4 31 4 4 0 0 void CustomChar char pos row char pos char char i Lcd Cmd 64 for i 0 i lt 7 i Lcd Chr CP character i Lcd Cmd LCD RETURN HOME Lcd Chr pos row pos char 0 93 MikroElektronika 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 min from Tools toolbar Seven Segment Editor Common cathode 113 Com i UDP Terminal The mikroC PRO for PIC32 includes the UDP Terminal You can launch it from the drop down menu Tools UDP Terminal MikroElektronika UDP Terminal Settings IP Address 192 168 020 025 Connect Send mikroElektronika Append
28. Lcd Chr isis dud void Lcd Chr unsigned int row unsigned int column char out char Prints character on Lcd at specified position Both variables and literals can be bu as a character Parameters row writing position row number column Writing position column number out char character to be written The Lcd module needs to be initialized See Lcd Init routine Zt ide character i at row 2 column 3 Lcd Chr 3y are MikroElektronika 350 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 Nothing Requires The Lcd module needs to be initialized See Lcd Init routine Write character e at current cursor position Led Chr Cp e None Lcd Cmd Clear Lcd display Lcd Cmd LCD CLEAR Predefined constants can be passed to the function see Available Lcd Commands Available Lcd Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected CD RETURN HOME 391 MikroElektronika 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 a
29. MikroElektronika 466 mikroC PRO for PIC32 External dependencies of SPI Ethernet ENC24J600 Library The following variables must be defined in all projects using SPI Ethernet Description ENC24J600 Library extern sfr sbit SPI sbit SPI Ethernet 243600 CS at Ethernet 24j600 CS ENG aT Sd ehipiselect pin LATF1 bit extern sfr sbit SPI Direction of the ENC24J600 chip sbit SPI Ethernet 243600 CS_ Ethernet 24j600 CS Direction select pin Direction at TRISF1 bit The following routines must be defined in all project using SPI Ethernet Description ENC24J600 Library unsignedintSPI Ethernet 245600 UserTCP unsigned char remoteHost unsigned int remotePort unsigned int TCP request handler localPort unsigned int reqLength TEthj600PktFlags flags s Refer to the library example at the bottom of this page for code implementation unsignedintSPI Ethernet 243600 UserUDP unsigned char remoteHost unsigned int remotePort unsigned int UDP request handler localPort unsigned int reqLength TEthj600PktFlags flags Refer to the library example at the bottom of this page for code implementation 467 MikroElektronika mikoC PRO for PIC32 Library Routines SPI Ethernet 24j600 Init SPI Ethernet 24j600 Enable SPI Ethernet 24j600 Disable SPI Ethernet 24j600 doPacket SPI Ethernet 24j600 putByte SPI Ethernet 24j600 putBytes SPI Ethernet 24j600 putString SP
30. 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 ofthe switch statement is switch expression case constant expression 1 statement 1 case constant expression n statement n default statement First the expression condition is evaluated The switch statement then compares it to all available constant expressions following the keyword case If a match is found switch passes control to that matching case causing the statement following the match evaluates Note that constant expressions must evaluate to integer It is not possible to have two same constant expressions evaluating to the same value Parentheses around expression are mandatory Upon finding a match program flow continues normally the following instructions will be executed in natural order regardless of the possible case label If no case satisfies the condition the default case evaluates if the label default is specified For example if a variable i has value between 1 and 3 the following switch would always return it as 4 switch i case 1 i case 2 i case 3 i To avoid evaluating any other cases and relinquish control from switch each case s
31. Nothing Requires Glcd needs to be initialized see Glcd Init routine Draw image my image on Glcd Glcd Image my image Use the mikroC PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd Glcd Partiallmage Prototype void Glcd Partiallmage 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 Description Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroC PRO for PIC pointer to const and pointer to RAM equivalency Nothing Requires Glcd needs to be initialized see Glcd Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 Gled Partralrimage 10 12 10 15 16 32 image Use the mikroC PRO for PIC32 integrated Glcd Bitmap Editor Tools Glcd Bitmap Editor to convert image to a constant array sui
32. Partial image Delay ms 500 SPI Glcd Partiallmage 24 16 68 30 128 64 truck bmp Delay ms 500 SPI Glcd Partiallmage 56 34 68 30 128 64 truck bmp Delay2s Delay2s SPI Glcd Fill 0x00 Clear GLCD SPI Glcd Box 62 40 124 56 1 Draw box SPI Glcd Rectangle 5 5 84 35 1 Draw rectangle Delay ms 1000 SPI Glcd Rectangle Round Edges 2 2 87 38 7 1 Delay ms 1000 SPI Glcd Rectangle Round Edges Fill 8 8 81 32 12 1 497 MikroElektronika mikoC PRO for PIC32 Delay ms 1000 SPI Glod Line 0 0 127 63 1 Delay2s for counter 5 counter lt 60 countert 5 Delay ms 250 SPI Glcd V Line 2 54 counter 1 SPI Glcd H Line 2 120 counter 1 Delay2s SPI Glcd Fill 0x00 PI Glcd Set Font Font Gl omeText 3X5 CAPITALS PI Glcd Write Text somel elay2s Junun PI Glcd Set_Font Font G omeText 5x7 Font PI Glcd Write Text somel elay2s Junun SPI Glcd Set Font Font Gl someText 5x7 Font SPI Glcd Set Font Font Glcd Character8x7 GLCDFonts c in Uses folder SPI Glcd Write Text mikroE 5 7 2 for counter 1 counter lt 10 counter SPI Gled Circle 63 32 3 counter 1 Delay2s SPI Gled Circle Fi11 63 32 30 1 Delay2S SPI Glod Box 12 20 70 63 2 Delay2s SPI Glcd Fill OxFF SPI Glcd Set Font Font Glcd Character8x7 8 someText 8x7 Font SPI Glcd Write Text someText 5 0 2 D
33. The first line LATB BO 1 will be decoded like in this way READ LATB is read STORE Data is stored inside a temporary internal register in the MCU OIUre reau vaiue Read from LATB c Discharged I capacitor capacitor Actual voltage levels on MCU pins are no longer relevant when using LATx for output MODIFY Data is modified to set the RBO bit WRITE LATB is written with the modified data The output driver for RBO turns on and the _ Modify value capacitor starts to charge Write gpa pc modified value Discharged 0 l capacitor capacitor MikroElektronika 170 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 Store read Expected value value Read from LATB T e capacitor 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 The Modify value output driver for RB1 turns on and the output driver for RBO remains turned on Write modified value Charging T capacitor When to use LATx instead of PORTx Depending on your hardware one may experience unpredictable behavior when using PORTx bits for driving output Displays GLCD LCD chip select pins in SPI interfaces and other cases when you need fast and r
34. The following assignments are illegal ci 0 NO cannot assign to a const int eue NO cannot change a const int pci 3 NO cannot assign to an object ef pointed at by pointer to const cp amp ci NO cannot assign to a const pointer ce even if value would be unchanged QDCT NO cannot change const pointer pi pci NO if this assignment were allowed Vi you would be able to assign to pci Er a const value by assigning to pi Similar rules are applayed to the volatile modifier Note that both const and volatile can appear as modifiers i ifi MikroElektronika 184 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 Constant expressions can consist only of the following literals enumeration constants simple constants no constant arrays or structures sizeof operators Constant expressions cannot contain any of the following operators unless the operators are contained within the operand of a sizeof operator assignment comma d
35. Wait for button to be released if Button amp PORTB 6 1 1 RB6 plays Tone2 Tone2 while RB6 bit Wait for button to be released if Button amp PORTB 5 1 1 RB5 plays Tone3 Tone3 while RB5 bit Wait for button to be released if Button amp PORTB 4 1 1 RB4 plays Melody2 Melody2 while RB4 bit Wait for button to be released if Button amp PORTB 3 1 1 RB3 plays Melody Melody while RB4 bit Wait for button to be released HW Connection OSCILLATOR PIEZO 2 SPEAKER Example of Sound Library MikroElektronika 432 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 To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Switching between the SPI modules in the SPI library is done by the SPI Set Active function both SPI modules have to be previously initialized Library Routines SPIx Init SPIx
36. We have lost our previous message CANSPI MASK Constants The CANSPI_ MASK constants define mask codes Function CANSPISetMask expects one of these as it s argument Copy Code To Clipboard const unsigned int CANSPI MASK B1 0 CANSPI MASK B2 1 CANSPI FILTER Constants The CANSPI FILTER constants define filter codes Functions CANSPISetFilter expects one of these as it s argument Copy Code To Clipboard const unsigned int CANSPI FILTER B1 F1 CANSPI FILTER Bl F2 CANSPI FILTER B2 F1 CANSPI FILTER B2 F2 CANSPI FILTER B2 F3 CANSPI FILTER B2 F4 Sh EQ BA pt MikroElektronika 282 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 Code for the first CANSPI node Copy Code To Clipboard unsigned char Can Init Flags Can Send Flags Can Rcv Flags unsigned char Rx Data Len bytes char RxTx Data 8 char Msg Rcvd const long ID 1st 12111 ID 2nd 3 long Rx ID CANSPI module connections sbit CanSpi CS at LATFO bit sbit CanSpi CS Direction at TRISFO0 bit sbit CanSpi Rst at LATF1 bit sbit CanSpi Rst Direction at TRISFl bit
37. WordToStr minute outstr ARTI Write Text outstr filename 7 filename 7 if amp hour amp minute n D Lr LE tir i n n U file has Cf Fat G its modified date d amp year amp month been found get File Date Modifi UART1 Write Text modified WordToStr year outst UART1 Write 1 t outs ByteToStr ts UART1 Writ ts WordToStr tr UART1 Writ WordToStr UART1 Write WordToStr ART1 Writ amp hour amp day amp minute Str tr U get file size fsize Cf Fat Get File Size LongToStr signed long fsize outstr UART1 Write Line outstr else file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 MikroElektronika 304 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 see help on this function for details if size LongToStr signed long size err txt UART1 Write Line err txt for i 0 i 5000 i Cf Write Sector sizet t Buffer UART1 Write Main Uncomment the function s to test the desired operation s void main define C
38. logical negation The following two expressions are equivalent Unary Bitwise Operator The result of the bitwise negation operator is the bitwise complement of the operand In the binary representation of the result every bit has the opposite value of the same bit in the binary representation of the operand bitwise complement unary inverts each bit li Address and Indirection Operator 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 See Pointers section for more details accesses a value indirectly through a pointer result is the 14 value at the address to which operand points gives the address of its operand Example int p to y p to y is defined as a pointer to an int int y y is defined as an int p to y ey assigns the address of the variable y to the pointer p to y p to y 37 causes the variable y to receive the value 3 Note Besides these sizeof and casting unary operators are supported also MikroElektronika 246 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
39. 0 Reset error counter else No error occured if byte rcvd OxOE If End byte was received see Transmitter example do not write anymore received byte on LCD Lcd Chr CP byte rcvd else write character on LCD chr counter t t Counts how many chars have been written on LCD if chr counter 25 If there were more then 25 characters synchronization is off Lcd Cmd LCD CLEAR Clear the LCD of garbled communication Man Synchro Try to synchronize again else chr counter 0 reset chr counter Delay ms 25 while byte rcvd OxO0E If End byte was received exit do loop The following code is code for the Manchester receiver it shows how to use the Manchester Library for receiving data Copy Code To Clipboard Manchester module connections sbit MANRXPIN at RFO bit sbit MANRXPIN Direction at TRISFO bit sbit MANTXPIN at LATF1 bit sbit MANTXPIN Direction at TRISF1 bit End Manchester module connections char index char sl void main CHECON 0 charac mikrol x32 ter Elektronika MikroElektronika mikroC PRO for PIC32 ADIPCFG TRISB LATB OxFFFF 0 0 Man Send Init while 1 Man Send 0x08 Delay ms 100 character s1 0 index 0 while character Man Send character Delay ms 90 indext character Man Send 0x0E Delay ms 1000 sl index
40. Address pin 1 CF A0 Address pin 0 DY direction Direction of the Ready pin E direction Direction of the Write enable pin E direction Direction of the Output enable pin D1 direction Direction of the Chip detect pin El direction Direction of the Chip enable pin CF A2 direction Direction of the Address 2 pin CF A1 direction Direction of the Address 1 pin CF A0 direction Direction of the Address 0 pin must be defined before using this function set compact flash pinout char Cf Data Port at PORTF sbit CF RDY at sbit CF WE at sbit CF OE at sbit Cl at sbit CF CEI at sbit at sbit at sbit CF at D bit D6 bit D5 bit D4 bit D3 bit D2 brit DI bit DO bit D D DDD N sbit C direction at TRISDT bit sbit E direction at TRISD6 bit sbit B direction at TRISDS bit sbit CD1 direction at TRISD4 bit sbit CF CE1 direction at TRISD3 bit sbit CF A2 direction at TRISD2 bit sbit CF Al direction at TRISD1 bit Sbit CF AO direction at TRISDO bit end of compact flash pinout Cf Init initialize CF MikroElektronika 290 mikroC PRO for PIC32 Cf Detect Prototype Checks for presence of CF card by reading the chip detect pin 1 if CF card was detected 0 otherwise The corresponding MCU ports must be appropriately initialized for CF card See C Init Wait until CF card is inserted do asm nop while Cf Detect PIC32 fa
41. Available SPI Lcd8 Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected Library Example This example demonstrates how to communicate Lcd in 8 bit mode via the SPI module using serial to parallel convertor MCP23S17 Copy Code To Clipboard char text mikroElektronika Port Expander module connections sbit SPExpanderRST at LATD8 bit sbit SPExpanderCS at LATD9 bit sbit SPExpanderRST Direction at TRISD8 bit sbit SPExpanderCS Direction at TRISD9 bit End Port Expander module connections char i Loop variable void Move Delay Function used for text moving Delay ms 500 You can change the moving speed here void main If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander MikroElektronika 910 mikroC PRO for PIC32 SPI2 Init Advanced SPI MAST SPI CLK IDLE LOW SPI ACTIVE 2 IDLE SPI I Lcd8 Cmd SPI Lcd8 Config 0 LCD CLEAR SPI Lcd8 Cmd SPI SPI I Lcd8 Out 2 SPI Lcd8 Out 1i Lcd8 Chr C POS rl text LCD CURSOR OFF 6 mikroE SPI Lcd8 Out 3 1 mikroE SPI Lod8 Out 4 15 mikroE Delay ms 2000 Moving text for i 0 SPI Lcd8 Cmd i 4 i Move Delay while 1 for i 0 SPI Lcd8 Cmd i 8
42. CR Send as typing Pie F Send as number mikroElektronika mikroElektronika MikroElektronika 94 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 from Tools toolbar Send mikroElektronika Send Repeat sending a r r Repeat sending every Support ASCII Append New Line ssia Send ASCII Send as typing BEZDLILLA Send from file m 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 Suppose we are writing a example for a GSM GPSR module which is connected to the EasyPIC6 and we would like to provide a photo of our hardware jumpers cables etc within the example It would also be nice to put some documentation about chip we are using and a GSM module extra board Now we can have all those things defined in one single comment using Active Comment Editor New Active Comment When you start Active Comment Editor
43. Connection Example Configure AN pins as digit Initialize transmitter Endless loop Send start byte Wait for a while Take first char from strin Initialize index variable String ends with zero Send character Wait for a while Increment index variable Take next char from strin Send end byte Transmitter RF module PIC32MX460F512L 15 Simple Transmitter connection Recevier RF module Antenna vec vcc RT4 m GND Antenna A Simple Receiver connection al i o g g OSCILLATOR OSCILLATOR SUL 361 MikroElektronika 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 The heap memory size can be configured in the Edit Project window Also user can override heap memory size in the code by setting the HEAP SIZE constant Library Routines Heap Init malloc free LargestFreeMemBlock TotalFreeMemSize Heap Init eums Wm const HEAP SIZE i declare Heap size Heap Init se
44. 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 These parameters can be fetched by using appropriate library IP get routines SPI Ethernet 24j600 getlpAddress fetch IP address SPI Ethernet 24j600 getGwlpAddress fetch gateway IP address SPI Ethernet 24j600 getDnslpAddress fetch DNS IP address SPI Ethernet 24j600 getlpMask fetch IP subnet mask UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port tmax time in seconds to wait for an reply 1 network parameters were obtained successfully 0 otherwise Ethernet module has to be initialized See SPI_Ethernet_24j600_Init SPI Ethernet 244600 initDHCP 5 get network configuration from DHCP server wait 5 sec for the response The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time When DHCP module is used global library variable SPI Ethernet 243600 userTimerSec is used to keep track of time It is user responsibility to increment this variable each second in it s code MikroElektronika 482 mikroC PRO for PIC32 SPI Ethernet 24j600 doDHCPLeaseTime Prototype unsigned int SPI Ethernet 2
45. Draw filled circles z ifdef FILL DEMO SPI T6963C circl PI T6963C circl PI T6963C circl PI T6963C circl PI T6963C circl PI T6963C circl PI T6963C circl PI T6963C circl PI T6963C circl PI T6963C circl PI T6963C circl SPI T6963C circl fendif ANNNNNNNNMN ER Eh Eh Eh EAER Eh eh bh En bh th je poppe j p es G j pg jes Rei ea 000000000000 Delay ms 1000 SPI T6963C sprite 76 4 Delay ms 1000 SPI T6963C setGrPanel 1 239 0 64 64 64 64 64 64 64 120 120 120 120 120 120 120 120 120 120 120 120 10 30 50 70 90 110 130 64 64 64 64 64 64 64 64 64 64 64 64 LADO A OS Ri ee oe Tw 6963C WHITE SPI T6963C WHITE SPI T6963C WHITI SPI T6963C WHITI SPI T6963C WHIT SPI T6963C WHIT SPI T6963C WHITI T6963C WHITI SPI T6963C WHITI SPI 60 SPI 7 55 SPI 7 50 SPI 7 45 SPI 7 40 SPI 7 35 SPI 7 30 SPI 7 25 SPI 1 20 SPI 1 15 SPI 7 10 SPI 7 C6963C WH 6963C Bl C6963C WH 6963C Pl C6963C WH 6963C Bl C6963C WH 6963C Bl C6963C WH 6963C B C6963C WH Ed pd pd Dd pd d d ITE LACK ITE LACK ITE LACK ITE LACK ITE LACK ITE Neos M8 M8 5 SPI T6963C BLACK einstein 88 SPI T6963C image mikroE 240x128 bmp SPI T6963C displayGrPanel 1 Delay ms 1
46. 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 of memory 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 Expressions are evaluated according to a certain conversion grouping associativity and precedence rules which depends on the operators used presence of parentheses and data types of the operands The precedence and associativity of the operators are summarized in Operator Precedence and Associativity The way operands and subexpressions are grouped does not necessarily specify the actual order in which they are evaluated by the mikroC PRO for PIC32 Expressions can produce lvalue rvalue or no value Expressions might cause side effects whether they produce a value or not Comma Expressions One of the specifics of C is that it allows using of comma as a sequence operator to form so called comma expressions or sequences Comma expression is a comma delimited list of expressions it is formally treated as a single expression So it can be used in places where an expression is expected The following sequence expression 1 expression 2 results in the left to right evaluation of each expression
47. PORTB dat i 1 dat 0 dat 0 1 increment received dat 0 Delay ms 1 RS485Slave Send dat 1 and send it back to master MikroElektronika 42 mikroC PRO for PIC32 HW Connection Shielded pair na nnnnannannnnninnnnnnnnnr no longer than 300m OSCILLATOR PIC32MX460F512L Example of interfacing PC to PIC32 MCU via RS485 bus with LTC485 as RS 485 transceiver 43 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 if exists DATA2 if exists DATA3 if exists CRC STOP BYTE OxA9 DATALEN bits bit7 1 MASTER SENDS SLAVE SENDS bit6 1 ADDRESS WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE 0 ADDRESS UNCHANGED bit5 0 FIXED bit4 1 DATA3 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE O0 DATA3 if exists UNCHANGED bit3 1 DATA2 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE O0 DATA2 if exists UNCHANGED bit2 1 DATA1 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE O0 DATA1 if exists UNCHANGED bitlbitO 0 to 3 NUMBER OF DATA BYTES SEND CRC generation crc send datalen address crc send d
48. Stand Alone CAN controller in the CANSPI module is set to Disable CAN capture Continue CAN operation in Idle mode Do not abort pending transmissions Fcan clock 4 Tcy Fosc Baud rate is set according to given parameters CAN mode Normal Filter and mask registers IDs are set to zero Filter and mask message frame type is set according to CANSPI_ CONFIG FLAGS value SAM SEG2PHTS WAKFIL and DBEN bits are set according to CANSPI CONFIG FLAGS value Parameters SJW as defined in MCU s datasheet CAN Module BRP as defined in MCU s datasheet CAN Module PHSEG1 as defined in MCU s datasheet CAN Module PHSEG2 as defined in MCU s datasheet CAN Module PROPSEG as defined in MCU s datasheet CAN Module CANSPI CONFIG FLAGS is formed from predefined constants See CANSPI CONFIG FLAGS constants Nothing 213 MikroElektronika 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 See connection example at the bottom of this pa
49. T6963C fill T6963C dot T6963C write char T6963C write text T6963C line T6963C rectangle T6963C rectangle round edges T6963C rectangle round edges fill T6963C box T6963C circle T6963C circle fill T6963C image T6963C Partiallmage T6963C sprite T6963C set cursor The following low level library routines are implemented as macros These macros can be found in the T6963C n header file which is located in the T6963C example projects folders T6963C clearBit T6963C setBit T6963C negBit T6963C displayGrPanel T6963C displayTxtPanel T6963C_setGrPanel T6963C setTxtPanel T6963C_panel Fill T6963C grFill T6963C txtFill T6963C cursor height T6963C graphics T6963C text T6963C cursor T6963C cursor blink MikroElektronika 538 mikroC PRO for PIC32 T6963C init Prototype void T6963C init unsigned int width unsigned char height unsigned char fntW Description Initalizes the Graphic Lcd controller Display RAM organization The library cuts the RAM into panels a complete panel is one graphics panel followed by a text panel see schematic below Parameters width width of the Glcd panel height height of the Glcd panel ntW font width Requires Global variables 6963C_dataPort Data Port r6963C_ ctrilwr Write signal pin 6963C_ctrlrd Read signal pin r6963C_ ctrlca Command Dat
50. The purpose of the swap file is to make reading and writing to CF media as fast as possible by using the Cf_Read_Sector and Cf_Write_Sector functions directly without potentially damaging the FAT system Swap file can be considered as a window on the media where the user can freely write read data It s main purpose in the this library is to be used for fast data acquisition when the time critical acquisition has finished the data can be re written into a normal file and formatted in the most suitable way sectors cnt number of consecutive sectors that user wants the swap file to have 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 The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension file a
51. The volatile qualifier indicates that variable values can be changed both with or without user s interference in the program The compiler should not optimize such variable Typedef Specifier The typedef declaration introduces a name that within its scope becomes a synonym for the specified type You can use typedef declarations to construct shorter or more meaningful names for types already defined by the language or declared by the user Typedef names allow you to encapsulate implementation details that may change Unlike the struct union and enum declarations the t ypedef declarations do not introduce new types but new names for existing types The specifier typedef stands first in the declaration typedef lt type definition gt synonym The typedef keyword assigns synonymto type definition gt The synonym needs to be a valid identifier A declaration starting with the typedef specifier does not introduce an object or a function of a given type but rather a new name for a given type In other words the t ypedef declaration is identical to a normal declaration but instead of objects it declares types It is a common practice to name custom type identifiers with starting capital letter this is not required by the mikroC PRO for PIC32 MikroElektronika 226 mikroC PRO for PIC32 For example Let s declare a synonym for unsigned long int typedef unsigned long int Distance Now synonym Distance c
52. else if RB1 bit amp amp value gt 0 Tf RB1 button is pressed value gu decrement value DAC Output value Send value to DAC chip Delay ms 1 Slow down key repeat pac 439 MikroElektronika mikoC PRO for PIC32 HW Connection CN10 DAC CONNECTOR SPI MOSI OSCILLATOR 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 ENC28460 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 Communication with the host controller is implemented via two interrupt pins and the SPI with data rates of up to 10 Mb s Two dedicated pins are used for LED link and network activity indication This library is designed to simplify handling of the underlying hardware 2NC28J60 It works with any PIC32 with integrated SPI and more than 4 Kb ROM memory 38 to 40 MHz clock is recommended to get from 8 to 10 Mhz SPI clock otherwise PIC32 should be clocked by ENC28J60 clock output due to its silicon bug in SPI hardware If you try lower PIC32 clock speed there
53. hexadecimal base 16 binary base 2 or octal base 8 In the absence of any overriding suffixes the data type of an integer constant is derived from its value Long and Unsigned Suffixes The suffix L or 1 attached to any constant forces that constant to be represented as a long Similarly the suffix U or u forces a constant to be unsigned Both L and U suffixes can be used with the same constant in any order or case ul Lu UL etc In the absence of any suffix U u L or 1 a constant is assigned the smallest of the following types that can accommodate its value short unsigned short int unsigned int long int unsigned long int Otherwise If a constant has the U suffix its data type will be the first of the following that can accommodate its value unsigned short unsigned int unsigned long int If a constant has the L suffix its data type will be the first of the following that can accommodate its value long int unsigned long int If a constant has both L and U suffixes LU or UL its data type will be unsigned long int Decimal Decimal constants from 2147483648 to 4294967295 are allowed Constants exceeding these bounds will produce an Out of range error Decimal constants must not use an initial zero An integer constant that has an initial zero is interpreted as an octal constant Thus int i 10 decimal 10 int i 010 decimal 8 int 1 Q decimal 0 octal 0 119 M
54. mikroC PRO for PIC32 Manual 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 offeatures 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 3096 code reduction and many more Numerous ready to use and well explained examples will give a good start for your embedded project 7 MikroElektronika SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD waking ib si ple mikoC PRO for PIC32 Table of Contents CHAPTER 1 30 INTRODUCTION 30 Introduction to mikroC PRO for PIC32 31 Features 31 Where to Start 31 Software License Agreement 32 mikroElektronika Associates License Statement and Limited Warranty 32 IMPORTANT READ CAREFULLY 32 LIMITED WARRANTY 32 HIGH RISK ACTIVITIES 33 GENERAL PROVISIONS 33 Technical Support 34 How to Register 34 Who Gets the License Key 34 How to Get License Key 34 After Receving the License Key 36 CHAPTER 2 38 mikroC PRO for PIC32 38 Environment 38 Main Menu Options 39 File 40 File Menu Options 40 Edit 41 Edit Menu Options 41 Find Text 42 Replace Text 42 Find In Files 43 Go To Line 43 Regular expressions option 43 View 44 View Menu Options 44 Project 46 Project Menu Options 46
55. no type checking beyond that is enforced That is c red OK c 1 Also OK means the same MikroElektronika 198 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 For example enum colors black value 0 red value 1 green value 2 blue 6 value 6 violet value 7 white 4 value 4 Initializer expression can include previously declared enumerators For example in the following declaration enum memory sizes bit 1 nibble 4 bit byte 2 nibble kilobyte 1024 byte nibble would acquire the value 4 byte the value 8 and kilobyte the value 8192 Anonymous Enum Type In our previous declaration the identifier colors is an optional enumeration tag that can be used in subsequent declarations of enumeration variables of the enum colors type enum colors bg border declare variables bg and border Like with struct and union declarations you can omit the tag if no further variables of this enum type are required Anonymous enum type enum black red green blue violet white color Enumeration Sco
56. r n Copyright Nr Mn c MikroElektronika 2006 r n Revision History r n 20060710 XtrXn MikroElektronika 644 Parameters The precision field is a non negative number that specifies the number of characters to print number of significant digits or number of decimal places The precision field can cause truncation or rounding of the output value in the case of a floating point number as specified in the following table flags Meaning of the precision field d u o x X The precision field is where you specify the minimum number of digits that will be included in the output value Digits are not truncated if the number of digits in an argument exceeds that defined in the precision field If the number of digits in the argument is less than the precision field the output value is padded on the left with zeros The precision field is where you specify the number of digits to the right of the mikroC PRO for PIC32 Initial release r n v Description rn Simple demonstration on usage of the PrintOut function r n Test configuration rn CU PIC32MX460F512L r n Dev Board LV 32MX v6 r n Oscillator HS 10 3 MHz r n Ext Modules None r n SW mikroC PRO for PICs r n NOTES r n one r n r n Get _Fosc_kHz 1000 645 MikroElektronika mikoC PRO for PIC32 Setjmp Library The Setjmp library contains functions and types defi
57. transmit buffer the text string replied by this request can be interpreted as javascript statements by browsers len putConstString httpHeader HTTP header len putConstString httpMimeTypeScript with text MIME type 461 MikroElektronika mikoC PRO for PIC32 add ANO value to reply WordToStr ADC1 Get Sample 0 dyna len putConstString var ANO len putString dyna len putConstString add AN1 value to reply WordToStr ADCl Get Sample 1 dyna len putConstString var AN1 len putString dyna len putConstString add PORTB value buttons to reply len putConstString var PORTB WordToStr PORTB dyna len putString dyna len putConstString add PORTD value LEDs to reply len putConstString var PORTD WordToStr PORTD dyna len putString dyna len putConstString add HTTP requests counter to reply WordToStr httpCounter dyna len putConstString var REQ len putString dyna len putConstString else if getRequest 5 t if request path name starts with t toggle PORTD LED bit number that comes after unsigned long bitMask 0 for bit mask if isdigit getRequest 6 if 0 lt bit number lt 9 bits 8 amp 9 does not exist but does not matter bitMask getRequest 6 0 convert ASCII to integer bit
58. 670 671 671 672 673 673 673 673 673 673 674 674 674 675 675 676 677 677 677 678 678 679 679 679 What are differences between mikroC PRO mikroPascal PRO and mikroC PRO compilers Why do they have different prices 679 Why do your PIC compilers don t support 12F508 and some similar chips 679 What are limitations of demo versions of mikroElektronika s compilers 679 Why do still get demo limit error when purchased and installed license key 679 have bought license for the older version do have to pay license for the new version of the com piler 680 Do your compilers work on Windows Vista Windows 7 680 What does this function procedure routine do 680 try to compile one of the provided examples and nothing happens what is the problem 680 Can get your library sources need to provide all sources with my project 680 Can use code developed in your compilers in commercial purposes Are there some limitations Why does an example provided with your compilers doesn t work 680 680 Your example works if use the same MCU you did but how to make it work for another MCU 680 need this project finished can you help me 681 Do you have some discount on your compilers development systems for students professors 681 have a question about your compilers which is not listed here Where can I find an answer 681 MikroElektronika 28 mikroC PRO for PIC32
59. 9 Lcd Init 9 Lcd Cmd LCD CLEAR Led Cmd LCD CURSOR OFF 30 for i 1 i lt 17 i Lcd Chr i i text i 1 Watch Values I3 E Eh Eh 90 oe er amp Ez A qu a Add Remove Properties bg AddAll k Remove All Select variable from list text Search for variable by assembly name _text 4 4 Peripherals Freeze Name Value Address text d 0x0800 PC 0x000280 0 00 us 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 void main t ADPCFG OxFFFF Lcd Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF LJ o for i 1 i lt 17 i Lcd Chr i i text i 1 Watch Values I3 Eh sh 5h 0 oo op amp FE fu a Add 36 Remove Properties iy AddAll k RemoveAll Select variable from list text X Search for variable by assembly name _text Ci V Peripherals Freeze Name Value gj text irri 0x0800 PC 0x000254 0 00 us 119 MikroElektronika mikoC PRO for PIC32 Step Into F7 Step Over F8 and Step Out Ctrl F8 are mikrolCD debugger functions that are used in stepping mode There is also a Real Time mode supported by the mikrolCD Functions that are used in the Real
60. Both expressions have to be of type pointer to qualified or unqualified versions of compatible types The resulting type is a pointer to a type qualified with all type qualifiers of the types pointed to by both expressions 5 One expression is a pointer and the other is a null pointer constant The resulting type is a pointer to a type qualified with all type qualifiers of the types pointed to by both expressions 6 One expression is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void The resulting type is that of the non pointer to vo i d expression 243 MikroElektronika 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 expressionl expression2 The expression1isanobject memory location to which the value of expression2isassigned Operand expressioni has to be Ivalue and expression2 can be any expression The assignment expression itself is not lvalue If expressionl and expression are of different types the result of the expression2 will be converted to the type of expressionl if necessary Refer to Type Conversions for more information Compound Assignment Operators C allows more comlex assignments by means of compound assignment oper
61. Cancel New Project Wizard Select the device you want to use Device Name P32MX460F512L Cancel MikroElektronika 658 mikroC PRO for PIC32 Step Two Enter the oscillator frequency value New Project Wizard Setup the clock for example 11 0592 MHz Device Clock 10 000000 Cancel Step Three Specify the location where your project will be saved New Project Wizard Step 3 6 Specify where your project will be saved Project File Name C Hello World Hello World mcp32 Cancel 659 MikroElektronika mikoC PRO for PIC32 Step Four Add project file to the project if they are avaiable at this point You can always add project files later using Project Manager New Project Wizard Add project files if they are available at this point You can always add project files later using the Project Manager in IDE Add File To Project C Projects Hello World h File Name C Projects Hello World h Remove Remove All Cancel Step Five Select inital Library Manager state New Project Wizard Step 5 6 Select initial Library Manager state Include Libraries Include all Default Include None Advanced Selecting all libraries is recommended for beginners Selecting libraries manually using Library Manager recommended For advanced users results in Faster compilation Libary Manager Help Next gt MikroElektronika mikroC
62. Cf Fat Get File Date Modified 299 Cf Fat Get File Size 300 Cf Fat Get Swap File 300 Library Example 302 HW Connection 306 Epson S1D13700 Graphic Lcd Library 307 External dependencies of the Epson S1D13700 Graphic Lcd Library 307 Library Routines 308 S1D13700 Init 309 S1D13700 Write Command 310 S1D13700 Write Parameter 311 S1D13700 Read Parameter 311 S1D13700 Fill 311 S1D13700 GrFill 312 13 MikroElektronika mikoC PRO for PIC32 S1D13700 TxtFill 312 S1D13700 Display GrLayer 312 S1D13700 Display TxtLayer 313 S1D13700 Set Cursor 313 S1D13700 Display Cursor 314 S1D13700 Write Char 314 S1D13700 Write Text 315 S1D13700 Dot 315 S1D13700 Line 316 S1D13700 H Line 316 S1D13700 V Line 317 S1D13700 Rectangle 317 S1D13700 Box 318 S1D13700 Rectangle Round Edges 318 S1D13700 Rectangle Round Edges Fill 319 S1D13700 Circle 319 S1D13700 Circle Fill 320 S1D13700 Image 320 S1D13700 Partiallmage 321 Flash Memory Library 322 Library Routines 322 Flash Write Word 323 Flash Write Row 323 Flash Erase Page 323 Graphic Lcd Library 324 Library Dependency Tree 324 External dependencies of Graphic Lcd Library 325 Glcd Init 326 Glcd Set Side 328 Glcd Set X 328 Glcd Set Page 328 Glcd Read Data 329 Glcd Write Data 329 Glcd Fill 330 Glcd Dot 330 Glcd Line 330 Glcd V Line 331 Glcd H Line 331 Glcd Rectangle 332 Glcd Rectangle Round Edges 332 Glcd Rectangle Round Edges Fill 333 Glcd Box 333 Glcd Circle 334 Glcd Circle Fill 334 Glcd Set
63. End CANSPI module connections void main CHECON 0x32 ADIPCFG OxFFFF PORTB 0 TRISB 0 Can Init Flags 0 Can Send Flags 0 Can Rcv Flags 0 Can Send Flags CANSPI TX PRIORITY 0 amp CANSPI TX XTD FRAME amp CANSPI TX NO RTR FRAME Can Init Flags CANSPI CONFIG SAMPLE THRICE amp CANSPI CONFIG PHSEG2 PRG ON amp CANSPI CONFIG XTD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG Initialize SPI2 module SPI2 Init CANSPIInitialize 1 3 3 3 1 CANSPISetOperationMode CANSPI MODE CONFIG OxFF CANSPI MASK B1 1 CANSPISetMask Can Init Flags n CANSPI CONFIG XTD MSG can flags received data length in can rx tx data buffer reception flag node IDs configure AN u A er 2 al CANSPISetMask CANSPI MASK B2 1 CANSPISetFilter CANSPI FILTI filter B2 F4 to 2nd node ID pins as digital I O clear PORTB set PORTB as output clear flags form with form with value to be used CANSPIWrite value to be used CANSPIInit initialize external CANSPI module set CONFIGURATION mode set all maski bits to ones CANSPI CONFIG XTD MSG set all mask2 bits to ones ER B2 F4 ID 2nd CANSPI CONFIG XTD MSG set id of 283 MikroElektronika mikoC PRO for PIC32 CANSPISetOperationMode CANS
64. Expander Write PortA 0 i Write i to expander s PORTA PORTB Expander Read PortB 0 Read expander s PORTB and write it to LEDs Delay ms 75 MikroElektronika 394 mikroC PRO for PIC32 HW Connection Port Expander HW connection 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 pressing the Caps Lock key will not turn on the Caps Lock LED External dependencies of PS 2 Library The following variables must be defined in all projects using PS 2 Library sei o mamie o extern sfr sbit PS2 Data PS 2 Data line sbit PS2 Data at RBO bit extern sfr sbit PS2 Clock PS 2 Clock line sbit PS2 Clock at RBI bit extern sfr sbit PS2 Data sbit PS2 Data Direction at TRISBO p Direction of the PS 2 Data pin i F Direction bot extern sfr sbit PS2 Clock i sbit PS2 Clock Direction at TRISB1 Direction of the PS 2 Clock pin So DIEM Direction bit Library Routines Ps2 Config Ps2 Key Read MikroElektronika 396 mikroC PRO for PIC32
65. Here is one commonly used directive include lt math h gt MikroElektronika 296 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 dif define ifdef elif ifndef else include endif line error undef Note For the time being only funcall pragma is supported Line Continuation with Backslash To break directive into multiple lines end the line with a backslash define MACRO This directive continues to the following line Macros Macros provide a mechanism for a token replacement prior to compilation with or without a set of formal function like parameters Defining Macros and Macro Expansions The define directive defines a macro define macro identifier token sequence Each occurrence of macro identifier in the source code following this control line will be replaced in the original position with the possibly empty token sequence there are some exceptions which are discussed later Such replacements are known as macro expansions token sequence is sometimes called the body of a macro An empty token sequence results in the removal of each affected macro identifier from the source code No semicolon is needed to terminate a preprocessor directive Any character found in the token sequence including semicolons will appear in a ma
66. Idexp 613 log 613 log10 613 modf 613 pow 613 sin 614 sinh 614 sqrt 614 tan 614 tanh 614 ANSI C Stdlib Library 615 Library Dependency Tree 615 Library Functions 615 abs 615 atof 616 atoi 616 atol 616 div 616 Idiv 617 uldiv 617 labs 617 max 617 min 618 rand 618 srand 618 xtoi 618 Div Structures 619 ANSI C String Library 620 Library Functions 620 memchr 620 memcmp 621 memcpy 621 memmove 621 memset 622 strcat 622 MikroElektronika 29 mikoC PRO for PIC32 strchr 622 strcmp 623 strcpy 623 strlen 623 strncat 624 strncpy 624 strspn 624 strncmp 625 strstr 625 strcspn 625 strpbrk 626 strrchr 626 strtok 627 Miscellaneous Libraries 628 Button Library 628 Library Routines 628 Button 628 Conversions Library 630 Library Dependency Tree 630 Library Routines 630 ByteToStr 631 ShortToStr 631 WordToStr 632 IntToStr 632 LongToStr 633 LongWordToStr 633 FloatToStr 634 WordToStrWithZeros 634 IntToStrWithZeros 635 LongWordToStrWithZeros 635 LongIntToStrWithZeros 636 ByteToHex 636 ShortToHex 637 WordToHex 637 IntToHex 638 LongWordToHex 638 LongIntToHex 639 Dec2Bcd 639 Bcd2Dec 640 Dec2Bcd16 640 Bcd2Dec16 640 Rtrim 641 Ltrim 641 PrintOut Library 642 Library Dependency Tree 642 Library Routines 642 MikroElektronika 26 mikroC PRO for PIC32 PrintOut 642 Setjmp Library 646 Library Routines 646 Setjmp 646 Longjmp 647 Library Example 647 Sprint Library 649 Library Dependency Tree 649 Function
67. Nt tab HT TAB same as x09 n newline NL same as x0a Vr car return CR same as x0d form feed FF same as x0c a alarm bell BEL same as x07 ve escape ESC same as x1b Examples unsigned x20int matches unsigned int note space in the middle tunsigned matches unsigned predecessed by tab Character classes You can specify a character class by enclosing a list of characters in which will match any of the characters from the list If the first character after the is the class matches any character not in the list 107 MikroElektronika 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 If you want you may place it at the start of list or precede it with a backslash Examples az matches a z and az matches a z and a z matches a z and a z matches all twenty six small characters from a to z n x0D matches any of 10 11 12 13 d t matches any digit or t 1 a matches any char f
68. Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library SPIx Write Requires Routine requires at least one SPI module Used SPI module must be initialized before using this function See the SPIx Init and SPlx Init Advanced routines write a byte to the SPI bus char buffer SPI1 Write buffer SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 437 MikroElektronika mikoC PRO for PIC32 SPI Set Active Prototype void SPI Set Active unsigned read ptr unsigned void write ptr unsigned Description Sets the active SPI module which will be used by the SPIx Read and SPIx Write routines Parameters Parameters read ptr SPI1 Read handler write ptr SPI1 Write handler Requires Routine is available only for MCUs with multiple SPI modules Used SPI module must be initialized before using this function See the SPIx Init and SPIx_Init_ Advanced routines SPI Set Active SPIl1 Read SPI1 Write Sets the SPI1 module active Number of SPI modules per MCU differs from ar to chip Please read the appropriate datasheet before utilizing this library Library Example
69. See Mmc Fat Assign delete current file Mmc Fat Delete None 313 MikroElektronika mikoC PRO for PIC32 Mmc Fat Write Prototype void Mmc Fat Write char fdata unsigned data len 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 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 See Mmc Fat Rewrite or Mmc Fat Append char file contents 42 Mme Fat_Write file_contents 42 write data to the assigned file Mmc_Fat_Set_File_Date Prototype void Mmc Fat Set File Date unsigned int year unsigned short day unsigned short hours unsigned short mins unsigned short seconds Description Sets the date time stamp Any subsequent file write operation will write this stamp to the currently assigned file s time date attributes Parameters year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 da y day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds seconds attribute Valid values 0 59 Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned
70. The code demonstrates how to use SPI library functions for communication between SPI2 module of the MCU and MCP4921 DAC chip Copy Code To Clipboard DAC module connections sbit Chip Select at LATFO bit sbit Chip Select Direction at TRISFO bit End DAC module connections unsigned int value void InitMain TRISBO bit 1 Set RBO pin as input TRISB1 bit 1 Set RB1 pin as input Chip Select 1 Deselect DAC Chip Select Direction 0 Set CS pin as Output SPI2 Init Initialize SPI2 module DAC increments 0 4095 gt output voltage 0 Vref void DAC Output unsigned int valueDAC char temp Chip Select 0 Select DAC chip Send High Byte temp valueDAC gt gt 8 amp OxOF Store valueDAC 11 8 to temp 3 0 temp 0x30 Define DAC setting see MCP4921 datasheet SPI2 Write temp Send high byte via SPI MikroElektronika 438 mikroC PRO for PIC32 Send Low Byte temp valueDAC Store valueDAC 7 0 to temp 7 0 SPI2 Write temp Send low byte via SPI Chip Select 1 Deselect DAC chip void main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital InitMain Perform main initialization value 2048 When program starts DAC gives the output in the mid range while 1 Endless loop if RBO bit amp amp value lt 4095 If RBO button is pressed value wf increment value
71. and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a prne es between dots 10 20 and 50 20 SPI Gled H Line t 205 LJ SPI Glcd Rectangle Prototype void SPI Glcd Rectangle char x upper left char y upper left char x bottom right char y bottom right char color Draws a rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 SPI Glcd Rectangle 5 5 40 40 1 MikroElektronika 490 mikroC PRO for PIC32 SPI Glcd Rectangle Round Edges Prototype void SPI Glcd Rectangle Round Edges 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 rounded edge rectangle on Glcd Parameters x upper left x coordinate of the u
72. ifi Binaries Project level defines 7j Image Files EEPROM Files Active Comments Files S Output Files 25 Led hex z Lcd asm Other Files Aabeue w 32a 044 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 Code editor The Code Editor is advanced text editor fashioned to satisfy needs of professionals Tools The mikroC PRO for PIC32 includes the Tools tab which enables the use of shortcuts to external programs like Calculator or Notepad You can set up to 10 different shortcuts by editing ToolO Tool9 85 MikroElektronika mikoC PRO for PIC32 Options Tools Tool Name Notepad File Name C WINDOWS NOTEPAD EXE A Parameters Macro s HEX FILE NAME Ful path and name of the out x Insert Shortcut F11 3 Clear all fields C Close when finished Output 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
73. maximum m The form n is equivalent to n n and matches exactly n times The form n matches n or more times There is no limit to the size of n or m but large numbers will chew up more memory and slow down execution If a curly bracket occurs in any other context it is treated as a regular character 109 MikroElektronika mikoC PRO for PIC32 Examples count r B matches strings like counter countelkjdflkj9r and countr count 4r 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 counte 2 3 r matches strings like counteer or counteeer but not counteeeer A little explanation about greediness Greedy takes as many as possible non greedy takes as few as possible For example b and b applied to string abbbbc return bbbb b returns b b returns empty string b 2 3 returns bb b 2 3 returns bbb Metacharacters Alternatives You can specify a series of alternatives for a pattern using to separate them so that bit bat bot will match any of bit bat or bot in the target string as would b i a o t The first alternative includes everything from the last pattern delimiter or the beginning of the pattern up to the first a
74. output End of RS485 module pinout UART1 Init 9600 initialize UART1 module RS485Slave Init 160 intialize MCU as a Slave for RS 485 communication with address 160 MikroElektronika 408 mikroC PRO for PIC32 RS485Slave Receive 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 2 message content data buffer 3 number of message bytes received 1 3 data buffer 4 is setto 255 when message is received data buffer 5 is setto 255 if error has occurred The routine automatically adjusts data 4 and data 5 upon every received message These flags need to be cleared by software MCU must be initialized as a Slave for RS 485 communication See RS485Slave Init char msg 8 RS485Slave Read msg RS485Slave Send Prototype void RS485Slave Send char data buffer char datalen Sends message to Master Message format can be found at the bottom of this page Parameters data buffer data to be sent datalen number of bytes for transmition Valid values O 3 Nothing Requires MCU must be initialized as a Slave for RS 485 communication See RS485Slave Init It is the user s responsibility to ensure by protocol that onl
75. output destination string Destination string should be at least 4 characters in length unsigned short t char txt 4 ByteToStr t txt ZZ txt is 24 one blank here ShortToStr Prototype void ShortToStr short input char output Description Converts input signed short number to a string The output string has fixed width of 5 characters including null character at the end string termination The output string is right justified and remaining positions on the left if any are filled with blanks Parameters input signed short number to be converted output destination string Destination string should be at least 5 characters in length short t 24 char txt 5 ShortToStr t txt 7 txt is 24 one blank here mikoC PRO for PIC32 WordToStr Prototype void WordToStr unsigned input char output Description Converts input word to a string The output string has fixed width of 6 characters including null character at the end string termination The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters input word to be converted output destination string Nothing Destination string should be at least 6 characters in length unsigned t 437 char txt 6 WordToStr t txt txt is 4437 two blanks here IntToStr Prototype void IntToStr int input char output Description Converts inpu
76. pm i 3 tmp mu i OK mu i 3 The third line is legal since mu i is an integral type However the bit pattern in mu i corresponds to parts of the previously assigned double As such it probably won t provide an useful integer interpretation When properly converted a pointer to a union points to each of its members and vice versa MikroElektronika 216 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 In addition to the restrictions listed above in Union anonymous unions are subject to additional restrictions They must also be declared as static if declared in global scope If declared in local scope they must be either static or automatic not external They can have only public members private and protected members in anonymous unions generate errors They cannot have function members Here is a simple example union no union tag int 2 float f union no union tag unsigned char uc char c im no declarator h no declarator Anonymous Union Member Access Anonymous un
77. then remote host port number WordToStr remotePort dyna 16 dyna 21 WordToStr destPort dyna 22 dyna 27 J dyna 28 0 my reply length human readable format first IP address byte second third fourth add separator the total length of the request is the length of the dynamic string plus the text of the request len 28 reqLength puts the dynamic string into the transmit buffer SPI Ethernet putBytes dyna 28 then puts the request string converted into upper char into the transmit buffer while reqhength SPI Ethernet putByte toupper SPI Ethernet return len getByte back to the library with the length of the UDP reply 463 MikroElektronika mikoC PRO for PIC32 main entry Wy void main aa 0x32 ADIPCFG OxFFFC all digital but rb0 ANO and rb1 AN1 PORTB 0 TRISB OxFFFF set PORTB as input for buttons and adc PORTD 0 TRISD 0 set PORTD as output ADC1_Init Enable ADC module starts ENC28J60 with reset bit on RCO CS but on REL my MAC amp IP address full duplex WE if SPTI Inite init SPI communication with ethernet board SPI2 Init Advanced SPI MASTER SPI 8 BIT 16 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI IDLE 2 ACTIVE SPI Ethernet Init myMacAddr myIpAddr Spi Ethernet FULLDUPLEX init
78. void SPI Ethernet 243600 confNetwork char ipMask char gwIpAddr char dnsIpAddr Configures network parameters IP subnet mask gateway IP address DNS IP address when DHCP is not used ipMask IP subnet mask gwl pAddr gateway IP address dnsIpAddr DNS IP address Nothing Ethernet module has to be initialized See SPI Ethernet 24j600 Init char ipMask 4 255 255 255 TL network mask for example 255 255 255 0 char gwIpAddr 4 192 168 1 gateway router IP address char dnsIpAddr 4 192 168 M DNS server IP address SPI Ethernet 243600 confNetwork ipMask gwIpAddr dnsIpAddr set network configuration parameters The above mentioned network parameters should be set by this routine only if DHCP module is not used Otherwise DHCP will override these settings 419 MikroElektronika mikoC PRO for PIC32 SPI Ethernet 24j600 arpResolve 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 Prototype unsigned char SPI Ethernet 243600 arpResolve unsigned char ip unsigned cash can store up to 3 entries For ARP cash structure refer to EthEnc24j600 h header file in the compiler s Uses folder Parameters i IP address to be resolved tmax time in seconds to wait for an reply
79. 1 3 3 7 58 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 inb ip str char ip More generally the cast type will convert a pointer to type pointer to type Explicit Types Conversions Typecasting In most situations compiler will provide an automatic implicit conversion of types where needed without any user s interference Also the user can explicitly convert an operand to another type using the prefix unary typecast operator type object This will convert object to a specified type Parentheses are mandatory For example Let s have two variables of char type char a b Following line will coerce a to unsigned int unsigned int a Following line will coerce a to double then coerce b to double automatically resulting in double type value double a b equivalent to double a b 221 MikroElektronika 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 The range of objects that can be declared includes Variables Constants Functions Type
80. 2 non blinking cursor SPI T6963C cursor 1 SPI T6963C cursor blink 0 break Delay ms 300 ifdef PARTIAL IMAGE DEMO If RB13 is pressed perform the Partial image demostration else if RB13 bit PI T6963C_setGrPanel 0 PI T6963C setTxtPanel PI T6963C txtFill 0 PI T6963C setGrPanel 1 0 PI T6963C setTxtPanel 0 PI T6963C graphics 1 PI T6963C text 1 PI T6963C displayGrPanel 1 PI T6963C write text txt2 5 15 SPI T6963C ROM MODE XOR elay 1sec PI T6963C grFill 0 I T6963C Partiallmage 0 0 64 64 240 128 mikroE 240x128 bmp elay 1sec PI T6963C Partiallmage 0 0 128 128 240 128 mikroE 240x128 bmp U elay_1sec PI T6963C Partiallmage 0 0 240 128 240 128 mikroE 240x128 bmp lay 1sec PI T6963C txtFill 0 PI T6963C write text txt 0 0 SPI T6963C ROM MODE XOR PI T6963C write text txtl 0 15 SPI T6963C ROM MODE XOR oO ANNDNDHNDHNHNDONHNHNnNNNNNnNNNN fendif ge Move cursor even if not visible T Cposxtt if cposx SPI T6963C txtCols cposx 0 cposytt if cposy SPI T6963C grHeight SPI T6963C CHARACTER HEIGHT cposy 0 SPI T6963C set cursor cposx cposy Delay ms 100 MikroElektronika 534 mikroC PRO for PIC32 HW Connection T PIC32MX460F512L B Adjustment
81. 2FFFFO B7A2A8 O7FFID 2000C0 781F80 O7FF4F O lt ETX gt lt STX gt ay B1002F 208610 781F80 200060 781F80 200010 781F80 07FF87 DLE t lt SPC gt lt BI006F 208690 781F80 200060 781F80 200020 781F80 O7FF7F 0 40 t lt SPC gt lt US gt B1006F 200CC8 273987 ED200E 3AFFFE ED2010 3AFFFC 200010 o amp lt FF gt lt SPC gt 9 781F80 07FF35 BIO02F 208700 781F80 200010 761F80 200010 U5 x5 BELL 781F80 O7FF6D B1006F 208810 781F80 200050 781F80 200020 US xmj BELL 0 gt STATUS Idle 133 MikroElektronika mikoC PRO for PIC32 Software Simulator Debugger Options Debugger Options ee Function Toolbar Description Key Icon Executes the current program line then halts If the executed Step Into program line calls another routine the debugger steps into the F7 DO routine and halts after executing the first instruction within it Executes the current program line then halts If the executed program line calls another routine the debugger will not step into it The whole routine will be executed and the debugger halts at the first instruction following the call Step dut Executes all remaining program lines within the subroutine The F8 o9 debugger halts immediately upon exiting the subroutine mnl Run To Cursor Executes the program until reaching the cursor position Ctrl F8 zm Vad ke meudieddiuk Toggle breakpoi
82. 3 xtern sfr sbit TFT i exte E t Direction of the Chip Select TFT CS Direction at TRISC3 bit Direction pin ET 7 f bi mpm i extern sfr sbit Direction of the Register Select TFT RS Direction at TRISB13 bit Direction pin S extern sfr sbit TFT RST 3 Direction of the Reset pin TFT RST Direction at TRISC1 bit Direction Ez 561 MikroElektronika mikoC PRO for PIC32 Library Routines TFT Init TFT Set Index TFT Write Command TFT Write Data TFT Set Active TFT Set Font TFT Write Char TFT Write Text TFT Fill Screen TFT Set Pen TFT Set Brush TFT Dot TFT Line TFT H Line TFT V Line TFT Rectangle TFT Rectangle Round Edges TFT Circle TFT Image TFT Partiallmage TFT Image Jpeg TFT RGBToColor16bit TFT Color16bitTORGB MikroElektronika 962 mikroC PRO for PIC32 TFT Init Prototype void TFT Init unsigned int display width unsigned char display height Nothing Description Initializes TFT display in the 8 bit working mode Parameters width width of the TFT panel height height of the TFT panel Requires Global variables DataPort Data Port r WR Write signal pin r RD Read signal pin r CS Chip Select signal pin r RS Register Select signal pin l RST Reset signal pin DataPort Direction Direction of Data Port WR Direction Direction of Write signal pin RD Direction Directi
83. 4 10 4 year day amp 0xC0 gt gt 6 day day amp 0x30 gt gt 4 10 month month amp 0x10 gt gt 4 10 B Re SSH SSS SSses Output values to LCD void Display Time Lcd Chr 1 6 day 10 48 Lcd Chr 1 7 day 10 48 Lcd Chr 1 9 month 10 48 Lcd Chr 1 10 month 10 48 Lcd Chr 1 15 year 49 Lcd Chr 2 6 hours 10 48 Lcd Chr 2 7 hours 10 t 48 Lcd Chr 2 9 minutes 10 48 Lcd Chr 2 10 minutes 10 48 Lcd Chr 2 12 seconds 10 48 Lcd Chr 2 13 seconds 10 48 void Init Main CHECON 0x30 AD1PCFG OxFFFF Soft I2C Init Initialize AN pins as digital UE Tf Tf rd Za Initialize Soft I2C communication Performs project wide init Initialize LCD Clear LCD display Turn cursor off nA TA na 77 Transform Transform Transform Transform Transform Transform Prepare and output static text on LCD Lcd Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF Lcd Out 1 1 Date Led Chr 1 8 2 Lcd Chr 1 11 Lcd Out 2 1 Time Led Chr 2 8 2 Led Chr 2 1L z Lcd Out 1 12 201 Vg Sa Se Sear e eee Main procedure void main Delay ms 100 Init Main while 1 Read Time Transform Time Display Time Delay ms 1000 Tf ZH vf ia a Perform initialization Endless l
84. Clipboard typedef struct unsigned canCloseTCP 1 flag which closes socket unsigned isBroadcast 1 flag which denotes that the IP package has been received via subnet broadcast address TEthPktFlags 0 there should not be a reply to the request Length of TCP reply data field otherwise Ethernet module has to be initialized See SPI Ethernet Init Example This function is internally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply MikroElektronika 450 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 The function must return the length in bytes of the UDP reply or 0 if nothing to transmit If you don t need to reply to the UDP requests just define this function with a return 0 as single statement Parameters remoteHost client s IP address remotePort client s port localPort port to which the request is sent re
85. Direction extern sfr sbit SP RST Direction Ethernet The following routines must be defined in all project using SPI Ethernet Library unsigned int UserTCP unsigned remoteHost remotePort unsigned int localPort unsigned int reqLength TEthPktFlags flags SPI Ethernet char unsigned int unsigned int UserUDP unsigned remoteHost remotePort unsigned int localPort unsigned int reqLength TEthPktFlags flags SPI Ethernet char unsigned int Description ENC28J60 chip select pin ENC28J60 reset pin Direction of the ENC28J60 chip select pin Direction of the ENC28J60 reset pin Description TCP request handler UDP request handler sbit SPI Ethernet CS at LATF1 bit sbit SPI Ethernet Rst at LATFO bit sbit SPI Ethernet CS Direction at TRISFl bit sbit SPI Ethernet Rst Direction at TRISFO bit Refer to the library example at the bottom of this page for code implementation Refer to the library example at the bottom of this page for code implementation MikroElektronika 442 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 g
86. E Related topics Keyboard shortcuts Edit Toolbar Advanced Edit Toolbar 43 MikroElektronika mikoC PRO for PIC32 View View Menu Options View Menu contains commands for controlling the on screen display of the current project Debug Windows gt Toolbars Bookmarks Code Explorer Library Manager Macro Editor Messages Project Manager Shift Ctrl F11 Project Settings Routine List Ctri L Quick Converter Ctri Q View Image Preview a Assembly Listing Statistics Windows MikroElektronika 44 mikroC PRO for PIC32 Show Hide Software Simulator mikroICD In Circuit Debugger Debug Windows rcc acc a rc acc Eo cum The Tools toolbar can easily be customized by adding new tools in Options F12 window Related topics Keyboard shortcuts Integrated Tools 45 MikroElektronika mikoC PRO for PIC32 Project Project Menu Options Project Menu allows the user to easily manipulate current project New Project Shift Ctrl N Open Project Shift Ctrl O Open Project Group Recent Projects gt Save Project EA Save Project As Close Project Close Project Group Add File To Project f Remove File From Project Edit Search Paths Edit Project Shift Ctrl E Clean Project Folder Import Project Ctrl I A Mg Gius Project Ctri Alt E
87. Font 335 Glcd Write Char 336 Glcd Write Text 336 MikroElektronika 1 mikroC PRO for PIC32 Glcd Image 337 Glcd Partiallmage 337 lC Library 338 Library Routines 338 I2Cx Init 338 I2Cx Init Advanced 339 I2Cx Start 339 I2Cx Restart 340 I2Cx Is Idle 340 I2Cx Read 341 I2Cx Write 341 I2Cx Stop 342 Library Example 342 Keypad Library 344 External dependencies of Keypad Library 344 Library Routines 344 Keypad Init 344 Keypad Key Press 345 Keypad Key Click 345 Library Example 346 HW Connection 347 Lcd Library 348 Library Dependency Tree 348 Keypad Key Click 348 Library Routines 348 Lcd Init 349 Lcd Out 350 Lcd Out Cp 350 Lcd Chr 350 Lcd Chr Cp 351 Lcd Cmd 351 Available Lcd Commands 351 Library Example 352 Manchester Code Library 354 External dependencies of Manchester Code Library 354 Library Routines 355 Man Receive Init 355 Man Receive 356 Man Send Init 356 Man Send 357 Man Synchro 357 Man Break 358 Library Example 359 Connection Example 361 Memory Manager Library 362 Library Routines 362 15 MikroElektronika mikoC PRO for PIC32 Heap Init 362 malloc 362 free 363 LargestFreeMemBlock 363 TotalFreeMemSize 363 Multi Media Card Library 364 Secure Digital Card 364 Secure Digital High Capacity Card 364 Library Dependency Tree 365 External dependencies of MMC Library 365 Library Routines 365 Mmc Init 366 Mmc Read Sector 367 Mmc Write Sector 367 Mmc Read Cid 368 Mmc Read Csd 368 Mmoc Fat Init 369
88. G t 408010 784010 FB8000 781F80 07FF32 B1002F 200011 470060 DLE Q DLE Qx 408810 37FFEF 2088CO0 AD0010 FASO00 060000 FAO002 EF2000 DLE G i97 A SPC 984700 90400E E10468 310009 2001CO0 781F80 07FF78 B1002F G SO Dh EOT 07FF31 B3C011 470060 40C810 37FFF4 Fasooo 060000 FAO002 1j BELL lt DC1 gt A EF2000 984700 90400E E10468 310009 200180 781F80 07FF67 SPC i G SO C B1002F 07FF20 B3C011 470060 40C810 37FFF4 FA8000 060000 SPC j BELL E 2088EF 20FFFO B7A020 200000 B7A034 200040 B72044 FA0000 i SPC 8y SPC SF 0203D8 000000 ZFFFF B7A2A8 O7FF1D 2000C0 781F80 O7FF4F lt ETX gt lt STX gt 8 y B1002F 208610 781F80 200060 781F80 200010 781F80 07FF87 DLE f SPC lt B1006F 208690 781F80 200060 781F80 200020 781F80 O7FF7F ot O f SPC US B1006F 200CC8 273987 ED200E 3AFFFE ED2010 3AFFFC 200010 o amp FF SPCo t9 781F80 07FF35 B1002F 208700 781F80 200010 781F80 200010 lt US gt x 5 y BELL 781F80 O7FF D BIOD F 208810 781F80 200050 781F80 200020 US xmj BELL o gt STATUS Idle E MikroElektronika 126 mikroC PRO for PIC32 CHAPTER o Software Simulator Overview 121 MikroElektronika mikoC PRO for PIC32 Software Simulator The Source level Software Simulator is
89. If an expression evaluates to be true it returns 1 otherwise it returns 0 All relational operators associate from left to right Relational Operators Overview ma p f mtema 9 gt greater than or equal lt less than or equal Relational Operators in Expressions Precedence of arithmetic and relational operators is designated in such a way to allow complex expressions without parentheses to have expected meaning at t5 gt cec 1 0 e a 5 s c 1120 7 e F7 Do not forget that relational operators return either 0 or 1 Consider the following examples ees 7 57 returns 0 10 lt 20 returns 1 this can be tricky 8 13 gt 5 returns 0 as 13 gt 5 gt 8 21 5o 0 WA SS bh 3 returns 1 ass 14 gt 5 lt 3 2 lt 3 2 7 a lt b lt 5 returns 1 as a lt b lt 5 0 or 1 lt 5 1 7 239 MikroElektronika 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 Bitwise Operators Overview amp bitwise AND compares pairs of bits and returns 1 if both bits are 1 otherwise returns 0 bitwise inclusive OR compares pairs of bits and returns 1 if either or both bits are 1 otherwise returns 0 bitwise exclusive OR XOR compar
90. Init Advanced SPIx Read SPIx Write SPI Set Active 433 MikroElektronika mikoC PRO for PIC32 SPIx Init Pipoitype 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 MCU must have the SPI1 module Initialize the SPI1 module with default settings SPII Triit SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Switching between the SPI modules in the SPI library is done by the SPI Set Active function both SPI modules have to be previously initialized MikroElektronika 434 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 Configures and initializes the SPI module with user defined settings Parameters Parameters master mode data mode c
91. Library 265 MikroElektronika 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 MikroElektronika 266 mikroC PRO for PIC32 Hardware Libraries ADC Library CANSPI Library Compact Flash Library Epson S1D13700 Graphic Lcd Library Flash Memory Library Graphic Lcd Library PC 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 C Library Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Ethernet ENC24J600 Library SPI Graphic Lcd Library SPI Lcd Library SPI Lcd8 Library SPI T6963C Graphic Lcd Library T6963C Graphic Lcd Library TFT Display Library Touch Panel Library Touch Panel TFT Library UART Library USB Library ADC Library ADC Analog to Digital Converter module is available with a number of PIC32 MCU modules ADC is an electronic circuit that converts continuous signals to discrete digital numbers ADC Library provides you a comfortable w
92. Link Files ml C Open as read only My Network If you click No comment will be removed from the source code Renaming Active Comment When you click on rename button you will be prompted to enter new name Active Comments Editor Select Active Comment activeComment Active Comment Actions New Rename Enter new Active Comment Name ictive CommentRename Rename Properties a Attributes Url ww mikroe com Image Easy_GSM_GPRS jpg File None Events OnLeftClick Alt OpenUrl OnRightClick None OnDbiClick None OnMouseOver X PreviewImage Add Image To Project Add File To Project MikroElektronika 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 I V ac activeCommentRename 30 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 MikroElektronika 104 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 fo
93. MANTXPIN r ils sbit MANTXPIN Direction at TRISF1 Direction of the Transmit pin Direction bait MikroElektronika 354 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 0 if initialization and synchronization were successful 1 upon unsuccessful synchronization 255 upon user abort Requires Global variables MANRXPIN Receive line MANRXPIN Direction Direction of the receive pin must be defined before using this function Initialize Receiver sbit MANRXPIN at RFO bitz sbit MANRXPIN Direction at TRISFOs bit if Man Receive Init In case of multiple persistent errors on reception the user should call this routine once again or Man_Synchro routine to enable synchronization 399 MikroElektronika mikoC PRO for PIC32 Man Receive Prototype unsigned char Man Receive unsigned int error The function extracts one byte from incoming signal Parameters error error flag If signal format does not match th
94. MHz N C NLcdNLod mcp32 SP C NProgram Files Mikroelektronika mikroC PRO for PIC32XDefs Output files generated to file path specified by filename SP C Program Files Mikroelektronika mikroC PRO for PIC32 Defs Add directory to the search path list SP C Program Files Mikroelektronika mikroC PRO for PIC32NUses V Add directory to the search path list SP C Lced Add directory to the search path list Lcd c Lib Math emcl Lib MathDouble emcl Lib System emcl Lib Delays emcl Lib LcdConsts emcl Lib Lcd emcl Specify input files MikroElektronika 114 mikroC PRO for PIC32 CHAPTER 4 Introduction The mikrolCD is a highly effective tool for a Real Time debugging on hardware level The mikrolCD 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 115 MikroElektronika mikoC PRO for PIC32 Se 1 C C If you have appropriate hardware and software for using the mikrolCD select mikrolCD Debug Build Type before compiling the project Project Settings Choose ICD Debug type if you want to use mikroICD debug Build Type O Release ICD Debug Debugger Q Software mikroIcD i i Now compile the project by pressing Ctrl F9 or by pressing Build Icon on Bu
95. Mmc Fat QuickFormat 370 Mmc Fat Assign 371 Mmc Fat Reset 372 Mmc Fat Read 372 Mmc Fat Rewrite 373 Mmc Fat Append 373 Mmc Fat Delete 373 Mmc Fat Write 374 Mmc Fat Set File Date 374 Mmc Fat Get File Date 375 Mmc Fat Get File Date Modified 376 Mmc Fat Get File Size 376 Mmc Fat Get Swap File 377 Library Example 378 HW Connection 382 OneWire Library 383 Library Routines 383 Ow Reset 383 Ow Read 384 Ow Write 384 Port Expander Library 385 Library Dependency Tree 385 External dependencies of Port Expander Library 385 Library Routines 385 Expander Init 386 Expander Init Advanced 387 Expander Read Byte 388 Expander Write Byte 388 Expander Read PortA 388 MikroElektronika 16 mikroC PRO for PIC32 Expander Read PortB 389 Expander Read PortAB 389 Expander Write PortA 390 Expander Write PortB 390 Expander Write PortAB 391 Expander Set DirectionPortA 391 Expander Set DirectionPortB 392 Expander Set DirectionPortAB 392 Expander Set PullUpsPortA 392 Expander Set PullUpsPortB 393 Expander Set PullUpsPortAB 393 Library Example 394 HW Connection 395 PS 2 Library 396 External dependencies of PS 2 Library 396 Library Routines 396 Ps2 Config 397 Ps2 Key Read 397 Special Function Keys 398 Library Example 399 HW Connection 400 PWM Library 400 Library Routines 400 PWM Init 401 PWM Init Advanced 401 PWM Set Duty 402 PWM Start 402 PWM Stop 402 Library Example 403 HW Connection 404 RS 485 Library 405 Library Dependency Tree 405 Ext
96. O DI AB 2CA 2088CO A60010 ABO2D6 A70010 A902D6 D7FF7C 2088c0 E lt STX gt SPC D A60010 370002 07FF64 370001 07FF86 FAS000 060000 FAO002 DLE STX 2 dj 37000F 200800 SFBF40 370019 200CO0 SFBF40 370016 200940 SI 7 BS SPC SFBF40 370013 200D40 SFBF40 370010 200800 SFBF40 37000D lt lt DC3 gt 7 lt CR gt 97B84E 10061 S2FFEE 97B84E E10062 32FFEE 97B84E E10063 N a ij2N b 32FFEE 97B84E 10064 32FFEE 37FFFO 97B83E 50001 570068 iy2N d ij28j7 408010 9FBF40 781F80 O7FF9B BIOOZF 2088CO A10010 EF2000 DLE G G t US 980700 97B8AE 470060 408010 E00410 32000C 97B8AE 470060 lt BELL gt G I 408010 784010 FBS000 781F80 O7FF32 B1002F 200011 470060 DLE O DLE Gx 408810 37FFEF 2088C0 A00010 FAG000 060000 FAO002 EF2000 DLE iy7A SPC 984700 90400E E10468 310009 2001C0 781F80 07FF78 B1002F G lt SO gt Oh lt EOT O7FF31 B3CO11 470060 40C810 37FFF4 FA8000 060000 FA0002 ij BELL DCi EF2000 984700 90400E E10468 310009 200180 781F80 07FF67 SPCoi G S0 GL B1002F 07FF20 B3COli 470060 40C810 37FFF4 FAS000 060000 amp SPC j BELL C 2088EF 20FFFO B7A020 200000 B7A034 200040 B72044 FAD000 i SPC j SPC SF O203D8 000000
97. PORTF 4 5 14400 0 Initialize Soft UART at 14400 bps The Software UART library implements time based activities so interrupts need to be disabled when using it 425 MikroElektronika 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 Byte received via UART Requires Software UART must be initialized before using this function See the Soft UART Init routine char data char error wait until data is received do data Soft UART Read amp error while error Now we can work with data if data 1 22 The Software UART library implements time based activities so interrupts need to be disabled when using it Soft_UART_Write ems Mig Requires Software UART must be initialized before using this function See the Soft UART Init routine ui Be aware that during transmission software UART is incapable of receiving data data transfer protocol must be set in such a way to prevent loss of information char some byte 0x0A Write a byte via Soft UART Soft UART Write some byte The Software UA
98. PRESCALE SEC 1 SPI PRESCALE PRI 4 SPI SS DISABLE SPI DATA SA E MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE MMC SD card has to be formatted to FAT16 file system 369 MikroElektronika mikoC PRO for PIC32 Mmc Fat QuickFormat Prototype unsigned int Mmc Fat QuickFormat char mmc fat label 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 If null string is passed volume will not be labeled 0 if MMC SD card was detected successfully formated and initialized 1 if FAT16 format was unseccessful 255 if MMC SD card was not detected The appropriate hardware SPI module must be previously initialized This routine can be used instead or in conjunction with Mmc Fat Init routine If MMC SD card already contains a valid boot sector it will remain unchanged except volume label field and only FAT and ROOT tables will be erased Also the new volume label will be set Initialize the SPI module SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Format and initialize MMC SD card and MMC FAT16 library globals mc Fat QuickF
99. 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 int The internal arithmetic performed on pointers depends on the memory specifier in force and the presence of any overriding pointer modifiers When performing arithmetic with pointers it is assumed that the pointer points to an array of objects Arrays and Pointers Arrays and pointers are not completely independent types in the mikroC PRO for PIC32 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 Due to this fact arrays are not modifiable lvalues Brackets indicate array subscripts The expression id exp is defined as id exp where either idis a pointer and exp is an integer or id is an integer and exp is a pointer 207 MikroElektronika mikoC PRO for PIC32 The following statements are true amp a i ati afi a i According to these guidelines it can be written pa amp a 4 pa points to a 4 x pa 3 7 x afl7 JE aio BAER F7 y pa 3 y al4 3 Also the care should be taken when using operator precedence patt Equal to pat increments the pointer pa Increments the pointed object The follow
100. Parameters x0 x coordinate of the upper left box corner y0 y coordinate of the upper left box corner x1 X coordinate of the lower right box corner y1 y coordinate of the lower right box corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE me em LETTERE Example SPI T6963C box 0 119 239 127 SPI T6963C WHITE T IM a RR MD I SPI T6963C circle Prototype void SPI T6963C circle int x int y long r unsigned char pcolor Draws a circle on the Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE meum pg ILEIUUECECEEDEXL Example SPI T6963C circle 120 64 110 SPI 769636 WHITE Ri ie 9 5 E SPI T6963C circle fill Prototype void SPI T6963C circle fill int x int y long r unsigned char pcolor Draws a filled circle on the Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size BeOS color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C circle fill 120 64 110 SPI T6963C WHITE MikroElektronika 522 mikroC PRO for PIC32 SPI T6963C image Prototype void SPI T6963C image const code char pic Description Displays bitmap
101. Prototype void ShortToHex unsigned short input char output Description Converts input number to a string containing the number s hexadecimal representation The output string has fixed width of 3 characters including null character at the end string termination Parameters input signed short number to be converted output destination string Destination string should be at least 3 characters in length short t 100 char txt 3 Short ToHex E Exel wu ext rs 96 WordToHex Prototype void WordToHex unsigned input char output Description Converts input number to a string containing the number s hexadecimal representation The output string has fixed width of 5 characters including null character at the end string termination Parameters input unsigned integer to be converted output destination string Destination string should be at least 5 characters in length unsigned t 1111 char txt 5 WordToHex t txt ff txt as 0457 637 MikroElektronika mikoC PRO for PIC32 IntToHex Prototype Description Parameters Requires void IntToHex int input char output Converts input number to a string containing the number s hexadecimal representation The output string has fixed width of 5 characters including null character at the end string termination input Signed integer number to be converted output destination string Nothing Destination strin
102. READ PORTB is read STORE Because the capacitor is still charging the voltage at RBO is still low and reads as a 0 since we are reading from the pins directly not from the PORTB register Store read Value we didn t expect here value but physically still correct one STO CIA TERNAL REGISTER Read from pins Charging 00000000 c capacitor Charging I 00000000 TC Capacitor Actual voltage levels on MCU pins are relevant MODIFY Data is modified to set the bit WRITE PORTB is written with the new data The output driver for RB1 turns on but the Modify value driver for RBO turns back off eM M M M M MM n a olo o fo YoYo ayo mess Write EACHCRORCACHCNE REGISTER modified value Imememe A 0 0 H Charging l capacitor Discharging 00000010 Decne 00000000 169 MikroElektronika 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 0500000011 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 For example lets analyze the following example LATB BO 1 LATB B1 1
103. S1D13700 Circle unsigned int x center unsigned int y center unsigned int radius unsigned short color Description Draws a 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 1D13700_ BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine amie S1D13700 Circle 120 64 110 S1D13700 WHITE 319 MikroElektronika mikoC PRO for PIC32 S1D13700 Circle Fill Prototype void S1D13700 Circle Fill unsigned int x center unsigned int y center unsigned int radius unsigned short color 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 1D13700_BLACK Black color 1D13700_ WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine 1D13700 Circle Fi11 120 64 110 S1D13700 WHITE S1D13700 Image Prototype void S1D13700 Image const code char pic Description Displays bitmap on Glcd Parameters image image to be displayed Bitmap array is located in code memory Note Image dimension must match the display dimension Glcd module needs to be initialized See the S1D13700 nit routine Example 5113700
104. SPI Gled Write Text SPI Gled Image SPI Gled Partiallmage SPI Glcd Init Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See SPIx_Init and SPIx Init Advanced routines Port Expander module connections sbit SPExpanderRST at LATFO bit sbit SPExpanderCS at LATF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI module SPI1 Init Initialize SPI module used with PortExpander SPI Gled Init 0 485 MikroElektronika mikoC PRO for PIC32 SPI Glcd Set Side Selects Glcd side Refer to the Glcd datasheet for detail explanation Parameters x pos position on x axis Valid values 0 127 The parameter x pos specifies the Glcd side values from 0 to 63 specify the left side values from 64 to 127 specify the right side Glcd needs to be initialized for SPI communication see SPI Glcd Init routine The following two lines are equivalent and both of them select the left side of Glcd SPI Glcd Set Side 0 SPE Gled Set Side 10 Notes For side x axis and page layout explanation see schematic at the bottom of this page SP
105. SPI T6963C Gicd HW connection mikoC PRO for PIC32 T6963C Graphic Lcd Library The mikroC PRO for PIC32 provides a library for working with Glcds based on TOSHIBA T6963C controller The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules It is capable of controlling displays with a resolution up to 240x128 Because of its low power and small outline it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement equipment Although small this contoller has a capability of displaying and merging text and graphics and it manages all the interfacing signals to the displays Row and Column drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with PIC32 family of MCUs be aware of their voltage incompatibility with certain number of T6963C based Glcd modules So additional external power supply for these modules may be required ChipEnable CE FontSelect FS and Reverse MD have to be set to appropriate levels by the user outside of the T6963C_Init function See the Library Example code at the bottom of this page Glcd size based initialization routines can be found in setup library files located in the Uses folder The user must make sure that used MCU has appropriate ports and pins If this is not the case the user should adjust initialization routines Some mikroElektronika s adapter boards have pinout diff
106. 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 In situations when multiple breakpoints are used within the code it is sometimes handy to enable disable certain breakpoints To do this just check uncheck the desired breakpoint using the checkbox in front of the breakpoint s name Breakpoints Enable Line File Name Watch Values Window Watch Values Window is the main Debugger window which allows you to monitor program execution To show the Watch Values Window select Debug Windows Watch from the View drop down menu The Watch Values Window displays variables and registers of the MCU with their addresses and values Values are updated along with the code execution Recently changed items are coloured red There are two ways to add variable register into the watch list by its real name variable s name in program code Just select wanted variable register from Select variable from list drop down menu and click the d Add button by its name ID assembly variable name Simply type name ID of the variable register you want to display into Search for variable by assemby name box and click the a add button 129 MikroElektronika mikoC PRO for PIC32 Also it is possible to add all varia
107. System5x7 font supplied with the library will be used Write character C on the position 10 inside the page 2 Gled Write Char C 10 2 1 For x axis and page layout explanation see schematic at the bottom of this page Glcd Write Text Prototype void Glcd Write Text char ene unsigned short x pos unsigned short page num unsigned short color Prints text on Glcd Parameters text text to be written x pos text starting position on x axis page num the number of the page on which text will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the text 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized see Glcd Init routine Use Glcd Set Fontto specify the font for display if no font is specified then default Font Gicd System5x7 font supplied with the library will be used Write text Hello world on the position 10 inside the page 2 Gled Write Text Hello world 10 2 1 For x axis and page layout explanation see schematic at the bottom of this page MikroElektronika 336 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
108. 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 Description in all using Keypad mau d extern unsigned a Keypad Port unsigned keypadPort at PORTB sase re Library Routines Keypad_lnit Keypad_Key_Press Keypad_Key_Click Keypad Init ums Nothing L Requires Global variable keypadPort Keypad port must be defined before using this function Keypad module connections char unsigned at PORTB End of keypad module connections Keypad Init Notes The Keypad library uses lower byte bits lt 7 0 gt of keypadPort MikroElektronika 344 mikroC PRO for PIC32 Keypad Key Press Prototype unsigned Keypad Key Press Reads the key from keypad when key gets pressed The code of a pressed key 1 16 If no key is pressed returns 0 Port needs to be initialized for working with the Keypad library see Keypad Init unsigned kp kp Keypad Key Press None Keypad Key Click Description Call to Keypad Key Click is a blocking call the function waits until some key is pressed and released When released the function returns 1 to 16 depending on the key If more than one key is pressed simultaneously the function will wait until all pressed keys are released After that th
109. TolalfeamemoyszeOSOSCSCSCSCSCSCSCSC C CS unsigned total void main block TotalFreeMemSize 363 MikroElektronika 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 PDAs 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 Secure Digital Card Secure Digital SD is a Flash memory card standard based on the older Multi Media Card MMC format SD cards are currently available in sizes of up to and including 2 GB and are used in digital cameras digital camcorders handheld computers media players mobile phones GPS receivers video games and PDAs Secure Digital High Capacity Card SDHC Secure Digital High Capacity SD 2 0 is an extension of the SD standard which increases card s storage capacity up to 32 GB by using sector addressing instead of byte addressing in the previous SD standard SDHC cards share the same physical and electrical form factor as older SD 1 x cards allowing SDHC devices to support both newer SDHC cards and older SD cards The current standard limits the maximum capacity of an SDHC card to 32 GB Import
110. Toolbar Tools Toolbar comes with the following default options E Run USART Terminal A EEPROM ASCII Chart CI Seven Segment Editor Open Active Comment editor apem T Tip The Tools toolbar can easily be customized by adding new tools in Options menu window View Toolbar ia fn View Toolbar provides access to assembly code listing file and statistics windows C Be plon Open assembly code in editor FJ Open listing file in editor View statistics for current project 81 MikroElektronika mikoC PRO for PIC32 Layout Toolbar Styles toolbar allows you to easily customize workspace through a number of different IDE layouts Help Toolbar TY Help Toolbar provides access to information on using and registering compilers Open Help file EM How To Register Related topics Keyboard shortcuts Integrated Tools MikroElektronika 82 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 Project Manager EJ Ier mESESEES s imo E C7 Sources Bj Led c S Header Files built_in h Binaries 73 Project level defines 73 Image Files EEPROM Files 7j Active Comments Files S Output Files ES Lcd hex ES Lcd asm Other Files Step 2 Drag the tool window from
111. 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 Enumerations An enumeration data type is used for representing an abstract discreet set of values with appropriate symbolic names Enumeration Declaration Enumeration is declared like this enum tag enumeration list Here tag is an optional name of the enumeration enumeration list is a comma delimited list of discreet values enumerators or enumeration constants Each enumerator is assigned a fixed integral value In the absence of explicit initializers the first enumerator is set to zero and the value of each succeeding enumerator is set to a value of its predecessor increased by one Variables of the enum type are declared the same as variables of any other type For example the following declaration enum colors black red green blue violet white c establishes a unique integral type enum colors variable c of this type and set of enumerators with constant integer values black 0 red 1 In the mikroC PRO for PIC32 a variable of an enumerated type can be assigned any value of the type int
112. UARTx Init Advanced routines UART1 Init 9600 UART2 Init 9600 RS485Master Init UART Set Active amp UART1 Read Idle set UART1 active RS485Master Send dat 1 160 UART Set Active amp UART2 Read Idle set UART2 active RS485Master Send dat 1 160 initialize UART1 module initialize UART2 module initialize MCU as Master amp UART1 Write amp UART1 Data Ready amp UART1 Tx send message through UARTI amp UART2 Write amp UART2 Data Ready amp UART2 Tx send through UART2 397 MikroElektronika mikoC PRO for PIC32 Library Example This example demonstrates simple data exchange via 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 El E Copy Code To Clipboard char uart rd void main CHECON 30 ADIPCFG OxFFFF UART1 Init 56000 Delay ms 100 UART1 Write Text Start UART1 Write 13 UART1 Write 10 while 1 if UART1 Data Ready uart rd UART1 Read UART1 Write uart rd 74 Lu ee A Lu Initialize UART module at 9600 bps Wait for UART module to stabilize Endless loop If data is received read the received data and send data via UART MikroElektronika mikroC PRO for PIC32 HW Connection SUB D 9p
113. Virtual address space can be thought as CPU s logical view and use of its physical resources A graphical representation of the PIC32MX virtual and physical memory is shown in picture below Virtual Memory Map Physical Memory Map OxFFFFFFFF OxFFFFFFFF NOT USED 0xC0000000 SS OxBF000000 MW BMXDUDBA OxBD000000 Ox4FFFFFFF KSEG2 KSEG3 OxBFC00000 WW UOO Y 0xBF 800000 KWAY 0xBD000000 OxAFFFFFFF SS 4 0x40000000 0xA0000000 Wwinw wi w g d ESSO RESERVED V KSEGO KSEG1 0X80000000 Ox7F000000 Ox1D000000 OxOFFFFFFF Noo SSSSSSSSSSSSSS S PIC32 Memory Map 0x7D000000 BMXPUPBA OxOFFFFFFF BMXDUDBA USEG KUSEG 9 axanananan axnononona 165 MikroElektronika 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 KSEGO 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 The PIC32MX s CPU also uses virtual addressing to fetch and execute program memory instructions If you look closely you ll see that the physical address r
114. amp keydata amp special amp down if down amp amp keydata 16 break while 1 397 MikroElektronika mikoC PRO for PIC32 Special Function Keys 7 F8 F9 F10 F11 F12 Enter Page Up Page Down Backspace Insert Delete Windows Ctrl Shift Alt Print Screen Pause Caps Lock Home Scroll Lock Num Lock Left Arrow Right Arrow Up Arrow Down Arrow Escape Tab Value returned 10 11 12 13 14 15 16 17 19 1 28 1 32 33 34 je joo C C 2 3 C ee C ee io eo jo eS 9 2 33 jaa pu MikroElektronika 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 Copy Code To Clipboard unsigned short keydata special down sbit PS2 Data at RDO bit sbit PS2 Clock at RDL bit sbit PS2 Data Direction at TRISDO bit sbit PS2 Clock Direction at TRISD1 bit void main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital I O TRISD 0 LATD 0 UART1 Init 56000 Initialize UART module at 19200 bps Ps2 Config Init PS 2 Keyboard Delay ms 100 Wait for keyboard to finish UART1 Write Text Ready UART1 Write 10 Line Feed UART1 Write 13 Carriage return do if Ps2 Key Read amp keydata amp special amp down if down amp amp keydata 16 Backspace UART1 Write 0x08 else if down am
115. 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 Upon completion of writing your program choose Release build Type in the Project Settings window Project Settings P32MX460F512L Choose Release type if you want to use software simulator 8 000000 Build Type P Release ICD Debug Debugger Software O mikroICD After you have successfuly compiled your project you can run the Software Simulator by selecting Run Start Debugger from the drop down menu or by clicking the Start Debugger Icon B from the Debugger Toolbar Starting the Software Simulator makes more options available Step Into Step Over Step Out Run to Cursor etc Line that is to be executed is color highlighted blue by default Note The Software Simulator simulates the program flow and execution of instruction lines but it cannot fully emulate PIC32 device behavior i e it doesn t update timers interrupt flags etc Related topics Software Simulator Debug Windows Software Simulator Debugger Options MikroElektronika 128 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
116. and you will get new license free of charge Do your compilers work on Windows Vista Windows 7 Yes What does this function procedure routine do Please see your compiler s Help where all of the functions are explained in detail try to compile one of the provided examples and nothing happens what is the problem You need to open project not file When you want to open an example go to Project Open Project then browse through projects and choose project file Now you will be able to compile and program with success Can get your library sources need to provide all sources with my project It is our company s policy not to share our source code Can use code developed in your compilers in commercial purposes Are there some limitations Regarding your code there are no limitations Your application is your own property and you can do whatever you like with it If you want to include some of code we provide with our compilers or on our site you may include them in your project however you are not allowed to charge your users for these Why does an example provided with your compilers doesn t work All of the examples provided with our compilers are tested and work fine You need to read commented header of the example and be sure that you have used the same MCU example is written for and that you have hardware connections DIP switches jumpers etc set as described Your example works if use the s
117. b i b i temp Note that unlike other statements compound statements do not end with semicolon i e there is never a semicolon following the closing brace Preprocessor Preprocessor is an integrated text processor which prepares the source code for compiling Preprocessor allows inserting text from a specifed file to a certain point in the code see File Inclusion replacing specific lexical symbols with other symbols see Macros conditional compiling which conditionally includes or omits parts of the code see Conditional Compilation Note that preprocessor analyzes text at token level not at individual character level Preprocessor is controled by means of preprocessor directives and preprocessor operators Preprocessor Directives Any line in the source code with a leading is taken as a preprocessing directive or control line unless is within a string literal in a character constant or embedded in a comment The initial can be preceded or followed by a whitespace excluding new lines A null directive consists of a line containing the single character This line is always ignored Preprocessor directives are usually placed at the beginning of the source code but they can legally appear at any point in a program The mikroC PRO for PIC32 preprocessor detects preprocessor directives and parses the tokens embedded in them A directive is in effect from its declaration to the end of the program file
118. bit 1 Set RB11 as input TRISB12 bit 1 Set RB12 as input TRISB13 bit 1 Set RB13 as input If Port Expander Library uses SPI1 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE bit 2 ws Dre Xe bie 0 uds ee ee ee ee a ee a a 4 chip ena gA WR RD ICD ble bit 4 is RST init display for 240 pixel width and 128 pixel height 8 bits character width data bus on MCP23517 portB control bus on MCP23S17 portA SPI DATA SAMPL E MIDDLE reverse on 8x8 font internaly set in library SPI T6963C Config 240 128 8 0 2 1 0 4 Delay ms 10 00 Enable both graphics and text display at the same time Ey SPI T6963C_graphics 1 SPI_T6963C_text 1 panel 0 i 0 curs 0 cposx cpo sy 0 MikroElektronika mikroC PRO for PIC32 Text messages xx SPI T6963C write text txt 0 0 SPI T6963C ROM MODE XOR SPI T6963C write text txtl 0 15 SPI T6963C ROM MODE XOR Cursor ey SPI T6963C cursor height 8 8 pixel height SPI T6963C set cursor 0 0 move cursor to top left SPI T6963C cursor 0 X cursof off Draw solid boxes d SPI T6963C box 0 0 239 8 SPI T6963C WHITE SPI T6963C box 0 119 239 127 SPI T6963C WHITE
119. buffer 12e ww Format ww and store it to buffer UART1 Write Text rne format Write message on UART UART1 Write Text buffer Write buffer on UART sprintf buffer 12f ww Format ww and store it to buffer UART1 Write Text rnf format Write message on UART UART1 Write Text buffer Write buffer on UART sprintf buffer 12g ww Format ww and store it to buffer UART1 Write Text rng format Write message on UART VARTI Write Text buffer Write buffer on UART mikroC PRO for PIC32 Time Library The Time Library contains functions and type definitions for time calculations in the UNIX time format which counts the number of seconds since the epoch This is very convenient for programs that work with time intervals the difference between two UNIX time values is a real time difference measured in seconds What is the epoch Originally it was defined as the beginning of 1970 GMT January 1 1970 Julian day GMT Greenwich Mean Time is a traditional term for the time zone in England The TimeStruct type is a structure type suitable for time and date storage Type declaration is contained in Time n which can be found in the mikroC PRO for PIC32 Time Library Demo example folder Library Routines Time dateToEpoch Time epochToDate Time dateDiff Time dateToEpoch long Time dateToEpoch TimeStruct ts eum messes SNGG O finclude i TimeStruct sl
120. class specifier assumes the automatic value auto Generally speaking an identifier cannot be legally used in a program before its declaration point in the source code Legal exceptions to this rule known as forward references are labels calls to undeclared functions and struct or union tags The range of objects that can be declared includes Variables Functions Types Arrays of other types Structure union and enumeration tags Structure members Union members Enumeration constants Statement labels Preprocessor macros The recursive nature of the declarator syntax allows complex declarators You ll probably want to use typedefs to improve legibility if constructing complex objects MikroElektronika 192 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 Historically 1 stood for left meaning that lvalue could legally stand on the left the receiving end of an assignment statement Now only modifiable lvalues can legally stand to the left of an assignment operator For exa
121. d 3 CONNECT NE MCU TO PC Send mE CONNECT Data Tx p PC TO MCU OSCILLATOR GNO PIC32MX460F512L o vcc3 UUDUUUUUUUUUTUUUUUUUUUUUU RS232 HW connection mikoC PRO for PIC32 USB Library Universal Serial Bus USB provides a serial bus standard for connecting a wide variety of devices including computers cell phones game consoles PDAs etc USB Library contains HID routines that support HID class devices and also the generic routines that can be used with vendor specified drivers USB HID Class The HID class consists primarily of devices that are used by humans to control the operation of computer systems Typical examples of HID class devices include Keyboards and pointing devices for example standard mouse devices trackballs and joysticks Front panel controls for example knobs switches buttons and sliders Controls that might be found on devices such as telephones VCR remote controls games or simulation devices for example data gloves throttles steering wheels and rudder pedals Devices that may not require human interaction but provide data in a similar format to HID class devices for example bar code readers thermometers or voltmeters Many typical HID class devices include indicators specialized displays audio feedback and force or tactile feedback Therefore the HID class definition includes support for various types of output directed to the end user Descrip
122. detected and successfully initialized 1 if FAT16 boot sector was not found 255 if card was not detected Init the FAT library DCE Bat In t Init the FAT library Cf Fat QuickFormat Prototype unsigned int Cf Fat QuickFormat char cf fat label Formats to FAT16 and initializes CF card Parameters cf fat label volume label 11 characters in length If less than 11 characters are provided the label will be padded with spaces If null string is passed the volume will not be labeled if CF card was detected successfully formated and initialized 1 if FAT16 format was unsuccessful 255 if card was not detected format and initialize the FAT library if Cf Fat QuickFormat amp cf fat label This routine can be used instead or in conjunction with Cf Fat Init routine If CF card already contains a valid boot sector it will remain unchanged except volume label field and only FAT and ROOT tables will be erased Also the new volume label will be set MikroElektronika 294 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 The f
123. displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C write char A 22 23 T6963C ROM MODE AND 543 MikroElektronika mikoC PRO for PIC32 T6963C write text Prototype void T6963C write text unsigned char str unsigned char x unsigned char y unsigned char mode Writes text in the current text panel of Glcd at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis mode mode parameter Valid values TG968C ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd
124. drop down menu or click the Show Options Icon i and then select the Spell Checker Tab Comment Style Code Editor has a feature to change the comment style to either single line or multi line Commenting or uncommenting the selected code is done by a simple click of a mouse using the Comment Icon i2 and Uncomment Icon u from the Advanced Edit Toolbar Code Folding Code folding is IDE feature which allows users to selectively hide and display sections of a source file In this way it is easier to manage large regions of code within one window while still viewing only those subsections of the code that are relevant during a particular editing session While typing the code folding symbols and t appear automatically Use the folding symbols to hide unhide the code subsections m main i t PORTA 0 PORTB 0 Lcd Init Lcd Out i1 1 txt 0 Lcd Out 2 1 txt 1 delay_ms 1000 Lcd Cmd i Lcd Out i i1 txt 1 Lcd Out 2 4 txt 2 delay_ms 500 void main 53 MikroElektronika 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 void main t l Np void main PORTA 0 PORTB 0 Lcd Init Lcd Out 1 1 txt 0 Lcd Out 2 1 txt 1 delay ms 1000 Lcd Cmd 1 Lcd Out i1 1 txt 1 Lcd Out 2 4 txt 2
125. duty if current dutyl gt pwm period2 if we increase current dutyl greater then possible pwm period2 value current dutyl 0 reset current dutyl value to zero PWM Set Duty current dutyl 2 set newly acquired duty ratio if RB3 bit button on RB3 pressed Delay ms 1 current dutyl current dutyl 5 decrement current duty if current dutyl gt pwm period2 if we decrease current dutyl greater then possible pwm periodi value overtlow current dutyl pwm period2 set current duty to max possible value PWM Set Duty current dutyl 2 Delay ms 1 slow down change pace a little HW Connection OSCILLATOR PIC32MX460F512L e Q vcc3 PWM demonstration MikroElektronika 404 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 The Slave can never initiate communication It is the user s responsibility to ensure that only one device transmits via 485 bus at a time The RS 485 routines require the UART mo
126. enables appropriate network traffic on the ENC28760 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 For this purpose predefined library constants see the table below can be ORed to form appropriate input value Advanced filtering available in the ENC28J60 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC28J60 module The ENC28360 module should be properly cofigured by the means of SPI Ethernet Init routine Parameters enF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 0x01 MAC Broadcast traffic receive filter flag When set SPI Ethernet MAC broadcast traffic will be enabled BROADCAST MAC Multicast traffic receive filter flag When set SPI Ethern MAC multicast traffic will be enabled MULTICAST CRC check flag When set packets with invalid
127. file and start with new data for loop 1 loop lt 99 looptt UART1 Write file contents 0 loop 10 48 file contents 1 loop 10 48 MikroElektronika 378 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 lt Z loop2t 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 amp time info Mmc Fat Assign amp filename 0xA0 find existing file or create a new one Mmc Fat Rewrite To clear file and start with new data for loop 1 loop lt 44 loopt file contents 0 loop 10 48 file contents 1 loop 10 48 Mmc Fat Write file contents LINE LEN 1 write data to the assigned file Opens an existing file and rewrites it void M Open File Rewrite filename 7 C Mmc Fat Assign amp filename 0 Mmc Fat Rewrite for loop 1 loop lt 55 looptt file contents 0 loop 10 48 file contents 1 loop 10 48 Mmc Fat Write file contents LINE LEN 1 write data to the assigned file Opens an existing file and appends data to it oF and alters the date time stamp void M Open File Append filename 7 B Mmc Fat Assign a
128. 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 amp 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 3 received IP packet was not IPv4 4 received packet was of type unknown to the library Ethernet module has to be initialized See SPI Ethernet Init Ethernet doPacket 0 1 process received packets 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption ENC28J60 controller needs to be restarted 2 received packet was not sent to us not our IP nor IP broadcast address Notes SPI Ethernet doPacket must be called as often as possible in user s code SPI Ethernet putByte Prototype void SPI Ethernet putByte unsigned char v Description This is MAC module routine It stores one byte to address pointed by the current ENC28J60 write pointer EWRPT Ethernet module has to be initialized See SPI Ethernet Init char data SPI Ethernet putByte data put a byte into ENC28J60 buffer 44
129. 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 number input number Returns Low word of number bits 15 0 d 0x12345678 tmp LoWord d Equals 0x5678 HiWord Prototype unsigned int HiWord unsigned long number Description The function returns high 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 number input number Retums High word of number bits 31 16 0x12345678 tmp HiWord d Equals 0x1234 MikroElektronika 150 mikroC PRO for PIC32 Delay us Prototype void Delay us const unsigned long time in us Description 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 meme m 000 S Example Delay us 10 Ten microseconds pause etes None Delay ms Prototype void Delay ms const unsigned int time in ms Description Creates a software delay in d
130. have added the image it will appear in the Image Preview Window i 1884912ld i i i i 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 Toolbars This section provides an overview of the toolbars available in mikroC PRO for PIC32 Help File Toolbar Edit Toolbar Advanced Edit Toolbar Find Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar MikroElektronika 16 mikroC PRO for PIC32 File Toolbar 5 File Toolbar is a standard toolbar with the following options Die o LB Opens a new editor window Open source file for editing or image file for viewing nl Save changes for active window Save changes in all opened windows Edit Toolbar Edit Toolbar is a standard toolbar with the following options S BeeWplan e Undo last change E3 Redo last change Cut selected text to clipboard Copy selected text to clipboard Paste text from clipboard 7 MikroElektronika mikoC PRO for PIC32 Advanced Edit Toolbar Advanced Edit Toolbar comes with the following options Icon DIT C X H
131. in actual arg 1ist Like with simple macro definitions rescanning occurs to detect any embedded macro identifiers eligible for expansion Here is a simple example A simple macro which returns greater of its 2 arguments define MAX A B A gt B A B y Let s call ite x MAX a b c d Preprocessor will transform the previous line into x 2 b gt e dp 2 fat B e d 7 It is highly recommended to put parentheses around each argument in the macro body in order to avoid possible problems with operator precedence Undefining Macros The unde directive is used to undefine a macro undef macro identifier The directive undef detaches any previous token sequence from macro identifier the macro definition has been forgotten and macro identifier is undefined No macro expansion occurs within the undef lines The state of being defined or undefined is an important property of an identifier regardless of the actual definition The ifdef and ifndef conditional directives used to test whether any identifier is currently defined or not offer a flexible mechanism for controlling many aspects of a compilation After a macro identifier has been undefined it can be redefined with define using the same or different token sequence File Inclusion The preprocessor directive include pulls in header files extension h into the source code Do not rely on preprocessor to include source files ex
132. in different declarations of the same function Here are two prototypes of the same function int test const char declares function test int test const char p declares the same function test Function prototypes are very useful in documenting code For example the function Cf Init takes two parameters Control Port and Data Port The question is which is which The function prototype void Cf Init char ctrlport char dataport makes it clear If a header file contains function prototypes the user can read that file to get the information needed for writing programs that call these functions If a prototype parameter includes an identifier then the indentifier is only used for error checking Function Definition Function definition consists of its declaration and function body The function body is technically a block a sequence of local definitions and statements enclosed within braces All variables declared within function body are local to the function i e they have function scope The function itself can be defined only within the file scope which means that function declarations cannot be nested To return the function result use the return statement The statement return in functions ofthe void type cannot have a parameter in fact the return statement can be omitted altogether if it is the last statement in the function body Here is a sample function definition function max returns gr
133. individual functions for divergence The mikroC PRO for PIC32 does not provide automatic initialization for objects Uninitialized globals and objects with static duration will take random values from memory Anonymous unions and structures are now supported C Language Extensions mikroC PRO for PIC32 has additional set of keywords that do not belong to the ANSI standard C language keywords code data x due Amt sbit but iy Implementation defined Behavior Certain sections of the ANSI standard have implementation defined behavior This means that the exact behavior of some C code can vary from compiler to compiler This Help contains the sections describing how the mikroC PRO for PIC32 compiler behaves in such situations The most notable specifics include Storage Classes Bit Fields Related topics Keywords PIC32 Specifics MikroElektronika 136 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 c file from defs folder containing declarations of available SFR registers and constants such as PORTB ADPCFG etc All i
134. input parameter multiplied by 1000 mE E3 196 result is 193 Return value range 1000 1000 MikroElektronika 656 mikroC PRO for PIC32 CHAPTER 10 Tutorials Managing Project Projects The mikroC PRO for PIC32 organizes applications into projects consisting of a single project file extension mcp32 and one or more source files extension c mikroC PRO for PIC32 IDE allows you to manage multiple projects see Project Manager Source files can be compiled only if they are part of a project The project file contains the following information project name and optional description target device device flags config word device clock list of the project source files with paths header files h binary files emcl image files other files Note that the project does not include files in the same way as preprocessor does see Add Remove Files from Project mikoC PRO for PIC32 New Project The easiest way to create a project is by means of the New Project Wizard drop down menu Project New Project or by clicking the New Project Icon E from Project Toolbar New Project Wizard Steps Start creating your New project by clicking Next button New Project Wizard Welcome to the New Project Wizard This wizard helps you e Create a new project e Select the device for your project e Setup device clock Add project files Click Next to continue
135. instructions that expect parameters like 1it1 1it4 slit6 slit6 bit4 etc be sure to preceed them with the hash symbol to ensure proper functioning Example BSET f 5 set bit 5 in f register MOV 416000 Wnd move number 16000 to destination working register ADD Ws 5 Acc add number 5 to accumulator Asm code and SSA optimization If asm code is mixed with the C code keep in mind thatthe 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 Because of this user must be very careful when writing asm code as existing values in the working registers used by SSA optimization can be overwritten To avoid this it is recommended that user includes desired asm code in a separate routine MikroElektronika 228 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 Scalar types are initialized with a single expres
136. long epoch what is the epoch of the date in ts poch Time dateToEpoch amp tsl 653 MikroElektronika mikoC PRO for PIC32 Time epochToDate Prototype void Time epochToDate long e TimeStruct ts Description Converts the UNIX time to time and date Parameters e UNIX time seconds since UNIX epoch ts time and date structure for storing conversion output include Tine Hh TimeStruct taz long epoch what date is epoch 1234567890 epoch 1234567890 Time epochToDate epoch amp ts2 Time dateDiff Prototype long Time dateDiff TimeStruct t1 TimeStruct t2 pee This function compares two dates and returns time difference in seconds as a signed long Result is pese if t1 is before t2 result is null if t1 is the same as t2 and result is negative if t1 is after t2 Parameters t1 time and date structure the first comparison parameter t2 time and date structure the second comparison parameter Parameters Nome o EE ee Time difference in seconds as a signed long include T3me h TimeStruct tsl ts2z long aifi j how many seconds between these two dates is contained in tsl and ts2 buffers diff Time dateDiff amp tsl amp ts2 MikroElektronika ag mikroC PRO for PIC32 Library Example Demonstration of Time library routines usage for time calculations in UNIX time format Copy Code To Clipboard include Time h TimeStruct tsl ts
137. members are ignored during initialization Anonymous Structures mikroC PRO for PIC32 allows you to declare a structure variable within another structure without giving it a name These nested structures are called anonymous structures You can access the members of an anonymous structure as if they were members in the containing structure struct phone int areacode long number h struct person char name 30 char gender int age int weight struct phone Anonymous structure no name needed Jim Jim number 1234567 Related topics Working with structures MikroElektronika 212 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 Note that two variables are of the same structured type only if they are both defined by the same instruction or using the same type identifier For example a and b are of the same type struct int ml m2 a b But c and d are not of the same type although their structure descriptions are identical struct int di m2 o struct int ml m2 d Size of Structure The size of the structure in
138. memory can be retrieved by means of the operator sizeof It is not necessary that the size of the structure is equal to the sum of its members sizes It is often greater due to certain limitations of memory storage Structures and Functions A function can return a structure type or a pointer to a structure type mystruct funcl void fu uncl returns a structure mystruct func2 vord func2 returns pointer to structure A structure can be passed as an argument to a function in the following ways void funcl mystruct s directly void func2 mystruct sptr via a pointer 213 MikroElektronika mikoC PRO for PIC32 Structure Member Access Structure and union members are accessed using the following two selection operators period gt 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 5 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 The operator gt is called the indirect or pointer member selector Suppose that the object s is of the struct type s and ps is a pointer to s Then if m is a member identifier of the type M declared in s the expression ps m indirect access to member m identical to ps m is of the type M a
139. needs to be initialized see Glcd Init routine Draw a circle with center in 50 50 and radius 10 Gled Carele 50 50 10 1 Glcd Circle Fill Prototype void Glcd Circle Fill int x center int y center int radius unsigned short color Draws a filled circle on Glcd Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 Glcd needs to be initialized see Glcd Init routine Draws a filled circle with center in 50 50 and radius 10 Gled Circle Fill 50 90 10 1 MikroElektronika 394 mikroC PRO for PIC32 Glcd Set Font Prototype void Glcd Set Font const char activeFont unsigned short aFontWidth unsigned short aFontHeight unsigned int aFontOffs 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 aFontOffs number that represents difference between the mikroC PRO for PIC32 character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroC PRO for PIC32 character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with spac
140. of the upper left rectangle corner y upper left y coordinate of the upper left rectangle corner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values S 1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Rectangle Round Edges 20 20 219 107 12 S1D13700 WHITE MikroElektronika 318 mikroC PRO for PIC32 S1D13700 Rectangle Round Edges Fill Prototype void S1D13700 Rectangle Round Edges Fill unsigned int x0 unsigned int y0 unsigned int xl unsigned int yl unsigned short round radius unsigned short color 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 x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner round radius radius of the rounded edge pcolor color parameter Valid values S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine 1D13700 Rectangle Round Edges Fill 20 20 219 107 12 S1D13700 WHITE S1D13700 Circle Prototype void
141. on Glcd Parameters pic 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 Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd SPI T6963C Partiallmage Prototype void SPI T6963C Partiallmage unsigned int x left unsigned int jy top unsigned int width unsigned int height unsigned int picture width unsigned int picture height code const unsigned short image Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroC PRO for PIC pointer to const and pointer to RAM equivalency Nothing Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Ori
142. optional Either decimal integer or decimal fraction but not both can be omitted Either decimal point or letter e or x with a signed integer exponent but not both can be omitted These rules allow conventional and scientific exponent notations Negative floating constants are taken as positive constants with an unary operator minus prefixed The mine PRO for PIC32 limits floating point constants to the range 1 17549435082 1078 6 80564774407 107 Here are some examples 0 0 0 1 23 1 23 23 45e6 23 45 10 6 2e 5 2 0 10 5 3E 10 ff 3 0 10710 09E34 0 09 10 34 The mikroC PRO for PIC32 floating point constants are of the type double Note that the mikroC PRO for PIC32 s implementation of ANSI Standard considers float and double together with the long double variant to be the same type Character Constants A character constant is one or more characters enclosed in single quotes such as A or n In the mikroC PRO for PIC32 single character constants are of the unsigned int type Multi character constants are referred to as string constants or string literals For more information refer to String Constants Escape Sequences A backslash character is used to introduce an escape sequence which allows a visual representation of certain nongraphic characters One of the most common escape constants is the newline character n A backslash
143. port if bit x in bit mask is set to 1 Toshiba Gled module needs to be initialized See SPI T6963C Config routine clear bits 0 and 1 on control port SPI T6963C clearBit 0x03 MikroElektronika 524 mikroC PRO for PIC32 SPI T6963C setBit Prototype void SPI T6963C setBit char b Description Sets control port bit s Parameters b bit mask The function will set bit x on control port if bit x in bit mask is set to 1 Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set bits 0 and 1 on control port SPI T6963C setBit 0x03 None SPI T6963C negBit Negates control port bit s b bit mask The function will negate bit x on control port if bit x in bit mask is set to 1 Nothing Toshiba Glcd module needs to be initialized See SPI T6963C Config routine negate bits 0 and 1 on control port SPI T6963C negBit 0x03 None SPI T6963C displayGrPanel eT RUE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display graphic panel 1 SPI T6963C displayGrPanel 1 None 929 MikroElektronika mikoC PRO for PIC32 SPI T6963C displayTxtPanel eum Noting OOOO Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display text panel 1 SPI T6963C displayTxtPanel 1 SPI T6963C setGrPanel Description CUm start address for selected graphic panel and set appropriate
144. red The user can edit and change the values in the RAM window mikrolCD Specific RAM window content will be written to the MCU before the next instruction execution Lcd4bit mikroE ikroElektronike EasydsPIC4 lt Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View Debug Windows Stopwatch The Stopwatch Window displays a Current Count of cycles time since the last Software Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started and can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has started and ended Watch Clock Cycles Time Current Count 2 103 943 273 105 20 s Delta 4044 07 ms Stopwatch 2 103 943 273 105197 16 ms Reset To Zero 80 131 MikroElektronika 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 mikrolCD is selected as a debugger To show the EEPROM Watch Window select Debug Windows EEPROM from the View
145. 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 Options Auto Correct Editor Settings V Enable Auto Correct sje Add Original Replacement Ue E Remove Ma Editor Colors Auto Correct Aut Completa e et Style Advanced V Correct Case to Match Declaration V Show Notification J Output This option is already set up to automatically correct some words For example if you type whie1 it will be corrected to while when you press the spacebar while Autocorrect from whiel to while mikroC PRO for PIC32 The user can easily add its common typos by entering original typo for example 5t ye 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 Options Editor E Editor Settings V Enable Auto Complete iy dow Editor Colors do while E Auto Correct do while For no Auto Complete For statement e function header template int Func declaration Suis if if no ife if no begin end else no beginfend ifes if else i
146. save the file 4 In the File Name field modify the name of the file you want to save 5 Click the Save button Closing file 1 Make sure that the tab containing the file that you want to close is the active tab 2 Select File Close from the drop down menu or right click the tab of the file that you want to close and select Close option from the context menu 3 If the file has been changed since it was last saved you will be prompted to save your changes Search Paths You can specify your own custom search paths select Project Edit Search Paths option from the drop down menu Search Paths E3 Path C Program Files Mikroelektronika mikroC PRO For PIC32 defs C Program Files Mikroelektronika mikroC PRO For PIC32 uses C Program Files Mikroelektronika mikroC PRO for PIC32 Examples Development Systems L 32MxX v6 Led Blink Header Files C Program Files Mikroelektronika mikroC PRO for PIC32 Examples Development Systems L 32Mx v6 Led Blink C Program Files Mikroelektronika mikroC PRO for PIC32tincludel Restore MikroElektronika 670 mikroC PRO for PIC32 Following options are available Leo Description Add Search Path Remove Search Path ca Purge Invalid Paths Paths for Source Files c You can specify either absolute or relative path to the source file If you specify a relative path mikroC PRO for PIC32 will look for the file in following locations in t
147. short month unsigned short day unsigned short hours unsigned short mins unsigned short seconds Description Sets the date time stamp Any subsequent file writing operation will write this stamp to currently assigned file s time date attributes Parameters year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 da y day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds seconds attribute Valid values 0 59 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 Example Cf Fat Set File Date 2005 9 30 17 41 0 oes None MikroElektronika 298 mikroC PRO for PIC32 Cf Fat Get File Date Prototype Description Parameters Requires void Cf Fat Get File Date unsigned int year unsigned short month unsigned short day unsigned short hours unsigned short mins Reads time date attributes of currently assigned file 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 da y buffer to store day attribute to Upon function execu
148. should be used when DHCP server is present on the network to fetch assigned IP subnet mask Pointer to the global variable holding IP subnet mask Requires Ethernet module has to be initialized See SPI Ethernet Init unsigned char IpMas user IP subnet mask buffer meinesyttalssk SPI Ethernet getIpMask 4 fetch IP subnet mask User should always copy the IP address from the RAM location returned by this routine into it s own IP subnet mask buffer These locations should not be altered by the user in any case SPI Ethernet confNetwork Prototype void SPI Ethernet confNetwork char ipMask char gwIpAddr char dnsIpAddr Configures network parameters IP subnet mask gateway IP address DNS IP address when DHCP is not used Parameters ipMask IP subnet mask gwlpAddr gateway IP address dnsIpAddr DNS IP address Ethernet module has to be initialized See SPI Ethernet Init char ipMask 4 255 255 255 0 network mask for example 255 255 295 0 char gwIpAddr 4 192 168 1 gateway router IP address char dnsIpAddr 4 192 168 1 DNS server IP address SPI Ethernet confNetwork ipMask gwIpAddr dnsIpAddr set network configuration parameters The above mentioned network parameters should be set by this routine only if DHCP module is not used Otherwise DHCP will override these settings 453 MikroElektronika mikoC PRO for PIC32 SPI Ethernet arpResolve
149. sizeof with expressions of function type incomplete types parenthesized names of such types or with lvalue that designates a bit field object Sizeof Applied to Expression If applied to expression the size of an operand is determined without evaluating the expression and therefore without side effects The result of the operation will be the size of the type of the expression s result Sizeof Applied to Type If applied to a type identifier si zeof returns the size of the specified type The unit for type size is sizeof char which is equivalent to one byte The operation sizeof char gives the result 1 whether char is signed or unsigned Thus sizeof char returns 1 sizeof int returns 2 sizeof unsigned long returns 4 sizeof float returns 4 When the operand is a non parameter of array type the result is the total number of bytes in the array in other words an array name is not converted to a pointer type int ip 3 allo j e sizeof a ll 9 sizeof inE 2 i sizeof a i 10 sizeof int 20 To get the number of elements in an array int num elem i j If the operand is a parameter declared as array type or function type sizeof gives the size of the pointer When applied to structures and unions sizeof gives the total number of bytes including any padding The operator sizeof cannot be applied to a function 22 MikroElektronika mikoC PRO for PIC32
150. termination The output string is right justified and remaining positions on the left if any are filled with zeros Parameters input unsigned integer to be converted output destination string Nothing Requires Destination string should be at least 6 characters in length unsigned short t 437 char txt 6 WordToStrWithZeros t txt txt is 0437 one zero here Mwobkrnko ig mikroC PRO for PIC32 IntToStrWithZeros Prototype void IntToStrWithZeros int input char output Description Converts input integer to a string The output string has fixed width of 7 characters including null character at the end string termination The output string is right justified and remaining positions on the left if any are filled with zeros Parameters input integer number to be converted output destination string Destination string should be at least 7 characters in length short t 3276 char txt 7 IntToStrWithZeros t txt txt is 03276 one zero here LongWordToStrWithZeros Prototype void LongWordToStrWithZeros unsigned long input char output Description Converts input longword to a string The output string has fixed width of 11 characters including null character at the end string termination The output string is right justified and the remaining positions on the left if any are filled with zeros Parameters input unsigned long number to be converted outp
151. the DriveB pin soit DriveB Direction at TRISC14 bit Library Routines TP Init TP Set ADC Threshold TP Press Detect TP Get Coordinates TP Calibrate Bottom Left TP Calibrate Upper Right TP Get Calibration Consts TP Set Calibration Consts 519 MikroElektronika mikoC PRO for PIC32 TP Init Prototype void TP Init unsigned int display width unsigned int display height unsigned int readX ChNo unsigned int readY ChNo Initialize touch panel display Default touch panel ADC threshold value is set to 3900 Parameters display width set display width display height set display height readX ChNo read X coordinate from desired ADC channel readY ChNo read Y coordinate from desired ADC channel Before calling this function initialize ADC module ADC1 Init Initalize ADC module TP Init 128 Initialize touch panel dimensions 128x64 TP Set ADC Threshold Prototype void TP Set ADC Threshold unsigned int threshold Set custom ADC threshold value call this function after TP Init threshold custom ADC threshold value TP Init has to be called before using this routine EIN TP Set ADC Threshold 3900 Set touch panel ADC threshold MikroElektronika 580 mikroC PRO for PIC32 TP Press Detect TT Detects if the touch panel has been pressed 1 if touch panel is pressed 0 otherwise Requires Global variables DriveA DriveA Dri
152. there was an error while reading MMC SD card must be initialized See Mmc Init unsigned int error char dataBuffer 16 rror Mmc Read Csd dataBuffer MikroElektronika 368 mikroC PRO for PIC32 Mmc Fat Init Prototype unsigned int Mmc Fat Init Initializes MMC SD card reads MMC SD FAT16 boot sector and extracts necessary data needed by the library 0 if MMC SD card was detected and successfully initialized 1 if FAT16 boot sector was not found 255 if MMC SD card was not detected Requires Global variables Mmc Chip Select Chip Select line Mmc Chip Select Direction Direction of the Chip Select pin must be defined before using this function The appropriate hardware SPI module must be previously initialized See the SPIx Init SPIx Init Advanced routines MMC module connections sbit Mmc Chip Select at LATFO bit sbit Mme Chip Select Direction at TRISFO bit MMC module connections include spi const h Initialize the SPI module SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE S PRESCALE PRI 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIV IDLE Initialize MMC SD card and MMC FAT16 library globals Mmc Fat Init Reinitialize the SPI module at higher speed change primary prescaler SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI
153. to be initialized for SPI communication see SPI Glcd Init routine Use the SPI Glcd Set Font to specify the font for display if no font is specified then the default Font Glcd System5x7 font supplied with the library will be used Write character C on the position 10 inside the page 2 SPI Gled Write GChar C 10 2 1 7 For x axis and page layout explanation see schematic at the bottom of this page SPI Glcd Write Text Prototype Description Parameters Requires void SPI Glcd Write Text char text char x pos char page num char color Prints text on Glcd text text to be written x pos text starting position on x axis page num the number of the page on which text will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the text 0 white 1 black and 2 inverts each dot Nothing Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Use the SPI_Glcd_Set_Font to specify the font for display if no font is specified then the default Font Glcd System5x7 font supplied with the library will be used Write text Hello world on the position 10 inside the page 2 SPI Gled Write Text Hello wotldi T0 2 1 For x axis and page layout explanation see schematic at the bottom of this page 499 MikroElektronika mikoC PRO for PIC32 SPI Glcd Image Prototype void SPI Glcd Image const co
154. to the displays Row and Column drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of T6963C based Glcd modules So additional external power supply for these modules may be required Glcd size based initialization routines can be found in setup library files located in the Uses folder The user must make sure that used MCU has appropriate ports and pins If this is not the case the user should adjust initialization routines The library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI T6963C Glcd Library For MCUs with multiple SPI modules it is possible to initialize both of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with mikroElektronika s Serial Glcd 240x128 and 240x64 Adapter Boards pinout see schematic at the bottom of this page for details To use constants located in Lib SPIT6963C Const nh file user must include it the source file include w SPIT6963C h Some mikroElektronika s adapter boards have pinout different from T6369C datasheets Appropriate relations between these labels are given in the table below Adapter Board T6369C datasheet Library Dependency Tree gt Port Expander SPI T6963C Gicd T
155. 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 Macro Editor A macro is a series of keystrokes that have been recorded in the order performed A macro allows you to record a series of keystrokes and then playback or repeat the recorded keystrokes 13 MikroElektronika mikoC PRO for PIC32 The Macro offers the following commands 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 Related topics Code Editor Code Templates Image Preview There are a lot of occassions in which the user besides the code must look at the appropriate schematics in order to succesfully write the desired program The mikroC PRO for PIC32 provides this possibility through the Image Preview Window To add an image to the Image Preview Window right click the Image Files node in the Project Manager Ez Project Manager 1 1 R5485_Master_Example mcp32 zu Esse eHait aa e B RS485 Master _Example mcp32 amp Sources Rs485 Master Example c Header Files Binaries C7 Project Level Defines
156. with the value and type of expression 2 giving the result of the whole expression Result of expression 1 is discarded Binary operator comma has the lowest precedence and associates from left to right so that b cis the same as a b c This allows writing sequences with any number of expressions expression 1 expression 2 expression n which results in the left to right evaluation of each expression with the value and type of expression n giving the result of the whole expression Results of other expressions are discarded but their possible side effect do occur For example result a 5 b 2 c returns preincremented value of variable c but also intializes a divides b by 2 and increments c result x 10 y x 3 x z x 3 y returns computed value of variable z and also computes x and y MikroElektronika 248 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 f nc a jy dy yox 2p X calls the function func with three arguments i 5 k not four Statements Statements specify a flow of control as the program executes In the absence of specific jump and selection statements statements are executed sequentially in the orde
157. zero This is also true for signed operands if all discarded bits are equal to a sign bit 000001 5 equals 000040 0x3801 lt lt 4 equals 0x8010 overflow With shift right gt gt far right bits are discarded and the freed bits on the left are assigned zeroes in case of unsigned operand or the value of a sign bit in case of signed operand Shifting operand to the right by n positions is equivalent to dividing it by 2n OxFF56 gt gt 4 equals OxFFF5 OxFF56u gt gt 4 equals OxOFF5 Bitwise vs Logical Do not forget of the principle difference between how bitwise and logical operators work For example 0222222 amp 05555557 equals 000000 0222222 amp amp 0555555 equals 1 Qx1234 equals OxEDCB 0x1234 equals 0 241 MikroElektronika 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 Logical Operators Overview Logical Operations Precedence of logical relational and arithmetic operators was designated in such a way to allow complex expressions without parentheses to have an expected meaning c gt 0 amp amp c lt 19 reads as c
158. 0 To fill the screen completely use Glcd_ Fill OxFF ea byte to fill Glcd memory with Glcd needs to be initialized see Glcd Init routine Clear screen Gled F3il 0 7 etes None Glcd Dot Prototype void Glcd Dot unsigned short x pos unsigned short y pos unsigned short color Draws a dot on Glcd at coordinates x pos y pos Parameters x pos x position Valid values 0 127 y pos y position Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines a dot state O clears dot 1 puts a dot and 2 inverts dot state Glcd needs to be initialized see Glcd Init routine Invert the dot in the upper left corner Gled Dot 0 0 2 Notes For x and y axis layout explanation see schematic at the bottom of this page Glcd Line Prototype void Glcd eee scene x Start int y start int x end int y end unsigned short color Draws a line on Glcd Parameters x start x coordinate of the line start Valid values 0 127 y start y coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color O white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a line between dots 0 0 and 20 30 Gica L ine 0 0 20 305 Iki
159. 0 i 5000 i Mmc Write Sector size t Buffer UART1 Write f 2 Main Uncomment the function s to test the desired operation s void main define COMPLETE EXAMPLE comment this line to make simpler smaller example PORTD 0 TRISD 0 PORTF 0 TRISF 0 CHECON 0x32 ADIPCFG OxFFFF initialize AN pins as digital Initialize UART1 module UART1 Init 19200 Delay ms 10 UART1 Write Line MCU Started MCU present report set up SPI for the file read SPI2 Init Advanced SPI MASTER SPI 8 BIT 64 SPI SS DISABLI MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Delay ms 10 Fl SPI DATA SAMPLE init the FAT library if Mmc Fat Init reinitialize spi at higher speed SPI2 Init Advanced SPI MASTER SPI 8 BIT 8 SPI SS DISABLI MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE Fl SPI DATA SAMPLE 381 MikroElektronika 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 N
160. 00 Write Char Prototype void S1D13700 Write Char unsigned char c unsigned int x unsigned int y unsigned char mode Description Writes a char in the current text layer of Glcd at coordinates x y Parameters c char to be written x char position on x axis column y char position on y axis row mode mode parameter Valid values In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons SIDIJJG0 OVERLAY XOR In this mode the text and graphics data are combined via the logical exclusive OR S1013200 OVERLAY AND The text and graphic data shown on display are combined via the logical AND function S1D13700 OVERLAY OR Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Write Char A 22 23 81D13700 OVERLAY OR MikroElektronika 314 mikroC PRO for PIC32 S1D13700 Write Text Prototype void S1D13700 Write Text unsigned char str unsigned char x unsigned char char mode 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 Valid values In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of comb
161. 000 ifdef PARTIAL IMAGE DEMO SPI T6963C grFill 0 SPI T6963C PartialImage 0 partial image Delay ms 1000 SPI T6963C graphics 0 fendif 0 64 SPI T6963C image mikroE 240x128 bmp SPI T6963C graphics 1 SPI T6963C displayGrPanel 0 119 64 240 Draw a sprite Select other graphic panel 128 mikrol E 240x128 bmp Display MikroElektronika 932 mikroC PRO for PIC32 for 4 Endless loop If RB8 is pressed display only graphic panel T if RB8 bit SPI T6963C graphics 1 SPI T6963C text 0 Delay ms 300 ifdef COMPLETE EXAMPLE If RB9 is pressed toggle the display between graphic panel 0 and graphic panel 1 Ey else if RB9 bit panel panel amp 1 SPI T6963C displayGrPanel panel Delay ms 300 fendif jf Tf RB10 is pressed display only text panel af else if RB10 bit SPI T6963C graphics 0 SPI T6963C text 1 Delay ms 300 f If RB11 is pressed display text and graphic panels rd else if RB11 bit SPI T6963C graphics 1 SPI T6963C text 1 Delay ms 300 If RB12 is pressed change cursor wf else if RB12 bit curstt if curs 3 curs 0 switch curs case 0 no cursor SPI T6963C cursor 0 break case 1 blinking cursor 533 MikroElektronika mikoC PRO for PIC32 SPI T6963C cursor 1 SPI T6963C cursor blink 1 break case
162. 000 VDelay Advanced ms pause fosc Generates approximately one second pause for a oscillator frequency of 10 MHz Delay Cyc Prototype void Delay Cyc unsigned int x unsigned int y y remainder of the NumberOfCycles 16384 division Rems Nom OOS Example Delay Cyc 1 10 1x16384 10 16394 cycles pause Delay Cyc is a library function rather than a built in routine it is presented in this topic for the sake of convenience Delay Cyc Long void Delay Cyc Long unsigned long CycNo tms Nang Example Delay Cyc Long 16394 16394 cycles pause Delay Cyc Long is a library function rather than a built in routine it is presented in this topic for the sake of convenience MikroElektronika 152 mikroC PRO for PIC32 Clock kHz Prototype unsigned long Clock kHz Description 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 unsigned long clk Clock_Mhz Prototype unsigned long Clock MHz Description Function returns device clock in MHz 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 Returns Devi
163. 08 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 If a pointer is declared to point to type adding an integral value n to the pointer increments the pointer value by n sizeof type as long as the pointer remains within the legal range first element to one beyond the last element If type has a size of 10 bytes then adding 5 to a pointer to t ype advances the pointer 50 bytes in memory In case of the void type the size of a step is one byte For example int a 10 array a containing 10 elements of type int int pa amp a 0 pa is pointer to int pointing to a 0 pa 3 6 pat3 is a pointer pointing to a 3 so a 3 now equals 6 patt pa now points to the next element of array a a l There is no such element as one past the last element of course but the pointer is allowed to assume such value C guarantees that the result of addition is defined even when pointing to one element past array If points to the last array element P 1 is legal but P 2 is undefined This allows you to write loops which access the array elements in a sequence by means of incrementing pointer in the last iteration you will have the pointer pointing to one element p
164. 1 Chip Select 1 Chip Select Direction 0 So DAC increments 0 4095 void DAC Output unsigned int valueDAC ch Ch ft SPI Init ar temp ip Select 0 Send High Byte mp valueDAC gt gt 8 amp OxOF te te Soft SPI Write temp mp 0x30 Send Low Byte te Soft SPI Write temp Ch mp valueDAC ip Select 1 void main CHECON 0x32 ADIPCFG OxFFFF InitMain value 2048 while 1 if RBO bit amp amp value lt 4095 value else if RB1 bit amp amp value DAC_Output value Delay ms 1 value gt 0 gt output Jd d d ut Zr Ly LE a A d d d ra d ea a Set RBO pin as input Set RB1 pin as input Deselect DAC Set CS pin as Output Initialize Soft_SPI voltage 0 Vref Select DAC chip Store valueDAC 11 8 to temp 3 0 Define DAC setting see MCP4921 datasheet Send high byte via Soft SPI Store valueDAC 7 0 to temp 7 0 Send low byte via Soft SPI Deselect DAC chip Configure AN pins as digital Perform main initialization When program starts DAC gives the output in the mid range Endless loop If RBO button is pressed increment value If RB1 button is pressed decrement value Send value to DAC chip Slow down key repeat pace MikroElektronika 424 mikroC PRO for PIC32 Software UART Library The mi
165. 2 long epoch long diff void main tsl ss 0 tsl mn 7 tsl hh 17 tsl md 23 tsl mo 5 tsl yy 2006 What is the epoch of the date in ts ye epoch Time dateToEpoch amp ts1 1148404020 y What date is epoch 1234567890 a epoch 1234567890 Time epochToDate epoch amp ts2 if 0X1E OxIF 0x17 0x0D How many seconds there are between these two dates Hye diff Time dateDiff amp tsl amp ts2 86163870 0x02 0x07D9 MikroElektronika mikoC PRO for PIC32 Trigonometry Library The mikroC PRO for PIC32 implements fundamental trigonometry functions These functions are implemented as look up tables Trigonometry functions are implemented in integer format in order to save memory Library Routines sinE3 cosE3 sinE3 Prototype int sinE3 unsigned angle deg Description The function calculates sine multiplied by 1000 and rounded to the nearest integer result round sin angle deg 1000 angle deg input angle in degrees Returns The function returns the sine of input parameter multiplied by 1000 mE E3 45 result is 707 Return value range 1000 1000 cosE3 Prototype int cosE3 unsigned angle deg Description The function calculates cosine multiplied by 1000 and rounded to the nearest integer result round cos angle deg 1000 angle deg input angle in degrees Returns The function returns the cosine of
166. 247600 CS at RFI bit sfr sbit SPI Ethernet 247600 CS Direction at TRISF1 bit end ethernet NIC definitions unsigned char myMacAddr 6 0x00 0x14 0xA5 0x76 0x19 Ox3f my MAC address unsigned char myIpAddr 192 168 1 60 my IP addr SPITI Inzt SPI Ethernet 243600 Init myMacAddr myIpAddr Ethernet 243600 MANUAL NEGOTIATION amp SPI Ethernet 243600 FULLDUPLE SPI Ethernet 243600 SPD100 MikroElektronika A10 mikroC PRO for PIC32 SPI Ethernet 24j600 Enable Prototype void SPI Ethernet 24600 Enable unsigned int enFlt Description This is MAC module routine This routine enables appropriate network traffic on the ENC24J600 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be enabled if a corresponding bit of this routine s input parameter is set Therefore more than one type of network traffic can be enabled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Advanced filtering available in the ENC24J600 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration o
167. 29 MikroElektronika mikoC PRO for PIC32 CHAPTER 1 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 TUNI T Wr AP P NEPOS NITET PERO 701 1 dioe em ee mo oom mc DDR ADADI wu Y caa gare em 0 aet 0 pote Chr rete D ya eee meve Decent 6 H Paim und Fes onal moring isalo BR 9 u 759 4 4 S LI ee 7 Jai meee pagans Tow cm change the mrang apum 4 r x D tm Ohne E ae Dos m LEE In tin PA lar E 00 WIUXACDIUNMBMNNNNENENENUIOTUIEIIUECITUISIINMMA X X X 8 Geen T7 bis gt c UD 34 Dust LI t nem mataas tct n z umm te nme ie mhi SCR CORP Gem anne Dome i OF a d led mdi DOR ODOR YI ji 6v vtm Oa ge s led Own Su terga oe nent dn Foe m aa ten 8 1 pe ae 2 Sa ded Ov 2 6 bnt te ia somai me dl hes Q awt uD P ene Loa Omai LC eua Came sinpi e wor wen PT B M Pr i Jij rase 214 z bu We e o ptt f onthe m em raf dem im ctt i ntt mn p an Ol feria tote am 4 LIA RN PE ne fo o it Ont DOD SHUT and m 5 gt gt al M EN Bem Pimp c M Me ap be Dnm va e e
168. 3 dereferencing to obtain the value Types Conversions The mikroC PRO for PIC32 is a strictly typed language with each operator statement and function demanding appropriately typed operands arguments However we often have to use objects of mismatching types in expressions In that case type conversion is needed Conversion of object of one type means that object s type is changed into another type The mikroC PRO for PIC32 defines a set of standard conversions for built in types provided by compiler when necessary For more information refer to the Standard Conversions Conversion is required in the following situations if a statement requires an expression of particular type according to language definition and we use an expression of different type if an operator requires an operand of particular type and we use an operand of different type if a function requires a formal parameter of particular type and we pass it an object of different type if an expression following the keyword return does not match the declared function return type if intializing an object in declaration with an object of different type In these situations compiler will provide an automatic implicit conversion oftypes without any programmer s interference Also the programmer can demand conversion explicitly by means of the typecast operator For more information refer to the Explicit Typecasting 219 MikroElektronika mi
169. 32 ADIPCFG OxFFFF Configure AN pins as digital I O TRISB OxFFFF configure PORTB pins as input PORTD 0 set PORTD to 0 TRISD 0 designate PORTD pins as output void main InitMain current duty 100 initial value for current duty current dutyl 100 initial value for current dutyl pwm periodl PWM Init 5000 1 1 2 pwm period2 PWM Init 10000 2 1 3 PWM Start 1 PWM Start 2 PWM Set Duty current duty 1 Set current duty for PWM1 PWM Set Duty current dutyl 2 Set current duty for PWM2 while 1 endless loop if RBO bit button on RBO pressed Delay ms 1 current duty current duty 5 increment current duty if current duty gt pwm periodl if we increase current duty greater then possible pwm periodi value current duty 0 reset current duty value to zero PWM Set Duty current duty 1 set newly acquired duty ratio if RB1 bit button on RB1 pressed Delay ms 1 current duty current duty 5 decrement current duty if current duty gt pwm periodl if we decrease current duty greater then possible pwm periodl value overflow current duty pwm periodl set current duty to max possible value PWM Set Duty current duty 1 set newly acquired duty ratio 403 MikroElektronika mikoC PRO for PIC32 if RB2 bit button on RB2 pressed Delay ms 1 current dutyl current dutyl 5 increment current
170. 4 instruction words A page of Flash is the smallest unit of memory that can be erased at a single time The program Flash array can be programmed in one of two ways Row programming with 128 instruction words at a time Word programming with 1 instruction word at a time The CPU stalls waits until the programming operation is finished The CPU will not execute any instruction or respond to interrupts during this time If any interrupts occur during the programming cycle they remain pending until the cycle completes Library Routines Flash Write Word Flash Write Row Flash Erase Page MikroElektronika 322 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 Nothing Requires Nothing Flash Write Row Prototype void Flash Write Row unsigned long address unsigned long rdata Description Writes one row in the program Flash memory 128 32 bit words or 512 bytes on the designated address Parameters address address of the FLASH memory word rdata data to be written Nothing Requires Nothing Noes Nme oS Flash Erase Page Prototype void Flash Erase Page unsigned long address Erases one page 8 rows 1024 32 bit word 4096 bytes f
171. 42 443 443 445 446 447 447 448 448 MikroElektronika 18 mikroC PRO for PIC32 SPI Ethernet putString 448 SPI Ethernet putConstString 449 SPI Ethernet getByte 449 SPI Ethernet getBytes 449 SPI Ethernet UserTCP 450 SPI Ethernet UserUDP 451 SPI Ethernet getlpAddress 452 Ethernet getGwlpAddress 452 SPI Ethernet getDnslpAddress 452 SPI Ethernet getlpMask 453 SPI Ethernet confNetwork 453 SPI Ethernet arpResolve 454 SPI Ethernet sendUDP 454 SPI Ethernet dnsResolve 455 SPI Ethernet initDHCP 456 SPI Ethernet doDHCPLeaseTime 456 SPI Ethernet renewDHCP 457 Library Example 458 HW Connection 465 SPI Ethernet ENC24J600 Library 466 Library Dependency Tree 466 External dependencies of SPI Ethernet ENC24J600 Library 467 Library Routines 468 SPI Ethernet 24j600 Init 469 SPI Ethernet 24j600 Enable 471 SPI Ethernet 24j600 Disable 472 SPI Ethernet 24j600 doPacket 473 SPI Ethernet 24j600 putByte 473 SPI Ethernet 24j600 putBytes 474 SPI Ethernet 24j600 putConstBytes 474 SPI Ethernet 24j600 putString 475 SPI Ethernet 24j600 putConstString 475 SPI Ethernet 24j600 getByte 475 SPI Ethernet 24j600 getBytes 476 SPI Ethernet 24j600 UserTCP 476 SPI Ethernet 24j600 UserUDP 477 SPI Ethernet 24j600 getlpAddress 477 SPI Ethernet 24j600 getGwlpAddress 478 SPI Ethernet 24j600 getDnslpAddress 478 SPI Ethernet 24j600 getlpMask 479 SPI Ethernet 24j600 confNetwork 479 SPI Ethernet 24j600 arpResolve 480 SPI Ethernet 24j600 sendUDP 480 SPI Ethernet 24j
172. 43 T6963C write text 544 T6963C line 544 T6963C rectangle 545 T6963C rectangle round edges 545 T6963C rectangle round edges fill 546 T6963C box 546 T6963C circle 546 T6963C circle fill 547 T6963C image 547 T6963C Partiallmage 548 T6963C sprite 548 T6963C set cursor 549 T6963C clearBit 549 T6963C setBit 549 T6963C negBit 550 T6963C displayGrPanel 550 T6963C displayTxtPanel 550 T6963C setGrPanel 551 T6963C setTxtPanel 551 T6963C panelFill 551 T6963C grFill 552 T6963C txtFill 552 T6963C cursor height 552 T6963C graphics 553 T6963C text 553 T6963C cursor 553 T6963C cursor blink 554 Library Example 554 HW Connection 560 TFT Library 561 External dependencies of TFT Library 561 Library Routines 562 TFT Init 563 MikroElektronika 22 mikroC PRO for PIC32 TFT Set Index 564 TFT Write Command 564 TFT Write Data 564 TFT Set Active 565 TFT Set Font 566 TFT Write Char 567 TFT Write Text 567 TFT Fill Screen 568 TFT Dot 569 TFT Set Pen 570 TFT Set Brush 571 TFT_Line 573 TFT_H_Line 574 TFT_V_Line 574 TFT_Rectangle 574 TFT_Rectangle_Round_Edges 575 TFT_Circle 575 TFT_Image 575 TFT Partial Image 576 TFT Image Jpeg 576 TFT RGBToColor16bit 577 TFT Color16bitToRGB 577 HW Connection 578 Touch Panel Library 579 Library Dependency Tree 579 External dependencies of Touch Panel Library 579 Library Routines 579 TP Init 580 TP Set ADC Threshold 580 TP Press Detect 581 TP Get Coordinates 582 TP Calibrate Bottom Left 582 TP Ca
173. 43600 doDHCPLeaseTime Description This is DHCP module routine It takes care of IP address lease time by decrementing the global lease time library counter When this time expires it s time to contact DHCP server and renew the lease Parameters None 0 lease time has not expired yet 1 lease time has expired it s time to renew it Ethernet module has to be initialized See SPI Ethernet 24600 Init Ethernet 243600 doDHCPLeaseTime it s time to renew the IP address lease SPI_Ethernet_24j600_renewDHCP Prototype unsigned int SPI Ethernet 243600 renewDHCP unsigned char tmax This is DHCP module routine It sends IP address lease time renewal request to DHCP server tmax time in seconds to wait for an reply 1 upon success lease time was renewed 0 otherwise renewal request timed out Ethernet module has to be initialized See SPI_Ethernet_24j600_Init if SPI Ethernet 245 600 doDHCPLeaseTime SPI Ethernet 243600 renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply 483 MikroElektronika mikoC PRO for PIC32 SPI Graphic Lcd Library mikroC PRO for PIC32 provides a library for operating Graphic Lcd 128x64 with commonly used Samsung KS108 KS107 controller via SPI interface For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Important When using this library with PIC32 family MCUs be aware of th
174. 55555 equals 1 0x1234 equals OxEDCB 0x1234 equals 0 Conditional Operator The conditional operator is the only ternary operator in C Syntax of the conditional operator is expressionl expression2 expression3 The expression is evaluated first If its value is true then expression2 evaluates and expression is ignored If expressioni evaluates to false then expressions evaluates and expression2is ignored The result will be a value of either expression2 or expression3 depending upon which of them evaluates Conditional operator associates from right to left Note The fact that only one of these two expressions evaluates is very important if they are expected to produce side effects Here are a couple of practical examples Find max a b max a b a b Convert small letter to capital no parentheses are actually necessary g eX o2 Sal gc lt w o 9009 32 9 Conditional Operator Rules expression must be a scalar expression expression2 and expression3 must obey one of the following rules 1 Both expressions have to be of arithmetic type expression2 and expression3 are subject to usual arithmetic conversions which determines the resulting type 2 Both expressions have to be of compatible struct or union types The resulting type is a structure or union type of exoression2 and expression3 3 Both expressions have to be of void type The resulting type is void 4
175. 600 dnsResolve 481 SPI Ethernet 24j600 initDHCP 482 SPI Ethernet 24j600 doDHCPLeaseTime 483 SPI Ethernet 24j600 renewDHCP 483 19 MikroElektronika mikoC PRO for PIC32 SPI Graphic Lcd Library 484 Library Dependency Tree 484 External dependencies of SPI Lcd Library 484 Library Routines 484 SPI Glcd Init 485 SPI Glcd Set Side 486 SPI Glcd Set Page 486 SPI Glcd Set X 486 SPI Glcd Read Data 487 SPI Glcd Write Data 487 SPI Gled Fill 488 SPI Glcd Dot 488 SPI Glcd Line 489 SPI Glcd V Line 489 SPI Glcd H Line 490 SPI Glcd Rectangle 490 SPI Glcd Rectangle Round Edges 491 SPI Glcd Rectangle Round Edges Fill 491 SPI Glcd Box 492 SPI Glcd Circle 492 SPI Glcd Circle FIll 493 SPI Glcd Set Font 494 SPI Glcd Write Char 495 SPI Glcd Write Text 495 SPI Glcd Image 496 SPI Glcd Partiallmage 496 Library Example 497 HW Connection 499 SPI Lcd Library 500 Library Dependency Tree 500 External dependencies of SPI Lcd Library 500 Library Routines 500 SPI Lcd Config 501 SPI Lcd Out 501 SPI Lcd Out Cp 502 SPI Lcd Chr 502 SPI Lcd Chr Cp 502 SPI Lcd Cmd 503 Available SPI Lcd Commands 503 Library Example 504 Default Pin Configuration 504 SPI Lcd8 8 bit interface Library 506 Library Dependency Tree 506 External dependencies of SPI Lcd Library 506 Library Routines 506 SPI Lcd8 Config 507 MikroElektronika 20 mikroC PRO for PIC32 SPI Lcd8 Out 508 SPI Lcd8 Out Cp 508 SPI Lcd8 Chr 508 SPI Lcd8 Chr Cp 509 SPI Lcd8 Cmd 509 Avail
176. 6789abcdef unsigned int j Unsigned hexadecimal number using 0123456789ABCEDF double Floating point number using the format dddd dddd double Floating point number using the format d dddde dd E double Floating point number using the format d ddddE dd double Floating point number using either e or f format whichever is more compact for the specified value and precision int int is converted to an unsigned char and the resulting character is written String with a terminating null character Pointer value the X format is used A is written No argument is converted The complete conversion specification shall be The flags field is where a single character is used to justify the output and to print signs and blanks decimal points and octal and hexadecimal prefixes as shown in the following table Left justify the output in the specified field width Prefix the output value with or sign if the output is a signed type space Prefix the output value with a blank if it is a signed positive value Otherwise no blank is prefixed Prefix a non zero output value with 0 0x or 0x when used with o x and x field types respectively When used with the e E f g and G field types the flag forces the output value to include a decimal point In any other case the flag is ignored Ignore format specifier The width field is a non negative number that specifies a minimum number of printe
177. 6963C init 240 128 8 T6963C writeData Prototype void 76963C writeData unsigned char mydata Writes data to T6963C controller mydata data to be written Rems Nothing OOOO Example 269630 weitesten OOOO wtes fn OSS MikroElektronika 540 mikroC PRO for PIC32 T6963C writeCommand Prototype void T6963C writeCommand unsigned char mydata Writes command to T6963C controller mydata command to be written Toshiba Glcd module needs to be initialized See the T6963C init routine TEM ET T6963C writeCommand T6963C CURSOR POINTE T6963C setPtr Prototype void T6963C setPtr unsigned int p unsigned char c Sets the memory pointer for command p Parameters address where command should be written c command to be written Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C setPtr T6963C grHomeAddr start T6963C ADDRESS POINTER T6963C waitReady Prototype Pools the status byte and loops until Toshiba Glcd module is ready ums NM OOOO Example reeGcweimeay OOOO moes noe OOo 541 MikroElektronika mikoC PRO for PIC32 T6963C fill Prototype void 7T6963C fill unsigned char v unsigned int start unsigned int len Fills controller memory block with given byte Parameters v byte to be written start starting address of the memory block Len length of the memory block in bytes ums Noi OOOO Exam
178. 89abcdef unsigned int Unsigned hexadecimal number using 0123456789ABCEDF dewle Floating point number using the format dddd dddd o Pii point number using the format d dddde ERR number using the format d ddddE dd double Floating point number using either e or f format whichever is more compact for the specified value and precision D int is converted to an unsigned char and the EN character is written Sune with a terminating null character lt none gt A is written No argument is converted The complete conversion specification shall be The flags field is where a single character is used to justify the output and to print signs and blanks decimal points and octal and hexadecimal prefixes as shown in the following table Left justify the output in the specified field width Prefix the output value with or sign if the output is a signed type space Prefix the output value with a blank if it is a signed positive value Otherwise no blank is prefixed Prefix a non zero output value with 0 0x or 0x when used with o x and x field types respectively When used with the e E f c and G field types the flag forces the output value to include a decimal point In any other case the flag is ignored Ignore format specifier The width field is a non negative number that specifies the minimum number of printed characters If a number of characters in the outp
179. 90 Asterisk Pointer Declaration 190 Equal Sign 191 Pound Sign Preprocessor Directive 191 Concepts 192 Objects 192 Objects and Declarations 192 Lvalues 193 Rvalues 193 Scope and Visibility 193 Scope 193 Visibility 193 Name Spaces 194 Duration 195 Static Duration 195 Local Duration 195 Types 196 Type Categories 196 Fundamental Types 197 Arithmetic Types 197 Integral Types 197 MikroElektronika mikroC PRO for PIC32 Floating point Types 198 Enumerations 198 Enumeration Declaration 198 Anonymous Enum Type 199 Enumeration Scope 199 Void Type 200 Void Functions 200 Generic Pointers 200 Derived Types 200 Arrays 201 Array Declaration 201 Array Initialization 201 Arrays in Expressions 202 Multi dimensional Arrays 202 Pointers 203 Pointer Declarations 203 Null Pointers 204 Function Pointers 204 Assign an address to a Function Pointer 204 Function Pointers 206 Assign an address to a Function Pointer 206 Pointer Arithmetic 207 Arrays and Pointers 207 Assignment and Comparison 208 Pointer Addition 209 Pointer Subtraction 210 Structures 210 Structure Declaration and Initialization 210 Incomplete Declarations 211 Untagged Structures and Typedefs 212 Anonymous Structures 212 Working with Structures 213 Assignment 213 Size of Structure 213 Structures and Functions 213 Structure Member Access 214 Accessing Nested Structures 215 Structure Uniqueness 215 Unions 216 Union Declaration 216 Size of Union 216 Union Memb
180. 963C displayGrPanel 0 Draw a sprite Select other graphic panel 128 mikrol E 240x128 bmp Display partial 997 MikroElektronika mikoC PRO for PIC32 for Endless loop JE If RB8 is pressed display only graphic panel 7d if RB8 bit T6963C graphics 1 T6963C text 0 Delay ms 300 Tf RBI is pressed toggle the display between graphic panel 0 and graphic panel 1 ud else if RB9 bit panel t panel amp 1 T6963C displayGrPanel panel Delay ms 300 If RB10 is pressed display only text panel ey else if RB10 bit T6963C graphics 0 T6963C text 1 Delay ms 300 Tf RB11 is pressed display text and graphic panels ura else if RB11 bit T6963C graphics 1 T6963C text 1 Delay ms 300 If RB12 is pressed change cursor a else if RB12 bit CurS tt if curs 3 curs 0 switch curs case 0 no cursor T6963C cursor 0 break case 1 blinking cursor T6963C cursor 1 T6963C cursor blink 1 MikroElektronika 558 mikroC PRO for PIC32 break case 2 non blinking cursor T6963C cursor 1 L6963C cursor blink 0 break Delay ms 300 ifdef PAR TIAL IMAGE DEMO P If RC13 is pressed perform the ad else if RB13 bit n Partial image L6963C setGrPanel 0 6963C_ setTxtPanel 6963C txtFill 0 6963C_setGrPanel
181. AME amp with CANSPIWrite CANSPI TX NO RTR FRAME MikroElektronika 284 mikroC PRO for PIC32 Can Init Flags CANSPI CONFIG SAMPLE THRICE amp CANSPI CONFIG PHSEG2 PRG ON amp CANSPI CONFIG XTD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG amp CANSPI CONFIG LINE FILTER OFF Initialize SPI2 module SPI2 Init Delay ms 10 CANSPIInitialize 1 3 3 3 1 Can Init Flags FL CANSPISetOperationMode _CANSPI_MOD E CONFIG OxFF form value to be used with CANSPIInit initialize external CANSPI module set CONFIGURATION mode set all maskli bits to set all mask2 bits to CANSPISetMask CANSPI MASK Bl 1 CANSPI CONFIG XTD MSG ones CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG ones CANSPISetFilter CANSPI FILTER B2 F3 ID 1st CANS PI CONFIG XTD MSG set id of filter B2 F3 to 1st node ID CANSPISetOperationMode CANSPI MODE NORMAL OxFF while 1 Msg Rcvd CANSPIRead amp Rx ID RxTx Data message if Rx ID ID 1st amp amp Msg Revd PORTB RxTx Data 0 RxTx Data O Ju CANSPIWrite ID 2nd RxTx Data amp Rx Data Len set NORMAL mode endless loop amp Can Rcv Flags receive if message received check id id correct output data at PORTC increment received data 1 Can Send Flags send incremented data back
182. ANSPI TX RTR FRAME OxBF XOXXXXXX You may use bitwise AND amp to adjust the appropriate flags For example Copy Code To Clipboard form value to be used as sending message flag send config CANSPI TX PRIORITY 0 amp CANSPI TX XTD FRAME amp CANSPI TX NO RTR FRAME CANSPIWrite id data 1 send config CANSPI RX MSG FLAGS Constants CANSPI RX MSG FLAGS are flags related to reception of CANSPI message If a particular bit is set then corresponding meaning is TRUE or else it will be FALSE 281 MikroElektronika mikoC PRO for PIC32 Copy Code To Clipboard const unsigned int CANSPI RX FILTER BITS 0x07 Use this to access filter bits CANSPI RX FILTER 1 0x00 CANSPI RX FILTER 2 0x01 CANSPI RX FILTER 3 0x02 CANSPI RX FILTER 4 0x03 CANSPI RX FILTER 5 0x04 CANSPI RX FILTER 6 0x05 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 0x40 Set if RTR message else cleared CANSPI RX DBL BUFFERED 0x80 Set if this message was hardware double buffered You may use bitwise AND s to adjust the appropriate flags For example Copy Code To Clipboard if MsgFlag amp CANSPI RX OVERFLOW 0 Receiver overflow has occurred
183. B7 RB3 as input Play sound at 880Hz for 1 second RB7 plays Tonel Wait for button to RB6 plays Tone2 Wait for button to RB5 plays Tone3 Wait for button to RB4 plays Melody2 Wait for button to RB3 plays Melody Wait for button to be be be be be released released released released released 429 MikroElektronika 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 Library Routines Sound Init Sound Play Sound Init Prototype void Sound Init unsigned int snd port unsigned int b gt snd pin Configures the appropriate MCU pin for sound generation Parameters snd port sound output port address snd pin sound output pin Initialize the pin RC3 for playing sound Sound Init amp PORTD 3 maes Nae T Sound Play dias void Sound Play unsigned int freq in hz unsigned int b duration ms Generates the square wave signal on the appropriate pin Parameters freq in hz signal frequency in Hertz Hz duration ms signal duration in miliseconds ms Requires In order to hear the sound you need a piezo speaker or other hardware on designated port Also you must call Sound Init to p
184. Build 47 Build Menu Options 47 Run 48 Run Menu Options 48 Tools 49 Tools Menu Options 49 Help 50 Help Menu Options 50 MikroElektronika mikroC PRO for PIC32 mikroC PRO for PIC32 IDE 51 IDE Overview 51 Code Editor 52 Editor Settings 52 Auto Save 53 Highlighter 53 Spelling 53 Comment Style 53 Code Folding 53 Code Assistant 54 Parameter Assistant 54 Bookmarks 54 Go to Line 54 Column Select Mode 55 Editor Colors 55 Auto Correct 56 Auto Complete Code Templates 57 Code Explorer 59 Routine List 60 Project Manager 60 Project Settings 62 Library Manager 63 Managing libraries using Package Manager 64 Routine List 65 Statistics 65 Memory Usage Windows 65 Variables 66 Used RAM Locations 66 SFR Locations 67 ROM Memory Usage 67 ROM Memory Constants 68 Functions 68 Functions Sorted By Name Chart 69 Functions Sorted By Size Chart 69 Functions Sorted By Addresses 70 Function Tree 70 Memory Summary 71 Messages Window 72 Quick Converter 73 Macro Editor 73 Image Preview 74 Toolbars 76 File Toolbar 77 Edit Toolbar 77 Advanced Edit Toolbar 78 MikroElektronika mikoC PRO for PIC32 Find Replace Toolbar Project Toolbar Build Toolbar Debug Toolbar Styles Toolbar Tools Toolbar View Toolbar Layout Toolbar Help Toolbar Customizing IDE Layout Docking Windows Saving Layout Auto Hide Options Code editor Tools Output settings Integrated Tools Active Comments Editor ASCII Chart EEPROM Edit
185. C bat 1 In this way if the Zero bit changes its register or position in the register you are sure that the appropriate bit will be affected For backward compatibility you can access bits in this way also Clear TRISB3 TRISBbits TRISB3 0 MikroElektronika 138 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 You can declare a sbit variable in a unit in such way that it points to a specific bit in SFR register extern sfr sbit Abit Abit is precisely defined in some external file for example in the main program unit In the main program you have to specify to which register this sbit points to for example sbit Abit at PORTB B0 this is where Abit is fully detined void main In this way the variable Abit will actually point to PORTB 0 Please note that we used the keyword s x for declaration of Abit because we are pointing it to PORTB which is defined as a s fr variable Note Declaring a sbit variable is not possible via FO F1 F31 identifiers In case we want to declare a bit over a variable which is not defined as sfr then the keyword sfr is not necessary for example extern sbit AnotherBit AnotherB
186. C24J600 buffer SPI Ethernet 24j600 getByte Prototype unsigned char SPI Ethernet 24j600 getByte Description This is MAC module routine It fetches a byte from address pointed to by current ENC247600 read pointer ERDPT Parameters None Byte read from ENC247600 RAM Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init char buffer buffer SPI Ethernet 243600 getByte read a byte from ENC24J600 buffer 475 MikroElektronika mikoC PRO for PIC32 SPI Ethernet 24j600 getBytes Prototype void SPI Ethernet 243600 getBytes unsigned char ptr unsigned int addr unsigned int n Description This is MAC module routine It fetches equested number of bytes from xNC243600 RAM starting from given address If value of OxFFFF is passed as the address parameter the reading will start from current ENC24J600 read pointer ERDPT location Parameters ptr buffer for storing bytes read from ENC245600 RAM addr ENC247600 RAM start address Valid values 0 8192 n number of bytes to be read Ethernet module has to be initialized See SPI Ethernet 24j600 Init char buffer 16 SPI Ethernet 24j600 getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 SPI Ethernet 24j600 UserTCP Prototype unsigned int SPI Ethernet 245600 UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int r
187. C32 Cf Fat Reset Prototype void Cf Fat Reset unsigned long size 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 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 guid long size Cf Fat Reset size Cf_Fat_Read Prototype void Cf Fat Read unsigned short bdata Description Reads a byte from currently assigned file opened for ie Upon function execution file pointers will be set to the next character in the file bdata buffer to store read byte to Upon this function execution read byte is returned through this parameter 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 reading See Cf_Fat_Reset char character Cf Fat Read amp character MikroElektronika 296 mikroC PRO for PIC32 Cf Fat Rewrite Description Opens currently assigned file for writing If the file is not empty its content will be erased Parameters None Nothing Requires CF card and CF library must be initialized for file operations See Cf Fat Init Prototype void Cf Fat Rewrite The file must be previously assigned See Cf Fat Assign open file for writing Cf Fat Rewr
188. CANSPI CONFIG STD MSG OxFF Af XXKXIXXX CANSPI CONFIG XTD MSG OxF7 ft XXXXODXXX CANSPI CONFIG DBL BUFFER BIT 0x10 CANSPI CONFIG DBL BUFFER ON OxFF XXX1XXXX CANSPI CONFIG DBL BUFFER OFF OxEF LL XXXOXXXX CANSPI CONFIG MSG BITS 0x60 CANSPI CONFIG ALL MSG OxFF Af BUTRRERX CANSPI CONFIG VALID XTD MSG OxDF ff XIOXXXXX CANSPI CONFIG VALID STD MSG OxBF ZZ XOTXXXXX CANSPI CONFIG ALL VALID MSG 0x9F ZZ XO0XXXXX MikroElektronika 280 mikroC PRO for PIC32 You may use bitwise AND s 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 amp CANSPI CONFIG LINE FILTER OFF DOM HS HS CANSPLingti 1 1 3 3 Ly ances initialize CANSPI CANSPI_TX_MSG_FLAGS Constants CANSPI TX MSG FLAGS are flags related to transmission of a CANSPI message Copy Code To Clipboard const unsigned int _CANSPI_TX PRIORITY BITS 0x03 _CANSPI_TX PRIORITY 0 OxFC XXXXXX00 _CANSPI_TX PRIORITY 1 OxFD XXXXXX01 _CANSPI_TX PRIORITY 2 OxFE XXXXXX10 _CANSPI_TX PRIORITY 3 OxFF XXXXXX11 CANSPI TX FRAME BIT 0x08 CANSPI TX STD FRAME OxFF Jy XXNXXIXX CANSPI TX XTD FRAME OxF7 XXXXX0XX CANSPI TX RTR BIT 0x40 CANSPI TX NO RTR FRAME OxFF A KINO C
189. Config Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections sbit SPExpanderRST at LATFO bit sbit SPExpanderCS at LATF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI1 module SPIL Init Initialize SPI module used with PortExpander SPI Lcd8 Config 0 intialize Lcd in 8bit mode via SPI 507 MikroElektronika mikoC PRO for PIC32 SPI Lcd8 Out Aai void SPI Lcd8 Out unsigned short row unsigned short column char text 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 Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routine Write text Hello on Lcd starting from row 1 column 3 SPE Beds Out l1 3 Hello j SPI Lcd8 Out Cp Prototype Prints text on Lcd at current cursor position Both string variables and literals can be passed as a text
190. D m m ws Om 28 r Pu i 8E m 10K Pin diagram of CF memory card vcc mikroC PRO for PIC32 Epson S1D13700 Graphic Lcd Library The mikroC PRO for PIC32 provides a library for working with Gleds 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 It includes 32K bytes of embedded SRAM display memory which is used to store text character codes and bit mapped graphics The S1D13700 Glcd handles display controller functions including Transferring data from the controlling microprocessor to the buffer memory Reading memory data converting data to display pixels Generating timing signals for the LCD panel The S1D13700 Glcd is designed with an internal character generator which supports 160 5x7 pixel characters in internal mask ROM CGROM and 64 8x8 pixel characters incharacter generator RAM CGRAM When the CGROM is not used up to 256 8x16 pixel characters are supported in CGRAM External dependencies of the Epson S1D13700 Graphic Lcd Library The following variables must be defined in all projects using S1D13700 Graphic Description Lcd library extern sfr sbit 3 1D13700 DATA Direction of the system data bus sbit S1D13700 DATA Di
191. D5 D6 D7 Direction of the Chip Select 2 pin extern stir sbit GLCD RW sbit GLCD RW Direction Direction of the Read Write pin Direction DIE extern Sfr sbit GLCD EN sbit GLCD EN Direction i Direction of the Enable pin a Direction DIt extern sfr sbit GLCD RST sbit GLCD RST Direction at 1 Direction of the Reset pin Direction bat 329 MikroElektronika mikoC PRO for PIC32 Library Routines Basic routines Glcd Init Glcd Set Side Glcd Set X Gled Set Page Glcd Read Data Gled Write Data Advanced routines Glcd Fill Glcd Dot Gled Line Glcd V Line Gled H Line Glcd Rectangle Gled Rectangle Round Edges Gled Rectangle Round Edges Fill Gled Box Gled Circle Gled Circle Fill Gled Set Font Gled Write Char Glcd Write Text Gled Image Glcd Partiallmage Glcd Init Prototype Description Initializes the Glcd module Each of the control lines are both port and pin configurable while data lines must be on a single port pins lt 0 7 gt Requires Global variables GLCD DO Data pin 0 D1 Data pin 1 D2 Data pin 2 03 Data pin 3 D4 Data pin 4 D5 Data pin 5 D6 Data pin 6 D7 Data pin 7 CS1 Chip select 1 signal pin CS2 Chip select 2 signal pin RS Register select signal pin RW Read Write Signal pin
192. D6 Direction at TRISB6 bit sbit LCD D7 Direction at TRISB7 bit End LCD module connections Manchester module connections sbit MANRXPIN at RFO bit sbit MANRXPIN Direction at TRISFO bit sbit MANTXPIN at LATF1 bit sbit MANTXPIN Direction at TRISF1 bit End Manchester module connections unsigned int error char ErrorCount chr counter byte rcvd void main ErrorCount 0 chr counter 0 CHECON 0x32 ADIPCFG OxFFFF TRISB 0 LATB 0 Led_Init Lcd Cmd LCD CLEAR Man Receive Init while 1 Lcd Cmd LCD FIRST ROW while 1 byte rcvd Man Receive amp error if byte rcvd OxO0B Configure AN pins as digital I O Initialize LCD Clear LCD display Initialize Receiver Endless loop Move cursor to the 1st row Wait for the start byte Attempt byte receive Start byte see Transmitter example MikroElektronika mikoC PRO for PIC32 break We got the starting sequence if error Exit so we do not loop forever break do byte rcvd Man Receive amp error Attempt byte receive if error If error occured Led Chr GP V Write question mark on LCD ErrorCountt Update error counter if ErrorCount gt 20 In case of multiple errors Man Synchro Try to synchronize again Man Receive Init Alternative try to Initialize Receiver again ErrorCount
193. DEBUG VER CPO DEBUG DDBLIMPR CPO DEBUG DDBSIMPR CF TRACEOONTRGL ASD Fa TACEN SP CPO_CONFIG1_IS CPO CONFIG1 MMUSIZE CPO0 CONFIG1 M CPO0 CONFIG2 M CPO CONFIG3 TL CPO CONFIG3 SM CPO0 CONFIG3 SP CPO_CONFIG3_VINT CPO_CONFIG3_VEIC CPO CONFIG3 ITL CPO CONFIG3 M CPO0 DEBUG DSS CP0 DEBUG DBP CPO DEBUG DDBL CPO DEBUG DDBS 157 MikroElektronika 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 3 5 gt 8 Constant propagation When a constant value is being assigned to a certain variable the compiler recognizes this and replaces the use of the variable by constant in the code that follows as long as the value of a variable remains unchanged Copy propagation The compiler recognizes that two variables have the same value and eliminates one of them further in the code Value numbering The compiler recognizes if two expressions yield the same result and can therefore eliminate the entire computation for one of them Dead code ellimination The code snippets that are not being used elsewhere in the programme do not affect the final result of the application They are automatically removed Stack allocation Temporary registers Stacks are being used more
194. Data Prototype void TFT Write Data unsigned int data Description Writes date into display memory Parameters data data to be written TFT module needs to be initialized See the TFT Init routine Send data TFT Write Data 0x02 MikroElektronika 564 mikroC PRO for PIC32 TFT Set Active Prototype void TFT Set Active void Set Index Ptr unsigned short void Write Command Ptr unsigned short void Write Data Ptr unsigned int Nothing Description This function sets appropriate pointers to a user defined basic routines in order to enable multiple working modes Parameters Set Index Ptr Set Index handler Write Command Ptr Write Command handler Write Data Ptr Write Data handler Example of establishing 16 bit communication between TFT display and PORTD PORTE of MCU void Set Index unsigned short index T RS 0 LATD index lr WR 0 void Write _ Command unsigned short cmd TFT_RS 1 Lo LATD cmd TFT WR 0 TET 44 void Write Data unsigned int data TFT RS 1 Lo LATE Hi data Lo LATD Lo _ data WR TFT WR void main TRISE 0 TRISD 0 TFT Set Active Set Index Write Command Write Data IET Init 320 240 565 MikroElektronika mikoC PRO for PIC32 TFT Set Font Prototype void TFT Set Font const char far activeFont unsigned int font color char font or
195. Data 6 pin D7 Direction Direction of the Data 7 pin must be defined before using this function Lcd module connections sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit LC nc LC LC LC LC LC LC LC LC LC LC at at at at at at Led Int LATDO bit LATD1 bit LATBO bit LATB1 bit LATB2 bit LATB3 bit Direction at TRISDO bit EN Direction at TRISD1 bit D4 Direction at TRISBO bit D5 Direction at TRISBI bit D6 Direction at TRISB2 bit D7 Direction at TRISB3 bit End Lcd module connections 349 MikroElektronika mikoC PRO for PIC32 Lcd Out DE void Lcd Out unsigned int row unsigned int column char text 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 The Lcd module needs to be initialized See Lcd Init routine Z6 gaan text Hello on Lcd starting from row 1 column 3 Lcd Out 3 Hello Notes None Lcd Out Cp Prototype void Lcd Out Cp char text Retums Nothing Prints text on Lcd at current cursor position Both string variables and literals can be passed as a text text text to be written The Lcd module needs to be initialized See Lcd Init routine Write text Here at current cursor position Led Out Cp Here
196. Draw rectangles ur fifdef LINE DEMO SPI T6963C rectangle 0 0 239 127 SPI T6963C WHITE SPI T6963C rectangle 20 20 219 107 SPI T6963C WHITE SPI T6963C rectangle 40 40 199 87 SPI T6963C WHITE SPI T6963C rectangle 60 60 179 67 SPI T6963C WHITE fendif Draw rounded edge rectangle a ifdef LINE DEMO SPI T6963C Rectangle Round Edges 10 10 229 117 12 SPI T6963C WHITE SPI T6963C Rectangle Round Edges 30 30 209 97 12 SPI T6963C WHITE SPI T6963C Rectangle Round Edges 50 50 189 77 12 SPI T6963C WHITE fendif Draw filled rounded edge rectangle ey ifdef FILL DEMO SPI T6963C Rectangle Round Edges Fill 10 10 229 117 12 SPI T6963C WHITE SPI T6963C Rectangle Round Edges Fill 20 20 219 107 12 SPI T6963C BLACK SPI T6963C Rectangle Round Edges Fill 30 30 209 97 12 SPI T6963C WHITE SPI T6963C Rectangle Round Edges Fill 40 40 199 87 12 SPI T6963C BLACK SPI T6963C Rectangle Round Edges Fill 50 50 189 77 12 SPI T6963C WHITE fendif Draw a Cross af 931 MikroElektronika mikoC PRO for PIC32 ifdef LINE DEMO SPI T6963C line 0 0 239 127 SPI 7 SPI T6963C line 0 127 fendif Draw circles P ifdef LINE DEMO SPI T6963C circle 120 SPI T6963C circle 120 SPI T6963C circle 120 SPI T6963C circle 120 SPI T6963C circle 120 SPI T6963C circle 120 SPI T6963C circle 120 fendif
197. E 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 ASSOCIATESHASBEENADVISED OF THE POSSIBILITY OF SUCH DAMAGES INANY CASE MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY UNDER ANY PROVISION OF THIS LICENSE AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR SOFTWARE PRODUCT PROVIDED HOWEVER IF YOU HAVE ENTERED INTOAMIKROELEKTRONIKAASSOCIATES SUPPORT SERVICES AGREEMENT MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOVERNED BY THE TERMS OF THAT AGREEMENT HIGH RISK ACTIVITIES Software is not fault tolerant and is not designed manufactured or intended for use or resale as on line control equipment in hazardous environments requiring fail safe performance such as in the operation of nuclear facilities aircraft navigation or communication systems air traffic control direct life support machines or weapons systems in which the failure of Software could lead directly to death personal injury or severe physical or environmental damage High Risk Activities mikroElektronika Associates and its suppliers specifically disclaim any expressed or implied warranty of fitness f
198. Elektronika 200 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 Array Declaration Array declaration is similar to variable declaration with the brackets added after identifer type array name constant expression This declares an array named as array name and composed of elements of type The type can be any scalar type except void user defined type pointer enumeration or another array Result of constant expression Within the brackets determines a number of elements in array If an expression is given in an array declarator it must evaluate to a positive constant integer The value is a number of elements in an array Each of the elements of an array is indexed from 0 to the number of elements minus one If a number of elements is n elements of array can be approached as variables array name 0 array name n 1 Of type Here are a few examples of array declaration define MAX 50 int vector one 10 declares an array of 10 integers float vector two MAX declares an array of 50 floats float vector three MAX 20 declares an array of 30 floats Array Initialization An array can be initialize
199. I C module Used I C module must be initialized before using this function See I2Cx Init routine Issue START signal TACI Start PC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library 339 MikroElektronika mikoC PRO for PIC32 I2Cx Restart ums Wm OOOO Requires MCU with at least one I C module Used I C module must be initialized before using this function See I2Cx Init routine Issue RESTART signal I2C1 Restart C library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx Is Idle 1 if IC bus is not free Requires MCU with at least one I C module Used lC module must be initialized before using this function See I2Cx Init routine unsigned char data if I2CLl Is Idle I2C1 Write data FC library routines require you to specify the module you want to use To select the desired l C module simply change the letter x in the routine prototype for a number from 1 to 5 Number
200. I Ethernet 24j600 putConstString SPI Ethernet 24j600 putConstBytes SPI Ethernet 24j600 getByte SPI Ethernet 24j600 getBytes SPI Ethernet 24j600 UserTCP SPI Ethernet 24j600 UserUDP SPI Ethernet 24j600 getlpAddress SPI Ethernet 24j600 getGwlpAddress SPI Ethernet 24j600 getDnslpAddress SPI Ethernet 24j600 getlpMask SPI Ethernet 24j600 confNetwork SPI Ethernet 24j600 arpResolve SPI Ethernet 24j600 sendUDP SPI Ethernet 24j600 dnsResolve SPI Ethernet 24j600 initDHCP SPI Ethernet 24j600 doDHCPLeaseTime SPI Ethernet 24j600 renewDHCP MikroElektronika 468 mikroC PRO for PIC32 SPI Ethernet 24j600 Init Prototype Description Parameters void SPI Ethernet 243600 Init unsigned char mac unsigned char ip unsigned char fullDuplex This is MAC module routine It initializes ENC2 47600 controller This function is internaly splited into 2 parts to help linker when coming short of memory ENC24J600 controller settings parameters not mentioned here are set to default receive buffer start address 0x0000 receive buffer end address 0x19AD transmit buffer start address 0x19AE transmit buffer end address Ox1FFF RAM buffer read write pointers in auto increment mode receive filters set to default CRC MAC Unicast MAC Broadcast in OR mode flow control with TX and RX pause frames in full duplex mode frames are padded to 60 bytes CRC maximum
201. I Glcd Set Page Returns 5232 page number vaid vaes 7 lt Example 521 orca ser rages O OOOO Notes Forside x axis and page layout explanation see schematic atthe botom ofthis pags SPI Glcd Set X Sets x axis position to x pos dots from the left border of Glcd within the selected side Parameters x pos position on x axis Valid values 0 63 Glcd needs to be initialized for SPI communication see SPI Glcd Init routine SPI Gled Set X 25 Notes For side x axis and page layout explanation see schematic at the bottom of this page MikroElektronika 486 mikroC PRO for PIC32 SPI Glcd Read Data Prototype char SPI Glcd Read Data Description Reads data from the current location of Glcd memory and moves to the next location One byte from Glcd memory Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI Glcd Set X and SPI Glcd Set Page Parameters None char data SPI Glcd Write Data Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI Glcd Set X and SPI Glcd Set Page char data SPI Glcd Write Data data 487 MikroElektronika mikoC PRO for PIC32 SPI Glcd Fill Prot
202. I T6963C config unsigned int width unsigned char height unsigned char fntW char DeviceAddress unsigned char wr unsigned char rd unsigned char cd unsigned char rst Description Initializes T6963C Graphic Lcd controller Display RAM organization The library cuts RAM into panels a complete panel is one graphics panel followed by a text panel see schematic below Parameters width width of the Glcd panel height height of the Glcd panel ntW font width DeviceAddress SPI expander hardware address see schematic at the bottom of this page wr Write signal pin on Glcd control port rd read signal pin on Glcd control port cd command data signal pin on Glcd control port rst reset signal pin on Glcd control port Returns Nothing Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See the SPIx Init and SPIx Init Advanced routines 919 MikroElektronika mikoC PRO for PIC32 Port Expander module connections sbit SPExpanderRST at LATFO bit sbit SPExpanderCS at LATF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISFl bit End Port Expander module connections
203. IT X E a Generate HTML code suitable for publishing current source code on the web Find Replace Toolbar D222 Find Replace Toolbar is a standard toolbar with the following options r Find text in current editor FUR Franextoseurenoe 0 O r1 Replace text Find text in files MikroElektronika 18 mikroC PRO for PIC32 Project Toolbar Project Toolbar comes with the following options Don BesHpies New project Open Project Save Project UNI Edit project settings Close current project Clean project folder n Add File To Project Remove File From Project Build Toolbar 95 0 Build Toolbar comes with the following options Den Besdpon O E Build current project a Build all opened projects Build and program active project Start programmer and load current HEX file 79 MikroElektronika mikoC PRO for PIC32 Debug Toolbar Debug Toolbar comes with the following options Ten SSCS eto SSOSCS S SCS Eh Sart Sotware simiatorormioteD r creutDebuager O B sposo i O Ba ser Step Over E3 Step Out Dc LIC R LITTERE Styles Toolbar Styles toolbar allows you to easily change colors of your workspace Office 2003 Blue Office 2003 Blue Office 2003 Silver Office 2003 Olive Office XP 1 Chocolate Arctic Silverfox Soft sand MikroElektronika 80 mikroC PRO for PIC32 Tools
204. In bitfield declarator list you can omit identifier s to create an artificial padding thus skipping irrelevant bits For example if there is a need to manipulate only bits 2 4 of a register as one block create a structure like this struct unsigned 2 Skip bits 0 and 1 no identifier here mybits 3 Relevant bits 2 3 and 4 Bits 5 6 and 7 are implicitly left out myreg Here is an example typedef struct lo nibble 4 hi nibble 4 high byte 8 myunsigned which declares the structured type myunsigned containing three components 1o nibble bits 3 0 hi nibble bits 7 4 and high byte bits 15 8 MikroElektronika 218 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 gt 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 amp T2CON explicit casting of pointer to T2CON so it can be assigned Value For PortB lo nibble 7 Value For PortB hi nibble 0x0C Value For PortB high byte OxAA PORTB unsigned void Value_For PortB typecasting 1 address of structure to pointer to void 2 pointer to void to pointer to unsigned
205. Lr6963C setTxtPanel L6963C graphics 1 0 j I 0 E demostration mikroE 240x128 bmp kroE 240x128 bmp kroE 240x128 bmp T6963C text 1 T6963C displayGrPanel 1 T6963C write text txt2 5 15 T6963C ROM MODE XOR Delay 1sec T6963C grFill 0 T6963C Partiallmage 0 0 64 64 240 128 Delay lsec T6963C Partiallmage 0 0 128 128 240 128 mi Delay lsec T6963C Partiallmage 0 0 240 128 240 128 mi Delay lsec T6963C txtFill 0 T6963C write text txt 0 0 T6963C ROM MODE XOR T6963C write text txtl 0 15 T6963C ROM MODE XOR fendif Move cursor even if not visible ud Cposxtt if cposx T6963C txtCols cposx 0 cposytt if cposy T6963C grHeight T6963C CHARACTER HEIGHT cposy 0 T6963C set cursor cposx cposy Delay ms 100 MikroElektronika mikoC PRO for PIC32 HW Connection Toshiba T6963C Graphic LCD 240x128 8E Contrast Adjustment SPI T6963C Glcd HW connection MikroElektronika 560 mikroC PRO for PIC32 TFT Library Thin film transistor liquid crystal display TFT LCD is a variant of liquid crystal display LCD which uses thin film transistor TFT technology to improve image quality e g addressability contrast TFT LCD is one type of active matrix LCD though all LCD screens are based on TFT active matrix addressing TFT LCD
206. Mask 1 lt lt bitMask create bit mask LATD PORTD bitMask toggle PORTD with xor operator if len 0 what do to by default len putConstString httpHeader HTTP header len putConstString httpMimeTypeHTML with HTML MIME type len putConstString indexPage HTML page first part len putConstString indexPage2 HTML page second part return len return to the library with the number of bytes to transmit MikroElektronika 462 mikroC PRO for PIC32 this function is called by the library the user accesses to the UDP request by successive calls to Spi Ethernet getByte the user puts data in the transmit buffer by successive calls to Spi Ethernet putByte the function must return the length in bytes of the UDP reply or 0 if nothing to transmit if you don t need to reply to UDP requests just define this function with a return 0 as single statement ne unsigned int SPI Ethernet UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength TEthPktFlags flags unsigned int len we reply is made of the remote host IP address in ByteToStr remoteHost 0 dyna it dyna 3 ue ByteToStr remoteHost 1 dyna 4 LE dyna 7 ByteToStr remoteHost 2 dyna 8 Z4 dyna 11 ByteToStr remoteHost 3 dyna 12 ras dyna 15
207. MikroElektronika 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 ENC28360 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 Nothing Requires Ethernet module has to be initialized See SPI Ethernet Init char buffer mikroElektronika SPI Ethernet putBytes buffer 16 put an RAM array into ENC28J60 buffer SPI Ethernet putConstBytes Prototype void SPI Ethernet putConstBytes const unsigned char ptr unsigned int n Description This is MAC module routine It stores requested number of const bytes into ENC28760 RAM starting from current ENC2860 write pointer EWRPT location Parameters ptr const buffer containing bytes to be written into ENC28760 RAM n number of bytes to be written Nothing Ethernet module has to be initialized See SPI Ethernet Init const char buffer mikroElektronika SPI Ethernet putConstBytes buffer 16 put a const array into ENC28J60 buffer ENC28J60 RAM ENC28360 write pointer EWRPT location ptr String to be written into ENC28760 RAM Number of bytes written into ENC28760 RAM Ethernet module has to be initialized See SPI Et
208. Mode In this mode the CPU always vectors to the same address This means that only one ISR can be defined The Single Vector mode address is calculated by using the Exception Base EBase address its address default is OX9FCO01000E The exact formula for Single Vector mode is as follows Single Vector Address EBase 0x200 Multi Vector Mode In this mode the CPU vectors to the unique address for each vector number Each vector is located at a specific offset with respect to a base address specified by the EBase register in the CPU The individual vector address offset is determined by the following equation EBase Vector_Number x Vector_Space 0x200 By default the compiler configures interrupts in the Multi Vector mode with the EBase address set to 0x9FC01000 and vector spacing of 32 Configuring the Interrupt operating mode is performed in the Edit Project window 141 MikroElektronika 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 The subpriority will cause that when two interrupts with the same priority are
209. OMPLETE EXAMPLE comment this line to make simpler smaller example CHECON 0x32 ADIPCFG OxFFFF disable A D inputs Initialize UART1 module UART1 Init 56000 Delay _ms 10 UART1 Write Line MCU Started MCU present report use fat16 quick format instead of init routine if a formatting is needed if Cf Fat Init 0 Delay ms 2000 wait for a while until the card is stabilized period depends on used CF card 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 305 MikroElektronika mikoC PRO for PIC32 else UART1 Write Line err txt Note Cf Fat Init tries to initialize a card more than once If card is not present initialization may last longer depending on clock speed HW Connection LELELTLELELELELDLCLDLDLELDLELTL LLL oO nee EE RD2 RD CjRGi5 GND OSCRLATOR PIC32MX460F512L E vcc3 vcc3 VCC3 VCC3 ome heer m Nm 2 a5 7 49 a i EE E J E EE E l pe S Compact Flash a Card LJ bd Pa EESS 37 _ 3 2 EET
210. OxAA dat 1 OxF0 dat 2 OxOF dat 4 0 ensure that message received flag is 0 dat 5 0 ensure that error flag is 0 dat 6 0 M U2IP0 bit 1 U2IP1 bit U2IP2 bit 1 set interrupt priority to 7 m M8 MikroElektronika 40 mikroC PRO for PIC32 URXISEL1 U2STA bit received U2RXIF bit 0 MVEC bit 1 asm ei RO U2RXIE bit 1 0 ji 0x Interrupt flag bit is set when a character is ensure interrupt not pending Interrupt controller configured for multi vectored mode Enable all interrupts enable intterupt RS485Master Send dat 1 160 while 1 centtt if dat PORTD if dat 4 cnt 0 dat 4 j dat for i PORTB ll IH 0 3 i dat 0 Delay ms 1 i lt dat 3 dat i 1 dat 0 it 1 RS485Master Send dat 1 160 if cnt gt 100000 PORTD cnt 0 RS485Master Send dat 1 160 if PORTD gt 10 RS485Master Send dat 1 50 RS485 Slave code Copy Code To Clipboard char dat 9 char i j sbit sbit RS485 rxtx pin Interrupt routine void interrupt at RF2 bit RS485 rxtx pin direction at TRISF2 bit upon completed valid message receiving data 4 is set to 255 if an error detected signal it by setting portd to OxAA if message received successfully clear message received flag show data on PORTB
211. PI MODE NORMAL OxFF 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 amp Rx ID RxTx Data amp Rx Data Len amp Can Rcv Flags Pod receive message if Rx ID ID 2nd amp amp Msg Rcvd if message received check id PORTB RxTx Data 0 id correct output data at PORTC RxTx Data 0 increment received data Delay ms 10 CANSPIWrite ID lst RxTx Data 1 Can Send Flags send incremented data back Code for the second CANSPI node Copy Code To Clipboard unsigned char Can Init Flags Can Send Flags Can Rcv Flags can flags unsigned char Rx Data Len received data length in bytes char RxTx Data 8 can rx tx data buffer char Msg Rcvd reception flag const long ID Ist 12111 ID 2nd 3 node IDs long Rx ID CANSPI module connections sbit CanSpi CS at LATFO bit sbit CanSpi CS Direction at TRISFO bit sbit CanSpi Rst at LATF1 bit sbit CanSpi Rst Direction at TRISF1 bit End CANSPI module connections void main CHECON 0x32 ADIPCFG OxFFFF configure AN pins as digital I O PORTB 0 clear PORTB TRISB 0 set PORTB as output Can Init Flags 0 ZZ Can_Send Flags 0 clear flags Can Rcv Flags 0 LE Can Send Flags CANSPI TX PRIORITY 0 amp form value to be used CANSPI TX XTD FR
212. PIC32 Idiv Prototype ldiv_t ldiv long number long denom Description Function is similar to the div function except that the arguments and result structure members all have type long Function computes the result of division of the numerator number by the denominator denom the function returns a structure of type 1div_ t comprising quotient quot and remainder rem see Div Structures Example dl ldiv 123456 1000 uldiv Prototype uldiv_t uldiv unsigned long number unsigned long denom Description Function is similar to the div function except that the arguments and result structure members all have type unsigned long Function computes the result of division of the numerator number by the denominator denom the function returns a structure of type uldiv_t comprising quotient quot and remainder rem see Div Structures Example dul uldiv 123456 1000 labs Prototype long labs long x Function returns the absolute i e positive value of long integer x Example result labs 2147483647 max n ise int max int a int b Function returns greater of the two integers a and b Example result max 123 967 function returns 123 617 MikroElektronika mikoC PRO for PIC32 min Prototype int min int a int b Function returns lower of the two integers a and 5 Example result min 123 67 function returns 67 rand Description Funct
213. PLL Input Divider 2x Divider PLL Multiplier 20x Multiplier USB PLL Input Divider 12x Divider USB PLL Enable Disabled and Bypassed System PLL Output Clock Divider PLL Divide by 1 Oscillator Selection Bits Primary Osc XT HS EC Secondary Oscillator Enable Enabled Internal External Switch Over Enabled Primary Oscillator Configuration XT osc mode CLKO Output Signal Active on the OSCO Pin Enabled Peripheral Clock Divisor Pb Clkis Sys Clk 1 MCU and Oscillator LoadScheme button button which lets you select default configuration bit settings for the selected device MCU Name P32MX460F512L Oscillator Frequency MHz Interrupt Control 8 000000 O Single Vector Base Address EBASE Ox 9FCO 1000 Multi Vector Vector Spacing VS SRS Priority Level IFCOZFF4 IFCOZFFS 1FCO2FFC Ox00008751 Ox0014S85A2 OxllOFFOOB Besides this user can control the Interrupt mechanism by selecting either Single or Multi Vector mode Base Ad dress and SRS Priority level Heap configuration can also be configured by changing the heap size Related topics Project Settings Customizing Projects Interrupts MikroElektronika 672 mikroC PRO for PIC32 Source Files Source files containing source code should have the extension c The lis
214. PRO for PIC32 Step Six Click Finish button to create your New Project New Project Wizard Step 6 6 You have successfully created a new project Click Finish to save the changes and to close the wizard gt Open Edit Project window to set Configuration bits 4 Back Finish Cancel Related topics Project Manager Project Settings New Project The easiest way to create a project is by means of the New Project Wizard drop down menu Project New Project or by clicking the New Project Icon EET from Project Toolbar New Project Wizard Steps Start creating your New project by clicking Next button New Project Wizard Welcome to the New Project Wizard This wizard helps you e Create a new project e Select the device for your project e Setup device clack Add project files Click Next to continue 661 MikroElektronika mikoC PRO for PIC32 Step One Select the device from the device drop down list New Project Wizard Step 1 6 Select the device you want to use Device Name P32MX460F512L Next gt Cancel Step Two Enter the oscillator frequency value New Project Wizard Setup the clock for example 11 0592 MHz Device Clock 10 000000 Next gt Cancel MikroElektronika 662 mikroC PRO for PIC32 Step Three Specify the location where your project will be saved New Project Wizard Step 3 6 Specify where your project will be sav
215. PRO for PIC32 Examples Development SystemslLV32MX v Related topics Customizing Projects mikroC PRO for PIC32 Compilation When you have created the project and written the source code it s time to compile it Select Project Build from the drop down menu or click the Build Icon 3h from the Build Toolbar If more more than one project is open you can compile all open projects by selecting Project Build All Projects from the drop down menu or click the Build All Projects Icon By trom the Build Toolbar Progress bar will appear to inform you about the status of compiling If there are some errors you will be notified in the Messages Window If no errors are encountered the mikroC PRO for PIC32 will generate output files Output Files Upon successful compilation the mikroC PRO for PIC32 will generate output files in the project folder folder which contains the project file mcp32 Output files are summarized in the table below Intel HEX Intel style hex records Use this file to program MCU Binary Extended mikro Compiled Library Binary distribution of application that can be included in other projects List File Overview of MCU memory allotment instruction 1st addresses registers routines and labels Assembler File Human readable assembly with symbolic names asm extracted from the List File Assembly View After compiling the program in the mikroC PRO for PIC32 you can click the View Assembly
216. Paths option from the drop down menu Search Paths E3 Path C Program Files Mikroelektronika mikroC PRO For PIC32 defs C Program Files Mikroelektronika mikroC PRO For PIC32 uses C Program Files Mikroelektronika mikroC PRO for PIC32 Examples Development Systems V32MX v6 Led Blink Header Files C Program Files Mikroelektronika mikroC PRO for PIC32 Examples Development Systems L 32Mx v6 Led Blink C Program Files Mikroelektronika mikroC PRO for PIC32 include Restore MikroElektronika 674 mikroC PRO for PIC32 The following options are available con Description e Add Search Path Remove Search Path Purge Invalid Paths Paths for Source Files c You can specify either absolute or relative path to the source file If you specify a relative path mikroC PRO for PIC32 will look for the file in following locations in this particular order 1 the project folder folder which contains the project file mcp32 2 your custom search paths 3 mikroC PRO for PIC32 installation folder gt Uses folder Paths for Header Files h Header files are included by means of preprocessor directive include If you place an explicit path to the header file in preprocessor directive only that location will be searched You can specify either absolute or relative path to the header If you specify a relative path mikroC PRO for PIC32 will look for the file in following locations in th
217. PortB Expander Set PullUpsPortAB 385 MikroElektronika 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 O0 register adressing slew rate enabled ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections sbit SPExpanderRST at RFO bit sbit SPExpanderCS at RF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI module SPII Initi s Initialize SPI module used with PortExpander Expander Inzt 0 Initialize Port Expander MikroElektronika 386 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 Pa
218. RB11 bit extern sbit Soft I2C Sda Soft I C Data line sbit Soft I2C Sda at RB12 bit extern sbit Soft I2C Scl Direction of the Soft IPC Clock sbit Soft I2C Scl Direction at Direction pin TRISB11_ bit extern sbit Soft_I2C Sda 5 sbit Soft_I2C_Sda_Direction at Direction Direction of the Soft I C Data pin TRISB12 bit Library Routines Soft I2C Init Soft I2C Start Soft I2C Read Soft I2C Write Soft I2C Stop Soft I2C Break 415 MikroElektronika mikoC PRO for PIC32 Soft I2C Init Rtms non SSS Requires Global variables Soft I2C Scl Soft IPC clock line Soft I2C Sda Soft FC 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 Software I2C connections sbit Soft I2C Scl at RB11 bit sbit Soft I2C Sda at RB12 bit sbit Soft I2C Scl Direction at TRISB11 bit sbit Soft I2C Sda Direction at TRISB12 bit End Software I2C connections Soft I2C Inrt Soft I2C Start Rmums Nothing S Software I C must be configured before using this function See Soft I2C Init routine Issue START signal Soft T20 Start MikroElektronika 416 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 para
219. RT library implements time based activities so interrupts need to be disabled when using it MikroElektronika 426 mikroC PRO for PIC32 Soft UART Break Prototype 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 char datal error counter 0 void TimerlInt org IVT ADDR T1INTERRUPT if counter gt 20 Soft UART Break counter 0 reset counter else counter increment counter TIIF bit 0 Clear Timerl overflow interrupt flag void main if Soft UART Init amp PORTF 4 Soft UART Write 0x55 try Soft UART Read with blocking prevention mechanism IPCO IPCO 0x1000 Interrupt priority level 1 TIIE bait 1 Enable Timerl interrupts T1CON 0x8030 Timerl ON internal clock FCY prescaler 1 256 datal Soft UART Read error TITE bit 0 Disable Timerl interrupts The Software UART library implements time based activities so interrupts need to be disabled when using it 427 MikroElektronika 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 simpl
220. Register from the drop down menu or click the How To Register Icon 2 You can choose between two registering methods work online or work offline based on your current internet connection and click Request license key now button MikroElektronika 34 mikroC PRO for PIC32 How to register Choose registration method Twork online Choose this option if you are connected to nternet You will be directed to a web page which will help you o send the license key request This is the Fastest way of i btaining the license key it takes minutes to get it in your mailbox Recommended O I work offline Choose this option if you are not connected to Internet You will be quided to Fill in the registration Form which you can e mail when you get online This is a slower way of getting the license key and it is intended for offline computers Request license key now If you choose work online registering method following page will be opened in your default browser DEVELOPMENT TOOLS COMPILERS BOOKS Email officeghmikroe com F MikroElektronika mie i evelopment Tool Compilers Accessory Boa Special Offers Easy Buy Publication Support Projects Download Software Activation In order to get activation key please fill in required fields Upon receiving and verifying your request we will send the license key to the e mail address you specified in the form Product Name John Smith A
221. SCII character and A is 45 in the mikroC PRO for PIC32 character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user can use fonts given in the file Lib GLCDFonts file located in the Uses folder or create his own fonts List of supported fonts Font Glcd System3x5 Font Gled System5x7 Font Gled 5x7 Font Glcd Character8x7 For the sake of the backward compatibility these fonts are supported also System3x5 equivalent to Font Glcd System3x5 FontSystem5x7 v2 equivalent to Font Glcd System5x7 font5x7 equivalent to Font Glcd 5x7 Character8x7 equivalent to Font Glcd Character8x7 Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Use the custom 5x7 font myfont which starts with space 32 Ja 2207 MikroElektronika 494 mikroC PRO for PIC32 SPI Glcd Write Char Prototype Description Parameters Requires void SPI Glcd Write Char char chri char x pos char page num char color Prints character on Glcd chr1 character to be written x pos character starting position on x axis Valid values 0 127 FontWidth page num the number of the page on which character will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Nothing Glcd needs
222. See Mmc Fat Assign The file must be opened for writing See Mmc Fat Rewrite or Mmc Fat Append April ist 2005 18 07 00 Mmc Fat Set File Date 2005 4 MikroElektronika 314 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 Upon function execution month attribute is returned through this parameter da y buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter nins buffer to store minutes attribute to Upon function execution minutes attribute is returned through this parameter 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 get Date time of file unsigned yr char mnth dat hrs mins file Name MYFILEABTXT Mmc Fat Assign file Name Mmc Fat Get File Date amp yr amp mnth amp day amp hrs amp mins 319 MikroElekt
223. Set DirectionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTB char read data Expander Set DirectionPortB 0 0xFF set expander s portb to be input Expander Read PortB 0 Expander Read PortAB Prototype unsigned int Expander Read PortAB char ModuleAddress Description The function reads word from Port Expander s ports PortA readings are in the higher byte of the result PortB readings are in the lower byte of the result ModuleAddress Port Expander hardware address see schematic at the bottom of this page Rtums woare Requires Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as inputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTA and PORTB unsigned int read data Expander Set DirectionPortAB 0 0xFFFF set expander s porta and portb to be input read data Expander Read PortAB 0 389 MikroElektronika mikoC PRO for PIC32 Expander Write PortA Prototype void Expander Write PortA char ModuleAddress char Data The function writes byte to Port Expander s PortA Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page bata data to be written Requires Nothing Port Expander must be initialized See Exp
224. Set Duty unsigned duty unsigned channel 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 Requires MCU must have the HW PWM Module PWM channel must be properly initialized See PWM Init routine Set channel 1 duty ratio to 508 unsigned int pwm periodl PWM Set Duty pwm periodl 2 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Start Rems nom OOOO Requires MCU must have the HW PWM Module PWM channel must be properly configured See the PWM Init and PWM Set Duty routines start PWM at channel 1 PWM Start 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Stop ums Nothing OOOO MCU must have the HW PWM Module stop PWM at channel 1 PWM Stop 1 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details MikroElektronika 402 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 Copy Code To Clipboard unsigned int current duty old duty current dutyl old dutyl unsigned int pwm periodl pwm period2 void InitMain CHECON 0x
225. T USE EN N CEE AEE EEEE M EEE E ECR ICICIE E visinieisjslsjslslalzlelnielslololulalal a le u o 18 411 ROM Memory Usage Displays ROM memory space usage in a pie like form Statistics BO7S bytes 0 6 521214 bytes 99 4 524289 bytes Project Name C Development Systems V32MY v6 LCD COG 2x16 lLcd mp2 Tene 1 31 2011 1 03 40 PM vewvemioe com mikoC PRO for PIC32 ROM Memory Constants Displays ROM memory constants and their addresses ROM Memory Constants Project Name C11 Development SystemslLVA2Mx VEILED COG 2xi6 iLed ancp32 Tine 1 31 2011 1 03 40 FM Sewers com Functions Sorts and displays functions in various ways Functions Sorted By Address Click on column header to sort table by Address Name Urigue Assembler Name or Size 32 488 32 16 16 204 28 36 424 56 1220 324 Lcd Out Project Name C Development SystemslL VIZMK v6l CD COG 2x16 iLed mep32 Tene 1 31 2011 1 03 40 PM seem mibroe com mikroC PRO for PIC32 Functions Sorted By Name Chart Sorts and displays functions by their name in the ascending order 1 000 1 100 1200 1300 Double cick on diagram to open R in a new window Project Nome Cil pevelopment Systems Vx VERD COG2xl MeAmqua Tee IRI TOMO remiron com Functions Sorted By Size Chart Sorts and displays functions by their sizes in a chart like form Double cick on diagram to open t in a new window Pr
226. TFT H Line 10 50 20 TFT V Line Prototype void TFT V Line int y start int y end int x pos Nothing Description Draws a vertical line on TFT Parameters y start y coordinate of the line start y end y coordinate of the line end x pos x coordinate of vertical line TFT module needs to be initialized See the TFT Init routine Draw a vertical line between dots 10 5 and 10 25 TET V Dbzne 5 25 10 TFT Rectangle Prototype void TFT Rectangle int x upper left int y upper left int x bottom right int y bottom right Nothing Description Draws a rectangle on TFT Parameters x upper left x coordinate of the upper left rectangle corner y upper left y coordinate of the upper left rectangle corner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner TFT module needs to be initialized See the TFT Init routine DOTT TFT Rectangle 20 20 219 107 MikroElektronika 574 mikroC PRO for PIC32 TFT Rectangle Round Edges Prototype void TFT Rectangle Round Edges unsigned int x upper left unsigned int y upper left unsigned int x bottom right unsigned int y bottom right unsigned int round radius Description Draws a rounded edge rectangle on TFT Parameters x upper left x coordinate of the upper left rectangle corner y upper left y coordinate of the upper left rectangle cor
227. 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 void main o Watch Values E ADPCFG OxFFFF TA rA 2 a E EB Eb Eh eo oo er e amp P Lcd Init a Add Remove Prop kg Add All s Remove All e Lcd Cmd LCD CLEAR Select variable from list gt 29 Led_Cmd LCD CURSOR_OFF text hd 30 Search for variable by assembly name for i i i lt 17 i text EY d HEELS fg mu Bassia ig Peripherals Freeze S 1 Name Value Address text mox 0x0800 PC 0x0002C2 0 00 us Run Pause Debugger F6 and Toggle Breakpoints F5 are mikrolCD debugger functions that are used in the Real Time mode Pressing F5 marks the line selected by the user for breakpoint F6 executes code until the breakpoint is reached After reaching the breakpoint Debugger halts Here in our example we will use breakpoints for writing mikroElektronika on Lcd char by char Breakpoint is set on Lcd Chr and the program will stop every time this function is reached After reaching breakpoint we must press F6 again to continue the program execution y Exo Sly Watch Values E ADPCFG OxFFFF SA nm a EB Gh Eh 90 oe er e E fu 9 Lcd Init ap Add 3 Remove Prop kd Add All k Remove All e Lcd Cmd LCD CLEAR Select variable from list Lcd Cmd LCD CURSOR OFF are 30 Search for variable by assem
228. UART module The internal UART module module is set to continue operation in IDLE mode default Tx and Rx pins loopback mode disabled 8 bit data no parity 1 STOP bit transmitter enabled generate interrupt on transmission end interrupt on reception enabled Address Detect mode disabled baud rate requested baud rate Nothing Routine requires the UART module Initialize hardware UART1 module and establish communication at 2400 bps UART1 Init 2400 Switching between the UART modules in the UART library is done by the UART Set Active function UART modules have to be previously initialized Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Refer to the device data sheet for baud rates allowed for specific Fosc The compiler will choose for which speed the calculation is to be performed high or low This does not mean that it is the best choice for desired baud rate If the baud rate error generated in this way is too big then UARTx Init Advanced routine which allows speed select be used UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 591 MikroElektronika mikoC PRO for PIC32 UARTx Init Advanced Prototype void UARTx Init Advanced unsigned long baud rate unsigned long fre
229. a mikoC PRO for PIC32 Description gradient enabled enable gradient Enable gradient lo Disable gradient gradient orientation sets gradient orientation Left to right gradient orientation Top to bottom gradient orientation gradient color from sets the starting gradient color MikroElektronika 512 mikroC PRO for PIC32 Description gradient color to sets the ending gradient color TFT module needs to be initialized See the TFT Init routine Enable gradient from black to white color left right orientation TFT Set Brush 0 0 1 LEFT TO RIGHT CL BLACK CL WHITE TFT Line Prototype void TFT Line int x1 int yl int x2 int y2 Description Draws a line from x1 y1 to x2 y2 Parameters x1 X coordinate of the line start y1 y coordinate of the line end x2 X coordinate of the line start y2 y coordinate of the line end TFT module needs to be initialized See the TFT Init routine mes TFT Line 0 239 127 913 MikroElektronika mikoC PRO for PIC32 TFT H Line Prototype void TFT H Line int x start int x end int y pos Description Draws a horizontal line on TFT Parameters x start X coordinate of the line start x end x coordinate of the line end y pos y coordinate of horizontal line TFT module needs to be initialized See the TFT Init routine Draw a horizontal line between dots 10 20 and 50 20
230. a mikoC PRO for PIC32 Library Example This code shows how to use the Ethernet mini library the board will reply to ARP amp 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 amp 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 tO t7 will toggle RDO to RD7 bit and return HTML main page all other requests return also HTML main page Copy Code To Clipboard include EthEnc28j60 h duplex config flags fdefine Spi Ethernet HALFDUPLEX 0x00 half duplex fdefine Spi Ethernet FULLDUPLEX 0x01 full duplex mE ehternet NIC pinout sfr sbit SPI Ethernet Rst at LATFO bit for writing to output pin always use latch sfr sbit SPI Ethernet CS at LATFl bit for writing to output pin always use latch sfr sbit SPI Ethernet Rst Direction at TRISFO bit sfr sbit SPI Ethernet CS Direction at TRISF1 bit end ethernet NIC definitions KOK KK kk kk kk kk k koc ke Sk kk kk kk koc kk kc kk A A I k kc ck kc kck ko A koe ke ke ke e kx ROM constant strings ax const code unsigned char httpHeader HTTP 1 1 200 OK nContent type HTTP header const code unsigned char httpMimeTypeHTML text html n n HTML MIME type const code unsigned char httpM
231. a new file with the p1d extension pld test file pld Next open it and write something like this pld test 3 Once you have done this save the file In the Project Manager add pid test file pld file by right clicking the Project Level Defines node In the source code write the following if pld test 3 fendif There are number of predefined project level defines See predefined project level defines Note For inclusion of the header files extension h use the preprocessor directive include See File Inclusion for more information Related topics Project Manager Project Settings Edit Project MikroElektronika 666 mikroC PRO for PIC32 Add Remove Files from Project The project can contain the following file types c source files h header files mc1 binary files pid project level defines files image files ihex EEPROM files hex asm and 1st files see output files These files can not be added or removed from project other files Project Manager 1 1 e S ES S i i cot Se Es B D Sources T6963C 240x128 c einstein_bmp c mikroe_bmp c S Header Files T 963C h a D Binaries T6963C_240x128 mcl 73 Project level defines 4 Image Files mikroE 240x128 bmp S EEPROM Files T6963C 240x128 ihex Active Comments Files 4 Output Files 5 16963C_240x128 hex T6963C 240x128 asm einstein bmp asm mikroe bmp asm T6963C 240x128 lst Other Files B Datasheet 70138b pdf T
232. a signal pin r6963C ctrirst Reset signal pin L6963C ctrlwr Direction Direction of Write signal pin L6963C ctrlrd Direction Direction of Read signal pin r6963C ctrlcd Direction Direction of Command Data signal pin L6963C ctrlrst Direction Direction of Reset signal pin must be defined before using this function 539 MikroElektronika mikoC PRO for PIC32 T6963C module connections char T6963C dataPort at PORTB DATA port sbit T6963C ctrlwr at LATF2 bit WR write signal sbit T6963C ctrird at LATF1 bit RD read signal sbit T6963C ctrlcd at LATFO bit CD command data signal sbit T6963C ctrlrst at LATF4 bit RST reset signal sbit T6963C ctrlwr Direction at TRISF2 bit WR write signal sbit T6963C ctrlrd Direction at TRISFI bit RD read signal sbit T6963C ctrlcd Direction at TRISFO bit CD command data signal Sbit T6963C ctrlrst Direction at TRISF4 bit RST reset signal Signals not used by library they are set in main function sbit T6963C ctrlce at LATF3 bit Pa signal sbit T6963C ctrlfs at LATF6 bit rd d signal sbit T6963C ctrlmd at LATF5 bit PE signal sbit T6963C ctrlce Direction at TRISF3 bit signal direction sbit T6963C ctrlfs Direction at TRISF6 bit Eus signal direction sbit T6963C ctrlmd Direction at TRISF5 bit d d signal direction End T6963C module connections init display for 240 pixel width 128 pixel height and 8 bits character width T
233. able SPI Lcd8 Commands 510 Library Example 510 SPI T6963C Graphic Lcd Library 513 Library Dependency Tree 513 External dependencies of SPI T6963C Graphic Lcd Library 513 Library Routines 514 SPI T6963C config 515 SPI T6963C writeData 516 SPI T6963C writeCommand 516 SPI T6963C setPtr 517 SPI T6963C waitReady 517 SPI T6963C fill 517 SPI T6963C dot 518 SPI T6963C write char 518 SPI T6963C write text 519 SPI T6963C line 520 SPI T6963C rectangle 520 SPI T6963C rectangle round edges 521 SPI T6963C rectangle round edges fill 521 SPI T6963C box 522 SPI T6963C circle 522 SPI T6963C circle fill 522 SPI T6963C image 523 SPI T6963C Partiallmage 523 SPI T6963C sprite 524 SPI T6963C set cursor 524 SPI T6963C clearBit 524 SPI T6963C setBit 525 SPI T6963C negBit 525 SPI T6963C displayGrPanel 525 SPI T6963C displayTxtPanel 526 SPI T6963C setGrPanel 526 SPI T6963C setTxtPanel 526 SPI T6963C panelFill 527 SPI T6963C grFill 527 SPI T6963C txtFill 527 SPI T6963C cursor height 528 SPI T6963C graphics 528 SPI T6963C text 528 SPI T6963C cursor 529 SPI T6963C cursor blink 529 Library Example 529 21 MikroElektronika mikoC PRO for PIC32 HW Connection 535 T6963C Graphic Lcd Library 536 Library Dependency Tree 536 External dependencies of T6963C Graphic Lcd Library 537 Library Routines 538 T6963C init 539 T6963C writeData 540 T6963C writeCommand 541 T6963C setPtr 541 T6963C waitReady 541 T6963C fill 542 T6963C dot 542 T6963C write char 5
234. able name 3 If accessing registers declared through register rx or str specifiers visible throughout the whole project variable name gt Accessing local variable lt routine name variable name gt Accessing routine parameter FARG routine name variable name gt 221 MikroElektronika mikoC PRO for PIC32 Here is an example of using asm instructions unsigned myvar absolute 0x2678 unsigned long myvarl const char msg Test absolute 0x3652 void main myvar 5 myvarl OxABCDEFAB org 0x11234 asm MOV _myvar w0 move myvar to WO nop MOV 46 WO move literal 6 to WO MOV WO _myvar move contents of WO to myvar MOV flo addr myvar W1 retrieve low address word of myvar and move it to Wl 0x2678 gt W1 MOV hi_addr _myvar W1 retrieve high address word of myvar and move it to W1 0x0000 gt W1 MOV lo addr main Labell WO retrieve lo address word of Labell and move it WO PC Labell gt WO MOV hi_addr _main WO retrieve hi address byte of main routine and move it to WO 0x0001 gt W1 MOV lo_addr _msg2 WO retrieve low address word of constant msg and move it to WO 0x3652 gt W1 MOV myvarl 2 W1 accessing hi word of myvarl variable and move it to W1 OxABCD gt W1 Labell asm MOV hi addr main Labell WO retrieve hi address word of Labell and move it WO PC Labell gt WO goto Labell When using asm
235. acement and merging during the preprocessor scanning phase See the Preprocessor Operators 191 MikroElektronika 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 This use of a term object is different from the same term used in object oriented languages which is more general Our definiton of the word would encompass functions variables symbolic constants user defined data types and labels Each value has an associated name and type also known as a data type The name is used to access the object and can be a simple identifier or complex expression that uniquely refers the object Objects and Declarations Declarations establish a necessary mapping between identifiers and objects Each declaration associates an identifier with a data type Associating identifiers with objects requires each identifier to have at least two attributes storage class and type sometimes referred to as data type The mikroC PRO for PIC32 compiler deduces these attributes from implicit or explicit declarations in the source code Usually only the type is explicitly specified and the storage
236. acter does not count against string s length char txt mikroElektronika int result result strlen txt calculates the length of the txt string result 16 mikoC PRO for PIC32 strncat Prototype char strncat char to char from int size Description Function appends not more than size characters from the string from to to The initial character of from overwrites the null character at the end of to The terminating null character is always appended to the result The function returns to char txt mikroElektronika char txt sub mikro char result txt 5 0 result strncat txt txt sub 4 routine appends first 4 characters from the string txt sub at the place of first null character in the txt string strncpy Prototype char strncpy char to char from int size Description Function copies not more than size characters from string from to to If copying takes place between objects that overlap the behavior is undefined If from is shorter than size characters then to will be padded out with null characters to make up the difference The function returns the resulting string to char txt mikroElektronika char txt sub mikro test int res res strncpy txt txt sub 4 copies first 4 characters form the string txt sub to txt strspn Prototype int sbrespn char strl char str2 Description Function returns the length of t
237. aits for DNS reply The incoming packets will be processed normaly during this time When DHCP module is used global library variable SPI Ethernet userTimerSec is used to keep track of time It is user responsibility to increment this variable each second in it s code SPI Ethernet doDHCPLeaseTime Prototype unsigned int SPI Ethernet doDHCPLeaseTime Description This is DHCP module routine It takes care of IP address lease time by decrementing the global lease time library counter When this time expires it s time to contact DHCP server and renew the lease 0 lease time has not expired yet lease time has expired it s time to renew it Ethernet module has to be initialized See SPI Ethernet Init while 1 if SPI Ethernet doDHCPLeaseTime it s time to renew the IP address lease MikroElektronika 456 mikroC PRO for PIC32 SPI Ethernet renewDHCP Prototype unsigned int SPI Ethernet renewDHCP unsigned char tmax This is DHCP module routine It sends IP address lease time renewal request to DHCP server tmax time in seconds to wait for an reply 1 upon success lease time was renewed 0 otherwise renewal request timed out Ethernet module has to be initialized See SPI Ethernet Init while 1 if SPI Ethernet doDHCPLeaseTime SPI Ethernet renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply 45 MikroElektronik
238. als 9 LCD D4 LCD D4 Direction 9 LCD D5 LCD D5 Direction LCD D6 LCD D6 Direction LCD D7 LCD D7 Direction 9 LCD EN LCD EN Direction 9 LCD RS LCD RS Direction 9 txtl 9 txt2 txt3 txt4 Externs B TypeDef Time B Tags 9 Character Set Includes 9 include built in h Web Links 9 http www rikroe com The following options are available in the Code Explorer kon Descriptor Expand Collapse all nodes in tree EJ Locate declaration in code 59 MikroElektronika 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 Routine List E3 Sort By Name Sort By Line C9iMove Delay Cishift Text Left DshiFt_Text_Right 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 Only one of them may be active at the moment Setting project in active mode is performed by double clicking the desired project in the Project Manager which will result in bolding the project s name Also the name of the currently active project will be diplayed in the Program Manager window title alongside
239. alue call this function after TP TFT Init threshold custom ADC threshold value Nothing TP TFT Init has to be called before using this routine TP TFT Set ADC Threshold 900 Set touch panel ADC threshold 585 MikroElektronika mikoC PRO for PIC32 TP TFT Press Detect pops Detects if the touch panel has been pressed 1 if touch panel is pressed 0 otherwise Requires Global variables DriveX Left DriveX Left pin DriveX Right DriveX Right pin DriveY Up DriveY Up pin DriveY Down DriveY Down pin DriveX Left Direction Direction of DriveX Left pin DriveX Right Direction Direction of DriveX Right pin DriveY Up Direction Direction of DriveY Up pin DriveY Down Direction Direction of DriveY Down pin must be defined before using this function Touch Panel module connections DriveX Left at LATBI3 bit DriveX Right at LATB11 bit DriveY Up at LATB12 bit DriveY Down at LATB10 bit DriveX Left Direction at TRISB13 bit DriveX Right Direction at TRISB11 bit DriveY Up Direction at TRISBI2 bit DriveY Down Direction at TRISB10 bit End Touch Panel module connections P TFT Press Detect MikroElektronika 586 mikroC PRO for PIC32 TP TFT Get Coordinates Prototype char TP TFT Get Coordinates unsigned int x coordinate unsigned int y coordinate Get touch panel coordinates and store them in x coordinate and y coordinate parameters Para
240. ame MCU you did but how to make it work for another MCU You should read your MCU s datasheet Different MCUs can have different pin assignments and may require different settings If you need help regarding this you can find free online books on our website and recommend you starting there You can also ask for help on our forum MikroElektronika 680 mikroC PRO for PIC32 need this project finished can you help me We currently do not do custom projects however we can give you some directions when you start working on your project and come to a problem Also our forum is very active community and as you can find there experts in different fields we encourage you to look for help there Do you have some discount on your compilers development systems for students professors Since large percentage of our customers are schools laboratories and students our prices are already scaled for these kinds of users If you plan ordering more than one of our products see special offers page on our website Also you can contact our Sales Department and see if you are eligible for some additional discount have a question about your compilers which is not listed here Where can find an answer Firstly look for it in your compiler s Help If you don t find an answer there please create a support ticket on our website UJO9 e0Jyuu 9 eoujo je sn j9ejuoo oj ejejiseu jou op sjesodoud sseulsnq Jo ponh ua suonsenb Au
241. an be used as type identifier Distance i declare variable i of unsigned long int In the t ypedef 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 asm Declaration The mikroC PRO for PIC32 allows embedding assembly in the source code by means of the asm declaration The declarations asm and asm are also allowed in the mikroC PRO for PIC32 and have the same meaning Note that numerals cannnot be used as absolute addresses for SFR or GPR variables in assembly instructions Symbolic names may be used instead listing will display these names as well as addresses Assembly instructions can be grouped by the asm keyword or asm or asm asm block of assembly instructions The mikroC PRO for PIC32 comments both single line and multi line are allowed in embedded assembly code The only types whose name remains the same in asm as it is in the mikroC PRO for PIC32 are registers e g INTCON PORTB WREG GIE etc Accessing variables Depending on the place of declaration accessing a variable can be done in several ways Accessing global variable 1 If declared as static visible only in the file where it was declared source file name variable name 2 If declared as a non static global visible throughout the whole project vari
242. 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 For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set _ Active function See the SPI Library functions Library does not use Port Expander interrupts Library Dependency Tree Port Expander gt sP1 External dependencies of Port Expander Library The following variables must be defined in all projects using Port Expander Description Library i MONS PES EDEN Reset line sbit SPExpanderRST at RFO bit SPExpanderRST extern sfr sbit SPE derCS RFI bit SPExpanderCs Chip Select line sbit xpanderCS at i extern sfr sbit Direction of the Reset pin sbit SPExpanderRST Direction SPExpanderRST Direction pi TRISFO bit extern sfr sbit A sbit SPExpanderCS Direction SPExpanderCS Direction Direction of the Chip Select pin TRISF1 bit Library Routines Expander Init Expander Init Advanced Expander Read Byte Expander Write Byte Expander Read PortA Expander Read PortB Expander Read PortAB Expander Write PortA Expander Write PortB Expander Write PortAB Expander Set DirectionPortA Expander Set DirectionPortB Expander Set DirectionPortAB Expander Set PullUpsPortA Expander Set PullUps
243. and q struct Dot p 1 Laj q 3 7 0 5 Declare and initialize circle ol struct Circle ol 1 0 0 ZZ radius is 1 center is at 0 0 Incomplete Declarations Incomplete declarations are also known as forward declarations A pointer to a structure type can legally appear in the declaration of another structure B before A has been declared struct A incomplete struct B struct A pa struct A struct B pb The first appearance of A is called incomplete because there is no definition for it at that point An incomplete declaration is allowed here because the definition of B doesn t need the size of A 211 MikroElektronika 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 ofthe 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 Mystruct Mystruct s ps arrs 10 same as struct mystruct s etc Without tag typedef struct Mystruct Mystruct s ps arrs 10 Usually there is no need to use both tag and typedef either can be used in structure type declarations Untagged structure and union
244. andard Issues 136 Divergence from the ANSI C Standard 136 C Language Extensions 136 Implementation defined Behavior 136 Predefined Globals and Constants 137 Predefined project level defines 137 Accessing Individual Bits 138 sbit type 139 at keyword 140 bit type 140 MikroElektronika mikoC PRO for PIC32 Interrupts 141 Configuring Interrupts 141 Single Vector Mode 141 Multi Vector Mode 141 Interrupt Priorities 142 Interrupts and Register Sets 142 Register Set Selection in Single Vector Mode 142 Interrupts and Register Sets 142 Interrupt Coding Requirements 142 Interrupt Service Routine 142 Function Calls from Interrupt 143 Interrupt Example 144 Linker Directives 145 Directive absolute 145 Directive org 146 Directive orgall 146 Directive funcorg 146 Indirect Function Calls 146 Built in Routines 147 Lo 148 Hi 148 Higher 149 Highest 149 LoWord 150 HiWord 150 Delay us 151 Delay ms 151 Vdelay ms 151 VDelay Advanced ms 152 Delay Cyc 152 Delay Cyc Long 152 Clock kHz 153 Clock Mhz 153 Get Fosc kHz 153 Get Fosc Per Cyc 154 KVAO TO KVA1 154 KVA1 TO KVAO 154 KVA TO PA 155 PA TO KVAO 155 PA TO KVA1 155 CPO GET 155 CPO SET 156 Enablelnterrupts 156 Disablelnterrupts 156 Code Optimization 158 Constant folding 158 MikroElektronika 6 mikroC PRO for PIC32 Constant propagation 158 Copy propagation 158 Value numbering 158 Dead code ellimination 158 Stack allocation 158 Local vars opti
245. ander Init Port Expander s PortA should be configured as output See Expander Set DirectionPortA and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTA Expander Set DirectionPortA 0 0x00 set expander s porta to be output Expander Write PortA 0 O0xAA Expander Write PortB Prototype void Expander Write PortB char ModuleAddress char Data The function writes byte to Port Expander s PortB Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page bata data to be written Requires Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as output See Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTB Expander Set DirectionPortB 0 0x00 set expander s portb to be output Expander Write PortB 0 0x55 MikroElektronika 390 mikroC PRO for PIC32 Expander Write PortAB Prototype Expander Write PortAB char ModuleAddress unsigned int Data Description The function writes word to Port Expander s ports Parameters ModulecAddress 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 Nothing Requires Port Expander must be in
246. ant Routines for file handling can be used only with FAT16 file system Library functions create and read files from the root directory only Library functions populate both FAT1 and FAT2 tables when writing to files but the file data is being read from the FAT1 table only i e there is no recovery if the FAT1 table gets corrupted If MMC SD card has Master Boot Record MBR the library will work with the first available primary logical partition that has non zero size If MMC SD card has Volume Boot Record i e there is only one logical partition and no MBRs the library works with entire card as a single partition For more information on MBR physical and logical drives primary secondary partitions and partition tables please consult other resources e g Wikipedia and similar Before write operation make sure you don t overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable Drive mapping tools such as Winhex can be of a great assistance Library uses SPI module for communication The user must initialize the appropriate SPI module before using the MMC Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active function See the SPI Library functions The SPI module has to be initialized through SPIx Init Advanced routine with the following parameters SPI Master bit mode secondary prescaler 1 pr
247. aphic panel 1 as current graphic panel T6963C setGrPanel 1 T6963C setTxtPanel Description Compute start address for selected text panel and set appropriate internal pointers All subsequent text operations will be preformed at this text panel n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See the T6963C init routine set text panel 1 as current text panel T6963C setTxtPanel 1 T6963C panelFill Rems Na OOOO Toshiba Glcd module needs to be initialized See the T6963C_init routine clear current panel T6963C panelFill 0 991 MikroElektronika mikoC PRO for PIC32 T6963C grFill Rems Ning 0000 S Toshiba Glcd module needs to be initialized See the T6963C init routine clear current graphic panel T6963C grFill 0 moes Nm Ooo T6963C_txtFill ums nom OOOO Peme e E O T6963C ExtPill 0 T6963C_cursor_height Prototype void T6963C_cursor height unsigned char n Parameters n cursor height Valid values 0 7 Rems Nang 0 Example r Gc cursor height SS moes None oOo MikroElektronika 092 mikroC PRO for PIC32 T6963C graphics Prototype void T6963C graphics unsigned int n Enable disable graphic displaying Parameters n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See the T6963C in
248. arameter lt S1D13700 Fill Prototype void S1D13700 Fill char d unsigned int start unsigned int len Description Fills Glcd memory block with given byte Parameters byte to be written start starting address of the memory block len length of the memory block in bytes Glcd module needs to be initialized See the S1D13700 Init routine from the starting address of 0x3000 fill the memory block size of Ox7FFF with 0x20 S1D13700 Fill 0x20 0x3000 Ox7FFF 311 MikroElektronika mikoC PRO for PIC32 S1D13700 GrFill Prototype void S1D13700 GrFill char d Description Fill GENE layer with appropriate value 0 to clear Parameters 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 Description Fill current text panel with appropriate value 0 to clear Parameters d this value will be used to fill text panel Glcd module needs to be initialized See the S1D13700 Init routine clear current text panel 1D13700 TxtFill 0 S1D13700 Display GrLayer Prototype void S1D13700 Display GrLayer char mode Description Display selected graphic layer Parameters mode graphic layer mode Valid values Glcd module needs to be initialized See the S1D13700 Init routine Turn o
249. arameter as used in initialization see HID Enable len specifies a length of the data to be transmitted puer If the data transmitting has failed the function returns 0 Otherwise it returns number of transmitted bytes USB HID needs to be enabled before using this function See HID Enable retry until success while HID Write amp writebuff 64 ges Function call needs to be repeated as long as data is not successfuly sent 601 MikroElektronika mikoC PRO for PIC32 HID Disable eum Nothing USB HID needs to be enabled before using this function See HID Enable Emme FIBRIN 7000000 E LI USB Interrupt Proc This routine is used fare servicing various USB bus events Should be called inside USB interrupt routine void USBlInterrupt iv IVT_ADDR_USB1INTERRUPT USB Interrup aped 0 Do not use this function with USB Polling Proc only one should be used To enable servicing through interrupt USB_ INTERRUPT constant should be set it is set by default in descriptor file MikroElektronika 602 mikroC PRO for PIC32 USB Polling Proc Prototype void USB Polling Proc void Description This routine is used for servicing various USB bus events It should be periodically preferably every 100 microseconds Requires Nothing while 1 USB Polling Proc kk HID Read if kk 0 for cnt 0 cnt lt 64 cnt writebuff
250. area X coordinate of the upper right corner of the working area y coordinate of the bottom left corner of the working area y coordinate of the upper right corner of the working area TP TFT Set Calibration Consts 173 776 75 760 Set calibration constants MikroElektronika 588 mikroC PRO for PIC32 HW Connection TFT 320x240 display MI0283QT2 Touch Panel TFT HW connection mikoC PRO for PIC32 UART Library The UART hardware module is available with a number of PIC32 MCUs The mikroC PRO for PIC32 UART Library provides comfortable work with the Asynchronous full duplex mode Important UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Switching between the UART modules in the UART library is done by the UART Set Active function UART modules have to be previously initialized 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 MikroElektronika 590 mikroC PRO for PIC32 UARTx Init Prototype void UARTx Init unsigned long baud rate Description Configures and initializes the
251. ast the array which is legal However applying an indirection operator to a pointer to one past the last element leads to undefined behavior For example void f some type a int n function f handles elements of array a array a has n elements of type some type int i some type p amp a 0 for i1 0 i n itt here we do something with p ptt and with the last iteration p exceeds the last element of array a at this point p is undefined 209 MikroElektronika 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 For example int 10 int pil amp a 0 int pi2 amp a 4 i pi2 pil i equals 8 piz i gt gt 1 pi2 pi2 4 pi2 now points to 0 Structures A structure is a derived type usually representing a user defined collection of named members or components These members can be of any type either fundamental or derived with some restrictions to be discussed later in any sequence In addition a structure member can be a bit field Unlike arrays structures are considered to be single objects The mikroC PRO for PIC32 structure type lets you handle complex data structures almost as easily a
252. ata buffer to store read byte to Upon this function execution read byte is returned through this parameter 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 reading See Mmc_Fat_Reset char character Mme Fat Read amp character MikroElektronika 372 mikroC PRO for PIC32 Mmc Fat Rewrite Description Opens the currently assigned file for writing If the file is not empty its content will be erased Nothing Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init Prototype void Mmc Fat Rewrite The file must be previously assigned See Mmc Fat Assign open file for writing Mmc Fat Rewrite Mmc Fat Append Prototype void Mmc Fat Append Description Opens the currently assigned file for appending Upon this function execution file pointers will be positioned after the last byte in the file so any subsequent file write operation will start from there 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 open file for appending Mmc Fat Append None Mmc Fat Delete Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init The file must be previously assigned
253. ata 0 if exists crc send data 1 if exists crc send data 2 if exists erc send cro send if cre send START BYTE crc send STOP BYTE crc sendtt NOTE DATALEN lt 4 0 gt can not take the START BYTE lt 4 0 gt or STOP BYTE 4 0 values MikroElektronika 414 mikroC PRO for PIC32 Software lC Library The mikroC PRO for PIC32 provides routines for implementing Software IPC communication These routines are hardware independent and can be used with any MCU The Software lC library enables you to use MCU as Master in lC communication Multi master mode is not supported Important This library implements time based activities so interrupts need to be disabled when using Software l C All PC Library functions are blocking call functions they are waiting for C clock line to become logical one The pins used for the Software I C communication should be connected to the pull up resistors Turning off the LEDs connected to these pins may also be required Every Software l C library routine has its own counterpart in Hardware FC library except 12C Repeated Start Soft I2C Start is used instead of I2C Repeated Start Working clock frequency of the Software C is 20kHz External dependencies of Software C Library The following variable must be defined Describtion in all projects using RS 485 Library P extern sbit Soft_I2C_Scl Soft I C Clock line sbit Soft I2C Scl at
254. atch Values Window displays variables and registers of the MCU with their addresses and values Values are updated along with the code execution Recently changed items are coloured red There are two ways to add variable register into the watch list by its real name variable s name in program code Just select wanted variable register from Select variable from list drop down menu and click the ox add button by its name ID assembly variable name Simply type name ID of the variable register you want to display into Search for variable by assemby name box and click the x add button MikroElektronika 122 mikroC PRO for PIC32 Also it is possible to add all variables in the Watch Values Window by clicking dw AddAll button To remove a variable from the Watch Values Window just select the variable that you want to remove and then click the 96 Remove button or press the Delete key It is possible to remove all variables from the Watch Values Window by clicking kA Remove All button You can also expand collapse complex variables i e struct type variables strings etc by clicking the appropriate button or beside variable name Watch Yalues Aey En Bx Select variable from list PC 0x00028E 9655 99 ms E Double clicking a variable or clicking the S Properties button opens the Edit Value window in which you can assign a new value to the selected variable register Also you can choose the for
255. atches previously matched subexpression Examples N11 matches aaaa and cc 1 matches abab and 123123 d 1 matches 13 in double quotes or 4 in single quotes or 77 without quotes etc MikroElektronika 110 mikroC PRO for PIC32 Keyboard Shortcuts Below is a complete list of keyboard shortcuts available in mikroC PRO for PIC32 IDE IDE Shortcuts F ep amo oem Oe Ctrl Shift F11 F F3 Shift F3 Alt F3 Ctrl A Ctrl C Ctrl F Ctrl R Ctrl P Ctrl S Ctrl Shift S Ctrl V Ctrl X Ctrl Y Ctrl Z Ctrl Shift Z Ctrl Shift number Ctrl Alt Select oa mikrolCD Debugger and Software Simulator Shortcuts Jump To Interrupt m MikroElektronika mikoC PRO for PIC32 Ctri F5 Add to Watch List Ctrl F8 Step Out Shift F5 Open Watch Window Alt D Disassembly View Ctrl Shift A Show Advanced Breakpoints MikroElektronika 112 mikroC PRO for PIC32 HAPTER 3 mikroC PRO for PIC32 Command Line Options Usage mikroCPIC32 exe lt opts gt lt opts gt lt infile gt lt opts gt lt opts gt Infile can be of c emcl and pild type The following parameters are valid P lt devicename gt MCU for which compilation will be done FO oscillator Set oscillator in MHz SP directory Add directory to the search path list filename Output files generated to file pat
256. ated SPI and more than 4 Kb ROM memory 38 to 40 MHz clock is recommended to get from 8 to 10 Mhz SPI clock otherwise PIC32 should be clocked by ENC2443600 clock output due to its silicon bug in SPI hardware If you try lower PIC32 clock speed there might be board hang or miss some requests SPI Ethernet ENC24J600 library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction ARP client with cache DNS client UDP client DHCP client packet fragmentation is NOT supported Important Global library variable SPI Ethernet 243600 userTimerSec is used to keep track of time for all client implementations ARP DNS UDP and DHCP It is user responsibility to increment this variable each second in it s code if any of the clients is used For advanced users there are header files EthEnc243600 h and EthEnc243j600Private h in Uses folder of the compiler with description of all routines and global variables relevant to the user implemented in the SPI Ethernet ENC24J600 Library The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet ENC24J600 library routines Refer to SPI Library For MCUs with multiple SPI modules it is possible to initialize them and then switch by using the SPI Set Active routine Library Dependency Tree pes SPI Ethernet H l String
257. atement This means that the function call as an operand in complex expression is treated as a function result If the function has no result type void or the result is not needed then the function call can be written as a self contained expression In C scalar arguments are always passed to the function by value The function can modify the values of its formal parameters but this has no effect on the actual arguments in the calling routine A scalar object can be passed by the address if a formal parameter is declared as a pointer The pointed object can be accessed by using the indirection operator MikroElektronika 232 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 amp 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 Standard Conversions If a function prototype is in scope the mikroC PRO for PIC32 converts the passed argument to the type of the declared parameter according to the same conversion rules as in assignment statements If a prototype is present the number of arguments must match The types need to be c
258. ations on Bit Level 240 Bitwise Shift Operators 241 Bitwise vs Logical 241 Logical Operators 242 Logical Operators Overview 242 Logical Operations 242 Logical Expressions and Side Effects 242 Logical vs Bitwise 243 Conditional Operator 243 Conditional Operator Rules 243 Assignment Operators 244 Simple Assignment Operator 244 Compound Assignment Operators 244 Assignment Rules 244 Unary Operators 245 Unary Arithmetic Operators 245 Unary Logical Operator 246 Unary Bitwise Operator 246 Address and Indirection Operator 246 Sizeof Operator 247 Sizeof Applied to Expression 247 Sizeof Applied to Type 247 Expressions 248 Comma Expressions 248 Statements 249 Labeled Statements 249 Expression Statements 250 Selection Statements 250 If Statement 250 Nested If statements 250 Switch Statement 251 Nested switch 252 Iteration Statements Loops 252 While Statement 252 Do Statement 252 For Statement 253 Jump Statements 254 Break and Continue Statements 254 Break Statement 254 Continue Statement 254 MikroElektronika 11 mikoC PRO for PIC32 Goto Statement 255 Return Statement 255 Compound Statements Blocks 256 Preprocessor 256 Preprocessor Directives 256 Line Continuation with Backslash Y 257 Macros 257 Defining Macros and Macro Expansions 257 Macros with Parameters 258 Undefining Macros 259 File Inclusion 259 Explicit Path 260 Preprocessor Operators 261 Operator 261 Operator 261 Conditional Compilation 262 Di
259. ators The syntax of compound assignment operators is expressionl op expression2 where op can be one of binary operators amp lt lt OF gt gt Thus we have 10 different compound assignment operators amp lt lt and gt gt All of them associate from right to left Spaces separating compound operators e g will generate error Compound assignment has the same effect as expressionl expressionl op expression2 except the lvalue expressioni is evaluated only once For example expressioni expression is the same as expressionl expressionl expression2 Assignment Rules For both simple and compound assignment the operands expressioni and expression2 must obey one of the following rules 1 expression is of qualified or unqualified arithmetic type and expression2 is of arithmetic type 2 expression has a qualified or unqualified version of structure or union type compatible with the type of expression2 3 expressioni and expression are pointers to qualified or unqualified versions of compatible types and the type pointed to by left has all qualifiers of the type pointed to by right MikroElektronika 244 mikroC PRO for PIC32 4 Either expressioniOrexpression2is 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 pointe
260. ax Description Gets calibration constants after calibration is done and stores them in x min x max y min and y max parameters Parameters x min x coordinate of the bottom left corner of the working area x max X coordinate of the upper right corner of the working area y min y coordinate of the bottom left corner of the working area y max y coordinate of the upper right corner of the working area TP Get Calibration Consts amp x min amp y min amp x max amp y max calibration constants TP Set Calibration Consts Prototype void TP Set Calibration pq ib iat di int x min unsigned int x max unsigned int y min unsigned int y max Sets calibration constants Parameters x min x coordinate of the bottom left corner of the working area x max X coordinate of the upper right corner of the working area y min y coordinate of the bottom left corner of the working area y max y coordinate of the upper right corner of the working area TP Set Calibration Consts 148 3590 519 3370 Set calibration constants Ree 583 MikroElektronika mikoC PRO for PIC32 Touch Panel TFT Library The mikroC PRO for PIC32 provides a library for working with Touch Panel for TFT Library Dependency Tree Touch Panel sl ADC External dependencies of Touch Panel TFT Library The following variables must be defined in all projects using Touch Panel TFT Library e extern s
261. ays use latch sbit CF CD1 at RD4 bit sbit CF CE1 at LATD3 bit for writing to output pin always use latch sbit CF A2 at LATD2 bit for writing to output pin always use latch sbit CF A1 at LATD1 bit for writing to output pin always use latch sbit CF A0 at LATDO bit for writing to output pin always use latch sbit CF RDY direction at TRISD7 bit sbit CF WE direction at TRISD6 bit sbit CF OE direction at TRISD5 bit sbit CF CD1 direction at TRISD4 bit sbit CF CE1 direction at TRISD3 bit sbit CF A2 direction at TRISD2 bit sbit CF A1 direction at TRISD1 bit sbit CF A0 direction at TRISDO bit end of cf pinout const LINE LEN 39 char err txt 20 FAT16 not found char file contents LINE LEN XX CF FAT16 library by Anton Rieckert n char filename 14 MIKROOOx TXT File names unsigned short loop loop2 unsigned long i size char Buffer 512 UART1 write text and new line carriage return line feed void UART1 Write Line char uart text UART1 Write Text uart text UART1 Write 13 UART1 Write 10 Creates new file and writes some data to it void M Create New File filename 7 A Cf Fat Set File Date 2005 6 21 10 35 0 Set file date amp time info Cf Fat Assign amp filename 0xA0 Find existing file or create a new one Cf Fat Rewrite To clear file and start with new data for loop 1 loop lt 99 looptt UART1_Write
262. b dd Perc oe ola MikroElektronika 326 mikroC PRO for PIC32 A ed o od nd Dd fs Requires EN Enable signal pin LCD RST Resetsignal pin 1 DO Direction Direction of the Data pin 0 D1 Direction Direction of the Data pin 1 1 D2 Direction Direction of the Data pin 2 1 D3_Direction Direction of the Data pin 3 D4 Direction Direction of the Data pin 4 1 D5_Direction Direction of the Data pin 5 1 D6 Direction Direction of the Data pin 6 LCD D7 Direction Direction of the Data pin 7 LCD CS1 Direction Direction of the Chip select 1 pin LCD CS2 Direction Direction of the Chip select 2 pin LCD RS Direction Direction of the Register select signal pin LCD RW Direction Direction of the Read Write signal pin LCD EN Direction Direction of the Enable signal pin LCD RST Direction Direction of the Reset signal pin must be defined before using this function AAAAMAAAAAAAAAAA ES Q AAAAAAAAQNAAAQAQAQ Glcd pinout settings sbit GLCD D0 at RBO bit sbit GLCD Dl at RB1 bit sbit D D2 at RB2 bit sbit GLCD D3 at RB3 bit sbit D D4 at RDO bit sbit GLCD D5 at RD1 bit sbit GLCD D6 at RD2 bit sbit GLCD D7 at RD3 bit sbit GLCD CS1 at RBO bit sbit GLCD CS2 at RBI bit sbit GLCD RS at RB2 bit sbit GLCD RW at RB3 bit sbit D EN at RB4 bit sbit GLCD RST at RB5 bit sbit Gl DO Direction at TRISBO bit sbit DI Direction at TRISBI bit sbit Gl D2 D
263. be at least 100 sectors If it succeeds it sends the No of start sector over UART void M Create Swap File Size Mmc Fat Get Swap File 100 if size lt gt 0 UART1 Write OxAA UART1 Write o size VARTI Write size UART1 Write Highest size UART1 Write OxAA L H innit Mid te Higher siad y5 Notes Long File Names LFN are not supported Library Example The following example demonstrates usage of the MMC and MMC FAT routines Copy Code To Clipboard MMC module connections sbit Mmc Chip Select at LATG9 bit for writing to output pin always use latch sbit Mmc Chip Select Direction at TRISG9 bit eof MMC module connections const LINE LEN 43 char err txt 20 FAT16 not found char file contents LINE LEN XX MMC SD FAT16 library by Anton Rieckert n char filename 14 MIKROOO0x TXT File names unsigned short loop loop2 unsigned long i size char Buffer 512 UART1 write text and new line carriage return line feed void UART1 Write Line char uart text UART1 Write Text uart text UART1 Write 13 UART1 Write 10 Creates new file and writes some data to it void M Create New File filename 7 A Mmc Fat Set File Date 2011 1 12 11 9 0 Set file date amp time info Mmc_Fat_Assign filename 0xA0 Find existing file or create a new one Mmc Fat Rewrite To clear
264. bit sbit LCD D5 Direction at TRISB5 bit sbit LCD D6 Direction at TRISB6 bit sbit LCD D7 Direction at TRISB7 bit End LCD module connections float temp char txt 20 Convert ADC value to Celsius degrees format float ADC to degC float result result ADC1 Get Sample 8 Read ADC value from AN8 pin result 3 25 1024 result 5 0 01 return result void main CHECON 0x32 ADIPCFG OxFFF7 Configure AN8 pin as analog I O ADC1 Init Initialize ADC Delay 100ms Lcd Init Initialize LCD Lcd Cmd LCD CLEAR Clear LCD Lcd Cmd LCD CURSOR OFF f Turn cursor off Lcd Out 1 1 Temperature hae while temp ADC to degC Convert ADC value to Celsius degrees format FloatToStr temp txt Led Chr 2 13 223 Print degree character C for Centigrades Different LCD displays have different char code for degree Lcd Chr 2 14 C If you see greek alpha letter try typing 178 instead of 223 Lcd Out 2 5 txt Delay lsec MikroElektronika 210 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 cer
265. bles in the Watch Values Window by clicking de Add All button To remove a variable from the Watch Values Window just select the variable that you want to remove and then click the 96 Remove button or press the Delete key It is possible to remove all variables from the Watch Values Window by clicking k Remove All button You can also expand collapse complex variables i e struct type variables strings etc by clicking the appropriate button or beside variable name Watch Yalues 2E sh Bh Select variable from list WREGL na PC 0x00028E 9655 99 ms Double clicking a variable or clicking the amp Properties button opens the Edit Value window in which you can assign a new value to the selected variable register Also you can choose the format of variable register representation between decimal hexadecimal binary float or character All representations except float are unsigned by default For signed representation click the check box next to the Signed label Edit Value ADPCFG 0000 FFFF Representation Dec S Hex OBin O Float O Char Daes An item s value can also be changed by double clicking item s value field and typing the new value directly MikroElektronika 130 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
266. bly name gt C 17 it _text EY G hr ext i 1 5 1 FPS UL SESE Ae SUSE v Peripherals Freeze e Name Value Address ig text tion 0x0800 PC 0x0002CA 0 00 us MikroElektronika 120 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 mikrolCD and simulate hardware breakpoints Software breakpoints are much slower than hardware breakpoints These differences between hardware and software breakpoints are not visible in the mikrolCD software but their different timings are quite notable That s why it is important to know that there are two types of breakpoints The picture below demonstrates step by step execution of the code used in above mentioned examples Common Errors Trying to program the MCU while the mikrolCD is active Trying to debug Release build version of the program with the mikrolCD debugger Trying to debug program code which has been changed but has not been compiled and programmed into the MCU Trying to select line that is empty for Run to cursor F4 and Toggle Breakpoints F5 functions Trying to debug MCU with mikrolCD while Watch Dog Timer is enabled Tr
267. break f default kp 4 48 case 1 kp 49 break Uncomment this block for keypad4x4 case 2 kp 50 break case 3 kp 51 break case 4 kp 65 break case 5 kp 52 break case 6 kp 53 break case 7 kp 54 break case 8 kp 66 break case 9 kp 55 break case 10 kp 56 break case 11 kp 57 break case 12 kp 67 break case 13 kp 42 break case 14 kp 48 break case 15 kp 35 break case 16 kp 68 break MikroElektronika 346 OF OFQODAIWAGOAPWNE mikroC PRO for PIC32 UART1 Write Text Key pressed UART1 Write kp Send value of pressed button to UART UART1 Write 10 UART1 Write 13 while 1 HW Connection 4x4 Keypad connection scheme 34 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 Library Dependency Tree Lcd Lcd Constants Keypad Key Click The following variables must be defined s Description in all projects using Lcd Library extern sfr sbit LC Register Select line sbit LCD RS at LATDO bit extern sfr sbit LC Enabl
268. broutine Executes the program until reaching the cursor position Ctrl F8 L Toggle Breakpoint Toggle breakpoints option sets new breakpoints or removes those F5 a already set at the current cursor position ama Related topics Run Menu Debug Toolbar 117 MikroElektronika mikoC PRO for PIC32 mikrolCD Debugger Example Here is a step by step mikroICD Debugger Example a SEP No T 7 0L o0 oo S First you have to write a program We will show how the mikroICD works using this example Lcd module connections sbit LCD RS at LATDO bit sbit LCD EN at LATD1 bit sbit LCD D4 at LATBO bit sbit LCD D5 at LATBl bit sbit LCD D6 at LATB2 bit sbit LCD D7 at LATB3 bit sbit LCD RS Direction at TRISDO bit sbit LCD EN Direction at TRISD1 bit sbit LCD D4 Direction at TRISBO bit sbit LCD D5 Direction at TRISB1 bit sbit LCD D6 Direction at TRISB2 bit sbit LCD D7 Direction at TRISB3 bit End Lcd module connections char text mikroElektronika char i void Move Delay Delay ms 500 void main ADPCFG OxFFFF Lcd Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF for i 1 x 17 ate Led Ghr l ip textIi 1 MikroElektronika 118 mikroC PRO for PIC32 After successful compilation and MCU programming press F9 to start the mikrolCD After the mikroICD initialization a blue active line should appear e void main E 25 e
269. bytes of packet to transmit 1 UDP packet was sent successfully 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init unsigned char IpAddr 4 192 168 1 1 remote IP address Ethernet sendUDP IpAddr 10001 10001 Hello 5 send Hello messag to the above IP address from UDP port 10001 to UDP port 10001 MikroElektronika 454 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 tmax time in seconds to wait for an reply pointer to the location holding the IP address the requested host name was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time User should always copy the IP address from the RAM location returned by this routine into it s own resolved host IP address buffer These locations should not be altered by the user in any case unsign
270. c Time C TouchPanel amp v Trigonometry amp E rwr E UART Help M Examples 3 Uninstall package BinaryToGray GrayToBinary vi Related topics mikroC PRO for PIC Libraries Creating New Library MikroElektronika 64 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 Routine List ES Sort By Name Sort By Line Line 74 Line 50 C9iMove Delay Line 54 ishift Text Left Line 64 Sishift Text Right Statistics After successful compilation you can review statistics of your code Click the Statistics Icon Bu Memory Usage Windows Provides overview of RAM and ROM usage in the various forms 65 MikroElektronika mikoC PRO for PIC32 Variables Displays variables sorted by addresses Project Name C Development Systems V32MX v6l CD COG 2x16 cd mcp32 Time 1 31 2011 1 03 40 PM sere iit com Used RAM Locations Displays used RAM memory locations and their names Variables Sorted By Address Click on column header to sort table by Address Name Unique Assembler Name or Size mikro PRO for PIC32 SFR Locations Displays list of used SFR locations 387 88558858258589089889
271. 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 emc1 on any MCU when this box is checked or for a selected MCU when this box is left unchecked For more information on creating new libraries see Creating New Library mikroC PRO for PIC32 Options f Editor Output Settings V Generate ASM file V Include HEX opcodes ton v Include ROM constants Output Settings V Include ROM Addresses V Generate list File V Include debug info V Include source lines in output files Optimization level Four VW Enable SSA optimization Compiler F Case sensitive F Dynamic link For string literals V Build all files as library E Always build all files in project 87 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 drop down menu Tools Active Comments Editor or by clicking the Active Comment Editor Icon A from Tools toolbar Active Comments Editor Enter comment name activeComment Active Comment Actions New Rename Properties Attributes Url Image File J Events OnLeftClick Alt None OnRightClick OnDblClick OnMouseOver
272. card must be initialized See Mmc Init read sector 510 of the MMC SD card unsigned int error unsigned long sectorNo 510 char dataBuffer 512 rror Mmc Read Sector sectorNo dataBuffer Mmc Write Sector Prototype unsigned int Mmc Write Sector unsigned long sector char dbuff The function writes 512 bytes of data to one MMC card sector Parameters sector MMC SD card sector to be written to dbuf f data to be written buffer of minimum 512 bytes in length 0 if writing was successful 1 if there was an error in sending write command 2 if there was an error in writing data rejected MMC SD card must be initialized See Mmc Init write to sector 510 of the MMC SD card unsigned int error unsigned long sectorNo 510 char dataBuffer 512 36 MikroElektronika mikoC PRO for PIC32 Mmc Read Cid The function reads 16 byte CID register data cid buffer of minimum 16 bytes in length for storing CID register content 0 if CID register was read successfully if there was an error while reading MMC SD card must be initialized See Mmc Init unsigned int error char dataBuffer 16 rror Mmc Read Cid dataBuffer Mmc Read Csd TOYS unsigned int Mmc Read Csd char data csd The function reads 16 byte CSD register data csd buffer of minimum 16 bytes in length for storing CSD register content 0 if CSD register was read successfully if
273. ce clock in MHz rounded to the nearest integer unsigned long clk clk Clock Mhz Get Fosc kHz Prototype unsigned long Get Fosc kHz Description Function returns device clock in kHz rounded to the nearest integer Note that Get Fosc kHz is library function rather than a built in routine it is presented in this topic for the sake of c nvenience Parameters None Returns Device clock in kHz rounded to the nearest integer unsigned long clk clk Get Pose KH2 153 MikroElektronika mikoC PRO for PIC32 Get Fosc Per Cyc Prototype unsigned int Get Fosc Per Cyc Description 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 unsigned int clk per _ cyc clk per cyc Get Fosc Per Cyc KVAO TO KVA1 PRetums VruwadiesiWeKSEGI O OOOO Example xvan zo vat ox9rc00000 Moes None SSCS KVA1_TO_KVAO Prototype unsigned long KVA1 TO KVAO const unsigned long Address Function converts virtual address from KSEG 1 to the virtual address in the KSEGO Desired Virtual address in the KSEG1 Returns Virtual address in the KSEGO Example KVA1 TO KVAO O0xBFC00000 Moes None OSS
274. ce on either side The preprocessor removes whitespace and combining the separate tokens into one new token This is commonly used for constructing identifiers For example see the definition of macro SPLICE for pasting two tokens into one identifier define SPLICE x y x y Now the call SPLICE cnt 2 will expand to the identifier cnt 2 Note The mikroC PRO for PIC32 does not support the older nonportable method of token pasting using A7 7 x 261 MikroElektronika 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 Directives if elif Zelse and endif The conditional directives 4 if elif else and endif work very similar to the common C conditional statements If the expression you write after i has a nonzero value the line group immediately following the i directive is retained in the translation unit The syntax is if constant expression 1 section 1 elif constant expression 2 section 2 gt telif constant expression n section n gt felse final section endif Each
275. clicking the Project Level Defines node In the source code write the following if pld test 3 fendif There are number of predefined project level defines See predefined project level defines Note For inclusion of the header files extension n use the preprocessor directive include See File Inclusion for more information Related topics Project Manager Project Settings Edit Project MikroElektronika 668 mikroC PRO for PIC32 Source Files Source files containing source code should have the extension c The list of source files relevant to the application is stored in project file with extension mcp32 along with other project information You can compile source files only if they are part of the project Use the preprocessor directive include to include header files with the extension n Do not rely on the preprocessor to include source files other than headers see Add Remove Files from Project for more information Managing Source Files Creating new source file To create a new source file do the following 1 Select File New Unit from the drop down menu or press Ctrl N or click the New File Icon iL from the File Toolbar 2 Anew tab will be opened This is a new source file Select File Save from the drop down menu or press Ctrl S or click the Save File Icon H from the File Toolbar and name it as you want If you use the New Project Wizard an empty source file named after the project wit
276. cnt readbuff cnt HID Write amp writebuff 64 Do not use this functions with USB_Interrupt_Proc To enable servicing by polling USB INTERRUPT constant should be set to 0 it is located in descriptor file Gen Enable Prototype void Gen Enable char readbuff char writebuff Description Initialize the USB module of the MCU Parameters readbuff Read Buffer writebuff Write Buffer Nothing Requires USB needs to be enabled before using this function See HID_Enable 603 MikroElektronika mikoC PRO for PIC32 Gen Read Prototype char Gen Read char readbuff char length char ep Generic routine that receives the specified data from the specified endpoint Parameters readbuf f Received data length The length of the data that you wish to receive ep Endpoint number you want to receive the data into Returns Returns the number of received bytes otherwise 0 USB needs to be enabled before using this function See HID Enable a ie while Gen Read readbuff 64 1 B 9 Gen Write char Gen Write char writebuff char length char ep Sends the specified data to the specified endpoint Parameters writebuff The data that you want to send length the length of the data that you wish to send ep Endpoint number you want to send the data into Retums Returns the number of transmitted bytes otherwise 0 Requires USB needs to b
277. comment is any sequence of characters placed after the symbol pair The comment terminates at the first occurance of the pair following the initial The entire sequence including four comment delimiter symbols is replaced by one space after macro expansion In the mikroC PRO for PIC32 int type i identifier parses as Int i Note that the mikroC PRO for PIC32 does not support a nonportable token pasting strategy using For more information on token pasting refer to the Preprocessor Operators C comments The mikroC PRO for PIC32 allows single line comments using two adjacent slashes The comment can start in any position and extends until the next new line The following code int i this is a comment int j parses as int i int J Nested comments ANSI C doesn t allow nested comments The attempt to nest a comment like this int declaration i fails because the scope of the first ends at the first This gives us ig cw which would generate a syntax error TII MikroElektronika 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 punc
278. component of the image rgb green green component of the image rgb blue blue component of the image TFT module needs to be initialized See the TFT_Init routine Example colorle TFT Image Jpeg 150 193 65 TFT Color16bitTOoRGB Prototype void TFT e int color char rgb red char rgb green char rgb blue Description Converts true color into 5 6 5 RGB format Parameters color true color to be converted rgb red red component of the input color rgb green green component of the input color rgb blue blue component of the input color TFT module needs to be initialized See the TFT Init routine ane p ee amp red start amp green start amp blue start 911 MikroElektronika mikoC PRO for PIC32 HW Connection TFT 320x240 display MI0283QT2 TFT HW connection MikroElektronika 918 mikroC PRO for PIC32 Touch Panel Library The mikroC PRO for PIC32 provides a library for working with Touch Panel Library Dependency Tree Touch Panel aoc External dependencies of Touch Panel Library The following variables must be defined in Description all projects using Touch Panel Library extern sfr sbit DriveA DriveA line sbit DriveA at LATC13 bit extern sfr sbit DriveB sbit DriveB at LATC14 bit extern sfr sbit DriveA Direction Direction of the DriveA pin soit DriveA Direction at TRISCI3 bit extern sfr sbit DriveB Direction Direction of
279. 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 These functions are equivalent to procedures of other programming languages such as Pascal C does not distinguish between procedure and function functions play both roles Each program must have a single external function named main marking the entry point of the program Functions are usually declared as prototypes in standard or user supplied header files or within program files Functions have external linkage by default and are normally accessible from any file in the program This can be restricted by using the static storage class specifier in function declaration see Storage Classes and Linkage Note Check the PIC32 Specifics for more information on functions limitations on the PIC32 MCUs Function Declaration Functions are declared in user s source files or made available by linking precompiled libraries The declaration syntax of the function is type function name parameter declarator list The function name must be a valid identifier This name is used to call the function see Function Calls for more information type represents the type of function result and can be of any standard or user defined type For functions that do not return value the void type should be used The type can be omitted i
280. count against the nested call limit Returns High byte of number bits 15 8 0x12345678 tmp Hi d Equals 0x56 MikroElektronika 118 mikroC PRO for PIC32 Higher Prototype define Higher param char amp param 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 number input number Returns Higher byte of number bits 23 16 d 0x12345678 tmp Higher d Equals 0x34 Highest Prototype define Highest param char amp param 3 Description The function returns highest 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 number input number Returns Highest byte of number bits 31 24 0x12345678 tmp Highest d Equals 0x12 149 MikroElektronika mikoC PRO for PIC32 LoWord Prototype unsigned int LoWord unsigned long number Description The function returns low word of number The function does not interpret bit patterns of number it merely returns 16 bits as
281. cro expansion coken sequence terminates at the first non backslashed new line encountered Any sequence of whitespace including comments in the token sequence is replaced with a single space character After each individual macro expansion a further scan is made of the newly expanded text This allows the possibility of using nested macros the expanded text can contain macro identifiers that are subject to replacement However if the macro expands into something that looks like a preprocessing directive such directive will not be recognized by the preprocessor Any occurrences of the macro identifier found within literal strings character constants or comments in the source code will not be expanded 251 MikroElektronika 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 Attempting to redefine an already defined macro identifier will result in a warning unless a new definition is exactly the same token by token definition as the existing one The preferred strategy when definitions might exist in other header files is as follows ifndef BLOCK SIZE define BLOCK SIZE 51 2 fendif The middle lin
282. ctions 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 Previewlmage Shows image when cursor is moved over a comment 2 None Does nothing Attributes are tightly bounded with events For example you can not have OnLeftClick Alt gt OpenFile if there is no file attribute set or if there is no file added to project The same behavior applies to image attribute Let s start editing our Active Comment by entering some valid web address in the URL field J Attributes www mikroe com Image File J Events OnLeftClick Alt i OnRightClick OnDbiClick OnMouseOver For every Active Comment a XML file will be created containing all valid information regarding the Active Comment attributes events etc and it is automatically added to Project manager after saving it Project Manager c Radni mikroC PRO for PI X Ae 8E i Le i Se Pb Easy_GSM_GPRS mcp32 ea Sources amp Easy G5M GPRS c 7 Header Files Binaries C73 Project Level Defines S 7j Image Files Easy GSM GPRS jpg EEPROM Files S E Active Comments Files feat LE activeComment xml E C7 Output Files Other Files MikroElektronika 98 mikroC PRO for PIC32 You can see the contents of the created XML file by expanding Active C
283. d characters If a number of characters in the output value is less than width blanks are added on the left or right when the flag is specified in order to pad to the minimum width If the width is prefixed with 0 then zeros are padded instead of blanks The width field never truncates a field If the length of the output value exceeds the specified width all characters are output mikoC PRO for PIC32 decimal point The last digit is rounded The precision field is where you specify the number of digits to the right of the decimal point The last digit is rounded The precision field is where you specify the maximum number of significant digits in the output value c The precision field has no effect on these field types The precision field is where you specify the maximum number of characters in the output value Excess characters are not output The optional characters 1 or L may immediately precede conversion type to respectively specify long versions of the integer types d i u o x and X You must ensure that the argument type matches that of the format specification You can use type casts to ensure that the proper type is passed to printout Print mikroElektronika example s header file to UART void PrintHandler char c UART1 Write c void main UART1 Init 9600 Delay ms 100 PrintOut PrintHandler r n Project name r n PrintOutExample Sample usage of PrintOut function
284. d for SPI communication see SPI Lcd Config routine Wis Write character i at row 2 column 3 SPI Lcd Chr 2 3 i SPI Lcd Chr Cp Mieto Prints character on Lcd at current cursor position Both variables and literals can be passed as character Out Char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write character e at current cursor position SPI Lcd Chr Cp e MikroElektronika 902 mikroC PRO for PIC32 SPI Lcd Cmd Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Clear Lcd display SPI Lcd Cmd LCD CLEAR Predefined constants can be passed to the routine see Available SPI Lcd Commands Available SPI Lcd Commands LCD RETURN HOME Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected 503 MikroElektronika mikoC PRO for PIC32 Library Example Default Pin Configuration Use SPI Lcd Init for default pin settings see the first figure below Copy Code To Clipboard char text mikroElektronika Port Expander module connections sbit SPExpanderRST at LATD8 bit sbit SPExpanderCS at LATD9 bit sbit SPExpanderRST Direction at TRISD8 bit sbit SPExpanderCS Direction at TRISD9 bit End Port Expander module connections char i Loop variable void Move Delay
285. d in declaration by assigning it a comma delimited sequence of values within braces When initializing an array in declaration you can omit the number of elements it will be automatically determined according to the number of elements assigned For example Declare an array which holds number of days in each month int days 12 31 28 31 30 931 30 31 31 30 31 30 31 This declaration is identical to the previous one int days 31 28 31 30 531 930 91 31 30 31 930 31 If you specify both the length and starting values the number of starting values must not exceed the specified length The opposite is possible in this case the trailing excess elements will be assigned to some encountered runtime values from memory In case of array of char you can use a shorter string literal notation For example The two declarations are identical const char msgl T e s t N0 const char msg2 Test For more information on string literals refer to String Constants 201 MikroElektronika mikoC PRO for PIC32 Arrays in Expressions When the name of an array comes up in expression evaluation except with operators amp 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 v
286. d 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 Message flags are retrieved and stored to location provided by the CANSPI RX MSG FLAGS parameter Parameters id message identifier address data an array of bytes up to 8 bytes in length dataLen data length address CANSPI RX MSG FLAGS message flags address For message receive flags format refer to CANSPI RX MSG FLACS constants See CANSPI RX MSG FLAGS constants 0 if nothing is received OxFFFF if one of the Receive Buffers is full message received Requires The CANSPI module must be in a mode in which receiving is possible See CANSPISetOperationMode 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 See connection example at the bottom of this page check the CANSPI module for received messages If any was received do something unsigned short msg rcvd rx flags data len char data 8 unsigned long msg id CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode CANSPI module must be in mode in which receive is possible rx flags 0 clear message flags msg rcvd CANSPIRead msg id data data len rx flags MikroElektronika 218 mikroC PRO for PIC32 CANSPIWrite Prototype
287. d to by right 5 expressionlis a pointer and expression2 is a null pointer constant Unary Operators Unary operators are operators that take exactly one argument Unary Arithmetic Operators Unary operators and are the only operators in C which can be either prefix e g k Xx or postfix e g k k When used as prefix operators and preincrement and predecrement add or subtract one from the value of the operand before the evaluation When used as suffix operators and postincrement and postdecrement add or subtract one from the value of the operand after the evaluation unary plus does not affect the operand I unary minus changes the sign of the operand increment adds one to the value of the operand Postincrement adds one to the value of the operand after it evaluates while preincrement adds one before it evaluates decrement subtracts one from the value of the operand Postdecrement subtracts one from the value of the operand after it evaluates while predecrement subtracts one before it evaluates For example int j 5 J k k k 1 j k which gives us j 6 k i Oy na but int j 5 j k j k k k 1 which gives us j 5 k i Oo Ruf 245 MikroElektronika 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
288. d values 2 Timer2 and 3 Timer3 OxFFFF if timer settings are not valid otherwise returns calculated timer period MCU must have the HW PWM Module Initializes the PWM module at 5KHz channel 1 no clock prescale timer2 unsigned int pwm periodl pwm periodi PWM Init 5000 1 0 2 Notes Number of available PWM channels depends on MCU Refer to MCU datasheet for details PWM Init Advanced Prototype unsigned int PWM Init Advanced unsigned long freq hz unsigned long Fpb_ kHz unsigned int enable channel x unsigned int timer prescale unsigned int use timer x Initializes the PWM module with duty ratio O Parameters freq hz PWM frequency in Hz Fpb kHz Peripheral Bus Clock frequency in kHz enable channel x number of PWM channel to be initialized Refer to MCU s datasheet for available PWM channels timer prescale timer prescaler parameter Valid values 1 8 64 and 256 use timer x timer to be used with the PWM module Valid values 2 Timer2 and 3 Timer3 Oxrrrr if timer settings are not valid otherwise returns calculated timer period MCU must have the HW PWM Module Initializes the PWM module at 5KHz channel 1 no clock prescale timer2 unsigned int pwm periodl pim periodl PWM Init 5000 1 0 2 Number of available PWM channels depends on MCU Refer to MCU datasheet for details 401 MikroElektronika mikoC PRO for PIC32 PWM Set Duty Prototype void PWM
289. ddress Invoice If you do not specify 2CO Number or invoice number then the license key request must be processed 2CO Number manually which can take longer time Email jsmitnexample com Re enter email smitnoexample com Company Product ID Comment Distributor MikroElektronika progrant 744 Submit Related Links Products News Forums Distributors About Mikro lektronika Legal Information and Privacy Policy Product Archive Contact Us Copyright 1996 2010 MikroElektrontka All rights reserved Al trade and or services marks mentioned are the property of their respective owners 35 MikroElektronika mikoC PRO for PIC32 Fill out the registration form select your distributor and click the Submit button If you choose work offline registering method following window will be opened How To Register Step 1 Fill in the form below Please make sure you fill in all required fields Step 2 Make sure that you provided a valid email address in the EMAIL edit box This email will be used for sending you the activation key Step 3 Make sure you select a correct distributor which will make the registration process faster If your distributor is not on the list then select Other and type in distributor s email address in the box below Step 4 Press the SEND button to send key request default email client will open with ready to send message Note If email client does not open you may copy te
290. de char image 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 Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw image my image on Glcd SPI Glcd Image my image Use the mikroC PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd SPI Glcd Partiallmage Prototype void SPI Glcd Partiallmage unsigned int x left unsigned int y top unsigned int width unsigned int height unsigned int e ict width unsigned int picture height code const unsigned short image Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroC PRO for PIC pointer to const and pointer to RAM equivalency Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draws a 10x15 part of the image starting from the upper left corner on the c
291. delay ms 500 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 Now you can keep typing to narrow the choice or you can select one from the list using the keyboard arrows and Enter 2H variable sfr unsigned char SP variable sfr unsigned char SPDR variable sfr unsigned char SPSR variable sfr unsigned char SPCR Parameter Assistant The Parameter Assistant will be automatically invoked when you open parenthesis or press Shift Ctrl Space If the name of a valid function precedes the parenthesis then the expected parameters will be displayed in a floating panel As you type the actual parameter the next expected parameter will become bold channel char DC Rea Bookmarks Bookmarks make navigation through a large code easier To set a bookmark use Ctrl Shifttnumber The same princliple applies to the removal of the bookmarks To jump to a bookmark use Ctrl number Go to Line The Go to Line option makes navigation through a large code easier Use the shortcut Ctrl G to activate this option MikroElektronika 54 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 colum
292. dentifiers are in upper case identical to nomenclature in the Microchip datasheets All PIC32 SFR registers are also available as structures with bitfields named identically to the Microchip datasheets in order to facilitate bit access e g TRISBbits TRISB3 1 For a complete set of predefined globals and constants look for Defs in the mikroC PRO for PIC32 installation folder or probe the Code Assistant for specific letters Ctrl Space in the Code Editor Predefined project level defines mikroC PRO for PIC32 provides several predefined project level defines that you can use in your project First one is equal to the name of selected device for the project i e if P322MX460F512L is selected device then P32MX460F512L token will be defined as 1 so it can be used for conditional compilation ifdef P32MX460F512L endif The second one is value of frequency in KHz for which the project is built ifdef FOSC 80000 endif Third one is for identifying mikroC PRO for PIC32 compiler ifdef MIKROC PRO FOR PIC32 endif Fourth one is for identifying the build version For instance if a desired build version is 142 user should put this in his code IE MIKROC PRO FOR PIC32 BUILD 142 endif Related topics Project Level Defines 137 MikroElektronika mikoC PRO for PIC32 Accessing Individual Bits The mikroC PRO for PIC32 allows you to access individual bits of 32 bit variables It also suppor
293. dians The return value is from 1 to 1 doub cos PI 3 doub 0 500008 611 MikroElektronika mikoC PRO for PIC32 cosh Prototype double cosh double x Description Function returns the paul cosine of x defined mathematically as e e 2 If the value of x is too ae if overflow occurs the function fails doub cosh PI 3 doub 1 600286 exp Prototype Function returns the value of e the base of natural logarithms raised to the power x i e eX Example doub exp 0 5 doub 1 648721 fabs Prototype double fabs double d Function returns the absolute i e positive value of d Example doub fabs 1 3 doub 1 3 floor Prototype double floor double x Function returns the value of parameter x rounded down to the nearest integer Example doub floor 15 258 doub 15 000000 frexp Prototype double frexp double value int eptr Function splits a floating point value into a normalized fraction and an integral power of 2 The return value is the normalized fraction and the integer exponent is stored in the object pointed to by eptr MikroElektronika 612 mikroC PRO for PIC32 Idexp Prototype double ldexp double value int newexp Description Function returns the result of multiplying the TEE point number num by 2 raised to the power n i e returns x 2 Example doub ldexp 2 doub Prototype double log doubl
294. ditor tab will become active Printing an open file 1 Make sure that the window containing the file that you want to print is the active window 2 Select File gt Print from the drop down menu or press Ctrl P 3 In the Print Preview Window set a desired layout of the document and click the OK button The file will be printed on the selected printer Saving file 1 Make sure that the window containing the file that you want to save is the active window 2 Select File Save from the drop down menu or press Ctrl S or click the Save File Icon Hd from the File Toolbar si mikoC PRO for PIC32 Saving file under a different name 1 Make sure that the window containing the file that you want to save is the active window 2 Select File Save As from the drop down menu The New File Name dialog will be displayed 3 In the dialog browse to the folder where you want to save the file 4 In the File Name field modify the name of the file you want to save 5 Click the Save button Closing file 1 Make sure that the tab containing the file that you want to close is the active tab 2 Select File Close from the drop down menu or right click the tab of the file that you want to close and select Close option from the context menu 3 If the file has been changed since it was last saved you will be prompted to save your changes Search Paths You can specify your own custom search paths select Project Edit Search
295. dow Read code 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 Also you can set an address scope in which hex code will be read CODE Watch Address Scope Read Code 000000 008000 Ps A75010 AS22CA 470060 A64010 4902C4 474010 AB802CA 2088C0 DLE PS G DLE E A60010 AS02D6 A70010 A902D6 07FF96 470060 463010 A962CA lt DLE gt STX DL A73010 A862CA 470060 A62010 A942CA A72010 A842CA 470060 lt DLE gt 05 b G lt DLI A61010 A922CA A71010 AS22CA 470060 A60010 a902cA A70010 DLE lt DLE gt E DI AB02CA 2088CO A60010 A802D6 A70010 A902D6 O7FF7C 2088C0 STX SPC D A60010 370002 07FF64 370001 O7FF86 FAB8000 060000 FA0002 DLE STX 7dy lt 37000F 200800 9FBF40 370019 200C00 9FBF40 370016 200940 SI 7 B5 SPC S9FBF40 370013 200D40 9FBF40 370010 200800 9FBF40 370000 lt DC3 gt 7 CR 97B84E 10061 32FFEE 97B84E E10062 32FFEE 97B84E E10063 N a iy2N b 32FFEE 97BB84E E10064 32FFEE 37FFF 97B83E 5000E1 5700068 iy2N d iy28y7 gt 408010 9FBF40 781F80 07FF98 B1002F 2088CO0 A10010 EF2000 lt DLE gt US 980700 97B8AE 470060 408010 E00410 32000C 97B8AE 470060 BELL 9
296. drop down menu The EEPROM Watch Window shows current content of the MCU s internal EEPROM memory There are two action buttons concerning the EEPROM Watch Window Read EEPROM Reads data from MCU s internal EEPROM memory and loads it up into the EEPROM window Write EEPROM Writes data from the EEPROM window into MCU s internal EEPROM memory EEPROM Watch STATUS Idle MikroElektronika 132 mikroC PRO for PIC32 Code Watch Window Note Code Watch Window is available only when mikrolCD 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 Read Code 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 Also you can set an address scope in which hex code will be read CODE Watch Address Scope Read Code 000000 008000 if A75010 AB22CA 470060 A64010 A902CA A74010 ABD2CA 2088C0 DLE PS G DLEIE A60010 AS02D6 A70010 AS02D6 07FF96 470060 A63010 A962CA DLE STX DL A73010 AG62CA 470060 A62010 A942CA A72010 AS42CA 470060 DLE 0S b G DUI A61010 AS22CA A71010 A822CA 470060 A60010 A902CA A70010 DLE DLE i
297. dule Pins of UART need to be attached to RS 485 interface transceiver such as LTC485 or similar see schematic at the bottom of this page Library constants START byte value 150 STOP byte value 169 Address 50 is the broadcast address for all Slaves packets containing address 50 will be received by all Slaves except the Slaves with addresses 150 and 169 Important The library uses the UART module for communication The user must initialize the appropriate UART module before using the RS 485 Library For MCUs with multiple UART modules it is possible to initialize them and then switch by using the UART Set Active routine Library Dependency Tree Rs485 uaRT External dependencies of RS 485 Library The following variable must be defined BascHatioiE in all projects using RS 485 Library P extern sfr sbit RS485 rxtx pin Pon Rea geo a d d sbit RS485 rxtx pin at RF2 bit operation mode extern sfr sbit RS485 rxtx pin Direction of the RS 485 Transmit sbit RS485 rxtx pin direction at direction Receive pin TRISE2 bit 405 MikroElektronika mikoC PRO for PIC32 Library Routines RS485Master Init RS485Master Receive RS485Master Send RS485Slave Init RS485Slave Receive RS485Slave Send RS485Master Init RMums Nothing O OOOO O Requires Global variables RS485 rxtx pin this pin is connected to RE DE input of RS 485 transceiver see schematic at
298. e The user can use fonts given in the file Lib GLCDFonts file located in the Uses folder or create his own fonts List of supported fonts Font Glcd System3x5 Font Glcd System5x7 Font Glcd 5x7 Font Glcd Character8x7 For the sake of the backward compatibility these fonts are supported also System3x5 equivalent to Font Gl1cd System3x5 FontSystem5x7 v2 equivalentto Font Glcd System5x7 font 5x7 equivalent to Font Glcd 5x7 Character8x7 equivalent to Font Glcd Character8x7 Nothing Glcd needs to be initialized see Glcd Init routine Use the custom 5x7 font myfont which starts with space 32 Glcd Set Font amp myfont 5 7 32 Notes Ne OOS 339 MikroElektronika 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 2 The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized see Glcd Init routine Use Glcd Set Fontto specify the font for display if no font is specified then default Font Gicd
299. e ney no poddns ue ios Soiu MMM ye 1exon INOA eoejd se jd uoneuuojJul EUSUUUS pasu uneni spnpoud ino Jo ie YIM V Sueqoid aulos ete de ale noA j WOT G0 XIU WM 3 9JISq9A JNO YISA esed sionpoid igne aow uJee A nof Q THOM Q30Q038WH HO4 SNOILL YTIOS 3H VMQHVH ANY gps eshte
300. e SSA user should regard the following rules during the coding process Routines should not contain too many parameters not more than 4 words Don t change the value of the parameter in the function body it is better to use a new local variable If the functionl parameters are passed as function2 parameters then parameter order should remain the same f2 int a ant b f fl int x ant y routine call f2 x y f2 y x x a and y gt b 1 to 1 and 2 to 2 is far more efficient than Z ya and gt b 1 to 2 and 2 to 1 Large amount of nested loops and complex structures as its members should be avoided When writing a code in assembly keep in mind that there are registers reserved exclusively for routine parameters Using goto and 1abe1 statements in nested loops should be avoided Obtaining address of the local variable with the global pointer and using it to alter the variable s address should be avoided Notes emc1 files compiled with or without SSA enabled are fully compatible and can be used and mixed without any restrictions except function pointers All function prototypes and function pointers have to be built using the same optimizer because of different calling conventions in different optimizers In SSA function parameters are passed via working registers and without SSA they end up on the function frame This means that you cannot have a function implementation which is opti
301. e declaration in this way if p is an object of type then p has to be a pointer to such object object of type Note You must initialize pointers before using them Our previously declared pointer p is not initialized i e assigned a value so it cannot be used yet In case of multiple pointer declarations each identifier requires an indirect operator For example int pa pb pc is same as int pa int pb int ee Once declared though a pointer can usually be reassigned so that it points to an object of another type The mikroC PRO for PIC32 lets you reassign pointers without typecasting but the compiler will warn you unless the pointer was originally declared to be pointing to void You can assign the void pointer to the non void pointer refer to void for details 203 MikroElektronika 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 sse The pointer type pointer to void must not be confused with the null pointer The declaration void vp declares that vp is a generic pointer capable of being assigned to by any pointer to type value including null without complaint Assignments without p
302. e enabled before using this function See HID Enable while Gen Write writebuff 64 1 0 None MikroElektronika 604 mikroC PRO for PIC32 Library Example This example establishes connection with the HID terminal that is active on the PC Upon connection establishment the HID Device Name will appear in the respective window After that software will wait for data and it will return received data back Examples uses USBdsc c descriptor file which is in the same folder and can be created by the HID Terminal Copy Code To Clipboard char cnt char kk char readbuff 64 char writebuff 64 unsigned long int i 0 void main void CHECON 0x32 ADIPCFG OxFFFF HID Enable amp readbuff amp writebuff while 1 USB Polling Proc kk HID Read if kk 0 for cnt 0 cnt lt 64 cnt writebuff cnt readbuff cnt HID Write amp writebuff 64 HW Connection lt Q O ENVREG omm l Q z o vec vec nnnnnnnnn Oo lt Q o e H veces USB connection scheme PIC32MX460F512L IGND vec IGND vcc GND GNDE OSC1L3 VCC RG2 RG3 VUSB VBUS ovcca3 HN Call this routine periodically OSCILLATOR m vsus OI USB o GND MikroElektronika mikoC PRO for PIC32 Standard ANSI C Libraries ANSI C Ctype Library ANSI C Math Librar
303. e expected the error flag will be set to non zero Returns A byte read from the incoming signal To use this function the user must prepare the MCU for receiving See Man Receive Init routines unsigned int data 0 error 0 data Man Receive amp error if Ay gi error handling Man Send Init Reums Noting SSS Requires Global variables MANTXPIN Transmit line MANTXPIN Direction Direction of the transmit pin must be defined before using this function Initialize Transmitter sbit MANTXPIN at LATF1 bit sbit MANTXPIN Direction at TRISF1 bit Man Send Init MikroElektronika 396 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 Nothing Requires To use this function the user must prepare the MCU for sending See Man Send Init routine unsigned int msg Man Send msg Baud rate used is 500 bps Man Synchro Prototype Measures half of the manchester bit length with 10us resolution 0 if synchronization was not successful Half of the manchester bit length given in multiples of 10us upon successful synchronization To use this function you must first prepare the MCU for receiving See Man Receive Init 39 MikroElektronika mikoC PRO for PIC32 Man Break Prototype void Man Break Description Man Receive is blocki
304. e function will return the code of the first pressed key Parameters None The code of a clicked key 1 16 If no key is clicked returns O Port needs to be initialized for working with the Keypad library see Keypad Init kp Keypad Key Click 945 MikroElektronika 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 Copy Code To Clipboard unsigned short kp oldstate 0 char txt 6 Keypad module connections unsigned long keypadPort at PORTD unsigned long keypadPort Direction at TRISD End Keypad module connections void main ADIPCFG OxFFFF CHECON 0x32 UART1 Init 19200 Initialize UART module at 9600 bps Delay ms 10 Keypad Init Initialize Keypad UART1 Write Text Press any key on your keypad UART1 Write 10 UART1 Write 13 LATD 0 do kp 0 Reset key code variable Wait for key to be pressed and released do kp Keypad Key Press Store key code in kp variable kp Keypad Key Click Store key code in kp variable while kp Prepare value for output transform key to it s ASCII value switch kp case 10 kp 42 break Uncomment this block for keypad4x3 case 11 kp 48 break 0 case 12 kp 35
305. e is bypassed if BLOCK SIZE is currently defined if BLOCK SIZE is not currently defined the middle line is invoked to define it Macros with Parameters The following syntax is used to define a macro with parameters define macro identifier lt arg list token sequence Note that there can be no whitespace between macro identifier and The optional arg list is a sequence of identifiers separated by commas like the argument list of a C function Each comma delimited identifier has the role of a formal argument or placeholder Such macros are called by writing macro identifier actual arg list in the subsequent source code The syntax is identical to that of a function call indeed many standard library C functions are implemented as macros However there are some important semantic differences The optional actual arg list must contain the same number of comma delimited token sequences known as actual arguments as found in the formal arg list of the define line there must be an actual argument for each formal argument An error will be reported if the number of arguments in two lists is not the same MikroElektronika 258 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
306. e is generated in the place of a call so the call doesn t count against the nested call limit The Vdelay ms Vdelay advanced ms Delay Cyc Delay Cyc Long Get Fosc kHz and Get Fosc Per Cyc are actual C routines Their sources can be found in Delays c file located in the uses folder of the compiler Lo Hi Higher Highest LoWord HiWord Delay_us Delay_ms Vdelay_ms Vdelay_Advanced_ms Delay_Cyc Delay_Cyc_Long Clock_kHz Clock_MHz Get_Fosc_kHz Get_Fosc_Per_Cyc KVAO TO KVA1 KVA1 TO KVAO KVA TO PA PA TO KVAO PA TO KVA1 CPO Get CPO Set Enablelnterrupts Disablelnterrupts 14 MikroElektronika mikoC PRO for PIC32 Prototype define Lo param char amp param 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 Returns Low byte of number bits 7 0 d 0x12345678 tmp Lo d Equals 0x78 Prototype define Hi param char amp param 1 Description The function returns high 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
307. e line sbit LCD EN at LATD1 bit extern sfr sbit LCD D4 Data 4 line sbit LCD D4 at LATBO bit Data 5 line sbit LCD D5 at LATBl1 bit Data 6 line sbit LCD D6 at LATB2 bit extern sfr sbit Data 7 line sbit LCD D7 at LATB3 bit extern sfr LCD RS 3 P i Direction i Register Select direction pin Direction extern sfr sbit LCD D4 i Direction i Data 4 direction pin eS Direction extern sfr sbit LCD DS i Direction Data 5 direction pin f dii Direction i extern sfr sbit LCD D6 i i Direction Data 6 direction pin Direction extern sfr sbit LCD D7 i Direction Data 7 direction pin f Direction Library Routines extern sfr sbit LCD EN l i Direction Enable direction pin Direction Lcd Init Lcd Out Lcd Out Cp Lcd Chr Lcd Chr Cp Lcd Cmd MikroElektronika 348 mikroC PRO for PIC32 Lcd Init Requires Global variables LC LC LC LC LC LC LC LC LC LC sme LC A d Dd od od a eti ae RS Register Select data instruction signal pin Enable signal pin Data bit 4 Data bit 5 Data bit 6 Data bit 7 Direction Direction of the Register Select pin EN Direction Direction of the Enable signal pin D4 Direction Direction of the Data 4 pin D5 Direction Direction of the Data 5 pin D6 Direction Direction of the
308. e operator 231 MikroElektronika 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 fF put te Saf dos equals 5 25 because we are working with floats Remainder operand works only with integers the sign of result is equal to the sign of the first operand for example 9 3 equals 0 Y 3 equals 1 7 3 equals 1 Arithmetic operators can be used for manipulating characters VAT 323 equals a ASCII only XG YAY al equals g both ASCII and EBCDIC Unary Arithmetic Operators Unary operators and are the only operators in C which can be either prefix e g x or postfix e g k k When used as prefix operators and preincrement and predecrement add or subtract one from the value of the operand before the evaluation When used as suffix operators and postincrement and postdecrement add or subtract one from the value of the operand after the evaluation For example int j 5 j k k k 1 j k which gives us j 6 k 6 but int j 5 j k j k k k 1 which gives us j 5 k 6 MikroElektronika 238 mikroC PRO for PIC32 Relational Operators Use relational operators to test equality or inequality of expressions
309. e the appropriate TRISx bits to designate pins as inputs The function sets the appropriate bit in the AD1PCFG registers to enable analog function of the chosen pin Refer to the appropriate Datasheet for channel to pin mapping unsigned adc value adc value ADC1 Get Sample 10 read analog value from ADC module channel 10 ADCx Read Retums 10 bit unsigned vale from the speciied narse S Requires The MCU with built in ADC module Before using the function be sure to configure the appropriate TRISx bits to designate pins as inputs unsigned adc value adc value ADC1 Read 10 read analog value from ADC1 module channel 10 The function sets the appropriate bit in the ADPCFG registers to enable analog function of the chosen pin Refer to the appropriate Datasheet for channel to pin mapping uli This is a standalone routine so there is no need for a previous initialization of ADC module 269 MikroElektronika mikoC PRO for PIC32 Library Example This code snippet reads analog value from the channel 1 and sends readings as a text over UART1 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
310. e x Function returns the natural logarithm of x i e Log x Example doub log 10 doub 2 302585E log10 Prototype Function returns the base 10 logarithm of x i e Log x Example doub 1og10 100 doub 2 000000 modf Prototype double modf double val double iptr Description Function returns the signed fractional component of va1 placing its whole number component into the variable pointed to by iptr Example dov modf 6 25 amp iptr doub 0 25 iptr 6 00 pow Prototype double pow double x double y Description Function returns the value of x raised to the power y i e xY If x is negative the function will automatically cast y into unsigned long Example doub pow 10 5 doub 9 999984e44 613 MikroElektronika mikoC PRO for PIC32 sin Prototype double sin double f Function returns the sine of in radians The return value is from 1 to 1 Example doub sin PI 2 doub 1 000000 sinh Prototype double sinh double x Description Function returns the hyperbolic sine of x defined mathematically as e e 2 If the value of x is too large if overflow occurs the function fails doub sinh PI 2 doub 2 301296 Prototype double sqrt double x Function returns the non c square root of x Example doub sqrt 10000 doub 100 0000 tan Prototype Description Function ret
311. eater one of its 2 arguments int max int x int y return x gt y x y 231 MikroElektronika 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 lt math h gt void polar double x double y double r double i tE sqrt x x y y fi x 0 amp amp y 0 0 atan2 y x return this 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 Function Calls and Argument Conversions Function Calls A function is called with actual arguments placed in the same sequence as their matching formal parameters Use the function call operator function name expression 1 expression n Each expression in the function call is an actual argument Number and types of actual arguments should match those of formal function parameters If types do not match implicit type conversions rules will be applied Actual arguments can be of any complexity but order of their evaluation is not specified Upon function call all formal parameters are created as local objects initialized by the values of actual arguments Upon return from a function a temporary object is created in the place of the call and it is initialized by the expression of the return st
312. ecrement function call increment Each constant expression can evaluate to a constant that is in the range of representable values for its type Constant expression can be used anywhere a constant is legal 185 MikroElektronika 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 TMRO PCL etc Probe the Code Assistant for specific letters CtrltSpace in Editor or refer to Predefined Globals and Constants Here is an alphabetical listing of keywords in C absolute asm at auto DIE bool break case catch char class code Const continue data default delete dma do double else enum explicit extern false far float for friend Goto 3f inline ant sx long mutable namespace near Operator Org pascal private MikroElektronika 186 mikroC PRO for PIC32 protected public register return oe Sir Short signed sizeof Static Struct switch template EDS throw true try typedef typeid typename union unsigned using virtual Onc volatile while xdata ydata Also the mikroC PRO fo
313. ectors Multidimensional arrays are constructed by declaring arrays of array type These arrays are stored in memory in such way that the right most subscript changes fastest i e arrays are stored in rows Here is a sample of 2 dimensional array float m 50 20 2 dimensional array of size 50x20 A variable m is an array of 50 elements which in turn are arrays of 20 floats each Thus we have a matrix of 50x20 elements the first element is m 0 0 the last one is m 49 19 The first element of the 5th row would be m 4 0 If you don t initialize the array in the declaration you can omit the first dimension of multi dimensional array In that case array is located elsewhere e g in another file This is a commonly used technique when passing arrays as function parameters int a 3 2 4 3 dimensional array of size 3x2x4 void func int n 21 4 we can omit first dimension n 2 1 3 increment the last element void main func a You can initialize a multi dimensional array with an appropriate set of values within braces For example int a 3 2 1 2 2 6 3 7 MikroElektronika 202 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 o
314. ed Project File Name C Hello World Hello World mcpds Cancel Step Four Add project file to the project if they are avaiable at this point You can always add project files later using Project Manager New Project Wizard Step 4 6 Add project files if they are available at this point You can always add project files later using the Project Manager in IDE Add File To Project C Projects Hello World h File Name C Projects Hello World h Remove Remove All Next gt Cancel 663 MikroElektronika mikoC PRO for PIC32 Step Five Select inital Library Manager state New Project Wizard Step 5 6 Select initial Library Manager state Include Libraries Include all Default Include None Advanced Selecting all libraries is recommended For beginners Selecting libraries manually using Library Manager recommended For advanced users results in Faster compilation Libary Manager Help Next gt Cancel Step Six Click Finish button to create your New Project New Project Wizard Step 6 6 You have successfully created a new project Click Finish to save the changes and to close the wizard J Open Edit Project window to set Configuration bits Einish Cancel Related topics Project Manager Project Settings MikroElektronika O 68 mikroC PRO for PIC32 Customizing Projects You can change basic project settings in the Project Settings window Y
315. ed For example two sequences int i float f and int i float f are lexically equivalent and parse identically to give six tokens int Whitespace in Strings The ASCII characters representing whitespace can occur within string literals In that case they are protected from the normal parsing process they remain as a part of the string For example N char name mikr foo parses into seven tokens including a single string literal token char name mikro foo just one token here Line Splicing with Backslash V A special case occurs if a line ends with a backslash Both backslash and new line character are discarded allowing two physical lines of a text to be treated as one unit So the following code mikroC PRO for PIC32 Compiler parses into mikroC PRO for PIC32 Compiler Refer to String Constants for more information MikroElektronika 116 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 C comments C
316. ed char remoteHostIpAddr 4 user host IP address buffer SNTP server Zurich Switzerland Integrated Systems Lab Swiss Fed Inst Technology 129 132 2 21 swisstime ethz ch Service Area Switzerland and Europe memcpy remoteHostIpAddr SPI Ethernet dnsResolve swisstime ethz ch 5 4 455 MikroElektronika 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 These parameters can be fetched by using appropriate library IP get routines SPI Ethernet getlpAddress fetch IP address SPI Ethernet getGwlpAddress fetch gateway IP address SPI Ethernet getDnslpAdadress fetch DNS IP address SPI Ethernet getlpMask fetch IP subnet mask UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port tmax time in seconds to wait for an reply 1 network parameters were obtained successfully 0 otherwise Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet initDHCP 5 get network configuration from DHCP server wait 5 sec for the response The Ethernet services are not stopped while this routine w
317. ed with these values The compile time operator sizeof allows you to determine the size in bytes of any standard or user defined type The mikroC PRO for PIC32 standard libraries and your own program and header files must provide unambiguous identifiers or expressions derived from them and types so that the mikroC PRO for PIC32 can consistently access interpret and possibly change the bit patterns in memory corresponding to each active object in your program Type Categories A common way to categorize types is to divide them into fundamental derived The fudamental types represent types that cannot be split up into smaller parts They are sometimes referred to as unstructured types The fundamental types are void char int float and double together with short long signed and unsigned variants of some of them For more information on fundamental types refer to the topic Fundamental Types The derived types are also known as structured types and they include pointers to other types arrays of other types function types structures and unions For more information on derived types refer to the topic Derived Types MikroElektronika 196 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 eleme
318. ee SPI T6963C Config routine Example ser T6963C cursor height OO OOO Moes Nm S SPI T6963C graphics Prototype void SPI T6963C graphics unsigned int n Enable disable graphic displaying Parameters n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable graphic displaying SPT T6963C graphics 1 SPI T6963C text Prototype void SPI T6963C text unsigned int n Enable disable text displaying Parameters n text enable disable parameter Valid values 0 disable text dispaying and 1 enable text displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable text displaying SPI T6963C text 1 MikroElektronika 028 mikroC PRO for PIC32 SPI T6963C cursor E E Vali Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set cursor on SPI T6963C cursor 1 SPI T6963C cursor blink Prototype void SPI 7T6963C cursor blink unsigned int n Description Enable disable cursor blinking Parameters n cursor blinking enable disable parameter Valid values 0 disable cursor blinking and 1 enable cursor blinking Nothing Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable cursor blinking SPI T6963C cur
319. eft rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 rectangle 20 20 219 107 SID13700 WHITE 317 MikroElektronika mikoC PRO for PIC32 S1D13700 Box Prototype void S1D13700 Rectangle unsigned int x0 unsigned int y0 unsigned int x1 unsigned int yl unsigned char pcolor Description Draws a rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values S 1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Box 0 119 239 127 S1D13700 WHITE S1D13700 Rectangle Round Edges Prototype void S1D13700 Rectangle Round Edges unsigned int x upper left unsigned int y upper left unsigned int x bottom right unsigned int y bottom right unsigned short round radius unsigned short color Description Draws a rounded edge rectangle on Glcd Parameters x upper left x coordinate
320. egion between the INTERNAL RAM at physical address 0x00000000 and the INTERNAL BOOT FLASH beginning at physical address 0x1FC00000 is matched up with the virtual memory schemes of KSEGO and KSEG1 The PIC32MX CPU maps the virtual areas of KSEGO and KSEG1 against the same physical memory area beginning at physical address 0x00000000 Because both the KSEGO and KSEG1 virtual segments point to the same physical memory area the PIC32MX CPU can execute instructions from either the KSEGO or KSEG1 virtual memory segment depending on the cacheable status of the application KSEGO and USEG KSEG are cacheable while KSEG1 is not cacheable Related topics Accessing individual bits SFRs Memory type specifiers MikroElektronika 166 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 SEE code The code memory type may be used for allocating constants in program memory puts txt in program memory const code char txt ENTER PARAME data This memory specifier is used when storing variable to the Data RAM puts x in data ram data unsigned char x rx Description This memory specifier al
321. eir voltage incompatibility with certain number of Samsung KS0108 based Glcd modules So additional external power supply for these modules may be required Library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI Glcd Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree gt Port Expander SPI Graphic Lcd 1 Gicd Fonts External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies Library Routines Basic routines SPI Glcd Init SPI Glcd Set Side SPI Glcd Set Page SPI Glcd Set X SPI Glcd Read Data SPI Glcd Write Data Advanced routines SPI Glcd Fill SPI Glcd Dot SPI Glcd Line SPI Glcd V Line SPI Glcd H Line MikroElektronika 484 mikroC PRO for PIC32 SPI Gled Rectangle SPI Gled Rectangle Round Edges SPI Gled Rectangle Round Edges Fill SPI Glcd Box SPI Glced Circle SPI Glced Circle Fill SPI Glcd Set Font SPI Glcd Write Char
322. eive transmit logic or any other part of the ENC24J600 module The ENC247600 module should be properly cofigured by the means of SPI Ethernet 24j600 Init routine An MikroElektronika mikoC PRO for PIC32 SPI Ethernet 24j600 Disable Prototype void SPI Ethernet 243600 Disable unsigned int disFlt Description This is MAC module routine This routine disables appropriate network traffic on the ENC247600 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 For this purpose predefined library constants see the table below can be ORed to form appropriate input value Parameters isrit network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 0x01 MAC Broadcast traffic receive filter flag When set MAC SPI Ethernet 243600 broadcast traffic will be disabled BROADCAST multicast traffic will be disabled MULTICAST ejoo mum O e S 1 0x80 MAC Unicast traffic receive filter flag When set MAC SPI Ethernet 24 600 unicast traffic will be disabled UNICAST Ethernet module has to be initialized See SPI Ethernet 24j600 Init SPI Ethernet 243600 Disable SPI Ethernet 247600 CRC SPI Ethernet 247600 UNICAST disable CRC checking and U
323. elated topics Keyboard shortcuts Debug Toolbar MikroElektronika 48 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 mE Programmer Fil Package Manager Active Comment Editor Ctrl Alt C Ascii Chart EEPROM Editor Export Code To HTML GLCD Bitmap Editor Interrupt Assistant Ctrl Alt I LCD Custom Character Seven Segment Editor UDP Terminal USART Terminal Ctri T Options F12 Related topics Keyboard shortcuts Tools Toolbar 49 MikroElektronika mikoC PRO for PIC32 Help Help Menu Options Help Fi Migration Document Check For Updates tmikroElektronika Support Forums mikroElektronika Web Page A How To Register About Hp pesmpim Related topics Keyboard shortcuts Help Toolbar MikroElektronika 50 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 cpg oe raged Cha Se wont The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant Spell Checker Aut
324. elay2s lcd System3x5 3 5 ONLY rext 60 2 2 lcd System5x7 5 7 Text 5 4 2 Lod 5x74 5 Tp 32 v2 SPI Glcd Write Text some Delay2s Text 5 6 2 8 Wu Be F Wu Dende 32 32 Le Lh ia Lr Te if Lh yat rd Tf 7274 rd Lf Vaf Draw line Draw horizontal and vertical lines Clear Glcd Choose font see _ Lib Write string Draw circles Draw circles Draw box Fill Greg Change font Write string Change font Write string Change font Write string Change font Write string MikroElektronika 498 mikroC PRO for PIC32 HW Connection o Leftside Right side 127 x axis x 63 x 0 PIC32MX460F512L CCS ovcca SPI Glcd HW connection 499 MikroElektronika mikoC PRO for PIC32 SPI Lcd Library The mikroC PRO for PIC32 provides a library for communication with Lcd with HD44780 compliant controllers in 4 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of Lcd modules So additional external power supply for these modules may be required Library uses the SPI module for communication The user must i
325. eliable output LATx should be used instead of PORTx 171 MikroElektronika miko PRO for PIC32 CHAPTER 8 mikroC PRO for PIC32 Language Reference 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 Type Derived Types Arrays Pointers Introduction to Pointers Pointer Arithmetic Structures Introduction to Structures Working with Structures Structure Member Access Unions Bit Fields 113 MikroElektronika 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 Assignment Operato
326. en Sd Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 547 MikroElektronika mikoC PRO for PIC32 T6963C Partiallmage Prototype void T6963C Partiallmage unsigned int x left unsigned int y top unsigned int width unsigned int height unsigned int dcm width unsigned int picture height code const unsigned short image Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width ofthe original image picture height height of the original image image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroC PRO for PIC pointer to const and pointer to RAM equivalency Toshiba Glcd module needs to be initialized See T6963C init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 T6963C Partzallmage l0 12 10 15 16 32 mage Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for dis
327. ent within loops is used to skip the cycle It passes control to the end of the innermost enclosing end brace belonging to a looping construct At that point the loop continuation condition is re evaluated This means that cont inue demands the next iteration if the loop continuation condition is true Specifically the cont inue statement within the loop will jump to the marked position as it is shown below while do FOF d21 2229 1 if val 0 continue if val gt 0 continue if val gt 0 continue continue jumps here continue jumps here continue jumps here while MikroElektronika 254 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 goto is used to break out from any level of nested control structures but it cannot be used to jump into block while skipping that block s initializations for example jumping into loop s body etc The use of goto statement is generally discouraged as practically every algorithm can be realized without it resulting in legible structured p
328. entrance exit from interrupt service routine except STATUS WREG and BSR registers in high priority interrupt Fast Register Stack This exception can be overrided by placing an asm RETFIE 0 instruction at the end of the high priority interrupt routine with redirecting all routine exits to this instruction Thus pragma disablecontexsaving pragma enables the user to manually write code for saving registers upon entrance and to restore them before exit from interrupt 143 MikroElektronika mikoC PRO for PIC32 Interrupt Example Here is a simple example of handling the interrupts from Timer1 if no other interrupts are allowed void Timerl interrupt Til nit 0 LATB PORTB void main ADIPCFG OxFFFF TRISB 0 LATB QxAAAA TMR1 0 PRI 65535 TLIPO bit 1 TIIP bit 1 T1IP2 Bit 1 TCKPSO bit 1 TCKPS1_bit 1 TIIE bit e 1j ON Ti1CON bit EnableInterrupts 1 V 724 iv IVT TIMER 1 ilevel 7 ics ICS SRS Clear T1IF Invert PORTB Initialize AN pins as digital initialize PORTB as output Initialize PORTB value reset timer value to zero Load period register set interrupt priority Var ea Fe to 7 Set Timer Input Clock Prescale value to 1 256 Enable all interrupts Enable Timerl Interrupt Enable Timerl MikroElektronika 144 mikroC PRO for PIC32 Linker Directives The mik
329. eqLength TEthj600PktFlags 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 24j600 get routines The user puts data in the transmit buffer by using some of the SPI Ethernet 24j600 put routines The function must return the length in bytes of the TCP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP requests just define this function with return 0 as a single statement Parameters remoteHost client s IP address remotePort client s TCP port localPort port to which the request is sent reqLength TCP request data field length flags structure consisted of two bit fields Copy Code To Clipboard typedef struct unsigned canCloseTCP 1 flag which closes socket unsigned isBroadcast 1 flag which denotes that the IP package has been received via subnet broadcast address TEthj600PktFlags 0 there should not be a reply to the request Length of TCP reply data field otherwise Ethernet module has to be initialized See SPI Ethernet 24600 Init Example This function is internally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply MikroElektronika 416 mikroC PRO for PIC32 SPI Ethernet 24
330. er Access 216 Anonymous Unions 217 Anonymous Union Member Access 217 Bit Fields 218 MikroElektronika mikoC PRO for PIC32 Bit Fields Declaration Bit Fields Access Types Conversions Standard Conversions Arithmetic Conversions Pointer Conversions Explicit Types Conversions Typecasting Declarations Declarations and Definitions Declarations and Declarators Linkage Linkage Rules Internal Linkage Rules Storage Classes Auto Register Static Extern Type Qualifiers Qualifier const Qualifier volatile Typedef Specifier asm Declaration Accessing variables Asm code and SSA optimization Initialization Automatic Initialization Functions Function Declaration Function Prototypes Function Definition Functions reentrancy Function Calls and Argument Conversions Function Calls Argument Conversions Ellipsis Operator Operators Operators Precedence and Associativity Arithmetic Operators Arithmetic Operators Overview Binary Arithmetic Operators Unary Arithmetic Operators Relational Operators Relational Operators Overview 218 219 219 220 220 221 221 222 222 223 223 224 224 224 225 225 225 225 226 226 226 226 227 227 228 229 229 230 230 231 231 232 232 232 233 234 235 236 237 237 238 238 239 239 MikroElektronika 10 mikroC PRO for PIC32 Relational Operators in Expressions 239 Bitwise Operators 240 Bitwise Operators Overview 240 Logical Oper
331. erent from T6369C datasheets Appropriate relations between these labels are given in the table below Adapter Board T6369C datasheet C D Library Dependency Tree Te963c Trigonometry MikroElektronika 536 mikroC PRO for PIC32 External dependencies of T6963C Graphic Lcd Library The following variables must be defined in all projects using T6963C Description Graphic Lcd library AEE WES SAP EES SR RUPEM T6963C Data Port char T6963C dataPort at PORTB dataPort i T6963C X LATF2 extern sfr sbit T6963C ctr Write signal QUSE A extern sfr sbit T6963C ctr Read signal S TESOIMENE SE LEPE i T6963C ctrirst LATF4 extern sfr sbit T6963C ctrl Reset signal anie pe ane S extern sfr sbit T6963C ctrlwr r sbit T6963C ctrlwr Direction i Direction of the Write pin a e poses Direction at TRISF2 bit extern sfr sbit T6963C ctrlrd R i T6963C ctrlrd Direction t Direction of the Read pin NL Direction Fl bit extern sfr sbit T76963C ctrlcd Direction of the Command i T6963C ctrlcd Direction Direction Data pin FO bit extern sfr sbit T6963C ctrlrst n i T6963C ctrlrst Direction f Direction of the Reset pin Aeon Direction SF4 bit wr Ld Lest 931 MikroElektronika mikoC PRO for PIC32 Library Routines T6963C init T6963C writeData T6963C writeCommand T6963C_setPtr T6963C waitReady
332. ernal dependencies of RS 485 Library 405 Library Routines 406 RS485Master Init 406 RS485Master Receive 407 RS485Master Send 407 RS485Slave Init 408 RS485Slave Receive 409 RS485Slave Send 409 Library Example 410 HW Connection 413 Message format and CRC calculations 414 Software C Library 415 External dependencies of Software PC Library 415 Library Routines 415 1 MikroElektronika mikoC PRO for PIC32 Soft I2C Init Soft I2C Start Soft I2C Read Soft I2C Write Soft I2C Stop Soft I2C Break Library Example Software SPI Library External dependencies of Software SPI Library Library Routines Soft SPI Init Soft SPI Read Soft SPI Write Library Example Software UART Library Library Routines Soft UART Init Soft UART Read Soft UART Write Soft UART Break Library Example Sound Library Library Routines Sound Init Sound Play HW Connection SPI Library Library Routines SPIx Init SPIx Init Advanced SPIx Read SPIx Write SPI Set Active Library Example HW Connection SPI Ethernet Library Library Dependency Tree External dependencies of SPI Ethernet Library Library Routines SPI Ethernet Init SPI Ethernet Enable SPI Ethernet Disable SPI Ethernet doPacket SPI Ethernet putByte SPI Ethernet putBytes SPI Ethernet putConstBytes 416 416 417 417 417 418 419 421 421 421 422 423 423 423 425 425 425 426 426 427 428 430 430 430 430 432 433 433 434 435 437 437 438 438 440 441 441 4
333. es of this constant in code with it s literal value In the second case your constant will be placed in Flash in the exact location specified Be careful when using the absolute directive as you may overlap two variables by accident For example Variable i will occupy 1 byte at address 0xA0000003 char i absolute 0xA0000003 Variable will occupy 4 bytes at 0xA0000000 0xA0000001 0xA0000002 0xA0000003 thus changing i changes jjjj highest byte at the same time and vice versa long jjjj absolute 0xA0000000 115 MikroElektronika 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 OxBD000000 Function will start at address O0xBD000000 asm nop It is possible to use org directive with functions that are defined externally such as library functions Simply add org directive to function declaration void UART1 Write char data org OxBD000000 Directive orgall If the user wants to place his routines constants etc above a specified address in ROM pragma orgall directive should be used pragma orgall OxBD000000 Directive funcorg You can use the pragma funcorg directive to specify the starting address of a routine in ROM using r
334. es pairs of bits and 7 returns 1 if the bits are complementary otherwise returns 0 bitwise complement unary inverts each bit bitwise shift left moves the bits to the left discards the far left bit and assigns 0 to the far right bit bitwise shift right moves the bits to the right discards the far right bit and if unsigned assigns 0 to the far left bit otherwise sign extends Bitwise operators and perform logical operations on the appropriate pairs of bits of their operands Operator complements each bit of its operand For example 0x1234 amp 0x5678 equals 0x1230 because 0x1234 0001 0010 0011 0100 0x5678 0101 0110 0111 1000 amp 0001 0010 0011 0000 that is Ox1230 MikroElektronika 240 mikroC PRO for PIC32 Similarly 0x1234 0x5678 equals 0x567C 0x1234 0x5678 equals 0x444C 0x1234 equals OxEDCB Note Operator can also be a pointer reference operator Refer to Pointers for more information Bitwise Shift Operators Binary operators lt lt and gt gt 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 With shift left lt lt far left bits are discarded and new bits on the right are assigned zeroes Thus shifting unsigned operand to the left by n positions is equivalent to multiplying it by 2n if all discarded bits are
335. escription This routine performs 3 operations simultaneously It provides clock for the Software SPI bus reads a byte and sends a byte sdata data to be sent Returns Byte received via the SPI bus Soft SPI must be initialized before using this function See Soft SPI Init routine unsigned short data read char data send Read a byte and assign it to data read variable data send byte will be sent via SPI during the Read operation data read Soft SPI Read data send Soft SPI Write Rems Noting Soft SPI must be initialized before using this function See Soft SPI Init Write a byte to the Soft SPI bus Soft SPI Write 0xAA Library Example This code demonstrates using library routines for Soft SPI communication Also this example demonstrates working with max7219 Eight 7 segment displays are connected to MAX7219 MAX7219 is connected to SDO SDI SCK pins are connected accordingly Copy Code To Clipboard DAC module connections sbit Chip Select at LATDO bit sbit SoftSpi CLK at LATD6 bit sbit SoftSpi SDI at RD2 bit sbit SoftSpi SDO at LATD3 bit sbit Chip Select Direction at TRISDO bit sbit SoftSpi CLK Direction at TRISD6 bit sbit SoftSpi SDI Direction at TRISD2 bit sbit SoftSpi SDO Direction at TRISD3 bit End DAC module connections 423 MikroElektronika mikoC PRO for PIC32 unsigned int value void InitMain TRISBO bit 1 TRISB1 bit
336. eter Valid values 0 2 Parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a line between dots 0 0 and 20 30 SPI Glcd Line 0 0 20 30 1 None SPI Glcd V Line Prototype void SPI Glcd V Line char y start char y end char x pos char 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 2 Parameter color determines the line color 0 white 1 black and 2 inverts each dot Nothing Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a vertical line between dots 10 5 and 10 25 SPI Glcd V Line 5 25 10 1 None 489 MikroElektronika mikoC PRO for PIC32 SPI Glcd H Line Prototype void SPI Glcd H Line char x start char x end char y pos char color Draws a horizontal line on Glcd Parameters x start x coordinate of the line start Valid values 0 127 x end X coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black
337. ethernet board dhcp will not be used here so use preconfigured addresses SPI Ethernet confNetwork ipMask gwIpAddr dnsIpAddr while 1 do forever if necessary test the return value to get error code SPI Ethernet doPacket process incoming Ethernet packets add your stuff here if needed Spi Ethernet doPacket must be called as often as possible otherwise packets could be lost nf MikroElektronika 464 mikroC PRO for PIC32 HW Connection I OSCILLATOR 465 MikroElektronika mikoC PRO for PIC32 SPI Ethernet ENC24J600 Library The ENC24J600 is a stand alone Ethernet controller with an industry standard Serial Peripheral Interface SPI It is designed to serve as an Ethernet network interface for any controller equipped with SPI The ENC24J3600 meets all of the IEEE 802 3 specifications applicable to 10Base T and 100Base TX Ethernet It incorporates a number of packet filtering schemes to limit incoming packets It also provides an internal 16 bit wide DMA module for fast data throughput and hardware assisted IP checksum calculations Communication with the host controller is implemented via two interrupt pins and the SPI with data rates of 10 100 Mb s Two dedicated pins are used for LED link and network activity indication This library is designed to simplify handling of the underlying hardware ENC244600 It works with any PIC32 with integr
338. etlpAddress SPI Ethernet getGwlpAddress SPI Ethernet getDnslpAddress SPI Ethernet getlpMask SPI Ethernet confNetwork SPI Ethernet arpResolve SPI Ethernet sendUDP SPI Ethernet dnsResolve SPI Ethernet initDHCP SPI Ethernet doDHCPLeaseTime SPI Ethernet renewDHCP SPI Ethernet Init Prototype void SPI Ethernet Init unsigned char mac unsigned char ip unsigned char fullDuplex Description This is MAC module routine It initializes ENC28 760 controller This function is internaly splited into 2 parts to help linker when coming short of memory ENC28J60 controller settings parameters not mentioned here are set to default receive buffer start address 0x0000 receive buffer end address 0x19AD transmit buffer start address 0x19AF transmit buffer end address 0xiFFF RAM buffer read write pointers in auto increment mode receive filters set to default CRC MAC Unicast MAC Broadcast in OR mode flow control with TX and RX pause frames in full duplex mode frames are padded to 60 bytes CRC maximum packet size is set to 1518 Back to Back Inter Packet Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 0x0012 in full duplex mode 0x0C12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC28J60 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half dupl
339. ex loopback disabled LED configuration default LEDA link status LEDB link activity M3 MikroElektronika 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 Requires Global variables SPI Ethernet CS Chip Select line SPI Ethernet CS Direction Direction of the Chip Select pin SPI Ethernet RST Resetline SPI Ethernet RST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See the SPIx Init and SPIx Init Advanced routines define SPI Ethernet HALFDUPLI define SPI Ethernet FULLDUPLI mE ethernet NIC pinout sfr sbit SPI Ethernet Rst at RFO bit sfr sbit SPI Ethernet CS at RFI bit sfr sbit SPI Ethernet Rst Direction at 1 F0 bit sfr sbit SPI Ethernet CS Direction at 7 Fl bit end ethernet NIC definitions unsigned char myMacAddr 6 0x00 0x14 OxA5 0x76 0x19 Ox3f my MAC address unsigned char myIpAddr 192 168 Ly 60 3 7 my IP addr SPIL Init SPI Ethernet Init myMacAddr myIpAddr SPI Ethernet FULLDUPLI MikroElektronika 444 mikroC PRO for PIC32 SPI Ethernet Enable Prototype void SPI Ethernet Enable unsigned char enFlt Description This is MAC module routine This routine
340. f this page value Register Value Reume WoW OOOO Example CP0 SET CPO CONFIG 0x1A2C0000 Enablelnterrupts Prototype void EnableInterrupts eum Noting EnableInterrupts None Disablelnterrupts Function disables interrupts Runs Non Example pissblermtesrups OOOO Noes noe CPO CONFIG3 CPO DEBUG CPO TRACECONTROL CPO TRACECONTROL2 CPO USERTRACEDATA CPO TRACEBPC CPO DEBUG2 CPO DEPC CPO0 ERROREPC CPO DESAVE MikroElektronika 156 mikroC PRO for PIC32 GEUREA M CPO CAUSE DC CPO0 CAUSE CE CPO CAUSE TI CPO0 CAUSE BD CPO PRID REVISION CPO PRID PATCHREV CPO PRID MINORREV CPO PRID MAJORREV CP0 PRID PROCESSORID CPO PRID COMPANYID CPO0 EBASE CPUNUM CPO0 EBASE EBASE CPO0 CONFIG KO CPO0 CONFIG MT CPO CONFIG AR CPO0 CONFIG UDI CPO0 CONFIG KU CPO0 CONFIG1 M CPO0 CONFIG1 FP CPO CONFIG1 EP CPO CONFIG1 CA CPO0 CONFIG1 WR CP0 CONFIG1 PC CPO0 CONFIG1 MD CPO CONFIG1 C2 CPO CONFIG1 DA CPO0 CONFIG1 DL CPO0 CONFIG1 DS CPO0 CONFIG1 IA CPO CONFIG1 IL CPO DEBUG DIB CP0 DEBUG DINT CPO0 DEBUG DIBIMPR CPO_DEBUG_R CPO DEBUG SST CPO CAUSE IP6 CPO CAUSE IP7 CPO CAUSE WP CPO CAUSE IV CPO CAUSE PCI CPO DEBUG EXI CPO DEBUG DBUSEP CPO DEBUG CACHEEP CPO DEBUG MCHECKP CPO DEBUG IBUSEP CPO DEBUG COUNTDM CPO0 DEBUG HALT CPO0 DEBUG DOZE CPO0 DEBUG LSNM CPO DEBUG NODCR CPO0 CONFIG AT CPO0 CONFIG BE CPO0 CONFIG DS CPO0 CONFIG MDU CPO CONFIG SB CPO DEBUG NOSST CPO DEBUG DEXCCODE CPO0
341. f value of 0xFFFF is passed as the address parameter the reading will start from current ENC28J60 read pointer ERDPT location Parameters ptr buffer for storing bytes read from ENC28760 RAM addr ENC28J60 RAM start address Valid values 0 8192 n number of bytes to be read Nothing Ethernet module has to be initialized See SPI Ethernet Init char buffer 16 SPI Ethernet getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 449 MikroElektronika mikoC PRO for PIC32 SPI Ethernet UserTCP l Prototype unsigned int SPI Ethernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength TEthPktFlags flacgs 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 The function must return the length in bytes of the TCP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP requests just define this function with return 0 as a single statement Parameters remoteHost client s IP address remotePort client s TCP port localPort port to which the request is sent regLength TCP request data field length flags structure consisted of two bit fields Copy Code To
342. ffectively Check the example at the end of the chapter CANSPI OP MODE Constants The CANSPI OP MODE constants define CANSPI operation mode Function CANSPISetOperationMode expects one of these as it s argument 219 MikroElektronika mikoC PRO for PIC32 Copy Code To Clipboard const unsigned int CANSPI MODE BITS OxEO Use this to access opmode bits CANSPI MODE NORMAL 0x00 CANSPI MODE SLEEP 0x20 CANSPI MODE LOOP 0x40 CANSPI MODE LISTEN 0x60 _CANSPI_ MODE CONFIG 0x80 CANSPI_CONFIG_FLAGS Constants The CANSPI CONFIG FLAGS constants define flags related to the CANSPI module configuration The functions CANSPIInit CANSPISetBaudRate CANSPISetMask and CANSPISetFilter expect one of these or a bitwise combination as their argument Copy Code To Clipboard const unsigned int CANSPI CONFIG DEFAULT OxFF fe ISS23721211 CANSPI CONFIG PHSEG2 PRG BIT 0x01 CANSPI CONFIG PHSEG2 PRG ON OxFF Jf XXXXEXXXI CANSPI CONFIG PHSEG2 PRG OFF OxFE Jf XXXXXXXO0 CANSPI CONFIG LINE FILTER BIT 0x02 CANSPI CONFIG LINE FILTER ON OxFF JL CXXEXXXTX CANSPI CONFIG LINE FILTER OFF OxFD d XXXXXXOX CANSPI CONFIG SAMPLE BIT 0x04 CANSPI CONFIG SAMPLE ONCE OxFF XXXXX1XX CANSPI CONFIG SAMPLE THRICE OxFB Af XXXXXO0XX CANSPI CONFIG MSG TYPE BIT 0x08
343. file contents 0 loop 10 48 file contents 1 loop 10 48 MikroElektronika 302 mikroC PRO for PIC32 Cf Fat Write file contents LINE LEN 1 Creates many new files and writes data to them void M Create Multiple Files for loop2 B loop2 lt Z loop2 UART1 Write loop2 filename 7 loop2 Cf Fat Set File Date 2005 6 21 10 35 0 Cf Fat Assign amp filename OxAQ Cf Fat Rewrite for loop 1 loop lt 44 loopt file contents 0 loop 10 48 file contents 1 loop 10 48 Cf Fat Write file contents LINE LEN 1 Opens an existing file and rewrites it void M Open File Rewrite filename 7 C Cf Fat Assign amp filename 0 Cf Fat Rewrite for loop 1 loop lt 55 looptt file contents 0 loop 10 48 file contents 1 loop 10 48 Cf Fat Write file contents LINE LEN 1 Opens an existing file and appends data to it LE and alters the date time stamp void M Open File Append filename 7 B Cf Fat Assign amp filename 0 Cf Fat Set File Date 2009 1 23 17 22 0 Cf Fat Append Cf Fat Write for mikroElektronika 2009 n 27 find existing file or creat To clear file and start with new data write data to the assigned file signal the progress set filename Set file date amp time info a new on write data to the a
344. for PIC32 Glcd Rectangle Prototype void Glcd Rectangle unsigned short x upper left unsigned short y upper Left paren short x bottom right unsigned short y bottom right unsigned short color Draws a unas on Glcd Parameters x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border O white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 Glcd Rectangle 5 5 40 40 1 Glcd Rectangle Round Edges Prototype void Glcd Rectangle Round Edges unsigned short x upper left unsigned short y upper left unsigned short x bottom right 2 short y bottom right unsigned short round radius unsigned short color Draws a rounded edge rectangle on Glcd Parameters x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of t
345. for dynamic response counter of HTTP requests 459 MikroElektronika mikoC PRO for PIC32 J ECKCKCKCkCk kk kk CkCkCkCkCkCkCkCkCkCk ck kCkCk Ck Ck Ck kCk k Ck k ck k ck k ck k ck ck ck ckok functions if put the constant string pointed to by s to the ENC transmit buffer wy unsigned int putConstString const code char s unsigned int ctr 0 while s Spi Ethernet putByte st DUEPTT return ctr Jaz f it will be much faster to use library Spi Ethernet putConstString routine instead of putConstString routine above However the code will be a little bit bigger User should choose between size and speed and pick the implementation that suites him best If you choose to go with the putConstString definition above the define line below should be commented out ty define putConstString SPI Ethernet putConstString put the string pointed to by s to the ENC transmit buffer Ty unsigned int putString char s unsigned int ctr 0 while s id Spi Ethernet putByte st CEFTA return ctr pes it will be much faster to use library Spi Ethernet putString routine instead of putString routine above However the code will be a little bit bigger User should choose between size and speed and pick the implementation that suites him best If you choose to go with the putString definition above the define line below should be commented out
346. for the first time from the View menu from editor s pop up menu or by pressing Ctrl Alt P you will get an empty editor Active Comments Editor Select Active Comment Active Comment Actions New Rename Delete Properties Add Image to Project AGG File To Project By clicking the New button you are prompted to enter a name for the comment MikroElektronika 96 mikroC PRO for PIC32 Active Comments Editor Enter comment name activeComment Active Comment Actions New Rename Properties Attributes Url Image File 3 Events OnLeftClick Alt N OnRightClick OnDblClick OnMouseOver Add Image To Project Add File To Project You can notice that when you start typing a name properties pane is automatically displayed so you can edit properties if you wish AComment will be is created when you click Save 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 gt Images File File has to be previously added to Project Project Manager gt Other Files There are four predefined event types you can apply to an Active Comment 1 OnLeftClick Alt 2 OnRightClick 3 OnDoubleClick 4 OnMouseOver 9 MikroElektronika mikoC PRO for PIC32 First three event types can have one of the following three a
347. fr sbit DriveX Left Direction Direction of the DriveX Left pin i DriveX Left Direction TRISB13 bit extern sfr sbit DriveX Right Direction Direction of the DriveX Right pin j DriveX Right Direction TRISB11 bit extern sfr sbit DriveY Up Direction Direction of the DriveY Up pin sbit DriveY Up Direction at TRISB12 bit extern sfr sbit DriveY Down Direction Direction of the DriveY Down pin i DriveY Down Direction SBIO bit Library Routines TP TFT Init TP TFT Set ADC Threshold TP TFT Press Detect TP TFT Get Coordinates TP TFT Calibrate Min TP TFT Calibrate Max TP TFT Get Calibration Consts TP TFT Set Calibration Consts MikroElektronika 584 mikroC PRO for PIC32 TP TFT Init Prototype void TP TFT Init unsigned int display width unsigned int display height unsigned int readX ChNo unsigned int readY ChNo Initialize TFT touch panel display Default touch panel ADC threshold value is set to 900 Parameters display width set display width display height set display height readX ChNo read X coordinate from desired ADC channel readY ChNo read Y coordinate from desired ADC channel Nothing Before calling this function initialize ADC module ADC1 Init Initalize ADC module TP TFT Init 320 240 13 12 Initialize touch panel TP_TFT_Set_ADC_Threshold Prototype void TP TFT Set ADC Threshold unsigned int threshold Set custom ADC threshold v
348. fs and it is named MCU_NAME m1k for example P32MX460F512L mlk 7 Add the the following segment of code to lt LIBRARIES gt node of the definition file definition file is in XML format lt LIB gt lt ALIAS gt Example Library lt ALIAS gt FILE Lib Example lt FILE gt lt TYPE gt REGULAR lt TYPE gt lt LIB gt 8 Add Library to mlk file for each MCU that you want to use with your library 9 Click Refresh button in Library Manager 10 Example Library should appear in the Library manager window Multiple Library Versions Library Alias represents unique name that is linked to corresponding Library emc1 file For example UART library for P32MX460F512L is different from UART library for P32MX675F512L MCU Therefore two different UART Library versions were made see n1k files for these two MCUs Note that these two libraries have the same Library Alias UART in both m1k files This approach enables you to have identical representation of UART library for both MCUs in Library Manager Related topics Library Manager Project Manager Managing Source Files MikroElektronika 678 mikroC PRO for PIC32 Frequently Asked Questions This is a list of frequently asked questions about using mikroElektronika compilers If your question is not answered on this page please contact mikroElektronika Support Desk Can use your compilers and programmer on Windows Vista Windows 7 Our compile
349. fs if statement proc void Func declaration ptemplate header comment for a project switch switch statement do while 5 MikroElektronika 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 do L Auto Complete You can add your own templates to the list by entering the desired keyword description and code of your template in appropriate boxes Autocomplete macros can retreive system and project information DATE current system date TIMES current system time SDEVICES device MCU name as specified in project settings SDEVICE CLOCKS clock as specified in project settings COMPILERS current compiler version These macros can be used in template code see template ptemplate provided with mikroC PRO for PIC32 installation MikroElektronika 58 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 Code Explorer B Functions main move_Delay S Gishift Text Left ej S Q shitt_Text_Right Pe B Glob
350. g SPI Lcd Init mikoC PRO for PIC32 SPI Lcd8 8 bit interface Library The mikroC PRO for PIC32 provides a library for communication with Lcd with HD44780 compliant controllers in 8 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Important When using this library with PIC32 family MCUs be aware of their voltage incompatibility with certain number of Lcd modules So additional external power supply for these modules may be required Library uses the SPI module for communication The user must initialize the appropriate SPI module before using the SPI Lcd8 Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree r Port Expander SPI Lcd8 1 i Lcd Constants External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies Library Routines SPI Lcd8 Config SPI Lcd8 Out SPI Lcd8 Out Cp SPI Lcd8 Chr SPI Lcd8 Chr Cp SPI Lcd8 Cmd MikroElektronika 506 mikroC PRO for PIC32 SPI Lcd8
351. g mp functions When called Set jmp saves its calling environment in its jmp buf argument for a later use by Longjmp Long jmp on the other hand restores the environment saved by the most recent invocation of Set jmp with the corresponding jmp buf argument mikoC PRO for PIC32 Copy Code To Clipboard finclude lt Setjmp h gt jmp buf buf void funce33 Delay ms 1000 asm nop Longjmp buf 2 asm nop void func portb 3 if Setjmp buf 2 portb 1 else f ncs3t s void main PORTB 0 TRISB 0 asm nop func asm nop Delay ms 1000 PORTB OxFFFF Note Program flow diagrams are indexed according to the sequence of execution MikroElektronika 648 mikroC PRO for PIC32 Sprint Library The mikroC PRO for PIC32 provides the standard ANSI C Sprintf function for easy data formatting Note In addition to ANSI C standard the Sprint Library also includes two limited versions of the sprintf function sprinti and sprintl These functions take less ROM and RAM and may be more convenient for use in some cases Library Dependency Tree Sprint c 1ype Functions sprintf sprintl sprinti sprintf Prototype void sprintf char wh const code char f Returns The function returns the number of characters actually written to destination string Description sprintf is used to format data and print them into destinati
352. g should be at least 5 characters in length int j 32768 char txt 5 IntToHex j txt txt is 8000 LongWordToHex Prototype Description Parameters Requires void LongWordToHex unsigned long input char output Converts input number to a string containing the number s hexadecimal representation The output string has fixed width of 9 characters including null character at the end string termination input unsigned long integer number to be converted output destination string Nothing Destination string should be at least 9 characters in length unsigned long jj 65535 char txt 9 LongWordToHex jj txt txt is 0000FFFF MikroElektronika 638 mikroC PRO for PIC32 LonglntToHex Prototype void LongIntToHex long int input char output Description Converts input number to a string containing the number s hexadecimal representation The output string has fixed width of 9 characters including null character at the end string termination Parameters input signed long integer number to be converted output destination string Nothing Destination string should be at least 9 characters in length long int jj 2147483648 char txt 9 LonstutTelicu i33 EXE txt is 80000000 Dec2Bcd Prototype unsigned short Dec2Bcd unsigned short decnum Converts input unsigned short integer number to its appropriate BCD representation decnum unsigned shor
353. g will be processed one character at a time until the function reaches a character which it doesn t recognize including a null character Example doub atof 1 23 doub 1 23 atoi Prototype int atoi char s Description Function converts the input string s into an integer value and returns the value The input string s should consist exclusively of decimal digits with an optional whitespace and a sign at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize including a null character Example result atoi 32000 result 32000 atol Prototype Description Function converts the input string s into a long integer value and returns the value The input string s should consist exclusively of decimal digits with an optional whitespace and a sign at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize including a null character Example result atol 32560 result 32560 div Prototype div t div int number int denom Description Function computes the result of division of the numerator number by the denominator denom the function returns a structure of type div t comprising quotient quot and remainder rem see Div Structures Example dt div 1234 100 MikroElektronika 616 mikroC PRO for
354. gLength UDP request data field length flags structure consisted of two bit fields Copy Code To Clipboard typedef struct unsigned canCloseTCP 1 flag which closes TCP socket not relevant to UDP unsigned isBroadcast 1 flag which denotes that the IP package has been received via subnet broadcast address TEthPktFlags 0 there should not be a reply to the request Length of UDP reply data field otherwise Ethernet module has to be initialized See SPI Ethernet Init Example This function is internally called by the library and should not be called by the user s code The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply 451 MikroElektronika mikoC PRO for PIC32 SPI Ethernet getlpAddress 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 Pointer to the global variable holding IP address Ethernet module has to be initialized See SPI Ethernet Init unsigned char ipAddr 4 user IP address buffer menepy pads SPI Ethernet getIpAddress 4 fetch IP address User should always copy the IP address from the RAM location returned by this routine into it s own IP address buffer These locations should not be altered by the user in any case Ethernet getGwlpAddress PEE un
355. ge CANSPI module connections sbit CanSpi CS at RFO bit sbit CanSpi CS Direction at TRISFO bit sbit CanSpi Rst at RFI bit sbit CanSpi Rst Direction at TRISF1 bit End CANSPI module connections initialize the CANSPI module with the appropriate baud rate and message acceptance flags along with the sampling rules char CANSPI Init Flags CANSPI Init Flags CANSPI CONFIG SAMPLE THRICE amp form value to be used CANSPI CONFIG PHSEG2 PRG ON amp with CANSPIInitialize CANSPI CONFIG XTD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG SPIL Init initialize SPI1 module CANSPIInitialize l 3 3 3 1 CANSPI Init Flags initialize external CANSPI module Notes CANSPI mode NORMAL will be set on exit MikroElektronika 214 mikroC PRO for PIC32 CANSPISetBaudRate Prototype 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 Parameters SJW as defined in MCU s datasheet CAN Module BRP as defined in MCU s datasheet CAN Module PHSEG1 as defined
356. ginal image size is 16x32 SPI T6963C PartialImage 10 12 10 15 16 32 image uli Image dimension must match the display dimension Use the integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd 923 MikroElektronika mikoC PRO for PIC32 SPI T6963C sprite Prototype void SPI T6963C sprite unsigned char px unsigned char py const code char pic unsigned char sx unsigned char sy Fills graphic rectangle area px py to px sx py sy with custom size picture Parameters x x coordinate of the upper left picture corner Valid values multiples of the font width py y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C sprite 76 einstein 119 draw a sprite If ox and sx parameters are not TATE of the font width Tm will be scaled to the nearest lower number that is a multiple of the font width SPI T6963C set cursor Prototype void SPI T6963C set cursor unsigned char x unsigned char y y cursor position column number Rum Ni OSS yS Example SPI T6963C set cursor cposx ocposy Notes fne OOOO SPI T6963C clearBit Clears control port bit s b bit mask The function will clear bit x on control
357. gs Main Editor Settings Features are Auto Save Highlighter Spelling Comment Style Code Folding Code Assistant Parameter Assistant Bookmarks and Go to Line Options Editor Settings Editor Settings Proje Fies Hn V Restore Last Opened Project Restore All Opened Files VA Editor Colors vig If Opened File Is Externally Modified Prompt For action Reload file but do not prompt Ignore externally made changes Save Breakpoints Save Bookmarks Auto Correct Auto Save m v Timeout Interval minutes Auto Complete Enable Auto Save c2 Highii Highlighter LO Style V Highlight brackets Spelling v Check Spelling Comment style e i single line Advanced Editor Options T Open options dialog Code Folding v Enable code folding Show Ident Guides Tools J Output MikroElektronika 52 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 Spelling The Spell Checker underlines unknown objects in the code so they can be easily noticed and corrected before compiling your project Select Tools Options from the
358. gt 0 amp amp c lt 9 a 1 b f x reads as a 1 b x Logical AND returns 1 only if both expressions evaluate to be nonzero otherwise returns O If the first expression evaluates to false the second expression will not be evaluated For example a gt b amp amp c lt d reads as a gt b amp amp c lt d if a b is false 0 c d will not be evaluated Logical OR returns 1 if either of expression evaluates to be nonzero otherwise returns O If the first expression evaluates to true the second expression is not evaluated For example a amp amp b c amp amp d reads as a amp amp b c amp amp d if a amp amp b is true 1 c amp amp d will not be evaluated Logical Expressions and Side Effects General rule regarding complex logical expressions is that the evaluation of consecutive logical operands stops at the very moment the final result is known For example if we have an expression amp amp b amp amp c where a is false 0 then operands b and c will not be evaluated This is very important if b and c are expressions as their possible side effects will not take place MikroElektronika 242 mikroC PRO for PIC32 Logical vs Bitwise Be aware of the principle difference between how bitwise and logical operators work For example 0222222 amp 0555555 equals 000000 0222222 amp amp 05
359. h extension c will be created automatically The mikroC PRO for PIC32 does not require you to have a source file named the same as the project it s just a matter of convenience Opening an existing file 1 Select File Open from the drop down menu or press Ctrl O or click the Open File Icon amp T from the File Toolbar In Open Dialog browse to the location of the file that you want to open select it and click the Open button 2 The selected file is displayed in its own tab If the selected file is already open its current Editor tab will become active Printing an open file 1 Make sure that the window containing the file that you want to print is the active window 2 Select File gt Print from the drop down menu or press Ctrl P 3 In the Print Preview Window set a desired layout of the document and click the OK button The file will be printed on the selected printer Saving file 1 Make sure that the window containing the file that you want to save is the active window 2 Select File gt Save from the drop down menu or press Ctrl S or click the Save File Icon H from the File Toolbar j 669 MikroElektronika mikoC PRO for PIC32 Saving file under a different name 1 Make sure that the window containing the file that you want to save is the active window 2 Select File Save As from the drop down menu The New File Name dialog will be displayed 3 In the dialog browse to the folder where you want to
360. h specified by filename B directory Save compiled binary files emc1 to directory O Miscellaneous output options DBG Generate debug info SF Short message format Y Dynamic link for string literals RA Rebuild all sources in project L Check and rebuild new libraries DL Build all files as libraries HF Generate Long hex format F Project file name H filename Full EEPROM HEX file name with path EAP size Heap size in bytes GC Generate COFF file PF Project file name SSA Enable SSA optimization UICD ICD build type INTDEF Interrupt settings EBASE Exception base address mT Aawe 113 MikroElektronika mikoC PRO for PIC32 Example mikroCPIC32 exe MSF DBG p32MX460F512L Y DL 011111114 f080 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 N Led 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 MSE Short Message Format used for internal purposes by IDE DBG Generate debug info p32MX460F512L MCU PIC32MX460F512L selected Y Dynamic link for string literals enabled DL All files built as libraries 011111114 Miscellaneous output options fo80 Setoscillator frequency in
361. have internal linkage 3 typedef names have internal linkage 4 enumeration constants have internal linkage External Linkage Rules 1 names having file scope that do not comply to any of previously stated internal linkage rules have external linkage The storage class specifiers auto and register cannot appear in an external declaration No more than one external definition can be given for each identifier in a translation unit declared with internal linkage An external definition is an external declaration that defines an object or a function and also allocates a storage If an identifier declared with external linkage is used in an expression other than as part of the operand of sizeof then exactly one external definition of that identifier must be somewhere in the entire program Storage Classes Associating identifiers with objects requires each identifier to have at least two attributes storage class and type sometimes referred to as data type The mikroC PRO for PIC32 compiler deduces these attributes from implicit or explicit declarations in the source code A storage class dictates the location data segment register heap or stack of object and its duration or lifetime the entire running time of the program or during execution of some blocks of code A storage class can be established by the syntax of a declaration by its placement in the source code or by both of these factors storage class type identifier The sto
362. he character is a digit 0 9 otherwise returns zero res isdigit o returns 1 res isdigit 1 returns 0 isgraph IU Description Function returns 1 if the character is a EE excluding the space decimal 32 otherwise returns zero isgraph Aor returns 1 res isgraph returns 0 607 MikroElektronika mikoC PRO for PIC32 islower Prototype unsigned int islower char character Function returns 1 if the character is a lowercase letter a z otherwise returns zero islower 0 returns 1 res islower A returns 0 ispunct Prototype unsigned int ispunct char character Description Function returns 1 if the character is a punctuation decimal 32 47 58 63 91 96 123 126 otherwise returns zero ispunct returns 1 ispunct 1 returns 0 isspace Description Function returns 1 if the character is a white space space tab CR HT VT NL FF otherwise returns zero res isspace returns 1 res ee S returns 0 isupper Prototype unsigned int isupper char character Function returns 1 if the character is an uppercase letter A Z otherwise returns zero isupper A returns 1 res isupper a returns 0 isxdigit aiiis unsigned int isxdigit char character Function returns 1 if the character is a hex d 0 9 A F a f otherwise returns zero res isxdigit A returns 1 res isxdigit P
363. he circle line 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a circle with center in 50 50 and radius 10 SPI Gled Crxrcle 50 50 10 1 MikroElektronika 492 mikroC PRO for PIC32 SPI Glcd Circle FIII Prototype void SPI Glcd Circle Fill int x center int y center int radius char color Draws a filled circle on Glcd Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle O white 1 black and 2 inverts each dot ae Draw a circle with center in 50 50 and radius 10 SPI Gled Circle Fill 50 50 10 1 Nes Nee OOS 493 MikroElektronika mikoC PRO for PIC32 SPI Glcd Set Font Prototype void SPI Glcd Set Font const code char activeFont char aFontWidth char aFontHeight unsigned int aFontOffs Sets font that will be used with SPI Glcd Write Char and SPI Glcd Write Text routines 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 aFontOf fs number that represents difference between the mikroC PRO for PIC32 character set and regular ASCII set eg if A is 65 in A
364. he do statement executes until the condition becomes false The syntax of the do statement is do statement while expression The statement is executed repeatedly as long as the value of expression remains non zero The expression is evaluated after each iteration so the loop will execute statement at least once Parentheses around expression are mandatory MikroElektronika 292 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 ali Blal itt while i n For Statement The for statement implements an iterative loop The syntax of the for statement is for init expression condition expression increment expression statement Before the first iteration of the loop init expression sets the starting variables for the loop You cannot pass declarations in init expression condition expressionis checked before the first entry into the block statement is executed repeatedly until the value of condition expressionis false After each iteration of the loop increment expression increments a loop counter Consequently i is functionally the same as i All expressions are optional If condition expression is left out
365. he list of relevant files is stored in the project file extension mcp32 To add a file to the project click the Add File to Project Icon cot or press Insert button on your keyboard Each read added source file must be self contained i e it must have all necessary definitions after preprocessing To remove file s from the project click the Remove File from Project Icon car or press Delete button on your keyboard SER 667 MikroElektronika mikoC PRO for PIC32 Project Level Defines Project Level Defines 513 files can also be added to project Project level define files enable you to have defines that are visible in all source files in the project A file must contain one definition per line in the following form symbol value Define a macro named symbol To specify a value use lt value gt If lt value gt is omitted 1 is assumed Do not enter white space characters immediately before the If a white space character is entered immediately after the the macro is defined as zero token This option can be specified repeatedly Each appearance of symbol will be replaced by the value before compilation For example lets make a project level define named pld test First of all create a new file with the p1d extension pld test file pld Next open it and write something like this pld test 3 Once you have done this save the file In the Project Manager add pid test f ile pid file by right
366. he lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 Gled Rectangle Round Edges 5 MikroElektronika 332 for PIC32 Glcd Rectangle Round Edges Fill Prototype Parameters Requires Glcd Box Prototype Description Parameters 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 Draws a filled rounded edge rectangle on Glcd with color x upper left x coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Nothing Glcd needs to be initialized see Glcd Init routine
367. he maximum initial segment of st r1 which consists entirely of characters from st r2 The terminating null character at the end of the string is not compared char txt mikroElektronika char txt sub mikro test int res result strspn txt txt sub routne returns 4 MikroElektronika O A mikroC PRO for PIC32 strncmp Prototype int strncmp char sl char s2 char len Description Function lexicographically compares not more than len characters characters that follow the null character are not compared from the string pointed by s1 to the string pointed by s2 The function returns a value indicating the s1 and s2 relationship Meaning sl less than s2 sl equal to s2 sl greater than s2 char txt mikroElektronika char txt sub mikro int res res strnemp txt sub txt 3 compares the first 3 characters from the string txt with the sting txt sub and returns a difference strstr Prototype char strstr char sl char s2 Description Function locates the first occurrence of the string s2 in the string s1 excluding the terminating null character The function returns pointer to first occurrence of s2 in s1 if no string was found function returns 0 If s2 is a null string the function returns 0 char txt mikroElektronika char txt sub mikro char res res strstr txt sub txt strcspn Description Function computes the length of t
368. he maximum initial segment of the string pointed to by s1 that consists entirely of characters that are not in the string pointed to by s2 The function returns the length of the initial segment char txt mikroElektronika char txt sub mikro char res res strcspn txt sub txt mikoC PRO for PIC32 strpbrk Prototype char strpbrk char s1 char s2 Description Function searches s1 for the first occurrence of any character from the string s2 The terminating null character is not included in the search The function returns pointer to the matching character in s1 If s1 contains no characters from s2 the function returns 0 char txt mikroElektronika char txt sub mikro char res res strpbrk txt sub txt strrchr Prototype char strrchr char ptr char chr Description Function searches the string ptr for the last occurrence of character chr The null character terminating ptr is not included in the search The function returns pointer to the last chr found in ptr ifno matching character was found function returns 0 char txt mikroElektronika res strrchr txt sub k returns the pointer to the k character of the txt string mikroC PRO for PIC32 strtok Prototype Description 621 char strtok char s1 char s2 The strtok function returns a pointer to the first character of a token or a null pointer if there is no token
369. he 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 This value is bit adjusted to appropriate filter registers CANSPI CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG STD MSG and CANSPI CONFIG XTD MSG See CANSPI CONFIG FLAGS constants Nothing Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode 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 See connection example at the bottom of this page set the appropriate filter value and message type CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be in config mode for filter settings Set id of filter B1 FI to 3 CANSPISetFilter CANSPI FILTER Bl F1 3 CANSPI CONFIG XTD MSG 211 MikroElektronika 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 i
370. hernet 24j600 Init Ethernet 243600 doPacket 0 1 process received packets ENC24J600 write Nothing Ethernet module has to be initialized See SPI Ethernet 24600 Init char data Ethernet 245600 putByte data put an byte into ENC24J600 buffer 473 MikroElektronika mikoC PRO for PIC32 SPI Ethernet 24j600 putBytes Prototype Ethernet 243600 putBytes unsigned char ptr unsigned int n Description This is MAC module routine It stores requested number of bytes into ENC247600 RAM starting from current ENC24J600 write pointer EWRPT location Parameters ptr RAM buffer containing bytes to be written into ENC247600 RAM n number of bytes to be written Nothing Requires Ethernet module has to be initialized See SPI Ethernet 24 600 Init char buffer mikroElektronika SPI Ethernet 24 600 putBytes buffer 16 put an RAM array into ENC24J600 buffer SPI Ethernet 24j600 putConstBytes Prototype void SPI Ethernet 245600 putConstBytes const unsigned char ptr unsigned int n Description This is MAC module routine It stores requested number of const bytes into ENC24J600 RAM starting from current ENC247600 write pointer EWRPT location Parameters ptr const buffer containing bytes to be written into ENC247600 RAM n number of bytes to be written Nothing Ethernet module has to be initialized See SPI Ethernet 24
371. hernet Init char buffer mikroElektronika Ethernet putString buffer put a RAM string into ENC28J60 buffer MikroElektronika 448 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 ENC28760 RAM starting from current ENC28760 write pointer EWRPT location Parameters ptr const string to be written into ENC28760 RAM Number of bytes written into ENC28760 RAM Requires Ethernet module has to be initialized See SPI Ethernet Init const char buffer mikroElektronika SPI Ethernet putConstString buffer put a const string into ENC28J60 buffer SPI Ethernet getByte Prototype unsigned char SPI Ethernet getByte Description This is MAC module routine It fetches a byte from address pointed to by current ENC28J60 read pointer ERDPT Byte read from ENC28760 RAM Requires Ethernet module has to be initialized See SPI Ethernet Init char buffer Ethernet getByte read a byte from ENC28J60 buffer SPI Ethernet getBytes Prototype void SPI Ethernet getBytes unsigned char ptr unsigned int addr unsigned int rn Description This is MAC module routine It fetches equested number of bytes from ENC28760 RAM starting from given address I
372. his particular order 1 the project folder folder which contains the project file mcp32 2 your custom search paths 3 mikroC PRO for PIC32 installation folder gt Uses folder Paths for Header Files h Header files are included by means of preprocessor directive include If you place an explicit path to the header file in preprocessor directive only that location will be searched You can specify either absolute or relative path to the header If you specify a relative path mikroC PRO for PIC32 will look for the file in following locations in this particular order 1 the project folder folder which contains the project file h 2 mikroC PRO for PIC32 installation folder gt Include folder 3 your custom search paths Related topics File Menu File Toolbar Project Manager Project Settings 671 MikroElektronika mikoC PRO for PIC32 Edit Project Edit Project gives you option to change MCU you wish to use change its oscillator frequency and build type Also Edit Project enables you to alter specific configuration bits of the selected device As you alter these bits appropriate register values will be updated also This can be viewed in the Configuration Registers pane When you have finished configuring your device you can save bit configuration as a scheme using Save scheme button In case you need this scheme in another project you can load it using There is also a Default Edit Project
373. hould be terminated with break Here is a simple example with switch Suppose we have a variable phase with only 3 different states 0 1 or 2 and a corresponding function event for each of these states This is how we could switch the code to the appopriate routine switch phase case 0 Lo break case 1 Mid break case 2 Hi break default Message Invalid state 291 MikroElektronika 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 The syntax of the while statement is while expression statement The statement executes repeatedly until the value of expression is false The test takes place before statement is executed Thus if expression evaluates to false on the first pass the loop does not execute Note that parentheses around expression are mandatory Here is an example of calculating scalar product of two vectors using the while statement int s 0 i 0 while i lt n s t ali b il arte Note that body of the loop can be a null statement For example while qt ptt Do Statement T
374. i CRC field will be discarded MAC Unicast traffic receive filter flag When set Y 0x80 MAC unicast traffic will be enabled Nothing Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet Enable SPI Ethernet CRC SPI Ethernet UNICAST enable CRC checking and Unicast traffic Advanced filtering available in the ENC28J60 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC28760 module The ENC28360 module should be properly cofigured by the means of SPI Ethernet Init routine 445 MikroElektronika mikoC PRO for PIC32 Prototype void SPI Ethernet Disable unsigned char disFlt SPI Ethernet Disable Description This is MAC module routine This routine disables appropriate network traffic on the ENC28760 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 For this purpo
375. ic state is affected by the load Instances of such loads are LEDs without current limiting resistors or loads with high capacitance or inductance For example if a capacitor is attached between pin and ground it will take a short while to charge when the pin is set to 1 On the other hand if the capacitor is discharged it acts like a short circuit forcing the pin to 0 state and therefore a read of the PORT register will return 0 even though we wrote a 1 to it Lets analyze the following example PORTB BO 1 PORTB B1 1 Assume that the PORTB is initially set to zero and that all pins are set to output Let s say we connect a discharged capacitor to RBO pin The first line PORTB BO 1 will be decoded like in this way READ PORTB is read STORE Data is stored inside a temporary internal register in the MCU Store read value gt 0000000 s 1 Read from pins boou c Discharged REGISTER T capacitor ETEC pe p pe Discharged capacitor 00000000 00000000 C I MikroElektronika 168 mikroC PRO for PIC32 Actual voltage levels on MCU pins are relevant MODIFY Data is modified to set the RBO bit WRITE PORTB is written with the modified data The output driver for RBO turns on and the Modify value capacitor starts to charge Write modified value Discharged 00000000 C capacitor 0850000 To Oe The second line PORTB B1 1 will be decoded like in this way
376. ich use 14 bit or wider instructions What are limitations of demo versions of mikroElektronika s compilers The only limitation of the free demo version is that it cannot generate hex output over 2K of program words Although it may sound restrictive this margin allows you to develop practical working applications without ever thinking of demo limit If you intend to develop really complex projects in one of our compilers you should consider purchasing the license key Why do still get demo limit error when purchased and installed license key If you are first time installing and registering compiler you need to follow instructions exactly as described in registration procedure License is valid only for the computer from which request is made so license requested from one computer won t work on another computer You can find on our site manual and video describing in detail how to get your license If you previously had an older version of our compiler and have working license key for it but it doesn t work with new compiler you have to repeat registration procedure from the new compiler and you will get a new license mikoC PRO for PIC32 have bought license for the older version do have to pay license for the new version of the compiler No once you pay for the license key you get a lifetime license When we release a new major release of the compiler you might need to repeat registration procedure from your new compiler
377. icolon The null statement does nothing and therefore is useful in situations where the mikroC PRO for PIC32 syntax expects a statement but the program does not need one For example a null statement is commonly used in empty loops for qt ptt body of this loop is a null statement Selection Statements Selection or flow control statements select one of alternative courses of action by testing certain values There are two types of selection statements if switch If Statement The if statement is used to implement a conditional statement The syntax of the if statement is if expression statementl1 else statement2 If expression evaluates to true statementi executes If expression is false statement executes The expression must evaluate to an integral value otherwise the condition is ill formed Parentheses around the expression are mandatory The else keyword is optional but no statements can come between if and else Nested If statements Nested if statements require additional attention A general rule is that the nested conditionals are parsed starting from the innermost conditional with each e1se bound to the nearest available if on its left if expressionl statementl else if expression2 if expression3 statement2 else statement3 this belongs to if expression3 else statement4 this belongs to if expression2 MikroElektronika 250 mikroC PRO for PIC32
378. icon al or select Project View Assembly from the drop down menu to review the generated assembly code asm file ina new tab window Assembly is human readable with symbolic names Related topics Project Menu Project Toolbar Messages Window Project Manager Project Settings mikoC PRO for PIC32 Creating New Library mikroC PRO for PIC32 allows you to create your own libraries In order to create a library in mikroC PRO for PIC32 follow the steps bellow 1 Create a new source file see Managing Source Files 2 Save the file in one of the subfolders of the compiler s Uses folder DriveName Program Files Mikroelektronika mikroC PRO for PIC32 Uses 3 Write a code for your library and save it 4 Add Lib Example file in some project see Project Manager Recompile the project If you wish to use this library for all MCUs then you should go to Tools Options Output settings and check Build all files as library box This will build libraries in a common form which will work with all MCUs If this box is not checked then library will be built for selected MCU Bear in mind that compiler will report an error if a library built for specific MCU is used for another one 5 Compiled file Lib Example emcl should appearin mikroC PRO for PIC32 Uses folder 6 Open the definition file for the MCU that you want to use This file is placed in the compiler s Defs folder DriveName Program Files Mikroelektronika mikroC PRO for PIC32 De
379. ientation Description Sets font its color and font orientation Parameters activeFont desired font Currently only TFT defaultFont Tahoma14x16 is supported font color sets font color font orientation Sets font orientation FO HORIZONTAL Horizontal orientation FO VERTICAL Vertical orientation TFT module needs to be initialized See the TFT Init routine Pee TFT Set Font TFT defaultFont CL BLACK FO HORIZONTAL MikroElektronika 566 mikroC PRO for PIC32 TFT Write Char Prototype void TFT Write Char unsigned int c unsigned int x unsigned int y Description Writes a char on the TFT at coordinates x y c char to be written x char position on x axis y char position on y axis TFT module needs to be initialized See the TFT Init routine Example TFT Write Char A 22 23 TFT Write Text Prototype void TFT Write Text unsigned char text unsigned int x unsigned int y Description Writes text on the TFT at coordinates x y Parameters text text to be written x text position on x axis y text position on y axis TFT module needs to be initialized See the TFT Init routine TFT Write Text TFT LIBRARY DE 567 MikroElektronika mikoC PRO for PIC32 TFT Fill Screen Prototype void TFT Fill Screen unsigned int color Description Fills screen memory block with given color Parameters color color to be fi
380. if directive in a source file must be matched by a closing endif directive Any number of e 1if directives can appear between if and endif directives but at most one e1se directive is allowed The else directive if present must be the last directive before tendi f sections can be any program text that has meaning to compiler or preprocessor The preprocessor selects a single section by evaluating constant expression following each if or elif directive until it finds a true nonzero constant expression The constant expressions are subject to macro expansion If all occurrences of constant expression are false or if no elif directives appear the preprocessor selects the text block after the e1se clause If the e1se clause is omitted and all instances of constant expressioninthe if block are false no sectionis selected for further processing Any processed section can contain further conditional clauses nested to any depth Each nested else elif or endif directive belongs to the closest preceding the if directive The net result of the preceding scenario is that only one code section possibly empty will be compiled MikroElektronika 262 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 cur
381. iffering characters in a left to right evaluation Accordingly the result is greater than zero if the object pointed to by s1 is greater than the object pointed to by s2 and vice versa char txt mikroElektronika char txt sub mikro res memcmp txt txt sub 16 returns 69 which is ASCII code of the first differing character letter E memcpy Prototype void memcpy void d1 void s1 int n Description Function copies n characters from the object pointed to by s1 into the object pointed to by d1 If copying takes place between objects that overlap the behavior is undefined The function returns address of the object pointed to by d1 char txt mikroElektronika char txt sub mikr res memcpy txt 4 txt sub 4 string txt will be populated with the first 4 characters of the txt sub string beginning from the 4th character routine returns the address of the first populated character if memory areas of the strings don t overlap memmove Prototype void memmove void to void from int n Description Function copies n characters from the object pointed to by rom into the object pointed to by to Unlike memopy the memory areas to and from may overlap The function returns address of the object pointed to by to char txt mikroElektronika char txt sub mikr res memmove txt 7 txt sub 4 string txt will be populated with fir
382. ign member by member aa i bb i aa j bb j aa d bb d 215 MikroElektronika 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 Here is a simple example union myunion union tag is myunion int 1 double d chat ch mu pm The identifier mu of the type myunion can be used to hold a 2 byte int 4 byte double or single byte char but only one of them at a certain moment The identifier pm is a pointer to union myunion Size of Union The size of a union is the size of its largest member In our previous example both sizeof union myunion and sizeof mu return 4 but 2 bytes are unused padded when mu holds the int object and 3 bytes are unused when mu holds char Union Member Access Union members can be accessed with the structure member selectors and gt be careful when doing this Referring to declarations from th xample above pm amp mu mu d 4 016 tmp mu d OK mu d 4 016 tmp mu i peculiar result
383. ignal I2C2 Write 0xA0 send byte via I2C command to 24cO2 I2C2 Write wAddr send byte address of EEPROM location I2C2 Write wData send data data to be written I2C2 Stop jg eR EE Reads data from 24C02 EEPROM single location random unsigned short EEPROM 24C02 RdSingle unsigned short rAddr unsigned short reslt I2C2 Start issue I2C start signal I2C2 Write 0xA0 send byte via I2C device address W I2C2 Write rAddr send byte data address I2C2 Restart issue I2C signal repeated start I2C2 Write 0xA1 send byte device address R reslt I2C2 Read 1 Read the data NO acknowledge I2C2 Stop return reslt MikroElektronika 342 mikroC PRO for PIC32 unsigned short i char b void main CHECON 0x30 AD1PCFG OxFFFFFFFF LATB 0 TRISB 0 TRISD 0 LADS 0 EEPROM 24C02 Init b 0x00 for i 0x00 i 0x80 EPROM 24C02 WrSingle i b T b delay ms 5 for i 0x00 i lt 0x80 LATD i ATB delay ms 100 T Set PORTB value to zero Configure PORTB as output Configure PORTB as output Set PORTD value to zero performs I2C initialization itt EPROM 24C02 RdSingle i 343 MikroElektronika mikoC PRO for PIC32 Keypad Library The mikroC PRO for PIC32 provides a library for working with 4x4 keypad
384. ikroC PRO for PIC32 compatible code You can launch it from the drop down menu Tools Glcd Bitmap Editor MikroElektronika GLCD Bitmap Editor 240x128 pix bw D 128x128 T6963C A 128x64 noting yet 2 12x32 not imp yet Vw M GLCD Picture name banner bmp GLCD Model Toshiba T6963C 240x128 unsigned char const banner bmp 3840 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 128 0 0 0 0 0 0 0 O 0 O O O O 0 0 0 0 O 0 O 0 O O O 1 128 O0 0 0 0 O 0 O 0 O 0 0 O O 0 O O 0 91 MikroElektronika 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 A mikroElektronika USB HID Terminal Terminal Descriptor HID Devices Info ABBAHOHE ABBAHOHE mikroE HID Librar Dell Premium USB Optical House r Communication HID Read Write Test Send Append CR vw Send as Typing Append LF Send as Number ormat ASCII C HEX C DEC Clear HID Read Write Test 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 gt Interrupt Assistant
385. ikroElektronika 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 Hexadecimal 2147483648 32769 32768 129 int 256 32767 int 32768 65535 65536 2147483647 2147483648 4294967295 gt 4294967295 All constants starting with 0x or 0X are taken to be hexadecimal In the absence of any overriding suffixes the data type of an hexadecimal constant is derived from its value according to the rules presented above For example 0xC367 will be treated as unsigned int Binary All constants starting with 0b or 0B are taken to be binary In the absence of any overriding suffixes the data type of an binary constant is derived from its value according to the rules presented above For example 0511101 will be treated as short Octal All constants with an initial zero are taken to be octal If an octal constant contains the illegal digits 8 or 9 an error is reported In the absence of any overriding suffixes the data type of an octal constant is derived from its value according to the rules presented above For example 0777 will be treated as int MikroElektronika 180 mikroC PRO for PIC32 Floating Point Constants A floating point constant consists of Decimal integer Decimal point Decimal fraction eor E and a signed integer exponent optional Type suffix or F or 1 or 1
386. ild Toolbar Se O S2 22 2C jU X CCCCC C C C Run the mikrolCD by selecting Run gt Start Debugger from the drop down menu or by clicking the Start Debugger Icon G Starting the Debugger makes more options available Step Into Step Over Run to Cursor etc Line that is to be executed is color highlighted blue by default There is also notification about the program execution and it can be found in the Watch Window yellow status bar Note that some functions take more time to execute execution is indicated with Running message in the Watch Window Status Bar dismiss Select variable from list Related topics mikrolCD Debugger Example mikroICD Debug Windows mikrolCD Debugger Options MikroElektronika 116 mikroC PRO for PIC32 mikrolCD Debugger Options Debugger Options pus Function Toolbar Description Key Icon Executes the current program line then halts If the executed Step Into program line calls another routine the debugger steps into the F7 PO routine and halts after executing the first instruction within it Executes the current program line then halts If the executed Sten Duer program line calls another routine the debugger will not step into it The whole routine will be executed and the debugger halts at the first instruction following the call See SE Executes all remaining program lines within the subroutine EM ry P debugger halts immediately upon exiting the su
387. ile name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension file cre attr file creation and attributes flags Each bit corresponds to the appropriate file attribute ait wask BDe on Fo or ReadOnly s ouo Dovie riemal se ony never found on ak File creation flag If the file does not exist and this flag is 7 0x80 c S 3 set a new file with specified name will be created 0 if file does not exist and no new file is created 1 if file already exists or file does not exist but a new file is created CF card and CF library must be initialized for file operations See Cf Fat Init create file with archive attributes if it does not already exist Cf Fat Assign MIKRO007 TXT 0xA0 Notes Long File Names LFN are not supported 295 MikroElektronika mikoC PRO for PI
388. iles T6963C 240x128 ihex Active Comments Files amp i 7 Output Files amp z T6963C 240x128 hex T6963C 240x128 asm einstein_bmp asm mikroe bmp asm T6963C 240x128 lst S E Other Files B Datasheet 70138b pdf 665 MikroElektronika mikoC PRO for PIC32 The list of relevant files is stored in the project file extension mcp32 To add a file to the project click the Add File to Project Icon pae press Insert button on your keyboard Each added source file must be self contained i e it must have all necessary definitions after preprocessing To remove file s from the project click the Remove File from Project Icon ar or press Delete button on your keyboard Ilt Project Level Defines Project Level Defines 14 files can also be added to project Project level define files enable you to have defines that are visible in all source files in the project A file must contain one definition per line in the following form symbol value Define a macro named symbol To specify a value use lt value gt If lt value gt is omitted 1 is assumed Do not enter white space characters immediately before the If a white space character is entered immediately after the the macro is defined as zero token This option can be specified repeatedly Each appearance of symbol will be replaced by the value before compilation For example lets make a project level define named pld test First of all create
389. imary prescaler 64 Slave Select disabled data sampled in the middle of data output time clock idle high Serial output data changes on transition from active clock state to idle clock state Tip Once the MMC SD card is initialized SPI module can be reinitialized at higher a speed See the Mmc Init and Mmc Fat Init routines MikroElektronika 364 mikroC PRO for PIC32 Library Dependency Tree MMC MMC FAT16 C String C Type External dependencies of MMC Library The following variable must be defined bescrintion in all projects using MMC library P extern fr sbit Mmc Chi P_ Chip select pin sbit Mmc Chip Select at LATFO bit Select extern sfr sbit Mmc Chip Select Direction of the chip select pin sbit Mnc Chip Select Direction Direction i Ip pi TRISFO bit Library Routines Mmc Init Mmc Read Sector Mmc Write Sector Mmc Read Cid Mmc Read Csd Routines for file handling Mmc Fat Init Mmc Fat QuickFormat Mmc Fat Assign Mmc Fat Reset Mmc Fat Read Mmc Fat Rewrite Mmc Fat Append Mmc Fat Delete Mmc Fat Write Mmc Fat Set File Date Mmc Fat Get File Date Mmc Fat Get File Date Modified Mmc Fat Get File Size Mmc Fat Get Swap File 365 MikroElektronika 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 o
390. imeTypeScript text plain n n TEXT MIME type unsigned char httpMethod GET web page splited into 2 parts when coming short of ROM fragmented data is handled more efficiently by linker this HTML page calls the boards to get its status and builds itself with javascript ey const code char indexPage Change the IP address of the page to be refreshed lt meta http equiv refresh content 3 url http 192 168 20 60 gt lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt lt h1l gt PIC32 ENC28J60 Mini Web Server lt hl1 gt lt a href gt Reload lt a gt lt script src s gt lt script gt MikroElektronika 458 mikroC PRO for PIC32 table gt lt tr gt lt td valign top gt lt tabl NS border 1 styl font size 20px font family terminal tr th colspan 2 gt ADC lt th gt lt tr gt tr td ANO td td script document write ANO lt script gt lt td gt lt tr gt lt tr gt lt td gt AN1 lt td gt lt td gt lt script gt document write AN1 lt script gt lt td gt lt tr gt lt table gt lt td gt lt td gt lt table border 1 style font size 20px font family terminal gt tr th colspan 2 gt PORTB lt th gt lt tr gt lt script gt var str i str 7 for i 2 1 lt 10 1i str lt tr gt lt td bgcolor pink gt BUTTON it lt td gt if PORTB amp 1 lt lt i str
391. in MCU s datasheet CAN Module PHSEG2 as defined in MCU s datasheet CAN Module PROPSEG as defined in MCU s datasheet CAN Module CANSPI CONFIG FLAGS is formed from predefined constants See CANSPI CONFIG FLAGS constants Nothing Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode 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 See connection example at the bottom of this page set required baud rate and sampling rules char CANSPI CONFIG FLAGS CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be in config mode for baud rate settings CANSPI CONFIG FLAGS _CANSPI CONFIG SAMPLE THRICE amp CANSPI CONFIG PHSEG2 PRG ON amp CANSPI CONFIG STD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG amp CANSPI CONFIG LINE FILTER OFF 1 3 3 1 CANSPI CONFIG FLAGS 215 MikroElektronika mikoC PRO for PIC32 CANSPISetMask Prototype void iD ree 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 va
392. increment received dat 0 send back to master if sending failed 10 times Af send message on broadcast address buffer for receving sending messages set transcieve pin set transcieve pin direction iv IVT_UART 2 ilevel 7 ics ICS_SRS ai MikroElektronika mikoC PRO for PIC32 RS485Slave Receive dat U2RXIF bit 0 void main CHECON 0x32 ADIPCFG OxFFFF TRISB TRISD PORTB PORTD oo 2 UART2 Init 19200 Delay ms 100 RS485Slave Init 160 dat 0 OxAA dat 1 OxF0 dat 2 OxOF dat 4 0 dat 5 0 dat 6 0 U2IPO bit 1 U2IP1 bit 1 U2IP2 bit 1 URXISEL1 U2STA bit 0 received U2RXIF bit 0 MVEC_bit 1 asm ei RO ensure interrupt not pending initialize UART2 module Intialize MCU as slave address 160 ensure that message received flag is 0 ensure that error flag is 0 set interrupt priority LC e 7 Ox Interrupt flag bit is set when a character is ensure interrupt not pending Interrupt controller configured for multi vectored mode Enable all interrupts U2RXIE bit 1 enable intterupt while 1 if dat 5 if an error detected signal it by PORTD OxAA setting portd to OxAA dat 5 0 if dat 4 upon completed valid message receive dat 4 0 du data 4 is set to OxFF j dat 3 for i 1 i lt dat 3 itt
393. ing examples are also valid but better avoid this syntax as it can make the code really illegible a IDE 3 same as a 1 i 3 i e afi 1 3 i 2 a 0 same as i 2 a 0 i e afi 2 0 Assignment and Comparison The simple assignment operator can be used to assign value of one pointer to another if they are of the same type If they are of different types you must use a typecast operator Explicit type conversion is not necessary if one of the pointers is generic of the void type Assigning the integer constant 0 to a pointer assigns a null pointer value to it Two pointers pointing to the same array may be compared by using relational operators lt lt gt and gt Results of these operations are the same as if they were used on subscript values of array elements in question int pa amp a 4 pb amp a 2 if pa pb won t be executed as 4 is not equal to 2 if pa gt pb will be executed as 4 is greater than 2 You can also compare pointers to zero value testing in that way if the pointer actually points to anything All pointers can be successfully tested for equality or inequality to null if pa 0 if pb l 0 i Note Comparing pointers pointing to different objects arrays can be performed at programmer s own responsibility a precise overview of data s physical storage is required MikroElektronika 2
394. ining text and graphics for example labels on buttons G1p13308 OVERERY XOR In this mode the text and graphics data are combined via the logical exclusive OR 913700 OURREAY AND The text and graphic data shawn on display are combined via the logical AND function Glcd module needs to be initialized See the S1D13700 Init routine eme 1D13700 Write Text EPSON LIBRARY DEMO WELCOME 0 S1D13700 OVERLAY S1D13700 Dot S1D13700 OVERLAY OR Prototype void S1D13700 Dot unsigned int x unsigned int y unsigned short color Description Draws a dot in the current graphic panel of Glcd at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine ETA S1D13700 Dot 50 50 S1D13700 WHITE 319 MikroElektronika mikoC PRO for PIC32 S1D13700 Line Prototype void S1D13700 Line unsigned int x0 unsigned int y0 unsigned int x1 unsigned int yl unsigned char pcolor 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 S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs t
395. integral value in assignments or via explicit typecast produces correct results only if the float value does not exceed the scope of destination integral type In details Here are the steps the mikroC PRO for PIC32 uses to convert the operands in an arithmetic expression First any small integral types are converted according to the following rules bit converts to char char converts to int Signed char converts to int with the same value short converts to int with the same value sign extended unsigned short converts to unsigned int With the same value zero filled enum converts to int with the same value OORUN After this any two values associated with an operator are either int including the Long and unsigned modifiers or float equivalent with double and long double in the mikroC PRO for PIC32 1 If either operand is float the other operand is converted to float 2 Otherwise if either operand is unsigned long the other operand is converted to unsigned long 3 Otherwise if either operand is long then the other operand is converted to long 4 Otherwise if either operand is unsigned then the other operand is converted to unsigned 5 Otherwise both operands are int The result of the expression is the same type as that of the two operands MikroElektronika 220 mikroC PRO for PIC32 Here are several examples of implicit conversion Soll SE a Ba A BD Se Ded Ww 4 3 5 4 3 143 s
396. internal pointers All subsequent graphic operations will be preformed at this graphic panel n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set graphic panel 1 as current graphic panel SPI T6963C setGrPanel 1 SPI T6963C setTxtPanel Description Compute Sl start address for selected text panel and set appropriate internal pointers All subsequent text operations will be preformed at this text panel n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set text panel 1 as current text panel SPI T6963C setTxtPanel 1 MikroElektronika 026 mikroC PRO for PIC32 SPI T6963C panelFill Prototype void SPI T6963C panelFill unsigned char v Description Fill current panel in full graphict text with appropriate value 0 to clear SPI T6963C panelFill 0 None SPI T6963C grFill mee CNN SPI T6963C grFill 0 ses None SPI T6963C txtFill E n Ill i 4 l J Toshiba Glcd module needs to be initialized See SPI_T6963C_Config routine clear current text panel SPI T6963C txtFill 0 None 521 MikroElektronika mikoC PRO for PIC32 SPI T6963C cursor height Prototype void SPI T6963C cursor height unsigned char n Parameters n cursor height Valid values 0 7 Toshiba Glcd module needs to be initialized S
397. ion Displays a partial area of the image on a desired location Requires Parameters left left coordinate of the image top top coordinate of the image width desired image width height desired image height image image to be displayed Bitmap array is located in code memory stretch stretches image by a given factor if 2 it will double the image TFT module needs to be initialized See the TFT_Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 TFT PartialImage 10 12 10 15 image 1 TFT_Image_Jpeg Prototype char TFT Image Jpeg unsigned int left unsigned int top code const far unsigned short image if image is loaded and displayed successfully if error occured Description Displays a JPEG image on a desired location Requires Parameters left left coordinate of the image top top coordinate of the image image image to be displayed Bitmap array is located in code memory TFT module needs to be initialized See the TFT_Init routine MikroElektronika 916 mikroC PRO for PIC32 TFT RGBToColor16bit blue Retums Returns a color value in the following bit order 5 bits red 6 bits green and 5 bits blue color Description Converts 5 6 5 RGB format into true color format Prototype a int TFT RGBToColorl bit char rgb red char rgb green char rgb_ Parameters rgb red red
398. ion 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 shift ctr I Indent selected code Outdent shift ctr U f 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 If the string is not found a message is displayed Search for Options Replace Text Dialog box for searching for a text string in file and replacing it with another text string mikroElektronika mikroE NC D crea MikroElektronika 42 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 ok cance Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned Regular expressions option By checking this box you will be able to advance your search through Regular expressions Search for unsigned x20int D E E
399. ion members are accessed directly because they are in the scope containing the anonymous union Referring to declarations from the example above i 13 f 3 145 uc cl c vu s 211 MikroElektronika 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 Much more elegant solution is to use the mikroC PRO for PIC32 s intrinsic ability for individual bit access see Accessing Individual Bits for more information Bit Fields Declaration Bit fields can be declared only in structures and unions Declare a structure normally and assign individual fields like this fields need to be unsigned struct tag unsigned bitfield declarator list Here tag is an optional name of the structure bitfield declarator list is a list of bit fields Each component identifer requires a colon and its width in bits to be explicitly specified Total width of all components cannot exceed two bytes 16 bits As an object bit fields structure takes two bytes Individual fields are packed within two bytes from right to left
400. ion returns a sequence of pseudo random numbers between 0 and 32767 The function will always produce the same sequence of numbers unless srand is called to seed the start point while 1 result rand srand Prototype void srand unsigned x Description Function uses x as a starting point for a new sequence of pseudo random numbers to be returned by subsequent calls to rand No values are returned by this function Bee jeep c 0 0 am xtoi Prototype unsigned xtoi char s Description Function converts the input string s consisting of hexadecimal digits into an integer value The input parameter s should consist exclusively of hexadecimal digits with an optional whitespace and a sign at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize including a null character Example result xtoi lIFF result 511 MikroElektronika 618 mikroC PRO for PIC32 Div Structures Copy Code To Clipboard typedef struct divstruct int quot int rem Jadiy t typedef struct ldivstruct long quot long rem F dv E typedef struct uldivstruct unsigned long quot unsigned long rem uldiv t 619 MikroElektronika mikoC PRO for PIC32 ANSI C String Library The mikroC PRO for PIC32 provides a set of standard ANSI C library functions useful for manipulating strings and RAM memory Important
401. ions If Port Expander Library uses SPI1 module SPILL Init Initialize SPI module used with PortExpander SPI Lcd Config 0 initialize Lcd over SPI interface SPI Lcd Out Prototype void SPI Lcd Out char row char column char text Description Prints text on the 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 Nothing Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write text Hello on Lcd starting from row 1 column 3 SPI Led Oue l 3 Hello Jy None 501 MikroElektronika mikoC PRO for PIC32 SPI Lcd Out Cp Ze void SPI Lcd Out CP char text Prints text on the Lcd at current cursor position Both string variables and literals can be passed as a text text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routine Write text Here at current cursor position SPI Led Out CP Herel SPI Lcd Chr diia a void SPI Lcd Chr char Row char Column char Out Char Prints character on Lcd at specified position Both variables and literals can be passed as character Parameters Row writing position row number Column Writing position column number Out Char character to be written Lcd needs to be initialize
402. irection at TRISB2 bit sbit Gl D3 Direction at TRISB3 bit sbit Gl D4 Direction at TRISDO bit sbit Gl D5 Direction at TRISD1 bit sbit GLCD D6 Direction at TRISD2 bit sbit GLCD D7 Direction at TRISD3 bit sbit GLCD CS1 Direction at TRISBO bit sbit GLCD CS2 Direction at TRISB1 bit sbit GLCD RS Direction at TRISB2 bit sbit GLCD RW Direction at TRISB3 bit sbit GLCD EN Direction at TRISB4 bit sbit GLCD RST Direction at TRISB5 bit Gled Init r 321 MikroElektronika mikoC PRO for PIC32 Glcd Set Side Prototype void Glcd Set Side unsigned short x pos 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 Glcd needs to be initialized see Glcd Init routine The following two lines are equivalent and both of them select the left side of Glcd Gled Select cee Gled Select Side Notes For side x axis and page Emm explanation see schematic at the bottom of this page Glcd Set X Parameters x pos position on x axis Valid values 0 63 Rtuns No Rampe erca sees OOO Notes Forside x axis and page layout explanation see schematic at the bottom ofthis page Glcd Set Page eum Noting Glcd needs to be initialized see Glcd Init routine Example Gic set raoe 5 d Notes Fo
403. ires Glcd needs to be initialized see SPI Glcd Init routine Draws a filled rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 SPI Glcd Rectangle Round Edges Fill 5 5 491 MikroElektronika mikoC PRO for PIC32 SPI Glcd Box Prototype void SPI Glcd Box char x upper _ TEE char y upper left char x bottom right char y bottom right char color Draws a box on Glcd Parameters x upper left x coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right x coordinate of the lower right box corner Valid values 0 127 y bottom right y coordinate of the lower right box corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the box fill O white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Draw a box between dots 5 15 and 20 40 SPI Glcd Box 5 15 20 40 1 SPI Glcd Circle Prototype void SPI Glcd Circle int x center int y center int radius char color Description Draws a circle on Glcd Parameters x center x coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of t
404. is particular order 1 the project folder folder which contains the project file h 2 mikroC PRO for PIC32 installation folder gt Include folder 3 your custom search paths Related topics File Menu File Toolbar Project Manager Project Settings 675 MikroElektronika mikoC PRO for PIC32 Clean Project Folder This menu gives you option to choose which files from your current project you want to delete Files marked in bold can be easily recreated by building a project Other files should be marked for deletion only with a great care because IDE cannot recover them Clean Project Folder Below is the list of all files in the project folder Files in bold are those generated by the compiler and they can be easily recreated when the project is rebuilt Select which files you want to remove from the project folder Please note that selected files will be permanently deleted from your disk if you click the Clean button L LED xml v LedBlinking asm LedBlinking c LedBlinking cfg LedBlinking cp LedBlinking dbg LedBlinking dct LedBlinking dlt LedBlinking emcl LedBlinking hex LedBlinking log LedBlinking Ist LedBlinking mcp32 LedBlinking mcp32_callertable txt LedBlinking mil LedBlinking user dic LedBlinking wch LEDs jpg Led Blinking mc32group Led Curtain c Led Curtain cfg Led Curtain hex Led Curtain mcp32 iv v v v v v M v C Program Files Mikroelektronika mikroC
405. is used with octal or hexadecimal numbers to represent an ASCII symbol or control code corresponding to that value for example x3F for the question mark Any value within legal range for data type char 0 to OxFF for the mikroC PRO for PIC32 can be used Larger numbers will generate the compiler error Out of range 181 MikroElektronika mikoC PRO for PIC32 For example the octal number 777 is larger than the maximum value allowed 37 7 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 The following table shows the available escape sequences E eer sese quote apostrophe om pwmemee Disambiguation Some ambiguous situations might arise when using escape sequences Here is an example Led Out Cp Vx091 0 Intro This is intended to be interpreted as x09 and 1 0 Intro However the mikroC PRO for PIC32 compiles it as the hexadecimal number x091 and literal string 0 Intro To avoid such problems we could rewrite the code in the following way Led Out Cp Nx09 1 0 Intro For more information on the previous line refer to String Constants Ambiguities might also arise if an octal escape sequence is followed by a nonoctal digit For example the following constan
406. it Soft I2C Scl at RCO bit sbit Soft I2C Sda at RCl bit sbit Soft I2C Scl Direction at TRISCO bit Sbit Soft I2C Sda Direction at TRISC1 bit End Software I2C connections char counter 0 void TimerlInt org IVT ADDR TlINTERRUFT if counter gt 20 Soft I2C Break counter 0 reset counter else counter increment counter TlIF bit 0 Clear Timerl overflow interrupt flag void main try Soft I2C Init with blocking prevention mechanism LPCO IPCO 0x1000 Interrupt priority level 1 TIIE bit 1 Enable Timerl interrupts T1CON 0x8030 Timerl ON internal clock FCY prescaler 2256 Soft I2C Init TITE bit 0 Disable Timerl interrupts iudi Interrupts should be disabled before using Software C routines again see note at the top of this page MikroElektronika 418 mikroC PRO for PIC32 Library Example The example demonstrates use of the Software 1 C Library The PIC32 MCU is connected SCL SDA pins to PCF8583 RTC real time clock Program sends date time to RTC Copy Code To Clipboard char seconds minutes hours day month year Global date time variables Software I2C connections sbit Soft I2C Scl at RF3 bit sbit Soft I2C Sda at RF4 bit sbit Soft I2C Scl Direction at TRISF3 bit sbit Soft I2C Sda Direction at TRISF4 bit End Software I2C connections LCD module connections
407. it is assumed to be always true Thus empty for statement is commonly used to create an endless loop in C for 7 statement The only way to break out of this loop is by means of the break statement Here is an example of calculating scalar product of two vectors using the for statement for s 0 t 0 X lt n it s t alil biil There is another way to do this for s 0 1 0 2 n s t ali bi 24 valid but ugly 7 but it is considered a bad programming style Although legal calculating the sum should not be a part of the incrementing expression because it is not in the service of loop routine Note that null statement is used for the loop body 253 MikroElektronika 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 Break is commonly used in the switch statements to stop its execution upon the first positive match For example switch state case 0 Lo break case 1 Mid break case 2 Hi break default Message Invalid state Continue Statement The continue statem
408. it is precisely defined in some external file for example in the main program unit char MyVar sbit AnotherBit at MyVar B0 this is where AnotherBit is fully defined void main 139 MikroElektronika 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 H Note Bear in mind that when using at operator in your code over a variable defined through the extern modifier appropriate memory specifer must be appended also bit type The mikroC PRO for PIC32 compiler provides a bit data type that may be used for variable declarations It can not be used for argument lists and function return values bit bf bit variable There are no pointers to bit variables bit ptr invalid An array of type bit is not valid bit arr 51 gt invalid Note Bit variables can not be initialized Bit variables can not be members of structures and unions Bit variables do not have addresses therefore unary operator address of is not applicable to these variables Related topics Bit fields Predefined globals and constants Extern modifier MikroElektronika 110 mikroC PRO fo
409. it routine enable graphic displaying T6963C graphics 1 T6963C text Prototype void T6963C text unsigned int n Enable disable text displaying n on off parameter Valid values 0 disable text displaying and 1 enable text displaying Toshiba Glcd module needs to be initialized See the T6963C init routine enable text displaying T6963C text L T6963C cursor Prototype void T6963C cursor unsigned int n Set cursor on off n on off parameter Valid values 0 set cursor off and 1 set cursor on Toshiba Glcd module needs to be initialized See the T6963C init routine set cursor on T6963C cursor 1 553 MikroElektronika mikoC PRO for PIC32 T6963C cursor blink Prototype void T6963C cursor blink unsigned int n Enable disable cursor blinking Parameters n cursor blinking enable disable parameter Valid values 0 disable cursor blinking and 1 enable cursor ESSE Toshiba Glcd module needs to be initialized See the T6963C init routine enable cursor blinking T6963C cursor blxnk 1 Notes None OOS Library Example The following drawing demo tests advanced routines of the T6963C Glcd library Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L Copy Code To Clipboard include T6963C h T6963C module connections unsigned long T6963C dataPort at PORTD DATA port u
410. ite Cf Fat Append Prototype void Cf Fat Append Opens currently assigned file for appending Upon this function execution file pointers will be positioned P after the last byte in the file so any subsequent file writing operation will start from there 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 open file for appending Cf Fat Append Notes noe Cf Fat Delete 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 delete current fil Cf Fat Delete Notes noe OTS 29 MikroElektronika 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 Speed for writing Parameters fdata data to be written data len number of lt lt ORS M to be written Retums Nothing 00000 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 char file contents 42 Cf Fat Write file contents 42 write data to the assigned file Cf Fat Set File Date Prototype void Cf Fat Set File Date unsigned int year unsigned
411. ith 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 fune int n char chy lt i This declaration indicates that func will be defined in such a way that calls must have at least two arguments int and char but can also have any number of additional arguments Example include lt stdarg h gt int addvararg char al va_list ap char temp va_start ap al while temp va_arg ap char al temp return al int res void main res addvararg 1 2 3 4 5 0 res addvararg 1 2 3 4 5 6 7 9 9 10 0 53 MikroElektronika 234 mikroC PRO for PIC32 Operators Operators are tokens that trigger some computation when applied to variables and other objects in an expression Arithmetic Operators Assignment Operators Bitwise Operators Logical Operators Reference Indirect Operators Relational Operators Structure Member Selectors Comma Operator Conditional Operator Array subscript operator Function call operator sizeof Operator Preprocessor Operators and 235 MikroElektronika 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 a
412. itialized See Expander Init Port Expander s PortA and PortB should be configured as outputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTA and PORTB Expander Set DirectionPortAB 0 0x0000 set expander s porta and portb to be output Expander Write PortAB 0 0xAA55 Expander Set DirectionPortA Prototype void Expander Set DirectionPortA char ModuleAddress char Data Description The function sets Port Expander s PortA direction Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written to the PortA direction register Each bit corresponds to the appropriate pin of the PortA register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Nothing Requires Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output Expander Set DirectionPortA 0 0x00 391 MikroElektronika mikoC PRO for PIC32 Expander Set DirectionPortB Prototype id Expander Set DirectionPortB char ModuleAddress char Data The function sets Port Expander s PortB direction Parameters ModulcAddress 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
413. ition LATB LATB oldstate 0 while 1 629 initialize AN pins as digital initialize portd as input initialize portb as output detect logical one state detect logical one to logical zero toggle portb MikroElektronika mikoC PRO for PIC32 Conversions Library The mikroC PRO for PIC32 Conversions Library provides routines for numerals to strings and BCD decimal conversions Library Dependency Tree Conversions C_String Library Routines You can get text representation of numerical value by passing it to one of the following routines ByteToStr ShortToStr WordToStr IntToStr LongToStr LongWordToStr FloatToStr WordToStrWithZeros IntToStrWithZeros LongWordToStrWithZeros LongIntToStrWithZeros ByteToHex ShortToHex WordToHex IntToHex LongWordToHex LongintToHex Rtrim Ltrim The following functions convert decimal values to BCD and vice versa Bcd2Dec Dec2Bcd Bcd2Dec16 Dec2Bcd16 MikroElektronika 630 mikroC PRO for PIC32 ByteToStr Prototype void ByteToStr unsigned short input char output Description Converts input byte to a string The output string has fixed width of 4 characters including null character at the end string termination The output string is right justified and remaining positions on the left if any are filled with blanks Parameters input byte to be converted
414. its current location A guide diamond appears The four arrows of the diamond point towards the four edges of the IDE Project Maj Be u 0 000000 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 E an cu 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 ik To set the layout select the desired layout from the layout drop down list and click the Set Layout Icon To remove the layout from the drop down list select the desired layout from the list and click the Delete Layout Icon lie Default Layout Code Layout Debug Layout NENNEN Auto Hide Auto Hide enables you to see more of your code at one time by minimizing tool windows along the edges of the IDE when not in use Click the window you want to keep visible to give it focus Click the Pushpin Icon 2X on the title bar of the window MikroElektronika 84 mikroC PRO for PIC32 z Project Manager AJ 593 5 i ae s EH B Sources Z Led c Header Files built_in h d a gp Lcd mcp M thas iere GS Souri L aa5eue palog
415. j600 Init const char buffer mikroElektronika SPI Ethernet 24 600 putConstBytes buffer 16 put a const array into ENC24J600 buffer MikroElektronika 474 mikroC PRO for PIC32 SPI Ethernet 24j600 putString Prototype unsigned int SPI Ethernet 243600 putString unsigned char ptr Description This is MAC module routine It stores whole string excluding null termination into ENC247600 RAM starting from current ENC247600 write pointer EWRPT location Parameters ptr string to be written into ENC247600 RAM Number of bytes written into ENC247600 RAM Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init char buffer mikroElektronika SPI Ethernet 243600 putString buffer put a RAM string into ENC24J600 buffer SPI Ethernet 24j600 putConstString Prototype unsigned int SPI Ethernet 243600 putConstString const unsigned char ptr Description This is MAC module routine It stores whole const string excluding null termination into ENC247600 RAM starting from current ENC24J600 write pointer EWRPT location Parameters ptr const string to be written into ENC247600 RAM Number of bytes written into ENC247600 RAM Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init const char buffer mikroElektronika SPI Ethernet 24j600 putConstString buffer put a const string into EN
416. j600 UserUDP Prototype unsigned int SPI Ethernet 243600 UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength TEthj600PktFlags 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 24j600 get routines The user puts data in the transmit buffer by using some of the SPI Ethernet 24j600 put routines The function must return the length in bytes of the UDP reply or 0 if nothing to transmit If you don t need to reply to the UDP requests just define this function with a return 0 as single statement Parameters remoteHost client s IP address remotePort client s port localPort port to which the request is sent regLength UDP request data field length flags Structure consisted of two bit fields Copy Code To Clipboard typedef struct unsigned canCloseTCP 1 flag which closes TCP socket not relevant to UDP unsigned isBroadcast 1 flag which denotes that the IP package has been received via subnet broadcast address TEthj600PktFlags T 0 there should not be a reply to the request Length of UDP reply data field otherwise Ethernet module has to be initialized See SPI Ethernet 24600 Init This function is internally called by the library and should not be called by the user s code The function source code is provided with appropria
417. ject B P popogoagago0g0o 2 gl lt No libraries from the list will be included in current project Restore library to the state just before last project saving 63 MikroElektronika 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 For example E Library Manager a ERRAN Sound S SPI SPI Ethernet SPI Glcd SPI Lcd SPI Lcd8 SPI T6963C SprintF Sprinti Sprintl T6963C Time 8 6 8 Ec E E EH E E E E TouchPanel Trigonometry TWI UART amp Conversions es E ByteToBinaryStr WordToBinaryStr LongWordToBinaryStr BinaryToGray GrayToBinary Ivi DHIOIKIDIBIHSI EI CI CI CL EI BI CI DJ DJ CI E E E From the Library Manager the user can also uninstall the desired package by right clicking the the appropriate node and from the drop down menu choose Uninstall package E Library Manager a Ee Vas CO Sound e 4 oO ser C SPI Ethernet C SPI_Gled O sPr Lcd CO sPt_teds LJ spr_tes63c O sprint C sprinti amp C Sprint amp v Tese3
418. koC PRO for PIC32 Standard Conversions Standard conversions are builtin 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 Arithmetic Conversions When using arithmetic expression such asa b where a and b are of different arithmetic types the mikroC PRO for PIC32 performs implicit type conversions before the expression is evaluated These standard conversions include promotions of lower types to higher types in the interests of accuracy and consistency Assigning a signed character object such as a variable to an integral object results in automatic sign extension Objects of type signed char always use sign extension objects of type unsigned char always has its high byte set to zero when converted to int Converting a longer integral type to a shorter type truncates the higher order bits and leaves low order bits unchanged Converting a shorter integral type to a longer type either sign extends or zero fills the extra bits of the new value depending on whether the shorter type is signed or unsigned respectively Note Conversion of floating point data into
419. kroC 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 Library Routines Soft UART Init Soft UART Read Soft UART Write Soft UART Break Soft UART Init Prototype char Soft UART Init unsigned int port unsigned int rx unsigned int tx unsigned long baud rate unsigned int inverted Description Configures and initializes the software UART module Software UART routines use Delay Cyc routine If requested baud rate is too low then calculated parameter for calling Delay Cyc exceeds Delay Cyc argument range If requested baud rate is too high then rounding error of Delay Cyc argument corrupts Software UART timings Parameters port software UART port address rx receiver pin tx transmiter pin baud rate requested baudrate Maximum baud rate depends on the MCU s clock and working conditions inverted if set to non zero value indicates inverted logic on output 2 error requested baud rate is too low 1 error requested baud rate is too high 0 successful initialization This will initialize software UART and establish the communication at 9600 bps char error error Soft UART Init amp
420. lared in different scopes for example in different files or declared more than once in the same scope The linkage is a process that allows each instance of an identifier to be associated correctly with one particular object or function All identifiers have one of two linkage attributes closely related to their scope external linkage or internal linkage These attributes are determined by the placement and format of your declarations together with an explicit or implicit by default use of the storage class specifier static or extern Each instance of a particular identifier with external linkage represents the same object or function throughout the entire set of files and libraries making up the program Each instance of a particular identifier with internal linkage represents the same object or function within one file only 223 MikroElektronika 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 names having file scope explicitly declared as const and not explicitly declared as extern
421. le has no static address Warning Messages Enhancement Besides the smaller code SSA also deals with the intensive code analysis which in turn has the consequence in enhancing the warning messages For example compiler will warn the user that the uninitialized variable is used void main int y if y Variable y might not have been initialized PORTD 0 Related topics Code Optimization PIC32 Specifics mikroC PRO for PIC32 specifics Memory type specifiers 161 MikroElektronika mikoC PRO for PIC32 CHAPTER 7 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 MikroElektronika 162 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 Nested Calls Limitations There are no Nested Calls Limitatio
422. learBit 0x0003 T6963C setBit Prototype void 7T6963C setBit unsigned int b Sets control port bit s Parameters bit mask The function will set bit x on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See the T6963C init routine set bits 0 and 1 on control port T6963C setBit 0x0003 549 MikroElektronika mikoC PRO for PIC32 T6963C negBit Prototype void T6963C negBit unsigned int b Negates control port bit s Parameters bit mask The function will negate bit x on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See the T6963C init routine negate bits 0 and 1 on control port T6963C negBit 0x0003 Notes Nm T6963C displayGrPanel Reums Nong OSS SSS EI TO OU a OO T6963C displayGrPanel 1 ges Noe OOS T6963C_displayTxtPanel Rems Nang 000000 Toshiba Glcd module needs to be initialized See the T6963C init routine display text panel 1 T6963C displayTxtPanel 1 Notes None OOO MikroElektronika 550 mikroC PRO for PIC32 T6963C setGrPanel Description Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See the T6963C init routine set gr
423. librate Upper Right 582 TP Get Calibration Consts 583 TP Set Calibration Consts 583 Touch Panel TFT Library 584 Library Dependency Tree 584 External dependencies of Touch Panel TFT Library 584 Library Routines 584 TP TFT Init 585 TP TFT Set ADC Threshold 585 TP TFT Press Detect 586 TP TFT Get Coordinates 587 TP TFT Calibrate Min 587 TP TFT Calibrate Max 587 TP TFT Get Calibration Consts 588 23 MikroElektronika mikoC PRO for PIC32 TP TFT Set Calibration Consts 588 HW Connection 589 UART Library 590 Library Routines 590 UARTXx Init 591 UARTx Init Advanced 592 UARTx Data Ready 593 UARTx Tx Idle 593 UARTx Read 594 UARTx Read Text 595 UARTx Write 596 UARTx Write Text 596 UART Set Active 597 Library Example 598 HW Connection 599 USB Library 600 USB HID Class 600 Descriptor File 600 Library Routines 600 HID Enable 601 HID Read 601 HID Write 601 HID Disable 602 USB Interrupt Proc 602 USB Polling Proc 603 Gen Enable 603 Gen Read 604 Gen Write 604 Library Example 605 HW Connection 605 Standard ANSI C Libraries 606 ANSI C Ctype Library 606 Library Functions 606 isalnum 607 isalpha 607 iscntrl 607 isdigit 607 isgraph 607 islower 608 ispunct 608 isspace 608 isupper 608 isxdigit 608 toupper 609 tolower 609 ANSI C Math Library 610 MikroElektronika 24 mikroC PRO for PIC32 Library Functions 610 acos 610 asin 611 atan 611 atan2 611 ceil 611 cos 611 cosh 612 exp 612 fabs 612 floor 612 frexp 612
424. lled TFT module needs to be initialized See the TFT Init routine Example Ter rin screen mac CS MikroElektronika 568 mikroC PRO for PIC32 TFT Dot Prototype void TFT Dot int x int y unsigned int color Description Draws a dot on the TFT at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values TFT module needs to be initialized See the TFT Init routine Example TFT Dot 50 50 CL BLACK 569 MikroElektronika mikoC PRO for PIC32 TFT Set Pen Prototype void TFT Set Pen unsigned int pen color char pen width Description Sets color and thickness parameter for drawing line circle and rectangle elements Parameters pen color Sets color pen width sets thickness TFT module needs to be initialized See the TFT Init routine Example TFT Set Pen CL BLACK 10 MikroElektronika 910 mikroC PRO for PIC32 TFT Set Brush Prototype void TFT Set Brush char brush enabled unsigned int brush color char gradient enabled char gradient orientation unsigned int gradient color from unsigned int gradient color to Description Sets color and gradient which will be used to fill circles or rectangles Parameters brush enabled enable brush fill Enable brush fill Disable brush fill brush color set brush fill color Description 971 MikroElektronik
425. lock divider slave select data sample clock idle and determine the working mode for SPI The master mode parameter determines the working mode for SPI module Master Slave mode he parameter data mode the data length mode which can be 8 bits per transmitions cycle 16 bits br 32 bits Data Length Mode 16 bit mode SPI 16 BIT he parameter clock divider determines the value of the SPI clock speed Used only in the Maste Mode Clock Divider Value Valid values from 2 to 1024 he parameter slave select determines whether the Slave Select SS pin is used in communication alid in the Slave Mode only he parameter data sample determines the sample moment phase of input data Data Sampling Moment D sampled in the middle of data output SPI DATA SAMPL IDDLE Data sampled at end of data output time SPI DATA SAMPLE END 435 MikroElektronika mikoC PRO for PIC32 Parameters The parameter clock idle determines the behaviour of the SPI clock CLK line in IDLE phase Clock Polarity IDLE state is Lo ACTIVE state is Hi SPI CLK IDLE LOW IDLE state is Hi ACTIVE state is Lo SPI CLK IDLE HIGH The parameter edge determines on which clock edge data is considered to be valid Clock Edge Data is valid on ACTIVE to IDLE transition SPI ACTIVE 2 IDLE Data is valid on IDLE to ACTIVE transition SPI IDLE 2 ACTIV Nothing MCU must have the SPI
426. lop and deploy complex applications Write your source code using the built in Code Editor Code and Parameter Assistants Code Folding Syntax Highlighting Auto Correct Code Templates and more Use included mikroC PRO for PIC32 libraries to dramatically speed up the development data acquisition memory displays conversions communication etc Monitor your program structure variables and functions in the Code Explorer Generate commented human readable assembly and standard HEX compatible with all programmers Use the integrated mikroICD In Circuit Debugger Real Time debugging tool to monitor program execution on the hardware level Inspect program flow and debug executable logic with the integrated Software Simulator Use Single Static Assignment optimization to shrink your code to even smaller size Get detailed reports and graphs RAM and ROM map code statistics assembly listing calling tree and more Active Comments enable you to make your comments alive and interactive mikroC PRO for PIC32 provides plenty of examples to expand develop and use as building bricks in your projects Copy them entirely if you deem fit that s why we included them with the compiler Where to Start In case that you re a beginner in programming the PIC32 microcontrollers read carefully the PIC32 Specifics chapter It might give you some useful pointers on the PIC32 constraints code portability and good programming p
427. lows variable to be stored in the working registers space reserved for compiler purposes only puts y in working register space rx Char y sfr Description This memory specifier allows user to access special function registers It also instructs compiler to maintain same identifier in source and assembly Example sfr char y puts y in SFR space Note If none of the memory specifiers are used when declaring a variable data specifier will be set as default by the compiler Related topics PIC32 Memory Organization Accessing individual bits SFRs Constants Functions 167 MikroElektronika 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 RBO in PORTB the microcontroller first READs all 8 bits of the PORTB register which represents the states of all 8 pins in PORTB RB7 RBO The microcontroller then stores this data in the MCU The bit associated with RB that you ve commanded to MODIFY is changed and then the microcontroller WRITES all 8 bits RB7 RBO back to the PORTB register During the first reading of the PORT register you will be reading the actual state of the physical pin The problem arises when an output pin is loaded in such a way that its log
428. ls see the T6963C datasheet Toshiba Gled module needs to be initialized See SPI T6963C Config routine Example SPI T6963C write char A 22 23 SPI T6963C ROM MODE AND MikroElektronika 918 mikroC PRO for PIC32 SPI T6963C write text Prototype void SPI T6963C write oe char str unsigned char x unsigned char y unsigned char mode Writes text in the current text panel of Glcd at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis mode mode parameter Valid values SPI T6963C ROM MODE OR SPI T6963C ROM MODE XOR SPI T6963C ROM MODE AND and SPI T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically DR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in negative mode i e white text on black background AND Mode The text and graphic data shown on the display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Nothing Toshiba Glcd module needs to be initialized See SPI T6963C Config ro
429. lt td bgcolor red gt ON else strt lt td bgcolor cccccc gt OFF str lt td gt lt tr gt 7 document write str lt script gt const code char indexPage2 lt table gt lt td gt lt td gt table border 1 style font size 20px font family terminal gt tr th colspan 3 gt PORTD lt th gt lt tr gt lt script gt var str i str 7 for i 0 i lt 8 1i strt lt tr gt lt td bgcolor yellow gt LED i lt td gt if PORTD amp 1 lt lt i str lt td bgcolor red gt ON else strt lt td bgcolor cccccc gt OFF str lt td gt lt td gt lt a href t it gt Toggle lt a gt lt td gt lt tr gt document write str lt script gt lt table gt lt td gt lt tr gt lt table gt This is HTTP request lt script gt document write REQ lt script gt lt BODY gt lt HTML gt RK HK Kk KK I I I kk RAM variables d unsigned char myMacAddr 6 0x00 0x14 OxA5 0x76 0x19 Ox3f my MAC address unsigned char myIpAddr 4 192 168 20 60 my IP address unsigned char gwlIpAddr 4 192 LOS 20 eh gateway router IP address unsigned char ipMask 4 255 255 255 0 network mask for example 255 255 255 0 unsigned char dnsIpAddr 4 192 168 20 1 DNS server IP address unsigned char unsigned char unsigned long getRequest 15 dyna 31 httpCounter 0 HTTP request buffer buffer
430. lues CANSPT MASK constants See CANSPI_ MASK constants val mask register value This value is bit adjusted to appropriate buffer mask registers CANSPI CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG STD MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG XTD MSG See CANSPI_CONFIG_FLAGS constants Requires The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode 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 See connection example at the bottom of this page set the appropriate filter mask and message type value CANSPISetOperationMode CANSPI MODE CONFIG OxFF Z set CONFIGURATION mode CANSPI module must be in config mode for mask settings Set all B1 mask bits to 1 all filtered bits are relevant Note that 1 is just a cheaper way to write OXFFFFFFFF Complement will do the trick and fill it up with ones CANSPISetMask CANSPI MASK Bl 1 _CANSPI CONFIG MATCH MSG TYP CONFIG_XTD MSG MikroElektronika 216 mikroC PRO for PIC32 CANSPISetFilter Prototype void CANSPISetFilter unsigned short CANSPI FILTER long value unsigned short CANSPI CONFIG FLAGS Description Configures message filter T
431. m character classes Example routi de matches strings like routile routi6e and so on but not routine routime and so on Metacharacters Word boundaries A word boundary X5 is a spot between two characters that has an alphanumeric character Vw on one side and a nonalphanumeric character NW on the other side in either order counting the imaginary characters off the beginning and end of the string as matching a Ww b match a word boundary XB match a non word boundary Metacharacters Iterators Any item of a regular expression may be followed by another type of metacharacters iterators Using this metacharacters you can specify number of occurences of previous character metacharacter or subexpression zero or more greedy similar to 0 one or more greedy similar to 1 zero or one greedy similar to 0 1 n exactly n times greedy n atleast n times greedy n m atleast n but not more than m times greedy Zero or more non greedy similar to 0 one or more non greedy similar to 1 zero or one non greedy similar to 0 1 n exactly n times non greedy n atleast n times non greedy n m atleast n but not more than m times non greedy So digits in curly brackets of the form n m specify the minimum number of times to match the item n and the
432. mat of variable register representation between decimal hexadecimal binary float or character All representations except float are unsigned by default For signed representation click the check box next to the Signed label Edit Value ADPCFG 0000 FFFF Representation Dec S Hex OBin O Float O Char An item s value can also be changed by double clicking item s value field and typing the new value directly 123 MikroElektronika 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 mikrolCD Specific RAM window content will be written to the MCU before the next instruction execution Lcd4bit mikroE ikroElektronike EasydsPIC4 lt Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View Debug Windows Stopwatch The Stopwatch Window displays a Current Count of cycles time since the last Software Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started and can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has started and ended Watch Clock Cycles Time Current Count 2 103 943 273 105 205
433. ment for i O07 i lt n i For more information see the Statements Colon Use colon to indicate the labeled statement start x 0 gabs Sassi Labels are discussed in the Labeled Statements Asterisk Pointer Declaration Asterisk in a variable declaration denotes the creation of a pointer to a type char char ptr a pointer to char is declared Pointers with multiple levels of indirection can be declared by indicating a pertinent number of asterisks int int ptr a pointer to an array of integers double double ptr a pointer to a matrix of doubles You can also use asterisk as an operator to either dereference a pointer or as multiplication operator i int ptr p 3 14 For more information see the Pointers MikroElektronika 190 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 Dy asb g 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 It signifies a compiler action not necessarily associated with a code generation See the Preprocessor Directives for more information and are also used as operators to perform token repl
434. meses T MikroElektronika 320 mikroC PRO for PIC32 S1D13700 Partiallmage Prototype void S1D13700 Partiallmage 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 Description Displays a partial area of the image on a desired location Parameters x left x coordinate of the desired location upper left coordinate y top y coordinate of the desired location upper left coordinate width desired image width height desired image height picture width width of the original image picture height height of the original image image image to be displayed Bitmap array is located in code memory Note Image dimension must match the display dimension Glcd module needs to be initialized See the S1D13700 Init routine Draws a 10x15 part of the image starting from the upper left corner on the coordinate 10 12 Original image size is 16x32 1D13700 PartialTmage 10 12 10 15 16 32 image 321 MikroElektronika 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 x 512 4096 bytes or 102
435. meter 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 IC 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 See Soft I2C Start routine unsigned short take Read data and send the not acknowledge signal take Soft I2C Read 0 Soft I2C Write Prototype unsigned short Soft I2C Write unsigned short data Sends data byte via the I C bus data data to be sent 0 if there were no errors 1 if write collision was detected on the I C bus Requires Soft IC 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 See Soft I2C Start routine unsigned short data error error Soft I2C Write data error Soft I2C Write 0xA3 Soft I2C Stop Requires Soft IC must be configured before using this function See Soft I2C Init routine Issue STOP signal Soft I2C Stop None 417 MikroElektronika mikoC PRO for PIC32 Soft I2C Break Prototype void Soft I2C Break 0 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 Software I2C connections sb
436. meters x coordinate x coordinate of the place of touch y coordinate y coordinate of the place of touch 1 ifreading is within display dimension range 0 if reading is out of display dimension range TP TFT Get Coordinates amp x coord amp y coord TP TFT Calibrate Min TP TFT Calibrate Max void TP TFT Calibrate Max Returns Nothing oooooo O Example TP TFT Calibrate Max Calibration of upper right corner LM 587 MikroElektronika mikoC PRO for PIC32 TP TFT Get Calibration Consts Prototype void TP TFT Get Calibration Consts unsigned int x min unsigned int x_ max unsigned int y min unsigned int y max Description Gets calibration constants after calibration is done and stores them in x min x max y min and y max parameters Parameters x min x coordinate of the bottom left corner of the working area x max X coordinate of the upper right corner of the working area y min y coordinate of the bottom left corner of the working area y max y coordinate of the upper right corner of the working area TP TFT Get Calibration Consts amp x min amp y min amp x max amp y max calibration constants TP TFT Set Calibration Consts Prototype void TP TFT Set Calibration Consts unsigned int x min unsigned int x max unsigned int y min unsigned int y max Sets calibration constants Parameters min X coordinate of the bottom left corner of the working
437. might be board hang or miss some requests SPI Ethernet library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction ARP client with cache DNS client UDP client DHCP client packet fragmentation is NOT supported Important Global library variable SPI Ethernet userTimerSec is used to keep track of time for all client implementations ARP DNS UDP and DHCP It is user responsibility to increment this variable each second in it s code if any of the clients is used For advanced users there are header files eth enc28j60LibDef h and eth enc28j60LibPrivate h in Uses folder of the compiler with description of all routines and global variables relevant to the user implemented in the SPI Ethernet Library The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines Refer to SPI Library For MCUs with multiple SPI modules it is possible to initialize them and then switch by using the SPI Set Active routine Library Dependency Tree SPI Ethernet I String M1 MikroElektronika mikoC PRO for PIC32 External dependencies of SPI Ethernet Library The following variables must be defined projects using SPI in all Ethernet Library extern sfr sbit SP Cor Ethernet extern sfr sbit SP RST Ethernet extern sfr sbit SPI Ethernet CS
438. 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 Negative initializers are allowed See Enumerations for details about enum declarations Pointer Constants A pointer or pointed at object can be declared with the const modifier Anything declared as const cannot change its value It is also illegal to create a pointer that might violate a non assignability of the constant object Consider the following examples ine i i is an int int pi pi is a pointer to int uninitialized int const cp amp i cp is a constant pointer to int const int ci 7 ci is a constant int const int pci pci is a pointer to constant int const int const cpc Sci cpc is a constant pointer to a constant int The following assignments are legal i ci Assign const int to int cp ci Assign const int to object pointed at by a const pointer Tepoir Increment a pointer to const pci cpc Assign a const pointer to a const to a pointer to const
439. mily MCU and CF card voltage levels are different The user must ensure that MCU s pin connected to CD line can read CF card Logical One correctly Cf_Enable Prototype Description Enables the device Routine needs to be called only if you have disabled the device by means of the Cf Disable routine These two routines in conjunction allow you to free occupy data line when working with multiple devices Nothing The corresponding MCU ports must be appropriately initialized for CF card See Cf Init enable compact flash Cf Enable None Cf Disable Prototype void Cf Disable Description Routine disables the device and frees the data lines for other devices To enable the device again call Cf Enable These two routines in conjunction allow you to free occupy data line when working with multiple devices P Nothing The corresponding MCU ports must be appropriately initialized for CF card See Cf Init disable compact flash Cf Disable None 291 MikroElektronika mikoC PRO for PIC32 Cf Read Init DEO void Cf Read Init unsigned long address unsigned short sector count 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 The corresponding MCU ports must be appropriately initialized for CF card See Cf Init initialize compact flash for reading fr
440. mization 158 Better code generation and local optimization 158 Single Static Assignment Optimization 159 Introduction 159 Proper Coding Recommendations 160 Asm code and SSA optimization 161 Debugging Notes 161 Warning Messages Enhancement 161 CHAPTER 7 162 PIC32 Specifics 162 Types Efficiency 163 Nested Calls Limitations 163 Variable constant and routine alignment 163 Boot Start up Initialization 163 PIC32 Memory Organization 164 PIC32MX Memory Layout 165 Virtual vs Physical Addresses 166 Memory Type Specifiers 167 code 167 data 167 rx 167 sfr 167 Read Modify Write Problem 168 CHAPTER 8 172 mikroC PRO for PIC32 Language Reference 172 Lexical Elements Overview 175 Whitespace 176 Whitespace in Strings 176 Line Splicing with Backslash 176 Comments 177 C comments 177 C comments 177 Nested comments 177 Tokens 178 Token Extraction Example 178 Constants 179 Integer Constants 179 Long and Unsigned Suffixes 179 Decimal 179 MikroElektronika mikoC PRO for PIC32 Hexadecimal 180 Binary 180 Octal 180 Floating Point Constants 181 Character Constants 181 Escape Sequences 181 Disambiguation 182 String Constants 183 Line Continuation with Backslash 183 Enumeration Constants 184 Pointer Constants 184 Constant Expressions 185 Keywords 186 Identifiers 187 Case Sensitivity 187 Uniqueness and Scope 188 Identifier Examples 188 Punctuators 188 Brackets 188 Parentheses 189 Braces 189 Comma 189 Semicolon 190 Colon 1
441. mized using SSA optimizer and to call this function via function pointer in another module which is optimized using NON SSA When using pointers to functions compiler must know exactly how to pass function parameters and how to execute function call MikroElektronika 160 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 Because of this user must be very careful when writing asm code as existing values in the working registers used by SSA optimization can be overwritten To avoid this it is recommended that user includes desired asm code in a separate routine Debugging Notes SSA also influences the code debugging in such a way that the local variables will be available in the Watch Window only in those parts of the procedure where they have useful value eg on entering the procedure variable isn t available until its definition Variables can be allocated in one part of the procedure in register W4 and in another part of the procedure in register W2 if the optimizer estimates that it is better that way That means that the local variab
442. module Set SPI1 to the Master Mode data length is 16 bit clock Fcy no clock scaling data sampled in the middle of interval clock IDLE state high and data transmitted at low to high clock edge SPI1 Init Advanced SPI MASTER SPI 16 BIT 1 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3 Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 436 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 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 SPlx Init Advanced routines read a byte from the SPI bus char take buffer take SPI1 Read buffer SPI library routines require you to specify the module you want to use To select the desired SPI module simply change the letter x in the routine prototype for a number from 1 to 3
443. module needs to be initialized See the T6963C init routine T6963C write text Glcd LIBRARY DE 0 0 T6963C ROM MODE XOR T6963C_line Prototype void T6963C line int x0 int y0 int x1 int yl unsigned char pcolor 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 T6963C BLACK and T6963C WHITE mum Re DTE Example T6963C line 0 239 127 T6963C WHITE S RN MikroElektronika 544 mikroC PRO for PIC32 T6963C rectangle Prototype void T6963C rectangle int x0 int y0 int xl int yl unsigned char pcolor Draws a re on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE mms emu DEUS Ese ee rectangle 20 20 219 107 T6963C WHITE me pe RN RN O T6963C_rectangle_round_edges Prototype void T6963C rectangle round edges int x0 int yO int xl int yl int round radius unsigned char pcolor Draws a rounded edge rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the up
444. mp filename 0 Mmc Fat Set File Date 2009 1 23 17 22 0 Mmc Fat Append Prepare file for append Mmc Fat Write for mikroElektronika 2009 5n 27 Write data to assigned file Opens an existing file reads data from it and puts it to UART void M Open File Read char character filename 7 B Mmc Fat Assign filename 0 Mmc Fat Reset amp size To read file procedure returns size of file for i 1 i lt size itt Mmc Fat Read amp character UART1 Write character Write data to UART 319 MikroElektronika mikoC PRO for PIC32 Deletes a file If file doesn t exist it will first be created and then deleted void M Delete File filename 7 WE Mmc Fat Assign filename 0 Mmc Fat Delete Tests whether file exists and if so sends its creation date and file size via UART void M Test File Exist unsigned long fsize unsigned int year unsigned short month day hour minute unsigned char outstr 12 Mmc Fat Get File Date amp year amp month amp day amp hour amp minute filename 7 B uncomment this line to search for file that DOES exists filename 7 F uncomment this line to search for file that DOES NOT exist if Mmc Fat Assign filename 0 file has been found get its create date mc Fat Get File Date amp year amp month amp day amp hour amp minute UART1 Write Text c
445. mple if a and b are nonconstant integer identifiers with properly allocated memory storage they are both modifiable lvalues and assignments such as a 1 and a bare legal Rvalues The expression a bisnotlvalue a b a is illegal because the expression on the left is not related to an object Such expressions are sometimes called rvalues short for right values Scope and Visibility Scope The scope of an identifier is a part of the program in which the identifier can be used to access its object There are different categories of scope block or local function function prototype and file These categories depend on how and where identifiers are declared Block The scope of an identifier with block or local scope starts at the declaration point and ends at the end of the block containing the declaration such block is known as the enclosing block Parameter declarations with a function definition also have block scope limited to the scope of the function body File File scope identifiers also known as globals are declared outside of all blocks their scope is from the point of declaration to the end of the source file Function The only identifiers having function scope are statement labels Label names can be used with goto statements anywhere in the function in which the label is declared Labels are declared implicitly by writing Label name followed by a statement Label names must be unique within a function
446. n a pointer A pointer of type pointer to object of type holds the address of that is points to an object of t ype Since pointers are objects you can have a pointer pointing to a pointer and so on Other objects commonly pointed to include arrays structures and unions A pointer to a function is best thought of as an address usually in a code segment where that function s executable code is stored that is the address to which control is transferred when that function is called Although pointers contain numbers with most of the characteristics of unsigned integers they have their own rules and restrictions for declarations assignments conversions and arithmetic The examples in the next few sections illustrate these rules and restrictions Pointer Declarations Pointers are declared the same as any other variable but with ahead of identifier Atype at the beginning of declaration specifies the type of a pointed object A pointer must be declared as pointing to some particular type even if that type is void which really means a pointer to anything Pointers to void are often called generic pointers and are treated as pointers to char in the mikroC PRO for PIC32 If type is any predefined or user defined type including void the declaration type p Uninitialized pointer declares p to be of type pointer to type All scoping duration and visibility rules are applied to the p object just declared You can view th
447. n 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 varl initl var2 init2 where vari var2 are any sequence of distinct identifiers with optional initializers Each of the variables is declared to be of type if omitted type defaults to int The specifier storage class can take the values extern static register or the default auto Optional type qualifier can take values const or volatile For more details refer to Storage Classes and Type Qualifiers For example Create 3 integer variables called x y and z and initialize x and y to the values 1 and 2 respectively int x 1 y 2 z z remains uninitialized Create a floating point variable q with static modifier and initialize it to 0 25 static float q 25 These are all defining declarations storage is allocated and any optional initializers are applied Linkage An executable program is usually created by compiling several independent translation units then linking the resulting object files with preexisting libraries A term translation unit refers to a source code file together with any included files but without the source lines omitted by conditional preprocessor directives A problem arises when the same identifier is dec
448. n field has no effect on these field types The precision field is where you specify the maximum number of characters in the output value Excess characters are not output The optional characters 1 or L may immediately precede conversion type to respectively specify long versions ofthe integertypes d i u o x and x You must ensure that the argument type matches that of the format specification You can use type casts to ensure that the proper type is passed to sprintf sprintl Prototype void sprintl char wh const code char f pem The function returns the number of characters actually written to destination string The same as sprintf except it doesn t support float type numbers sprinti Prototype void sprinti char wh const code char f pum The function returns the number of characters actually written to destination string The same as sprintf except it doesn t support long integers and float type numbers mikoC PRO for PIC32 Library Example This is a demonstration of the standard C library sprintf routine usage Three different representations of the same floating poing number obtained by using the sprintf routine are sent via UART Copy Code To Clipboard double ww 1 2587538e41 char buffer 15 void main UART1 Init 4800 Initialize UART module at 4800 bps Delay ms 10 UART1 Write Text Floating point number representation Write message on UART sprintf
449. n global function declarations and function will assume the int type by default Function type can also be a pointer For example float means that a function result is a pointer to float The generic pointer void is also allowed The function cannot return an array or another function Within parentheses parameter declarator list is a list of formal arguments that function takes These declarators specify the type of each function parameter The compiler uses this information to check validity of function calls If the list is empty a function does not take any arguments Also if the list is void a function also does not take any arguments note that this is the only case when void can be used as an arguments type Unlike variable declaration each argument in the list needs its own type specifier and possible qualifier const or volatile MikroElektronika 230 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 The name of a parameter in function prototype has its scope limited to the prototype This allows one parameter identifier to have different name
450. n graphic layer S1D13700 Display GrLayer S1D13700 LAYER _ MikroElektronika 312 mikroC PRO for PIC32 S1D13700 Display TxtLayer Prototype void S1D13700 Display TxtLayer char mode Description Display selected text layer Parameters mode text layer mode Valid values Glcd module needs to be initialized See the S1D13700 Init routine Display on text layer S1D13700 Display TxtLayer S1D13700 LAYER ON S1D13700 Set Cursor Prototype void S1D13700 Set Cursor char width char height char mode Description Sets cursor properties Parameters width in pixels 1 must be less than or equal to the horizontal char size height in lines 1 must be less than or equal to the vertical char size mode cursor mode Valid values S1D13700 CURSOR UNDERSCORE Set cursor shape underscore S1D13700 CURSOR BLOCK Set cursor shape block Glcd module needs to be initialized See the S1D13700 Init routine set cursor with the following properties width 5px height 10px cursor shape block S1D13700 Set Cursor 5 10 S1D13700 CURSOR BLOCK 313 MikroElektronika mikoC PRO for PIC32 S1D13700 Display Cursor Prototype void S1D13700 Display Cursor char mode Description eem cursor Parameters mode mode parameter Valid values Gicd module needs to be initialized See the S1D13700_Init routine set cursor on 1D13700 Display Cursor S1D13700 CURSOR ON S1D137
451. n menu or by clicking the Jump To Interrupt Icon fu from the Watch Values Window Available Interrupts 0x0000 IVT_CORE_TIMER_VECTOR Ox0001 IVT_CORE_SOFTWARE_O_VECTOR 0x0002 IVT_CORE_SOFTWARE_1_VECTOR 0x0003 IVT EXTERNAL 0 VECTOR Ox0004 IVT TIMER 1 VECTOR 0x0005 IVT INPUT CAPTURE 1 VECTOR 0x0006 IVT OUTPUT COMPARE 1 VECTOR 0x0007 IVT_EXTERNAL_1_VECTOR 0x0008 IVT TIMER 2 VECTOR 0x0009 IVT INPUT CAPTURE 2 VECTOR Ox000A IVT OUTPUT COMPARE 2 VECTOR 0x000B IVT EXTERNAL 2 VECTOR OxODOC IVT TIMER 3 VECTOR 0x000D IVT INPUT CAPTURE 3 VECTOR OxQO0E IVT OUTPUT COMPARE 3 VECTOR OxOO0F IVT EXTERNAL 3 VECTOR 0x0010 IVT TIMER 4 VECTOR 0x0011 IVT INPUT CAPTURE 4 VECTOR 0x0012 IVT OUTPUT COMPARE 4 VECTOR 0x0013 IVT EXTERNAL 4 VECTOR 0x0014 IVT TIMER 5 VECTOR 0x0015 IT INPUT CAPTURE 5 VECTOR 0x0016 IVT OUTPUT COMPARE 5 VECTOR 0x0017 IVT SPI 1 VECTOR 0x0018 IVT LIART 1 VECTOR 0x0019 IVT I2C 1 VECTOR Ox0014 IVT CHANGE NOTICE VECTOR 0x001B IVT_ADC_VECTOR Ox001C IVT PMP VECTOR Ox001D IVT COMPARATOR 1 VECTOR OxOD1E IVT COMPARATOR 2 VECTOR OxOD1F IVT SPI 2 VECTOR 0x0020 IVT ART 2 VECTOR 0x0021 IVT I2C 2 VECTOR 0x0022 IVT FAIL SAFE MONITOR VECTOR 0x0023 IVT RTCC VECTOR nynn 4 WT DMA N VECTOR Conly used By checking the Only Used box you can display only the used breakpoints Mik
452. n of the Chip Enable pin sbit CF CEl1 direction at TRISD3 bit direction extern sfr sbit CF A22 1 i z i i i Direction of the Address 2 pin sbit CF A2 direction at TRISD2 bit direction EM extern sfr sbit CF Al A Direction of the Address 1 pin Sbit CF Al direction at TRISD1 bit direction puces extern sfr sbit CF A0 P n k i i i 3 Direction of the Address 0 pin sbit CF A0 direction at TRISDO bit direction SS MikroElektronika 288 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 internal use by compiler only Cf Issue ID Command 289 MikroElektronika mikoC PRO for PIC32 Cf Init eums Wm Requires Global variables CF Data Port Compact Flash data port DY Ready signal line E Write enable signal line E Output enable signal line D1 Chip detect signal line CE1 Enable signal line CF_A2 Address pin 2 CF A1
453. n 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 Column mode editing is sometimes referred to as block mode editing as the act of selecting text forms a rectangle To enter this mode press Alt Left mouse button drag the mouse towards the desired direction thus selecting the text Editor Colors Options E ditor Settings Editor Colors L4 Auto Correct Tools Output Current Scheme Scheme Setup Editor Colors Office 2003 Blue Delete w New Scheme HDEFINE PWM_ SEQUENCE ON Element Assembler Binary Character Comment Float Hexadecimal Identifier Illegal Char Number Octal Preprocessor Reserved Word Space String Symbol Web link Text Attributes F Bold Underline Foreground Lee Black E Italic Background v NENNEN Black F Strikeout E Active Line Color C Custom Kl V Show Active Line Gutter Colors Gradient From Gradient To CSS Sky Blue C whte Font R Blue E 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
454. n resistors configuration Each bit corresponds to the appropriate pin of the PortA register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Set Port Expander s PORTA pull up resistors Expander Set PullUpsPortA 0 OxFF MikroElektronika 392 mikroC PRO for PIC32 Expander Set PullUpsPortB Prototype void Expander Set PullUpsPortB char ModuleAddress char Data The function sets Port Expander s PortB pull up down resistors Parameters ModulecAddress 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 Port Expander must be initialized See Expander Init Set Port Expander s PORTB pull up resistors Expander Set PullUpsPortB 0 OxFF Expander Set PullUpsPortAB Prototype void Expander Set PullUpsPortAB char ModuleAddress unsigned int PullUps The function sets Port Expander s PortA and PortB pull up down resistors Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page PullUps data for choosing pull up down resistors configuration PortA pull up down resistors configuration is passed in Pul 1Ups s higher byte PortB pull up down resistors configuration is passed in PullUps s lower byte Each bi
455. n the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC24J600 module The ENC247600 module should be properly cofigured by the means of SPI Ethernet 24j600 Init routine multicast traffic will be enabled MULTICAST 5 0x20 CRC check flag When set packets with invalid CRC field SPI Ethernet 24j600 CRC will be discarded ar Es pe foul mue o 1 0x80 MAC Unicast traffic receive filter flag When set MAC SPI Ethernet 24 600 unicast traffic will be enabled UNICAST Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init SPI Ethernet 243600 Enable SPI Ethernet 24 600 CRC SPI Ethernet 243600 UNICAST enable CRC checking and Unicast traffic Parameters enF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 0x01 MAC Broadcast traffic receive filter flag When set MAC _SPI _Ethernet_24j600_ broadcast traffic will be enabled BROADCAST Advanced filtering available in the NC243600 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling rec
456. nd represents the member object m in s The expression ps gt m is a convenient shorthand for ps m For example struct mystruct int 1 char str 21 double d is sptr s Sp 33 assign to the i member of mystruct s sptr gt d 1 23 assign to the d member of mystruct s The expression s m is Ivalue providing that s is lvalue and mis not an array type The expression spt r gt mis an Ivalue unless m is an array type MikroElektronika 211 mikroC PRO for PIC32 Accessing Nested Structures If the structure B contains a field whose type is the structure A the members of 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 bos sptr s i 3 assign 3 to the i member of B S aa j 2 assign 2 to the j member of A sptr d 1 23 assign 1 23 to the d member of B sptr gt aa x 3 14 assign 3 14 to x member of A Structure Uniqueness Each structure declaration introduces a unique structure type so that in struct A int i j double d aa aaa struct B int i j double d bb the objects aa and aaa are both of the type struct A but the objects aa and bb are of different structure types Structures can be assigned only if the source and destination have the same type aa aaa OK same type member by member assignment aa bb ILLEGAL different types but you can ass
457. nd the last alternative contains everything from the last to the next pattern delimiter For this reason it s common practice to include alternatives in parentheses to minimize confusion about where they start and end Alternatives are tried from left to right so the first alternative found for which the entire expression matches is the one that is chosen This means that alternatives are not necessarily greedy For example when matching rou rout against routine only the rou part will match as that is the first alternative tried and it successfully matches the target string this might not seem important but it is important when you are capturing matched text using parentheses Also remember that is interpreted as a literal within square brackets so if you write bit bat bot you re really only matching biao Examples rou tine te matches strings routine or route Metacharacters Subexpressions The bracketing construct may also be used for define regular subexpressions Subexpressions are numbered based on the left to right order of their opening parenthesis The first subexpression has number 1 Examples int 8 10 matches strings which contain 8 9 or 10 instances of the int routi 0 9 a e matches routi0e routile routine routinne routinnne etc Metacharacters Backreferences Metacharacters 1 through 9 are interpreted as backreferences m
458. ne UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx_Init_ Advanced routines UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Read text until the sequence OK is received and send back what s been received UART1 Init 4800 initialize UART1 module Delay ms 100 while 1 if VARTI Data Ready 1 if data is received UART1 Read Text output OK 10 reads text until OK is found UART1 Write Text output sends back text MikroElektronika 596 mikroC PRO for PIC32 UART Set Active Prototype void UART Set Active unsigned read ptr void write ptr unsigned char data unsigned ready ptr unsigned tx idle ptr Description Sets active UART module which will be used by UARTx Data Ready UARTx Read and UARTx Write routines Parameters Parameters read ptr UARTx Read handler write ptr UARTx Write handler ready ptr UARTx Data Ready handler tx idle ptr UARTx Tx Idle handler Routine is available only for MCUs with multiple UART modules Requires Used UART module must be initialized before using this routine See UARTx Init and
459. ner x bottom right x coordinate of the lower right rectangle corner y bottom right y coordinate of the lower right rectangle corner round radius radius of the rounded edge TFT module needs to be initialized See the TFT Init routine TFT Rectangle Round Edges 20 20 219 107 12 TFT Circle Prototype void TFT Circle int x center int y center int radius Description Draws a circle on TFT Parameters x X coordinate of the circle center y y coordinate of the circle center r radius size TFT module needs to be initialized See the TFT Init routine PFA TFT Circle 120 64 110 TFT Image Prototype void TFT Image unsigned int left unsigned int top code const far unsigned short image unsigned short stretch Description Displays an image on a desired location Parameters left position of the image s left edge top position of the image s top edge image image to be displayed Bitmap array is located in code memory stretch stretches image by a given factor if 2 it will double the image TFT module needs to be initialized See the TFT Init routine Example TT maset 0 image D 0 1 019 MikroElektronika mikoC PRO for PIC32 TFT Partial Image Prototype void TFT Partial Image unsigned int left unsigned int top unsigned int width unsigned int height code const far unsigned short image unsigned rr L Retums Nothing eee Descript
460. ner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Rum E Example 16963C_box 0 119 239 127 T6963C WHITE Neue Neg OoOo RM T6963C circle Prototype void T6963C circle int x int y long r unsigned char pcolor Draws a circle on Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values TE963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C circle 120 64 110 T6963C WHITE MikroElektronika 546 mikroC PRO for PIC32 T6963C circle fill Prototype void T6963C circle fill int x int y long r unsigned char pcolor Draws a filled circle on Glcd Parameters x x coordinate of the circle center y y coordinate of the circle center r radius size color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C circle fill 120 64 110 T6963C WHITE T6963C image Prototype void T6963C image const code char pic Displays bitmap on Glcd Parameters pic 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 Toshiba Glcd module needs to be initialized See the T6963C init routine Example reese mese mrim
461. ng routine and it can block the program flow Call this routine from interrupt to unblock the program execution This mechanism is similar to WDT char datal error counter 0 void TimerlInt org IVT ADDR T1INTERRUPT if counter gt 20 Man Break counter 0 reset counter else counter increment counter TlIF bit 0 Clear Timerl overflow interrupt flag void main if Man Receive Init try Man Receive with blocking prevention mechanism IPOD IPCO 0x1000 Interrupt priority level 1 TLIE bit 1 Enable Timerl interrupts TICON 0x8030 Timerl ON internal clock FCY prescaler 2256 datal Man Receive amp error TIIE bit 0 Disable Timerl interrupts MEE Interrupts should be disabled before using Manchester routines again see note at the top of this page MikroElektronika 398 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 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
462. nicast traffic Advanced filtering available in the ENC243600 module such as Pattern Match Magic Packet and Hash Table can not be disabled by this routine This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC247600 module The E NC243600 module should be properly cofigured by the means of SPI Ethernet 24j600 Init routine MikroElektronika 412 mikroC PRO for PIC32 SPI Ethernet 24j600 doPacket Prototype unsigned int SPI Ethernet 243600 doPacket Description This is MAC module routine It processes next received packet if such exists Packets are processed in the following manner ARP amp ICMP requests are replied automatically upon TCP request the SPI Ethernet 24j600 UserTCP function is called for further processing upon UDP request the SPI Ethernet 24j600 UserUDP function is called for further processing Parameters None 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption ENC24J600 controller needs to be restarted 2 received packet was not sent to us not our IP nor IP broadcast address 3 received IP packet was not IPv4 4 received packet was of type unknown to the library Ethernet module has to be initialized See SPI Et
463. nika mikoC PRO for PIC32 S1D13700 Write Command Prototype void S1D13700 Write Command char command Description Writes a command to S1D13700 controller Parameters command command to be issued a31D13960 CS RIGHT Cursor moves right after write to display memory Miso ee DEB Cursor moves left after write to display memory Ginsgsgg Es ve Cursor moves up after write to display taii memory 63013200 CS DOWN Cursor moves down after write to display e memory Selects the gray ae in bits per pixel S1D13700 MEMWRITE Write to display memory S1D13700 MEMREAD Read from display memory Glcd module needs to be initialized See the S1D13700 Init routine Turn the display on S1D13700 Write Command S1D13700 DISP ON MikroElektronika 310 mikroC PRO for PIC32 S1D13700 Write Parameter Prototype void S1D13700 Write Parameter char parameter Description Writes a parameter to S1D13700 controller Parameters parameter parameter to be written Requires Glcd module needs to be initialized See the S1D13700 Init routine Previously a command must be sent through S1D13700 Write Command routine S1D13700 Write Command S1D13700 CSRW set cursor address S1D13700 Write Parameter Lo start send lower byte of cursor address S1D13700 Write Parameter Hi start send higher byte cursor address S1D13700 Read Parameter Remum Nothing SSCS Example parameter 51013700 Read P
464. nitialize the appropriate SPI module before using the SPI Lcd Library For MCUs with multiple SPI modules it is possible to initialize all of them and then switch by using the SPI Set Active routine See the SPI Library functions This Library is designed to work with the mikroElektronika s Serial Lcd Adapter Board pinout see schematic at the bottom of this page for details Library Dependency Tree r Port Expander SPI Lcd I 1 i Lcd Constants External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies Library Routines SPI Lcd Config SPI Lcd Out SPI Lcd Out Cp SPI Lcd Chr SPI Lcd Chr Cp SPI Lcd Cmd MikroElektronika 500 mikroC PRO for PIC32 SPI Lcd Config Requires Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections sbit SPExpanderRST at LATFO bit sbit SPExpanderCS at LATF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISF1 bit End Port Expander module connect
465. nitions for bypassing the normal function call and return discipline jmp buf is an array of unsigned int type suitable for holding information needed to restore a calling environment Type declaration is contained in the sejmp h header file which can be found in the include folder of the compiler Library Routines Setjmp Longjmp Setjmp Prototype int Setjmp jmp buf env This function saves calling position for a later use by Longjmp env buffer suitable for holding information needed for restoring calling environment 0 if the return is from direct invocation nonzero value if the return is from a call to Long jmp this value will be set by the Long jmp routine jmp buf buf Setjmp buf mikroC PRO for PIC32 Longjmp Prototype void Longjmp jmp buf env int val Description Restores calling environment saved in env buffer by the most recent invocation of Set jmp If there has been no such invocation or the function containing the invocation of Setjmp has terminated in the interim the behavior is undefined Parameters env buffer holding the information saved by the corresponding Set jmp invocation val value to be returned by the corresponding Set jmp function Invocation of Longjmp must occur before return from the function in which Set jmp was called encounters jmp buf buf Longjmp buf 2 Library Example This example demonstrates function cross calling using the Set jmp and Lon
466. nor appear as the first non whitespace character following include include macro identifier It assumes that macro definition that will expand macro identifier into a valid delimited header name with either header name Or header name formats exists MikroElektronika 260 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 If you need an actual argument the exact sequence of characters within quotes as a result of preprocessing use the operator in macro body It can be placed in front of a formal macro argument in definition in order to convert the actual argument to a string after replacement For example let s have macro LCD PRINT for printing variable name and value on Lcd define LCD PRINT val Lcd Out _Cp val p y Lcd Out Cp IntToStr val Now the following code LCD PRINT temp will be preprocessed to this Lcd Out Cp temp i Led Out Cp IntTostr temp Operator Operator is used for token pasting Two tokens can be pasted merged together by placing in between them plus optional whitespa
467. nowledge Base www mikroe com en kb you can find the answers to Frequently Asked Questions and solutions to known problems If you can not find the solution to your problem in Knowledge Base then report it to Support Desk www mikroe com en support In this way we can record and track down bugs more efficiently which is in our mutual interest We respond to every bug report and question in a suitable manner ever improving our technical support How to Register Thelatest version of the mikroC PRO for PIC32 is always available for downloading from our website It is a fully functional software with the mikrolCD in circuit Debugger all the libraries examples and comprehensive help included The only limitation of the free version is that it cannot generate hex output over 2K of program words Although it might sound restrictive this margin allows you to develop practical working applications with no thinking of demo limit If you intend to develop really complex projects in the mikroC PRO for PIC32 then you should consider the possibility of purchasing the license key Who Gets the License Key Buyers of the mikroC PRO for PIC32 are entitled to the license key After you have completed the payment procedure you have an option of registering your mikroC PRO for PIC32 In this way you can generate hex output without any limitations How to Get License Key After you have completed the payment procedure start the program Select Help How to
468. nput parameter x must be between 1 and 1 inclusive The return value is in radians between 0 and M inclusive Example doub acos 0 5 doub 1 047198 MikroElektronika 610 mikroC PRO for PIC32 asin Prototype double asin double x Description Function returns the arc sine of parameter x that is the value whose sine is x The input parameter x must be between 1 and 1 inclusive The return value is in radians between 1 2 and TT2 inclusive Example doub asin 0 5 doub 5 235987e 1 atan Prototype double atan double f Description Function computes the arc tangent of parameter that is the value whose tangent is The return value is in radians between 1 2 and 1 2 inclusive doub atan 1 0 doub 7 853982e 1 atan2 Prototype double atan2 double y double x Description This is the two argument arc tangent function It is similar to computing the arc tangent of y x except that the signs of both arguments are used to determine the quadrant of the result and x is permitted to be zero The return value is in radians between M and 1 inclusive Example doub atan2 2 doub 4 636475e 1 ceil Prototype double ceil double x Function returns value of Missas x rounded up to the next whole number Example doub ceil 0 5 doub 1 000000 COS Prototype double cos double f Function returns the cosine of f in ra
469. ns except by RAM size A Nested call represents a function call within the function body either to itself recursive calls or to another function Recursive calls as a form of cross calling are supported by mikroC PRO for PIC32 but they should be used very carefully Also calling functions from interrupt is allowed Calling function from both interrupt and main thread is allowed Be careful because this programming technique may cause unpredictable results if common resources are used in both main and interrupt Variable constant and routine alignment Simple type variables whose size exceeds 2 byte int long float double long double and those exceeding 4 bytes are always set to alignment 4 Routines are always set to aligment 4 Boot Start up Initialization Upon reset MCU positions at the address OXBFCO00000 on which the Boot StartUp function is located BootStartUp function configures CPO coprocessor registers SFR registers associated with the interrupt Stack pointer R29 and global pointer R1 By default the MCU is configured as follows Cache Enabled Prefetch enabled for executable code and constants Flash waitstates set for specified oscillator frequency Executable code allocated in the KSEGO Data allocated in the KSEG1 After this start up function has been executed MCU will jump into the main routine Interupts will be set accordingly to the settings in the Edit Project 163 Mikr
470. nsResolve 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 tmax time in seconds to wait for an reply pointer to the location holding the IP address the requested host name was resolved 0 otherwise Ethernet module has to be initialized See SPI Ethernet 24j600 Init The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time User should always copy the IP address from the RAM location returned by this routine into it s own resolved host IP address buffer These locations should not be altered by the user in any case unsigned char remoteHostIpAddr 4 user host IP address buffer SNTP server Zurich Switzerland Integrated Systems Lab Swiss Fed Inst of Technology 129 132 2 21 swisstime ethz ch Service Area Switzerland and Europe memcpy remoteHostIpAddr SPI Ethernet 247600 dnsResolve swisstime ethz en D Ale 481 MikroElektronika mikoC PRO for PIC32 SPI Ethernet 24j600 initDHCP Prototype unsigned int SPI Ethernet 243600 initDHCP unsigned char tmax
471. nsecutive sectors that user wants the swap file to have filename name ofthe file that should be assigned for file operations File name should be in DOS 8 3 flle name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension i e MIKROELETXT gt MIKROELE TXT In this case last 3 characters of the string are considered to be file extension file attr file creation and attributes flags Each bit corresponds to the appropriate file attribute Pei wask Description o foo Resow Ls oxo pesce tema use ony never found ond Number of the start sector for the newly created swap file if there was enough free space on the MMC SD card to create file of required size 0 otherwise 371 MikroElektronika mikoC PRO for PIC32 MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init Tries to create a swap file whose size will
472. nsigned int port unsigned int pin Issues OneWire reset signal for DS18x20 Parameters port OneWire bus port pin OneWire bus pin 0 if the device is present 1 if the device is not present Requires Devices compliant with the Dallas OneWire protocol Issue Reset v on One Wire Bus connected to pin RF6 Ow Reset amp PORTF 6 mass pe SSS 383 MikroElektronika mikoC PRO for PIC32 Ow Read Prototype unsigned short Ow Read unsigned int port unsigned int pin 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 Devices compliant with the Dallas OneWire protocol Read a byte from the One Wire Bus connected to pin RF6 unsigned short read data read data Ow Read amp PORTF Ow Write GRO pe void Ow Write unsigned int port unsigned int pin unsigned short data Writes one byte of data via the OneWire bus Parameters port OneWire bus port pin OneWire bus pin data data to be written Devices compliant with the Dallas OneWire protocol Send a byte to the One Wire Bus connected to pin RF6 Ow Write amp PORTF 6 OxCC MikroElektronika 384 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
473. nsigned long T6963C cntlPort at PORTE CTRL port sbit T6963C ctrlwr at LATE2 bit WR write signal sbit T6963C ctrlrd at LATE bit RD read signal sbit T6963C ctrlcd at LATEO bit CD command data signal sbit T6963C ctrlrst at LATE4 bit RST reset signal sbit T6963C ctrlwr Direction at TRISE2 bit WR write signal sbit T6963C ctrlrd Direction at TRISE1 bit RD read signal sbit T6963C ctrlcd Direction at TRISEO bit CD command data signal sbit T6963C ctrlrst Direction at TRISE4 bit RST reset signal Signals not used by library they are set in main function sbit T6963C ctrlce at LATE3 bit CE signal sbit T6963C ctrlfs at LATE6 bit FS signal sbit T6963C ctrlmd at LATES bit MD signal sbit T6963C ctrlce Direction at TRISE3 bit CE signal direction sbit T6963C ctrlfs Direction at TRISE6 bit FS signal direction sbit T6963C ctrlmd Direction at TRISE5 bit MD signal direction End T6963C module connections y bitmap pictures stored in ROM Le const code char mikroE 240x128 bmp const code char einstein MikroElektronika 554 mikroC PRO for PIC32 void main fdefine COMPLETE EXAMPLE fdefine LINE DEMO Uncomment to demonstrate line drawing routines fdefine FILL DEMO Uncomment to demonstrate fill routines define PARTIAL IMAGE DEMO Uncomment to demonstrate partial image routine char txtl
474. nt width unsigned char height Description Initializes S1D13700 Graphic Lcd controller Parameters width width of the Glcd panel height height of the Glcd panel Requires Global variables 1D13700 Data Port Data Bus Port 51D13700 WR Write signal pin 51D13700 RD Read signal pin 51D13700 A0 Command Data signal pin 51D13700 RES Reset signal pin 51D13700 CS Chip Select signal pin 1D13700 Data Port Direction Data Bus Port Direction 51D13700 WR Direction Direction of Write signal pin 1D13700 RD Direction Direction of Read signal pin 51D13700 A0 Direction Direction of Command Data signal pin 81D13700 RES Direction Direction of Reset signal pin 81D13700 CS Direction Direction of Chip Select signal pin must be defined before using this function S1D13700 module connections char S1D13700 Data Port at PORTD sbit S1D13700 WR at LATC2 Dit sbit S1D13700 RD at LATC1 bit sbit S1D13700 AO at LATCO bit sbit S1D13700 RES at LATC4 bit sbit 51D13700 CS at LATC5 bit char S1D13700 Data Port Direction at TRISD sbit S1D13700 WR Direction at TRISC2 bit sbit S1D13700 RD Direction at TRISC1 bit sbit S1D13700 AO Direction at TRISCO bit sbit S1D13700 RES Direction at TRISC4 bit sbit 1D13700 CS Direction at TRISC5 bit End of S1D13700 module connections init display for 320 pixel width 240 pixel height S1D13700 Init 320 240 309 MikroElektro
475. nts in creating more complex derived or user defined types The fundamental types include Arithmetic Types Enumerations Void Type Arithmetic Types The arithmetic type specifiers are built up from the following keywords void char int float and double together with the prefixes short long signed and unsigned From these keywords you can build both integral and floating point types Integral Types The types char and int together with their variants are considered to be integral data types Variants are created by using one of the prefix modifiers short long signed and unsigned In the table below is an overview of the integral types keywords in parentheses can be and often are omitted The modifiers signed and unsigned can be applied to both char and int Inthe absence of the unsigned prefix signed is automatically assumed for integral types The only exception is char which is unsigned by default The keywords signed and unsigned when used on their own mean signed int andunsigned int respectively The modifiers short and long can only be applied to int The keywords short and long used on their own mean short int and long int respectively unsigned short int signed long int 2147483648 2147483647 signed long long 92233720368547 75808 9223372036854775807 8 0 18446744073709551615 197 MikroElektronika unsigned long long mikoC PRO for PIC32 Floating point
476. nts option sets new breakpoints or removes those a already set at the current cursor position Step Over Related topics Run Menu Debug Toolbar MikroElektronika 134 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 This allows using const objects in places where ANSI C expects a constant expression If aiming at portability use the traditional preprocessor defined constants See Type Qualifiers and Constants The mikroC PRO for PIC32 allows C style single line comments using two adjacent slashes The comment can start at any position and extends until the next new line See Comments A number of standard C libraries ctype math stdlib string have been implemented check the
477. o Correct for common typos and Code Templates Auto Complete The Code Explorer is at your disposal for easier project management The Project Manager alows multiple project management General project settings can be made in the Project Settings window Library manager enables simple handling libraries being used in a project The Messages Window displays all messages during compiling and linking The source level Software Simulator lets you debug executable logic step by step by watching the program flow The New Project Wizard is a fast reliable and easy way to create a project Help files are syntax and context sensitive Like in any modern Windows application you may customize the layout of mikroC PRO for PIC32 to suit your needs best Spell checker underlines identifiers which are unknown to the project In this way it helps the programmer to spot potential problems early much before the project is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F12 51 MikroElektronika 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 Editor Settin
478. o be initialized See the S1D13700 Init routine S1D13700 Line 0 0 239 127 S1D13700 WHITE S1D13700 H Line Prototype void S1D13700 H Line unsigned int x start unsigned int x end unsigned int y pos unsigned short color Description Draws a horizontal line Parameters x start x coordinate of the line start x end x coordinate of the line end y pos line position on the y axis pcolor color parameter Valid values S1D13700 BLACK Black color S1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Line 0 0 239 127 S1D13700 WHITE MikroElektronika 316 mikroC PRO for PIC32 S1D13700 V Line Prototype void S1D13700 V Line unsigned int y start unsigned int y end unsigned int X pos unsigned short color 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 S1D13700 BLACK Black color 1D13700 WHITE White color Glcd module needs to be initialized See the S1D13700 Init routine S1D13700 Line 0 0 239 127 S1D13700 WHITE S1D13700 Rectangle Prototype void S1D13700 Rectangle unsigned int x0 unsigned int y0 unsigned int x1 unsigned int yl unsigned char pcolor Description Draws a rectangle on Glcd Parameters x0 x coordinate of the upper l
479. o the appropriate file attribute Pat wask Description o foo Resow Ls oxo Davie tema use ony never found ona File creation flag If file does not exist and this flag is set a new file with specified name will be created 1 if file already exists or file does not exist but a new file is created 0 if file does not exist and no new file is created MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init create file with archive attribute if it does not already exist Mme Fat Assign MIKRO007 TXT 0xA0 Notes Long File Names LFN are not supported 371 MikroElektronika mikoC PRO for PIC32 Mmc Fat Reset iiia as void Mmc Fat Reset unsigned long size 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 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 unsigned long size Mmc Fat Reset size Mmc_Fat_Read Prototype void Mmc Fat Read unsigned short bdata Description Reads a byte from the currently assigned file opened for reading Upon function execution file pointers will be set to the next character in the file bd
480. oElektronika 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 Key features of PIC32MX memory organization include the following 32 bit native data width Separate User and Kernel mode address spaces Flexible program Flash memory partitioning Flexible data RAM partitioning for data and program space Separate boot Flash memory for protected code Robust bus exception handling to intercept runaway code Simple memory mapping with Fixed Mapping Translation FMT unit Cacheable and non cacheable address regions MikroElektronika 164 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
481. ocal variables into the RX space instead onto the frame To do that SSA has to make an alias and data flow analysis of the Control Flow Graph Besides these savings there are a number of compiler optimization algorithms enhanced by the use of SSA like Constant Propagation Dead Code Elimination Global Value Numbering Register Allocation Changes that SSA brings is also in the way in which routine parameters are passed When the SSA is enabled parameters are passed through a part of the RX space which is reserved exclusively for this purpose Allocating local variables and parameters in RX space has its true meaning for those architectures with hardware frame Lets consider a trivial case void SSA Test int y int k LE YFK asm nop void main SSA Test 5 5 With SSA enabled this example is consisted of 3 asm instructions Example c 25 2 LE qv 0x9D000000 0x033A1021 ADDU R2 R25 R26 0x9D000004 0x10400002 BEQ R2 R0 L SSA Testo 0x9D000008 0x70000000 NOP L SSA Test3 159 MikroElektronika mikoC PRO for PIC32 Without SSA enabled this example is consisted of 5 asm instructions Example c 25 0x9D000000 0x87A30002 0x9D000004 0x87A20000 0x9D000008 0x00431021 Ox9D00000C 0x10400002 0x9D000010 0x70000000 Lh SSA Test3 D if ytk H R3 2 SP H R2 O SP DDU R2 R2 R3 EQ R2 RO L SSA TestO OP Proper Coding Recommendations To get the maximum out of th
482. ode switching verification request If WAIT 0 the call is non blocking The function does not verify if the CANSPI module is switched to requested mode or not Caller must use CANSPIGetOperationMode to verify correct operation mode before performing mode specific operation If WATT 0 the call is blocking the function won t return until the requested mode is set 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 See connection example at the bottom of this page set the CANSPI module into configuration mode wait inside CANSPISetOperationMode until this mode is set CANSPISetOperationMode CANSPI MODE CONFIG OxFF MikroElektronika 212 mikroC PRO for PIC32 CANSPIGetOperationMode constants or device datasheet for operation mode codes 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 See connection example at the bottom of this page check whether the CANSPI module is in Normal mode and if it is do something if CANSPIGetOperationMode CANSPI MODE NORMAL CANSPIInitialize Prototype void CANSPIInitialize char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CANSPI CONFIG FLAGS Description Initializes the CANSPI module
483. of IPC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 340 mikroC PRO for PIC32 I2Cx Read Prototype unsigned char I2Cx Read unsigned ack Reads a byte from the lC 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 Retums 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 See I2Cx Start unsigned char take Read data and send the not acknowledge signal take I2C1 Read 1 u PC library routines require you to specify the module you want to use To select the desired C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx Write Per EEE eea 0000000 1 if write collision was detected on the I C bus Requires MCU with at least one lC module Used I C module must be initialized before using this function See I2Cx Init routine Also START signal needs to be issued in order to use this function See I2Cx Start unsigned char data unsigned error error I2Cl Write data er
484. oject Name C14 Development SystemslLV32Mx v lL CD COG 2x16 lLcd mda Time 1 31 2011 1 03 40 PM vesemieon com mikoC PRO for PIC32 Functions Sorted By Addresses Sorts and displays functions by their addresses in the ascending order 1 800 000 000 1 500000 000 Double cick on diagram to open it in a new window Project Name C 1 Development Systemsil VIZMK v l CD COG 2x16 lLcd mepiz Mee mieos com Function Tree Displays Function Tree with the relevant data for each function Project Name C Development Systems VIM v l CD COG 2x16 lcd med Time 1731 2011 1 03 40 PM ero mtbr com MikroElektronika 10 mikroC PRO for PIC32 Memory Summary Displays summary of RAM and ROM memory in a pie like form n MikroElektronika 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 The Messages Window will display errros at the bottom of the window by default The compiler also reports warnings but these do not affect the output only er
485. om sector 590 Cf Read Init 590 1 Nos Nm S Cf Read Byte Prototype Description Reads one byte from i Compad Flash sector buffer location currently pointed to by internal read pointers These pointers will be autoicremented upon reading Returns Returns a byte read from Compact Flash sector buffer Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init CF card must be initialized for reading operation See Cf Read Init Read a byte from compact flash unsigned char data data Cf Read Byt Notes Higher byte of the unsigned return value is cleared Cf Write Init iiia void Cf Write Init unsigned long address unsigned short sectcnt Initializes CF card for writing Parameters address the first sector to be prepared for writing operation sectcnt number of sectors to be prepared for writing operation The corresponding MCU ports must be appropriately initialized for CF card See Cf Init initialize compact flash for writing to sector 590 Cr Write Init 590 1 MikroElektronika 292 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 secto
486. omment Editor Active Comments Editor Enter comment name lt activeComment gt activeComment Attributes Url snnr mikroe comc Url lt Image gt lt Image gt lt File gt lt File gt Properties lt Attributes gt Active Comment Actions New Rename Attributes lt Events gt Url www mikroe com lt OnLeftClick gt lt OnLeftClick gt Image lt OnRightClick gt lt OnRightClick gt File lt OnDb1LClick gt lt OnDb1Click gt I Events lt OnMouseOver gt lt OnMouseOver gt OnLeftClick Alt lt Events gt OnRightClick SNL OnDblClick activeCommen OnMouseOver Add Image To Project Add File To Project 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 Add Image To Project Or Add File To Project button 99 MikroElektronika mikoC PRO for PIC32 Next file dialog will be opened Look in Images B My Recent Documents 2 Desktop My Documents My Computer File name Easy GSM GPRS Files of type Image Files bmp ipg png Cancel C Open as read only My Network There you should select the desired image to be added In our example Easy GSM GPRS jpg image will be added Selected picture is automatically added to the drop down list of the Image field in Active Comment Editor Acti
487. ompatible only to the extent that an assignment can legally convert them The user can always use an explicit cast to convert an argument to a type that is acceptable to a function prototype Note If the function prototype does not match the actual function definition the mikroC PRO for PIC32 will detect this if and only if that definition is in the same compilation unit as the prototype If you create a library of routines with the corresponding header file of prototypes consider including that header file when you compile the library so that any discrepancies between the prototypes and actual definitions will be detected The compiler is also able to force arguments to change their type to a proper one Consider the following code int limit 32 char ch A long res prototype extern long func long parl long par2 main res fune limit ch function call Since the program has the function prototype for func it converts limit and ch to long using the standard rules of assignment before it places them on the stack for the call to func Without the function prototype 1 imit and ch would be placed on the stack as an integer and a character respectively in that case the stack passed to func will not match size or content that func expects which can cause problems 233 MikroElektronika mikoC PRO for PIC32 Ellipsis Operator The ellipsis consists of three successive periods w
488. on of Read signal pin l CS Direction Direction of Chip Select signal pin RS Direction Direction of Register Select signal pin RST Direction Direction of Reset signal pin must be defined before using this function TFT display connections char TFT DataPort at LATE sbit TFT WR at LATD13 bit sbit TFT RD at LATD12 bit sbit TFT CS at LATC3 bit sbit TFT RS at LATB15 bit Sbit TFT RST at LATC1 bit char TFT DataPort Direction at TRISE Sbit TFT WR Direction at TRISDI3 bit sbit TFT RD Direction at TRISD12 bit sbit l CS Direction at TRISC3 bit sbit TFT RS Direction at TRISB15 bit sbit RST Direction at TRISC1 bit End of TFT display connections Initialize 240x320 TFT display TET InTt 240 320 563 MikroElektronika mikoC PRO for PIC32 TFT Set Index Prototype void TFT Set Index unsigned short index Description Accesses register space of the controller and sets the desired register Parameters index desired register number TFT module needs to be initialized See the TFT Init routine Access register at the location 0x02 TFT Set Index 0x02 TFT Write Command Prototype void TFT Write Command unsigned short cmd Description Accesses data space and writes a command Parameters cmd command to be written TFT module needs to be initialized See the TFT Init routine Write a command TFT Write Command 0x02 TFT Write
489. on string Parameters wh destination string format string The argument is a format string and may be composed of characters escape sequences and format specifications Ordinary characters and escape sequences are copied to the destination string in the order in which they are interpreted Format specifications always begin with a percent sign and require additional arguments to be included in the function call The format string is read from left to right The first format specification encountered refers to the first argument after and then converts and outputs it using the format specification The second format specification accesses the second argument after and so on If there are more arguments than format specifications then these extra arguments are ignored Results are unpredictable if there are not enough arguments for the format specifications The format specifications have the following format flags width precision ff i b Jj econverszon type Each field in the format specification can be a single character or a number which specifies a particular format option The conversion type field is where a single character specifies that the argument is interpreted as a character string number or pointer as shown in the following table 649 MikroElektronika mikoC PRO for PIC32 uns unsigned int unsigned int Unsigned octal number Ee Ant Unsigned hexadecimal number using 01234567
490. oop Read time from RTC PCF8583 Format date and time Prepare and display on LCD Wait 1 second seconds months hours year day month Print tens digit of day variable Print oness digit of day variable Print year vaiable 1 start from year 2011 MikroElektronika 420 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 Data transmitted at low to high edge The library configures SPI to the master mode clock 20kHz data sampled at the middle of interval clock idle state low and data transmitted at low to high edge Important The Software SPI library implements time based activities so interrupts need to be disabled when using it External dependencies of Software SPI Library The following variables must be defined in all projects using Software SPI Description Library extern sfr sbit SoftSpi SDI Data In line sbit SoftSpi SDI at RF4 bit extern sfr sbit SoftSpi SDO Data Out line sbit SoftSpi SDO at LATF3 bit extern
491. oordinate 10 12 Original image size is 16x32 SPI Gled PartiallImage 10 12 10 15 16 32 image Use the mikroC PRO for PIC32 integrated Glcd Bitmap Editor Tools gt Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd MikroElektronika 496 mikroC PRO for PIC32 Library Example The example demonstrates how to communicate to KS0108 Glcd via the SPI module using serial to parallel convertor MCP23S17 Copy Code To Clipboard const code char truck bmp 1024 Port Expander module connections sbit SPExpanderRST at LATD8 bit sbit SPExpanderCS at LATD9 bit sbit SPExpanderRST Direction at TRISD8 bit sbit SPExpanderCS Direction at TRISD9 bit End Port Expander module connections void Delay2s 2 seconds delay function Delay ms 2000 void main char counter char someText CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE SPI Glcd Init 0 Initialize Glcd via SPI SPI Glcd Fill 0x00 Clear Glod while 1 SPI Glcd Image truck bmp Draw image Delay2s Delay2s SPI Glcd fill 0x00 Clear GLCD SPI Glcd Partiallmage 0 0 68 30 128 64 truck bmp
492. or Draws a rounded edge 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 round radius radius of the rounded edge pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C rectangle round edges 20 20 219 107 X12 SPI T6963C WHITE SPI T6963C rectangle round edges fill Prototype void SPI T6963C rectangle round edges os x0 int yO int xl int yl int round radius unsigned char pcolor Draws a filled rounded edge 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 round radius radius of the rounded edge JEU color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C rectangle round edges fil 20 20 219 107 12 SPI T6963C WHITE 521 MikroElektronika mikoC PRO for PIC32 SPI T6963C box Prototype void SPI T6963C box int x0 int y0 int xl int yl unsigned char pcolor Draws a box on the Glcd
493. or Graphic Lcd Bitmap Editor HID Terminal Interrupt Assistant Lcd Custom Character Seven Segment Editor UDP Terminal USART Terminal Active Comments New Active Comment Renaming Active Comment Deleting Active Comment Export Project Jump To Interrupt Regular Expressions Introduction Simple matches Escape sequences Character classes Metacharacters Metacharacters Line separators Metacharacters Predefined classes Metacharacters Word boundaries Metacharacters Iterators Metacharacters Alternatives Metacharacters Subexpressions 110 MikroElektronika mikroC PRO for PIC32 Metacharacters Backreferences 110 Keyboard Shortcuts 111 CHAPTER 3 113 mikroC PRO for PIC32 Command Line Options 113 CHAPTER 4 115 mikrolCD In Circuit Debugger 115 Introduction 115 mikrolCD Debugger Options 117 Debugger Options 117 mikrolCD Debugger Example 118 mikrolCD Debugger Windows 122 Debug Windows 122 Breakpoints Window 122 Watch Values Window 122 RAM Window 124 Stopwatch Window 124 EEPROM Watch Window 125 Code Watch Window 126 CHAPTER 5 127 Software Simulator Overview 127 Software Simulator 128 Software Simulator Debug Windows 129 Debug Windows 129 Breakpoints Window 129 Watch Values Window 129 RAM Window 131 Stopwatch Window 131 EEPROM Watch Window 132 Code Watch Window 133 Software Simulator Debugger Options 134 Debugger Options 134 CHAPTER 6 135 mikroC PRO for PIC32 Specifics 135 ANSI St
494. or High Risk Activities GENERAL PROVISIONS This statement may only be modified in writing signed by you and an authorised officer of mikroElektronika Associates If any provision of this statement is found void or unenforceable the remainder will remain valid and enforceable according to its terms If any remedy provided is determined to have failed for its essential purpose all limitations of liability and exclusions of damages set forth in the Limited Warranty shall remain in effect This statement gives you specific legal rights you may have others which vary from country to country mikroElektronika Associates reserves all rights not specifically granted in this statement mikroElektronika Visegradska 1A 11000 Belgrade Europe Phone 381 11 36 28 830 Fax 381 11 36 28 831 Web www mikroe com E mail office mikroe com 33 MikroElektronika 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 Your comments and suggestions on future development of the mikroC PRO for PIC32 are always appreciated feel free to drop a note or two on our Wishlist In our K
495. ork with the module 261 MikroElektronika mikoC PRO for PIC32 Library Routines ADCx Init ADCx Init Advanced ADCx Get Sample ADCx Read ADCx Init Prototype 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 ums Nothing Example sximit initialize ADC nodule with defawit settings Its None OSS ADOx Init Advanced Prototype void ADC1 Init Advanced unsigned Reference This routine configures the internal ADC module to work with user defined settings Parameters Reference voltage reference used in ADC process The MCU with built in ADC module Example ADC1_ Init Advanced ADC INTERNAL RE set internal reference used Not all MCUs support advanced configuration Please read the appropriate datasheet before utilizing this library MikroElektronika 268 mikroC PRO for PIC32 ADCx Get Sample PRetums 10bit unsigned value from tne spected channcl OOS Requires 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 Before using the function be sure to configur
496. ormat mikroE Reinitialize the SPI module at higher speed change primary prescaler SPI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI PRESCALE PRI 4 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIVE 2 IDLE MikroElektronika 310 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 ofthe file that should be assigned for file operations File name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension i e MIKROELETXT gt MIKROELE TXT In this case last 3 characters of the string are considered to be file extension file cre attr file creation and attributes flags Each bit corresponds t
497. ote Mmc Fat Init tries to initialize a card more than once If card is not present initialization may last longer depending on clock speed HW Connection SPLMISO SPISCK Pin diagram of MMC memory card MikroElektronika 382 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 Some basic characteristics of this protocol are single master system low cost low transfer rates up to 16 kbps fairly long distances up to 300 meters small data transfer packages Each OneWire device also has a unique 64 bit registration number 8 bit device type 48 bit serial number and 8 bit CRC so multiple slaves can co exist on the same bus Important Oscillator frequency Fosc needs to be at least 4MHz in order to use the routines with Dallas digital thermometers This library implements time based activities so interrupts need to be disabled when using OneWire library Library Routines Ow Reset Ow Read Ow Write Ow Reset isis unsigned int Ow Reset u
498. otype void SPI Glcd Fill char pattern Description Fills Glcd memory with byte pattern To clear the Glcd screen use SPI Gicd Fill 0 To fill the screen completely use SPI Gicd Fill OxFF byte to fill Glcd memory with Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Clear screen SPI Glcd Fill 0 SPI Glcd Dot Prototype void SPI Glcd Dot char x pos char y pos char color Draws a dot on Glcd at coordinates x pos y pos Parameters x pos x position Valid values 0 127 y pos y position Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the dot state 0 clears dot 1 puts a dot and 2 inverts dot state Glcd needs to be initialized for SPI communication see SPI Glcd Init routine Invert the dot in the upper left corner SPI Glcd Dot 0 0 2 Notes For x and y axis layout explanation see schematic at the bottom of this page MikroElektronika 488 mikroC PRO for PIC32 SPI Glcd Line Prototype void SPI Glcd Line int x start int y start int x end int y end char color Description Draws a line on Glcd Parameters Parameters x start x coordinate of the line start Valid values 0 127 y start y coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color color param
499. ou the right to use Software in a way provided below This Software is owned by mikroElektronika Associates and is protected by copyright law and international copyright treaty Therefore you must treat this Software like any other copyright material e g a book You may transfer Software and documentation on a permanent basis provided You retain no copies and the recipient agrees to the terms of the License Agreement Except as provided in the License Agreement you may not transfer rent lease lend copy modify translate sublicense time share or electronically transmit or receive Software media or documentation You acknowledge that Software in the source code form remains a confidential trade secret of mikroElektronika Associates and therefore you agree not to modify Software or attempt to reverse engineer decompile or disassemble it except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation If you have purchased an upgrade version of Software it constitutes a single product with the mikroElektronika Associates software that you upgraded You may use the upgrade version of Software only in accordance with the License Agreement LIMITED WARRANTY Respectfully excepting the Redistributables which are provided as is without warranty of any kind mikroElektronika Associates warrants that Software once updated and properly used will perform substantially in accordance
500. ou can change chip and oscillator frequency Any change in the Project Setting Window affects currently active project only so in case more than one project is open you have to ensure that exactly the desired project is set as active one in the Project Manager Also you can change configuration bits of the selected chip in the Edit Project window Managing Project Group mikroC PRO for PIC32 IDE provides convenient option which enables several projects to be open simultaneously If you have several projects being connected in some way you can create a project group The project group may be saved by clicking the Save Project Group Icon D from the Project Manager window The project group may be reopened by clicking the Open Project Group Icon 8 All relevant data about the project group is stored in the project group file extension mcdsgroup Vs Add Remove Files from Project The project can contain the following file types c source files h header files mc1 binary files pid project level defines files image files ihex EEPROM files hex asmand 1st files see output files These files can not be added or removed from project other files Project Manager 1 1 ARS RS S ES ee ct et o Es ag C Sources E T6963C 240x128 c einstein_bmp c mikroe bmp c 2 Header Files T6963C h 24 Binaries T6963C_240x128 mel E Project level defines 1 Image Files mikroE_240x128 bmp S EEPROM F
501. outine name only pragma funcorg func name starting address gt Related topics Indirect Function Calls Indirect Function Calls If the linker encounters an indirect function call by a pointer to function it assumes that any of the functions addresses of which were taken anywhere in the program can be called at that point Use the pragma funcal1 directive to instruct the linker which functions can be called indirectly from the current function pragma funcall func name called func called func A corresponding pragma must be placed in the source module where the function unc name is implemented This module must also include declarations of all functions listed in the called func list These functions will be linked if the function Func name is called in the code no matter whether any of them was called or not MikroElektronika 116 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 n header file located in the inlclude folder of the compiler into your project The Delay us and Delay ms routines are implemented as inline i e cod
502. p amp keydata 13 f Enter UART1 Write Nr send carriage return to usart terminal UART1 Write in uncomment this line if usart terminal also expects line feed for new line transition else if down amp amp special amp amp keydata UART1 Write keydata Send key to usart terminal Delay ms 1 Debounce period while 1 399 MikroElektronika mikoC PRO for PIC32 HW Connection PS2 CONNECTOR D y c vcc3 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 Library Routines PWM_Init PWM Init Advanced PWM Set Duty PWM Start PWM Stop MikroElektronika 400 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 Initializes the PWM module with duty ratio O 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 Valid values 1 8 64 and 256 use timer x timerto be used with the PWM module Vali
503. packet size is set to 1518 Back to Back Inter Packet Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 0x0012 in full duplex mode 0x0C12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC24 600 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half duplex loopback disabled LED configuration default LEDA link status LEDB link activity mac RAM buffer containing valid MAC address ip RAM buffer containing valid IP address configuration ethernet negotiation duplex and speed mode settings For this purpose predefined library constants see the list below can be combined using logical AND to form appropriate value Ethernet 24j TO NEGOTIATION ote It is advisable to use only the Auto negotiation setting If manual negotiation is used then duplex and Speed mode setting must be set also Duplex and speed mode may be set only when using manual negotiation 469 MikroElektronika mikoC PRO for PIC32 Requires Global variables SPI Ethernet 247600 CS Chip Select line SPI Ethernet 243600 CS Direction Direction of the Chip Select pin must be defined before using this function The SPI module needs to be initialized See the SPIx Init and SPIx Init Advanced routines include EthEnc24J600 h mE ethernet NIC pinout sfr sbit SPI Ethernet
504. pe Enumeration tags share the same name space as structure and union tags Enumerators share the same name space as ordinary variable identifiers int blue 73 open a block enum colors black red green blue violet white c enumerator blue 3 now hides outer declaration of int blue struct colors int i 37 Jg ILLEGAL colors duplicate tag double red 2 ILLEGAL redefinition of red blue 37 back in int blue scope 199 MikroElektronika 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 Led Chr Cp C Use void as a function heading if the function does not take any parameters Alternatively you can just write empty parentheses main void same as main Generic Pointers Pointers can be declared as void which means that they can point to any type These pointers are sometimes called generic Derived Types The derived types are also known as structured types They are used as elements in creating more complex user defined types The derived types include arrays pointers structures unions Mikro
505. pending the interrupt with the highest subpriority will be handled first The user selectable subpriority levels range from 0 the lowest subpriority to 3 the highest Interrupts and Register Sets The PIC32MX family of devices employs two register sets a primary register set for normal program execution and a shadow register set for highest priority interrupt processing Register Set Selection in Single Vector Mode In Single Vector mode you can select which register set will be used By default the interrupt controller will instruct the CPU to use the first register set This can be changed later in the code Interrupts and Register Sets When a priority level interrupt matches a shadow set priority the interrupt controller instructs the CPU to use the shadow set For all other interrupt priorities the interrupt controller instructs the CPU to use the primary register set Interrupt Coding Requirements In order to correctly utilize interrupts and correctly write the ISR code the user will need to take care of these things 1 Write the Interrupt Service Routine You may use Interrupt Assistant to easily write this routine 2 Initialize the module which will generate an interrupt 3 Set the correct priority and subpriority for the used module according to the priorities set in the Interrupt Service Routine 4 Enable Interrupts Interrupt Service Routine Interrupt service routine is defined in this way void interrupt i
506. per left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner round radius radius of the rounded edge Te color parameter Valid values T6963C_BLACK and T6963C_WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C rectangle round edges 20 20 219 107 12 T6963C WHITE 515 MikroElektronika mikoC PRO for PIC32 T6963C rectangle round edges fill Prototype void T6963C rectangle round edges fill int x0 int yO int xl int yl int round radius unsigned char pcolor Draws a filled rounded edge 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 round radius radius of the rounded edge ee color parameter Valid values T6963C_ BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C rectangle round edges fil1 20 20 219 107 12 T6963C WHITE T6963C box a void T6963C box int x0 int y0 int xl int yl unsigned char pcolor Draws a box on Glcd Parameters x0 x coordinate of the upper left box corner y0 y coordinate of the upper left box corner x1 X coordinate of the lower right box corner y1 y coordinate of the lower right box cor
507. pin of the PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Port Expander must be initialized See Expander Init Set Port Expander s PORTB to be Expander Set DirectionPortB 0 0xFF Notes fn SS Expander Set DirectionPortAB Prototype void Expander Set DirectionPortAB char ModuleAddress unsigned int Direction The function sets Port Expander s PortA and PortB direction Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page Direction data to be written to direction registers Data to be written to the PortA direction register are passed in Direction s higher byte Data to be written to the PortB direction register are passed in Direction s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output and PORTB to be input Expander Set DirectionPortAB 0 0x00FF Expander Set PullUpsPortA Prototype void Expander Set PullUpsPortA char ModuleAddress char Data The function sets Port Expander s PortA pull up down resistors Parameters ModulcAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up dow
508. playing on Glcd T6963C sprite Prototype void T6963C sprite unsigned char px unsigned char py const code char pic unsigned char sx unsigned char sy Fills graphic rectangle area px py to px sx py sy with custom size picture Parameters px x coordinate of the upper left picture corner Valid values multiples of the font width py y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C sprite 76 einstein 119 draw a sprite If ox and sx eee are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width MikroElektronika 548 mikroC PRO for PIC32 T6963C set cursor Prototype void 76963C set cursor unsigned char x unsigned char y Description Sets cursor to row x and column y Parameters x cursor position row number y cursor position column number UCM o oOo ooo UUU Example T6963C set cursor cposx cposy etes None T6963C clearBit Prototype void T6963C clearBit unsigned int b Clears control port bit s b bit mask The function will clear bit x on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See the T6963C init routine clear bits 0 and 1 on control port T6963C c
509. ple resesc 11 0x95 0x00FF DE O OOOO O O OOOO Ies None SSCS T6963C_dot Prototype void T6963C dot int x int y unsigned char color Draws a dot in the current graphic panel of Glcd at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values T6963C BLACK and T6963C WHITE Rum Wm S Example T6963C dot x0 y0 pcolor oes Noe MikroElektronika 542 mikroC PRO for PIC32 T6963C write char Prototype void T6963C write char unsigned char c unsigned char x unsigned char y unsigned char mode Writes a char in the current text panel of Glcd at coordinates x y Parameters c char to be written x char position on x axis y char position on y axis mode mode parameter Valid values T6968C ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when
510. ppear in the table the first occurrence is unary and the second binary Each category has an associativity rule left to right gt or right to left In the absence of parentheses these rules resolve a grouping of expressions with operators of equal precedence N wo A T e e o5 gt e O es e ii MikroElektronika 236 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 Arithmetic Operators Overview Binary Operators sw 1 modulus operator returns the remainder of integer division 13 cannot be used with floating points Unary Operators unary plus does not affect the operand i unary minus changes the sign of the operand increment adds one to the value of the operand Postincrement 14 adds one to the value of the operand after it evaluates while preincrement adds one before it evaluates decrement subtracts one from the value of the operand Postdecrement subtracts one from the value of the operand after it evaluates while predecrement subtracts one before it evaluates Note Operator is context sensitive and can also represent the pointer referenc
511. pper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 Nothing Requires Glcd needs to be initialized see SPI Glcd Init routine Draw a rounded edge rectangle between dots 5 5 and 40 40 with the radius of 12 SPI Glcd Rectangle Round Edges Fill Prototype void SPI 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 Valid values 0 63 x bottom right x coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 round radius radius of the rounded edge color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Nothing Requ
512. pt with ac prefix So it would look like this ff ac activeComment4 Add Comment To Project 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 After saving you can always edit your active comment by Active Comment Editor and switch between comments directly from editor If you remove a file from the Project Manager or add an Active Comment File which contains information about the file which is no longer in project and hover the mouse over the comment you will be prompted to either add file to project or remove event definition from Active Comment for this file Warning A File linked to this active comment is missing Would you like to add File to a project and make events associated with in valid or unlink file from Active Comment v Show more info If you remove active comment file from the Project Manager you ll receive this message Warning A Missing a file for this active comment Would you like to add File to a project or delete this Active Comment v Show more info Click on Yes button you ll prompted for an active comment file MikroElektronika 102 mikroC PRO for PIC32 O Easy_GSM_GPRS amp activeComment2 My Recent Documents My Computer File name Files of type Active
513. q _ dns unsigned short high low unsigned short parity unsigned short stop bits Configures and initializes the UART module with user defined settings Parameters baud rate requested baud rate freq Khz Peripheral Bus Clock frequency in kHz high low speed High low speed selection parameter Valid values parity Parity and data selection parameter Valid values stop bits stop bit selection parameter Valid values Predefined library const One stop bit UART ONE STOPBIT Two stop bit UART TWO STOPBITS Routine requires the UART module Refer to the device data sheet for baud rates allowed for specific Fosc UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Switching between the UART modules in the UART library is done by the UART Set Active function UART modules have to be previously initialized Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 592 mikroC PRO for PIC32 UARTx Data Ready Prototype unsigned UARTx Data Ready The function tests if data in receive buffer is ready for reading 1 if data is ready for reading 0 if there is no data in the receive register Requires Routine requires at least one UART module Used UART module must be initialized before u
514. quires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx_Init_ Advanced routines unsigned receive read data if ready if UART1 Data Ready receive UART1 Read UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library MikroElektronika 594 mikroC PRO for PIC32 UARTx Read Text Prototype void UARTx Read Text char Output char Delimiter char Attempts Description Reads characters received via UART until the delimiter sequence is detected The read sequence is stored in the parameter output delimiter sequence is stored in the parameter delimiter This is a blocking call the delimiter sequence is expected otherwise the procedure exits if the delimiter is not found Parameters Output received text Delimiter sequence of characters that identifies the end of a received string Attempts defines number of received characters in which Delimiter sequence is expected If Attempts is set to 255 this routine will continuously try to detect the Delimiter sequence Requires Routine requires at least one UART module Used UART module must be initialized before using this ro
515. r Parameters data_ byte to be written Nothing Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init CF card must be initialized for writing operation See Cf Write Init char data OxAA Cf Write Byte data Cf Read Sector Prototype void Cf Read Sector unsigned long sector number unsigned short buffer Description Reads one sector 512 bytes Read data is stored into buffer provided by the buffer parameter Parameters sector number sector to be read buffer data buffer of at least 512 bytes in length Nothing Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init read sector 22 unsigned short data 512 Cf Read Sector 22 data Cf Write Sector Prototype void Cf Write Sector unsigned long sector number unsigned short buffer Description Writes 512 bytes of data provided by the buffer parameter to one CF sector Parameters sector number sector to be written to buffer data buffer of 512 bytes in length Nothing Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init write to sector 22 unsigned short data 512 Cf Write Sector 22 data 293 MikroElektronika mikoC PRO for PIC32 Cf Fat Init Prototype Initializes CF card reads CF FAT16 boot sector and extracts necessary data needed by the library 0 if CF card was
516. r 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 Module freeze in Debug mode Seven user selectable priority levels for each vector Four user selectable subpriority levels within each priority User configurable shadow set based on priority level this feature is not available on all devices refer to the specific device data sheet for availability Software can generate any interrupt User configurable interrupt vector table location ISRs are organized in IVT ISR is defined as a standard function but with the iv directive afterwards which connects the function with specific interrupt vector For more information on IVT refer to the PIC32 Family Reference Manual Configuring Interrupts The PIC32MX interrupt controller can be configured to operate in one of two modes Single Vector mode all interrupt requests will be serviced at one vector address mode out of reset Multi Vector mode interrupt requests will be serviced at the calculated vector address Single Vector
517. r 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 Identifiers Identifiers are arbitrary names of any length given to functions variables symbolic constants user defined data types and labels All these program elements will be referred to as objects throughout the help don t get confused with the meaning of object in object oriented programming Identifiers can contain the letters a to z and Ato Z underscore character is that the first character must be a letter or an underscore and digits from 0 to 9 The only restriction Case Sensitivity The mikroC PRO for PIC32 identifiers aren t case sensitive by default so that Sum sum and suM represent an equivalent identifier Case sensitivity can be activated or suspended in Output Settings window Even if case sensitivity is turned off Keywords remain case sensitive and they must be written in lower case 187 MikroElektronika 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 Iden
518. r RegAddress char data Routine writes a byte to Port Expander Parameters ModulcAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address bata data to be written Retums Byte read Port Expander must be initialized See Expander Init Write a byte to the Port Expander s register Expander Write Byte 0 1 0xFF Expander_Read_PortA Prototype char Expander Read PortA char ModuleAddress The function reads byte from Port Expander s PortA ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as input See Expander_Set_DirectionPortA and Expander_Set_DirectionPortAB routines Read a byte from Port Expander s PORTA char read data Expander Set DirectionPortA 0 0xFF set expander s porta to be cud Expander Read PortA 0 MikroElektronika 388 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 ModulecAddress Port Expander hardware address see schematic at the bottom of this page Byte read Requires Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as input See Expander
519. r msg 8 RS485Master Receive msg RS485Master Send Prototype void RS485Master Send char data buffer char datalen char slave address Description Sends message to Slave s Message format can be found at the bottom of this page Parameters data buffer data to be sent datalen number of bytes for transmition Valid values O 3 slave address Slave s address Nothing Requires MCU must be initialized as a Master for RS 485 communication See RS485Master Init It is the user s responsibility to ensure by protocol that only one device sends data via 485 bus at a time char msg 8 send 3 bytes of data to Slave with address 0x12 RS485Master Send msg 3 0x12 407 MikroElektronika mikoC PRO for PIC32 RS485Slave Init Rens Noting Requires Global variables R8485 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 Valid values 1 for transmitting and 0 for receiving RS485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this routine UART HW module needs to be initialized See UARTx Init Initialize MCU as a Slave with address 160 RS485 module pinout sbit RS485 rxtx pin at RC2 bit transmit receive control set to PORTC B2 sbit RS485 rxtx pin direction at TRISC2 bit RxTx pin direction set as
520. r of appearance in the source code Statements can be roughly divided into Labeled Statements Expression Statements Selection Statements Iteration Statements Loops Jump Statements Compound Statements Blocks Labeled Statements Each statement in a program can be labeled A label is an identifier added before the statement like this label identifier statement There is no special declaration of a label it just tags the statement Label identifier has a function scope and the same label cannot be redefined within the same function Labels have their own namespace label identifier can match any other identifier in the program A statement can be labeled for two reasons 1 The label identifier serves as a target for the unconditional goto statement 2 The label identifier serves as a target for the switch statement For this purpose only case and default labeled statements are used case constant expression statement default statement 249 MikroElektronika 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 sem
521. r side x axis and page layout explanation see schematic at the bottom of this page MikroElektronika 328 mikroC PRO for PIC32 Glcd Read Data Prototype unsigned short Glcd Read Data Description Reads data from from the current location of Gled memory and moves to the next location 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 unsigned int data Glcd Read Data data_ Glcd Read Data This routine needs to be called twice After the first call data is placed in the buffer register After the second call data is passed from the buffer register to data lines Glcd Write Data Prototype void Glcd Write Data unsigned short data Nothing Description Writes one byte to the current location in Glcd memory and moves to the next location Parameters data data to be written 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 unsigned short data Glcd Write Data data 329 MikroElektronika mikoC PRO for PIC32 Gled Fill Prototype void Gicd Fill unsigned short pattern Description Fills Glcd memory with the byte pattern To clear the Glcd screen useGicd Fill
522. ractices If you are experienced in C programming you will probably want to consult mikroC PRO for PIC32 Specifics first For language issues you can always refer to the comprehensive Language Reference A complete list of included libraries is available at mikroC PRO for PIC32 Libraries If you are not very experienced in C programming don t panic mikroC PRO for PIC32 provides plenty of examples making it easy for you to go quickly through it We suggest that you first consult Projects and Source Files first and then start browsing the examples that you re the most interested in Copyright c 2002 2010 mikroElektronika All rights reserved What do you think about this topic Send us feedback 31 MikroElektronika 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 BY INSTALLING COPYING OR OTHERWISE USING SOFTWARE YOU AGREE TO BE BOUND BY ALL TERMS AND CONDITIONS OF THE LICENSE AGREEMENT Upon your acceptance of the terms and conditions of the License Agreement mikroElektronika Associates grants y
523. rage class specifiers in the mikroC PRO for PIC32 are auto register static extern MikroElektronika 2241 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 Register The register storage class specifier is used to define local variables that should be stored in a register instead of RAM At the moment this modifier has no special meaning in mikroC PRO for PIC32 mikroC PRO for PIC32 simply ignores requests for register allocation Static The static storage class specifier lets you define variables or functions with internal linkage which means that each instance of a particular identifier represents the same variable or function within one file only In addition variables declared static have static storage duration which means that memory for these variables is allocated when the program begins running and is freed when the program terminates Static storage duration for a variable is different from file or global scope A variable can have static duration but local Scope Extern The extern s
524. rameters rst Port Port Expander s reset port rst Pin Port Expander s reset pin haen Port Expander s hardware address Requires SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPIx Init and SPIx Init Advanced routines Port Expander module connections sbit SPExpanderRST at RFO bit sbit SPExpanderCS at RF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISF1 bit End Port Expander module connections If Port Expander Library uses SPI module SPI1 inate 7 Initialize SPI1 module used with PortExpander Expander Init Advanced amp PORTB 0 0 Initialize Port Expander 387 MikroElektronika mikoC PRO for PIC32 Expander Read Byte Prototype char Expander Read Byte char ModuleAddress char RegAddress The function reads byte from Port Expander Parameters ModulecAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Port Expander must be initialized See Expander Init Read a byte from Port Expander s register char read data Expander Read Byte 0 1 Expander Write Byte Prototype void Expander Write Byte char ModuleAddress cha
525. rationally allowing VERY complex expressions to be evaluated with a minimum stack consumption Local vars optimization No local variables are being used if their result does not affect some of the global or volatile variables Better code generation and local optimization Code generation is more consistent and more attention is payed to implement specific solutions for the code building bricks that further reduce output code size Related topics SSA Optimization PIC32 specifics mikroC PRO for PIC32 specifics Memory type specifiers MikroElektronika 158 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 A new version of the variable is distinguished renamed by subscripting the variable name with its version number or an index so that every definition of each variable in a program becomes unique At a joining point of the control flow graph where two or more different definitions of a variable meet a hypothetical function called a phi function is inserted so that these multiple definitions are merged In mikroC PRO for PIC32 SSA s main goal is in allocating l
526. rd has Volume Boot Record i e there is only one logical partition and no MBRS the library works with entire card as a single partition For more information on MBR physical and logical drives primary secondary partitions and partition tables please consult other resources e g Wikipedia and similar Before writing operation make sure not to overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable Drive mapping tools such as Winhex can be of great assistance Library Dependency Tree r CompactFlash Compact Flash FAri6 L c Type 281 MikroElektronika mikoC PRO for PIC32 External dependencies of Compact Flash Library The following variables must be defined in all projects Description using Compact Flash Library CF Data Port extern sfr sbit CF RDY Direction of the Ready pin sbit CF RDY direction at TRISD7 bit direction Ti extern sfr sbit CF WE F P E i Direction of the Write Enable pin sbit CF WE direction at TRISDB6 bit direction xd dam extern sfr sbit CF OE F i i f Direction of the Output Enable pin sbit CF OE direction at TRISD5 bit direction SS extern sfr sbit CF CD1 x Direction of the Chip Detect pin sbit CF CD1 direction at TRISD4 bit direction extern sfr sbit CF CE1 A i f Directio
527. reated WordToStr year outstr UART1 Write Text outstr ByteToStr month outstr UART1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr file has been found get its modified date mc Fat Get File Date Modified amp year amp month amp day amp hour amp minute UART1 Write Text modified WordToStr year outstr UART1 Write Text outstr ByteToStr month outstr UART1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordToStr hour outstr UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr get file size fsize Mmc Fat Get File Size LongToStr signed long fsize outstr UART1 Write Line outstr MikroElektronika 380 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 lt 512 i Buffer i i size Mmc Fat Get Swap File 5000 mikroE txt 0x20 see help on this function for details if size LongToStr signed long size err txt UART1 Write Line err txt for i
528. rection at Direction pins TRISD extern sfr sbit 51D13700 WR sbit 1D13700 WR Direction at TRISC2 i Direction of the Write pin i Direction bit extern sfr sbit 51D13700 RD A sbit 1D13700 RD Direction at TRISC1 Direction of the Read pin res s Direction bitty extern sfr sbit 1D13700 AO Direction of the System Address sbit S1D13700 AO Direction at TRISC2 Direction pin bity extern sfr sbit 51D13700_RES_ Direction of the Reset pin sbit S1D13700 RES Direction at Direction pin TRISCO bit extern sfr sbit 51D13700 CS F sbit 51D13700 CS Direction at TRISC4 Direction of the Chip select pin 3 eT Direction bit 307 MikroElektronika mikoC PRO for PIC32 Library Routines 81D13700 Init 81D13700 Write Command 81D13700 Write Parameter 81D13700 Read Parameter 81D13700 Fill 81D13700 GrFill 81D13700 TxtFill 81D13700 Display GrLayer 81D13700 Display TxtLayer 1D13700 Set Cursor 81D13700 Display Cursor 81D13700 Write Char 81D13700 Write Text 81D13700 Dot 81D13700 Line 81D13700 H Line 81D13700 V Line 81D13700 Rectangle 81D13700 Box 81D13700 Rectangle Round Edges 81D13700 Rectangle Round Edges Fill 81D13700 Circle 81D13700 Circle Fill 81D13700 Image 81D13700 Partiallmage MikroElektronika 308 mikroC PRO for PIC32 S1D13700 Init Prototype void S1D13700 Init unsigned i
529. rectives if elif else and endif 262 Directives ifdef and ifndef 263 CHAPTER 9 264 mikroC PRO for PIC32 Libraries 264 Hardware Libraries 265 Standard ANSI C Libraries 266 Miscellaneous Libraries 266 Hardware Libraries 267 ADC Library 267 Library Routines 268 ADCx Init 268 ADCx Init Advanced 268 ADCx Get Sample 269 ADCx Read 269 Library Example 270 CANSPI Library 271 Library Dependency Tree 271 External dependencies of CANSPI Library 271 Library Routines 272 CANSPISetOperationMode 272 CANSPIGetOperationMode 273 CANSPIInitialize 273 CANSPISetBaudRate 275 CANSPISetMask 276 CANSPISetFilter 277 CANSPIRead 278 CANSPIWrite 279 CANSPI Constants 279 MikroElektronika 12 mikroC PRO for PIC32 CANSPI OP MODE Constants 279 CANSPI CONFIG FLAGS Constants 280 CANSPI TX MSG FLAGS Constants 281 CANSPI RX MSG FLAGS Constants 281 CANSPI MASK Constants 282 CANSPI FILTER Constants 282 Library Example 283 HW Connection 286 Compact Flash Library 287 Library Dependency Tree 287 External dependencies of Compact Flash Library 288 Library Routines 289 Cf Init 290 Cf Detect 291 Cf Enable 291 Cf Disable 291 Cf Read Init 292 Cf Read Byte 292 Cf Write Init 292 Cf Write Byte 293 Cf Read Sector 293 Cf Write Sector 293 Cf Fat Init 294 Cf Fat QuickFormat 294 Cf Fat Assign 295 Cf Fat Reset 296 Cf Fat Read 296 Cf Fat Rewrite 297 Cf Fat Append 297 Cf Fat Delete 297 Cf Fat Write 298 Cf Fat Set File Date 298 Cf Fat Get File Date 299
530. rence of character chr in the string ptr The function returns a pointer to the first occurrence of character chr or a null pointer if chr does not occur in ptr The terminating null character is considered to be a part of the string char txt mikroElektronika char res res strchr txt E routine will locate the character txt string and return the address of the character mikroC PRO for PIC32 strcmp Description Function compares strings s1 and s2 and returns zero if the strings are equal or returns a difference between the first differing characters in a left to right evaluation Accordingly the result is greater than zero if s1 is greater than s2 and vice versa char txt mikroElektronika char txt sub mikro int res res stromp txt txt sub compares strings txt and txt sub and returns returns a difference between the first differing characters in this case 69 Prototype char strcpy char to char from Description Function copies the string from into the string to If copying is successful the function returns to If copying takes place between objects that overlap the behavior is undefined char txt mikroElektronika char txt sub mikro test int res res strcpy txt txt sub copies string txt_sub to txt strlen RE Description Function returns the length of the string s the terminating null char
531. rently defined and the same effect as if Oif identifier is currently undefined The other directive ifndef tests true for the not defined condition producing the opposite results The syntax thereafter follows that of if elif else and endif An identifier defined as NULL is considered to be defined 263 MikroElektronika mikoC PRO for PIC32 CHAPTER 9 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 MikroElektronika 264 mikroC PRO for PIC32 Hardware Libraries ADC Library CANSPI Library Compact Flash Library Epson S1D13700 Graphic Lcd Library Flash Memory Library Graphic Lcd Library PC 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 C Library Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Ethernet ENC24J600 Library SPI Graphic Lcd Library SPI Lcd Library SPI Lcd8 Library SPI T6963C Graphic Lcd Library T6963C Graphic Lcd Library TFT Display Library Touch Panel Library Touch Panel TFT Library UART Library USB
532. repare hardware for output before using this function Play sound of 1KHz in duration of 100ms Sound Play 1000 100 MikroElektronika 430 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 Copy Code To Clipboard void Tonel Sound Play 659 250 if void Tone2 Sound Play 698 250 void Tone3 Sound Play 784 250 void Melody LL Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tone3 Tone3 Tone2 void ToneA Sound Play 880 50 void ToneC Sound Play 1046 50 void ToneE Sound Play 1318 50 void Melody2 unsigned short i for i 9 i 0 i ToneA ToneC ToneE void main CHECON 0x32 ADIPCFG OxFFFF TRISB OxF8 LATB 0 Sound Init amp PORTD 3 Sound Play 880 1000 Frequency 659Hz duration 250ms Frequency 698Hz duration 250ms Frequency 784Hz duration 250ms Plays the melody Yellow house Tone3 Tone3 Tone3 Tone2 Tonel Configure AN pins as digital Configure RB7 RB3 as input Play sound at 880Hz for 1 second 431 MikroElektronika mikoC PRO for PIC32 while 1 if Button amp PORTB 7 1 1 RB7 plays Tonel Tonel while RB7 bit
533. ressions Braces Braces indicate the start and end of a compound statement if d z Tx func Closing brace serves as a terminator for the compound statement so a semicolon is not required after except in structure declarations Sometimes the semicolon can be illegal as in if statement E cioe DR illegal semicolon else Lake dui For more information refer to the Compound Statements Comma Comma separates the elements of a function argument list void func int n float f char ch Comma is also used as an operator in comma expressions Mixing two uses of comma is legal but you must use parentheses to distinguish them Note that exp1 exp2 evalutates both but is equal to the second func i g 4 call func with two args func expl exp2 exp3 exp4 exp5 also calls func with two args 189 MikroElektronika 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 a b Evaluate a b but discard value t a Side effect on a but discard value of tta Empty expression or a null statement Semicolons are sometimes used to create an empty state
534. rgotten during manual relocation In order to simplify this Export Project gives you opportunity to do this task automatically To open Export Project from Project menu select Export Project or hit Ctrl Alt E The following window will appear Export Project Select project to export hikroC PRO for PIC32 Examples Development SystemslLV32MXx velLed BlinkinglLedBlinking mcp32 E Select destination folder l D Project EJ In the empty input boxes current location and the destination folder of the desired project should be entered By default currently active project will be set for export You can change it any time by clicking the Open Button i Once you have entered the appropriate data click Export Project button After exporting is done and if everything was OK you ll receive a message Information Project successfully exported You have successfully exported the project All Files From the project are now copied to D Project Now Export Project has copied all project files into desired folder and changed project search paths so you can easily move the entire folder to another location and run the project 105 MikroElektronika 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 dow
535. rigonometry External dependencies of SPI T6963C Graphic Lcd Library The implementation of SPI T6963C Graphic Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies 913 MikroElektronika mikoC PRO for PIC32 Library Routines SPI T6963C config SPI T6963C writeData SPI T6963C writeCommand SPI T6963C setPtr SPI T6963C waitReady SPI T6963C fill SPI T6963C dot SPI T6963C write char SPI T6963C write text SPI T6963C line SPI T6963C rectangle SPI T6963C rectangle round edges SPI T6963C rectangle round edges fill SPI T6963C box SPI T6963C circle SPI T6963C circle fill SPI T6963C image SPI T6963C Partiallmage SPI T6963C sprite SPI T6963C set cursor SPI T6963C clearBit SPI T6963C setBit SPI T6963C negBit The following low level library routines are implemented as macros These macros can be found inthe SPIT6963C h header file which is located in the SPI T6963C example projects folders SPI T6963C displayGrPanel SPI T6963C displayTxtPanel SPI T6963C setGrPanel SPI T6963C setTxtPanel SPI T6963C panelFill SPI T6963C grFill SPI T6963C txtFill SPI T6963C cursor height SPI T6963C graphics SPI T6963C text SPI T6963C cursor SPI T6963C cursor blink MikroElektronika 514 mikroC PRO for PIC32 SPI T6963C config Prototype void SP
536. rned through this parameter mins buffer to store minutes of modification attribute to Upon function execution minutes of modification attribute is returned through this parameter Nothing CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign unsigned year char month day hours mins Cf Fat Get File Date Modified amp year amp month amp day amp hours amp mins 299 MikroElektronika mikoC PRO for PIC32 Cf Fat Get File Size Reums Szeofhecurenlyassgnedfembyes 7 7 y y 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 UL ais long my file size my diac size Cf Fat Get File Size Cf Fat Get Swap File Prototype unsigned long Cf Fat Get Swap File unsigned long sectors cnt char filename char fil attr Description This function is used to create a swap file of predefined name and size on the CF media If a file Parameters 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 exists before calling this function If it is not erased and there is still enough space for a new swap file this function will delete it after allocating new memory space for a new swap file
537. rnet 24j600 getDnslIpAddressQ char SPI Ethernet 243600 getDnsIpAddress This routine should be used when DHCP server is present on the network to fetch paned ehar sss e E NOTES UNS DNS IP address Returns Pointer to the global variable holding DNS IP address Ethernet module has to be initialized See SPI Ethernet 24600 Init unsigned char dnsIpAddr 4 user DNS IP address buffer memcpy dnsIpAddr SPI Ethernet 24j600 getDnsIpAddress 4 fetch DNS server address User should always copy the IP address from the RAM location returned by this routine into it s own DNS IP address buffer These locations should not be altered by the user in any case MikroElektronika 418 mikroC PRO for PIC32 SPI Ethernet 24j600 getlpMask This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Pointer to the global variable holding IP subnet mask Ethernet module has to be initialized See SPI Ethernet 24j600 Init Prototype Description Parameters Requires unsigned char IpMask 4 user IP subnet mask buffer memcpy IpMask SPI Ethernet 24 600 getIpMask 4 fetch IP subnet mask User should always copy the IP address from the RAM location returned by this routine into it s own IP subnet mask buffer These locations should not be altered by the user in any case SPI Ethernet 24j600 confNetwork Prototype Description Parameters Requires
538. roC 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 KSEGO and for variables it is the KSEG1 Linker directives are used with the virtual addresses Directive absolute Directive absolute specifies the starting address in RAM for a variable or a starting address in ROM for a constant If the variable or constant is multi byte higher bytes will be stored at the consecutive locations Directive absolute is appended to declaration of a variable or constant Variable x will occupy 1 byte at address 0xA0000000 short x absolute 0xA0000000 Variable y will occupy 2 bytes at addresses 0xA0000000 and 0xA0000001 int y absolute 0xA0000000 Const array elements will be placed on the consecutive locations starting from OxBD000000 const short ConstantArray 1 2 3 absolute OxBD000000 Note If you want to place simple type constant into Flash memory instead of following declaration const short SimpeConstant 0xAA absolute 0xBD000000 use an array consisting of single element const short SimpleConstant 0xAA absolute 0xBD000000 In first case compiler will recognize your attempt but in order to save Flash space and boost performance it will automatically replace all instanc
539. roElektronika 106 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 A series of characters matches that series of characters in the target string so the pattern short would match short in the target string You can cause characters that normally function as metacharacters or escape sequences to be interpreted by preceding them with a backslash For instance metacharacter matches beginning of string but matches character and matches V etc Examples unsigned matches string unsigned unsigned matches string unsigned Escape sequences Characters may be specified using an escape sequences n matches a newline c a tab etc More generally xnn Where nn is a string of hexadecimal digits matches the character whose ASCII value is nn If you need wide Unicode character code you can use x nnnn where nnnn one or more hexadecimal digits xnn char with hex code nn Vx nnnn char with hex code nnnn one byte for plain text and two bytes for Unicode
540. rograms One possible application of the goto statement is breaking out from deeply nested control structures for oua 1 fot f if disaster goto Error Error error handling code Return Statement The return statement is used to exit from the current function back to the calling routine optionally returning a value The syntax is return expression This will evaluate expression and return the result Returned value will be automatically converted to the expected function type if needed The expression is optional if omitted the function will return a random value from memory Note The statement return in functions of the void type cannot have expression in fact the return statement can be omitted altogether if it is the last statement in the function body 255 MikroElektronika 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 For example the for loop expects one statement in its body so we can pass it a compound statement for i 0 i lt n itt int temp a i afi
541. rom a Metacharacters Metacharacters are special characters which are the essence of regular expressions There are different types of metacharacters described below Metacharacters Line separators start of line end of line A start of text z end of text any character in line Examples PORTA matches string PORTA only if it s at the beginning of line PORTAS matches string PORTA only if it s at the end of line PORTAS matches string PORTA only if it s the only string in line PORT r matches strings like PORTA PORTB PORT1 and so on The metacharacter by default is only guaranteed to match beginning of the input string text and the metacharacter only at the end Embedded line separators will not be matched by or You may however wish to treat a string as a multi line buffer such that the will match after any line separator within the string and will match before any line separator Regular expressions works with line separators as recommended at http www unicode org unicode reports tr18 MikroElektronika 108 mikroC PRO for PIC32 Metacharacters Predefined classes Ww an alphanumeric character including NW a nonalphanumeric character Xd a numeric character XD a non numeric character Xs any space same as t n r f S anon space You may use w dand s within custo
542. rom the program Flash memory address starting address of the FLASH memory block Nothing Requires Nothing 323 MikroElektronika 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 Library Dependency Tree Gicd J Glcd Fonts MikroElektronika 324 mikroC PRO for PIC32 External dependencies of Graphic Lcd Library The following variables must be defined in all projects using Graphic Lcd Description Library ine CD LA CD DO ret Sem aem CHCH Direction of the Data 0 pin Direction of the Data 1 pin t at TRISBO Direction extern sfr sbit G Direction extern sfr sbit G Direction of the Data 3 pin Direction of the Data 4 pin Direction Direction extern sfr sbit G Direction extern sfr sbit G Direction Direction of the Data 5 pin Direction of the Data 6 pin t bit GLCD hs pu Som is Direction of the Data 7 pin Direction i GLCD CS1 be it GLCD CS1 Di ti 7 co UNE Direction of the Chip Select 1 pin a eee es Direction bit extern sfr sbit GLCD_CS2_ sbit GLCD_CS2 Direction at 1 Direction bit extern sfr sbit GLCD RS Direction of the Register select sbit GLCD_RS_ Direction Direction pin bit DO D1 D3 extern sfr sbit G D4
543. ronika 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 month buffer to store month attribute to Upon function execution month attribute is returned through this parameter day buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter mins buffer to store minutes attribute to Upon function execution minutes attribute is returned through this parameter The file must be assigned see Mmc Fat Assign get modification Date time of file unsigned yr char mnth dat hrs mins fille Name MYFILEABTXT Mmc Fat Assign file Name Mmc Fat Get File Date Modified amp yr amp mnth amp day amp hrs amp mins Mmc Fat Get File Size Returns Thsfmionreumssecfagwefe Ga bye Requires MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init
544. roper casting between a pointer to type1 and a pointer to type2 where type1 and type2 are different types can invoke a compiler warning or error If type is a function and type2 isn t or vice versa pointer assignments are illegal If type1 is a pointer to void no cast is needed If type2 is a pointer to void no cast is needed 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 Simply take the name of a suitable and known function Using the address operator amp infront of the function s name is optional Assign an address to the function pointer int DoIt float a char b char c return atbtc pt2Function amp DoIt assignment MikroElektronika 204 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 8 bC mulC divC modC int a
545. ror I2C1 Write 0xA3 module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library u PC library routines require you to specify the module you want to use To select the desired C 341 MikroElektronika mikoC PRO for PIC32 I2Cx Stop eums Noting Requires MCU with at least one I C module Used I C module must be initialized before using this function See I2Cx Init routine Issue STOP signal I2Cl Stop FC library routines require you to specify the module you want to use To select the desired 1 C module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Example This code demonstrates working with the I C library Program sends data to EEPROM data is written at the address 2 After that program reads data from the same EEPROM address and displays it on PORTB for visual check See the figure below how to interface the 24C02 to PIC32 Copy Code To Clipboard void EEPROM 24C02 Init I2C2 Init 100000 ff 2S 255 Writes data to 24C02 EEPROM signle location void EEPROM 24C02 WrSingle unsigned short wAddr unsigned short wData I2C2 Start issue I2C start s
546. rors can interefere with the generation of hex Messages v Errors Warnings Hints Line Message Mo Message Text 1 mikroCPIC32 exe MSF DBG pP32MX460F512L 126 All Files Preprocessed in 1 ms 122 Compilation Started LedBlinking c 123 Compiled Successfully LedBlinking c 127 All Files Compiled in 15 ms 1144 Used RX bytes 32 100 Free RX bytes 0 Used RX bytes 32 100 Free RX bytes 0 0 1144 Static RAM bytes 0 Dynamic RAM bytes 32765 Static RAM bytes 0 Dynamic RAM bytes 32765 1144 Used ROM bytes 448 0 Free ROM bytes Used ROM bytes 448 0 Free ROM bytes 523841 125 Project Linked Successfully LedBlinking mcp32 128 Linked in 203 ms 129 Project LedBlinking mcp32 completed 359 ms 103 Finished successfully 31 Jan 2011 12 32 52 LedBlinking mcp32 6 4 Double click the message line in the Message Window to highlight the line where the error was encountered MikroElektronika D mikroC PRO for PIC32 Quick Converter Quick Converter enables the user to easily transform numbers from one base to another Quick Converter Size Sign DECIMAL HEXADECIMAL BINARY CHARACTER D Le 9 Unsigned 77 0000004D 00000000 00000000 00000000 01001101 16 bits A 32bis O Signed FLOAT DECIMAL 136 893 C FLOAT 32 bit IEEE FLOAT 32 bit MICROCHIP RADIX 1 15 S Hex 43 08 E4 9C 86 08 E4 9C The
547. rrpf char char int res char i void main for i 0 1 lt 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 Simply take the name of a suitable and known function Using the address operator amp infront of the function s name is optional Assign an address to the function pointer int Dort float a char b char c return atbt c pt2Function amp DoIt assignment 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 MikroElektronika 206 mikroC PRO for PIC32 array of pointer to functions that receive two chars and returns int arrpf char ch r adde subC mulC divC modC int res char i void main for i 0 i lt 5 it t res arrpf i 10 20 Pointer Arithmetic Pointer arithmetic in the mikroC
548. rs Sizeof Operator Expressions Introduction to Expressions Comma Expressions Statements Introduction Labeled Statements Expression Statements Selection Statements If Statement Switch Statement Iteration Statements Loops While Statement Do Statement For Statement MikroElektronika 174 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 They describe different categories of word like units tokens recognized by the mikroC PRO for PIC32 In the tokenizing phase of compilation the source code file is parsed that is broken down into tokens and whitespace The tokens in the mikroC PRO for PIC32 are derived from a series of operations performed on your programs by the compiler and its built in preprocessor MikroElektronika TIS 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 discard
549. rs and programmer software are developed to work on and tested on Windows 98 Windows 2000 Windows ME Windows XP 32 and 64 bit Windows Vista 32 and 64 bit and Windows 7 32 and 64 bit and they work fine on these operating systems You can find the latest drivers on our website am getting Access is denied error in Vista how to solve this problem Please turn off User Account Control UAC This should make your software fully functional To do this follow the path in your Windows Vista logged in as administrator Control Panel User Accounts Turn User Account Control on or off uncheck Use User Account Control UAC and click OK What are differences between mikroC PRO mikroPascal PRO and mikroC PRO compilers Why do they have different prices Basically there is little differences between these compilers mikroC PRO is standardized with ANSI C and it is much more complex and it is far more difficult to write the compiler for it We used a lot more resources for making it than what we used for mikroPascal and mikroBasic We also worked on some very complex topics such as floating point typedef union a completely new debugger and many other Because of that there is difference in price Why do your PIC compilers don t support 12F508 and some similar chips Unfortunately our PIC compilers don t support 12F508 and similar chips because these chips are designed to use 12 bit wide instructions Our compiler support MCUs wh
550. s Structure union and enumeration tags Structure members Union members Arrays of other types Statement labels Preprocessor macros Declarations and Definitions Defining declarations also known as definitions beside introducing the name of an object also establish the creation where and when of an object that is the allocation of physical memory and its possible initialization Referencing declarations or just declarations simply make their identifiers and types known to the compiler Here is an overview Declaration is also a definition except if it declares a function without specifying its body it has the extern specifier and has no initializator or body in case of func itis the c ypedef declaration There can be many referencing declarations for the same identifier especially in a multifile program but only one defining declaration for that identifier is allowed For example Here is a nondefining declaration of function max it merely informs compiler that max is a function int max Here is a definition of function max int max int x int y return x gt y x y Definition of variable i int i Following line is an error i is already defined int i MikroElektronika 222 mikroC PRO for PIC32 Declarations and Declarators The declaration contains specifier s followed by one or more identifiers declarators The declaratio
551. s tere ov am o wae d 1 tn dec ne m v ome mm DEN CILE X Ji Bree lass se tee afe T rime owo m ae M com Ee Sere Jolene P M F I or m wee m va aari CDM o Bit aene aem d DOS gt ome det Oni S09 mier asm s be m a ee b Ges i4 LS bd 9 D Domn ie D Lo tA D we pm oi we O OI cA i end 8 CH ua Qd n iram WD Fes SOR Bed Nt INT asco Dyas EUR Fes BOR Bend RTL UV we m co 0 0cb 0L 8 58 el mikroC PRO for PIC32 IDE MikroElektronika 30 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 Having a wide range of application being prized for its efficiency PIC32 MCUS are a natural choice for developing embedded systems mikroC PRO for PIC32 provides a successful match featuring highly advanced IDE ANSI compliant compiler broad set of hardware libraries comprehensive documentation and plenty of ready to run examples Features mikroC PRO for PIC32 allows you to quickly deve
552. s Edit Project Customizing Projects Project Manager MikroElektronika 62 mikroC PRO for PIC32 Library Manager Library Manager enables simple handling libraries being used in a project Library Manager window lists all libraries extension emc1 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 In order to have all library functions accessible simply press the button Check All ail and all libraries will be selected In case none library is needed in a project press the button Clear All E and all libraries will be cleared from the project Only the selected libraries will be linked Library Manager Ce VEI E mikroE C apc C BitReverseComplex Button CAN CAN SPI Conversions C Math C Stdlib C String C Type EEPROM FFT FirRadix FLASH Glcd Glcd Fonts I2c TirRadix Keypad4x4 Lcd Lcd Constants IK E D zl w v ra iz E E EQ EH E E B Ez I E Manchester H Matrices H E Mmc Mmc FAT16 One Wire Port Expander PrintOut len escription Refresh Library by scanning files in Uses folder Useful when new libraries are added by copying files to Uses folder Rebuild all available libraries Useful when library sources are available and need refreshing Include all available libraries in current pro
553. s 649 sprintf 649 sprintl 651 sprinti 651 Library Example 652 Time Library 653 Library Routines 653 Time dateToEpoch 653 Time epochToDate 654 Time dateDiff 654 Library Example 655 Trigonometry Library 656 Library Routines 656 sinE3 656 cosE3 656 CHAPTER 10 657 Tutorials 657 Managing Project 657 Projects 657 New Project 658 New Project Wizard Steps 658 New Project 661 New Project Wizard Steps 661 Customizing Projects 665 Managing Project Group 665 Add Remove Files from Project 665 Project Level Defines 666 Add Remove Files from Project 667 Project Level Defines 668 Source Files 669 Managing Source Files 669 Creating new source file 669 Opening an existing file 669 Printing an open file 669 Saving file 669 Saving file under a different name 670 MikroElektronika 21 mikoC PRO for PIC32 Closing file Search Paths Paths for Source Files c Paths for Header Files h Edit Project Source Files 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 h Clean Project Folder Compilation Output Files Assembly View Creating New Library Multiple Library Versions Frequently Asked Questions Can use your compilers and programmer on Windows Vista Windows 7 am getting Access is denied error in Vista how to solve this problem 670
554. s are used in television sets computer monitors mobile phones handheld video game systems personal digital assistants navigation systems projectors etc The mikroC PRO for PIC32 provides a library for working with HX8347 D 320x240 TFT Lcd controller The HX8347 D is designed to provide a single chip solution that combines a gate driver a source driver power supply circuit for 262 144 colors to drive a TFT panel with 320x240 dots at maximum The HX8347 D is suitable for any small portable battery driven and long term driving products such as small PDAs digital cellular phones and bi directional pagers External dependencies of TFT Library The following variables must be defined in all projects using Description TFT library See EP csv TEN TFT Data Port char TFT DataPort at LATE DataPort t h TET dace QU Direction of the TFT Data Port TF DataPort Direction extern sfr sbit TFT WR Write signal TET IDIS bit extern sfr sbit TFT RD Read signal TFT D12 bit extern sfr sbit TFT CS Chip Select signal TET O3 bit extern sfr sbit TFT RS hag eem selset TPT BIS bit extern sfr sbit TFT RST Reset signal TFT RST at LATC1 bit extern sfr sbit TFT i Direction of the Write pin TFT WR Direction at TRISD13 bit l DataPort Direction at TRISE i zi extern sfr sbit TFT Direction Direction Direction of the Read pin TFT RD Direction at TRISD12 bit i J 3 WR_ RD_ Gs i
555. s single variables The mikroC PRO for PIC32 supports anonymous structures Structure Declaration and Initialization Structures are declared using the keyword struct struct tag member declarator list Here tag is the name of a structure member declarator list is a list of structure members actually a list of variable declarations Variables of structured type are declared the same as variables of any other type The member type cannot be the same as the struct type being currently declared However a member can be a pointer to the structure being declared as in the following example struct mystruct mystruct s illegal struct mystruct mystruct ps l OK MikroElektronika 210 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 ol o2 declare variables ol and o2 of Circle Note that the structure tag can be omitted but then additional objects of this type cannot be declared elsewhere For more information see the Untagged Structures below Structure is initialized by assigning it a comma delimited sequence of values within braces similar to array For example Referring to declarations from the example above Declare and initialize dots p
556. se predefined library constants see the table below can be ORed to form appropriate input value Parameters disFlt network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter MAC Broadcast traffic receive filter flag When set SPI Ethernet MAC broadcast traffic will be disabled BROADCAST x02 MAC Multicast traffic receive filter flag When set MAC SPI Ethernet multicast traffic will be disabled MULTICAST muse nome o o x e o x e co CRC check flag When set CRC check will be disabled and packets with invalid CRC field will be accepted o o X x N RE o MAC Unicast traffic receive filter flag When set MAC SPI Ethernet unicast traffic will be disabled UNICAST eo x e AR o x Co o Nothing Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet Disable SPI Ethernet CRC SPI Ethernet UNICAST disable CRC checking and Unicast traffic Advanced filtering available in the ENC28J60 module such as Pattern Match Magic Packet and Hash Table can not be disabled by this routine This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the ENC28760 module The ENC28760 module should be properly cofigured by the means of SPI Ethernet Init routine MikroElektronika 446 mikroC PRO
557. sfr sbit SoftSpi CLK Clock line sbit SoftSpi CLK at LATF6 bit extern sfr sbit SoftSpi SDI sbit SoftSpi SDI Direction at TRISF4 Direction of the Data In pin f we rie Direction pats extern sfr sbit SoftSpi SDO sbit SoftSpi SDO Direction at TRISF3 P Direction of the Data Out pin pre Direction bat extern sfr sbit SoftSpi CLK i sbit SoftSpi CLK Direction at TRISF6 P Direction of the Clock pin i piov LE Direction bit Library Routines Soft SPI Init Soft SPI Read Soft SPI Write 471 MikroElektronika mikoC PRO for PIC32 Soft SPI Init Reums Noting C Requires Global variables SoftSpi SDI Datain 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 Software SPI module connections sbit sbit sbit sbit sbit sbit SoftSpi SDI at RF4 bit SoftSpi SDO at LATF3 bit SoftSpi CLK at LATF6 bit SoftSpi SDI Direction at TRISF4 bit SoftSpi SDO Direction at TRISF3 bit SoftSpi CLK Direction at TRISF6 bit End Software SPI module connections Soft SPI Init 0 s 7 7 Indt Soft SPI MikroElektronika 422 mikroC PRO for PIC32 Soft SPI Read Prototype unsigned short Soft SPI Read char sdata D
558. signed char SPI Ethernet getGwIpAddressQ sd char SPI Ethernet getGwIpAddress This routine should be used when DHCP server is present on the network to fetch EN gateway IP address Returns Pointer to the global variable holding gateway IP address Ethernet module has to be initialized See SPI Ethernet Init unsigned char gwIpAddr 4 user gateway IP address buffer memcpy gwlpAddr SPI Ethernet getGwIpAddress 4 fetch gateway IP address User should always copy the IP address from the RAM location returned by this routine into it s own gateway IP address buffer These locations should not be altered by the user in any case Ethernet getDnslpAddress Prototype Prototype unsigned char SPI Ethernet_getDnsIpAddress sd char SPI Ethernet _getDnsIpAddress FS a E routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Returns Pointer to the global variable holding DNS IP address Ethernet module has to be initialized See SPI Ethernet Init unsigned char dnsIpAddr 4 user DNS IP address buffer memcpy dnsIpAddr SPI Ethernet getDnsIpAddress 4 fetch DNS server address User should always copy the IP address from the RAM location returned by this routine into it s own DNS IP address buffer These locations should not be altered by the user in any case MikroElektronika 452 mikroC PRO for PIC32 IMS Description This routine
559. sing this routine See UARTx Init and UARTx Init Advanced routines unsigned receive read data if ready if UART1 Data Ready receive UART1 Read al UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UARTx Tx Idle Prototype Use the function to test if the transmit shift register is empty or not 1 if the data has been transmitted 0 otherwise Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx Init Advanced routines If the previous data has been shifted out send next data if VARTI Tx Idle 1 UART1 Write data module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library ul UART library routines require you to specify the module you want to use To select the desired UART 593 MikroElektronika mikoC PRO for PIC32 UARTx Read Prototype The function receives a we via UART Use the UARTx Data Ready function to test if data is ready first Returns Received byte Re
560. sion which can optionally be enclosed in braces The initial value of an object is that of the expression the same constraints for type and conversions as for simple assignments are applied to initializations too For example int i 1 char s hello struct complex c 0 1 0 2 where complex is a structure float float For structures or unions with automatic storage duration the initializer must be one of the following An initializer list A single expression with compatible union or structure type In this case the initial value of the object is that of the expression For example struct dot int x int y m 30 40 For more information refer to Structures and Unions Also you can initialize arrays of character type with a literal string optionally enclosed in braces Each character in the string including the null terminator initializes successive elements in the array For more information refer to Arrays Automatic Initialization The mikroC PRO for PIC32 does not provide automatic initialization for objects Uninitialized globals and objects with static duration will take random values from memory 229 MikroElektronika 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
561. sitions on the left if any are filled with blanks Parameters input unsigned long integer number to be converted output destination string Nothing Requires Destination string should be at least 11 characters in length unsigned long jj 3700000 char txt 11 LongqworaTostr jj txt J xe re 3700000 three blanks here 633 MikroElektronika mikoC PRO for PIC32 FloatToStr Prototype unsigned char FloatToStr float fnum unsigned char str Description Converts a floating point number to a string The output string is left justified and null terminated after the last digit Parameters fnum floating point number to be converted str destination string 3 if input number is NaN 2 if input number is INF 1 if input number is INF 0 if conversion was successful Requires Destination string should be at least 14 characters in length float ffl 374 2 float ff2 123 456789 float 3 0 000001234 char txt l15 PloatToStr ftfl txt QU Eee as 374 2 FloaETOStr ff2 txt J Ext xs COSS 42567 PloatToStr ft3 txt Jf txt is 1 2346 0 Notes Given floating point number will be truncated to 7 most significant digits before conversion WordToStrWithZeros Prototype void WordToStrWithZeros unsigned int input char output Description Converts input word to a string The output string has fixed width of 6 characters including null character at the end string
562. sor blink l1 Library Example The following drawing demo tests advanced routines of the SPI T6963C Glcd library Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L Copy Code To Clipboard include SPIT6963C h bitmap pictures stored in ROM mu const code char mikroE 240x128 bmp const code char einstein Port Expander module connections sbit SPExpanderRST at LATD8 bit sbit SPExpanderCS at LATD9 bit sbit SPExpanderRST Direction at TRISD8 bit sbit SPExpanderCS Direction at TRISD9 bit End Port Expander module connections void main define COMPLETE EXAMPLE define LINE DEMO Uncomment to demonstrate line drawing routines 929 MikroElektronika mikoC PRO for PIC32 define FILL DEMO Uncomment to demonstrate fill routines define PARTIAL IMAGE DEMO Uncomment to demonstrate partial image routine char txtl EINSTEIN WOULD HAVE LIKED mE char txt GLCD LIBRARY DEMO WELCOME char txt2 Partial image demo unsigned char panel Current panel unsigned int i General purpose register unsigned char curs Zf Cursor visibility unsigned int cposx cposy Cursor x y position CHECON 0x32 ADIPCFG OxFFFF initialize AN pins as digital TRISB8 bit 1 Set RB8 as input TRISB9 bit 1 Set RB9 as input TRISB10 bit 1 Set RB10 as input TRISB11
563. ssigned file write data to the assigned file Prepare file for append Write data to assigned file Opens an existing file reads data from it and puts it to UART void M Open File Read char character filename 7 B Cf Fat Assign amp filename 0 Cf Fat Reset amp size for i 1 i lt size i Cf Fat Read amp character UART1 Write character To read fil procedur returns size of file Write data to UART MikroElektronika mikoC PRO for PIC32 Deletes a file If file doesn t exist and then deleted void M Delete File it will first be created filename 7 F Cf Fat _Assign filename 0 Cf Fat Delete Tests whether file exists and if so sends its creation date and file size via UART void M Test File Exist unsigned long fsize unsigned int year unsigned shor unsigned char t month day minute outstr 12 hour Bes uncomment this line to search for file that DOES exists YET uncomment this line to search for file that DOES NOT exist Cf Fat Assign filename 0 file has been found get its date Cf Fat G File Date amp year amp month amp day UART1 Write Text created WordToStr year outstr UART1 Write Text outs ByteToStr month outs UART1 Write Text outs WordToStr day outstr UART1 Write Text outstr WordToStr hour ocutstr UART1 Write Text outstr
564. st 4 characters of the txt sub string beginning from the 7th character routine returns the address of the first populated character memory areas of the object may overlap 621 MikroElektronika mikoC PRO for PIC32 memset Prototype void memset void pl char character int n Description Function copies the value of the character into each of the first n characters of the object pointed by p1 The function returns address of the object pointed to by p1 char txt mikroElektronika memset txt a 2 routine will copy the character a into each of the first n characters of the string txt strcat Prototype char strcat char to char from Description Function appends a copy of the string from to the string to overwriting the null character at the end of to Then a terminating null character is added to the result If copying takes place between objects that overlap the behavior is undefined to string must have enough space to store the result The function returns address of the object pointed to by to char txt mikroElektronika char res txt 3 0 res strcat txt test routine will append the test at the place of the first null character adding terminating null character to the result routine returns the address of the txt string strchr Prototype char strchr char ptr char chr Description Function locates the first occur
565. st be unique within the block in which they are defined Tags declared outside of any function must be unique 3 Structure and union member names must be unique within the structure or union in which they are defined There is no restriction on the type or offset of members with the same member name in different structures 4 Variables typedefs functions and enumeration members must be unique within the scope in which they are defined Externally declared identifiers must be unique among externally declared variables Duplicate names are legal for different name spaces regardless of the scope rules For example int blue 73 open a block enum colors black red green blue violet white c enumerator blue 3 now hides outer declaration of int blue struct colors int i jz Fy ILLEGAL colors duplicate tag double red 2 ILLEGAL redefinition of red blue 37 back in int blue scope MikroElektronika 194 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 Static Duration Memory is allocated to objects with static duration as soon as execution is underwa
566. t 4118 would be interpreted as a two character constant made up of the characters 11 and 8 because 8 is not a legal octal digit MikroElektronika 182 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 The characters inside the double quotes can include escape sequences This code for example t Name tAddress n n prints like this Name Address The Name is preceded by two tabs The Address is preceded by one tab The line is followed by two new lines The X provides interior double quotes The escape character sequence is translated into by the compiler Adjacent string literals separated only by whitespace are concatenated during the parsing phase For example v This 3s Just an example is equivalent to This is just an example Line Continuation with Backslash You can also use the backslash as a continuation character to extend a string constant across line boundaries This is really a one line string 183 MikroElektronika
567. t Heap size Prototype void malloc unsigned WantedSize Description Allocates a block of size bytes of memory returning a pointer to the beginning of the block The content of the newly allocated block of memory is not initialized remaining with indeterminate values WantedSize Size of the memory block in bytes int pi pointer to integer int ai 100 array of integers void main pi int malloc sizeof ai pi will point to a memory block where a array is allocated The type of this pointer is always void which can be cast to the desired type of data pointer in order to be dereferenceable MikroElektronika 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 Nothing Requires Nothing int pi pointer to integer int ai 100 array of integers void main pi int malloc sizeof ai pi will point to a memory block in the Heap where the array is allocated free pi sizeof pi frees memory block from the Heap allocated by malloc pointed to by the pi pointer LargestFreeMemBlock unsigned block void main block LargestFreeMemBlock TotalFreeMemSize Description This function is used to determine total free memory size Reums
568. t 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 Direction at TRISB7 bit End LCD module connections char txtl mikroElektronika char txt2 LV32MX v6 char txt3 Lcd4bit char txt4 example char i void Move Delay Delay ms 750 void main CHECON 0x32 ADIPCFG OxFFFF Lcd Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF Lcd Out 1 6 txt3 Lcd Out 2 6 txt4 Delay ms 2000 Lcd Cmd LCD CLEAR Lcd Out 1 1 txt1 Led Out 2 5 txt2 Delay ms 2000 Moving text for i 0 i 4 itt Lcd Cmd LCD SHIFT RIGHT Move Delay ea yu ted Loop variable Function used for text moving You can change the moving speed here Configure AN pins as digital I O Initialize LCD Clear display Cursor off Write text in Write text in Clear display Write text in Write text in first row second row first row second row Move text to the right 4 times MikroElektronika 302 mikroC PRO for PIC32 for i 0 i 8 itt Move text to the right 7 times Led Cmd LCD SHIFT RIGHT Move Delay t
569. t corresponds to the appropriate pin of the PortA PortB register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Set Port Expander s PORTA and PORTB pull up resistors Expander Set PullUpsPortAB 0 OxFFFF 393 MikroElektronika mikoC PRO for PIC32 Library Example The example demonstrates how to communicate with Port Expander MCP23S17 Note that Port Expander pins A2 A1 AO are connected to GND so Port Expander Hardware Address is 0 Copy Code To Clipboard Port Expander module connections sbit SPExpanderRST at LATFO bit sbit SPExpanderCS at LATF1 bit sbit SPExpanderRST Direction at TRISFO bit sbit SPExpanderCS Direction at TRISF1 bit End Port Expander module connections unsigned int i 0 void main CHECON 0x32 ADIPCFG OxFFFF Configure AN pins as digital TRISB 0x00 LATB OxFF If Port Expander Library uses SPI2 module SPI2 Init Advanced SPI MASTER SPI 8 BIT 4 _SPI_SS_DISABLI Fl Fl SPI DATA SAMPL MIDDLE SPI CLK IDLE LOW SPI ACTIVE 2 IDLE Expander Init 0 Initialize Port Expander Expander Set DirectionPortA 0 0x00 Set Expander s PORTA to be output Expander Set DirectionPortB 0 0xFF Set Expander s PORTB to be input Expander Set PullUpsPortB 0 0xFF Set pull ups to all of the Expander s PORTB pins while i Endless loop
570. t integer number to be converted o Converted BCD value unsigned short a b 22 Dec2Bcd b equals 34 639 MikroElektronika mikoC PRO for PIC32 Bcd2Dec LLOMLLLLLCL UM NN NR unsigned short a b 34 Bcd2Dec 22 b equals 22 Dec2Bcd16 peme meme 000000000 unsigned a b 2345 Dec2Bcd16 a b equals 9029 Bcd2Dec16 ems foerman O O unsigned a b a 0x1234 a equals 4660 b Bcd2Dec16 a b equals 1234 MikroElektronika 640 mikroC PRO for PIC32 Rtrim eme meteeetetesteeg essen am 000000000 char res res Rtrim mikroe trims the trailing spaces and returns the address of the first non space character Ltrim Prototype char Ltrim char string Description 66 Trims the leading spaces from array given with string string array to be trimmed Returns The function returns the address of the first non space character char res res Ltrim mikroe trims the leading spaces and returns the address of the first non space character 641 MikroElektronika mikoC PRO for PIC32 PrintOut Library The mikroC PRO for PIC32 provides the PrintOut routine for easy data formatting and printing Library Dependency Tree Printout 9 c Type Library Routines PrintOut PrintOut Prototype void PrintOut void prntoutfunc char ch const char f PrintOut is used to format data and print
571. t of source files relevant to the application is stored in project file with extension mcp32 along with other project information You can compile source files only if they are part of the project Use the preprocessor directive 4 include to include header files with the extension n Do not rely on the preprocessor to include source files other than headers see Add Remove Files from Project for more information Managing Source Files Creating new source file To create a new source file do the following 1 Select File New Unit from the drop down menu or press Ctrl N or click the New File Icon F from the File Toolbar n 2 Anew tab will be opened This is a new source file Select File gt Save from the drop down menu or press Ctrl S or click the Save File Icon bli the File Toolbar and name it as you want If you use the New Project Wizard an empty source file named after the project with extension c will be created automatically The mikroC PRO for PIC32 does not require you to have a source file named the same as the project it s just a matter of convenience Opening an existing file 1 Select File Open from the drop down menu or press Ctrl O or click the Open File Icon amp from the File Toolbar In Open Dialog browse to the location of the file that you want to open select it and click the Open button 2 The selected file is displayed in its own tab If the selected file is already open its current E
572. t signed integer number to a string The output string has fixed width of 7 characters including null character at the end string termination The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters UPS signed integer number to be converted output destination string Destination string should be at least 7 characters in length int j 4220 char txt 7 IntToStr txt txt is 4220 one blank here mikroC PRO for PIC32 LongToStr Prototype void LongToStr long input char output Description Converts input signed long integer number to a string The output string has fixed width of 12 characters including null character at the end string termination The output string is right justified and the remaining positions on the left if any are filled with blanks Parameters input signed long integer number to be converted output destination string Requires Destination string should be at least 12 characters in length long jj 3700000 char txt 12 LongroStr j j Ext Jf ext ig 3700000 three blanks here LongWordToStr Prototype void LongWordToStr unsigned long input char output Description Converts input unsigned long integer number to a string The output string has fixed width of 11 characters including null character at the end string termination The output string is right justified and the remaining po
573. table for displaying on Glcd 337 MikroElektronika mikoC PRO for PIC32 PC Library The PC 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 IC mode Important FC 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 1 C modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Routines 2Cx Init 2Cx Init Advanced 2Cx Start 2Cx Restart 2Cx Is Idle 2Cx Read I2Cx Write 2Cx Stop I2Cx Init Prototype void I2Cx Init unsigned long scl Description This function configures and initializes the desired IC module with default settings This function enables the I C module by setting the I2CEN bit The rest of the bits in I C control register remains unchanged Default initialization after reset of IC module is Continue operation in IDLE mode T bit slave address Slew rate control enabled for High Speed mode 400 kHz General call address disabled SCL clock stretching disabled 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 scl requested serial clock rate MCU with the lC module Initialize
574. tainly is slower than real CAN The library uses the SPI module for communication User must initialize appropriate SPI module before using the CANSPI Library For MCUs with multiple SPI modules it is possible to initialize both of them and then switch by using the SPI Set Active routine Number of SPI modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Library Dependency Tree CANSPI 9 sri External dependencies of CANSPI Library The following variables must be defined in all projects using CANSPI Description Library sbit CanSpi CS at extern sfr sbit Reset line sbit CanSpi Rst at CanSpi Rst ng RFL bit extern sfr sbit asi Canso CS Hirestion Direction of the Chip Select pin CanSpi_CS_Direction piv at TRISFO bit sbit extern sfr sbit i z Cansoi Ret Direction Direction of the Reset pin CanSpi Rst Direction pease at TRISFl bit 271 MikroElektronika mikoC PRO for PIC32 Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialize CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIRead CANSPIWrite CANSPISetOperationMode Prototype void CANSPISetOperationMode char mode char WAIT 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 m
575. tangle 20 20 219 107 T6963C rectangle 40 40 199 87 T6963C rectangle 60 60 179 67 fendif Draw rounded edge rectangle a ifdef LINE DEMO T6963C Rectangle Round Edges 10 T6963C Rectangle Round Edges 30 T6963C Rectangle Round Edges 50 fendif 1 3 5 Draw filled rounded edge rectangle sz ifdef FILL DEMO T6963C Rectangle Round Edges Fill T6963C Rectangle Round Edges Fill T6963C Rectangle Round Edges Fill T6963C Rectangle Round Edges Fill T6963C Rectangle Round Edges Fill fendif P Draw a cross ud ifdef LINE DEMO pixel height rsor off E r m WHITE 6963C WHITE T6963C WHI T6963C WHITI T6963C WHITI E B H 0 299 137 0 209 97 0 189 77 10 10 229 20 20 219 30 30 209 40 40 199 50 50 189 12 T6963C WHITI 12 T6963C WHITI Move cursor to top left IM RM 12 T6963C WHITE m H Rm H 117 107 57 87 TuS 12 T6963C WHITE 12 T6963C BLACK 12 T6963C WHITE 12 T6963C BLACK 12 T6963C WHITE T6963C line 0 0 239 127 T6963C WHITE T6963C line 0 127 239 0 T6963C WHITE fendif MikroElektronika mikroC PRO for PIC32 ra x Draw circles wd ifdef LINE DEMO T6963C circle 120 T6963C circle 120 T6963C circle 120 T6963C circle 120 T6963C circle 120 T6963C circle 120 T6963C circle 120 fendif y
576. te example projects The code should be adjusted by the user to achieve desired reply SPI Ethernet 24j600 getlpAddress Description This routine should be used when DHCP server is present on the network to fetch assigned IP address Pointer to the global variable holding IP address Requires Ethernet module has to be initialized See SPI Ethernet 24j600 Init unsigned char ipAddr 4 user IP address buffer memcpy ipAddr SPI Ethernet 24 600 getIpAddress 4 fetch IP address User should always copy the IP address from the RAM location returned by this routine into it s own IP address buffer These locations should not be altered by the user in any case ATI MikroElektronika mikoC PRO for PIC32 SPI Ethernet 24j600 getGwlpAddress Description This routine should be used when DHCP server is Y on the network to fetch assigned gateway IP address Pointer to the global variable holding gateway IP address Requires Ethernet module has to be initialized See SPI Ethernet 24 600 Init unsigned char gwIpAddr 4 user gateway IP address buffer amp Bemoby tawi pAddr SPI Ethernet 243600 getGwIpAddress 4 fetch gateway IP address User should always copy the IP address from the RAM location returned by this routine into it s own gateway IP address buffer These locations should not be altered by the user in any case SPI Ethernet 24j600 getDnslpAddress ee unsigned char SPI Ethe
577. tension c see Add Remove Files from Project for more information The syntax of the include directive has two formats include header name include header name 259 MikroElektronika 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 If the 4 include directive is used with the lt header name gt version the search is made successively in each of the following locations in this particular order 1 the mikroC PRO for PIC32 installation folder include folder 2 user s custom search paths The header name version specifies a user supplied include file the mikroC PRO for PIC32 will look for the header file in the following locations in this particular order 1 the project folder folder which contains the project file mcp32 2 the mikroC PRO for PIC32 installation folder include folder 3 user s custom search paths Explicit Path By placing an explicit path in header name only that directory will be searched For example include C my files Ntest h Note There is also a third version of the include directive rarely used which assumes that neither lt
578. the bottom of this page RE DE signal controls RS 485 transceiver operation mode RS485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this routine UART HW module needs to be initialized See UARTx Init RS485 module pinout sbit RS485 rxtx pin direction at RF2 bit transmit receive control set to PORTC B2 sbit RS485 rxtx pin direction at TRISF2 bit RxTx pin direction set as output end RS485 module pinout UART1 Init 9600 initialize UART1 module RS485Master Init intialize MCU as a Master for RS 485 communication MikroElektronika A06 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 2 message content data buffer number of message bytes received 1 3 data buffer is set to 255 when message is received data buffer is set to 255 if error has occurred data buffer 6 address of the Slave which sent the message The routine automatically adjusts data 4 and data 5 upon every received message These flags need to be cleared by software Nothing Requires MCU must be initialized as a Master for RS 485 communication See RS485Master Init cha
579. the I2C1 module with clock rate of 100000 I2CTI Init 100000 Refer to the MCU s datasheet for correct values of the scl in respect with Fosc C library routines require you to specify the module you want to use To select the desired lC 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 Please read the appropriate datasheet before utilizing this library MikroElektronika 338 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 lC 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 Requires MCU with the I C module Used I C module must be initialized before using this function See I2Cx Init routine PC library routines require you to specify the module you want to use To select the desired IPC module simply change the letter x in the routine prototype for a number from 1 to 5 Number of IC modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library I2Cx Start Requires MCU with at least one
580. them in a way defined by the user through a print handler function Parameters prntoutfunc print handler function format string The argument is a format string and may be composed of characters escape sequences and format specifications Ordinary characters and escape sequences are copied to the print handler in order in which they are interpreted Format specifications always begin with a percent sign and require additional arguments to be included in the function call The format string is read from left to right The first format specification encountered refers to the first argument after the parameter and then converts and outputs it using the format specification The second format specification accesses the second argument after and so on If there are more arguments than format specifications the extra arguments are ignored Results are unpredictable if there are not enough arguments for the format specifications The format specifications have the following format flags width precision 1 L conversion type Each field in the format specification can be a single character or a number which specifies a particular format option The conversion type field is where a single character specifies that an argument is interpreted as a character string number or pointer as shown in the following table Mwobkrnko ng mikroC PRO for PIC32 unsigned int Unsigned hexadecimal number using 012345
581. ther functions of this library 0 if MMC SD card was detected and successfully initialized 1 otherwise Requires The appropriate hardware SPI module must be previously initialized Global variables Mmc Chip Select Chip Select line Mmc Chip Select Direction Direction of the Chip Select pin must be defined before using this function MMC module connections sbit Mmc Chip Select at LATFO bit sbit Mmc Chip Select Direction at TRISFO bit MMC module connections Initialize the SPI module PI1 Init Advanced SPI MASTER _SPI 8 BIT _SPI_PRESCALE Si ESCALE PRI 64 SPI SS DISABLE SPI DATA SAMPLE MIDDLE SPI CLK IDLE HIGH SPI ACTIV DLE Loop until MMC is initialized hile Mmc Init Reinitialize the SPI module at higher speed change primary prescaler PI1 Init Advanced SPI MASTER SPI 8 BIT SPI PRESCALE SEC 1 SPI ESCALE PRI 4 SPI SS DISABLE SPI DATA SAI E MIDDLE SPI CLK IDLE HIGH SPI ACTIV MikroElektronika 366 mikroC PRO for PIC32 Mmc Read Sector Prototype unsigned int Mmc Read Sector unsigned long sector char dbuff The function reads one sector 512 bytes from MMC card Parameters sector MMC SD card sector to be read dbuf f buffer of minimum 512 bytes in length for data storage 0 if reading was successful 1 ifan error occurred MMC SD
582. tifier Examples Here are some valid identifiers temperature V1 Pressure to ALE dat2string SUM3 vtext and here are some invalid identifiers temp NO cannot begin with a numeral Shigher NO cannot contain special characters am NO cannot match reserved word j23 07 04 NO cannot contain special characters dot Punctuators The mikroC PRO for PIC32 punctuators also known as separators are Brackets Parentheses Braces Comma Semicolon Colon Asterisk Equal sign Pound sign Most of these punctuators also function as operators Brackets Brackets indicate single and multidimensional array subscripts char ch str mikro int mat 3 4 3 x 4 matrix eh sErED2IS 4th element MikroElektronika 188 mikroC PRO for PIC32 Parentheses Parentheses are used to group expressions isolate conditional expressions and indicate function calls and function parameters ad e ab override normal precedence if d z x essential with conditional statement func function call no args void func2 int n function declaration with parameters Parentheses are recommended in macro definitions to avoid potential precedence problems during an expansion fdefine CUBE x x x x For more information refer to Operators Precedence And Associativity and Exp
583. tion day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter nins buffer to store minutes attribute to Upon function execution minutes attribute is returned through this parameter Nothing CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign unsigned year char month day hours mins Cf Fat Get File Date amp year amp month amp day amp hours amp mins Cf Fat Get File Date Modified Prototype Description Parameters Requires void Cf Fat Get File Date Modified unsigned int year unsigned short month unsigned short day unsigned short hours unsigned short mins Retrieves the last modification date time of the currently assigned file year buffer to store year of modification attribute to Upon function execution year of modification attribute is returned through this parameter month buffer to store month of modification attribute to Upon function execution month of modification attribute is returned through this parameter day buffer to store day of modification attribute to Upon function execution day of modification attribute is returned through this parameter hours bufferto store hours of modification attribute to Upon function execution hours of modification attribute is retu
584. tor File Each project based on the USB library should include a descriptor source file which contains vendor id and name product id and name report length and other relevant information To create a descriptor file use the integrated USB HID terminal of mikroC PRO for PIC32 Tools gt USB HID Terminal The default name for descriptor file is USBdsc c but you may rename it Library Routines HID Enable HID Read HID Write HID Disable USB Interrupt Proc USB Polling Proc Gen Enable Gen Read Gen Write MikroElektronika 600 mikroC PRO for PIC32 HID Enable Prototype void HID Enable char readbuff char writebuff Enables USB HID communication Parameters readbuff Read Buffer writebuftf Write Buffer These parameters are used for HID communication Nothing HID Enable amp readbuff amp writebuff pee This function needs to be called before using other routines of USB HID Library HID Read Prototype Receives message from host and stores it in the Read Buffer If the data reading has failed the function returns 0 Otherwise it returns number of characters received from the host USB HID needs to be enabled before using this function See HID Enable retry until success while HID Read HID Write Prototype char HID Write char writebuff char len Function sends data from Write Buffer writebuff to host Parameters writebuff Write Buffer same p
585. torage class specifier lets you declare objects that can be used in several source files An extern declaration makes a described variable usable by the succeeding part of the current source file This declaration does not replace the definition It is used to describe a variable that is externally defined An extern declaration can appear outside a function or at the beginning of a block If the declaration describes a function or appears outside a function and describes an object with external linkage the keyword extern is optional If a declaration for an identifier already exists within the file scope any extern declaration of the same identifier found within a block refers to the same object If no other declaration for the identifier exists within the file scope the identifier has external linkage See Linkage for more information 225 MikroElektronika 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 consc qualifier the same as literals or preprocessor constants If the user tries to change an object declared with the const qualifier compiler will report an error For example const double PI 3 14159 Qualifier volatile
586. trepy x strtok 0 KE MikroElektronika mikoC PRO for PIC32 Miscellaneous Libraries Button Library Conversions Library PrintOut Library Setjmp Library Sprint Library Time Library Trigonometry Library Button Library The Button Library provides routines for detecting button presses and debouncing eliminating the influence of contact flickering upon pressing a button Library Routines Button Button Prototype unsigned int Button unsigned int port unsigned int pin unsigned int time unsigned int active state Description The function eliminates the influence of contact flickering upon pressing a button debouncing The Button pin is tested just after the function call and then again after the debouncing period has expired If the pin was in the active state in both cases then the function returns 255 true Parameters port button port address pin button pin time debouncing period in milliseconds active state determines what is considered as active state Valid values 0 logical zero and 1 logical one 255 if the pin was in the active state for given period 0 otherwise LE Button PORTD Q l 1 PORTB OxFF mikroC PRO for PIC32 unsigned int oldstate void main ADPCFG OxFFFF TRISD OxFFFF TRISB 0x0000 do if Button amp PORTD 0 1 1 oldstate 1 if oldstate amp amp Button amp PORTD 0 1 0 trans
587. ts 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 Bl1 To access this bit in your code by its name you can write something like this Clear Zero bit SRZ s In this way if Zero bit changes its position in the register you are sure that the appropriate bit will be affected But if Zero bit is not located in the designated register you may get errors Another way of accesing bits is by using the direct member selector with a variable followed by one of identifiers BO Bl B3l or FO Fl F32 with F32 being the most significant bit to access the desired bit predefined globals as bit designators Clear Zero bit SR B1 0 Set Zero bit SR F1 1 In this way if the target bit changes its position in the register you cannot be sure that you are invoking the appropriate bit This kind of selective access is an intrinsic feature of mikroC PRO for PIC32 and can be used anywhere in the code Identifiers 50 531 are not case sensitive and have a specific namespace You may override them with your own members 50 831 within any given structure When using literal constants as bit designators instead of predefined ones make sure not to exceed the appropriate type size Also you can access the desired bit by using its alias name in this case Z bit Set Zero Bit
588. ttr file creation and attributes flags Each bit corresponds to the appropriate file attribute MikroElektronika 300 mikroC PRO for PIC32 Device internal use only never found on disk 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 Parameters Volume Label Subdirectory Try to create a swap file with archive atribute whose size will be at least 1000 sectors i i If it succeeds it sends the No of start sector over UART unsigned long size j Cf Fat Get Swap File 1000 mikroE txt 0x20 j size UART1 Write 0xAA UART1 Write Lo size 7 UART1 Write Hi size UART1 Write Higher size UART1 Write Highest size VARTI Write 0xAA Long File Names LFN are not supported 301 MikroElektronika 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 Copy Code To Clipboard set compact flash pinout char Cf Data Port at PORTE sbit CF_RDY at RD7 bit sbit CF_WE at LATD6 bit for writing to output pin always use latch sbit CF OE at LATD5 bit for writing to output pin alw
589. tuators also known as separators Tokens can be concatenated pasted by means of the preprocessor operator See the Preprocessor Operators for details Token Extraction Example Here is an example of token extraction Take a look at the following example code sequence inter atttb First note that inter would be parsed as a single identifier rather than as the keyword int followed by the identifier er The programmer who has written the code might have intended to write inter a b but it wouldn t work that way The compiler would parse it into the seven following tokens inter variable identifier assignment operator a variable identifier Ft postincrement operator addition operator b variable identifier statement terminator Note that parses as the longest token possible followed by According to the operator precedence rules our code sequence is actually inter at t b MikroElektronika 178 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 Integer Constants Integer constants can be decimal base 10
590. u upgrade the compiler you should start this program again in order to reactivate the license 37 MikroElektronika miko PRO for PIC32 CHAPTER 2 mikroC PRO for PIC32 Environment mikroC PRO for PIC32 Main Menu Options Available Main Menu options are m F E E E S E E E F T IL T a 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 L New Unit Ctr N Open Ctri o Recent Files gt Save Ctr S Save As Close Ctri F4 Close All Shift Ctrl F4 Print Preview S25 Print Ctrl P Exit AIL X File Z4 Description O Related topics Keyboard shortcuts File Toolbar Managing Source Files MikroElektronika 40 mikroC PRO for PIC32 Edit Edit Menu Options The Edit Menu contains commands for editing the contents of the current document Undo Ctr z Redo Shift Ctrl z My Cut Ctrl Copy Ctrl C Paste Ctrl V Delete Select All Ctr A Find Ctrl F Find Next F3 Find Previous Shift F3 Replace Ctri R FindInFiles Alt F3 Goto Line Ctri G Advanced Edt Bescipin O a MikroElektronika mikoC PRO for PIC32 Advanced Descript
591. unsigned short CANSPIWrite long id ipid d 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 Valid values CANSPI TX MSG FLAGS constants See se TX_ MSG_ _FLAGS constants 0 if all Transmit Buffers are busy OxFFFF if at least one Transmit Buffer is available ba The CANSPI module must be in mode in which transmission is possible See CANSPISetOperationMode 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 See connection example at the bottom of this page send message extended CAN message with the appropriate ID and data unsigned short tx lags char data 8 long msg id CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode CANSPI must be in mode in which transmission is possible tx flags CANSPI TX PRIORITY 0 amp CANSPI TX XTD FRAME 2 tx flags CANSPI Constants There is a number of constants predefined in the CANSPI library You need to be familiar with them in order to be able to use the library e
592. uration of time in ms milliseconds This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Parameters time in ms delaytime in milliseconds Valid values constant values range of applicable constants depends on the oscillator frequency Delay ms 1000 One second pause Notes For generating delays with variable as input parameter use the Vdelay ms routine Vdelay ms Prototype Description Creates a software T in duration on Time ms milliseconds Generated delay is not as precise as the delay created by Delay ms Time ms delay time in milliseconds unsignedpause 1000 Vdelay ms pause one second pause Vdelay ms is a library function rather than a built in routine it is presented in this topic for the sake of convenience 151 MikroElektronika mikoC PRO for PIC32 VDelay Advanced ms Prototype void VDelay Advanced ms unsigned time in ms unsigned Current Fosc kHz Description 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 Parameters Time ms delay time in milliseconds Current Fosc_kHz desiredoscillator frequency Note that VDelay Advanced ms is library function rather than a built in routine it is presented in this topic for the sake of convenience pause 1000 fosc 10
593. urns the of x in radians The return value spans the allowed range of floating point in the mikroC PRO for PIC32 doub tan PI 4 doub 0 999998 tanh Prototype double tanh double x Function returns the hyperbolic tangent of x defined mathematically as sinh x cosh x Example doub tanh PI 4 doub 0 655793 MikroElektronika 614 mikroC PRO for PIC32 ANSI C Stdlib Library The mikroC PRO for PIC32 provides a set of standard ANSI C library functions of general utility Important Not all of the standard functions have been included The functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC32 programming Be sure to skim through the description before using standard C functions Library Dependency Tree C Stdlib 9 c Type Library Functions abs atof atoi atol div Idiv uldiv labs max min rand srand xtoi abs Prototype Function returns the absolute i e positive value of a Example result abs 12 result 12 615 MikroElektronika mikoC PRO for PIC32 atof Prototype double atof char s Description Function converts the input string s into a double precision value and returns the value Input string s should conform to the floating point literal format with an optional whitespace at the beginning The strin
594. ut destination string Destination string should be at least 11 characters in length unsigned t 12345678 char txt 11 LongWordToStrWithZeros t txt txt is 0012345678 two zeros 635 MikroElektronika mikoC PRO for PIC32 LongIntToStrWithZeros Prototype void LongIntToStrWithZeros long input char output Description Converts input signed long integer number to a string The output string has fixed width of 12 characters including null character at the end string termination The output string is right justified and the remaining positions on the left if any are filled with zeros Parameters input signed long number to be converted output destination A Returns Nothing 5 Destination string should be at least 12 characters in length int j 12345678 char txt 1i2 LongIntToStrWithZeros txt txt is 0012345678 one zero here ByteToHex Prototype void ByteToHex char input char output Description Converts input number to a string containing the number s hexadecimal representation The output string has fixed width of 3 characters including null character at the end string termination Parameters input byte to be converted output destination string Destination string should be at least 3 characters in length unsigned short t char txt 3 ByteToHex t s ext w Gee ang 02 MikroElektronika 636 mikroC PRO for PIC32 ShortToHex
595. ut value is less than width then blanks are added on the left or right when the flag is specified to pad to the minimum width If width is prefixed with 0 then zeros are padded instead of blanks The width field never truncates a field If a length of the output value exceeds the specified width all characters are output MikroElektronika 650 mikroC PRO for PIC32 Parameters The precision field is a non negative number that specifies a number of characters to print number of significant digits or number of decimal places The precision field can cause truncation or rounding of the output value in the case of a floating point number as specified in the following table Meaning of the precision field d u x X The precision field is where you specify the minimum number of digits that will be included in the output value Digits are not truncated if the number of digits in an argument exceeds that defined in the precision field If the number of digits in the argument is less than the precision field the output value is padded on the left with zeros The precision field is where you specify the number of digits to the right of the decimal point The last digit is rounded The precision field is where you specify the number of digits to the right of the decimal point The last digit is rounded EE The precision field is where you specify the maximum number of significant digits in the output value The precisio
596. utine SPI T6963C write text Glcd LIBRARY DE F 0 SPI T6963C ROM E XOR 919 MikroElektronika mikoC PRO for PIC32 SPI T6963C line Prototype void SPI T6963C line int x0 int y0 int xl int yl unsigned char poolor s Draws a line from x0 yO 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 SPI T6963C BLACK and SPI T6963C WHITE uum Wig O OOO SSS Example SPI T6963C line 0 0 239 127 SPI T6963C WHITE OUI D RN MR GN NM E NT SPI T6963C rectangle Prototype void SPI T6963C rectangle int x0 int y0 int xl int yl unsigned char peolor Draws a rectangle on Glcd Parameters x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine EE SPI T6963C rectangle 20 20 219 107 SPI T6963C WHITE MikroElektronika 020 mikroC PRO for PIC32 SPI T6963C rectangle round edges Prototype void SPI T6963C rectangle round edges int x0 int y0 int xl int yl int round radius unsigned char pcol
597. utine See UARTx Init and UARTx Init Advanced routines UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Read text until the sequence OK is received and send back what s been received UART1 Init 4800 initialize UART1 module Delay ms 100 while 1 if UART1 Data Ready 1 if data is received UART1 Read Text output OK 10 reads text until OK is found UART1 Write Text output sends back text 595 MikroElektronika mikoC PRO for PIC32 UARTx Write Rems Nothing Requires Routine requires at least one UART module Used UART module must be initialized before using this routine See UARTx Init and UARTx Init Advanced routines unsigned char data 0x1E UART1 Write data UART library routines require you to specify the module you want to use To select the desired UART module simply change the letter x in the routine prototype for a number from 1 to 6 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library UARTx Write Text void UARTx Write Text char UART text Rtums Noting SSS Requires Routine requires at least o
598. v IVT ADC ilevel 7 ics ICS SOFT Interrupt service routine code MikroElektronika 112 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 1CS_OFF No context saving 4 ICS AUTO Compiler chooses whether the ICS SOFT or ICS_ SRS will be used User can explicitly declare starting interrupt routine address using org directive void interrupt org 0x9D000000 iv IVT ADC ilevel 7 ics ICS SOFT Interrupt service routine code Function Calls from Interrupt Calling functions from within the interrupt routine is possible The compiler takes care about the registers being used both in interrupt and in main thread and performs smart context switching between two of them saving only the registers that have been used in both threads It is not recommended to use a function call from interrupt In case of doing that take care of stack depth Disable Context Saving Use the pragma disablecontexsaving to instruct the compiler not to automatically perform context switching This means that no register will be saved restored by the compiler on
599. variable init b only upon first call to f static int b 1 checkpoint att btt void main At checkpoint we will have f ea 1l bel after first call fr ZZ ael b 2 after second call f Z asi b 3 after third call ff ete 195 MikroElektronika 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 The type serves to determine the correct memory allocation required to interpret the bit patterns found in the object during subsequent accesses in many type checking situations to ensure that illegal assignments are trapped The mikroC PRO for PIC32 supports many standard predefined and user defined data types including signed and unsigned integers in various sizes floating point numbers with various precisions arrays structures and unions In addition pointers to most of these objects can be established and manipulated in memory The type determines how much memory is allocated to an object and how the program will interpret the bit patterns found in the object s storage allocation A given data type can be viewed as a set of values often implementation dependent that identifiers of that type can assume together with a set of operations allow
600. ve Comments Editor Select Active Comment activeComment Active Comment Actions New Rename Properties Attributes Url www mikroe com Ea RS pg Be I File iJ Events OnLeftClick Alt N OnRightClitk None OnDbIClick OnMouseOver Add Image To Project Add File To Project MikroElektronika 100 mikroC PRO for PIC32 Now when image has been selected we can assign an event to it For example OnMouseOver will be used for Previewlmage action and OnLeftClick Alt will be assigned to OpenUrl action Attributes Url www mikroe com Image Easy_GSM_GPRS jpg File None Events OnLeftClick Alt OpenUrl OnRightClick None OnDblClick Mone OnMouseOver X PreviewImage 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 Once we have finished creating our active comment we can notice that it has been added to source file on current caret position with ac prefix telling IDE that itis active comment I V ae activeComnment 30 Now let s try it If you LeftClick Alt on it URL in default Web browser will be opened If you hover the mouse over it you will see an Image preview Vs ae activeComment 101 MikroElektronika 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 exce
601. veB DriveB DriveA Direction Direction of DriveA pin DriveB Direction Direction of DriveB pin must be defined before using this function Touch Panel module connections sbit DriveA at LATC13 bit sbit DriveB at LATC14 bit Sbit DriveA Direction at TRISC13 bit sbit DriveB Direction at TRISC14 bit End Touch Panel module connections TP Press Detect 581 MikroElektronika mikoC PRO for PIC32 TP Get Coordinates Prototype char TP Get Coordinates unsigned int x coordinate unsigned int y coordinate Get touch panel coordinates and store them in x coordinate and y coordinate parameters Parameters x coordinate x coordinate of the place of touch y coordinate y coordinate of the place of touch 1 if reading is within display dimension range 0 if reading is out of display dimension range TP Get Coordinates x coord amp y coord TP Calibrate Bottom Left Prototype void TP Calibrate Bottom Left emms Non Example TP Calibrate Bottom Left Calibration of bottom left corner pee TP Calibrate Upper Right Reums Nothing Example TP Calibrate Upper Right Calibration of upper right corner LION NN MikroElektronika 582 mikroC PRO for PIC32 TP Get Calibration Consts Prototype void TP Get Calibration S imi qp ioi Gas int x min unsigned int x max unsigned int y min unsigned int y m
602. with the accompanying documentation and Software media will be free from defects in materials and workmanship for a period of ninety 90 days from the date of receipt Any implied warranties on Software are limited to ninety 90 days mikroElektronika Associates and its suppliers entire liability and your exclusive remedy shall be at mikroElektronika Associates option either a return of the price paid or b repair or replacement of Software that does not meet mikroElektronika Associates Limited Warranty and which is returned to mikroElektronika Associates with a copy of your receipt DO NOT RETURN ANY PRODUCT UNTIL YOU HAVE CALLED MIKROELEKTRONIKA ASSOCIATES FIRST AND OBTAINED A RETURN AUTHORIZATION NUMBER This Limited Warranty is void if failure of Software has resulted from an accident abuse or misapplication Any replacement of Software will be warranted for the rest of the original warranty period or thirty 30 days whichever is longer TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW MIKROELEKTRONIKA ASSOCIATES AND ITS SUPPLIERS DISCLAIM ALL OTHER WARRANTIES AND CONDITIONS EITHER EXPRESSED OR IMPLIED INCLUDED BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FORA PARTICULAR PURPOSE TITLE AND NON INFRINGEMENT WITH REGARD TO SOFTWARE AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES MikroElektronika 32 mikroC PRO for PIC32 IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLIERS B
603. with the number of projects in project group Project Manager 1 1 Lcd mcp32 c Progr X d S S S A ct Se amp Lcd mcp32 Sources 3 Lcd c S E Header Files built in h C73 Binaries Project level defines E Image Files EEPROM Files C73 Active Comments Files Output Files Lcd hex g Lcd asm E Other Files MikroElektronika 60 mikroC PRO for PIC32 Following options are available in the Project Manager icon Description EIC TN EIN E Remove project from the project group Add file to the active project Remove selected file from the project E Build the active project Run mikroElektronika s Flash programmer For details about adding and removing files from project see Add Remove Files from Project Related topics Project Settings Project Menu Options File Menu Options Project Toolbar Build Toolbar Add Remove Files from Project 61 MikroElektronika 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 Project Settings Elgg Device Name P32MX460F512L 4G MCU Clock Frequency 80 000000 E Build Debugger T Build Type 9 Release ICD Debug Debugger Software O mikroICD Related topic
604. xt of the message and paste it manually into a new email message before sending it to your distributor s ernail NAME John Smith ADDRESS Enter your address Enter invoice number if available Enter 2CheckOut Order Number or invoice number if available 10 characters mikroElektronika key mikroe com Name John Smith Address Invoice number BA Copy to clipboard 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 Upon receiving and verifying your request we will send the license key to the e mail address you specified in the form After Receving the License Key The license key comes as a small autoextracting file just start it anywhere on your computer in order to activate your copy of compiler and remove the demo limit You do not need to restart your computer or install any additional components Also there is no need to run the mikroC PRO for PIC32 at the time of activation MikroElektronika 36 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 yo
605. y ANSI C Stdlib Library ANSI C String Library ANSI C Ctype Library The mikroC PRO for PIC32 provides a set of standard ANSI C library functions for testing and mapping characters Important Not all of the standard functions have been included The functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC32 programming Be sure to skim through the description before using standard C functions Library Functions isalnum isalpha iscntrl isdigit isgraph islower ispunct isspace isupper isxdigit toupper tolower MikroElektronika 606 mikroC PRO for PIC32 isalnum Prototype unsigned int isalnum char character Function returns 1 if the character is alphanumeric A Z a z 0 9 otherwise returns zero isalnum o returns 1 res isalnum r returns 0 isalpha Prototype unsigned int isalpha char character Function returns 1 if the character is alphabetic A Z a z otherwise returns zero isalpha A returns 1 res isalpha 1 returns 0 iscntrl Prototype unsigned int iscntrl char character Description Function returns 1 if the character is a control or delete character decimal 0 31 and 127 otherwise returns zero Lsontrl returns 1 res iscntrl ne returns 0 isdigit Prototype unsigned int isdigit char character Function returns 1 if t
606. y this storage allocation lasts until the program terminates Static duration objects usually reside in fixed data segments allocated according to the memory specifier in force All globals have static duration All functions wherever defined are objects with static duration Other variables can be given static duration by using the explicit static orextern storage class specifiers In the mikroC PRO for PIC32 static duration objects are not initialized to zero or null in the absence of any explicit initializer Don t mix static duration with file or global scope An object can have static duration and local scope see the example below Local Duration Local duration objects are also known as automatic objects They are created on the stack or in a register when an enclosing block or a function is entered They are deallocated when the program exits that block or function Local duration objects must be explicitly initialized otherwise their contents are unpredictable The storage class specifier auto can be used when declaring local duration variables but it is usually redundant because auto is default for variables declared within a block An object with local duration also has local scope because it does not exist outside of its enclosing block On the other hand a local scope object can have static duration For example void f local duration variable init a upon every call to f int a 1 static duration
607. y click the USART Terminal Icon Copy Code To Clipboard void Tonel Sound Play 659 250 Frequency 659Hz duration 250ms void Tone2 Sound Play 698 250 Frequency 698Hz duration 250ms void Tone3 Sound Play 784 250 Frequency 784Hz duration 250ms void Melody Plays the melody Yellow house Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tone3 Tone2 Tone2 Tonel void ToneA Sound Play 880 50 void ToneC Sound Play 1046 50 void ToneE Sound Play 1318 50 void Melody2 unsigned short i for i 9 i 0 i ToneA ToneC ToneE MikroElektronika 428 mikroC PRO for PIC32 void CHI AD TR LA So So wh main ECON 0x32 1PCFG OxFFFF ISB OxF8 TB 0 und Init amp PORTD und Play 880 1000 ile 1 if Button amp PORTB 7 1 1 Tonel while RB7 bit if Button amp PORTB 6 1 1 Tone2 while RB6 bit if Button amp PORTB 5 1 1 Tone3 while RB5 bit if Button amp PORTB 4 1 1 Melody2 while RB4 bit if Button amp PORTB 3 1 1 Melody while RB4 bit P4 rd ve a aa Configure AN pins as digital Configure R
608. y one device sends data via 485 bus at a time char msg 8 send 2 bytes of data to the Master RS485Slave Send msg 2 409 MikroElektronika 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 OxAA and number of consecutive unsuccessful retries are displayed on PORTD Slave displays received data on PORTB while error on receive 0xAA is displayed on PORTD Hardware configurations in this example are made for the LV 32MX v6 board and PIC32MX460F512L RS485 Master code Copy Code To Clipboard char dat 10 buffer for receving sending messages char i j sbit RS485 rxtx pin at RF2 bit set transcieve pin sbit RS485 rxtx pin direction at TRISF2 bit set transcieve pin direction Interrupt routine void interrupt iv IVT UART 2 ilevel 7 ics ICS SRS RS485Master Receive dat U2RXIF bit 0 ensure interrupt not pending void main long cnt 0 CHECON 0x32 ADIPCFG OxFFFF PORTB PORTD TRISB TRISD ll CO oo UART2 Init 19200 initialize UART2 module Delay ms 100 RS485Master Init initialize MCU as Master dat 0
609. ying to debug MCU with mikroICD while Power Up Timer is enabled Trying to Step Into F7 the mikroC PRO for PIC32 Library routines Use Step Over F8 command for these routines It is not possible to force Code Protect while trying to debug MCU with mikroICD Trying to debug MCU with mikrolCD with pull up resistors set to ON on RB6 and RB7 Related topics mikrolCD Debugger mikrolCD Debug Windows mikrolCD Debugger Options 121 MikroElektronika 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 In situations when multiple breakpoints are used within the code it is sometimes handy to enable disable certain breakpoints To do this just check uncheck the desired breakpoint using the checkbox in front of the breakpoint s name Breakpoints EnablejLine File Name M Watch Values Window Watch Values Window is the main Debugger window which allows you to monitor program execution To show the Watch Values Window select Debug Windows gt Watch from the View drop down menu The W
Download Pdf Manuals
Related Search
Related Contents
MyScreen Mix antiBacterial Histoire Mythique de SHATAN Manual - Process Controls VDIP2 Vinculum VNC1L Module Datasheet the great outdoors by Minka Lavery 8267-66-L Instructions / Assembly 2039-Classe 1 rev07 11. JEAN-LOUIS AUBERT: Parle-moi Asahi Pentax Espio 24EW Operating Manual Pulse™ Series Remote Monitoring Systems Copyright © All rights reserved.
Failed to retrieve file