Home
mikroC PRO for PIC User Manual v100
Contents
1. NE OFF FF FF FF FF FF FF FF FF FF FF FF jy TTE FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 009 EEPROM Edit Input Format Edit Value D EEPROM Address 2105 No Ox Edit Q Hex Start Address FFFF Size mien AutoInc Byte 2 Word DWord String MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 57 2 Environment mikroC PRO for PIC 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 ASCII chart or by clicking the View ASCII Chart Icon A from Tools toolbar NUL STX ETX EOT BEL BS LF VT FF 0 1 2 3 4 5 6 9 10 11 12 DLE DC1 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS 9 2 21 22 23 24 2 2 28 40 8 56 H CHR h DEC 104 1 HEX 0x68 ub 58 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Seven Segment Converter The Seven Segment Convertor is a convenient visual panel which returns decimal hex value for any viable combination you would like to display on 7seg Click on the parts of 7 segment image to get the reques
2. a 571 ANSI Stdlib Library 1 571 Library Functions 571 XXIV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents CL X CP 572 CI oe ey ae Sods heehee ee 572 LM EET 572 cl aan a 572 rs 572 LAC TT 573 E EVE a EN 573 REG 573 caddis bens won nce PTT 573 nie ar 573 theta nd weed bh dd rui Ra 573 2 ta PTT 574 574 Div Str ctures 2 28 he4 cheb bee Ee EP 574 ANSI C String LI rary uox chee wed ER AUR eee ee 575 Library 5 oreste who eee 575 Ie 576 MEMCMP cas dues 1 409 Y XI AVE s E oS 576 Er 576 MEMMOVE 225 024
3. 451 PIC16 and PIC18 5 2522 eer HEP bed ek 451 PIGTQIONIVE PPP 451 Spi Ethernet Init E hed HR CHE tete 452 Spi Ethernet Enable 454 Spi Ethernet Disable 455 Spi Ethernet doPacket 222229012 rae pte 456 Spi Ethernet putByte 457 Spi Ethernet putBytes 457 Spi Ethernet putConstBytes 458 Spi Ethernet putString ee eee dae Pee ERE RR EE xe 458 _ _ 515 459 Spi Ethernet getByte 459 Spi Ethernet getByles cee de e RR pn 460 Spt Ethernet serT OP eek pein eae eR rose iode eta et 461 Spi Ethernet 462 SPI Ethernet 462 SPI Ethernet getGwlpAddress 463 SPI Ethernet getDnslpAddress 463 SPI Ethernet getlpMask 464 SPI Ethernet confNetwork 464 SPI Ethernet arpResolve
4. 171 En mertation Scope 212 EXTA geek pp Pacta Ret Ie E 171 NONI 172 8 uada dus darte RETE AUR are Ries 172 Genenic Pointers kl ek hs Pr eet 172 Derived Types aot hex SERE ER Re E EG Re d RE EO RUD RUE x 173 DR 173 Array Declaration 173 Array Initialization Chee bees REA ROS Gas ee eee 174 Arrays n EXpressions duse decree Bese ae ae ek ee 174 Multi dimensional Arrays 174 Pointers cR PRISE DER eR eae 175 Pointer 5 176 Null Pointers 22222 2040504 bed sie kes 177 Function Pointers 177 Assign an address to a Function 178 Pointer ar Rode a x Ron epe Soke Ro 179 Arrays and pointers 179 Assignment and Comparison 180 Pointer Addition sics concn orn mea ee dos Re ROS dd 181 Pointer Subtraction
5. hee 576 RPM 576 tige rr 577 Cup 577 577 eh 577 SEM 577 Cn mg PPP 578 juges AMT 578 jm e Aedes as 578 Imp 578 Curl ge c Breet 579 SECS PON TP uM 579 jio Aor 579 SUCHE oh he REL Dee hh 579 Miscellaneous Libraries 580 Button Library dad Parc ped Soin rs dt 581 Library ROUUNGS uu sepes exe ER deen RR E Re eee Ub 581 Button D RUOLI TIRES 581 Conversions Library 2 2 22 2 1 4 582 Library ROUUNGS s poh cree AUS od ae 582 cupid P Em 583 ShortlIoStt eh seed ees 583 WoOrndlOStl TET 584 MITOS pedore I cob 584 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents mikroC PRO for PIC LongintTOSI ei mc lx ee bebe eee ee ete 585 save mations dees bea Mee ee vege eee ae 585 diuo PE 586 Dec2Bod
6. 213 Bitwise versus Logical 214 Logical Operators 214 Logical Operators 1 214 Logical Operators 214 Logical Expressions and Side Effects 215 Logical versus Bitwise 215 Conditional Operator 2 216 Conditional Operator Rules 216 Assignment Operators 217 Simple Assignment Operator 217 Compound Assignment Operator 217 Assignment Rules 218 Sizeof Operator 218 Sizeof Applied to Expression 218 Sizeof Applied to 22 m ede kk Bede ER 218 expression herbed Pied a e vex ben 219 Comma EXpressiohs eeu xx En ERR REX Xa d e 219 Statements oei zu ke Bn RNC S S DR 221 Labeled Statements 2 2 221 Expression Statements
7. exit Alt x File Description New Unit a new editor window c en Ctrl O source file for editing or image file for viewing ecent Files Reopen recently used file ve CtrltS Save changes for active editor Save the active source file with the different name or change the file type ii Close Alt F4 Close active source file Print Ctrl P Print Preview amp exit Exit IDE Related topics Keyboard shortcuts File Toolbar Managing Source Files 14 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment EDIT MENU OPTIONS undo Redo Shift Ctrl Z Cut 83 Copy Ctrl C Paste Ctrl V Delete Select All JA Find Ctrl F Jd Find Next F3 92 FindPrevious Shift F3 Replace Ctrl R d Find In Files Alt F3 Goto Line Ctrl G Advanced Edit Description undo Undo last change Redo Shift Ctrl Z Redo last change Cut selected text to clipboard B3 Copy Ctrl C selected text to clipboard 3 Paste Paste text from clipboard X Delete Delete selected text Select All Ctr A Select all text in active editor Find Ctrl F Find text in active editor Find Nex
8. SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Man Receive Prototype unsigned char Man Receive unsigned char error Returns A byte read from the incoming signal The function extracts one byte from incoming signal Parameters Description error error flag If signal format does not match the expected the error flag will be set to non zero To use this function the user must prepare the MCU for receiving See Requires Man Receive Init 0 unsigned char data 0 error data Man Receive amp error if error error handling Man Send Init The function configures Transmitter pin Global variables TXPIN Transmit line TXPIN Direction Direction of the transmit pin must be defined before using this function Initialize Transmitter sbit MANTXPIN at RCL pity sbit MANTXPIN Direction at TIRISCI bit Man Send Init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 361 7 Libraries mikroC PRO for PIC Man Send Prototype void Man Send unsigned char tr data Sends one byte Parameters Description tr data data to be sent Note Baud rate used is 500 bps To use this function the user must prepare the MCU for sending See Requires h Man Send Init unsigned char msg Man Send msg Man Synchro Prototype unsign
9. 534 T6963C use E Sige 534 36963C waitleady prp EA Eee a 534 T6963C fill ce mnenja pe RE De ape gaia ERIS RE Ses 535 T6963C D0lb s ce deen EISE hie abe MARBRE RENE 535 XXII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents T6963C write 222224252220 X iis 536 T6963C write teXl i es eae chee E Food XU IUD dece 537 T6963 lNE cre 538 T6963C rectangle 2242 lt 538 T16963C IDOX io hat Ee EE EE LS bok iba d dier eee 539 T6963C CIICI8 ae ee 539 T6963C Image x ede xor Dec ios BOR 540 69636 SPME cout rane ace hah ese abd ose 540 T6963C bon Raa dla Ea edie deed eae 541 16963C GlearBil seg won ance me ded meee dh ee dod 541 6963 nr oria orte ees 541 T6963C negBit 2 2 24 22242054 ea 542 T6963C displayGrPanel 542 T6963C 542 T6963C setGrPanel 2 2 22 s duse epe REES
10. Ree ROSE Pet qus Redon 557 HW Gonnectlon 33 eoe eee ao e woe dor Bea 558 USB HID Library i bak eg Ghee ede 559 Descriptor File EP delen 559 Library Routines 559 Hid Enable PERS petet ee 560 Hid Read taser ve tois CEPR 560 560 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXIII Table of Contents mikroC PRO for PIC Hid Disable 2222 2522 cheer Y ky nes 561 Library Example x REX pex IRSE YR Re pK avv m Kex x Ron 561 EM Connection eut a REOR ec a e a ege D 563 Standard ANSI C Libraries 564 ANSI C Ctype Library 564 Library 5 564 565 ISAID Nay ee ee 565 Lg P cr 565 Lope PPP 565 ISOLA 22 eee 565 lin 565 ISPUNCE aon eer hxc eoe i near Ron ae eee RETRO 565 155
11. 351 Library Routlhes sd eked pe haa eee ee dee e AL eee 352 lcd Init se E P 352 ed Out be net 353 bed Out situ hoe ieee etn RES She EIE ieu ts 353 lcd Ch Bader oed soe Rants c eS 354 Chip Cp ssi trece across d Roc RR RR 354 ae ate ese backed CEU CPU 355 Available LCD 355 Library Example meek made OR IS Ate dd 356 HW connection nume a Rui Rer Re ER dete 358 Manchester Code Library 359 External dependencies of Manchester Code 359 Library ROUUNGS 2 2 360 Man Receive dn REA IE Ee 360 RECEIVE RESTE PIE Rp dee 361 Man Send Irit 12 252 leak E I Rete n dre 361 Man Send 2 1 eee ee eid ages nee DUE p PN ed Apud den e 362 Man Synchro uere eh EE DER RUE Rp pueden d RETE 362 Man Break zx eei dh ea RA ek opes rte dt 363 Library Example deve coer EOYs bea A Ree 364 Connection Example
12. 367 Multi Media Card 368 Secure Digital Card cess cir RUE OR hae ee Tm ote 368 External dependencies of MMC Library 369 Library Routines 2 369 nsn eee Ree 370 Mme Read Sector 2252450 bp EE RE Da da Sha 370 Mme Write 2 222 222 422 42 22 0 371 Mm Read Cid osi de aser EROR REESE 371 Read 371 Mme UPPER ETT 372 Mmc Fat QuickFormat 373 Mmc Fat ASSIQn i us tret b 374 Mime Fat Reset IR RR GATA ad 375 Mmc Fat Rewrite 375 Mme Fat Append 1 elis suc sede ea pha Y ees 375 Mme Fat Read de eee aon e eoe dob Re a Rp E edad 376 Fat Delete nen RES Pade and eds 376 Mme Fat Write olei EAR DERE Rcs 376 Mmc Fat Set _ 377 Get File Date 22 2 222 2 222222222 2 377 Mme Fat Get File Size isse Re aed 377
13. 465 SPI Ethernet sendUDP 466 SPI Ethernet dnsResolve 467 SPI Ethernet 2 2 2 2 4 2 468 SPI Ethernet doDHCPLeaseTime 469 SPI Ethernet renewDHCP 469 Library Example s scie mao iot woe doc de whee KU Ee odes 470 MW iei re Fn ended 478 SPI Graphic LCD 479 External dependencies of SPI Graphic LCD Library 479 Library ROUUNGS i 2d oer eo E ERR SERERE 479 Spi Gled Init 2 2 05 seeded eke er Re REPE 480 Set SIde ii desee e E 481 XX MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents SPI Glcd Page 2 2 2 2 2 eee 481 SPI Set X iussa x me kem e ne RR ee bee 482 Gled Read Data eese pe Eee er RO rob 482 SPI Glcd Write Data 483 obPIoledsbilliz tocco 483 DOE oe tees E Dni E ead 484 SPI
14. 12 Main Menu Options ns bn RAE REUS bia ES E RO Pre E 13 File Menu Options 14 Edit Menu Options 15 FING 55 Rede Er dog Rob dtl e Bird dote nes 16 Replace Text isse xn sepe ERA DRE tage mea 17 Find FICS Eu E x Pn ols etse 17 Go To Line Roc m mdp d RITE REPRE RENE 18 Regular expressions option 18 Mew Menu Options 4 rone erem EA eed anre et eda 19 Toolbats Pawn edo bbs eee ek xe Ere pe peces es 20 File Toolbar xm cesso dake eae ae E DERE ERR E XAR XR OD 20 Edit Toolbat 5 ERU Poe Ped 20 Advanced Edit 21 Find Replace 1 21 Project v E oe lea e 22 Build Toolbar nae mean mae gea kire gia e ee SOLUS 22 ES 23 Siles To0lbal f DD 23 Tools Toolbar es repere Gee EE eee Dee es ee Ruine RATE dios 24 Project Menu Options 25 Run
15. 245 CANGetOperationMode 246 CANInitializ Bes eee Sa Qa gee dS 246 CANSetBoudRate 247 CANSetMASK Bale ari ee 248 CANSetFillet a anne mo eee TA BOR RR E KOC dog 248 PI 249 CANWrtite eraispena kien kedda neeaaea uer RIA Peu pd 249 CAN ConstantS asse kata e doe nacre E wo Rer RR TRO REUS Rod 250 OP MODE nen da kg Ee de e 250 CONFIG FLAGS 250 CAN TX MSG 251 RX MSG FLAGS chet bL S 252 MASK lieu EGER parad bee eer pae Dude Rp ea ven 252 CAN EIBTER 252 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XIII Table of Contents mikroC PRO for PIC Library Example 2 2 RE RUE 253 HW Connection ee Dy eae ee eee x p pon 255 CANSPL ODA PM EET 256 External dependecies of CANSPI Library 256 Library Routines
16. 393 Expander Write Port 393 Expander Write PortB 552282 Ree eee ded 394 Expander Write PortAB 394 Expander Set 395 Expander Set DirectionPortB 395 Expander Set DirectionPortAB 396 Expander Set 396 Expander Set PullUpsPortB 397 Expander Set 5 397 Library Example sieut koe mere Ea De 398 HW Connection 2 2 4 4 399 urls 400 External dependencies of PS 2 Library 400 Library ROUTIDIBS sp Romae ix eie RB Aus o Ro SOR 400 css ope ce Boxset erect ase els Gee Bee aun or eat 401 Ps2 Key hRead beh Bee ae eed ao el 402 Special Function Keys 2 ee ee d 403 Library Example 404 HW Connection soos usce ma deer PEE HORE VIE XR IEEE 405 PWM LIDT any cs isa ea dee ee ee Kok eal Ae eR eRe eee lay 406 Library ROUTI
17. 118 Divergence from the ANSI C Standard 118 C Language Exstensions 118 Predefined Globals and Constants 118 Predefined project level defines 119 Accessing Individual Bits 2 119 Accessing Individual Bits Of Variables 119 SPILDE PI eames 120 120 huge 121 P18 priority interrupts 2 122 re Ed EORR 122 Function Calls from Interrupt 122 Interrupt Examples 122 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD VII Table of Contents mikroC PRO for PIC Linker DirectiVeS 22 8 oiii y 2 123 Directive absolute usen mcg Re E eR xx ena xs 123 Directive Org ETT 123 Directive orgall 124 Directive funcorg 124 Indirect Function Calls 22 2 124 ROUUNCS zo serios set God RE eine 125 EE 125 censebat peine pruden x eed Pare Pea 126 MINET g
18. network mask for example 255 255 255 0 unsigned char gwIpAddr 4 192 gateway router IP address unsigned char dnsIpAddr 4 192 168 lys 22 DNS er IP address Ethernet confNetwork ipMask gwlIpAddr dnsIpAddr set network configuration parameters 308 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Ethernet arpResolve Fo char Ethernet arpResolve unsigned char ip unsigned Fo tmax MAC ices behind the IP address the requested IP address was resolved 0 otherwise 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 stor ing the configuration ARP cash can store up to 3 entries For ARP cash structure refer to eth j60LibDef n header file in the compiler s Uses P18 folder Prototype Description Parameters ip IP address to be resolved time in seconds to wait for an reply Note The Ethernet services are not stopped while this routine waits for ARP reply The incoming packets will be processed normaly during this time Ethernet module has to be initialized See Ethernet Init unsigned char IpAddr 4 192 168 1 1 IP address Eth rnet arpResolve IpAddr 5 get MAC address behind the above IP address wait 5 secs for the respo
19. Ee x Render het 587 Bocd2D6c16 REA LER Serata ds 587 DOG2BCd EMT 588 Printout LIBAN 2 itio tete Ross ipe me ek Ame eee Ree 589 Library Routlnes ceeded re p xe den EE RR ERE eee eee eee 589 Xie apr EET 589 Selimp LIDEaSEV eoe pe s RR AE REDE REOR Mem 593 Library Routines 7 593 SI Er 593 LONQIMP 2 1 tec i onus y Ac ae eee ROAD Ra fe e 594 Library Example 2 2 rp eR tre ede 595 Sprint Library aen iode Pg duisi 596 FUNCIONS CP 596 596 SPRING cet eek ed ade ae ace aloes 599 Close M CPP 599 library Example doping ertet e ctr Sere dos 600 Time Library iss pne cp SE ERES a ER eee 601 Library Routines 601 Time dateToEpoch 602 Time epochToDate 2 3 ee law keting PEE eae MEE ee 602 Time ate EP 603 Library Example 604 Tigonometry Library i ges ee nm spo DR Ree
20. ER 135 Breaking Through Pages 135 Limits of Indirect Approach Through FSR 135 Memory Type Specifiers 136 p TT 136 data Lege geo eder S Pda dne 4 136 pn 136 jig crc 137 CHAPTER 6 Lexical Elements Overview 143 VIII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents Whitespace 22 5 2 4 1 ee o pe dd nes 143 Whitespace in Strings 2 22 2 144 Line Splicing with Backslash 144 Comments ELE RUE PEE e hed 145 C comments demam ER RR RS ER EKG he EG ke dd bee rus ea 145 CEF COMMENTS aes E 145 Nested comments 146 TOKENS 147 Token Extraction Example 147 CONSIAINS T ec eee BE Meee Meee me ee and 148 Integer Constants 148 Long and Unsigned Suffixes 148 DECIMAIS acc 149 Hexadecimal Constants 149 Binary Constants 2 60 064 ce oc Mende ee emi E EY DERE
21. eee Mie 294 Library Routines 294 EEPROM Read eed eae a E RE dob ae eed 294 EEPROM Write ee e RC RUE 294 Library Example awk meee eked CR AC S 295 Ethernet PIC18FxxJ60 LibrarY 296 PIC18FxxJ60 family of 296 Library ROUTINES 222022 ases n Rake eine es dee spur REA 297 Ethernet 23 etre aches Rook dp e Eod 298 Ethernet Enable 299 Ethernet Disable 300 Ethernet doPacket 2212 sel Ep eee Pe bisa 301 Ethernet s2c s 028 cee ee eid eniri Ra er ud eed dx ctus 302 Ethernet putByl s Rer PUER REP RE 302 Ethernet putConstBytes 252525225 ni Iber Rem 303 Ethernet putString suse E GG RE EAS E 303 Ethernet putConstString 304 Ethernet getByle ee hee Rf eX eg e qus 304 Ethernet getBytes 3 ee vee PERN Cee ee 304 Ethernet Use rTGDP uut peperere BEA 305 Ethernet_UserUDP
22. qputConststring add PORTD value LEDs to reply len putConstString var PORTD IntToStr PORTD len putString dyna len putConstString add HTTP requests counter to reply IntToStr 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 char bitMask 0 for bit mask 474 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries if isdigit getRequest 6 if 0 lt bit number lt 9 bits 8 6 9 does not exist but does not matter bitMask getRequest 6 0 convert ASCII to integer bitMask 1 lt lt bitMask create bit mask 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 sec ond part return len return to the library with the number of bytes to transmit this function is called by the library the user accesses to the UDP request by successive calls to Spi Ethernet getByte the user
23. What date is epoch 1234567890 ia epoch 1234567890 Time epochTobate epoch ts2 How much seconds between this two dates ef diff Time dateDiff etsl amp 2 604 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries TRIGONOMETRY LIBRARY The mikroC PRO for PIC 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 The function returns the sine of input parameter The function calculates sine multiplied by 1000 and rounded to the nearest integer result round sin angle deg 1000 Description Parameters angle deg input angle in degrees Note Return value range 1000 1000 ES 45 2 Jf is 707 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 605 7 Libraries mikroC PRO for PIC cosE3 Prototype int cosE3 unsigned angle deg The function returns the cosine of input parameter The function calculates cosine multiplied by 1000 and rounded to the nearest integer result round cos angle deg 1000 Description Parameters angle deg input angle in degrees Note Return value range 1000 1000 E3 196 result is 193 606 MIK
24. unsigned char myMacAddr 6 0x00 0x14 0xA5 0x76 0x19 0x3f my MAC address unsigned char myIpAddr 192 168 ls 50 Lb my add Ethernet Init myMacAddr myIpAddr Ethernet FULLDUPLEX 298 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Ethernet Enable Ethernet Enable unsigned char enFlt Nothing This is MAC module routine This routine enables appropriate network traffic on the MCU s internal Ethernet 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 appro priate input value Parameters enFlt network traffic receive filter flags Each bit corresponds to the appro priate network traffic receive filter const MAC Broadcast traffic receive filter flag When o mot set MAC broadcast traffic will be enabled MAC Multicast traffic receive filter flag When t set MAC multicast traffic will be enabled UI mE ne qum CRC check flag When set packets with DE invalid field will be discarded NENNT Unicast traffic receive filter flag When pre set
25. 182 I oye eee eh we ed ee ose Bee aed 183 Structure Declaration and Initialization 183 Incomplete Declarations 184 Untagged Structures and Typedefs 184 Working with Structures 1 2 21 185 ASSIONMONL racar Fach 185 185 Structures and Functions 185 X MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents Structure Member Access 186 Accessing Nested Structures 187 Structure UNIQUENESS iiec Ee kg e e Rt ROS e Robe EYED ete 187 UNIONS 2 SLE ps 188 Unions 188 Size UNION Mie 188 Union Member Access 188 Bit Fields 25 ouais strains aS oe REN n dor qur oin 189 Bit Fields Declaration 189 Bit Fields ACCeSS 24422285008 akku AIME EORR os eRe Ae dd 190 Type Conversions
26. CANSetBaucdbate l l 3 3 Ly init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 247 7 Libraries mikroC PRO for PIC CANSetMask Description void CANSetFilter char CAN FILTER long value char CAN CONFIG FLAGS Function sets mask for advanced filtering of messages Given value is bit adjust ed to appropriate buffer mask registers Parameters cAN MASK is one of predefined constant values see CAN constants value is the mask register value CAN CONFIG FLAGS Selects type of message to filter either CAN CONFIG XTD MSG or CAN CONFIG STD MSG CAN must be in Config mode otherwise the function will be ignored CAN routines are currently supported only by P18XXX8 MCUs Microcontroller must be connected to CAN transceiver MCP2551 or similar which is connected to CAN bus Set all mask bits to 1 i e all filtered bits are relevant CANSetMask MASK Bl 1 CAN CONFIG XTD MSG Note that 1 is just a cheaper way to write OxFFFFFFFF Complement will do the trick and fill it up with ones CANSetFilter Prototype void CANSetFilter char CAN FILTER long value char CAN CONFIG FLAGS Description 248 Function sets message filter Given value is bit adjusted to appropriate buffer mask registers Parameters CAN FILTER is one of predefined constant values see CAN constants value is the filter register value C
27. write data to the Opens an existing file and rewrites it void M Open File Rewrite filename 7 C Cf Fat Assign amp filename Cf Fat Rewrite 0 for loop 1 loop lt MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 555 looptt 4 289 7 Libraries mikroC PRO for PIC file contents 0 loop 10 65 file contents 1 loop 5 10 65 Cf Fat Write file contents LINE LEN 1 write data to the assigned file Opens an existing file and appends data to it 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 2005 6 21 10 35 0 7 Cf Fat Append Prepare file for append Cf Fat Write for mikroElektronika 2005n 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 Cf Fat Assign amp filename 0 Cf Fat Reset amp size To read file procedure returns size of file for i 1 i lt size itt Fat Read amp character UART1 Write character Write data to UART Deletes a file If file doesn t exist it will first be created and then deleted void M Delete File 1 filename 7 F Cf Fat Assign filename 0 Cf Fat Delete Tests whether file exists and if so sends its creati
28. 7 mikroC PRO for PIC Libraries Cf Fat Init 0 if CF card was detected and successfuly initialized 1 if FAT16 boot sector was not found 255 if card was not detected Initializes reads CF FAT16 boot sector and extracts necessary data Description needed by the library Init the FAT library Xf Fat IndE Q 4 init the FAT library Cf Fat QuickFormat Prototype unsigned char Cf Fat QuickFormat char cf fat label 0 if CF card was detected successfuly formated and initialized 1 if FAT16 format was unseccessful 255 ifcard was not detected 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 Description passed the volume will not be labeled Note This routine can be used instead or in conjunction with Cf Fat Init routine Note 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 format and initialize the FAT library if Cf Fat QuickFormat amp cf fat label MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 281 7 Libraries mikroC PRO for PIC Cf Fat Assign Prototype Description Requires unsigned
29. 39 COIT 39 Comment 39 Gode Explorer drm Rh kom ROM RR BOR OE ER Reo Rm x ox 40 Fab eee and oad ee abs 41 Project Manager suse kat Roh pu Ra SER RUE Rob S ERE d 42 Project Settings Window 44 Library Manager 222 2 24 46 RR CR EUR E Roe dus od ER 45 Error 22 22 222 222 47 NIE MI EN 48 Memory Usage Windows 48 RAM Memory Usage 48 Used RAM Locations 20 loeis ele e eed Ropa s E eed 49 SER Locations c psp espo nan dose ORE Gi E i 49 ROM Memory Usage 50 ROM Memory Constants 50 Function Sorted by Name 51 Functions Sorted by Size 51 Functions Sorted by Addresses 52 Functions Sorted by Name Chart 52 Functions Sorted by Size 53 Functions sorted by Address Chart 53 ape
30. 478 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI GRAPHIC LCD LIBRARY The mikroC PRO for PIC provides a library for operating Graphic Lcd 128x64 with commonly used Samsung KS108 KS 107 controller via SPI interface For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Note The library uses the SPI module for communication User must initialize SPI module before using the SPI Graphic Lcd Library For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the Set Active routine Note 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 External dependencies of SPI Graphic LCD Library The implementation of SPI Graphic Lcd Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependen cies Library Routines Basic routines SPI 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 SPI Glcd Rectangle SPI Glcd Box SPI Glcd Circle MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 479 CHAPTER 7 Librari
31. You can also compare pointers to zero value testing in that way if the pointer actu ally points to anything All pointers can be successfuly tested for equality or inequal ity to null if pa 0 42 if pb 0 2 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 180 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 adding an integral value 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 type advances the pointer 50 bytes in memory In case of the type type the size of a step is one byte For example int al 10 array a containing 10 elements of type int int 0 pa is pointer to int pointing to a 0 3 6 3 is a pointer pointing to 31 so af 3 now equals 6 patt p
32. const char CAN RX FILTER BITS 0x07 Use this to access filter bits CAN RX FILTER 1 0x00 CAN RX FILTER 2 0x01 CAN RX FILTER 3 0x02 CAN RX FILTER 4 0x03 CAN RX FILTER 5 0x04 CAN RX FILTER 6 0x05 _CAN RX OVERFLOW 0x08 Set tt Overtlowed else cleared CAN RX INVALID MSG 0x10 Set if invalid else cleared CAN RX XTD FRAME 0x20 Set if message else cleared CAN RX RTR FRAME 0x40 Set if RTR message else cleared RX DBL BUFFERED 0x80 Set if this message was hard ware double buffered You may use bitwise AND to adjust the appropriate flags For example if MsgFlag 6 RX OVERFLOW 0 Receiver overflow has occurred We have lost our previous message CAN_MASK CAN MASK constants define mask codes Function CANSetMask expects one of these as its argument const char _CAN MASK 1 0 _CAN MASK B2 1 CAN_FILTER CAN FILTER constants define filter codes Function cANSet Filter expects one of these as its argument const char CAN FILTER B1 F1 CAN FILTER B1 F2 CAN FILTER B2 F1 CAN FILTER B2 F2 ll wHo 252 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Li CAN FII CAN FTI B2 B2 F4 Li Library Example This is a simple demonstration of CAN Libra CHAPTER 7 Libraries
33. eiie eh ee pe rd dc 566 ISUPPOR T TT 566 566 ere Rp epe 566 lnc 566 ANSI C Math Library 4 567 Library FUNCIONS x9 dor ertet e ot Sortes 567 ACOS osse hae ch ha Od OR apd Eie TA Ead E A ac ER d Oe ER 400 a 568 CC E Er 568 CI LETTER 568 ALAN ee a LT 568 Ceil 568 COS pe 568 oe eae LIU 569 OVAL poly eoe 569 OXP Leb be hae 569 labs sees Ste eee ests these te ee ee neath A 569 MOOK rr 569 hol eet Ae ee ane 569 NOX Oe 569 lOG bote pede a e 570 Dou ps CETT 570 Inmodi EL EMITE 570 POW CD 570 ipee cT 570 Jp MES 570 570 571
34. host host name to be resolved Description id tmax time in seconds to wait for an reply Note The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time Note 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 Ethernet module has to be initialized See Ethernet Init 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 Ethernet dnsResolve swisstime ethz ch 5 4 310 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Ethernet initDHCL Prototype unsigned char Ethernet initDHCP unsigned char tmax 1 network parameters were obtained successfuly 0 otherwise 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 successfuly their values are stored into the library global variables These parameters can be fetched by using appropriate library IP get rou
35. returnictr pez MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 315 7 Libraries mikroC PRO for PIC it will be much faster to use library Ethernet putString routine instead of putString routine above However the code will be a little pit bigger User should choose between size and speed and pick the implementation that suites him best If you choose to go with the putString defini tion above the define line below should be commented out define putString Ethernet putString thus function is called by the library the user accesses to the HTTP request by successive calls to Ethernet getByte the user puts data in the transmit buffer by successive calls to Ethernet the function must return the length in bytes of the HTTP reply or 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 unsigned int Ethernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength unsigned int len 0 my reply length unsigned char ij general purpose char 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 i 0 4 10 144 getRequest i Ethernet getByte
36. set a new file with specified name will be created Note Long File Names LFN are not supported 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 O0xAO0 282 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Cf Fat Reset Prototype void Fat Reset unsigned long size Returns Noting Opens currently assigned file for reading Description Parameters size buffer to store file size to After file has been open for reading its size is returned through this parameter 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 long size Reset size Cf_Fat_Read Prototype void Cf Fat Read unsigned short bdata Returns Noting Reads a byte from currently assigned file opened for reading Upon function exe cution file pointers will be set to the next character in the file Description Parameters bdata buffer to store read byte to Upon this function execution read byte is returned through this parameter 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 cha
37. 7 Libraries mikroC PRO for PIC Available LCD Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected D RETURN HOME 504 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Example This example demonstrates how to communicate Lcd in 8 bit mode via the SPI mod ule using serial to parallel convertor 23517 char text mikroE Port Expander module connections sbit SPExpanderRST at RCO bit sbit SPExpanderCcS at bit sbit SPExpanderRST Direction at TRISCO bit sbit SPExpanderCS Direction at TRISCI bit End Port Expander module connections void main Port Expander Library uses SPI1 module 0 Initialize SPI module used with PortExpander If Port Expander Library uses SPI2 module SPI2 Init Initialize SPI module used with PortExpander SPI Lcd8 Config 0 Intialize in 8bit mode via SPI SPI Lcd8 Cmd LCD CLEAR Clear display SPI Lcd8 Cmd LCD CURSOR OFF Tarn cursor off SPL Leds Out 1 6 text 77 Print text to Led Ist row 6th column SPL Loss Che 5 Append SPI Lcd8 Out 2 1 mikroElektronika If Print text to Led 2nd tow Ist colum SPI Lcd8 Out 3 1 text For Lcd modules wit
38. Can Init Flags CAN CONFIG SAMPLE THRICE amp form value to be used CAN CONFIG PHSEG2 PRG ON amp with CANInit CAN CONFIG XTD MSG amp CAN CONFIG DBL BUFFER ON amp CAN CONFIG VALID XTD MSG amp CAN CONFIG LINE FILTER OFF CANInitialize 1 3 3 3 1 Can Init Flags initialize external CAN module CANSetOperationMode CAN MODE CONFIG OxFF set CONFIGURATION mode CANSetMask CAN MASK 1 1 CAN CONFIG XTD MSG set all maski bits to ones 254 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries CANSetMask CAN MASK B2 1 CAN CONFIG XTD MSG set all mask2 bits to ones CANSetFilter CAN FILTER B2 F3 ID 1st CAN CONFIG XTD MSG set id filter B2 Lo ist node ID CANSetOperationMode CAN MODE NORMAL OxFF set NORMAL mode while 1 endless loop Msg Rcvd CANRead amp Rx ID RxTx Data amp Rx Data Len amp Can Rcv Flags receive message if Rx ID ID 1st amp amp Msg Rcvd if message received check id PORTC RxTx Data 0 id correct output data at PORTC RxTx Data 0 increment received data CANWrite ID 2nd RxTx Data 1 Can Send Flags send incre mented data back HW Connection CAN RX of MCU CAN TX of MCU MCP2551 Shielded 27 H twisted pair Example of interfacing CAN transceiver with MCU a
39. Description Parameters 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 7 T6963C_Panel Fill Prototype void T6963C panelFill unsigned char v Fill current panel in full graphic text with appropriate value 0 to clear Description Parameters v Value to fill panel with Toshiba module needs to be initialized See the T6963C init routine clear current panel T6963C panelELtll 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 543 7 Libraries mikroC PRO for PIC T6963C grFill Prototype void T6963C grFill unsigned char v Fill current graphic panel with appropriate value 0 to clear Description Parameters v Value to fill graphic panel with Requires Toshiba Toshiba Gled module needs to be initialized See the T6963C_init routine module needs to be initialized See the T6963C_init routine a clear 4 1 T6963C GrFill 0 T6963C txtFill Prototype void T6963C txtFill unsigned char v Fill current text panel with appropriate value 0 to clear Description Parameters v this value increased by 32 will be used to fill text panel Toshiba Glcd module needs to be initialized See the T6963C init routine clear current text panel T6963C txtFill 0 T6963C cursor h
40. Expander Set DirectionPortB 0 0xFF set expander s portb to be input read data Expander Read PortB 0 392 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Expander Read PortAB Prototype unsigned int Expander Read PortAB char ModuleAddress 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 Description Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page 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 Expander Write PortA Prototype void Expander Write PortA char ModuleAddress char Data The function writes byte to Port Expander s PortA Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Port Expander must be initialized See Expander Init Port Expander s PortA should be configure
41. 161 CONCEPTS serbe eee uenia E pU Rue eoa bard Rol o d ates 162 RE dre anon nensi 162 Objects and Declarations 162 BUM D 163 Isvaluesc s sisse hus Gees ER A DELLI 163 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD IX Table of Contents mikroC PRO for PIC Scope and 0 164 SCOPE ps EBD Y Eo RO KC EROR 164 MEE PE 164 Name Spaces 165 Duration Sa LEE Gs s EP LU DER 165 Static Duration 166 D ratlOri cack tm ean me SE M ae E Add 166 UII PUER 167 Categories sc estero Ear Phe be eee Pd eae 167 Fundamental suus sio toes ee dle ape 168 Arithmetic 168 Integral Types subse ae eae gba qued eR doit ee 168 Floating point 2 2 2 169 En rmerations c 2 42 rotten i ado Ehe dp RE CI 170 Enumeration Declaration 170 Anomous Enum
42. 2 mikroC PRO for PIC Environment 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 Pese 4495 LedBlinking mcppi 7 Sources 4 LedBlinking c 1 7 Header Files 405 Binaries ff Project level defines 7j Image Files Output Files 7j Other Files Step 2 Drag the tool window from its current location A guide diamond appears The four arrows of the diamond point towards the four edges of the IDE Other Files MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 33 2 Environment mikroC PRO for PIC Step 3 Move the pointer over the corresponding portion of the guide diamond An outline of the window appears in the designated area E UT 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 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 D
43. 3 mikrolCD mikroC PRO for PIC mikrolCD Debugger Options Start Debugger F9 Run Pause Run or pause Debugger F6 Toggle breakpoint at the current cursor posi tion To view all breakpoints select Run gt View Breakpoints from the drop down menu Double clicking an item in the Breakpoints Window List locates the breakpoint Execute all instructions between the current Run to cursor F4 instruction and cursor position Execute the current C single or multi cycle instruction then halt If the instruction is a routine call enter the routine and halt at the first instruc tion following the call Execute the current C single or multi cycle Step Over instruction then halt If the instruction is a rou F8 tine call skip it and halt at the first instruction following the call Flush current PIC RAM All variable values Flush RAM will be changed according to values from N A watch window Disassembly Toggle between disassembly and C source Alt D View Toggle Breakpoints Step Into F7 104 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 mikroC PRO for PIC mikrolCD mikrolCD Debugger Examples Here is a step by step mikrolCD Debugger Example Step No 1 First you have to write a program We will show how mikrolCD works using this example LCD module connections sbit LCD RS at RB4 bit sbit LCD EN at RBS bit sbit LCD D4 at RBO
44. 462 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 7 SPI Ethernet getGwlpAddress Returns Ponter to the global variable holding gateway IP address Description This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address Note 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 module has to be initialized See SPI Ethernet Init Available for PIC18 family MCUs only unsigned char gwIpAddr 41 user gateway IP address buffer memcpy gwIpAddr SPI Ethernet getGwIpAddress 4 fetch gate way IP address SPI Ethernet getDnslpAddress Returns Ponter to the global variable holding DNS IP address Description This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Note 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 Ethernet module has to be initialized See SPI Ethernet Init Available for PIC18 family MCUs only unsigned char dnsIpAddr 4 user DNS IP address buffer memcpy dnsIpAddr SPI Ethernet getDnsIpAddress 4 fetch DNS server address
45. 6 mikroC PRO for PIC Language Reference 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 func tion declarations cannot be nested To return the function result use the return statement The statement return in functions of the 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 greater one of its 2 arguments int max int x int y return gt x y 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 math h void polar double x double y double r double fi X ode ye v xfi x 0 amp amp 0 0 atan2 y x return this line can be omitted Function Reentrancy Functions reentrancy is allowed if the function has no parameters and local vari ables or if the local variables are placed in the Rx space Remember that the PIC has stack and memory limitations which ca
46. Braces Comma Semicolon Colon Asterisk Equal sign Pound sign Most of these punctuators also function as operators Brackets Brackets 1 indicate single and multidimensional array subscripts char ch str mikro int mati 31 41 3 x 4 matrix ch str 312 4th element Parentheses Parentheses are used to group expressions isolate conditional expressions and indicate function calls and function parameters a override normal precedence if z x essential with conditional statement func fuhctionm Call no args fune2 int n function declaration with parameters Parentheses are recommended in macro definitions to avoid potential precedence problems during an expansion define x x x For more information refer to Operators Precedence And Associativity and Expres sions 158 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Braces Braces indicate the start and end of a compound statement if d 491 Tek 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 x32 illegal semicolon else Ta F
47. If RAO is pressed display only graphic panel ri if RAO bit T6963C graphics 1 7 548 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries T6963C text 0 Delay ms 300 If is pressed toggle the display between graphic panel 0 and graphic panel 1 wy else if RAl bit 1 panel amp 1 T6963C displayGrPanel panel Delay ms 300 If RA2 is pressed display only text panel 7 else if RA2 bit T6963C graphics 0 T6963C t ext 1 Delay ms 300 If RA3 is pressed display text and graphic panels else if RA3 bit T6963C graphics 1 T6963C text 1 Delay ms 300 RA4 is pressed change cursor Ek else if RA4 bit if curs 3 curs 0 switch curs case 0 no cursor T6963C cursor 0 break case 1 blinking cursor T69630 cursor l T6963C cursor bIink 1 break case 2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 549 7 Libraries mikroC PRO for PIC non blinking cursor T609693C cursor T6963C cursor blink 0 break Delay ms 300 Move cursor mp even if not visible Af cposx T6903C txtCols 4 cposx 0 cposy if cposy cposy 0 T6963C grHeight T6963C CHARACTI ER HEIGHT T69
48. 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 node mode parameter Valid values SPI T6963C ROM MODE OR SPI T6963C ROM MODE SPI T6963C ROM MODE AND and SPI T6963C ROM MODE TEXT Description 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 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 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example T6963C write text Glcd LIBRARY DEMO WELCOME T6963C ROM MODE EXOR 514 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi T6963C line void SPI 6963 line int x0 int int xl int yl unsigned char pcolor Draws a line fr
49. month amp 0x0F Transform month E Output values to LCD void Display Time Lcd 1 6 day 10 48 Print tens digit of day variable Chr 1 7 day 5 10 48 Print oness digit of day variable Led Chr l 9 month 2210 46 1 10 month 10 48 hed OQhr 15 year 56 Print year vaiable 8 426 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC start from year 2008 Led Obr 2 5 hours Led Chr 2 7 hours Led Chr 2 minutes hod Chir 25 minutes Ohr 2 seconds Led Chr 2 13 seconds eem mm mmi Ep ur Ss I m void Init Main TRISB 0 PORTB OxFF TRISB Oxff ANSEL 0 ANSELH 0 Soft 126 Imnuit Log Inve Lcd Cmd LCD CLEAR Log LED CURSOR OEF Led Outil l Datei Led Che Led Led Dut 2 l Led 8 Log Chee ta Led Out 1 12 200 void main Delay 5 2000 Init Main while 1 Read Time Transform Time Display Time Delay ms 1000 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 7 Libraries 10 48 10 48 10 48 10 48 10 48 10 48 Configure AN pins as digital I O Initialize Soft I2C communication 7 Initialize LCD Cl ar
50. t if request path name starts with t toggle PORTD LED bit number that comes after unsigned char 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 317 7 Libraries 318 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC bitMask getRequest 6 0 convert ASCII to integer bitMask 1 lt lt bitMask create bit mask PORTD bitMask toggle PORTD with xor operator f len ee 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 this function is called by the library the user accesses to the UDP request by successive calls to Ethernet the user puts data in the transmit buffer by successive calls to 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 m unsigned int Etherne
51. 257 CANSPISetOperationMode 258 CANSPIGetOperationMode 258 CANSPIInitialize 259 CANSPISetBaudRate 261 GANSPISetMaSk oeger xe a Pee mead dog 262 CANSPISetFiller 263 CANSPIR amp ad i etnine Ru Rd d 264 S Rin ADDE 265 CANSPI Constants 52 Epp epo RR CREE ea ges 266 CANSPI OP MODE 2 222 22 4 4 4 0 0 266 CANSPI CONFIG FLAGS 266 CANSPI TX MSG FLAGS 2529 Lzknids Dhaai eek b bee ee 267 CANSPI RX MSG 5 268 CANSPI MASK 268 CANSPIUFILTER opted e ert Bener tes uud 268 Library Example nrs issu er E nee eee RR E 269 HW Connection ee bee en etre me rt me 272 Compact Flash Library 1 4 273 Library ROUUNGS nde Ea e IR E RR RS OD 275 EI ee 276 Detect PT 277 Enables AER EES OER ee 277 Cf Disable
52. 7 Libraries mikroC PRO for PIC PWM LIBRARY CCP module is available with a number of PIC MCUs mikroC PRO for PIC provides library which simplifies using PWM HW Module Note Some MCUs have multiple CCP modules In order to use the desired CCP library routine simply change the number 1 in the prototype with the appropriate module number i e PWM2 Start Library Routines PWMI Init PWM1 Set Duty PWM Start PWM1 Stop PWM Init Initializes the PWM module with duty ratio 0 Parameter is a desired PWM frequency in Hz refer to device data sheet for correct values in respect with Description Fosc This routine needs to be called before using other functions from PWM Library MCU must have CCP module Note Calculation of the PWM frequency value is carried out by the compiler as it would produce a relatively large code if performed on the libary level Therefore compiler needs to know the value of the parameter in the compile time That is why this parameter needs to be a constant and not a variable Initialize PWM module at 5KHz PWM1 Init 5000 406 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries PWMA1 Set Duty Prototype void PWM1 Set Duty unsigned short duty ratio Sets PWM duty ratio Parameter duty takes values from 0 to 255 where 0 is Description 0 127 is 50 and 255 is 100 duty ratio Other specific value
53. 7 mikroC PRO for PIC Libraries lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt lt gt ENC28J60 Mini Web Server lt hl1 gt a href gt Reload lt a gt lt script src s gt lt script gt lt table gt lt tr gt lt td valign top table border 1 style font size 20px font family terminal gt tr th colspan 2 gt ADC lt th gt lt tr gt tr td AN2 td td script document write AN2 lt script gt lt td gt lt tr gt tr td AN3 td td script document write AN3 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 lt tr gt lt th colspan 2 gt PORTB lt th gt lt tr gt lt script gt Var Str i str for i 0 i1 lt 8 i strt lt tr gt lt td bgcolor pink gt BUTTON it lt td gt if PORTB 1 lt lt i strt lt td bgcolor red gt ON else strt lt td bgcolor cccccc gt OFF str t L C tre document write lt script gt const char indexPage2 table td td table border 1 style font size 20px font family terminal gt lt tr gt lt th colspan 3 gt PORTD lt th gt lt tr gt script Var sti L str for i 0 i lt 8 i strt lt tr gt lt td bgcolor yellow gt LED it lt td gt if PORTD amp 1 lt lt i strt lt td bgcolor red gt ON else strt lt td bgcolor cccccc gt
54. Description inator denom the function returns a structure of type div comprising quotient quot and remainder see Div Structures 572 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Idiv Prototype ldiv t ldiv long number long denom Function is similar to the div function except that the arguments and result structure members all have type long DSssripph Function computes the result of division of the numerator number by the denom inator denom the function returns a structure of type ldiv comprising quo tient quot and remainder see Div Structures uldiv Prototype uldiv t uldiv unsigned long number unsigned long denom Function is similar to the div function except that the arguments and result structure members all have type unsigned long Description Function computes the result of division of the numerator number by the denom inator denom the function returns a structure of type uldiv t comprising quo tient quot and remainder rem see Div Structures labs 0 Function returns the absolute i e positive value of long integer max Prototype imt max mt a max int imt max mt a int b Function returns greater of the two integers a and Prototype int min int a int Function returns lower of the two integers a and rand Prototype int rand Functio
55. INTCON GIE 0 Global interrupt disable MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 437 7 Libraries mikroC PRO for PIC 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 PIC USART Terminal Tool char i error byte read Auxiliary variables void main ANSEL 0 Configure AN pins as digital I O ANSELH 0 TRISB 0x00 Set PORTB as output error signalization PORTB 0 No error error Soft UART Init amp PORTC 7 6 14400 0 Initialize Soft UART at 9600 bps if error gt 0 4 PORTS gt rror Signalize Init error while 1 Stop program Delay ms 100 for i z i gt A i Send bytes from z downto A Soft UART Write i Delay ms 100 while 1 Endless loop byte read Soft UART Read amp error Read byte then test error flag if error If error was detected PORTB error gy signal it on PORTB else Soft UART Write byte read If error was not detect ed return byte read 438 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SOUND LIBRARY The mikroC PRO for PIC provides a Sound Library to supply users with routines necessary for sound signalization in their applications Sound generatio
56. LED configuration default LEDA link status LEDB link activity Parameters nac 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI Ethernet Chip Select line SPI Ethernet CS Direction Direction of the Chip Select pin SPI Ethernet RST Reset line SPI Ethernet RST Direction Direction of the Reset pin Requires be defined before using this function he SPI module needs to be initialized See the SPI1_Init and SPI1 Init Advanced routines define SPI Ethernet HALFDUPL define SPI Ethernet FULLDUPLE mE ehternet NIC pinout sfr sbit SPI Ethernet at RCO bit sfr sbit SPI Ethernet CS at bit sfr sbit SPI Ethernet Rst Direction at TRISCO bit sfr sbit SPI Ethernet CS Direction at TRISC1 bit end ethernet NIC definitions unsigned char myMacAddr 6 0x00 0x14 OxA5 0x76 0x19 0x3f my MAC address unsigned char myIpAddr 2192 168 1 6072 my addr SEIT SPI Ethernet Init myMacAddr myIpAddr SPI Ethernet FULLDUPL MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 453 CHAPTER 7 Libraries Spi Ethernet Enable void SPI Ethernet Enabl
57. Next Step One Select the device from the device drop down list New Project Wizard gt Select the device you want to use Device Name AGE Y 4 Back Next gt Cancel MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 79 2 Environment mikroC PRO for PIC Step Two Enter the oscillator frequency value New Project Wizard xX Step 2 5 Setup the clock for example 11 0592 MHz Device Clock 11 059200 MHz 4 Back Next gt Cancel Step Three Specify the location where your project will be saved New Project Wizard sss Specify where your project will be saved Project File Name 4 Back Next gt Cancel 80 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 2 Environment 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 4 Back Next gt Step Five Click Finish button to create your New Project New Project Wizard x Step 4 5 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 D Projects FirstProject Definit h i File Name D Projects FirstProject Definit h Remove Remove All Lll Cancel
58. aFontOffs number that represents difference between the mikroC PRO char acter set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroC PRO 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 Glcd fonts file located in the Uses folder or create his own fonts Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Example Use the custom 5x7 font myfont which starts with space 32 SPI Gled Ser Font myfont 5 7 32 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 487 CHAPTER 7 Libraries mikroC PRO for PIC Spi Glcd Write Char Prototype Description void SPI Glcd Write Char char chrl char x pos char page num char color Nothing Prints character on GLCD Parameters chri 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 Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Use t
59. if Ethernet doDHCPLeaseTime it s time to renew the IP address lease Ethernet renewDHCP Prototype unsigned char Ethernet renewDHCP unsigned char tmax 0 upon success lease time was renewed 1 otherwise renewal request timed out This is DHCP module routine It sends IP address lease time renewal request to DHCP server Description Parameters time in seconds to wait for an reply Ethernet module has to be initialized See Ethernet Init while 1 if Ethernet_doDHCPLeaseTime Ethernet renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Example This code shows how to use the PIC18FxxJ60 Ethernet 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 t7 will toggle RDO to RD7 bit and return HTML main page all other requests return also HTML main page define Ethernet HALFDUPLEX 0 define Ethernet FULLDUPLEX i 8 RRR kk kA KK Kk KK CKCKCKCkCKCkCkCkCkCk kCkCkCkCkCKCKCKCkCKCKCKCkCkCkCk C
60. starting address 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 funcall directive to instruct the link er 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 func name 18 implemented This module must also include declarations of all func tions listed in the called tunc list These functions will be linked if the function unc name is called the code no mat ter whether any of them was called or not Note The pragma 11 directive can help the linker to optimize function frame allocation in the compiled stack Related topics Linker Directives 124 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 4 mikroC PRO for PIC Specifics Built in Routines mikroC PRO for PIC compiler provides a set of useful built in utility functions Built in functions do not require any header files to be included you can use them in any part of your project Built in routines are implemented as inline i e code is generated in the place of the call so the call doesn t count against the nested call limit The
61. 605 Library ROUTINES pos ated Ses 605 SIDES 12222222052 qu x hd odie et idee bebe bed 605 cu O ees Lhe SM Hu 606 XXVI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Introduction to mikroC PRO for PIC The mikroC PRO for PIC is a powerful feature rich development tool for PIC microcontrollers It is designed to provide the programmer with the easiest possi ble solution to developing applications for embedded systems without compromis ing performance or control 1 Introduction mikroC PRO for PIC mikroC PRO for PIC IDE PIC and C fit together well PIC is the most popular 8 bit chip in the world used in a wide variety of applications and C prized for its efficiency is the natural choice for developing embedded systems mikroC PRO for PIC provides a successful match featuring highly advanced IDE ANSI compliant compiler broad set of hard ware libraries comprehensive documentation and plenty of ready to run examples Features mikroC PRO for PIC allows you to quickly develop and deploy complex applications W Write your C source code using the built in Code Editor Code and Parameter Assistants Code Folding Syntax Highlighting Auto Correct Code Templates and more W Use included mikroC PRO for PIC libraries to dramatically speed up the devel opment data acq
62. Description initial character of from overwrites the null character at the end of to The termi nating null character is always appended to the result The function returns to strncpy Prototype char strncpy char to char from int size Function copies not more than size characters from string from to co If copy ing 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 Description strspn Prototype int strspn char strl char str2 Function returns the length of the maximum initial segment of cx which consists Description entirely of characters from str2 The terminating null character at the end of the string is not compared strncmp Prototype int strncmp char s1 char s2 char len Function lexicographically compares not more than 1e characters characters that follow the null character are not compared from the string pointed by s to the string pointed by s2 The function returns a value indicating the si and s2 relationship Description Meaning sl less than 62 51 equal to s2 51 greater than s2 578 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries strstr Prototype char strstr char 51 char s2 Function locates the first occu
63. Draws a vertical line on Glcd Prototype 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 Description Parameter color determines the line color 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see Glod needs to be initialized for SPI communication see SPI_Gled_Initroutines routines Draw a vertical line between dots 10 5 and 10 25 SPI V 25 10 1 SPI Glcd H Line void SPI Glcd H Line char x start char x end char y pos char color Draws a horizontal line on Glcd Prototype Parameters x start X coordinate of the line start Valid values 0 127 Description 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 Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a horizontal line between dots 10 20 and 50 20 SPI Gled H Line l0 50 20 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 485 7 Libraries mikroC PRO for PIC
64. In the absence of parentheses these rules resolve a grouping of expres sions with operators of equal precedence SENE E NEN eo V V Y ww 1 1 24 5 1 qw 2 __ Arithmetic Operators Arithmetic operators are used to perform mathematical computations They have numerical operands and return numerical results The type char technically repre sents small integers so the char variables can be used as operands in arithmetic operations All arithmetic operators associate from left to right 208 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Binary Operators mmm as IE modulus operator returns the remainder of integer division cannot be used with floating points Unary Operators unary plus does not affect the operand unary minus changes the sign of the operand decrement subtracts one from the value of the operand Postdecrement subtracts one from the value of the operand after it evaluates while pre decrement subtracts one before it evaluates increment adds one to the value of the Postincrement adds one to the value of the operand 14 after it evaluates while preincrement adds one before it evaluates e Note Operator is context sensitive and
65. LCD Library Manchester Code Library Muliti Media Card Libray OneWire Library Port Expander Library PrintOut Library PS 2 Library PWM Library RS 485 Library Software Library Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Graphic LCD Library SPI LCD Library SPI LCD8 Library SPI T6963C Graphic LCD Library T6963C Graphic LCD Library UART Library USB HID Library 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 Sprint Library Setjmp Library Time Library Trigonometry Library See also Built in Routines 240 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC LIBRARY DEPENDENCIES CANSPI 9LsPt 1 C CF FAT16 Compact Flash Conversions C String Glcd Fonts Lcd Led Constants MMC se MMC FAT16 MMC Port Expander gt SPI RS 485 SPI SPI Ethernet E String _ Port Expander SPI SPI Glcd 17 Glcd Fonts Port Expander gt SPI SPI Lcd Led_Constants Port Expander SPI SPI_Led8 Led_Constants
66. Library Routines You can get text representation of numerical value by passing it to one of the follow ing routines ByteToStr ShortToStr WordToStr IntToStr LongToStr LongWordToStr FloatToStr The following functions convert decimal values to BCD and vice versa Dec2Bcd Bcd2Dec16 Dec2Bcd16 582 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries ByteToStr Prototype void ByteToStr unsigned short input char output 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 Description Parameters input byte to be converted output destination string Requires Destination string should be at least 4 characters in length unsigned short t 24 char txt 4 ByteToStr t txt txt is 24 one blank here ShortToStr Prototype void ShortToStr short input char output Nothing 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 Description Parameters input Short number to be converted output destination s
67. Line 2 120 ii 1 delay28 Glcd Fill 0x00 Clear GLCD ifdef COMPLETE EXAMPLE Glcd_Set_Font Character8x7 8 7 32 Choose font see Lib GLCDFonts c in Uses folder fendif Glod Write Text mikroE 1 7 29 Write string for 11 44 lt 10 114 Draw circles Gled Circle 63 32 3 21 2 delay2S Gled Box 12 20 TO 57 2 Draw box delay2S COMPLETE EXAMPLE Gled Fill jf Fill GLCD Gled Set Font Character8x7 8 7 32 Change font someText 8x7 Font Glcd Write Text someText 5 0 2 Write string delay2S Glcd Set Font System3x5 3 5 32 Change font someText 3X5 CAPITALS ONLY Glcd Write Text someText 60 2 2 Write string delay28 Set Font fontbx7 5 7 32 Change font someText 5x7 Font MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 339 7 Libraries mikroC PRO for PIC Glcd Write Text someText 5 4 2 Write string delay28 Glcd Set Font FontSystem5x7 v2 5 7 32 Change font someText 5x7 Font v2 Glcd Write Text someText 5 6 2 Write string 1 25 endif HW Connection Left side Right side 2 e vec e888 88 18849214 88 Glcd HW connection 340 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 m
68. OxOF ts Configuration 0 0 OxFF OxFF 0x07 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 561 7 Libraries mikroC PRO for PIC LATA LATB LATE LATD LATE oo gt OO Clear user RAM Banks 00 071 8x 256 2048 Bytes asm LFSR FSRO 0x000 MOVLW 0x08 CLRF POSTINCO 0 CPFSEQ FSROH 0 BRA 2 Timer 0 TOCON 0x07 TMROH 65536 156 gt gt 8 TMROL 65536 156 amp OxFF INTCON TOIE 1 Enable TOIE TOCON TMROON 1 Main Program Routine void main Init Main Hid Enable amp userRD buffer amp userWR buffer do for E OF k lt Eat 4 Prepare send buffer userWR buffer 0 Send the number via USB Hid Write suserWR buffer 1 while 1 Hid Disable 562 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection OSS7A8LOld 100nF 100nF T USB connection scheme MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 563 7 Libraries mikroC PRO for PIC STANDARD ANSI C LIBRARIES ANSI C Ctype Library ANSI C Math Library ANSI C Stdlib Library ANSI C String Library ANSI C Ctype Library The mikroC PRO for PIC provides a set of standard ANSI C library functions for test ing and
69. SPExpanderRST Direction Direction of the Reset pin SPExpanderRST Direction TRISCO bit extern sfr sbit Direction of the Chip i PExpanderCS Direction SPExpanderCS Direction Select TRISCl bit Library Routines Expander Init Expander Read Byte Expander Write Byte Expander Read PortA Expander Read PortB Expander Read PortAB Expander Write PortA Expander Write PortB Expander Write PortAB Expander Set DirectionPortA Expander Set DirectionPortB Expander Set DirectionPortAB Expander Set PullUpsPortA Expander Set PullUpsPortB Expander Set PullUpsPortAB MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 389 7 Libraries 390 mikroC PRO for PIC Expander Init Prototype void Expander Init char ModuleAddress Description Initializes Port Expander using SPI communication Port Expander module settings hardware addressing enabled automatic address pointer incrementing disabled byte mode BANK_0 register adressing slew rate enabled Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page 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 mod
70. Save from the drop down menu or press Ctrl S or click the Save File Icon W 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 with extension will be created automatically The mikroC PRO for PIC 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 gt Open from the drop down menu or press or click the Open File Icon 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 active 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 84 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Saving file 1 Make sure that the window containing the file that you want to save is active 2 Select File gt Save from the drop down menu or press Ctrl S or click the Save File Icon from the File Toolbar Saving file under
71. amp a 4 pa points to af 4 pa 3 f Pt buts y Spat y a4 3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 179 6 Language Reference mikroC PRO for PIC Also the care should be taken when using operator precedence Equal to increments the pointer pa p Increments the pointed object The following examples are also valid but better avoid this syntax as it can make the code really illegible Cae 3 a 1 4 3 i e ali 1 3 same as 1 0 same as i 2 a 0 i e 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 oper ators 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 a 4 pb amp a 2 if pb won t be executed as 4 is not equal to 2 if gt pb will be executed as 4 is greater than 2
72. initialized see Glcd Init routine _ 5 e u in the upper left corner Glcd Dot Glcd Line void Glcod Line int x start ink 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 Description The parameter color determines the line color 0 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 Gled Line 0 0 20 30 1 332 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Glcd V Line void Glcd V Line unsigned short y start unsigned short y end unsigned short x pos unsigned short color Nothing Draws a vertical line on Glcd Parameters y start y coordinate of the line start Valid values 0 63 Description 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 Requires Glcd needs to be initialized see Glcd Init rou
73. max a gt bj 2 Convert small letter to capital no parentheses are actually necessary 46 gt toe 32 6 Conditional Operator Rules expressioni 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 expression2 and expression3 3 Both expressions have to be of void type The resulting type is void 4 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 result ing type is a pointer to a type qualified with all type qualifiers of the types point ed 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 void expression 216 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Assignme
74. pointed at by pointer to const amp ci NO cannot assign to a const pointer even if value would be unchanged cect NO cannot change const pointer pei NO if this assignment were allowed you would be able to assign to pci 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 to the same identifier 154 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 decrement function call increment Each constant expression can evaluate to a constant that is in the range of repre sentable values for its type Constant expression can be used anywhere a constant is legal MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 155 6 Language Reference mikroC PRO for PIC KEYWORDS Keywords are words reserve
75. routine routinne routinnne etc Metacharacters Backreferences Metacharacters 1 through are interpreted as backreferences matches previ ously matched subexpression 4 Examples 1 matches and 1 matches abab and 123123 11712 d 1 matches 13 in double quotes or 4 in single quotes or 77 without quotes etc T2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment mikroC PRO for PIC COMMAND LINE OPTIONS Usage mikroCPIC1618 exe lt opts gt lt opts gt lt infile gt lt opts gt opts j Infile can be of c mcl and pid type The following parameters and some more see manual are valid MCU for which compilation will be done Fo Set oscillator in MHz sp Add directory to the search path list IF Add directory to the include search list N Output files generated to file path specified by filename Save compiled binary files mc1 to directory Miscellaneous output options Generate debug info 1 Check and rebuild new libraries Build all files as libraries v Dynamic link for string literals c Turn on case sensitivity UCD ICD build type Example mikroCPIC1618 exe MSF DBG 16 887 ES C 011111114 fo8 N C Led Lcd mcppi SP C Program Files Mikroelektronika mikroC PRO for PIC Defs SP C Program Files Mikro
76. 191 Standard Conversions 191 BICI s hae eee 192 Pointer Conversion 192 Explicit Type Concersions Typecasting 193 Declarations 193 Declarations and Definitions 194 Declarations and Declarators 194 PC 195 Linkage Rules 5 bie dhe 195 Internal Linkage Rules 196 External Linkage Rules 196 Storage Classes ee 196 AUO ene te ne Bie BOD RI Ue Bie a PULS 197 hcec 197 Stale TDI 197 do RE Ro E e as 197 Type Qualifier dec Esdras 197 Qualifiers Const i so 197 Qualifier Volatile 198 Typedet Speciet ce eerta Oe Ave te Ando ea 198 asm Declarations 198 Initialization i PS 200 Automatic Initialization 200 FUNCIONS 22225 tee Gale ee eee he RR 20
77. 2 and 1 2 inclusive atan Prototype doublie atan double f Function computes the arc tangent of parameter f that is the value whose tan Deseription gent is The return value is in radians between 2 and 1 2 inclusive atan2 Prototype double atan2 double y double x This is the two argument arc tangent function It is similar to computing the arc tangent of 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 1 inclusive Description ceil Function returns value of parameter x rounded up to the next whole number cos 15 Function returns the cosine of in radians The return value is from 1 to 1 568 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries cosh Prototype double cosh double x Function returns the hyperbolic cosine of x defined mathematically as e e 2 If Description the value of x is too large if overflow occurs the function fails eval poly Prototype Prototype static double eval poly double x const double code d int n Function Calculates polynom for number with coefficients stored in qj for Description degree n exp Prototype double exp double x Function s the value of e the base of natural logarithms raised to the Desc
78. 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 i 4 hi nibble 4 high byte 8 myunsigned which declares the structured type myunsigned containing three components lo nibble bits 3 0 ni nibble bits 7 4 and high byte bits 15 8 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 pre viously declared myunsigned like this This example writes low byte of bit field of myunsigned type to PORTO myunsigned Value For PORTO void main Value For PORTO lo nibble 7 Value For PORTO hi nibble 0 0 char void amp Value For PORTO typecasting 1 address of structure to pointer to void 2 pointer to void to pointer to char 3 dereferencing to obtain the value 190 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Type Conversions The mikroC PRO for PIC 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 P
79. End DAC module connections unsigned int value void InitMain TRISBO bit 1 Set RAO pin as input TRISB1 bit 1 Set RAL pin as input Chip Select 1 Deselect DAC Chip Select Direction 0 Set CS pin as Output Soft SPI Init Initialize Soft SPI 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 Ox0F Store valueDAC 11 8 to temp 3 0 temp 0x30 Define DAC setting see MCP4921 datasheet Soft SPI Write temp i Send high byte via Soft Send Low Byte temp valueDAC Store valueDAC 7 0 to temp 7 0 Soft SPI Write temp Send low byte via Soft SPI Chip Select 1 Deselect DAC chip void main ANSEL 0 turn off analog inputs MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 431 7 Libraries mikroC PRO for PIC ANSELH 0 InitMain Perform main initialization value 2048 When program starts DAC gives py the output in the mid range while 1 Endless loop if RAO bit amp amp value 4095 If RAO button is pressed value Pe increment value else if RAl bit amp amp value gt 0 If RAL button is pressed value 27 decrement value DAC Output value Send value to DAC chip Delay ms 1 Slo
80. Functions Sorted By Size Chart Functions Sorted By Address Chat Functions Tree Summary Project Name C Program FleslMiroelektronkalmnkroC PRO Time 2 24 2009 8 47 11 AM for PIC Examples Development SystemsiEasyPICSiGlcdiGicd mappi wwew mbroe com ROM Memory Constants Displays ROM memory constants and their addresses Statistics Brint to file RAM Memory Usage ROM Memory Constants Used RAM Locations FRLocations ROM Memory Usage ROM Memory Functions Sorted By Neme Functions Sorted By Size Functions Sorted By Address Functions Sorted Name Chart Functions Sorted By Size Chart Functions Sorted By Address Chat Functions Tree Summary Project Name C Program FleslMbroelektronkalmkroC PRO Time 2 24 2009 8 47 11 AM for PIC Exemolesi Development Systems EasyPICS Gled led mbroe com 50 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Function Sorted by Name Sorts and displays functions by their addresses symbolic names and unique assembler names Functions Sorted by Size Sorts and displays functions by their size in the ascending order Functions Sorted By Size MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 51 2 Environment mikroC PRO for PIC Functions Sorted by Addresses Sorts and dis
81. PORTB 0 TRISB Oxff set PORTB as input for buttons PORTD 0 OF set PORTD as output Ethernet Init myMacAddr myIpAddr Ethernet FULLDUPLEX Initialize Ethernet controller dhcp will not be used here so use preconfigured addresses Ethernet confNetwork ipMask gwlpAddr dnsIpAddr MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 319 7 Libraries mikroC PRO for PIC while 1 do forever if necessary test the return value to get error code Ethernet doPacket process incoming Ethernet packets add your stuff here if needed Ethernet doPacket must be called as often as possible otherwise packets could be lost d 320 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries FLASH MEMORY LIBRARY This library provides routines for accessing microcontroller Flash memory Note that prototypes differ for PIC16 and PIC18 families Note Due to the P16 P18 family flash specifics flash library is MCU dependent Since the P18 family differ significantlly in number of bytes that can be erased and or written to specific MCUs the appropirate suffix is added to the names of functions in order to make it easier to use them Flash memory operations are MCU dependent 1 Read operation supported For this group of MCU s only read function is im
82. Parameters filename name of the file that should be assigned for file operations File name should be in DOS 8 3 file name extension format 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 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 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 gt MIKROELE TXT In this case last 3 characters of the string are considered to be file extension file cre attr file creation and attributs flags Each bit corresponds to appropriate file attribut o9 Red 6 0x40 Device internal use only never found on disk File creation flag If file does not exist and this flag is set Description new file with specified name will be created Note Long File Names LFN are not supported MMC SD MMC library must be initialized for file operations See Requires _ Init Create file with archive attribut if it does not already exists Fat Assign MIKROELE TXT
83. Read signal Description 6963 dataPort at 6963 ctrlwr at extern sfr sbit T6963C ctrlrd extern sfr sbit T59630 extern sfr sbit T60963C 6963C ctrlrd at bit Command Data sbit T6963C ctrlcd at signal lest ae Reset signal 530 extern sfr extern sfr T6963C ctr extern sfr T6963C gtr extern sfr T6963C ctrl sbit wr Direction it Direction it Direction sbit T6969C Ctrl lrst Direction Direction of the Write pin Direction of the Read pin Direction of the Data pin Direction of the Reset pin T6963C ctrlwr RISC2 bit r6963C ctrird TRISCL bit r6963C etrlied i RISCO bit at TRISCA bit Direction Direction Direction 6963 ctrlrst Direction MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Routines T6963C init T6963C writeData T6963C writeCommand T6963C setPtr T6963C waitReady 6963 fill T6963C dot T6963C write char T6963C write text T6963C line T6963C rectangle T6963C box T6963C circle T6963C image T6963C sprite T6963C set cursor Note The following low level library routines are implemented as macros These macros be found in the 76963c n header file which is located in the T6963C example projects folders T6963C clearBit
84. SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Note Once the MMC SD card is initialized the user can reinitialize at higher speed See the Mmc Init and Mmc Fat Init routines External dependencies of MMC Library The following variable must be defined in all projects Description using MMC library extern sfr sbit Chip select pin sbit Mme Chip Select at Chip Select P pin RCZ bit extern sfr sbit Direction ofthe 5 Mos il chi vid Mme Chip Select Direction Pes chip Select pin at TRISC2 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 Size Mmc Fat Get Swap File MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 369 7 Libraries mikroC PRO for PIC 370 Init Prototype unsigned char Mmc Init 0 if MMC SD card was detected and successfuly initialized 1 otherwise Initializes hardware SPI communication The function returns 1 if MMC card is Description present and successfuly initialized otherwise returns 0 Init needs
85. SPI Glcd Rectangle 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 coordinate of the upper left rectangle corner Valid values 0 63 x bottom right X coordinate of the lower right rectangle corner Valid val Description ues 0 127 y bottom right y coordinate of the lower right rectangle corner Valid val ues 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 Requires GLCD needs to be initialized for SPI communication see Spi Glcd Init routines Draw a box between dots 5 15 and 20 40 Spi Gled Box 5 15 20 40 1 SPI Glcd Box void SPI Glcd Box char x upper left char y upper left char x bottom right char y bottom right char color Nothing 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 Description 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 determin
86. T6963C setBit 6963 negBit T6963C displayGrPanel T6963C displayTxtPanel T6963C setGrPanel T6963C setTxtPanel T6963C panelFill T6963C grFill T6963C txtFill T6963C cursor height T6963C graphics T6963C text T6963C cursor T6963C cursor blink MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 531 7 Libraries mikroC PRO for PIC T6963C Init void T6963C init unsigned int width unsigned char height unsigned char fntW Nothing Initalizes the Graphic Lcd controller Prototype Parameters width Width of the GLCD panel height height of the GLCD panel ntw font width 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 Schematic Description Global variables T6963C dataPort Data Port T6963C ctrlwr Write signal pin T6963C 1 Read signal pin T6963C ctrlicd Command Data signal pin T6963C ctrirst Reset signal pin T6963C ctrlwr Direction Direction of Write signal pin T6963C ctrlrd Direction Direction of Read signal pin T6963C ctrlcd Direction Direction of Command Data signal pin T6963C ctrlrst Direction Direction of Reset signal pin must be defined before using this function 532 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for P
87. The mikroC PRO for PIC treats objects declared with the const 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 197 6 Language Reference mikroC PRO for PIC For example const double PI 3 14159 Qualifier Volatile The qualifier volatile implies that a variable may change its value during runtime independently from the program Use the volatile modifier to indicate that a variable can be changed by a background routine an interrupt routine or I O port Declaring an object to be volatile warns the compiler not to make assumptions concerning the value of an object while evaluating expressions in which it occurs because the value could be changed at any moment Typedef Specifier The specifier typedef introduces a synonym for a specified type The typedef dec larations are used to construct shorter or more convenient names for types already defined by the language or declared by the user The specifier typedef stands first in the declaration typedef lt type definition gt synonym The typedef keyword assigns synonym to lt 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
88. 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 Description OMM tmax time seconds to wait for an reply Note The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time Note 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 Reauires Ethernet module has to be initialized See SPI Ethernet Init q Available for PIC18 family MCUs only unsigned 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 467 7 Libraries mikroC PRO for PIC SPI Ethernet initDHCP Prototype unsigned char SPI Ethernet initDHCP unsigned char tmax 1 network parameters were obtained successfully 0 ot
89. column Starting position column number text text to be written Requires The Lcd module needs to be initialized See Lcd Init routine ind text Hello on Led starting from row 1 columm 3 Qut 3 Herligt yz Lcd Out CP Prints text on LCD at current cursor position Both string variables and literals can be passed as a text Deseripuen Parameters text text to be written Requires The Lcd module needs to be initialized See Lcd Init routine Write text Here at current cursor position Led Out CP Here MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 353 7 Libraries mikroC PRO for PIC Lcd Chr Prototype void Lcd Chr char row char column char out char Nothing Prints character on LCD at specified position Both variables and literals can be passed as a character Description Parameters row Writing position row number column Writing position column number out char character to be written Requires The Lcd module needs to be initialized See Lcd Init routine 77 Weite character zr at row 2 column 3 Led Ohr 2 3 i y Lcd Chr Cp Prototype void Lcd Chr CP char out char Nothing Prints character on LCD at current cursor position Both variables and literals can be passed as a character Description Parameters out char character to be written Requires The Lcd module needs to be initialized See Lcd Init ro
90. the user code can use the normal interrupt vector at 0x0004 The boot code must avoid using the interrupt vector so it should have a program branch in the address range 0x0000 to 0x0003 The boot code must be programmed into memory using conventional programming techniques and the configuration bits must be pro grammed at this time The boot code is unable to access the configuration bits since they are not mapped into the program memory space 64 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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 PIC 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 TS J Tool Name Tool File Name Press button to open file dialog 0 F lpsthandnameoftheout MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 65 CHAPTER 2 Environment Output settings mikroC PRO for PIC By modifying Output Settings user can configure the content of the output files You can enable or disable for example generation of ASM and List file Also user can
91. 0 break UART1 Write Line if data ok VARTI Write Line Content OK else UART1 Write Line Content Error else if there are errors UARTI Write Line Read Error Signal test end VARTI Write Line Test End mikroC PRO for PIC 382 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection 0cSr 8L Old MMC interface 1234567 MMC Back view MMC back view MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 383 7 Libraries mikroC PRO for PIC ONEWIRE LIBRARY The OneWire library provides routines for communication via the Dallas OneWire protocol for example with DS18x20 digital thermometer OneWire is a Master Slave protocol and all communication cabling required is a single wire OneWire enabled devices should have open collector drivers with single pull up resistor on the shared data line Slave devices on the OneWire bus can even get their power supply from data line 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 nu
92. 222 Selection Statements s e glad Ro Be e n 222 li Statement cric ox soror meee Ae ee eoe S Tek Fon eoe Ac 222 Nested If Statement 223 Switch Statements 223 Nested 2 ios ko d ve meee eee REUS pe 224 Iteration Statements Loops 224 While Statement 52 26 seed dm repere S E adus 224 Statement sace m ace e ao Ww wo dor e a Ron ROC A e da 225 FOr Statement iion rede e Ptr d de dev e c 226 Jump Statements iue xe pe EE RE ER ea 227 Break and Continue Statements 227 Break Statement vised Peek dhe 227 Continue Statement 2 5 227 Goto Statement 228 XII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents Return Statement 222 0 i idR Ra xr xe nee 228 Compound Statements Blocks 229 eicere Cr DEI 229 Preprocessor Directives 229 Line Continuation with Backslash 230 Pm 231 Defining Ma
93. 67 Character Classes 3 55 anta Paderb 68 Metacharacters bere tee 68 Metacharacters Line separators 69 Metacharacters Predefined classes 69 Example Lui eR eder x ped dob pos etl Race 69 Metacharacters Word boundaries 70 Metacharacters Iterators 70 Metacharacters Alternatives 71 Metacharacters Subexpressions 72 Metacharacters Backreferences 72 PRO for ru nane eR dune 73 Command Line Options 2 73 dire TT 74 New Project iiem epe xeu v Rer EROR UD LR 74 New Project Wizard Steps 75 lle qe ET 78 New Project cies 56 rr 78 New Project Wizard Steps 79 Customizing 4 82 Edit Projecti vnc ae caisse dike weaned EROGO E Rec EE is eR Ra RD a 82 Managing Project Group 82 Add Remove Files from Project 82 Project Leve
94. Build current project Build all opened projects Build and program active project Start programmer and load current HEX file Open assembly code in editor Fag Open lisitng file in editor View statistics for current project 22 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Debugger lE Bh ce el 82 f Debugger Toolbar comes with following options Icon Description Start Software Simulator or mikroICD In Circuit Debugger Bi Run Pause debugger Stop debugger E Step into e Step over On Step out gt Run to cursor Toggle breakpoint aZ Toggle breakpoints e Clear breakpoints ad View watch window View stopwatch window Styles Toolbar Office 2003 Blue v Office 2003 Blue Office 2003 Silver Office 2003 Olive Office XP Styles toolbar allows you to easily customize your workspace MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 23 2 Environment mikroC PRO for PIC Tools Toolbar IDAD Tools Toolbar comes with following default options Icon Description Ei Run USART Terminal EEPROM A ASCII Chart Ej Seven segment decoder tool ait Options menu The Tools to
95. ENTER Description The code memory type may be used for allocating constants in program memory data This memory specifier is used when storing variable to the internal data SRAM puts PORTG in data ram sfr data unsigned short PORTG absolute 0x65 rx This memory specifier allows variable to be stored in the Rx space Register file Note In most of the cases there will be enough space left for the user variables in Deseripuien the Rx space However since compiler uses Rx space for storing temporary vari ables it might happen that user variables will be stored in the internal data SRAM when writing complex programs puts y in Rx space Sfr char rx y 136 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 5 mikroC PRO for PIC PIC Specifics sfr This memory specifier in combination with xx data allows user to access spe Description cial function registers It also instructs compiler to maintain same identifier in C and assembly eee 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 Accessing individual bits SFRs Constants Functions MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 137 5 PIC Specifics mikroC PRO for PIC 138 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FO
96. Ethernet putConstString buffer put a const string into Ethernet controller s buffer Ethernet getByte Prototype unsigned char Ethernet getByte Returns Byte read from Ethernet controller s RAM This is MAC module routine It fetches a byte from address pointed to by current Ethernet controller s read pointer ERDPT Ethernet module has to be initialized See Ethernet Init char buffer Description buffer Ethernet getByte read a byte from Ethernet con troller s buffer Ethernet getBytes void Ethernet getBytes unsigned char ptr unsigned int addr Prototype 4 pos 3 unsigned char This is MAC module routine It fetches equested number of bytes from Ethernet controller s RAM starting from given address If value of OXFFFF is passed as the address parameter the reading will start from current Ethernet controller s read pointer ERDPT location Parameters ptr buffer for storing bytes read from Ethernet controller s RAM addr Ethernet controller s RAM start address Valid values 0 8192 n number of bytes to be read Ethernet module has to be initialized See Ethernet Init char buffer 16 Description Ethernet getBytes buffer 0 100 16 read 16 bytes starting from address 0x100 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Ethernet UserTCP unsigned int E
97. Expander Set PullUpsPortA Prototype Description Requires void Expander Set PullUpsPortA char ModuleAddress char Data Nothing The function sets Port Expander s PortA pull up down resistors Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up down resistors configuration Each bit corresponds to the appropriate pin of the 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 396 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Expander Set PullUpsPortB Prototype void Expander Set PullUpsPortB char ModuleAddress char Data Nothing The function sets Port Expander s PortB pull up down resistors Parameters Description ModulcAddress 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 Requires Port Expander must be initialized See Expander Init Example Set Port Expander s PORTB pull up resistors Expander Set PullUpsPortB 0 OxFF Expander Set PullUpsPortAB void Expan
98. Menu Options ipie 52 25 e edule 27 Tools Menu B e da 28 Help Menu Options i d Gaede eb tia eg wah Ghd eed ee 29 Keyboard Shortcuts 2 2 2 30 IDE OV6etVIBW 1s cessere ga a Badu ype Gls Besa EE 32 Customizing IDE Layout eee 33 Docking Windows 2 2 2 2 2 222 2 33 Saving Layout 2 34 IV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents Auto Hide XE e a Sce RR OR 35 Advanced Code Editon pe Lr Ea ew oe boe Roe 36 Advanced Editor Features 36 Code Assistant 37 Code Folding eee a Re Ae eto elec eed 37 Parameter Assistant 38 Code Templates Auto Complete 38 Auto 2 nat ulin dane e Baek Bale sues ae 39 Spell CHECKED 2 52 39 BOOKMAMNKS 225552 Sen et
99. PORTAS matches string PORTA only if it s at the end of line PORTA matches string PORTA only if it s the only string in line PORT r matches strings like PORTA PORTB PORT1 and 50 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 uni code org unicode reports tr18 Metacharacters Predefined classes w an alphanumeric character including W a nonalphanumeric character ld a numeric character 1D a non numeric character 15 any space same as t n r f S a non space You may use w d and s within custom character classes Example routi de matches strings like xoutiie routi6e and so but not routine routime and 50 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 69 2 Environment mikroC PRO for PIC Metacharacters Word boundaries A word boundary b is a spot between two characters that has an alphanumeric character w one side and a nonalphanumeric character W on the other side in either order counting
100. Pret 56 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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 Use this EEPROM definition is checked compiler will generate Intel hex file project name ihex that contains data from EEPROM editor When you run mikroElektronika programmer software from mikroC PRO for PIC IDE project name hex file will be loaded automatically while i hex file must be loaded manually mikroElektroniks EEPROM Tool E E PROM Editor F Use Eeprom in project Help Device EEPROM Size EEPROM Fill EEPROM File Bytes alue Ox FF Fill Load Save EEPROM Data 0 IDE FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF DTE rr rr rr rr rr FF FF rr FF rr FF rr rr FF DEB FF FF FF FF FF FF FF FF FF FF FF FF FF PPHYPYTPYYYYYYYY 003 YYYYYYYYYYYYYYYY ITE FF FF FF FF FF FF FF yy 0060 FF FF
101. SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SETJMP LIBRARY This library contains functions and types definitions for bypassing the normal function call and return discipline The type declared is jmp buf which is an array type suitable for holding the infor mation needed to restore a calling environment Type declaration is contained in sejmp16 h and setjmp18 h header files for PIC16 and PIC18 fam ily mcus respectively These headers can be found in the include folder of the compiler The imple mentation of this library is different for PIC16 and PIC18 family mcus For PIC16 family Setjmp and Longjmp are implemented as macros defined in setjmp16 h header file and for PIC18 family as functions defined in setjmp library file Note Due to PIC16 family specific of not being able to read write stack pointer the program exe cution after Longjmp ivocation occurs depends on the stack content That is why for PIC16 fam ily only implementation of Setjmp and Longjmp functions is not ANSI C standard compliant Library Routines Setjmp Longjmp Setjmp Prototype int setjmp jmp buf env if the return is from direct invocation it returns 0 if the return is from a call to the longjmp it returns nonzero value This function saves calling position jmp for later use by longjmp The Description parameter array of type jmp buf suitible for holding the information
102. SPI Ethernet arpResolve IpAddr 5 get MAC address behind the above IP address wait 5 secs for the response MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 465 7 Libraries mikroC PRO for PIC SPI Ethernet sendUDP unsigned char SPI Ethernet sendUDP unsigned char destIP unsigned int sourcePort unsigned int destPort unsigned char pkt unsigned int pktLen 1 UDP packet was sent successfuly 0 otherwise This is UDP module routine It sends an UDP packet on the network Parameters Description destIP remote host IP address sourcePort local UDP source port number destPort destination UDP port number pkt packet to transmit pktLen length in bytes of packet to transmit Requires Ethernet module has to be initialized See SPI Ethernet Init 4 Available for PIC18 family MCUs only unsigned char IpAddr 4 192 168 ds E remote IP address SPI Ethernet sendUDP IpAddr 10001 10001 Hello 5 send Hello message to the above IP address from UDP port 10001 to UDP port 10001 466 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI Ethernet dnsResolve unsigned char SPI Ethernet dnsResolve unsigned char host unsigned char tmax Prototype pointer to the location holding the IP address the requested host name was resolved 0 otherwise
103. 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 cCANSPI CONFIG FLAGS value Refer to datasheet for details Parameters as defined CAN controller s datasheet BRP as defined CAN controller s datasheet PHSEG1 as defined in CAN controller s datasheet PHSEG2 as defined in CAN controller s datasheet PROPSEG as defined in CAN controller s datasheet CONFIG FLAGS is formed from predefined constants see CANSPI constants 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 CONFIGU RATION mode CANSPI module mast 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 CANSPISetBaudRate 1
104. T8 Code Explorer Project Manager Library Manager Bookmarks Messages Macro Editor Windows Description Show Hide toolbars Show Hide debug windows Show Hide Routine List in active editor Show Hide Project Settings window Show Hide Code Explorer window Shift Ctrl Show Hide Project Manager window Show Hide Library Manager window Show Hide Bookmarks window Show Hide Error Messages window Show Hide Macro Editor window Show Window List window MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 19 2 Environment 20 TOOLBARS File Toolbar PAPA DB File Toolbar is a standard toolbar with following options mikroC PRO for PIC Icon Description F Opens a new editor window E source file for editing or image file for viewing Save changes for active window B Save changes in all opened windows E Close current editor Close all editors Print Preview Edit Toolbar 3 Edit Toolbar is a standard toolbar with following options Icon Description Undo last change 2 Redo last change Cut selected text to clipboard Copy selected text to clipboard Paste text from clipboard oy E MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environm
105. TRISBO bit TRISB1 bit TRISB2 bit TRISB3 bit mikroElektronika Lcd4bit example void Move Delay Delay ms 500 void main TRI TRI ANS ANS SB PORTB SB Bl ELH Lcd Cmd 1 Lcd Cmd OF OxFF Oxit 0 OF Led Tne EED LCD CURSOR OFF CLEAR Bos Out l Leod Out 2 6 txt4 Delay ms 2000 Lcd Cmd LCD CLEAR Lcd Out 1 1 txt1 Led i 47 Loop variable Function used for text moving You can change the moving speed here Configure AN pins as digital I O Initialize LCD 77 Clear display OLEI Write Write Clear Write Write text in text in display text in text in first row second row first row second row 356 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Delay ms 2000 Moving text for i 0 1 lt 4 SE 4 Move text to the right 4 times Lcd Cmd LCD SHIFT RIGHT Move Delay while 1 Endless loop for i 0 1 lt 8 itt Move text to the left 7 times Lcd Cmd LCD SBIFT LEFT Move Delay for 0 148 i 1 Move text to the right 7 times Led Cmd LCD SHIFT RIGHT Move Delay MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 357 7 Libraries mikroC PRO
106. at RB3 bit sbit L sbit L sbit L sbit L sbit L sbit L sbit L sbit L sbit L sbit L sbit L sbit L End void m ent CD RS CD D4 CD DS CD DG CD D7 C C e LCD ain 0 CD_EN D D d CD D D CD D7 Direction Direction Direction Direction Direction Direction Keypad Init Lcd Cmd Logd Insti LCD CLEAR LCD CURSOR OFF at TRISB4 bit at TRISBS bit at TRISBO bit at TRISBI bit at TRISB2 bit at TRISB3 bit module connections do Led Qut Leg Out ned Out 1 1 2 p pU i Key T 12 kp 0 Wait do kp Keypad Key Press Keypad Key Click kp while kp oldstate ie iy 27 if yy 0 Reset counter Initialize Keypad Initialize Lcd Clear display Cursor Qtr Write message text on Lcd Reset key code variable for key to be pressed and released Store key code in kp variable Store key code in kp variable 348 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 7 Libraries transform key to it s ASCII value if 27 py fi Er 23 OWI WHA UB YP Q IN v 0 Uncomment this block for break 1 Uncomment this block for keypad4x4 Pressed key
107. bit position sbit LEDB at PORTB FO sbit bit name at sfr name F bit position If you are familiar with a particular MCU and its ports and direc tion registers TRIS you can access bits by their names sbit LEDC at RCO bit sbit bit name at R lt port letter gt lt bit position gt bit sbit TRISCO at TRISCO bit sbit bit name at TRIS port lotter bit positior bit bit type The mikroC PRO for PIC compiler provides a bit data type that may be used for vari able declarations It can not be used for argument lists and function return values bit bf bit variable There are no pointers to bit variables invalid An array of type bit is not valid bit eee anvalud 120 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 4 mikroC PRO for PIC Specifics 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 amp address of is not applicable to these variables Related topics Bit fields Predefined globals and constants Interrupts Interrupts can be easily handled by means of reserved word interrupt mikroC PRO for PIC implictly declares function interrupt which cannot be redeclared Its prototype is void interrupt void For P18 low priorty interrupts reserved word is interrupt low void i
108. 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 compares pairs of bits and returns 1 if the bits are complementary other wise returns 0 bitwise complement unary inverts each bit 4 bitwise shift left moves the bits to the left discards 11 the far left bit and assigns 0 to the far right bit bitwise shift right moves the bits to the right dis cards the far right bit and if unsigned assigns 0 to 11 the far left bit otherwise sign extends Logical Operations on Bit Level Bitwise operators s and perform logical operations on the appropriate pairs of bits of their operands Operator complements each bit of its operand For example 212 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 0x1234 amp 0x5678 equals 0x1230 because 0x1234 0001 0010 0011 0100 023678 4 OTOL 0410 0111 1000 amp 0001 0010 0011 0000 that is 0x1230 Similarly 0x1234 05678 equals 0x567C Oxlz34 056785 equals 0x444C 12345 equals OxEDCB Note Operator can also be a pointer reference operator Refer to Pointers for more information Bitwise Shift Operators Binary operators and move the bits of the left
109. eed s lm e am y gii 306 Ethernet 0 2 306 Ethernet getGwlpAddress 307 _ 5 55 307 Ethernet 308 Ethernet confNetworkK 22 2 2 2 308 Ethernet arpResolve 2 2 309 Ethernet sendUDP pP Ren ben 309 Ethernet 2 2 2 310 Ethernet InttDACk Juss pe degai me RO E d 311 Ethernet doDHCPLeaseTime 312 Ethernet renewDHCP 2 eae ee 312 Library Example gus suce maxi tke dote eoe dor de a Ron RU RUE acide 313 Flash Memory i mne odes Ede cte Efe gd n 321 Library Routines icc lm emi E EI ERA D EE 321 FLASH Read e E eho eee Rupe x Ens Slee ad eee 322 FLASH Read Bytes Ed rr E eh 322 FLASH Write EG e usd A xod Eae 323 FEASH Erase 2 22 22 oe pete PLEBE 324 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR
110. extern sfr sbi SoftSpi SDO Direction bit i Direction of the Clock pin 5o tSpi CLK Direction Direction 55 em at TRISC3 bit 428 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Library Routines Soft Spi Init Soft Spi Read Soft Spi Write Soft Spi Init Configures and initializes the software SPI module Chip Select Direction SoftSspi SDI Direction SoftSpi SDO Direction Direction of the Chip Select pin Direction of the Data in pin Direction of the Data out pin Direction of the Data clock pin must be defined before using this function Global variables Chip Select Chip Select line SoftSpi SDI Data line SoftSpi spo Data outline SoftSpi Data clock line Requires Fa i SoftSpi CLK Direction Di Software SPI module connections at RCO bac at RC4 bit at RC5 bit at RC3 bit sbit Chip Select sbit SoftSpi S bi sbit SoftSpi 5 Eo sbit SoftSpi CI Bor shit Chip Select sbit SoftSpi SDI sbit SoftSpi SDO sbit SoftSpi CLK Di i End Software SPI module Soft SPI i DBDuregtuon Direction Direction Direction at TRISCO bit at TRISCA bit at TRISCS bit at TRISC3 bit connections Init Soft SPI CHAPTER 7 Libraries MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 429 7 Libraries mikroC PRO for PIC Soft Spi Read Prototyp
111. getRequest 10 0 if memcmp getRequest httpMethod 5 only GET method is supported here return 0 316 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries httpCountert one more request done if getRequest 5 s if request path name starts with s store dynamic data in 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 add AN2 value to reply IntToStr 2 dyna len putConstString var 2 len putString dyna len putConstString add AN3 value to reply IntToStr ADC Read 3 dyna len putConstString var AN3 len putString dyna len putConstString add PORTB value buttons to reply len putConstString var PORTB IntToStr PORTB dyna 7 len putString dyna len putConstString add PORTD value LEDs to reply len putConstString var PORTD IntToStr FORTD dyna 2 len putString dyna len putConstString add HTTP requests counter to reply IntToStr httpCounter dyna len putConstString var REQ len putString dyna len putConstString else if getRequest 5
112. the translation unit The syntax is if constant expression 1 section 15 telif constant expression 2 sectron 2 gt telif constant expression n section n else final gt fendif Each i directive in a source file must be matched by a closing directive Any number of e1i directives can appear between i and endif directives but at most one 1 directive is allowed The 15 directive if present must be the last directive before endif sections be any program text that has meaning to compiler or preprocessor The preprocessor selects a single section by evaluating constant expression fol 236 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference lowing each if or 1 directive until it finds a true nonzero constant expres sion The constant expressions are subject to macro expansion If all occurrences of constant expression are false or if no ei directives appear the preprocessor selects the text block after the cise clause If the else clause is omitted and all instances of constant expression in the 1 block are false no section is 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 i directive Th
113. 1 Ox3FAA 2 Ox3FAA 3 Ox3FAA 4 5 Ox3FAA 6 Ox3FAA 7 Qx3FAA 8 Ox3FAA 9 Ox3FAA 10 Ox3FAA 11 12 Ox3FAA 13 Ox3FAA 14 Ox3FAA 15 void main ANSEL 0 Contigure AN pins as digital 1 0 ANSELH 0 PORTB 0 Initial PORTB value TRISB 0 Set PORTB as output PORTC 0 Initial PORTC value TRISC 0 Set PORTC as output Delay ms 500 All block writes to program memory are done as 16 word erase by eight word write operations The write operation is edge aligned and cannot occur across boundaries Therefore it is recommended to perform flash writes in 16 word chunks That is why lower 4 bits of start address 3 0 must be zero Since FLASH Write routine performs writes in 4 word chunks we need to call it 4 times in a row addr 0x0430 starting Flash address valid for P16F887 for i 0 i lt 4 i Write some data to Flash Delay ms 100 FLASH Write addr i 4 dataAR i Delay 5 500 addr 0x0430 for 1 ax 16 ift data FLASH Read addr P16 s FLASH is 14 bit wide so Delay us 10 two MSB s will always be 00 PORTB data Display data on PORTB LS Byte PORTC data gt gt 8 and PORTC MS Byte Delay ms 500 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 325 7 Libraries mikroC PRO for PIC GRAPHIC L
114. 179 67 SPI T6963C WHITE Draw a cross SEI 65963 Iine 0 0 239 127 SPI T6963 WHITE SPI T69636 line l0 127 239 0 SPI T6963C WHITE Draw solid boxes x SPI T69630 box 0 0 239 9 SPI 76963 WHITE SPI T6963C box 0 119 239 127 SPI T6963C WHITE Draw circles mr SPI T6963C circle 120 64 10 SPI T6963C WHITE SPI T6963C circle 120 64 30 SPI T6963C WHITE SPI T6963C cirole 120 64 50 SPI T6963C WHITE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 525 CHAPTER 7 Libraries mikroC PRO for PIC SPI T6963C circle 120 64 70 SPI T6963C WHITE SPI 109630 cirole 120 64 90 SPI 69630 WHITE SPI T6963C circle 120 64 110 SPI T6963C WHITE SPI 6963 circle 120 64 130 SPI T6963C WHITE SPI T6963C sprite 76 4 einstein 88 119 Draw a sprite SPI T6963C setGrPanel 1 Select other graphic panel SPI T6963C image me Fill the graphic screen with a picture while 1 Endless loop If PORTA is pressed toggle the display between graphic panel 0 and graphic 1 ep if bit panel panel amp 1 SPI T6963C displayGrPanel panel Delay ms 300 PORTA 1 is pressed display only graphic panel af else if RAl bit SPI T6963C graphics 1 SPI T6963C text 0 Delay 5 300 PORTA 2 is pressed display only text panel ep else if 2 bit
115. 8x8 0 Column number select Configure AN pins as digital I O 6369C 128 8 graphics and text display at the same time 1 0 T6963C ROM MODE XOR im T6963C ROM MODE XOR 547 CHAPTER 7 Libraries mikroC PRO for PIC 8 pixel height Move cursor to top left Cursor off T6963C WHITE T6963C WHITI pn E IM E Draw a sprite Select other graphic panel Cursor Pr 169636 cursor T6963C set cursor 0 0 T6963C cursor 0 Draw rectangles 769636 rectangle 0 0 239 127 T69630 recteangle 20 20 219 107 T6963C rectangle 40 40 199 87 T6963C WHIT T6963C rectangle 60 60 179 67 T6963C WEITE Draw Cross a T69630 lzme 0 0 239 127 T6963C WHIT T6963C line 0 127 239 0 T6963C WHITE Draw solid boxes x T6963C 0 0 239 8 T6963C WHITE T6963C Dox 0 119 239 127 159630 WHET Draw circles ur T6963C 120 64 10 T6963C0 WHITE T6963C circle 120 64 30 T6963C WHITE T6963C circle 120 64 50 T6963C WHITE T6963C circle 120 64 70 T6963C WHITE T69630 120 64 90 T6963C WHITE T6963C circle 120 64 110 T6963C WHITE T6963C circle 120 64 130 T6963C WHITE T6963C sprite 76 4 einstein 88 119 T6963C sectGrPane l 1 T6963C_image mC fori 4 Endless loop
116. CHAPTER 2 Environment mikroC PRO for PIC IDE OVERVIEW The mikroC PRO for PIC is an user friendly and intuitive environment 8 en ene ok E Ome ame SC The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant Auto Correct for common typos and Code Tem plates 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 Error Window displays all errors detected 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 PIC 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 proj ect is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F12 32 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
117. Control RS 485 Transmit Receive operation mode f i i connate vini Direction of the 5 485 8025 RS485 rxtx pin direc T it R RS485 rxtx pin direc tion pin tion at TRISC2 bit 410 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD extern sfr sbit sbit RS485 rxtx pin at REOS Dit RS485 rxtx pin 7 mikroC PRO for PIC Libraries Library Routines RS485master Init RS485master Receive RS485master Send RS485slave Init RS485slave Receive RS485slave Send RS485Master Init Initializes MCU as a Master for RS 485 communication Global variables RS485 rxtx pin this pin is connected to RE DE input of RS 485 transceiv er see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Requires RS485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this function UART HW module needs to be initialized See UART1_Init RS485 module pinout sbit RS485 rxtx pin direction at RC2 bit transmit receive control set to PORTC B2 Pin direction sbit RS485 rxtx pin direction at TRISC2 bit RxTx pin direc tion set as output VARTI Init 9600 initialize UART module RS485Master Init intialize MCU as a Master for RS 485 communication MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 411 7 Libraries mik
118. E Eur 496 Lcd CMs ee ooh x Roe EXERCERE A RR EDO 496 Available LCD 497 Library Example 498 HW Connection 0 499 SPI LCD8 8 bit interface 500 External dependencies of SPI LCD Library 500 Library Routines 500 Spi Led8 Config serie esha Roe etre dnm ROSE 501 Spi Led8 Oul Meee ee Bam CIRCA 501 Spl_Led8 Out Op J c edere pre bre reed orte Sa Dieu Rs 502 Led8 een Rude vea ehe sp Ee ud e e DR end 502 Spi Led8 Chr Gp uus ke sa cesta Rea Rus Rod ROS 503 Spi qoid adu Endo dte e Rit 503 Available LCD 504 Library Example 505 HW Connection 2 dae Rus 506 SPI T6963C Graphic LCD 507 External dependencies of Spi T6963C Graphic LCD Library 507 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXI Table of Contents mikroC PR
119. EMBEDDED WORLD XV Table of Contents mikroC PRO for PIC FLASH Erase Write 22 2 nis 324 Library Example iss cur eee eee DESDE Re LR DN 325 Graphic EIbrary 5 eoe Eros Roin Rapid de 326 External dependencies of Graphic LCD Library 326 Library Routines 327 CIS MP mE 328 Gled Set Side epe ou non me Box de Sot dd dou a Res ROS RAE n 329 e PEDE 329 Glcd Set iion rg eh DE 330 Gled_Read Data sesat es aa crina eos sco domi ior RR S RU DR 330 Glcd Write Data 331 Gled Fill need or Bk eec ep pre RE eed a Bede 331 Cm eee ee eee ee 332 Gled EE 332 Glcd V LING 22 0 es 4e em eee he be Ae reese PE IHR Reed dares 333 Gled hi Eine ey ays de Dior SES 333 Gled Rectangle ER EE E Ep tes Pac eee eed 334 Glcd BOX 2 22 2542 Pe eee ele a recreate exer edes 334 Glcd P 335 Gled Sete FONE 335 Glcd Write Char eee eee EEA heed ee ae Uis 336 Gled Write inu Rp Rer ARR Shales aoe 337 Glcd 222 22 12 hem x Ab bee hoes Pee eee oe 337 Library
120. ER D iet E or Rond 421 External dependecies of Soft I2C Library 421 Library Routines 421 Soft 12C Init 422 Soft I2C Start 2c cede id we ere era ye Pa eu RR ERN d 422 SOM 2C ead uses esL EUER ERA PUR ee menu Spree 423 Soft 12 Witte 133 s died de etn dog S rc Epl dius cun 423 Soft 1265100 dean a Ce Rab Ea RR A Re Y cus 424 SOM 2C Break EEG See ae 424 Library Example 425 Software SPI Library c ba pok aote Ro OS oss 428 External dependencies of Software SPI Library 428 Library Routines 429 Soft aoo ERREUR ERA ERE Rae 429 Soft Read v Sede no sse e Edd egt dont Raro EIE 430 Soft SPI 2222 222522100121 hb bebe 430 Library Example 1 25 geese e RE ER ELDER Rees 431 Software Library s nee eee eA SE Anke e dee 433 Library ROUUNGS ure shoe kk on Re SOLUS Ros 433 Soft soca aes te GPa a ong ova E rer d tes 434 Soft U
121. FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Replace Text Dialog box for searching for a text string in file and replacing it with another text string Search for mikroElektronika mikroE 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 Text to find 90 Options MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 17 CHAPTER 2 Environment mikroC PRO for PIC 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 Related topics Keyboard shortcuts Edit Toolbar Advanced Edit Toolbar 18 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC VIEW MENU OPTIONS Toolbars Debug Windows m Routine List Project Settings Code Explorer Library Manager Bookmarks Messages Macro Editor Project Manager Shift Ctrl F11 Windows CHAPTER 2 Environment File Toolbars Debug Windows T Routines List Project Settings
122. FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment SOFTWARE SIMULATOR OPTIONS Mme Key icon Description Key Icon Start Start Software Simulator F9 Run Pause Run or pause Software Simulator F6 Stop Stop Software Simulator Ctrl F2 Toggle breakpoint at the current cursor position To view all breakpoints select Run gt View Breakpoints from the drop down F5 menu Double clicking an item in the Break points Window List locates the breakpoint Run to cur Execute all instructions between the current ti F4 vel sor instruction and cursor position Execute the current C single or multi cycle instruction then halt If the instruction is a rou F7 p tine call enter the routine and halt at the first instruction following the call Execute the current C single or e multi cycle instruction then halt Execute all remaining instructions in the current routine return and then halt etre FB Related topics Run Menu Debug Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 97 2 Environment mikroC PRO for PIC CREATING NEW LIBRARY mikroC PRO for PIC allows you to create your own libraries In order to create a library in mikroC PRO for PIC follow the steps bellow 1 Create a new C source file see Managing Source Files 2 Save the file in
123. Labels are declared implicitly by writing label name fol lowed by a statement Label names must be unique within a function B 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 pro totype 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 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 0 1 i and double j are visible int j 3 in scope but hidden 164 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference double j out of scope j 1 int j visible 4 i j are both out of scope Name Spaces Name space is a scope within which an identifier must
124. MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Libraries 463 7 Libraries mikroC PRO for PIC 464 SPI Ethernet getlpMask Prototype unsigned char SPI Ethernet getIpMask Ponter to the global variable holding IP subnet mask This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask Note 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 Ethernet module has to be initialized See SPI Ethernet Init 4 Available for PIC18 family only unsigned char 4 user IP subnet mask buffer memcpy IpMask SPI Ethernet getIpMask 4 fetch IP subnet mask SPI Ethernet confNetwork void SPI Ethernet confNetwork char ipMask char gwIpAddr char dnsIpAddr Nothing Configures network parameters IP subnet mask gateway IP address DNS IP address when DHCP is not used Prototype Parameters ipMask IP subnet mask gwIpAddr gateway IP address dnsIpAddr DNS IP address Description Note The above mentioned network parameters should be set by this routine only if DHCP module is not used Otherwise DHCP will override these settings R 2 Ethernet module has to be initialized See SPI Ethernet Init equires Available fo
125. Mmc Fat Get Swap File 378 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XVIII Table of Contents mikroC PRO for PIC Library Example 22 RE 380 HW Connection cane ee xo so nom EE 383 OneWire bIbrapy RO Rp Rot Ea wae eee 384 Library Routines n ip aeiia 384 OW Oe REM LS Lett x 385 iie HER 385 QU MIL MC me 385 library Example shred eae we ter 386 HW Connection dedo e ee ieee Shea 388 Port Expander LBAN nocd xor grati mitate ad RR eee ISTUD us 389 External dependencies of Port Expander Library 389 Library Routines ssa ssi eem be e dx 389 Expander 1 22 pus sr ne eee mee eine iot cui eite 390 Expander R ad Byte 225222222290 kp RR REL VR ERE e ees eed 391 Expander Write 2 391 Expander Read Port 392 Expander Read PortB 222522961 m RE e eh eee 392 Expander Read PortAB
126. New Project Wizard Step 5 5 and to close the wizard 4 Back Finish MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD You have successfully created a new project Click Finish to save the changes Cancel 81 2 Environment mikroC PRO for PIC CUSTOMIZING PROJECTS Edit Project You can change basic project settings in the Project Settings window You 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 PIC IDE provides covenient option which enables several projects to be open simultaneously If you have several projects being connected in some can create a project group The project group may be saved by clicking the Save Project Group Icon e from the Project Manager window The project group may be reopend by clicking the Open Project Group Icon e All relevant data about the project group is stored in the project group file extension mpgroup Add Remove Files from Project The project can contain the following file types source files h header files mc1 binary files pld project level defines files image f
127. OFFE str lt td gt lt td gt lt a href t it gt Toggle lt a gt lt td gt lt tr document write str lt script gt lt table gt lt td gt lt tr gt lt table gt This is HITE request script document write REQ script BODY HTML J 8CKCKCKCK kk kk kk Ck ko ke kk kk kk ok ke ke ke ke e RAM variables i unsigned char myMacAddr 6 0x00 0x14 OxA5 0x76 0x19 0 3 my MAC address unsigned char myIpAddr 4 1019925 168 20 my IP address unsigned char getRequest 15 HTTP request buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 471 7 Libraries mikroC PRO for PIC unsigned char dyna 30 buffer for dynamic response unsigned long httpCounter 0 counter of HTTP requests JRCKCKCKCkCkCkCkCkCkCkCkCk kCk Ck Ck Ck CkCkCkCkCkCkCkCkCkCkCk ck Ck kCk ck k ck k ckck kck KK functions put the constant string pointed to by s to the transmit buffer ay unsigned int putConstString const char unsigned int ctr 0 while s Spi Ethernet putByte stt return ctr pel it will be much faster to use library Spi Ethernet putConstString routine instead of putConstString routine above However the code will be a little pit bigger User should choose between size and speed and pick the implementation that suites him best If you choose to go wi
128. Ow Write amp PORTA 5 OxCC Issue command 5 ROM Ow Write amp PORTA 5 xBE Issue command READ SCRATCHPAD temp Read amp PORTA 5 temp Ow Read amp PORTE 5 lt lt 8 temp Format and display result on Lcd Display Temperature temp Delay ms 500 while 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 387 7 Libraries mikroC PRO for PIC HW Connection 1259 OSCLLATOR O 9IN2 LCD 2X16 Example of 051820 connection 388 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries PORT EXPANDER LIBRARY The mikroC PRO for PIC provides a library for communication with the Microchip s Port Expander 23517 via SPI interface Connections of the PIC compliant MCU and MCP23817 is given on the schematic at the bottom of this page Note Library does not use Port Expander interrupts Note The appropriate hardware SPI module must be initialized before using any of the Port Expander library routines Refer to SPI Library External dependencies of Port Expander Library The following variables must be defined in all projects using Port Expander Library extern sfr sbit Reset line PExpanderCS sbit ExpanderRST i Pi 12 Description SE extern sfr sbit PExpanderRST sbit SPExpanderCS Chip Select line extern sfr sbit
129. Port Expander gt SPI sPLTe963C Trigonometry Sprintf L C Type Sprintl C_Type Sprinti C_Type T6963C Trigonometry CHAPTER 7 Libraries Certain libraries use depend on function and or variables con stants defined in other libraries Image below shows clear repre sentation about these dependen cies For example SPI_Glcd uses Glcd_Fonts and Port_Expander library which uses SPI library This means that if you check SPI_Glcd library in Library manag er all libraries on which it depends will be checked too Related topics Library manager PIC Libraries MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 Libraries mikroC PRO for PIC HARDWARE LIBRARIES ADC Library CAN Library CANSPI Library Compact Flash Library EEPROM Library Ethernet PIC18FxxJ60 Library Flash Memory Library Graphic Lcd Library 1 Library Keypad Library Lcd Library Manchester Code Library Multi Media Card Library OneWire Library Port Expander Library PrintOut Library PS 2 Library PWM Library RS 485 Library Software Library Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Graphic Lcd Library SPI Lcd Library SPI Lcd8 Library SPI T6963C Graphic Lcd Library T6963C Graphic Lcd Library UART Library USB HID Library 242 MIKROE
130. Ps2 Key Read unsigned short Ps2 Key 242 short value unsigned short Prototype 2 Special unsigned short pressed 1 if reading of a key from the keyboard was successful 0 if no key was pressed The function retrieves information on key pressed Parameters value holds the value of the key pressed For characters numerals Description 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 16 a flag for special function keys F1 Enter Esc etc If key pressed is one of these special will be set to 1 otherwise 0 pressed 6 set to 1 if the key is pressed and 0 if it is released 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 amp keydata amp special amp down if down amp amp keydata 16 break while 1 402 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Special Function Keys Key Num Lock Left Arrow 2 t nd Right Arrow Down Arrow Escape Up Arrow Tab BE NN m 8 71 M MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 403 F1 F2 F3 F4 F5 F6 F7 F8 F9 F1 Al C
131. Reference 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 7 remains uninitialized Create a floating point variable q with static modifier and initialize it to 0 254 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 trans lation 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 with out the source lines omitted by conditional preprocessor directives A problem aris es when the same identifier is declared 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 togeth er with an explicit or implicit by default use of the storage class specifier sta
132. SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 363 CHAPTER 7 Libraries mikroC PRO for PIC Library Example The following code is code for the Manchester receiver it shows how to use the Manchester Library for receiving data LCD module connections sbit LCD RS at RB4 bit sbit LCD EN at RB5 bit sbit LCD D4 at RBO bit sbit LCD DS at REI bit sbit LCD D6 at RB2 bit sbit LCD D7 at RBS bit sbit LCD RS Direction at TRISB4 bit sbit LCD EN Direction at TRISB5 bit sbit LCD D4 Direction at TRISBO bit sbit LCD D5 Direction at bit sbit LCD D6 Direction at TRISB2 bit sbit LCD D7 Direction at TRISB3 bit End LCD module connections Manchester module connections sbit MANRXPIN at RCO bits sbit MANRXPIN Direction at TRISCO bit sbit MANTXPIN at bit sbit MANTXPIN Direction at TRISCI bit End Manchester module connections char error ErrorCount temp void main ErrorCount 0 ANSEL 0 Configure AN pins as digital I O ANSELH 0 TRISC FS 0 hod If Initialize LCD Lcd Cmd LCD CLEAR Clear LCD display Man Receive Init Initialize Receiver while 1 Endless loop Led Cmd LCD FIRST ROW Move cursor to the 1st row while 1 Wait for the start byte temp Man Receive amp error Attempt byte receive if temp 0x0B Start byte see Transmitter example break We got the starting seq
133. SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment LIBRARY MANAGER Library Manager enables simple handling libraries being used in a project Library Manager window lists all libraries extencion mcl which are instantly stored in the compiler Uses folder The desirable library is added to the project by selecting check box next to the library name In order to have all library functions accessible simply press the button Check All all libraries will be selected In case none library is needed in a project press the button Clear d and all libraries will be cleared from the project Only the selected libraries will be linked a Library Manager 89 2 1 ADC v Button C Math E stdlib C String C Type CAN SPI Compact Flash 16 Compact Flash Conversions EEPROM FLASH Fonts Glcd Keypad4x4 Lcd Constants Lcd Manchester Mmc_FAT16 Mme One_Wire Port_Expander 52 PWM12 PWM3 45 5485 Software I2C 7 Seftware SPI Software Sound SPI Ethernet SPI Glcd SPI Lcd SPI Lcd SPI T6963C v SPI Sprintf Sprinti Sprint T6963C 4 Jl lt lt Time Trigonometry UART MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 45 2 Environment mikroC PRO for PIC Icon Description p Refresh Library by scanning files in Uses folder
134. SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Uart Init Prototype void 1 Init unsigned long baud rate Initializes desired hardware UART module with the desired baud rate Refer to the Description device data sheet for baud rates allowed for specific If you specify the unsupported baud rate compiler will report an error You need PIC MCU with hardware UART UART1 Init needs to be called before using other functions from UART Library Parameters baud rate requested baud rate Refer to the device data sheet for baud rates allowed for specific Fosc Note Calculation of the UART baud rate value is carried out by the compiler as it would produce a relatively large code if performed on the libary level Therefore compiler needs to know the value of the parameter in the compile time That is why this parameter needs to be a constant and not a variable This will initialize hardware UART1 module and establish the communication at 2400 bps UART1 Init 2400 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 553 7 Libraries mikroC PRO for PIC Uart Data Ready iif dai is ready for ug 0 if there is no data in the receive register Use the function to test if data in receive buffer is ready for reading Requires UART HW module must be initialized and communication established before 4 using this function See UART1_ Init If dat
135. SPI T6963C graphics 0 SPI T6963C text 1 Delay ms 300 PORTA 3 pressed display text and graphic panels else if RA3 bit SPI T6963C graphics 1 SPI T6963C text 1 Delay ms 300 526 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries If PORTA 4 is pressed change cursor ey else if RA4 bit CUES tty if curs 3 curs 0 switch curs case 0 no cursor SPI 6963 cursor 0 break case 1 blinking cursor SPI 6963 cursor 1 SPI TO0563C cursor DlIink l break case 2 non blinking cursor SPI T6963C cursor 1 SPI T69630 cursor break Delay ms 300 Move cursor even if not visible if SPI 17696386 txtCols 1 cposx 0 if cposy SPI T6963C grHeight SPI T6963C CHARACTER HEIGHT cposy 0 SPI T6963C set cursor oposx eposy Delay ms 100 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 527 7 Libraries mikroC PRO for PIC HW Connection Toshiba T6963C Graphic LCD 240x128 Contrast Adjustment Spi T6963C GLCD HW connection 528 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries T
136. TMR2 Slave select enabled PI SLAVE SS ENABLI Slave select disabled PI Sl DIS Data sampling interval Input data sampled in middle of interval Input data sampled at the end of interval SE SPI clock idle state Clock idle HIGH Clock idle LOW SPI edge Data transmit on high to low edge PI HIGH You need PIC MCU with hardware integrated Set 5 1 module to master mode clock Fosc 4 data sampled at the middle of interval clock idle state low and data trans mitted at low to high edge SPI1 Init Advanced SPI MASTER OSC DIV4 SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI LOW 2 HIGH 444 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi1 Read Prototype unsigned short 5 1 Read unsigned short buffer Returns Returns the received data Reads one byte from the SPI bus Description Parameters buf fer dummy data for clock generation see device Datasheet for SPI modules implementation details You need PIC MCU with hardware integrated SPI must be initialized and communication established before using this func tion See SPI1 Init Advanced or SPI Init short take buffer take SPII Read buffer Spi1 Write Prototype void SPI1 Write unsigned short data Writes byte via the SPI bus D
137. TRISB 0 Set PORTB as output PORTB OxFF Port Expander Library uses SPI1 module 5 1 Init Initialize SPI module used with PortExpander If Port Expander Library uses SPI2 module SPI2 Init Initialize SPI module used with PortExpander Expander Init 0 Initialize Port Expander Expander Set DirectionPortA 0 0x00 Set Expander s PORTA to be output input Expander s PORTB pins Expander Set DirectionPortB 0 0xFF Set Expander s PORTB to be Expander Set PullUpsPortB 0 0xFF Set pull ups to all of the while 1 Endless loop Expander Write PortA 0 i Write to expander s PORTA PORTB Expander Read PortB 0 Read expander s PORTB and write it to LEDs Delay ms 100 398 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection 598 z 8 18849514 RC Rea Port Expander HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 399 7 Libraries mikroC PRO for PIC PS 2 LIBRARY The mikroC PRO for PIC provides a library for communication with the common PS 2 keyboard Note The library does not utilize interrupts for data retrieval and requires the oscil lator clock to be at least 6 2 Note The pins to which a PS 2 keyboard is attached should be connected to the pull up resistors Note Al
138. The attempt to nest a comment like this j inte declaration xj fails because the scope of the first ends at the first This gives us xg which would generate a syntax error 146 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference TOKENS Token is the smallest element of a C program that compiler can recognize The pars er 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 PIC recognizes the following kinds of tokens keywords identifiers constants operators punctuators also known as separators Token Extraction Example Here is an example of token extraction Take a look at the following example code sequence inter actttb First note that inter would be parsed as a single identifier rather than as the key word int followed by the identifier er The programmer who has written the code might have intended to write inter but it wouldn t work that way The compiler would parse it into the seven following tokens inter variable identifier ET assignment operator a variable identifier postincrement operator addition operator b variable identifier statement terminator Note that parses as the longest token possible followed by According to the operator pre
139. 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 Requires GLCD needs to be initialized see Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 Gled R ectangle 5 5 40 40 1 Glcd Box 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 Description 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 Requires 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 52 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Glcd Circle void Glcd Circle int x center int y center int radius unsigned Prototype short color Draws a circle on GLCD Parameters x center X coordinate
140. WHITESPACE Whitespace is a collective name given to spaces blanks horizontal and vertical tabs newline characters and comments Whitespace can serve to indicate where tokens start and end but beyond this function any surplus whitespace is discarded For example two sequences int i float f and int 25 float f are lexically equivalent and parse identically to give six tokens int i float E MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 143 6 Language Reference mikroC PRO for PIC 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 char name mikro foo parses into seven tokens including a single string literal token char name mikro foo just one token here Line Splicing with Backslash Y A special case occurs if a line ends with a backslash 1 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 V for PIC Compil r parses into mikroC PRO for PIC Compiler Refer to String Constants for more information 144 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference COMMENTS Comments are pieces
141. Window View Stopwatch Shift F5 Clear Breakpoints Show Hide Watch Window Show Hide Stopwatch Window Disassembly mode Ctrl D Toggle between Pascal source and disas sembly Related topics Keyboard shortcuts Debug Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 27 2 Environment 28 TOOLS MENU OPTIONS mE Programmer F11 USART Terminal Ctrl T EEPROM Editor Ascii Chart Seven Segment Convertor Export Code To HTML LCD Custom Character GLCD Bitmap Editor HID Terminal UDP Terminal mikroBootloader Options mikroC PRO for PIC Tools Description Run mikroElektronika Programmer Run USART Terminal Run EEPROM Editor Run ASCII Chart Run 7 Segment Display Converter Export Code To HTML Generate HTML code suitable for publishing source code on the web Run Lcd custom character Run Glcd bitmap editor Run UDP communication terminal mikroBootloader Open Options window Related topics Keyboard shortcuts Tools Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment HELP MENU OPTIONS Help Fi Migration Document Check For Updates mikroElektronika Support Forums mikroElektronika Web Page How To Register Ab
142. according to the sequence of execution void func33 jy eseesseess rd asm nop Jd longjmp buf 2 3 gt ff void func d esse 22 ports 3 ried if isetjmpibuf 2 portb 1 4 gt else Fi fune33 df meatu exl asm nop EP LT CE gt depends on stack content void main Zr PORTB 0 TRISB 0 Hf asm nop Lumet iesse zi df asm nop fy MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 595 7 Libraries mikroC PRO for PIC SPRINT LIBRARY The mikroC PRO for PIC 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 sprinti These functions take less ROM and RAM and may be more convenient for use in some cases Functions sprintf sprintl sprinti sprintf Prototype sprintf char wh const char f The function returns the number of characters written to destination string sprintf is used to format data and print them into destination 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 es
143. are sent via UART double ww 1 2587538 1 char buffer 15 Function for sending string to UART void UartWriteText char txt while txt UART1 Write txt Function for sending const string to UART void UartWriteConstText const char txt while txt VARTI Write void main UART1 Init 4800 Initialize UART module at 4800 bps Delay ms 10 UartWriteConstText Floating point number representation Write message on UART sprintf buffer 12e ww Format ww and store it to buffer UartWriteConstText r ne format Write message on UART VUartwritetext butter Write buffer on UART sprintf buffer SI2f ww Format ww and store it to buffer UartWriteConstText r nt format Write message on UART UartwritetText butter Write buffer on UART buffer 129 ww Format ww and store it to buffer UartWriteConstText r ng format Write message on UART UartWriteText buffer Write buffer on UART 600 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries 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 d
144. be initialized See Spi Ethernet Init char buffer buffer SPI Ethernet getByte read a byte from ENC28J60 buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 459 7 Libraries mikroC PRO for PIC Spi Ethernet getBytes void SPI Ethernet getBytes unsigned char ptr unsigned int addr unsigned char n Nothing This is MAC module routine It fetches equested number of bytes from ENC28360 RAM starting from given address If value of 0xrrrr is passed as the address parameter the reading will start from current 28 760 read pointer ERDPT location Description 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 Requires 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 0 100 460 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi Ethernet UserTCP unsigned int SPI Ethernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength 0 there should not be a reply to the request Length of TCP HTTP reply data field otherwise This is TCP module routine It is internally called by the lib
145. bit sbit LCD B5 RBI bit sbit ECD at RB2 bit sbit LCD DT at brt sbrt LCD RS Direction at TRISB4 bit LCD EN Direction at TRISB5 bit sbit LCD D4 Direction at TRISBO bit sbit LCD D5 Direction at TRISB1 bit sbit LCD D6 Direction at TRISB2 bit shit BCD DT Direction at TRISBS bit End LCD module connections char text 17 mikroElektronika char i void main PORTB 0 TRISB 0 ANSEL 0 ANSELH 0 Led Init r Lcd Cmd LCD CLEAR Led LCD CURSOR QFEE for 33 i77 xd 4 hed Chr l 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 105 3 mikrolCD mikroC PRO for PIC Step No 2 After successful compilation and PIC programming press F9 for starting mikroICD After mikroICD initialization blue active line should appear PORTB 0 20 30 0 0000 Cycle 0 00 Step No 3 We will debug program line by line Pressing F8 we are executing code line by line It is recommended that user does not use Step Into F7 and Step Over F8 over Delays routines and routines containing delays Instead use Run to cursor F4 and Breakpoints functions All changes are read from PIC and loaded into Watch Window Note that PORTB TRISB ANSEL and ANSELH changed its values 255 to 0 0 0000 Cycle 0 00 106 MIKROELEKTRONIKA SOFTWARE AND HARDWARE
146. can contain bit fields that can be up to 16 bits You cannot take the address of a bit field Note If you need to handle specific bits of 8 bit variables char and unsigned short or registers you don t need to declare bit fields Much more elegant solution is to use the mikroC PRO for PIC 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 normal ly 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 isa 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 In bitfield declarator list you can omit identifi er s to create an artificial padding thus skipping irrelevant bits MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 189 6 Language Reference mikroC PRO for PIC 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
147. choose optimization level and compiler specific settings which include case sensitivity dynamic link for string literals setting described in mikroC PRO for PIC specifics Build all files as library enables user to use compiled library 1 on any PIC MCU when this box is checked or for a selected PIC MCU when this box is left unchecked For more information on creating new libraries see Creating New Library Output Settings V Generate ASM file Include HEX opcodes Output Settings V Include ROM constants Include ROM Addresses V Generate list file V Include debug info V Include source lines in output files Optimization level Compiler V Case sensitive 9 Dynamic link For string literals V Build all files as library Cancel 66 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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 particu lar 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
148. client packet fragmentation is NOT supported Note Due to PIC16 RAM Flash limitations PIC16 library does NOT have ARP DNS UDP and DHCP client support implemented Note 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 responsi bility to increment this variable each second in it s code if any of the clients is used Note For advanced users there are header files eth enc28j60LibDef h and eth enc28j60LibPrivate h Uses P16 and Uses P18 folders of the compiler with description of all routines and global variables relevant to the user implement ed in the SPI Ethernet Library MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 449 7 Libraries mikroC PRO for PIC Note The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines Refer to SPI Library For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the s Set Active routine External dependencies of SPI Ethernet Library The following variables must be defined in all Description projects using SPI Eth ernet Library extern sfr sbit A sbit SPI Ethernet CS SPI Ethernet Cs ENC26J60 chip select pin at bit xtern sfr sbit sbit SPI Ethernet Rst PI Ethernet RST at RCO e S extern sfr sbit SPI Et
149. compliant MCUs Function Declaration Functions are declared in user s source files or made available by linking precom piled libraries The declaration syntax of the function is type function name parameter declarator list The unction name must be a valid identifier This name is used to call the func tion 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 in 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 voic is also allowed MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 201 6 Language Reference mikroC PRO for PIC 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 be used as an argument s type Unlike variable declaration each argu
150. 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 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example SPI T6963C box 0 119 239 127 T6963C WHITE Spi T6963C circle SPI T6963C circle int x int y long r unsigned char pcol Prototype Draws a circle on the GLCD Parameters Description 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 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine E SPI T6963C circle 120 64 110 T6963C WHITE 516 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi T6963C image Prototype void SPI T6963C image const code char 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 PIC pointer to const and pointer to Description RAM equivalency Use the mikroC PRO s integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for display ing on Glcd Note Image dimension must match the display dimension Toshiba Glcd mod
151. 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 long res prototype extern long func long parl long par2 g res fume limit och 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 Limit and ch would be placed 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 Ellipsis Operator The ellipsis consists of three successive periods with no whitespace intervening An ellipsis can be used in the formal argument lists of function prototypes to indicate a variable number of arguments or arguments with varying types For example Void func int chers ch 220 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 any number of addition al arguments MIKROELEKTRONIKA SOF
152. 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 Description Parameters remoteHost Client s IP address remotePort Client s port destPort port to which the request is sent regLength UDP request data field length Note The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply Ethernet module has to be initialized See Spi Ethernet Init This function is internally called by the library and should not be called by the user s code SPI Ethernet getlpAddress Prototype unsigned char SPI Ethernet getlIpAddress Returns Ponter to the global variable holding IP address This routine should be used when DHCP server is present on the network to fetch assigned IP address Description Note 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 Requires Ethernet module has to be initialized See Ethernet Init 4 Available for PIC18 family MCUs unsigned char ipAddr 4 user IP address buffer pads SPI Ethernet getlIpAddress 4 fetch IP address
153. dec laration point in the source code Legal exceptions to this rule Known as forward ref erences 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 162 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 Lvalues Lvalue is an object locator an expression that designates an object An example of lvalue expression is where 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 exam ple is not a modifiable lvalue A pointer to a constant can be changed but its deref erenced value cannot Historically stood for left meaning that Ivalue could legally stand on the left the receiving end of an assignment statement Now only modifiable can legal ly stand to the left of an assignment operator For example if a and b are noncon stant
154. differs from previous Pressed key is same as previous Print key ASCII value on Lcd If counter varialble overflow Prepare value for output switch kp case 10 kp 42 break keypad4x3 case 11 kp 48 break case 12 kp 35 break default kp 48 case 1 kp 49 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 if kp oldstate genae Iy oldstate kp else Chit hed 10 Xp if cnt 255 cnt 0 Led Out 10 T ms WordTostr cut Led Out 2 while 1 10 txt Transform counter value to string txt Display counter value on Lcd MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 349 7 Libraries mikroC PRO for PIC HW Connection 2 8888 8 lt 2 o lt 588 48849214 8888 LCD 2X16 4x4 Keypad connection scheme 350 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries LCD LIBRARY The mikroC PRO for PIC provides a library for communication with Leds with HD44780 compli
155. extern sfr sbit MA Tm sbit MANTXPIN at Transmit line bit Description TXPIN extern sfr sbit MAN Direction of the Receive pin sbit MANRXPIN Direction RXPIN Direction pin at TRISCO bit extern sfr sbit MAN Direction of the Transmit pin sbit MANTXPIN Direction TXPIN Direction pin at TRISC1 bit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 359 CHAPTER 7 Libraries mikroC PRO for PIC 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 0 if initialization and synchronization were successful 1 upon unsuccessful synchronization 255 upon user abort The function configures Receiver pin and performs synchronization procedure in order to retrieve baud rate out of the incoming signal Note In case of multiple persistent errors on reception the user should call this routine once again or Man_Synchro routine to enable synchronization Global variables MANRXPIN Receive line MANRXPIN Direction Direction of the receive pin must be defined before using this function Initialize Receiver sbit MANRXPIN at RCO bit sbit MANRXPIN Direction at TRISCO bit Man Receive Init 360
156. filter flag When set MAC unicast traffic will be 5 Ethernet UNICAST Note 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 282760 module ENC28360 module should be properly cofigured by the means of SPI Ethernet Init routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 7 Libraries 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 Spi Ethernet Disable Prototype void SPI Ethernet Disable unsigned char disFlt Description This is MAC module routine This routine disables appropriate network traffic on the 28760 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 net work 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 disFlt network traffic receive filter flags Each bit corresponds to the appro priate network traffic receive filter const T MAC Broadcast traffic rece
157. int year unsigned short month unsigned short day unsigned short hours unsigned short mins T Retrieves date and time for the currently selected file Seconds are not being Description retrieved since they are written in 2 sec increments The file must be assigned see Mmc Fat Assign get Date time of file unsigned yr char mnth dat hrs mins Prototype file Name MYFILEABTXT Mmc Fat Assign file Name Mmc Fat Get File Date yr mnth dat hrs mins Mmc Fat Get File Size Returns This function returns size of active file in bytes Retrieves size for currently selected file The file must be assigned see Mmc Fat Assign get Date time of file unsigned yr char mnth dat hrs mins file name MYFILEXXTXT Mmc Fat Assign file name mmc size Mmc Fat Get File Size MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 377 7 Libraries mikroC PRO for PIC Mmc Fat Get Swap File unsigned long Mmc Fat Get Swap File unsigned long sectors cnt char filename char file attr 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 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 s
158. integer identifiers with properly allocated memory storage they are both mod ifiable Ivalues and assignments such as 1 a b are legal Rvalues The expression bis notlvalue b a is illegal because the expression on the left is not related to an object Such expressions are sometimes called rval ues short for right values MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 163 6 Language Reference mikroC PRO for PIC 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 func tion function prototype and file These categories depend on how and where iden tifiers are declared B Block The scope of an identifier with block or local scope starts at the declara tion 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 defini tion also have block scope limited to the scope of the function body E 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
159. integral type while expected but s found void func cannot return values continue outside of loop Unreachable code Label redefined void type in expression Too many chars Unresolved type Arrays of objects containing zero size arrays are illegal Invalid enumerator ILevel can be used only with interrupt service routines ILevel value must be integral constant ILevel out of range 0 4 p expected 2 1 found expected but sj found break outside of loop or switch Empty char Nonexistent field Illegal char representation s Initializer syntax error multidimensional array missing subscript Too many initializers of subaggregate At least one Search Path must be specified Not enough RAM for call stack Demo Limit Parameter 5 1 must not be of bit or sbit type Function must not have return value of bit or sbit type 90 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Compiler Warning Messages Bad or missing fosc parameter Default value 8MHz used Specified search path does not exist 251 Specified include path does not exist Result is not defined in function 55 Initialization of extern object Suspicious pointer conversion Implicit conversion of pointer to int Unknown pragma line ignored sj Implicit conversion of int to ptr Generated baud rate is gt s bps error 5 percent Un
160. ipMask 4 255 255 255 91 77 network mask for example 255 259 255 0 unsigned char dnsIpAddr 4 1192 168 20 1 1 DNS server IP address unsigned char getReguest 151 HTTP request buffer unsigned unsigned 314 char long dyna 301 buffer for dynamic response httpCounter 0 counter of HTTP requests MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC RRR Rk kA CKCk KK CKCKCKCkCkCk Ck Ck Ck Ck ck Ck Ck Ck ck Ck ck k ck ck ckck ko functions ur put the constant string pointed to by s to the troller s transmit buffer CHAPTER 7 Libraries Ethernet con y unsigned int purConstString const char s unsigned int ctr 0 while s Ethernet putByte s tt Clete return ctr poy it will be much faster to use library Ethernet putConstString rou tine instead of putConstString routine above However the code will be a little pit bigger User should choose between size and speed and pick the implementation that suites him best If you choose to go with the putConstString def inition above the define line below should be commented out no define putConstString Ethernet putConstString put the string pointed to by s to the Ethernet controller s trans mit buffer unsigned int putString char s unsigned int ctr 0 while s Ethernet putByte s tt
161. is not initialized i e assigned a value so it cannot be used yet Note In case of multiple pointer declarations each identifier requires an indirect operator For example ant pb is same as int int pb int Once declared though a pointer can usually be reassigned so that it points to an object of another type The mikroC PRO for PIC 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 pointer refer to void for details 176 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 The pointer type pointer to void must not be confused with the null pointer declaration void declares that v is a generic pointer capable of being assigned to by any pointer to type value including null without complaint Assignments without proper casting between a pointer to type1 and a pointer to type2 where
162. it has the extern specifier and has initializator or body in case of func itis the typedef 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 1 return x gt y x v yj Defrnitiom variable a int 1 Following line is an error i is already defined ant i Declarations and Declarators The declaration contains specifier s followed by one or more identifiers declara tors The declaration begins with optional storage class specifiers type specifiers and other modifiers The identifiers are separated by commas and the list is termi nated by a semicolon Declarations of variable identifiers have the following pattern storage class type qualifier type varl initl var2 init2 where vari var2 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 194 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language
163. main Globals TypeDef Tags Includes Following options are available in the Code Explorer Icon Description E Expand Collapse all nodes in tree Locate declaration in code 40 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment ROUTINE LIST Routine list diplays list of routines and enables filtering routines by name Routine list window be accessed by pressing Ctrl L You can jump to a desired routine by double clicking on it Used ROM bytes 1029 19 Free ROM byte Sound Project Sound mpe completed 1030 ms successfully 28 Jan 200 10 21 23 Sard expen MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 41 2 Environment 42 mikroC PRO for PIC PROJECT MANAGER Project Manager is IDE feature which allows users to manage multiple projects Several projects which together make project group may be open at the same time Only one of them may be active at the moment Setting project in active mode is performed by double click on the desired project in the Project Manager Project Manager 9 4 LedBlinking mcppi 7j Sources 2 LedBlinking c E Header Files Binaries E Project level defines Image Files 7j Output Files 25 LedBlinking hex 25 LedBlinking asm LedBlink
164. mapping characters Note Not all of the standard functions have been included Note The functions have been mostly implemented according to the ANSI C stan dard but certain functions have been modified in order to facilitate PIC program ming 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 564 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries isalnum Prototype unsigned short isalpha char character Function returns 1 if the character is alphanumeric A Z a z 0 9 otherwise Description returns zero isalpha Prototype Prototype unsignec short isalpha char character Function returns 1 if the character is alphabetic A Z a z otherwise returns Description zero Prototype unsigned short iscntrl char character Function returns 1 if the character is a control or delete character decimal 0 Description 31 and 127 otherwise returns zero isdigit Prototype unsigned short isdigit char character Description Function returns 1 if the character isa TT 0 9 otherwise returns zero isgraph Prototype Prototype unsigned short isgraph char character 2 returns 1 if the character is a printable excluding the space decimal Descri
165. mikroC PRO for PIC provides plenty of examples making it easy for you to go quickly We sug gest that you first consult Projects and Source Files and then start browsing the examples that you re the most interested in MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 1 Introduction mikroC PRO for PIC 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 mikroElek tronika mikroElektronika Associates for software product Software identified above including any software media and accompanying on line or printed docu mentation 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 you the right to use Software in a way provided below This Software is owned by mikroElektronika Associates and is protected by copy right 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
166. need ed for restoring calling environment CONDI NN MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 593 7 Libraries mikroC PRO for PIC Longjmp Prototype void longjmp jmp buf env int val Returns longjmp causes setjmp to return val if val is O it will return 1 Restores calling environment saved in jmp buf by most recent invocation of setjmp macro If there has been no such invocation or function conatinig the invo Description cation of setjmp has terminated in the interim the behaviour is undefined Param eter env array of type buf holding the information saved by corresponding setjmp invocation va 1 char value that will return corresponding setjmp Invocation of Longjmp must occur before return from the function in which Setjmp Requires was called encounters 594 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Example Example demonstrates function cross calling using setimp and longjmp functions When called Setjmp saves its calling environment in its jmp buf argument for later use by the Longjmp Longjmp on the other hand restores the environment saved by the most recent invocation of the Setjmp with the corresponding jmp buf argument The given example is for P16 include Setjmp16 h include Setjmpl6 h jmp buf buf Note Program flow diagrams are indexed
167. negBit erga kr er Ep Ree Ett wm 519 Spi T6963C DisplayGrPanel 519 Spi T6963C displayTxtPanel 519 6963 1 520 T6963C setTxtPanel 2 2 4 520 Spi T6963C panelFll eee Seek eee eae emm RR eee 521 Spi T6963C ood ecco el mn mr ye bI RE perd 521 T6963C E REX RnB OR 521 Spi T6963C cursor height 522 Spi T6963C graphics pee eee a RE 522 6963 55425 ta 522 Spi T6963C CUSO 5 525 oe pee dud oo dne e 523 Spi T6963C cursor blink oes mais rogi RR Ro RS RR ind 523 Library Example 523 FW Connection per eee a b RID Rc 528 T6963C Graphic LCD Library 529 External dependencies of T6963C Graphic LCD Library 530 Library Routines Re Re E EE EE AR es 531 6963 532 T6963C writeData er eal 533 T6963C WriteCommand
168. not provide automatic initialization for objects Unini 200 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference tialized globals and objects with static duration will take random values from mem FUNCTIONS Functions are central to C programming Functions are usually defined as subpro grams which return a value based on a number of input parameters Return value of the function can be used in expressions technically function call is considered to be an expression like any other C allows a function to create results other than its return value referred to as side effects Often the function return value is not used at all depending on the side effects These functions are equivalent to procedures of other programming lan guages 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 PIC Specifics for more information on functions limitations on the PIC
169. 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 mcl 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 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 o from Project Toolbar as 74 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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 new project e Select the device for your project e Setup device clock and choose device flags e Select desired memory model 77 Add project files Click Next to continue Back Next gt Cancel Step One Select the device from the device drop down list New Project Wizard Select the device you want to use Device Name 21227 Back Next gt Cancel MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 75 2 E
170. of the circle center Valid values 0 127 Description center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle line 0 white 1 black and 2 inverts each dot Requires GLCD needs to be initialized see Glcd Init routine Draw with center in 50 50 and radius 10 lcg 905 10 Glcd Set Font Prototvpe void Glcd Set Font const char activeFont unsigned short yp 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 byte aFontWidth width of the font characters in dots aFontHeight height of the font characters in dots Description 220202 number that represents difference between the mikroC PRO for PIC character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroC PRO for PIC 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 Lib GLCDFonts file located the Uses folder or create his own fonts Requires GLCD needs to be initialized see Glcd Init routine Use the custom 5x7 font myfont which starts with space 32
171. of these values For example init CONFIG SAMPLE THRICE 6 CAN CONFIG PHSEG2 PRG ON amp CAN CONFIG STD MSG amp CAN CONFIG DBL BUFFER ON amp CAN CONFIG VALID XTD MSG amp CAN CONFIG LINE FILTER OFF CANInitd2alimge l 1 3 3 1 initi initialize CAN TX MSG FLAGS CAN TX MSG FLAGS are flags related to transmission of a CAN message const char CAN TX PRIORITY BITS 0x03 CAN TX PRIORITY 0 OxFC XXXXXX00 CAN TX PRIORITY 1 OxFD XXXXXX01 TX PRIORITY 2 OxFE XXXXXX10 TX PRIORITY 3 OxFF XXXXXX11 CAN TX FRAME BIT 0x08 CAN TX STD FRAME OxFF XXXXX1XX CAN TX XTD FRAME OxF7 XXXXXOXX CAN TX RTR BIT 0x40 CAN TX NO RTR FRAME OxFF 1 CAN TX RTR FRAME OxBF XOXXXXXX You may use bitwise AND to adjust the appropriate flags For example form value to be used with CANSendMessage send config CAN TX PRIORITY 0 amp CAN TX XTD FRAME amp CAN TX NO RTR FRAME CANSendMessage id data 1 send config MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 251 7 Libraries mikroC PRO for PIC CAN RX MSG FLAGS CAN RX MSG FLAGS are flags related to reception of CAN message If a particular bit is set cor responding meaning is TRUE or else it will be FALSE
172. omitted the function will return a random value from memory Note The statement return in functions of the voia type cannot have expres sion fact the return statement can be omitted altogether if it is the last state ment in the function body 228 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 07 1 lt ny as y Y int temp a i api B airs bl i temp Note that unlike other statements compound statements do not end with semicolon Le 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 con
173. operand by a number of posi tions 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 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 zero This is also true for signed operands if all discarded bits are equal to a sign bit 000001 5 equals 000040 0x3801 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 Shifting operand to the right by n positions is equivalent to divid ing it by 2n S equals OxFFF5 OxFF56u gt gt 4 equals 5 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 213 6 Language Reference mikroC PRO for PIC Bitwise versus 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 equals OxEDCB 0x1234 equals 0 Logical Operators Operands of logical operations are considered true or false that is non zero or zero Logical operators always
174. other words the typedef 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 start ing capital letter this is not required by the mikroC PRO for PIC For example Let s declare a synonym for unsigned long int typedef unsigned long int Distance Now synonym Distance can be used as type identifier Distance i declare variable i of unsigned long int In the typedef declaration as in any other declaration several types can be declared at once For example typedef int Pti Array 10 is a synonym for type pointer to int and Array is a synonym for type array of 10 int elements asm Declarations 198 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference The mikroC PRO for PIC 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 PIC 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 asm asm block of assembly instructions There are two ways to embeding single assemb
175. port bit s Description Parameters b bit mask The function will clear bit x on control port if bit in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI 6963 Config routine clear bits 0 and 1 on control port SPI 6963 clearBit 0x03 Spi T6963C setBit Sets control port bit s Description Parameters b 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 SPI T6963C Config routine bits 0 and 1 om control port SPI T6963C SeLBit 0x03 7 518 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi T6963C negBit Prototype void SPI T6963C negBit char b Nothing Negates control port bit s Parameters Description b bit mask The function will negate bit x on control port if bit x in bit mask is set to 1 Toshiba module needs to be initialized See SPI T6963C Config routine negate bits 0 and 1 on control port SPI T6963C negBit 0x03 Spi T6963C DisplayGrPanel Prototype void SPI T6963C displayGrPanel char n Nothing Display selected graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display graphic panel 1 SPI T6963C displayGrPanel 1 2 Spi_
176. program on a host PIC microcontroller and view variable values Special Function Registers SFR memo ry and EEPROM as the program is running 101 3 mikrolCD mikroC PRO for PIC Step No 1 If you have appropriate hardware and software for using mikrolCD then upon com pletion of writing your program you will have to choose ICD Debug build type Project Settings 3 Segre Name 16 877 8 000000 MHz Choose ICD Debug type if you want to use mikroICD debug Build Type Release ICD Debug Debugger Software mikroICD Step No 2 You can run the mikroICD by selecting Run Debug from the drop down menu or by clicking Debug Icon Starting the Debugger makes more options available Step Into Step Over Run to Cursor etc Line that is to be executed is color high lighted blue by default There is also notification about program execution and it can be found on Watch Window yellow status bar Note that some functions take time to execute so running of program is indicated on Watch Window 102 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC PRO for PIC mikrolCD iB BB Select variable from list text text V Peripherals Freeze 0 0000 Cycle 0 00 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 103
177. services marks are the property of the respective owners MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents CHAPTER 1 CHAPTER 2 CHAPTER 3 CHAPTER 4 CHAPTER 5 CHAPTER 6 CHAPTER 7 Introduction mikroC PRO for PIC Environment MikrolCD In Circuit Debugger mikroC PRO for PIC Specifics PIC Specifics mikroC PRO for PIC Language Reference mikroC PRO for PIC Libraries Table of Contents mikroC PRO for PIC CHAPTER 1 5 s ec A Rave KORR oS ae 2 Wheret6 Start Eod ob gus EATER S Roe i Bens 3 mikroElektronika Associates License Statement and Limited Warranty 4 IMPORTANT READ 4 LIMITED WARRANTY 2 5 HIGH RISK ACTIVITIES 6 GENERAL PROVISIONS 1 44 4 0 6 Technical Support 255555 Eque Robin E P RC ERROR de 7 How to Reglster ou nes pan kac dox baia ke A eee SOR RUE UR 8 Who Gets the License Key 8 How to Get License Key 8 After Receiving the License Key 10 CHAPTER 2 IDE OVetvieW sce gees RE RR
178. short Cf Fat Assign char filename char file cre attr 0 iffile 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 Assigns file for file operations read write delete All subsequent file opera tions 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 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 prop er 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 attributs flags Each bit corresponds to the appropriate file attribut Be mes Demon 79 foor 6 0x40 Device internal use only never found on disk File creation flag If the file does not exist and this flag is 7 0x80
179. size LongToStr signed long size err txt UART1 Write Line err txt for 1 0 i 5000 Write Sector sizer Butter gt VARTI Write Main Uncomment the function s to test the desired operation s void main define COMPLETE EXAMPLE comment this line to make sim pler smaller example MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 291 7 Libraries mikroC PRO for PIC ADCON1 OxOF Configure AN pins as digital CMCON 7 Turn off comparators Initialize UART1 module UART1 Init 19200 Delay ms 10 VARTI Write Line PIC Started PIC present report use fatl6 quick format instead of init routine if a formatting is needed i CE Fat 8 Delay ms 2000 wait for a while until the card is stabilized period depends on used CF card Test start UARTI Write Line Test Start Test routines Uncomment them one by one to test certain features M Create New File ifdef COMPLETE EXAMPLE Create Multiple Files M Open File Rewrite Open File Append Open File Read Delete Pilet Test Exrst Create Swap File endif UART1 Write Line Test End else UARTI Write Line err txt Note Fat Init tries to initial ize a card more than once If card is not present initializa tion may last longer de
180. starting with 0b or 08 are taken to be binary In the absence of any over riding 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 Constants 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 suffix es 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 Floating Point Constants A floating point constant consists of Decimal integer Decimal point Decimal fraction e or E and a signed integer exponent optional Type suffix or F or 1 or L optional Either decimal integer or decimal fraction but not both can be omitted Either dec imal point or letter or E with a signed integer exponent but not both can be omit ted These rules allow conventional and scientific exponent notations Negative floating constants are taken as positive constants with an unary operator minus prefixed The mikroC PRO for PIC limits floating point constants to the range 1 17549435082 10 38 6 80564774407 1038 Here are some examples 0 J 0 0 1 23 fi 1 23 23 45e6 23 45 10 6 2e 5 JU rm 1085 3E 10 Jf T0510 09E34 0 09 10 34 The mikroC PRO for PIC f
181. the imaginary characters off the beginning and end of the string as matching a WW b match a word boundary 1B match a non word boundary Metacharacters Iterators Any item of a regular expression may be followed by another type of metacharac ters 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 at least n times greedy n m at least 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 non greedy similar to 0 1 n exactly n times non greedy n at least n times non greedy n m at least n but not more than m times non greedy So digits curly brackets of the form n m specify the minimum number of times to match the item n and the 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 So digits in curly brackets of the form n m specify the minimum number of times to match the item n and the maximum m The form n is equivalent to n n and matche
182. 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 Sequence pei _ E E pe ps NEN LUNG NND J par a C by sting oF upto 3 oca diis E ry sting ofhex cits pe ry Fr sting of MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 151 6 Language Reference mikroC PRO for PIC Disambiguation Some ambiguous situations might arise when using escape sequences Here is an example Led Out Cpx091 0 Intro This is intended to be interpreted as 09 and 1 0 Intro However the mikroC PRO for PIC 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 Cep ix09 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 constant 118 would be interpreted as a two character constant made up of the characters 11 and 8 because 8 is not a legal octal digit 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 seq
183. 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 Deseripron The format string is read from left to right The first format specification encoun tered refers to the first argument after the parameter and then converts and out puts 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 It d 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 589 7 Libraries mikroC PRO for PIC conversion type Argument Type Output Format Bigned decimal number bnsigned int Unsigned decimal number bnsigned int Unsigned octal number were Unsigned hexadecimal number using 0123456789abcdef int Unsigned hexadecimal number using ud 01234567
184. 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 characters of the string are considered to be file extension 378 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 7 Libraries file attr file creation and attributs flags Each bit corresponds to appropri ate file attribut Ls ot Read ny Archive 6 0x40 Device internal use only never found on disk Note Long File Names LFN are not supported MMC SD card and MMC library must be initialized for file operations See Requires Fat Init Tries to create a swap file whose size will be at least 100 sectors T it succeeds it sends the No of start sector over UART void M Create Swap File Mmc Fat Get Swap File 100 if size lt gt 0 size ue pem Wem ART Write Write _ Write Lo Write Hi _Write Higher size 0 o size i size Write Highest size MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 379 7 Libraries mikroC PRO for PIC Library Example The following example demonstrates MMC library test Upon flashing insert a MMC SD card into the module when y
185. 0 01 the last one 174 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference is mf 4917191 The first element of the 5th row would be m 417 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 commonly used technique when passing arrays as function parameters int 311 2311 4 3 dimensional array of size 3x2x4 void func int n 2 4 we can omit first dimension n 21 1 3 increment the last element void main a You can initialize multi dimensional array with an appropriate set of values within braces For example int a 3 D2 11 2 2 6 3 7 Pointers Pointers are special objects for holding or pointing to memory addresses In the mikroC PRO for PIC 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 gt on a pointer A pointer of type pointer to object of type holds the address of that is points to an object of type Since pointers are objects you can have a pointer pointing to a pointer and so on 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 segmen
186. 00 data buffer sizeof data buffer 322 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries FLASH Write y PICIO void FLASH Write unsigned address unsigned int data for 8 void FLASH Write 8 long address char data void FLASH Write 16 long address char data void FLASH Write 32 long address char data void FLASH Write 64 long address char data Writes block of data to Flash memory Block size is MCU dependent P16 This function may erase memory segment before writing block of data to it MCU dependent Furthermore memory segment which will be erased may be greater than the size of the data block that will be written MCU dependent Therefore it is recommended to write as many bytes as you erase FLASH Write writes 4 flash memory locations in a row so it needs to be called as many times as it is necessary to meet the size of the data block that will be written Description P18 This function does not perform erase prior to write Flash memory that will be written may have to be erased before this function is 4 called MCU dependent Refer to MCU datasheet for details Write consecutive values in 64 consecutive locations starting from 0 0000 unsigned short toWrite 64 initialize array for 0 lt 64 i toWrite i i write contents of the array to the address 0 0000 F
187. 1 3 3 1 canspi config flags MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 261 7 Libraries mikroC PRO for PIC CANSPISetMask Prototype Description void CANSPISetMask char CANSPI MASK long val char CANSPI CON FIG FLAGS Nothing Configures mask for advanced filtering of messages The parameter value is bit adjusted to the appropriate mask registers Parameters CAN MASK CANSPI module mask number Valid values cANSPI MASK costants see CANSPI constants val mask register value CONFIG FLAGS Selects type of message to filter Valid values CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG STD MSG CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG XTD MSG see CANSPI constants 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 valu CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be in config mode for mask settings Set all mask bits to 1 all filtered bits relevanti No
188. 1 Function Declaration 201 Function Prototype 1 202 Function Definition 203 Function Reentrancy ies rni pr ng ER ee rA pe Ea lee 203 Function Calls and Argument Conversion 204 Function Calls 204 Argument Conversions eek ERR ee Enn 204 Operators xta bos 207 Operators Presidence Associativity 208 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XI Table of Contents mikroC PRO for PIC Arithmetic Operators 208 Binary Arithmetic Operators 210 Unary Arithmetic Operators 210 Relational Operators 211 Relational Operators Overview 211 Relational Operators in Expressions 211 Bitwise Operators iios s caos S 212 Bitwise Operators Overview 212 Logical Operations on Bit Level 212 Bitwise Shift Operators
189. 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 1 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 Here are several examples of implicit conversion 9 24 c ok Boil 7 5 1 d 9 932 RY Ban 2m 5 y Suo tob 4 pee Esau quee gg megue Xl SIS Pointer Conversion Pointer types can be converted to other pointer types using the typecasting mecha nism Char int 1p str char ip More generally the cast type will convert a pointer to type pointer to type 192 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Explicit Type Concersions 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
190. 1 and type2 are different types can invoke a compiler warning or error If is a function and isn t or vice versa pointer assignments are illegal If 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 func tion Define a function pointer int ptz2Function float char char Note Thus functions and function pointers with different calling convention argu ment order arguments type or return type is different are incompatible with each other MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 177 6 Language Reference mikroC PRO for PIC 178 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 Delt float a char b char return atbtc pt2Function amp DoIt assignment Example int addC char x char return 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 a
191. 12 18 i8 18 18 i8 10 9 9 9 9 9 9 9 E 9 9 9 9 9 9 9 9 9 137 137 137 137 137 137 137 137 137 137 137 137 137 9 9 9 9 9 9 9 9 9 9 9 13 253 13 195 6 252 0 0 0 0 0 0 0 8 a OG OU mi Copy CODE to Clipboard ver 2 0 1 27012005 System status Win NT like OS 60 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment HID Terminal The mikroC PRO for PIC includes the HID communication terminal for USB commu nication You can launch it from the drop down menu Tools HID Terminal mikroElektronika USB HID Terminal Descriptor HID Devices Info mikroE HID Librar Dell Premium USB Optical Mouse Communication HID Read Write Test Send Appe 3 Send as Typing Send as Number Format ASCII C HEX Clear HID Read Write Test MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 61 2 Environment mikroC PRO for PIC UDP Terminal The mikroC PRO for PIC includes the UDP Terminal You can launch it from the drop down menu Tools UDP Terminal IP Address 192 168 20 25 Port 10001 Send mikroElektronika Send Append CR Send as typing Send as number mikroE lektronika Receive
192. 150 Octal Constants 150 Floating Point Constants 150 Character Constants 151 Escape SEQUENCES 525 Rea ger ee esee c RE 151 Disambiguation i aba oe pepe Added ul 152 string Constans eee eee 152 Line Continuation with Backslash 153 Enumeration Constants 153 Pointer Gonstants menaran PAS oe eee eue 154 Constant Expressions xen ale ioe dee ade 155 Keywords nsu need bid e IG eg Ege de dels bes 156 Identifl amp ES sito ce CA Pe do xr on RAE EES Busca Ep eoa d apos ed 157 Case Sensitivity edendo oro e op 157 Uniqueness and Scope 157 Identifier Examples 157 PUNCtUATOIS o PPP Er 158 suc AT 158 Parentheses PPP 158 c ccr 159 COMMA since Reha Rope 159 Semicolon DE euet cations 159 ates ee eet 160 Asterisk Pointer Declaration 160 Pound Sign Preprocessor Directive
193. 1783 86B SYN lt ETX gt ETB 84 86A 80 2E28 1383 186C 1783 1683 wf B5 f DC 1703 1386 184 1683 1703 800 EC 3008 lt ETX gt ETB t pca i3 ED 301E E9 309E 2F82 F84 2E93 lt amp 5 gt 0 20 _ STATUS Idle 112 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 mikroC PRO for PIC mikrolCD View RAM Memory Debugger View RAM Window is available from the drop down menu View Debug Windows View RAM The View RAM Window displays the map of PIC s RAM with recently changed items colored red Common Errors W Trying to program PIC while mikroICD is active Trying to debug Release build Type version of program Trying to debug changed program code which hasn t been compiled and pro grammed into PIC Trying to select line that is empty for Run to cursor F4 and Toggle Breakpoints F5 functions Trying to debug PIC with mikroICD while Watch Dog Timer is enabled Trying to debug PIC with mikroICD while Power Up Timer is enabled It is not possible to force Code Protect while trying to debug PIC with mikrolCD Trying to debug PIC with mikroICD with pull up resistors set to ON on RB6 and RB7 For correct mikroICD debugging do not use pull ups MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 113 mikroC PRO for PIC MIKROICD ADVANCED BREAKPOINTS mikrolCD provides the possibility to use the Advanced Break
194. 4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries LongintToStr Prototype void LongToStr long input char output 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 Description 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 11 f ag 3700000 three blanks here LongWordToStr Prototype void LongWordToStr unsigned long input char output Nothing 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 positions on the left if any are filled with blanks Description Parameters input unsigned long integer number to be converted output destination string Requires Destination string should be at least 11 characters in length unsigned long jj 3700000 char txt 11 hengiostritay txt txt is 3700000 three blanks here MIKROELEKTRONIKA SOFTWA
195. 63C init routine Emme 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 Description x dot position on x axis y dot position on y axis color color parameter Valid values T6963C_BLACK and T6963C_WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine Example T6963C dot x0 0 pcolor MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD bab CHAPTER 7 Libraries mikroC PRO for PIC T6963C write Char Prototype Description void T6963C write char unsigned char c unsigned char x unsigned char y unsigned char mode Nothing 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 6963 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 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 the negative mode i e white text on black background AND Mode The tex
196. 63C set cursor cposx Delay ms 100 550 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection Toshiba T6963C Graphic LCD 240x128 VCC VCC 50R Contrast Adjustment 48849214 T6963C GLCD HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 551 7 Libraries mikroC PRO for PIC UART LIBRARY UART hardware module is available with a number of PIC MCUs mikroC PRO for PIC UART Library provides comfortable work with the Asynchronous full duplex mode You can easily communicate with other devices via RS 232 protocol for example with PC see the figure at the end of the topic RS 232 HW connection You need a PIC MCU with hardware integrated UART for example 16F887 Then simply use the functions listed below Note Some PIC18 MCUs have multiple UART modules Switching between the UART modules in the UART library is done by the Set Active function UART module has to be previously initialized Note In order to use the desired UART library routine simply change the number 1 in the prototype with the appropriate module number i e UART2 Init 2400 Library Routines UARTI Init UART1 Data Ready UART1 Tx Idle UART1 Read UART1 Read Text UART1 Write UART1 Write Text UART Set Active 552 MIKROELEKTRONIKA SOFTWARE AND HARDWARE
197. 6963C GRAPHIC LCD LIBRARY The mikroC PRO for PIC 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 res olution 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 equip ment 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 Col umn drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Note ChipEnable CE FontSelect FS and Reverse MD have to be set to appro priate levels by the user outside of the 76963c init function See the Library Example code at the bottom of this page Note 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 529 7 Libraries mikroC PRO for PIC External dependencies of T6963C Graphic LCD Library The following variables must be defined in all projects using T6963C Graphic LCD library extern sfr char 7658630 dataPorti T6963C Data Port t bit 27 2 Write signal T6963C
198. 7890 Time epochToDate epoch 6652 602 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Time dateDiff Prototype long Time dateDiff TimeStruct tl TimeStruct t2 Returns Time difference in seconds as a signed long This function compares two dates and returns time difference in seconds as a signed long Result is positive if t1 is before t2 result is null if c is the same as t2 and result is negative if c is after t2 Parameters Description ti time and date structure the first comparison parameter t2 time and date structure the second comparison parameter Note This function is implemented as macro in the timelib h header file which can be found in the mikroC PRO for PIC Time Library Demo example folder include timelib h TimeStruct tsi 521 long aa tts how many seconds between these two dates contained in tsl and ts2 buffers SU diff Time dateDiff amp tsl amp ts2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 603 CHAPTER 7 Libraries mikroC PRO for PIC Library Example This example demonstrates Time Library usage include timelib h TimeStruct tsi long epoch long diff void main tsl ss 0 tsl mn 7 tsl hh e 175 tsl md 23 ts51 mo 53 tsl yy 2006 What is the epoch of the date in ts f poch Time dateToEpoch amp ts1
199. 8 PIC MCUS Microcon troller must be connected to CAN transceiver 2551 or similar which is connected to CAN bus if CANGetOperationMode CAN MODE NORMAL CANInitialize void CANInitialize char SJW char BRP char PHSEG1 char PHSE char PROPSEG char CAN CONFIG FLAGS Returns Nothing Initializes CAN All pending transmissions are aborted Sets all mask registers to 0 to allow all messages The Config mode is internaly set by this function Upon a execu tion of this function Normal mode is set Filter registers are set according to flag value if CAN CONFIG FLAGS amp CONFIG VALID XTD MSG 0 Set all filters to XTD MSG else if config amp CONFIG VALID STD MSG 0 Set all filters to STD MSG Description 1S If Set half the filters to STD and the rest to XTD MSG Parameters sJw as defined in 18XXX8 datasheet 1 4 BRP as defined 18XXX8 datasheet 1 64 PHSEG1 as defined 18XXX8 datasheet 1 8 PHSEG2 as defined 18XXX8 datasheet 1 8 PROPSEG as defined in 18XXX8 datasheet 1 8 CAN CONFIG FLAGS is formed from predefined constants see CAN constants CAN routines are currently supported only by P18XXX8 PIC MCUs Microcon troller must be connected to CAN transceiver MCP2551 or similar which is con nected to CAN bus CAN CONFIG SAMPLE THRICE amp CAN CONFIG PHSEG2 PRG ON amp CAN CONFIG STD MSG amp CAN CONFIG DBL BUFFER ON amp CAN CONFIG
200. 89ABCEDF b Floating point number using the format dddd dddd T Floating point number using the format d dddde dd b b r ormat whichever is more compact for the specified value and precision i int is converted to an unsigned char and the resulting character is written per Bing with a terminating null character Description n d ddddE dd z ou ou ou Floating point number using either e or f ou t ha he complete conversion specification shall be 9696 REN JN AEN 590 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Description CHAPTER 7 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 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 ox when used with o x and x field types respectively When used with the e g ield 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 specifie
201. AN CONFIG FLAGS selects type of message to filter either CAN CONFIG XTD MSG or CAN CONFIG STD MSG CAN must be in Config mode otherwise the function will be ignored CAN routines are currently supported only by P18XXX8 PIC MCUs Microcontroller must be connected to CAN transceiver MCP2551 or similar which is connected to CAN bus 4 See id of filter BI Fl to 3 CANSetFilter CAN FILTER B1 F1 3 CAN CONFIG XTD MSG MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries CANRead Prototvpe char CANRead long id char data char datalen char CAN RX MSG FLAGS Returns Message from receive buffer or zero if no message found Function reads message from receive buffer If at least one full receive buffer is found it is extracted and returned If none found function returns zero Parameters Description ic is message identifier data is an of bytes up to 8 bytes in length datalen is data length from 1 8 CAN RX MSG FLAGS is value formed from constants see CAN constants CAN must be in mode in which receiving is possible CAN routines are currently supported only by P18XXX8 PIC MCUs Microcontroller must be connected to CAN transceiver MCP2551 or similar which is connected to CAN bus char rcv rx len 8 long id len x CANWrite Prototype unsigned short CANWrite long id char data char datale
202. ART Read senio ege rg Ea Euer entree dm 435 Sot DAFT Wiite sesse sek ea e hoe eus c do dn 436 Soft Uart Br ak bp ERR ave ERR epu Ros 436 Library Example Re eae PX e x Re RUE 438 Sound PPP 439 Library ROUUNCS 439 SOUNG M ge 439 Sound Play Lie due EI EE FEE EAE 440 Library Example 2 222 ERE Pty tere doh 440 HW Connection 2 2 22 2 Xu 442 SPL HDAN ubt mus ee x ee 443 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XIX Table of Contents mikroC PRO for PIC Library Routines 22 2 eI s 443 weer cage ER Ron x DEC Eon OR Ron Eee RO RO RS LR 443 Spi1 Init Advanced 444 2 2222 2245 ks ER ERI 445 Spit Wile 2 5 2 Aon DB br ok UR X 445 Siu mc EU 446 Library Example bey yew ome 446 HW Connection 4 448 oPLEtherret LDIDrary 2 22 eoe ial Re EE 449 External dependencies of SPI Ethernet Library 450 Library Routines
203. ART module at 9600 bps Delay ms 100 Wait for UART module to stabi lize while 1 Endless loop if UART1 Data Ready If data is received uart rd UART1 Read 27 read the received data UART1 Write uart rd 27 and send data via UART MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 557 7 Libraries mikroC PRO for PIC HW Connection SUB D 9p Receive data Rx Ds CONNECT MCU TO PC sa CABLE M CONNECT PC TO MCU Send SUB D 9p OSCRLATOR VOCO 48849514 RS 232 HW connection 558 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries USB HID 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 mikroC PRO for PIC includes a library for working with human interface devices via Universal Serial Bus A human interface device or HID is a type of computer device that interacts directly with and takes input from humans such as the keyboard mouse graphics tablet and the like Descriptor File Each project based on the USB HID 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 t
204. ASCII C HEX C DEC 62 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment mikroBootloader From Microchip s document AN732 The PIC16F87X family of microcontrollers has the ability to write to their own program memory This feature allows a small boot loader program to receive and write new firmware into memory In its most simple form the bootloader starts the user code running unless it finds that new firmware should be downloaded If there is new firmware to be downloaded it gets the data and writes it into program memory There are many variations and additional fea tures that can be added to improve reliability and simplify the use of the bootloader Note mikroBootloader can be used only with PIC MCUS that support flash write How to use mikroBootloader 1 Load the PIC with the appropriate hex file using the conventional programming techniques e g for PIC16F877A use 16 877a nex 2 Start mikroBootloader from the drop down menu Tools Bootoader 3 Click on Setup Port and select the COM port that will be used Make sure that BAUD is set to 9600 Kpbs 4 Click on Open File and select the HEX file you would like to upload 5 Since the bootcode in the PIC only gives the computer 4 5 sec to connect you should reset the PIC and then click on the Connect button within 4 5 seconds The last line in then history window should now read Connected To s
205. BEDDED WORLD 417 CHAPTER 7 Libraries UART1 Init 9600 Delay ms 100 RS485Slave Init 160 mikroC PRO for PIC initialize UART1 module Intialize MCU as slave address 160 dac 4 0 ensure that message received flag is 0 dat 5 0 ensure that message received flag is 0 dati 6 9 ensure that error flag is 0 1 1 enable interrupt on UART1 receive PIE2 TXIE 0 disable interrupt on UART1 transmit INTCON PEIE 1 enable peripheral interrupts INTCON GIE 1 enable all interrupts while 1 oF Kear oi qd if an error detected signal it by PORTD OxAA 4 setting portd to dat 5 0 af dati 4 upon completed valid message receiv 41 e 0 E 4 is set to OxFF j dati 5 for 1 1 i lt dati 3 i 4M PORTB dat i 1 dati 0 dati 0 1 increment received dat 0 Delay ms 1 RS485Slave Send dat 1 7 and send it back to master 418 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection Shielded pair no longer than 300m Im vcc 7 OSCLLATOR WCCO 1 lt 48849514 Example of interfacing PC to 8051 MCU via RS485 bus with LTC485 as RS 485 transceiver MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 419 CHAPTER 7 Libraries mikroC PRO for PIC Message
206. Breakpoints will be cleared File Register Break File Register Break can be used to stop the code execution when read write access to the specific data memory location occurs If Read Access is selected the File Register Equal option can be used to set the matching value The program execu tion will be stopped when the value read from the specified data memory location is equal to the number written in the value field Values entered in the Address and Value fields must be in hex format Note File Register Break can also use the Passcount option in the same way as Program Memory Break MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 115 3 mikrolCD mikroC Emulator Features Event Breakpoints B Break on Stack Overflow Underflow not implemented B Break on Watchdog Timer not implemented PRO for PIC B Break on SLEEP break on SLEEP instruction SLEEP instruction will not be executed If you choose to continue the mikrolCD debugging F6 then the pro gram execution will start from the first instruction following the SLEEP instruction Stopwatch Stopwatch uses Breakpoint 2 and Breakpoint 3 as a Start and Stop condi tions To use the Stopwatch define these two Breakpoints and check the Stopwatch checkbox Stopwatch options Halt on Start Condition Enable M Halt on Start Condition Breakpoint 2 when checked the program execution will stop on Breakpoint 2 Otherwise Breakp
207. CD LIBRARY The mikroC PRO for PIC provides a library for operating Graphic Lcd 128x64 with commonly used Samsung 5108 5107 controller For creating a custom set of Glcd images use Glcd Bitmap Editor Tool External dependencies of Graphic LCD Library The following variables must be defined in all projects Description using Graphic LCD Library extern sfr char char GLCD DataPort at GLCD DataPort Gled Data Port PORTD extern sfr sbit sbit GLCD CS1 at GLCD CS1 Chip Select 1 line RBO bit extern sfr sbit sbit GLCD CS2 at GLCD CS2 Chip Select 2 line BB Bits extern sfr sbit Register select line sbit GLCD RS at GLCD RS 9 4 extern sfr sbit TAE sbit GLCD RW at GLCD RW Read Write line RB3 bit E sfr sbit Enable line B sfr sbit Reset line sbit GLCD_RST at RT RB5 bit tern sfr sbit Direction of the Chip sbit GLCD 51 Direction CD CS1 Direction Select 1 pin at TRISBO bit tern sfr sbit Direction of the Chip sbit GLCD CS2 Direction eene D CS2 Direction Select 2 pin at TRISB1 bit 5 sfr sbit Direction of the Regis sbit GLCD RS Direction CD RS Direction ter select pin at TRISB2 bit tern sfr sbit Direction of the sbit GLCD RW Direction RW Direction Read Write pin at TRISB3 bit ter n sfr sbit Direction of the Enable sbit GLCD EN Direction GLCD EN Direction pin at TRISB4 bit extern sfr sbit Direction of the Reset sbit
208. CD starting from specified position Both string variables and literals can be passed as a text Description Parameters row Starting position row number column Starting position column number text text to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write text Hello on Lcd starting from row 1 column 3 SPI Lcd Out 1 3 Hello Spi Lcd Out Cp Prints text on the LCD at current cursor position Both string variables and liter als can be passed as a text Description Parameters text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write text Here at current cursor position SPI bed Out CP HereIl Spi Lcd Chr Prototype 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 Description Parameters Row Writing position row number Column Writing position column number Out Char character to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write character i at row 2 column 3 Led Che 2 3 Va he MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 495 7 Libraries mikroC PRO for PIC Spi Lcd Chr Cp Prototype void SPI Lcd Chr CP char Out Char Prints character
209. D HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi T6963C panelFill Prototype void SPI T6963C panelFill unsigned char v Fill current panel in full graphic text with appropriate value 0 to clear Description Parameters v Value to fill panel with Toshiba Glcd module needs to be initialized See SPI 6963 Config routine clear current panel SPI T6963C panel Fill 0 Spi_T6963C_GrFill Prototype void SPI T6963C grFill unsigned char v Fill current graphic panel with appropriate value 0 to clear Description Parameters v Value to fill graphic panel with Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear current graphic panel SPI T6963C grFill 0 Spi T6963C txtFill Prototype void SPI T6963C txtFill unsigned char Fill current text panel with appropriate value 0 to clear Description Parameters v this value increased by 32 will be used to fill text panel Requires Toshiba Glcd module needs to be initialized See T6963C Toshiba Gled module needs to be initialized See SPI 6963 Config routine routine EROS 1 eee clear current a ares SPI 6963 txt rill MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 521 7 Libraries mikroC PRO for PIC Spi T6963C cursor height Prototype void SPI T6963C cursor height unsigned char n Set cursor s
210. D MSG CANS PI CONFIG DB CANS PI CONFIG VALID XT CANS PI CONFIG LINE FILTER PHSEG2 PRG ON amp amp L BUFFER ON amp D MSG amp OFF CANSPIInitialize l 1 3 3 l CANSPI TX MSG FLAGS initialize CANSPI CANSPI TX MSG FLAGS are flags related to transmission of a CAN message const char CANSPI TX PRIORITY BITS 0x03 CANSPI TX PRIORITY 0 OxFC 4 CANSPI TX PRIORITY 1 OxFD if CANSPI TX PRIORITY 2 OxFE fi CANSPI TX PRIORITY 3 OxFF CANSPI TX FRAME BIT 0208 CANSPI TX STD FRAME OxFF CANSPI TX XTD FRAME 0587 0240 CANSPI TX NO RTR FRAME OxFF gy CANSPI TX RTR FRAME OxBF di XXXXXX00 XXXXXX01 XXXXXX10 XXXXXX11 XXXXXl1XX XXXXXOXX XlXXXXXX XOXXXXXX You may use bitwise AND to adjust the appropriate flags For example send config CANSPI TX XTD FRAM form value to be used as sending message flag _ TX PRIORITY 0 amp amp CANSPI TX NO RTR FRAME CANSPIWrite id data 1 send config MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD ra 267 7 Libraries mikroC PRO for PIC CANSPI MSG FLAGS CANSPI RX MSG FLAGS are flags related to reception of CAN message If a particu lar bit is set then corresponding meaning is TRUE or else it will b
211. D command data signal RST reset signal function E signal S signal signal signal direction signal direction D signal direction E UO HS gs n MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC bitmap pictures stored in ROM const code char const code char void main char txtl char txt char int char int unsigned unsigned unsigned unsigned TRISAO bit TROSAI bit TRISA2 bit TRISAS bit TRISA4 bit PR NA T6963C ctrlce T696306 ctrifs T6963C ctrlmd ANSEL 0 ANSELH 0 Initialize T T6963C init 240 Enable both ri T6963C graphics T6963C text 1 panel 0 0 curs 0 Cposx cposy Je Text message E MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD T6963C trica Direction T6963C ctrlfs Direction T6963C ctrlmd Direction mC einstein EINSTEIN WOULD HAVE CHAPTER 7 Libraries LIKED GLCD LIBRARY DEMO WELCOME S T69630 write 07 0 T6963C write t xt txtl 0 panel Current panel m General purpose register Cuts Cursor visibility cposx cposy Cursor x y position Set RAO as input Set 1 as input Set RA2 as input 7 Set as input Set RA4 as input sd Os Enable T6963C di OF Font Select
212. E ER AGE 543 6963 5 543 169630 PanelFill 22 nibii eee eret 543 T6963C ecit eed ded PA See ee rnb RES x EE Aue 544 zril eae een be 544 T6963C cursor heights ix epo dope etag Ere zero 544 1769636 Graphics pr EERE OEE ER Ra REX EAE RE 545 T6963C t6XL 2c cione 545 T6963C CUISOF 122 nisse pec xke xe eae ee 545 T6963C Cursor Blink 2522 25 pr Rem mx RR ED 546 Library Example tercer oett deer E ete Ee 546 HW Connection 2 2 2 2 551 552 Library 552 Uart Nt 2 RS 553 Uart Data Ready 554 UARIT Ix Idle 554 WARY Read eaae itus dx etna bed RSS o 554 UART1 Read Text 1 555 reete prem se AE eo ERE 555 WARTT Write as iesus suos aite oen so Roe RR D me 556 UART Set Active 556 Library Example
213. E3MikroElektronika SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD waking it si ple Ls ww p CY o dm T T T 0 5 2 4 S B i gan eng isk Develop your applications quickly and easily with the world s most intuitive mikroC PRO for PIC Microcontrollers Highly sophisticated IDE provides the power you need with the simplicity of a Windows based point and click environment With useful implemented tools many practical code examples broad set of built in routines and a comprehensive Help mikroC PRO for PIC makes a fast and reliable tool which can satisfy needs of experienced engineers and beginners alike mikroC PRO for PIC April 2009 Reader s note DISCLAIMER mikroC PRO for PIC and this manual are owned by mikroElektronika and are protected by copyright law and international copyright treaty Therefore you should treat this manual like any other copyrighted material e g a book The manual and the compiler may not be copied partially or as a whole without the written consent from the mikroEelktronika The PDF edition of the manual can be printed for private or local use but not for distribution Modifying the manual or the compiler is strictly prohibited HIGH RISK ACTIVITIES The mikroC PRO for PIC compiler is not fault tolerant and is not designed manufactured or intended for use or resale as on line control eq
214. EDDED WORLD 273 7 Libraries mikroC PRO for PIC 274 The following variables must be defined in all ee Description projects using Compact Flash Library extern sfr char char CF Data Port CF Data Port Compact Flash Data Port at PORTD extern sfr sbit Ready signal line sbit CF_RDY at CE BDYS y 519 RB7 bit extern sfr sbit sbit CF WE at CF WE Write Enable signal line RBG bit extern sfr sbit sbit CF OE at CF OE Output Enable signal line extern sfr sbit Chip Detect si i sbit CF CD1 at CF CD1 Ip Detect signal line RB4 bit extern sfr sbit sbit CF at CF CE RB3 bit br extern sfr sbit sbit CF_A2 at extern sfr sbit Address 1 sbit CF 1 at 1 d RBl bit Chip Enable signal line extern sfr sbit Address pin 0 sbit CF_A0 at CF A0 piny RBO bit extern sfr sbit sbit CF RDY direc CF RDY direction Direction of the Ready pin tion at TRISB bit extern sfr sbit Direction of the Write Enable sbit CF WE direction CF WE direction pin at TRISB6 bit extern sfr sbit Direction of the Output sbit CF OE direction CF OE direction Enable pin at TRISBS bit extern sfr sbit Direction of the Chip Detect sbit CF direc CD1 direction pin tion at 5 4 bit extern sfr sbit Direction of the Chip Enable sbit CF direc CEL direction pi tron at TRISBS bit in extern sfr sbit Direction of the Address 2 sbit CF A2 direc
215. EXample es s cage es oh ete ed Veg 6 338 D 340 Peed ne 341 Library ROUUNGS secs xm aX Ren 341 PAX PD Pm 341 I2C 1 Start eb dese hb eae he bea PES 342 2 1 Repeated Start ee eo 342 PFAOSREEAD EE 342 eee toe ee eh eon ace mee meee 342 prs PEU 343 1201 Stop eec oro reb eh 343 EW CONMNCCHON us ace usce kon deemed eee RR a RR DAR 345 Keypad Library 346 External dependencies of Keypad Library 346 Library RoUutlniBS a sx sme tee wo doc Re aC Rr EDU A Codd 346 Keypad eene hs Ed tede e baa Pod S 346 Keypad Key 22 22 21 22 22 lt 347 Keypad Key 347 Library Example 2 nete PER ERE Ret Peak dhe dhe 348 HW Connection 2 2 22 2 6 ER be eee 350 ECD Library e Sen aden ECCE ISP ER ptu pip Ud xr RE 351 XVI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents External dependencies of LCD Library
216. FTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries RS485slave Init Prototype void RS485Slave Init char Slave address Description Initializes MCU as a Slave for RS 485 communication Parameters slave address Slave address Global variables RS485 rxtx pin this pin is connected to RE DE input of RS 485 transceiv er see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Valid values for transmitting and 0 for receiv ing RS485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this function UART HW module needs to be initialized See UARTI Init RS485 module pinout sbit RS485 rxtx pin at RC2 bit transmit receive control set to PORTC B2 Pin direction sbit RS485 rxtx pin direction at TRISC2 bit pin direc tion set as output UART1 Init 9600 initialize UART module RS485Slave Init 160 intialize MCU as a Slave for RS 485 communication with address 160 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 413 7 Libraries mikroC PRO for PIC RS485slave Receive Prototype void RS485Slave Receive char data buffer 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 rece
217. GLCD RST Direction GLED RST Direction pin at TRISB5 bit 326 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Routines Basic routines Glcd Init Set Side Set X Glcd Set Page Read Data Write Data Advanced routines Fill Dot Glcd Line Glcd V Line Glcd H Line Glcd Rectangle Box Glcd Circle Glcd Set Font Write Char Glcd Write Text Glcd Image MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 327 7 Libraries Glcd Init mikroC PRO for PIC Dasciiptih Initializes the Glcd module Each of the control lines is both port and pin config P urable while data lines must be on a single port pins lt 0 7 gt Global variables CJ RJ CJ QJ must be defined before using this function Qo 63 LCD Chip select 1 signal pin LCD CS2 Chip select 2 signal pin LCD RS Register select signal pin LCD RW Read Write Signal pin LCD EN Enable signal pin LCD Reset signal pin Requires LCD DataPort Data port 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
218. Glcd Set Font font5x7 5 7 32 Change font someText 5x7 Font SPI Glcd Write Text someText 5 5 2 Write string Delay2s SPI Glcd Set Font FontSystem5x7 v2 5 7 32 Change font someText 5x7 Font v2 SPI Glcd Write Text someText 5 7 2 Write string Delay2s HW Connection 48849214 3 28 SPI HW connection 492 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI LCD LIBRARY The mikroC PRO for PIC 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 Note The library uses the SPI module for communication The user must initialize the SPI module before using the SPI Lcd Library For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the spi set active routine Note 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 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 dependen cies Library Rou
219. Gled LIn8 xus ots sexos e Bo ke toe 484 oPIGled V Lire gh ed pad tas 485 SPIGlcd FH Eine Eod rg 485 SPI Rectangle 2 cessus sco domi dor 486 SPI GICA BOX LIE LE aa tU ee 486 SPI Pa ed 487 SPI Set Font ses Red Kei un 487 Spi Gled Wiite Chat 50550 E 488 Spi Gled Writ Text 2 2 2 2 pee eR aped 489 Spi 490 Library leak 490 HW Connection 2 2 222 22 1 492 PEEL 493 External dependencies of SPI LCD Library 493 Library Ree SEALED Une 493 COMM s sia en cheer REN Ep Rupert E oA RAE 494 Spi Led eet ened eee a 495 Spi Led Out Cp ee gon x not RO RU ERROR REUS OD Reape US 495 Ayer trey ase tte E D 495 Chr Cp 22 22 2 22 222 d gr EDS
220. Gled Set Font amp myfont 5 1 32 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 335 7 Libraries 336 mikroC PRO for PIC Glcd Write Char Prototype void Glcd Write Char unsigned short chr unsigned short x pos unsigned short page num unsigned short color Description Prints character on the GLCD Parameters chr 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 Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine Use Set Font to speci fy the font for display if no font is specified then default 5x8 font supplied with the library will be used Write character C on the position 10 inside the page 2 Weite Char Ct 10 2 19 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Glcd Write Text void Glcd Write Text char text unsigned short x pos unsigned Prototype short page num unsigned short color Prints text on GLCD Parameters text text to be written x pos text starti
221. HAPTER 1 mikroC PRO for PIC Introduction 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 text of the message and paste it manually into a new email message before sending it to your distributor s ernail Marko Jovanovic Enter your address ik Invoice number 2theck ut order number Company E Mail marko amp mikroe com Product key _ 515C 557269 6F6D72 5751 Copy to clipboard SEND This will start your e mail client with message ready for sending Review the infor mation 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 9 1 Intr
222. HAPTER 7 Libraries mikroC PRO for PIC Library Example This simple example reads values of the pressed keys on the PS 2 keyboard and sends them via UART unsigned short keydata 0 special 0 down 0 sbit PS2 Data at RCO bit sbit PS2 Clock at bit sbit PS2 Data Direction at TRISCO bit sbit PS2 Clock Direction at 5 bit void main ANSEL 0 Configure AN pins as digital I O ANSELH 0 UART1 Init 19200 Initialize UART module at 19200 bps Ps2 Contig Init PS 2 Keyboard Delay ms 100 Wait for keyboard to finish UART1 Write Text Ready do if Ps2 Key Read amp keydata amp special amp down if down amp amp keydata 16 Backspace VARTI Write 0x08 else if down amp amp keydata 13 Enter UART1 Write r send carriage return to usart terminal Usart Write n 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 Delay ms 1 debounce while 1 404 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection VCC VCC o o d PS2 CONNECTOR OSCILLATOR Example of PS2 keyboard connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 405
223. IC T6963C module connections char sbit sbit sbit sbit sbit sbit sbit sbit T6963C ctr T6963C dataPort at PORTD T6963C ctrl T6963C T6963C ctrl 16963 T6963C ctrl T6963C ctrl T6963C ctrl wr at RC2 bit rd at bit cd at RCO bit rst at RC4 bit wr Direction at rd Direction at cd Direction at lrst Direction at TRISC2 bit TRISC1 bit TRISCO bit TRISC4 bit End of T6963C module connections Signals not used by library sbit sbit sbit sbit tion sbit sbit T6963C ctrl 169530 etri T6963C ctrl T6963C TOOSSUC ctrl direction ce at RCS bit fs at RCG Dit md at RC5 bit ce Direction at fs Direction at direction End T6963C module connections T6963C md Direction at signal FS signal MD signal TRISC6 bit TRISC5 bit CHAPTER 7 Libraries hey are set in main function TRISC3_bit CE signal direc signal MD signal init display for 240 pixel width 128 pixel height and 8 bits character width T6963C init 240 T6963C writeData Prototype 12898 8934 void T6963C writeData unsigned char mydata Nothing Writes data to T6963C controller Description Parameters mnydata data to be written T6963C writeData AddrL Toshiba Glcd module needs to be initialized See the T6963C init routine MIKROELEKTRONIKA SOFTWARE AND HARD
224. IC Ethernet Init Description void Ethernet Init unsigned char mac unsigned char ip unsigned char fullDuplex Nothing This is MAC module routine It initializes Ethernet controller This function is internaly splited into 2 parts to help linker when coming short of memory Ethernet controller settings parameters not mentioned here are set to default receive buffer start address 0x0000 receive buffer end address 0 1 transmit buffer start address 0x192r transmit buffer end address 0oxirrr RAM buffer read write pointers in auto increment mode receive filters set to default CRC MAC Unicast MAC Broadcast 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 00012 in full duplex mode 0x0c12 in half duplex mode half duplex loopback disabled LED configuration default LEDA link status LEDB link activity Parameters mac RAM buffer containing valid MAC address RAM buffer containing valid IP address fullDuplex ethernet duplex mode switch Valid values 0 half duplex mode and 1 full duplex mode Note If a DHCP server is to be used IP address should be set to 0 0 0 0 define Ethernet HALFDUPLE define Ethernet FULLDUPLE
225. KROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 217 6 Language Reference mikroC PRO for PIC Assignment Rules For both simple and compound assignment the operands expressionl and expression2 must obey one of the following rules 1 expression is of qualified or unqualified arithmetic type and expression is of arithmetic type 2 expressioni 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 4 Either expressioni 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 type pointed to by left has all qualifiers of the type pointed to by right expressioni is a pointer and expression2 is a null pointer constant 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 take either a type identifier or an unary expression as an operand You cannot use sizeof with expressions of function type incomplete types parenthesized names of such types or with lvalue that designates a bit field object Sizeof Applied to Exp
226. LASH Write 64 0 0000 toWrite MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 323 7 Libraries mikroC PRO for PIC FLASH Erase for PIC16 void FLASH Erase unsigned address Prototype for PIC18 void FLASH Erase 64 long address void FLASH Erase 1024 long address Erases memory block starting from a given address For P16 familly is implement Description ed only for those MCU s whose flash memory does not support erase and write operations refer to datasheet for details Erase 64 byte memory memory block starting from address 0 0000 FLASH Erase 64 0x0D00 FLASH Erase Write void FLASH Erase Write 64 long address char data Erase then write memory block starting from a given address Erase Write 1024 long address char data char toWrite 64 int ij initialize array for i 0 1 lt 64 itt toWrite i 2i erase block of memory at address 0 0000 then write contents of the array to the address 0 0 00 FLASH Erase Write 64 0x0D00 toWrite 324 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Example The example demonstrates simple write to the flash memory for PIC16F887 then reads the data and displays it on PORTB and PORTC chat i 0 unsigned int addr data dataAR 4 4 Ox3FAA 0 0 3
227. LCD display If Tarn cursor oft Prepare and output static text on LCD Main procedure If Perform initialization ed E 4 on Endless loop Read time from RTC PCF8583 Format date and time Prepare and display on LCD Wait 1 second 427 7 Libraries mikroC PRO for PIC SOFTWARE SPI LIBRARY The mikroC PRO for PIC provides routines for implementing Software SPI commu nication These routines are hardware independent and can be used with any MCU The Software SPI Library provides easy communication with other devices via 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 Note 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 A Description projects using Software SPI Library extern sfr sbit Data In line sbit SoftSpi SDI at SoftSpi SDI RCA bit extern sfr sbit sbit SoftSpi SDO at SoftSpi SDO Data Out line RC5 bit extern sfr sbit Clock line sbit SoftSpi CLK at SoftSpi CLK RC3 bit extern sfr sbit Dat Sit Direction of the Data In SoftSpi SDI Direction poU at TRISC4 bit
228. LEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries ADC LIBRARY ADC Analog to Digital Converter module is available with a number of PIC MCU models Library function _ Read is included to provide you comfortable work with the module ADC Read Prototype unsigned ADC Read unsigned short channel Returns 10 bit unsigned value read from the specified channel Initializes PIC s internal ADC module to work with RC clock Clock determines the time period necessary for performing AD conversion min 12TAD Description Parameter channel represents the channel from which the analog value is to be acquired Refer to the appropriate datasheet for channel to pin mapping unsigned tmp tmp ADC Read 2 Read analog value from channel 2 Library Example This example code reads analog value from channel 2 and displays it on PORTB and PORTC unsigned int temp res void main ANSEL 0x04 Configure AN2 pin as analog TRISA OxFF PORTA is input ANSELH 0 Configure other AN pins as digital I O TBISC 0x3 Pins RC7 RC6 are outputs TRISB 0 77 PORTE is output do temp res ADC Read 2 Get 10 bit results of AD conversion PORTB temp res Send lower 8 bits to PORTB PORTC temp res gt gt 2 Send 2 most significant bits to RC7 RC6 while 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED W
229. MAC unicast traffic will be enabled Note Advance filtering available in the MCU s internal Ethernet 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 Note 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 MCU s internal Ethernet module The MCU s internal Ethernet module should be properly cofigured by the means of Ethernet Init routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 299 7 Libraries mikroC PRO for PIC Requires module has to be initialized See Ethernet Init Ethernet Enable Ethernet CRC Ethernet UNICAST enable CRC checking and Unicast traffic Ethernet Disable Prototype Description 300 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Ethernet Enable unsigned char enFlt Nothing This is MAC module routine This routine disables appropriate network traffic on the MCU s intemal Ethernet 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
230. NES RR doi tk ba eed tus 406 PWMI Init iui tex Per EP tears a Wek 406 PWM1 Set Duty mk rp 407 Ihnen ee aR oe eee ee eene d 407 PWM1 Stop esie Edu ee dE me EU PEE ba DPA NUES 407 Library Example 408 XVIII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents HW Connection 22 4 2 EAR 409 RS 485 Library segete dean UE MEER Mee ee eee ORTOS a 410 External dependencies of RS 485 Library 410 Library Routines 411 RS485Master Init 1 411 RS485Master Receive 2 2 2 412 RS465Master Send suos e dex sintata whale gene ewe 412 RS4S5slave Init er eee 413 RS485slave_Rec ive see pee ee bak ER ER B Re 414 RS465slave Send Re 415 Library Example 415 HW Connection n d Lr Rd Re e EE EE RR IE ERU 419 Message format and CRC calculations 420 Software LO Library
231. NS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries text 1 temp whole 10 10 48 Extract tens digit text 2 temp whole 10 48 Extract ones digit extract temp fraction and convert it to unsigned int temp fraction temp2write lt lt 4 RES SHIFT temp fraction amp 0 000 temp fraction 625 convert temp fraction to characters text 4 temp fraction 1000 48 Extract thousands digit 5 temp fraction 100 10 48 Extract hundreds digit text 6 temp fraction 10 10 48 Extract tens digit text 7 temp fraction 10 48 Extract ones digit print temperature on LCD Logd OQut 2 Sy text void main ANSEL 0 Configure AN pins as digital I O ANSELH 0 Init If Xnttrasltse LOD Lcd Cmd LCD CLEAR Clear LCD Lcd Cmd LCD CURSOR OFF Tura Cursor Off Out l 1 Temperature Print degree character C for Centigrades Lcd Chr 2 13 223 different LCD displays have different char code for degree if you see greek alpha letter try typing 178 instead of 223 Led Chr 2 1014 TQT g main loop do perform temperature reading Ow Reset amp PORTA 5 Onewire reset signal Ow Write amp PORTA 5 OxCC Issue command SKIP ROM Ow Write amp PORTA 5 0x44 Issue command CONVERT T Delay 120 Ow Reset amp PORTA 5
232. NSPI FILTER B2 F3 CANSPI FILTER B2 F4 5 Ds Library Example This is a simple demonstration of CANSPI Library routines usage First node initi ates 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 unsigned char Can Init Flags Can Send Flags Can Rcv Flags can flags unsigned char Rx Data Len 17 received data length bytes char RxTx Datal 8 22 x tx data buffer char Msg Rcvd reception flag const long ID 1st 12111 ID 2nd 3 node IDs long Rx ID CANSPI module connections sbit CanSpi CS at RCO bit sbit CanSpi CS Direction at TRISCO bit sbit CanSpi Rst at RC2 bit sbit CanSpi Rst Direction at TRISC2 bit End CANSPI module connections void main ANSEL 0 Configure AN pins as digital I O ANSELH 0 PORTB TRISB OF clear PORTB set PORTB as output Init Flags 0 Can Send Flags 0 clear flags Can Rcv Flags 0 Can Send Flags CANSPI TX PRIORITY 0 amp form value to be used CANSPI TX XTD FRAME amp with CANSPIWrite CANSPI TX NO RTR FRAME Can Init Flags CANSPI CONFIG SAMPLE THRICE amp Form value to be used CANSPI CONFIG PHSEG2 PRG ON amp with CANSPIInit CANS
233. NSPI MASK 1 1 CANSPI CONFIG XTD MSG set all maski bits to ones CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG set MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 271 CHAPTER 7 Libraries mikroC PRO for PIC all mask2 bits to ones CANSPISetFilter CANSPI FILTER B2 F3 ID 1st CANSPI CONFIG XTD MSG set id of filter B2 to 1st node ID CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode while 1 endless loop Msg Reyd CANSPIRead amp Rx ID RxTx Data amp Rx Data Len amp Can Rcv Flags receive message if Rx ID ID 1st 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 CANSPIWrite ID 2nd RxTx Data 1 Can Send Flags send incremented data back HW Connection 79 w D ep oN MCP2551 RCS 4 Shielded twisted pair Example of interfacing CAN transceiver MCP2510 with MCU via interface 272 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries 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 mem
234. Nothing This is MAC module routine This routine enables appropriate network traffic on 454 the mikroC PRO for PIC e unsigned char enFlt ENC28360 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 net work 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 Parameters enFit network traffic receive filter flags Each bit corresponds to the appropri ate network traffic receive filter MAC Broadcast traffic receive filter Ethernet BROAD 0x01 flag When se t MAC broadcast traf fic will be enabled t traffic receive filter t MAC multicast traffic will be enabled MAC Multicas 1 0x02 flag When se one check flag When set packets with invalid CRC field will be discarded SPI Ethernet rome MAC Unicast 7 0x80 enabled Note Advance filtering available in the 28760 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 traffic receive
235. O for PIC Library Routines 508 Spi T6963C CONTIG 22 sasewene ke Xo gos 509 Spi T6963C WriteData 510 6963 510 6963 iieri ene RR hue hades detente 511 Spi T6963C WaitReady 2 22 2 2 511 Spi 316963C aed toe a ive ee ioa Bonus cag Tn 511 Spl 16963C ie Rene e oreet Se aut teehee 512 Spi T6963C Write Char nn 513 769636 write Text ios ck s Er EA me Bade cog 514 Spi 69636 Ire 5 ce epe e 515 Spi T6963C rectangle 2 2 2 2 2 22 222222222 reis bere 515 Spi 109630 516 Spi 169636 GIICle i xii dera E RITE afe Eo icd 516 1769636 image x ualde eed Rr e 517 Spi T6963C Sprite 517 SpL T6963C set CUFSOF 2222505 p Perg petere dre Eutr 518 Spi 6963 clearBIt 2 2222 22 202 er pe onde d Ed 518 Spi T6963C setBit 5 518 Spi 16963 6
236. ORLD 7 mikroC PRO for PIC Libraries Cf Fat Get Swap File Prototype unsigned long Cf Fat Get Swap File unsigned long sectors cnt char filename char file attr 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 This function is used to create a swap file of predefined name and size on the CF media If a file with specified name already exists on the media search for con secutive sectors will ignore sectors occupied by this file Therefore it is recom mended 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 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 consid ered as a window the media where the user can freely write read data It s main purpose in the mikroC s 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 Parameters sectors cnt number of consecutive sectors that user wants the swap file to have filename name of th
237. ORLD 243 7 Libraries mikroC PRO for PIC HW Connection 330 100 2 v E 330 0g i E LD3 ss U r o acid 330 104 2 E LE 330 105 2 HI 0030 90 scire 330 EA Ut i 330 107 2 330 4 H 330 m4 i 0D ADC HW connection CAN LIBRARY mikroC PRO for PIC provides a library driver for working with the CAN module CAN is a very robust protocol that has error detection and signalling self checking and fault confinement Faulty CAN data and remote frames are re transmitted auto matically similar to the Ethernet Data transfer rates vary from up to 1 Mbit s at network lengths below 40m to 250 Kbit s at 250m cables and can go even lower at greater network distances down to 200Kbit s which is the minimum bitrate defined by the standard Cables used are shielded twisted pairs and maximum cable length is 1000m CAN supports two message formats Standard format with 11 identifier bits and m Extended format with 29 identifier bits Note CAN Library is supported only by MCUs with the CAN module Note Consult the CAN standard about CAN bus termination resistance 244 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Routines CANSetOperationMode CANGetOperat
238. OxAO 374 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Mmc Fat Reset Prototype void Mmc Fat Reset unsigned long size Procedure resets the file pointer moves it to the start of the file of the assigned Description file so that the file can be read Parameter size stores the size of the assigned file in bytes The file must be assigned see Mmc Fat Assign 0000000000 Fat Rewrite Returns Nohing Procedure resets the file pointer and clears the assigned file so that new data Description can be written into the file The file must be assigned see Mmc Fat Assign Bmw fe Mmc Fat Append Ee void Mmc Fat Returns The procedure moves the file pointer to the end of the assigned file so that Description data can be appended to the file The file must be assigned see Mmc_Fat_Assign COO MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 375 7 Libraries mikroC PRO for PIC Mmc Fat Read Prototype void Fat Read unsigned short bdata Nothing Procedure reads the byte at which the file pointer points to and stores data into Description parameter data The file pointer automatically increments with each call of Mmc Fat Read The file must be assigned see Mmc Fat Assign Also file pointer must be ini tialized see M
239. PI CONFIG XTD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 269 CHAPTER 7 Libraries mikroC PRO for PIC Tart initialize SPI1 module CANSPIInitialize 1 3 3 3 1 Can Init Flags Initialize external CANSPI module CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPISetMask CANSPI MASK 1 1 CANSPI CONFIG XTD MSG set all maski bits to ones CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG set all mask2 bits to ones CANSPISetFilter CANSPI FILTER B2 F4 ID 2nd CANSPI CONFIG XTD MSG set id of filter B2 F4 to 2nd node ID CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode RxTx Data 0 9 set initial data to be sent CANSPIWrite ID 1st RxTx Data 1 Can Send Flags send initial message while 1 endless loop Msg Revd CANSPIRead amp Rx ID RxTx Data amp Rx Data Len amp Can Rcv Flags receive message if Rx ID ID 2nd amp amp Msg Rcvd 1 if message received check id PORTB RxTx Data 01 id correct output data at PORTC RxTx Data 0 increment received data Delay ms 10 CANSPIWrite ID 1st RxTx Data 1 Send Flags send incremented data back 270 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC P
240. PI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI LOW 2 HIGH initialise a MMC card mmc error Mmc Init if mme error 0 UART1 Write Line MMC Init OK If MMC present report else UART1 Write Line MMC Init error If error report Fill MMC buffer with same characters for 1i 0 14 511 itt SectorData i FILL CHAR Write sector mmc error Mmc Write Sector SectorNo SectorData if mmc error 0 UART1 Write Line Write OK else if there are errors UART1 Write Line Write Error Reading of CID register mmc error Mmc Read Cid data for registers ifimup error 0 4 UART1 Write Text CID for 0 1 lt 152 i44 PrintHex data for registers 11 UART1 Write Line else UARTI Write Line CrD error Reading of CSD register error Read Csd for registers LE mme error 0 4 UARTI Write Text CSD fori i 0 2 lt 15 344 PrintHex data for registers ilJ UART1 Write Line else VARTI Write Line CSD error Read sector MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 381 7 Libraries mmc error Mmc Read Sector SectorNo SectorData if mmc error 0 4 UART1 Write Line Read OK Chech data match data ok 1 FEL G 0 r blilir 334 4 UART1 Write SectorData i if SectorDatal il FILL CHAR 4 data ok
241. PRO for PIC results in the left to right evaluation of each expression 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 c isthe sameas 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 7 2 Gt 2 returns preincremented value of variable c but also intializes a divides b by 2 and increments c result x 10 y e x 4 3 x 3 y returns computed value of variable z and also computes x and y Note Do not confuse comma operator sequence operator with comma punctuator which separates elements in a function argument list and initializator lists To avoid ambi guity with commas in function argument and initializer lists use parentheses For example funce i 1 I 4 E calls the function func with three arguments i 5 not four 220 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference STATEMENTS Statem
242. Panel 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 508 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi T6963C Config void SPI 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 Initalizes the Graphic Lcd controller Parameters width Width of the GLCD panel height height of the GLCD panel fntw 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 c command data signal pin on GLCD control port rst reset signal pin on GLCD control port Display RAM organization The library cuts RAM into panels a complete panel is one graphics panel fol lowed by a text panel see schematic below Description schematic MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 509 CHAPTER 7 Libraries Expandercs Chip Select line ExpanderRST Reset line ExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before us
243. R EMBEDDED WORLD mikroC PRO for PIC Language Reference The mikroC PRO for PIC Language Reference describes the syntax semantics and implementation of the mikroC PRO for PIC language The aim of this reference guide is to provide a more understandable description of the mikroC PRO for PIC language to the user 139 6 Language Reference mikroC PRO for PIC Lexical Elements Whitespace Comments Tokens Constants Constants Overview Integer Constants Floating Point Constants Character Constants String Constants Enumeration Constants Pointer Constants Constant Expression 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 Type Conversions Standard Conversions Explicit Typecasting 140 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 6 Language Reference 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 Opera
244. RDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries T6963C set cursor Prototype void T6963C set cursor unsigned char x unsigned char y Sets cursor to row x and column y 5 4 Parameters Description x cursor position row number y cursor position column number Toshiba Glcd module needs to be initialized See the T6963C init routine a T6963C set cursor cposx cposy T6963C clearBit Clears control port bit s Description Parameters b bit mask The function will clear bit on control port if bit 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 clearBit 0x03 T6963C setBit Sets control port bit s Description Parameters b bit mask The function will set bit x on control port if bit x in bit mask is set to 1 Requires Toshiba Glcd module needs to be initialized See the T6963C init routine set bits 0 and 1 on control port T6963C setBit 0x03 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 541 7 Libraries mikroC PRO for PIC T6963C negBit Negates control port bit s ES Parameters Description b bit mask The function will negate bit on control port if bit 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
245. RE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 585 7 Libraries mikroC PRO for PIC FloatToStr Prototype unsigned char FloatToStr float fnum unsigned char str 3 if input number is NaN 2 if input number is INF 1 if input number is INF 0 if conversion was successful Converts a floating point number to a string Parameters input floating point number to be converted Description output destination string The output string is left justified and null terminated after the last digit Note Given floating point number will be truncated to 7 most significant digits before conversion Requires Destination string should be at least 14 characters in length float 1 374 2 float ff2 123 4567897 float 0 000001234 char txt 15 Ext PloatrloStre ft2 txt is 123 4567 jf txt 4314 2 PloatToStr ff3 txt txt is 1 234e 6 586 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Dec2Bcd Prototype unsigned short Dec2Bcd unsigned short decnum Returns Converted BCD value Converts input unsigned short integer number to its appropriate BCD represen tation Description Parameters decnum unsigned short integer number to be converted unsigned short a b a 22 b Dec2Bcd b equals 34 Bcd2Dec16 Prototype unsigned Bcd2Dec16 u
246. RISCI bit End Port Expander module connections void main If Port Expander Library uses SPI1 module Int Initialize SPI module used with PortExpander If Port Expander Library uses SPI2 module SPI2 Init Initialize SPI module used with PortExpander SPI Lcd Config 0 Initialize Lcd over SPI interface SPI Led Cmd LCD CLEAR Clear display SPI Led Cmd LCD CURSOR OFF Turn cursor off SPI Lcd Out 1 6 mnikroE Print text to Led lst row 6th col umn Led Chr Cp Tl 74 Append 1 Lod Out 2 1 text Print text to 2nd row lst column 49 Led Owe 3 1 mikrob jz For Led with more than two rows SPI Lcd Out 4 15 mikroE For Lcd with more than two rows 498 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection OSGLLATOR SPI LCD HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 499 7 Libraries mikroC PRO for PIC SPI LCD8 8 BIT INTERFACE LIBRARY The mikroC PRO for PIC 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 Note Library uses the SPI module for communication The user must initia
247. RO for PIC Libraries Code for the second CANSPI node 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 Datal 8 can rx tx data buffer char Msg Rcvd reception flag const long ID 1st 12111 ID 2nd 3 node IDs long Rx ID CANSPI module connections sbit CanSpi CS at RCO bit sbit CanSpi CS Direction at TRISCO bit sbit CanSpi Rst bit sbit CanSpi Rst Direction at TRISC2 bit End CANSPI module connections void main ANSEL 0 Configure AN pins as digital 1 0 ANSELH 0 PORTB 0 clear PORTB TRISB 0 set PORTB as output Can Init Flags Oy fi Can Send Flags 0 clear flags Can Rcv Flags 0 Can Send Flags CANSPI TX PRIORITY 0 form value to be used CANSPI TX XTD FRAME amp with CANSPIWrite CANSPI TX NO RTR FRAME Can Init Flags CANSPI CONFIG SAMPLE THRICE amp Form value to be used CANSPI CONFIG PHSEG2 PRG ON amp with CANSPIInit CANSPI CONFIG XTD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG amp CANSPI CONFIG LINE FILTER OFF T SPIL Tait initialize SPIL module CANSPIInitialize 1 3 3 3 1 Can Init Flags initialize external CANSPI module CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGU RATION mode CANSPISetMask CA
248. RO for PIC 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 def inition and we use an expression of different type if an operator requires an operand of particular type and we use an operand of dif ferent 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 func tion return type if intializing an object in declaration with an object of different type In these situations compiler will provide an automatic implicit conversion of types without any programmers interference Also the programmer can demand conversion explicitly by means of the typecast operator For more information refer to the Explicit Typecasting Standard Conversions When using arithmetic expression such as b where a and are of different arithmetic types the mikroC PRO for PIC 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
249. ROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 607 OOO sionpoud Aue lt nof 5 12e1u02 eseejd jesodoud ss uisnq e 10 1 uonsanb 13470 Aue nof j cs Y Vo ma e SNOLLOTTOS 3HVMQWVH ANY 38VM 13OS E41U01149 30 19A Mouser Electronics Authorized Distributor Click to View Pricing Inventory Delivery amp Lifecycle Information mikroElektronika MIKROE 736
250. RONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Relational Operators Use relational operators to test equality or inequality of expressions If an expres sion evaluates to be true it returns 1 otherwise it returns 0 All relational operators associate from left to right Relational Operators Overview E qme 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 a 45 1 0 e f 2 te by ee I0 ej Do not forget that relational operators return either O or 1 Consider the following examples 5 gt 7 returns 0 10 lt 20 returns 1 this be tricky 8 13 gt 5 retiris 0 13 gt 5 9 1 142 8 returns 1 14 gt 5 3 F 7 quy a be S returns 1 as a b lt 5 32 0 1 amp b a Iy MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 211 6 Language Reference mikroC PRO for PIC 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 com plement operator which associates from right to left Bitwise Operators Overview
251. RONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 7 Libraries char filename 14 MIKROOOx TXT 27 File names unsigned short loop 1 2 unsigned long i size char Buffer 5121 1 write text and new line carriage return line feed void VARTI Write Line char uart text UART1 Write Text uart text UART1 Write 13 UART1 Write 10 Creates new fil and writes some data to it void M Create New File filename 7 Cf Fat Assign amp filename new one Cf Fat Rewrite for loop 1 loop UART1 Write file contents 0 file contents 1 Cf Fat Write file assigned file 0 Find existing file or create a To clear file and start with new data lt 99 loopt 4 loop 10 loop 10 contents 48 48 LINE LEN 1 write data to the Creates many new files and writes data to them void M Create Multiple Files for loop2 loop2 lt 2 1 24 UART1 Write loop2 signal the progress filename 7 loop2 set filename 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 44 1 1 file contents 0 loop 10 48 File contents 1 loop 2 19 29 Fat Weite tile contents assigned file LINE LEN 1
252. S Inst CHAPTER 7 Libraries Initialize SPI module used with PortExpander Initialize Glcd via SPI Clear Gica while 1 SPI Gled Image truck bmp Draw image Delay2s Delay2s SPI Fill 0x00 Clear Glcd Delay2s SPI Gled Box 62 40 124 56 1 Draw box SPI Glcd Rectangle 5 5 84 35 1 Draw rectangle SPI Gled Line 0 53 127 0 1 Draw line Delay2s for counter 5 counter lt 60 counter 5 Draw horizon tal and vertical line Delay ms 250 SPI Gled V 2 54 counter 19 SPE Gleg Line 2 120 counter 1 Delay2s SPI eled 111 0 00 77 Clear Gled SPI Glcd Set Font Character8x7 8 389 Choose font see Lib GLCDFonts c in Uses folder SPI Clod Werte 5 7 2 2 Write string for counter 1 counter lt 10 counter Draw circles SPI Gled 63 32 J3 oounter 1 Delay2s SPI Gled Boxi12 205 T7T0 63 2 7 Draw box Delay2s SPI Glcd Fill OxFF Fill Gled SPI Glcd Set Font Character8x7 8 7 32 Change font someText 8x7 Font SPI Glcd Write Text someText 5 1 2 Write string Delay2s SPI Glcd Set Font System3x5 3 5 32 Change font someText 3X5 CAPITALS ONLY SPI Glcd Write Text someText 5 3 2 7 Write string Delay2s MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 491 7 Libraries mikroC PRO for PIC SPI
253. SOLUTIONS FOR EMBEDDED WORLD 3 mikroC PRO for PIC mikrolCD Step No 4 Step Into F7 and Step Over F8 are mikrolCD debugger functions that are used in stepping mode There is also Real Time mode supported by mikroICD Functions that are used in Real Time mode are Run Pause Debugger F6 and Run to cursor F4 Pressing F4 goes to line selected by user User just have to select line with cursor and press F4 and code will be executed until selected line is reached 20 24 wed Init z 30 0 000009 Cycle 0 00 Step No 5 Run Pause Debugger F6 and Toggle Breakpoints F5 are mikrolCD debugger functions that are used in Real Time mode Pressing F5 marks line selected by user for breakpoint F6 executes code until breakpoint is reached After reaching breakpoint Debugger halts at our example we will use breakpoints for writing mikroElektronika on Lcd char by char Breakpoint is set on Lcd Chr and program will stop everytime this function is reached After reaching breakpoint we must press F6 again for continuing program execution Lcd Chr i1 i text i 1 PC 0x0000DD 0 00 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 107 3 mikrolCD mikroC PRO for PIC Breakpoints has been separated into two groups There are hardware and software break points Hardware breakpoints are placed in PIC and they provide fastest debug Num
254. SOLUTIONS FOR EMBEDDED WORLD 227 6 Language Reference mikroC PRO for PIC Goto Statement The goto statement is used for unconditional jump to a local label for more infor mation 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 identi fier The label identifier has to a name ofthe label within the same func tion 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 jump ing into loop s body etc The use of goto statement is generally discouraged as practically every algorithm be realized without it resulting in legible structured programs One possible application of the goto statement is breaking out from deeply nested control structures for 4232 4 fof Coca 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 auto matically converted to the expected function type if needed The expression is optional if
255. T6963C_displayTxtPanel Prototype void SPI T6963C displayTxtPanel char n Nothing Display selected text panel Description Parameters n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI 6963 Config routine f display text panel 1 SPI T6963C displayTxtPanel 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 519 7 Libraries mikroC PRO for PIC Spi T6963C setGrPanel Prototype void SPI T6963C setGrPanel char n Nothing Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example set graphic panel 1 as current graphic panel SPI 6963 setGrPanel 1 Spi T6963C setTxtPanel Prototype void SPI T6963C setTxtPanel char n Nothing Compute start address for selected text panel and set appropriate internal point ers All subsequent text operations will be preformed at this text panel Description Parameters 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 T6963 secTxtPan l 1 520 MIKROELEKTRONIKA SOFTWARE AN
256. TER B2 F4 ID 2nd CAN CONFIG XTD MSG set id of filter 2 to 2nd node ID CANSetOperationMode CAN MOD RxTx Datal 0 9 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLU E NORMAL OxFF set NORMAL mode set initial data to be sent TIONS FOR EMBEDDED WORLD 253 7 Libraries mikroC PRO for PIC CANWrite ID 1st RxTx Data 1 Can Send Flags send initial message while 1 endless loop Msg Rcvd CANRead amp Rx ID RxTx Data amp Rx Data Len amp Can Rcv Flags receive message if Rx ID ID 2nd amp amp Msg Rcvd if message received check id PORTC RxTx Dat 0 id correct output data at PORTC RxTx 0 increment received data Delay ms 10 CANWrite ID 1st RxTx Data 1 Can Send Flags send incremented data back Code for the second CAN node 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 1st 12111 ID 2nd 3 node IDs long Rx ID void main PORTC TRISC 0 clear PORTC 05 set PORTC as output Can Init Flags 0 Can Send Flags 0 clear flags Can Rcv Flags 0 r Can Send Flags TX PRIORITY 0 6 form value to be used _ TX XTD FRAME amp with CANWrite CAN TX NO RTR FRAME M
257. TRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection ORATOR VCCO Interfacing 24c02 to PIC via 2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 345 7 Libraries mikroC PRO for PIC KEYPAD LIBRARY The mikroC PRO for PIC provides a library for working with 4x4 keypad The library routines can also be used with 4x1 4x2 or 4x3 keypad For connections explanation see schematic at the bot tom of this page External dependencies of Keypad Library The following variable must be defined in all projects Description using Keypad Library extern sfr char h k P PORTD keypadPort Keypad Port char keypadPort at PO Library Routines Keypad Init Keypad Key Press Keypad Key Click Keypad Init Prototype Initializes port for working with keypad Global variable Requires keypadPort Keypad port must be defined before using this function Keypad module connections char keypadPort at PORTD End of keypad module connections Keypad Init 346 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Keypad Key Press Prototype char Keypad Key Press void The code of a pressed key 1 16 If no key is pressed returns 0 Reads the key from keypad when key gets pressed Port
258. TWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Jump Statements The jump statement when executed transfers control unconditionally There are four such statements in the mikroC PRO for PIC 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 Ordo 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 statement 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 contin ue demands the next iteration if the loop continuation condition is true Specifically the continue statement within the loop will jump to the marked tion as it is shown below while do fOE igo gu d if val 0 continue if val 0 continue if val 0 continue continue jumps continue jumps continue jumps here here here while MIKROELEKTRONIKA SOFTWARE AND HARDWARE
259. TWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 205 6 Language Reference mikroC PRO for PIC Example include lt stdarg h gt int addvararg char al wa 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 70 0 206 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 B sizeof Operator Preprocessor Operators and MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 207 6 Language Reference mikroC PRO for PIC Operators Presidence and Associativity There are 15 precedence categories some of them contain only one operator Operators in the same category have equal precedence If duplicates of operators appear in the table the first occurrence is unary and the second binary Each category has an associativity rule left to right or right to left
260. 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 module needs to be initialized See the T6963C init routine T6963C write text Glcd LIBRARY DEMO W T6963C ROM MODE XOR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 537 7 Libraries mikroC PRO for PIC T6963C line void T6963C line int x0 int int xl int yl unsigned char peoler Draws a line from x0 y0 to x1 y1 Prototype Parameters x0 X coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start yl y coordinate of the line end pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine CT T6963C line 0 0 239 127 T6963C WHITE T6963C rectangle Description void 6963 rectangle int x0 int int xl int yl unsigned char poolor s Draws a rectangle on GLCD Prototype Parameters Description 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 yl y coordinate of the lower right rectangle
261. Tm 277 Cf Read Init AM RIEN RAI 278 Cf Read Byle sen soe weitere RM REA WERE RI ERR ES 278 Write Init sis esite sennie cte Role re Rae ox 279 Cf Write Byte noe me See uy ics Rb 279 Read Sector Dh or gear dab 280 Cf Write Sector Ee dee CREDE Hn 280 ma un app ore nme Peden Ree A wee ee Ree eS 281 Cf Fat QuickFormat 281 Cf Fat 55 Pe tud 282 cT 283 Iioc 283 Cf Fat Rewrite coiere heeded te een 284 Gf Fat App nd iesu ena opea epi qe kids 284 Delete 4 ee ete petens Pada TE rud 284 Cf Fat Write 222 22 05 de Bees 285 Cf Fat Set File Date 285 XIV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents Cf Fat Set File Date 2 22 2 2222 222 286 Fat Set File SIZE imus EE Rex ka E eS 286 Cf Get Swap File s tisa cs pe Siew ea eroe 287 Library Example 4 2 4 1 288 HW Connection sss pee eer eas ioe ke EE GG dee 293 EEPROM Libraty
262. UPPORT SERVICES EVEN IF MIKROELEKTRONIKA ASSOCIATES HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES IN ANY 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 INTO A MIKROELEKTRONIKA ASSOCIATES SUPPORT SERVICES AGREEMENT MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOVERNED BY THE TERMS OF THAT AGREEMENT MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 5 1 Introduction mikroC PRO for PIC 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 mikroElektron ika Associates and its suppliers specifically disclaim any expressed or implied war ranty of fitness for High Risk Activities GENERAL PROVISIONS This statement may only be modified in writing signed by you and an authorised offi cer of mikroElektronika Associates If any provision of this stat
263. 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 project No libraries from the list will be included in current project EE Restore library to the state just before last project saving Related topics mikroC PRO for PIC Libraries Creating New Library 46 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 2 Environment ERROR WINDOW In case that errors were encountered during compiling the compiler will report them and won t generate a hex file The Error Window will be prompted at the bottom of the main window by default The Error Window is located under message tab and displays location and type of errors the compiler has encountered The compiler also reports warnings but these do not affect the output only errors can interefere with the generation of hex Messages v Errors Warnings v Hints Line Message No 1 125 121 399 399 368 393 102 Message Text mikroCPIC1618 exe MSF DBG pP16F887 UICD C Y DL 011111114 fo8 N C Program Files Mikroelektronika mikroC PRO For PIC Examples SPI All files Preprocessed in 1 ms Compilation Started expected but text Found expected but found Sp
264. VALID XTD MSG amp CAN CONFIG LINE FILTER OFF CANINmaitialize l 1 To If initialize MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CANSetBoudRate void CANSetBaudRate char SJW char BRP char PHSEG1 char PHSE CHAPTER 7 Libraries char PROPSEG char CAN CONFIG FLAGS Sets CAN baud rate Due to complexity of CAN protocol you cannot simply force a bps value Instead use this function when CAN is in Config mode Refer to datasheet for details Parameters Description sJw as defined in 18XXX8 datasheet 1 4 BRP as defined 18XXX8 datasheet 1 64 PHSEG1 as defined 18XXX8 datasheet 1 8 PHSEG2 as defined 18XXX8 datasheet 1 8 PROPSEG as defined 18XXX8 datasheet 1 8 CAN CONFIG FLAGS is formed from predefined constants see CAN constants CAN must be in Config mode otherwise the function will be ignored CAN routines are currently supported only by P18XXX8 PIC MCUs Microcon troller must be connected to CAN transceiver MCP2551 or similar which is con nected to CAN bus CAN CONFIG SA PLE THRICE amp CAN CONFIG PH SEG2 PRG ON amp CAN CONFIG ST D MSG amp CAN CONFIG DB L BUFFER ON amp CAN CONFIG VA LID XTD MSG amp CAN CONFIG LINE FILTER
265. WARE SOLUTIONS FOR EMBEDDED WORLD 533 7 Libraries mikroC PRO for PIC T6963C WriteCommand Prototype void T6963C writeCommand unsigned char mydata Writes command to T6963C controller Description Parameters mydata command to be written Toshiba module needs to be initialized See the T6963C init routine T6963C writeCommand T6963C CURSOR POINTER T6963C SetPtr Prototype void T6963C setPtr unsigned int p unsigned char c Sets the memory pointer p for command c Parameters Description p address where command should be written c command to be written Requires Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C setPtr T6963C grHomeAddr start T6963C ADDRESS POINTER SET T6963C waitReady Pools the status byte and loops until Toshiba GLCD module is ready Toshiba Glcd module needs to be initialized See the T6963C init routine 534 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries T6963C fill void T6963C fill unsigned char v unsigned int start unsigned Prototype int Lani Fills controller memory block with given byte Parameters Description v byte to be written start Starting address of the memory block 1en length of the memory block in bytes Toshiba module needs to be initialized See the T69
266. You can also add your own preferences to the list Also the Code Editor has a feature to comment or uncomment the selected code by sim ple click of a mouse using the Comment Icon and Uncomment Icon 1 from the Code Toolbar Spell Checker 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 drop down menu or click the Show Options Icon at and then select the Spell Checker Tab Bookmarks Bookmarks make navigation through a large code easier To set a bookmark use Ctrl Shifttnumber To jump to a bookmark use Ctrl number Goto Line The Goto Line option makes navigation through a large code easier Use the short cut Ctrl G to activate this option Comment Uncomment Also the Code Editor has a feature to comment or uncomment the selected code by simple click of a mouse using the Comment Icon Uncom ment Icon 1 from the Code Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 39 2 Environment mikroC PRO for PIC 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 right clicking it Also besides the list of defined and declared objects code explorer displays message about first error and it s location in code Code Explorer 4 Functions
267. a Glcd module needs to be initialized See SPI 6963 Config routine SPI T6963C setPtr T6963C grHomeAddr start T6963C ADDRESS POINTER SET Spi T6963C WaitReady Spi T6963C Fill void SPI T6963C fill unsigned char v unsigned int start Prototype unsigned int len Fills controller memory block with given byte Parameters Description v byte to be written start Starting address of the memory block 1en length of the memory block in bytes Toshiba Glcd module needs to be initialized See SPI T6963C Config routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 511 7 Libraries mikroC PRO for PIC Spi T6963C Dot Prototype void SPI T6963C dot int x int y unsigned char color Nothing Draws a dot in the current graphic panel of GLCD at coordinates x y Parameters Description o x dot position on x axis y dot position on y axis color color parameter Valid values Spi TG963C BLACK and Spi T6963C WHITE Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C dot x0 pcolor 512 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi T6963C Write Char void SPI T6963C write char unsigned char c unsigned char x i char y unsign
268. a different name 1 Make sure that the window containing the file that you want to save is active 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 Related topics File Menu File Toolbar Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 85 2 Environment mikroC PRO for PIC 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
269. a is ready read it if UART1 Data Ready 1 receive VARTI Read 4 ie 1 if data is for em 0 if there is data in the receive register Use the function to test if the transmit shift register is empty or not Requires UART HW module must be initialized and communication established before q using this function See UART1_Init If the previous data has been shifted out send next data if Tx Idle 1 UART1 Write data UART1 Read Returns the received byte Function receives a byte via UART Use the function UART1 Data Ready to Description test if data is ready first Reauires UART HW module must be initialized and communication established before q using this function See UART1_Init If data is ready read it if UARTI Data Ready 1 1 receive Read 554 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 7 UART1 Read Text Prototype Description void UART1 Read Text char Output char Delimiter char Attempts Nothing 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 proce dure exits if the delimiter is not found Parame
270. a now points to the next element of array a ed e 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 P points to the last array element P 11s legal but 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 point ing to one element past 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 af int 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 3 0 x n ate 4 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 181 6 Language Reference mikroC PRO for PIC 182 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
271. ack what s been received UART1 Init 4800 initialize UART1 module Delay ms 100 while 1 if UART1 Data Ready 1 jf ah data 15 received UART1 Read Text output delim 10 reads text until delim is found Write Text output sends back text UART_Set_Active void UART Set Active char read ptr void write ptr unsigned char data_ char ready ptr char Ex pre 3 Sets active UART module which will be used by the UART library routines Parameters Description wes UART Read handler write ptr UART1 Write handler ready ptr 1 Data Ready handler tx idle ptr UART1 Tx Idle handler Routine is available only for MCUs with two UART modules Used UART module must be initialized before using this routine See UARTI Init routine Activate UART2 module UART Set Active amp UART1 Read amp UART1 Write amp UART1 Data Ready amp UART1 Tx Idle MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Library Example CHAPTER 7 Libraries The example demonstrates a simple data exchange via UART When PIC MCU receives data it immediately sends it back If PIC is connected to the PC see the figure below you can test the example from the mikroC PRO for PIC terminal for RS 232 communication menu choice Tools Terminal char uart rd void main VARTI Init 9600 Initialize U
272. ander must be initialized 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 0 0000 set expander s porta and portb to be output Expander Write PortAB 0 55 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Expander Set DirectionPortA Prototype void Expander Set DirectionPortA char ModuleAddress char Data The function sets Port Expander s PortA direction Parameters Description ModuleAddress 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 configures the correspon ding pin as an input Cleared bit configures the corresponding pin as an output Port Expander must be initialized See Expander Init Example Set Port Expander s PORTA to be output Expander Set DirectionPortA 0 0x00 Expander Set DirectionPortB Prototype void Expander Set DirectionPortB char ModuleAddress char Data Nothing The function sets Port Expander s PortB direction Parameters Description ModulcAddress Port Expander hardware address see schema
273. ant controllers through the 4 bit interface An example of Lcd con nections is given on the schematic at the bottom of this page For creating a set of custom Lcd characters use Lcd Custom Character Tool External dependencies of LCD Library The following variables must be defined in all projects using Lcd Library extern sfr sbit Register Select line sbit LC LCD RS egister select line RB4 bi extern sfr sbit sbit LCD EN Enable line RB5 bi tern sfr sbit Data 7 line sbit LCD LCD Ds RBS bit extern sfr sbit Data 6 line sbit LCD LCD D6 RB2 bit extern sfr sbit Data 5 line sbit LCD LCD D5 i RBI pity extern sfr sbit LCD LCD D4 Didier bi extern sfr sbit sbit LCD RS Direction Direct ren at TRISB4 bit Description sfr sbit i EN Direction Direction Dit sfr sbit it D7 Direction Direction piti sfr sbit Data 6 direction pin it 1 D6 Direction Direction a pin bit sfr sbit it D5 Direction Data 5 direction pin m Direction bit sfr sbit Data 4 direction sbit LCD D4 Direction Direction pin RISBO bit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 351 7 Libraries mikroC PRO for PIC Library Routines Lcd Init Lcd Out Lcd Out Cp Lcd Chr Lcd Chr Cp Lcd Cmd Lcd Init Prototype Returns Nothing Initializes LCD module Global v
274. ariables LCD D7 Data bit 7 LCD D6 Data bit 6 LCD D5 Data bit 5 LCD D4 Data bit 4 LCD RS Register Select data instruction signal pin LCD EN Enable signal LCD D7 Direction Direction of the Data 7 pin LCD D6 Direction Direction of the Data 6 pin LCD D5 Direction Direction of the Data 5 pin LCD D4 Direction Direction of the Data 4 pin LCD RS Direction Direction of the Register Select pin LCD EN Direction Direction of the Enable signal pin X CUN eS t be defined before using this function Lcd pinout settings sbit LCD RS at RB4 bit sbit LCD EN at RB5 bit sbit LCD D7 at RB3 bit sbit LCD D6 at RB2 bit shit LCD DS at bit sbit LCD D4 at RBO bit Pin direction sbit LCD RS Direction at TRISB4 bit sbit 1 EN Direction at TRISB5 bit sbit 1 07 Direction at TRISB3 bit sbit 1 D6 Direction at TRISB2 bit Sbit LCD D5 Direction at TRISB1 bit sbit LCD D4 Direction at TRISBO bit U er 1 ios cr oo ica Tert 352 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Lcd Out Prototype void Lcd Out char row char column char text Prints text on Lcd starting from specified position Both string variables and liter als can be passed as a text 2 4 Parameters Description row Starting position row number
275. as an error in writing Library needs to be initialized see Mmc Init error Mmc Write Sector sector data Mmc Read Cid Prototype unsigned char Mmc Read Cid char data for registers Returns Returns 0 if 0 if read was successful or 1 if an error occurred was successful or 1 if 0 if read was successful or 1 if an error occurred error occurred ee reads CID register and returns 16 bytes of content into Description data_for registers Requires Library needs to be initialized see Mmc_Init Example rror Mmc Read Cid data Mmc_Read_Csd Prototype unsigned char Mmc Read Csd char data for registers Returns 0 if read was successful or 1 if an error occurred Function reads CSD register and returns 16 bytes of content into Description data for registers Requires Library needs to be initialized see Mmo Init 000000000 Library needs to be initialized see Mmo Init 000000000 to be initialized see Init Example rror Mmc Read Csd data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 371 7 Libraries mikroC PRO for PIC Mmc Fat Init Prototype unsigned short Mmc Fat Init Description 0 if MMC SD card was detected and successfuly initialized 1 f FAT16 boot sector was not found 255 if MMC SD card was not detected Initializes MMC SD card reads MMC SD FAT 16 boot sector and extracts neces sa
276. 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 prod uct with the mikroElektronika Associates software that you upgraded You may use the upgrade version of Software only in accordance with the License Agreement 4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 1 mikroC PRO for PIC Introduction LIMITED WARRANTY Respectfully excepting the Redistributables which are provided as is without war ranty of any kind mikroElektronika Associates warrants that Software once updat ed and properly used will perform substantially in accordance with the accompany ing 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 liab
277. aste ert apiid EE 126 alert 127 127 Delay MS SCRIPT 128 MS ETT a 128 Delay Hee hee deu aeo EP E X EE Aud 129 Clock KHZ duc ERE EN ER SEDE 129 Clock 2 oe 130 Get Fosc kHz 22 22 cde we bao pe Rr Rp RARE ERU d 130 Code Optimization 1 130 Constant folding i e dette e ere d eet cao 130 Constant 130 Copy propagation 21 4 4 131 Value numbering 2 2 2 131 Dead code elimination 131 St ck allocation i er Pie eid o 131 Local vars optimization 131 Better code generation and local 131 CHAPTER 5 Types Efficiency 134 Nested Calls Limitations 134 PICTS8EXxJXxx SpeclflCS cioara sate gaii iiis kinas 135 Shared Address SFRS 135 16 5
278. aster 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 ini tiate 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 module 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 Note The library uses the UART module for communication The user must initial ize the appropriate UART module before using the RS 485 Library For MCUs with two UART modules it is possible to initialize both of them and then switch by using the Set Active function See the UART Library functions 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 Note Since some PIC18 MCUs have multiple UART modules appropiate UART module must be initialized Switching between UART modules in the UART library is done by the UART Set Active function UART module has to be previously ini tialized External dependencies of RS 485 Library The following variable must be defined in all proj Description ects using RS 485 Library
279. at the time of declaration initializa tion A part of the declaration which specifies the initialization is called initializer Initializers for globals and static objects must be constants or constant expres sions The initializer for an automatic object can be any legal expression that eval uates to an assignment compatible value for the type of the variable involved Scalar types are initialized with a single expression 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 1j char s hello struct complex 10 1 20 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 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 initial izes successive elements in the array For more information refer to Arrays Automatic Initialization The mikroC PRO for PIC does
280. ata to be written data len number of bytes to be written 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 void Cf Fat Set File Date unsigned int year unsigned short month unsigned short day unsigned short hours unsigned short mins unsigned short seconds Sets the date time stamp Any subsequent file writing operation will write this stamp to currently assigned file s time date attributs Parameters Description year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 day 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 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 Fat Set File Date 2005 9 30 17 41 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 285 7 Libraries mikroC PRO for PIC Cf Fat Set File Date void Cf Fat Get File Date unsigned int year unsigned short month unsigned shor
281. ations Universal advice is to use the smallest possible type in every situation It applies to all programming in general and doubly so with microcontrollers Get to know your tool When it comes down to calculus not all PIC MCUs are of equal performance For example PIC16 family lacks hardware resources to multi ply two bytes so it is compensated by a software algorithm On the other hand PIC18 family has HW multiplier and as a result multiplication works considerably faster Nested Calls Limitations Nested call represents a function call within function body either to itself recursive calls or to another function Recursive function calls are supported by mikroC PRO for PIC but with limitations Recursive function calls can t contain any function parameters and local variables due to the PIC s stack and memory limitations mikroC PRO for PIC limits the number of non recursive nested calls to 8 calls for PIC12 family 8 calls for PIC16 family 91 calls for PIC18 family Note that some of the built in routines do not count against this limit due to their inline implementation Number of the allowed nested calls decreases by one if you use any of the follow ing operators in the code It further decreases if you use interrupts in the program Number of decreases is specified by number of functions called from inter rupt Check functions reentrancy If the allowed number of nested calls is exceeded the compil
282. ay Cyc Prototype void Delay Cyc char Cycles div by 10 Creates a delay based on MCU clock Delay lasts for 10 times the input param eter in MCU cycles Description Note that Delay is library function rather than a built in routine it is pre sented in this topic for the sake of convenience There are limitations for Cycles div by 10 value Value Cycles div by 10 must be between 3 and 255 Requires Nothing Example os Mole Hundred MCU cycles pause Clock Khz Prototype unsigned Clock Khz void Returns Device clock KHz rounded to the nearest integer Function returns device clock in KHz rounded to the nearest integer Description 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 129 4 Specifics mikroC PRO for PIC Clock Mhz Prototype unsigned short Clock Mhz void Returns Device clock in MHz rounded to the nearest integer Function returns device clock in MHz rounded to the nearest integer Description 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 pene ecm Get_Fosc_kHz Prototype unsigned long Get Fosc kHz void Returns Device clock in KHz rounded to the nearest integer Function returns device cl
283. be unique The mikroC PRO for PIC 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 must 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 with in 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 2 ILLEGAL colors duplicate tag double red 2 ILLEGAL redefinition of red blue 37 back in int blue scope Duration Duration closely related to a storage class defines a period during which the declared iden tifiers have real physical objects allocated in memory We also distinguish between com pile time and run time objects Variables for instance unlike typedefs and types have real memory allocated during ru
284. ber of hardware breakpoints is limited 1 for P16 and 1 or 3 for P18 If all hardware brekpoints are used next breakpoints that will be used are software breakpoint Those breakpoints are placed inside mikrolCD and they simulate hard ware breakpoints Software breakpoints are much slower than hardware break points This differences between hardware and software differences are not visible in mikrolCD software but their different timings are quite notable so it is important to know that there is two types of breakpoints 108 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 mikroC PRO for PIC mikrolCD mikrolCD In Circuit Debugger Overview 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 correspon ding location in source code Breakpoints a Line File Name 50 Lcd c 54 Lcd c 58 Lcd c 64 Lcd c 75 Lcd c 76 Lcd c MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 109 3 mikrolCD mikroC PRO for PIC Watch Window Debugger Watch Window is the main Debugger window which allows you to moni tor program items while running your program To show the Watch Window select View Debug Windows Watch Window from the drop down menu The Watch Window displays variables and registers of PIC with their addresses a
285. ble case label If no case satisfies the condition the default case evaluates if the label default is speci fied For example if a variable has value between 1 and 3 the following switch would MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 223 6 Language Reference mikroC PRO for PIC always return it as 4 switch 1 4 1 1 2 1 3 itt To avoid evaluating any other cases and relinquish control from switch each case should 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 case Message Invalid state 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 iter ation statements in the mikroC PRO for PIC W while B 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 valu
286. braries mikroC PRO for PIC abs Function returns the absolute i e positive value of a atof Prototype double atof char s 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 Description optional whitespace at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize includ ing a null character atoi Prototype int atoi char s 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 Description whitespace and a sign at the beginning The string will be processed one charac ter at a time until the function reaches a character which it doesn t recognize including a null character atol Prototype long atol char s 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 Description 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 recog nize including a null character div Prototype div t div int number int denom Function computes the result of division of the numerator number by the denom
287. by the address if a for mal parameter is declared as a pointer The pointed object can be accessed by using the indirection operator 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 PIC 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 PIC converts the passed argument to the type of the declared parameter according to the same conversion rules as in assignment state ments 204 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference If a prototype is present the number of arguments must match The types need to be compatible 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 accept able to a function prototype Note If the function prototype does not match the actual function definition the mikroC PRO for PIC will detect this if and only if that definition is in the same compilation unit as the prototype If you
288. c Types and Pointers d Ox1AC30F4 tmp Hi d Equals 0x30 Returns Returns next to the highest byte of number bits 16 23 Description Requires Function returns the highest byte of number Function does not interpret bit pat terns 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 Arguments must be variable of scalar type i e Arithmetic Types and Pointers d 0 1 30 4 tmp Higher d Equals MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 4 mikroC PRO for PIC Specifics Highest Returns Returns the highest byte of number bits 24 31 Function returns next to the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register Description 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 Requires Arguments must be variable of scalar type i e Arithmetic Types and Pointers d Ox1AC30F4 tmp Highest d Equals 0x01 Delay us Creates a software delay in duration of time in us microseconds a constant Range of applicable constants depends on the oscillator frequency Description This is an inline routine code is generated in the place o
289. can also represent the pointer reference operator MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 209 6 Language Reference mikroC PRO for PIC Binary Arithmetic Operators Division of two integers returns an integer while remainder is simply truncated for example equals 1 qow e f equals 5 but Was 923 us 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 7 3j equals 1 7 5 3 equals 1 Arithmetic operators can be used for manipulating characters TAT 325 equals a ASCII only UU ue equals both ASCII and EBCDIC Unary Arithmetic Operators Unary operators and are the only operators in C which can be either prefix e g k k or postfix e g 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 suf fix operators and postincrement and postdecrement add or subtract one from the value of the operand after the evaluation For example int j 5 J Es k k 1 j which gives us j 6 k 6 but int j 5 J kay k 1 which gives us j 5 k 6 210 MIKROELEKT
290. cape sequences are copied to the destination string in the order in which they are inter preted Format specifications always begin with a percent sign and require Description additional arguments to be included in the function call The format string is read from left to right The first format specification encoun tered 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 specifica tions 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 li Lo hd conversion type 596 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries 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 num ber or pointer as shown in the following table conversion type Argument Type P Unsigned hexadecimal number using 0123456789abcdef Pu Unsigned hexadecimal number using 3 0123456789ABCEDF Floating point number using the format dddd dddd Floating poi
291. cedence rules our code sequence is actually inter MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 147 6 Language Reference mikroC PRO for PIC CONSTANTS Constants or literals are tokens representing fixed numeric or character values The mikroC PRO for PIC 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 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 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 suffixes can be used with the same constant any order or case ul Lu Ur 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 W constant has the U suffix its data type will be the first of the following that can accommodate its value unsigned short u
292. 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 b Declarations A declaration introduces one or several names to a program it informs the compil er 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 Types Structure union and enumeration tags Structure members Union members Arrays of other types Statement labels Preprocessor macros MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 193 6 Language Reference mikroC PRO for PIC 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 alloca tion 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
293. characters immediately before the f 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 There are two predefined project level defines See predefined project level defines Note For inclusion of the header files extension h use the preprocessor direc tive include See File Inclusion for more information Related topics Project Manager Project Settings Edit Project MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 83 2 Environment mikroC PRO for PIC SOURCE FILES Source files containing C code should have the extension The list of source files relevant to the application is stored in project file with extension mcppi 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 h 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 gt New Unit from the drop down menu or press Ctrl N or click the New File Icon from the File Toolbar 2 A new tab will be opened This is a new source file Select File
294. contents will be transfered to appropriate flash memory Description Seta Parameters data byte to be written 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 Cf Write Byte data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 279 7 Libraries mikroC PRO for PIC 280 Cf Read Sector void Cf Read Sector unsigned long sector number unsigned short buffer Reads one sector 512 bytes Read data is stored into buffer provided by the buffer parameter Prototype Description Parameters sector number Sector to be read buffer data buffer of at least 512 bytes in length 4 MCU ports must be appropriately initialized for CF card See read sector 22 unsigned short data 512 Cf Read Sector 22 data Cf Write Sector void Cf Write Sector unsigned long sector number unsigned short buffer Writes 512 bytes of data provided by the buffer parameter to one CF sector Prototype Description Parameters sector number Sector to be written to buffer data buffer of 512 bytes in length ports must be appropriately initialized for CF card See f write to sector 22 unsigned short data 512 Cf Write Sector 22 data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
295. corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine rom m n _ 538 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries T6963C box void T6963C box int x0 int int xl int yl unsigned char pecolor Draws a box on GLCD Prototype Parameters Description 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 yl y coordinate of the lower right box corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine Pus eem 0 119 239 127 T6963C WHITE T6963C circle Prototype void 6963 circle int x int y long r unsigned char pcolor Draws a circle on GLCD Parameters Description x X coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C init routine Ee dee 120 64 110 T6963C WHITE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 539 CHAPTER 7 Libraries mikroC PRO for PIC T6963C image P
296. cros and Macro Expansions 231 Macros with Parameters 232 Undetning rU RC Re gore 233 File Incl slOD i mco dot e gk e don em Ree 233 Explicit Pallio s Rosse ort s RE E Gun O RE es 234 Preprocessor Operators 235 Operator tr e dhe dod RUE EOE ed 235 Operator E DL 235 Conditional Compilation 236 Directives if Zelif else and 236 Directives Zifdef and Zifndef 237 7 Hardware PIC specific Libraries 240 Standard ANSI C Libraries 240 Miscellaneous Libraries 240 Library Dependencies 241 Hardware Libraries i s m cR RUD Da ee 242 LUDAN m p TIT 243 ADC R ad cs soe oe ques en Rye re EP eek LE Rue 243 Library Example secu axe Ree diene E m ge Roo Eon 243 CAN Library 525 ee Save ois a Rh poet leads Roe bee hee na 244 Library Routines 245 CANSetOperationMode
297. cs ts apne aol chr a hak 54 Memory SUMMALY eee aes Bale ae ba ead Shae 54 MACRO EDITOR za eed eee eee eRe REA OEE AE 55 Integrated Tools 1 56 USART Terminal edd Re IEEE 56 EEPROM EdItOr ti Ree 57 DOR M 58 Seven Segment 59 LCD Custom Character sss be Tii RO AE 59 Graphic LCD Bitmap Editor 60 FID Terminal Ue goaded Reed aloes 61 UDP Terminal 62 5 65 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD V Table of Contents mikroC PRO for PIC Code edito eli 2122 RI etie hr ER En 65 TOONS 2 65 8 osos Bee 66 Regular Expressions 67 Introduction 67 Simple matches 2254 deine 67 Escape SEQUENCES ek saos esr ede
298. ct Shift Ctr E project settings E Open Project Group Open project group lose Project Group Close project group un ve Project As Save active project file with the different name Open recently used project p ecent Projects Close Project Close active project 08 Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings 26 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC RUN MENU OPTIONS CHAPTER 2 Environment Start Debugger F9 5h Stop Debugger Ctrl F2 Pause Debugger F6 0 StepInto F 4 Step Over F8 O Step Out Ctri F8 fu Jump To Interrupt F2 amp Toggle Breakpoint F5 Breakpoints Shift F4 Clear Breakpoints Shift Ctrl F5 Gd Watch Window Shift F5 View Stopwatch Disassembly mode Alt D Run Description Start Software Simulator or mikrolCD In 5 start Debugger us Circuit Debugger hy Stop Debugger Ctrl F2 Stop debugger 5h Pause Debugger F6 Pause Debugger StepInto F Step Into amp Step Over F8 Step Over Step Out Ctrl F8 Step Out Jump Interrupt F2 Jump to interrupt in current project i Toggle Breakpoint F5 Toggle Breakpoint Show Hide Breakpoints Shift F4 Breakpoints 8 on Clear Breakpoints Shift Ctrl F5 Watch
299. ct 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 Error Window displays all errors detected 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 PIC 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 proj ect is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F12 12 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC MAIN MENU OPTIONS Available Main Menu options are Related topics Keyboard shortcuts CHAPTER 2 Environment MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 13 2 Environment mikroC PRO for PIC FILE MENU OPTIONS The File menu is the main entry point for manipulation with the source files n Mew Unit 3X Open Recent Files 9 Save Ctr S Save 11 dose
300. ctuators 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 identi fier and expression defined recursively Expressions are evaluated according to a certain conversion grouping associativi ty and precedence rules which depends on the operators used presence of paren theses and data types of the operands The precedence and associativity of the operators are summarized in Operator Precedence and Associativity way operands and subexpressions are grouped does not necessarily specify the actual order in which they are evaluated by the mikroC PRO for PIC 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 219 6 Language Reference mikroC
301. d Device parameter missing for example P16F Invalid parameter string Project name must be set Specifier needed 55 not found s Index out of bounds Array dimension must be greater than 0 Const expression expected Integer const expected Recursion in definition Array corrupted Arguments cannot be of void type Arguments cannot have explicit memory specificator Bad storage class Pointer to function required Function required Illegal pointer conversion to double Integer type needed Members cannot have memory specifier Members cannot be of bit or sbit type Too many initializers Too many initializers of subaggregate Already used Illegal expression with void Address must be greater than 0 55 Identifier redefined User abort Expression must be greater than 0 Invalid declarator expected or identifier typdef name redefined gt s Declarator error Specifer qualifier list expected s already used lLevel can be used only with interrupt service routines expected but sj found MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 89 2 Environment mikroC PRO for PIC Expected 7 ss Identifier redefined expected but gt s found expected but 551 found case out of switch expected but 551 found default label out of switch switch expression must evaluate to
302. d 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 393 CHAPTER 7 Libraries 394 mikroC PRO for PIC Expander Write PortB Prototype void Expander Write PortB char ModuleAddress char Data The function writes byte to Port Expander s PortB Description Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written 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 Expander Write PortAB Prototype Expander Write PortAB char ModuleAddress unsigned int Data Description The function writes word to Port Expander s ports Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Data to be written to PortA are passed in Data s higher byte Data to be written to PortB are passed in Data s lower byte Port Exp
303. d 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 PCL etc Probe the Code Assistant for specific letters Ctrl Space in Editor or refer to Pre defined Globals and Constants Here is an alphabetical listing of keywords in C asm auto break case phar const continue default double else enum xlLern tloac Lor goto if quy long register return short signed sizeof static tT switch typedef union unsigned oud volatile while Also the mikroC PRO for PIC 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 PIC Libraries NIGER OF RUOGUEAT RSXDFFROA AR DANDARERANTAREREDVAR DSISLRORONGHEDD HD WORLD 6 mikroC PRO for PIC Language Reference 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
304. data increments it and sends it back to the Master Master then does the same and sends incre mented data back to Slave etc Master displays received data on PORTB while error on receive and number of consec utive 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 EasyPIC5 board and 16F887 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 415 CHAPTER 7 Libraries RS485 Master code char dat 10 char i j sbit 6485 rxtx pin at RC2 bit sbit rs485 rxtx pin direction at TRISC2 bit direction Interrupt routine void interrupt RS485Master Receive dat void main long cnt 0 ANSEL 0 Configure AN pins ANSELH 0 PORTB 0 PORTD 0 TRISB 0 TEISD 0 1 Init 9600 Delay ms 100 initialize UART1 module mikroC PRO for PIC buffer for receving sending messages set transcieve pin set transcieve pin as digital I O RS485Master Init initialize MCU as Master dat 0 OxAA dat 1 OxF0 2 0 0 dat 4 0 ensure that message received flag is 0 5 0 ensure that error flag is 0 dat 6 0 RS485Master Send dat 1 160 1 1 enable interrupt on UART1 receive PIE2 TXIE 0 disable interrupt
305. 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 attrib utes storage class and type sometimes referred to as data type The mikroC PRO for PIC 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 syn tax of a declaration by its placement in the source code or by both of these factors storage class type identifier The storage class specifiers in the mikroC PRO for PIC are auto register static extern 196 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Auto The auto modifer is used to define that a local variable has a local duration This is the default for local variables and is rarely used auto can not be used with globals See also Functions Register A
306. def Note For the time being only funcall pragma is supported Line Continuation with Backslash Y To break directive into multiple lines end the line with a backslash define MACRO This directive continues to the following line MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 some exceptions which are discussed later Such replacements are known as macro expansions oken 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 macro expan Sion oken sequence terminates at the first non backslashed new line encoun tered Any sequence of whitespace including comments in the token sequence is replaced with a single space character After each individual macro expansion a
307. defines Accessing Individual Bits The mikroC PRO for PIC allows you to access individual bits of 8 bit variables It also supports sbit and bit data types Accessing Individual Bits Of Variables If you are familiar with a particular MCU you can access bits by name Clear Global Interrupt Bit GIE GIE bit 0 Also you can simply use the direct member selector with a variable followed by one of identifiers B1 B7 Or F0 Fi F7 With r7 being the most sig nificant bit Clear bit 0 in INTCON register INTCON BO 0 Set bit 5 in ADCONO register ADCONO F5 1 119 MMIKGEIEEKKFRGNINIKA SGERMAAERIANBIPLAEAIBUWARSGAOIUDORNSISCORIEMBSEBDEED WORLD 4 Specifics mikroC PRO for PIC There is no need of any special declarations This kind of selective access is an intrinsic feature of mikroC PRO for PIC and can be used anywhere in the code Iden 50 87 are not case sensitive and have a specific namespace You may over ride them with your own members 80 87 within any given structure See Predefined Globals and Constants for more information on register bit names Note If aiming at portability avoid this style of accessing individual bits use the bit fields instead sbit type The mikroC PRO for PIC compiler has sbit data type which provides access to bit addressable SFRs You can access them in the following manner sbit LEDA at PORTA BO sbit bit name at sfr name B
308. der Set PullUpsPortAB char ModuleAddress unsigned int PullUps Nothing The function sets Port Expander s PortA and PortB pull up down resistors Prototype Parameters ModuleAddress Port Expander hardware address see schematic at the Description bottom of this page PullUps data for choosing pull up down resistors configuration PortA pull up down resistors configuration is passed in Pullups s higher byte PortB pull up down resistors configuration is passed in Pullups s lower byte Each bit 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 397 CHAPTER 7 Libraries mikroC PRO for PIC Library Example The example demonstrates how to communicate with Port Expander 23517 Note that Port Expander pins A2 1 0 are connected to GND so Port Expander Hardware Address is 0 Port Expander module connections sbit SPExpanderRST at RCO bit sbit SPExpanderCS at RCI bit sbit SPExpanderRST Direction at TRISCO bit sbit SPExpanderCS Direction at TRISCI bit End Port Expander module connections unsigned char i 0 void main ANSEL 0 Configure AN pins as digital 1 0 ANSELH 0
309. ditional 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 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 229 6 Language Reference mikroC PRO for PIC 230 they can legally appear at any point in a program The mikroC PRO for PIC pre processor 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 Here is one commonly used directive include math h For more information on including files with the include directive refer to File Inclusion The mikroC PRO for PIC supports standard preprocessor directives null directive dif define ifdef telif ifndef else include endif Plane error fun
310. e he precision field has no effect on these field types he precision field is where you specify the maximum number of characters in the output value Excess characters are not output MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Libraries 591 7 Libraries mikroC PRO for PIC The optional characters 1 or L may immediately precede conversion type to respectively specify long versions of the integer types i u o x and x Description You must ensure that the argument type matches that of the format specifica tion You can use type casts to ensure that the proper type is passed to print out Print mikroElektronika example s header file to UART void PrintHandler char UART1 Write c void main UART1 Init 9600 Delay ms 100 PrintOut PrintHandler of PrintOut 2006 V EX mn of the PrintOut PIC18F8520 r n 10 3 MHz r n for PTOXTXn 592 function rrn Project name r n PrintOutExample Sample Copyright r n c MikroElektronika Revision History r n 20060710 r n Initial release r n Description r n Simple demonstration on usage funetionyrya Test configuration VrMn MCUs Dev Board Oscillato r BigPIlO5Xrzin HS Ext SW Modules None r n mikroC PRO NOTES r n None r n r n Get Fosc kHz 1000 MIKROELEKTRONIKA
311. e FALSE const char 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 hard ware double buffered You may use bitwise AND amp to adjust the appropriate flags For example if MsgFlag amp CANSPI RX OVERFLOW 0 Receiver overflow has occurred We have lost our previous message CANSPI_MASK The CANSPI MASK constants define mask codes Function CANSPISetMask expects one of these as it s argument const char _CANSPI MASK B1 _CANSPI MASK B2 MN Eee M CANSPI FILTER The cANSPI FILTER constants define filter codes Functions CANSPISetFilter expects one of these as it s argument const char CANSPI FILTER Bl Fl 0 CANSPI FILTER B1 F2 1 CANSPI ER B2 Fl 2 CANSPI ER B2 F2 3 268 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries CA
312. e bottom of this page check the CANSPI module for received messages received do something char msg rcvd rx flags char data 8 long msg id If any was data len CANSPISetOperationMode NSPI MODE NORMAL OxFF set NORMAL mode receive is possible CANSPI module must be in mode in which rx flags 0 clear message flags if msg rovd CANSPIRead msg id data data len rx flags 4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries CANSPIWrite Prototype Description char CANSPIWrite long id char wr data char data len char CAN SPI TX MSG FLAGS 0 if all Transmit Buffers are busy OxFF if at least one Transmit Buffer is available 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 wr data data to be sent an array of bytes up to 8 bytes in length data len data length Valid values 1 to 8 CAN RX MSG FLAGS message flags 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
313. e characters from the list If the first character after the is the class matches any character not in the list 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 and 2 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 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 t 1 matches any char from a Metacharacters Metacharacters are special characters which are the essence of regular expres sions There are different types of metacharacters described below 68 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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
314. e declaration is allowed here because the definition of doesn t need the size of a Untagged Structures and Typedefs If the structure tag is omitted an untagged structure is created The untagged structures can be used to declare the identifiers in the comma delimited member declarator list to be of the given structure type or derived from it but addition al 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 0 same as struct mystruct s etc Without tag typedef struct Mystruct Mystruct s ps 10 7 Usually there is no need to use both tag and typedef either can be used in struc ture type declarations 184 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Untagged structure and union members are ignored during initialization Note See also Working with structures 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
315. e 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 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 Description 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 chsaracter between the file name and extension MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension file attr file creation and attributs flags Each bit corresponds to the appropriate file attribut Bk Mak Descition o oof Archive 6 0x40 Device internal use only never found on disk Note Long File Names LFN are not supported MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 287 7 Libraries Requires mikroC PRO for PIC CF card and CF library must be initialized for file operations See Cf Fat Init Try to create a swap file with archive whose size will be at least 1000 sectors it sends the No of start sector over UART atr
316. e label will be padded with spaces If null string is passed rT volume will not be labeled Description Note This routine can be used instead or in conjunction with Mmc_Fat_Init rou tine Note 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 The appropriate hardware SPI module must be previously initialized Initialize SPI1 module and set pointer s SPI1 Init Advanced MASTER OSC DIV64 CLK IDLE LOW LOW 2 HIG to functions DATA SAMPLE MIDDLE Format and initialize MMC SD card and MMC FAT16 library glob als if Mmc Fat QuickFormat amp mmc fat label Reinitialize the SPI module at higher speed prescaler SPI1 Init Advanced MAST CLK IDLE LOW LOW 2 HIG ER OSC DIVA 5 E MIDDLE change primary MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 373 7 Libraries mikroC PRO for PIC Mmc Fat Assign Prototype unsigned short Mmc Fat Assign char filename char file cre attr 1 iffile already exists or file does not exist but new file is created 0 iffile does not exist and no new file is created Assigns file for file operations read write delete All subsequent file opera tions will be applied over the assigned file
317. e must be in config mode for filter settings Set id of filter Bl rto 3 CANSPISetFilter CANSPI FILTER B1 F1 3 CANSPI CONFIG XTD MSG MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 263 7 Libraries mikroC PRO for PIC CANSPIRead Prototype Description 264 char CANSPIRead long id char rd data char data len char CANSPI RX MSG FLAGS 0 if nothing is received oxFF if one of the Receive Buffers is full message received If at least one full Receive Buffer is found it will be processed in the following way Message ID is retrieved and stored to location provided by the id parameter Message data is retrieved and stored to a buffer provided by the data parameter Message length is retrieved and stored to location provided by the data len parameter Message flags are retrieved and stored to location provided by the CAN RX MSG FLAGS parameter Parameters id message identifier storage address rd data data buffer an array of bytes up to 8 bytes in length data len data length storage address CAN RX MSG FLAGS message flags storage address 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 th
318. e name of a valid function precedes the paren thesis 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 Code Templates Auto Complete You can insert the Code Template by typing the name of the template for instance whiles then press Ctrl J and the Code Editor will automatically generate a code You can add your own templates to the list Select Tools Options from the drop down menu or click the Show Options Icon zl and then select the Auto Complete Tab Here you can enter the appropriate keyword description and code of your template Autocomplete macros can retreive system and project information SDATES current system date TIMES current system time ICE device MCU name as specified in project settings ICE CLOCK Clock as specified in project settings COMPILER current compiler version EV EV 38 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment These macros can be used in template code see template ptemplate provided with mikroC PRO for PIC installation Auto Correct The Auto Correct feature corrects common typing mistakes To access the list of rec ognized typos select Tools Options from the drop down menu or click the Show Options Icon at and then select the Auto Correct Tab
319. e net result of the preceding scenario is that only one code section possibly empty will be compiled Directives ifdef and ifndef The ifdef and ifndef directives can be used anywhere be used they can test whether an identifier is currently defined or not The line ifdef identifier has exactly the same effect as if 1 if identifier is currently defined and the same effect as if 0 if identifier is currently undefined The other directive 1 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 237 6 Language Reference mikroC PRO for PIC 238 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Libraries mikroC PRO for PIC provides a set of libraries which simplify the initialization and use of PIC compliant MCUs and their modules Use Library manager to include mikroC PRO for PIC Libraries in you project 239 7 Libraries mikroC PRO for PIC Hardware PIC specific Libraries ADC Library CAN Library CANSPI Library Compact Flash Library EEPROM Library Ethernet PIC18FxxJ60 Library Flash Memory Library Graphic LCD Library FC Library Keypad Library
320. e of expression is false The test takes place before statement is executed Thus if expression evaluates to false 224 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference on the first pass the loop does not execute Note that parentheses around expres sion are mandatory is an example of calculating scalar product of two vectors using the while statement int 0 i 0 while i lt Ss seca bi a 3 i Note that body of the loop can be a null statement For example while Do Statement The ao 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 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 state ment do Steal a opas while i n MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 225 6 Language Refere
321. e unsigned short Soft SPI Read char sdata Returns Byte received via the SPI bus This routine performs 3 operations simultaneously It provides clock for the Soft ware SPI bus reads a byte and sends a byte Description Parameters sdata data to be sent 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 opera tion data read Soft SPI Read data send Soft SPI Write This routine sends one byte via the Software SPI bus Description Parameters sdata data to be sent Soft SPI must be initialized before using this function See Soft SPI Init routine Write a byte to the Soft SPI bus Soft SPI Write 430 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Example This code demonstrates using library routines for Soft SPI communication Also this example demonstrates working with Microchip s MCP4921 12 bit D A convert er DAC module connections sbit Chip Select at RCO bit sbit SoftSpi CLK at RC3 bit sbit SoftSpi SDI at RC4 bit sbit SoftSpi SDO at RC5 bit sbit Chip Select Direction at TRISCO btt sbit SoftSpi CLK Direction at TRISC3 bit sbit SoftSpi SDI Direction at TRISCA bit sbit SoftSpi SDO Direction at TRISC5 bit
322. ead Byte Prototype unsigned short Read Byte void Returns a byte read from Compact Flash sector buffer Note Higher byte of the unsigned return value is cleared Reads byte from Compact Flash sector buffer location currently pointed to Description by internal read pointers These pointers will be autoicremented upon reading The corresponding MCU ports must be appropriately initialized for CF card See Cf Init Requires CF card must be initialized for reading operation See Cf Read Init Read a byte from compact flash char datar data Cf Read Byte 278 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Cf Write Init Prototype void Cf Write Init unsigned long address unsigned short sectcnt Initializes CF card for writing Description Parameters address the first sector to be prepared for writing operation sectcnt number of sectors to be prepared for writing operation corresponding MCU ports must be appropriately initialized for CF card See Requires Cf Init initialize compact flash for writing to sector 590 CE Write Init 590 19 Cf Write Byte Prototype void Cf Write Byte unsigned short data 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
323. eased if Button amp PORTB 5 1 1 RB5 plays Tone3 Tone3 while PORTB amp 0x20 Wait for button to be released if Button amp PORTB 4 1 1 RB4 plays Melody2 Melody2 while amp 0x10 Wait for button to be released if Button amp PORTB 3 1 1 RB3 plays Melody Melody while PORTB amp 0x08 Wait for button to be released MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 441 7 Libraries mikroC PRO for PIC HW Connection PIEZO SPEAKER VCC s PORTB B3 gt PORTB B4 a PORTB B5 2 a PORTB B6 m PORTB B7 D OSCILLATOR VCCO 12884914 Example of Sound Library sonnection 442 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI LIBRARY SPI module is available with a number of PIC MCU models mikroC PRO for PIC provides a library for initializing Slave mode and comfortable work with Master mode PIC can easily com municate with other devices via SPI A D converters D A converters MAX7219 LTC 1290 etc You need PIC MCU with hardware integrated SPI for example PIC16F877 Note Some PIC18 MCUs have multiple SPI modules Switching between the SPI modules in the SPI library is done by the SPI Set Active function SPI module has to be previously
324. ecifier needed Invalid declarator expected or identifier Finished with errors 09 Dec 2008 10 04 01 Double click the message line in the Error Window to highlight the line where the error was encountered Related topics Error Messages MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 47 2 Environment mikroC PRO for PIC STATISTICS After successful compilation you can review statistics of your code Click the Statis tics Icon Memory Usage Windows Provides overview of RAM and ROM usage in the various forms RAM Memory Usage Displays RAM memory usage in a pie like form 48 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Used RAM Locations Displays used RAM memory locations and their names Print to file SFR Locations Displays list of used SFR locations MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 49 2 Environment mikroC PRO for PIC ROM Memory Usage Displays ROM memory space usage in a pie like form Statistics Print to file RAM Memory Usage ROM Memory Usage Used RAM Locations SFR Locations ROMM 5758 bytes 70 lemory 2433 bytes 30 3 8191 bytes Constants Functions Sorted By Name Functions Sorted By Size Functions Sorted By Address Functions Sorted By Name Chart
325. ectors occupied by this file Therefore it is recomended to erase such file if it exists before calling this function If it is not erased and there is still enough space for new swap file this function will delete it after allocating new memory space for 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 Swap file can be considered as a window on the media where user can freely write read the data It s main purpose mikroC s 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 Description Parameters 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 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 con vert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with first
326. ed but s found Operator gt s is not applicable to these operands gt s Assigning to non lvalue 251 Cannot cast 55 to gt s Cannot assign s 0125 Lvalue required Pointer required Argument is out of range Undeclared identifier 251 in expression Too many initializers Cannot establish this baud rate at 5 MHz clock Stack overflow Invalid operator 5 Expected variable but constant 551 found Expected constant but 551 found Ss cannot be used outside a loop Unknown type 251 Variable 251 is redeclared Undeclared identifier 5j Output limit has raised 2K words 3s has already been declared 251 Type mismatch expected 5251 5 found File 551 not found 251 There is not enough RAM space for all variables There is not enough ROM space Invalid type in Array Division by zero Incompatible types 5s s Too many characters 88 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Assembler instruction s was not found Project name must be specified Unknown command line Option 5 File extension missing 251 Bad FO argument s Preprocessor exited with error code sj Bad absolute address s Recursion or cross calling of Reentrancy is not allowed function s called from two threads no files specifie
327. ed char Man Synchro 255 if synchronization was not successful Half of the manchester bit length given in multiples of 10us upon suc cessful synchronization Measures half of the manchester bit length with 10us resolution To use this function you must first prepare the MCU for receiving See Requires Man Receive Init unsigned int man half bit len man half bit len Man Synchro 362 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Man Break Man Receive is blocking routine and it can block the program flow Call this routine from interrupt to unblock the program execution This mechanism is sim Description ilar to WDT Note Interrupts should be disabled before using Manchester routines again note at the top of this page char datal error counter 0 void interrupt if INTCON TOIF if counter gt 20 Man Break eounter 0 reset counter else increment counter INTCON TOIF 0 Clear TimerO overflow interrupt flag void main OPTION REG 0x04 f IMRO prescaler set to 1 32 Man Recerve InTt try Man Receive with blocking prevention mechanism INTCON GIE 1 Global interrupt enable INTCON TOIE 1 Enable TimerO overflow interrupt datal Man Receive amp error INTCON GIE Global interrupt disable MIKROELEKTRONIKA
328. ed char mode Writes a char in the current text panel of GLCD at coordinates x y Prototype Parameters c Char to be written x Char position on x axis y Char position on y axis node mode parameter Valid values T6963C ROM MODE OR SPI T6963C ROM MODE T6963C ROM MODE AND and T6963C ROM MODE TEXT Description 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 details see the T6963C datasheet Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C write char A 22 23 AND j MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 513 7 Libraries mikroC PRO for PIC Spi T6963C write Text void SPI T6963C write text unsigned char str unsigned char x Prototype unsigned char y unsigned char mode
329. eight Prototype void T6963C cursor height unsigned char n Set cursor size Description Parameters n cursor height Valid values 0 7 Toshiba Glcd module needs to be initialized See the T6963C init routine 544 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries T6963C Graphics Enable disable graphic displaying Description Parameters n on off parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See the T6963C init routine enable graphic displaying T6963C graphics 1 T6963C text Enable disable text displaying Description Parameters n on off parameter Valid values o disable text dispaying and 1 enable text displaying Toshiba Glcd module needs to be initialized See the T6963C init routine enable text displaying T6963C text 1 T6963C cursor Set cursor on off Description Parameters 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 cursort l MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 545 7 Libraries T6963C Cursor Blink Prototype void T6963C cursor blink char n mikroC PRO for PIC Nothing Enable di
330. eive buffer corruption ENc28760 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 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 Description Note Spi Ethernet doPacket must be called as often as possible in user s code Ethernet module has to be initialized See Spi Ethernet Init Ethernet doPacket process received pack 456 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi Ethernet putByte Prototype void SPI Ethernet putByte unsigned char v This is MAC module routine It stores one byte to address pointed by the cur rent NC28 760 write pointer EWRPT Deseripuen Parameters v Value to store Ethernet module has to be initialized See Spi Ethernet Init char data SPI Ethernet putByte data put an byte into ENC28J60 buffer Spi Ethernet putBytes Prototype void SPI Ethernet putBytes unsigned char ptr unsigned char n This is MAC module
331. elektronika mikroC PRO for PIC Uses P16 SP C Led Led e Math mcl Lib MathDouble mcl Lib System mcl Lib Delays mcl Lib LcdConsts mcl Lib Lcd mcl Parameters used in the example MSF Short Message Format used for internal purposes by IDE Generate debug info p16F887 MCU 16F887 selected c Turn on case sensitivity 011111114 Miscellaneous output options o10 Set oscillator frequency in MHz N C Led Led mcppi SP C V Program Files Mikroelektronika mikroC PRO for PIC defs Output files generated to file path specified by filename SP C Program Files Mikroelektronika mikroC PRO for PIC defs Add directory to the search path list SP C Program Files Mikroelektronika mikroC PRO for PIC uses Add directory to the search path list SP C Led Add directory to the search path list Lcd c Lib Math mcl MathDouble mcl Lib System mcl Lib Delays mcl Lib LcdConsts mcl Lib Led mcl Specify input files MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 73 2 Environment mikroC PRO for PIC PROJECTS The mikroC PRO for PIC organizes applications into projects consisting of a single project file extension 1 and one or more source files extension mikroC PRO for PIC IDE allows you to manage multiple projects see Project Manager Source files can be compiled only if they are part
332. elete Layout Icon 2 34 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Auto Hide Auto Hide enables you to see more of your code at one time by minimizing tool win dows along the edges of the IDE when not in use WClick the window you want to keep visible to give it focus WClick the Pushpin Icon on the title bar of the window 4 B FirstProject mcppi 7 Sources SecondProject c 7 Header Files E Binaries 73 Project level defines 7j Image Files E Output Files E Other Files dabeue yy palo 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 point er over the tab The window slides back into view and is ready for use MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 35 2 Environment mikroC PRO for PIC ADVANCED 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 Advanced Editor Features Adjustable Syntax Highlighting Code Assistant Code Folding Parameter Assistant Code Tem
333. ement 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 Warran ty 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 6 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 1 mikroC PRO for PIC Introduction TECHNICAL SUPPORT 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 develop ment of the mikroC PRO for PIC are always appreciated feel free to drop a note or two on our Wishlist In our Knowledge Base www mikroe com en kb you can find the answers to Fre quently 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 effici
334. endUDP SPI Ethernet dnsResolve SPI Ethernet initDHCP SPI Ethernet doDHCPLeaseTime SPI Ethernet renewDHCP MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 451 CHAPTER 7 Libraries mikroC PRO for PIC Spi Ethernet Init Description 452 void SPI Ethernet Init unsigned char mac unsigned char ip unsigned char fullDuplex Nothing This is MAC module routine It initializes 282760 controller This function is internaly splited into 2 parts to help linker when coming short of memory ENC28360 controller settings parameters not mentioned here set to default receive buffer start address 0x0000 receive buffer end address 0 1 transmit buffer start address 0x19AE transmit buffer end address 0xirrr RAM buffer read write pointers in auto increment mode receive filters set to default 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 0 0 12 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 duplex loopback disabled
335. eneral rule is that the nested conditionals are parsed starting from the innermost conditional with each else bound to the nearest available i 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 Note 4if and eise preprocessor statements directives look similar to if and eise statements but have very different effects They control which source file lines are compiled and which are ignored Switch Statements The switch statement is used to pass control to a specific program branch based on a certain condition The syntax of the switch statement is switch expression case constant expression 1 statement 1 case constant expression n statement n default statement First the expression condition is evaluated The switch statement then com pares it to all available constant expressions following the keyword If a match is found switch passes control to that matching case causing the statement fol lowing 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 possi
336. ent Advanced Edit Toolbar aui EE ud Advanced Edit Toolbar comes with following options Icon Description Ld Comment selected code or put single line comment if there is no selection Uncomment selected code or remove single line comment if there is ie no selection E Select text from starting delimiter to ending delimiter EHDI Go to ending delimiter Go to line Indent selected code lines Be Outdent selected code lines Generate HTML code suitable for publishing current source code on Lal the web Find Replace Toolbar Find Replace Toolbar is a standard toolbar with following options Icon Description Find text in current editor Find next occurence p 5 Find previous occurence Replace text Find text in files PROG MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 21 2 Environment mikroC PRO for PIC Project Toolbar Project Toolbar comes with following options Icon Description Ege New project ER Open Project st Save Project Close current project Edit project settings Add existing project to project group Remove existing project from project group Add File To Project GR Gr Remove File From Project Build Toolbar t bad Build Toolbar comes with the following options Icon Description
337. ently which is in our mutual interest We respond to every bug report and ques tion in a suitable manner ever improving our technical support MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 1 Introduction mikroC PRO for PIC HOW TO REGISTER The latest version of the mikroC PRO for PIC is always available for downloading from our website It is a fully functional software libraries examples and compre hensive help included The only limitation of the free version is that it cannot generate hex output over 2 KB 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 PIC then you should consider the possibil ity of purchasing the license key Who Gets the License Key Buyers of the mikroC PRO for PIC are entitled to the license key After you have completed the payment procedure you have an option of registering your mikroC PRO 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 Register from the drop down menu or click the How To Register Icon 2 Fill out the registration form figure below select your distributor and click the Send button 8 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD C
338. ents specify a flow of control as the program executes In the absence of specific jump and selection statements statements are executed sequentially in the order 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 iden tifier 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 221 6 Language Reference mikroC PRO for PIC Expression Statements Any expression followed by a semicolon forms an expression statement expression The mikroC PRO for PIC executes an expression statement by evaluati
339. enu View gt Debug Windows View Code The Code Watch window shows code hex code written into PIC There is action button concerning Code Watch window Read Code Read Code reads code from PIC and loads it up in View Code Window Also you can set an address scope in which hex code will be read CODEWatch Address Scope KT 000000 1 00 E03 1683 1703 E3 EE3 804 E4 lt ETX gt SO f S 80A ES 158A 160A 1683 1703 80E 1683 LF B5 8 5 NAI 1703 E7 1683 1703 80F 1683 1703 E6 lt ETX gt lt gt c f lt 1683 1703 1706 1386 1283 1703 1786 00 SYN lt ETX gt ETB 1F06 2E20 1B06 2E22 1386 1683 1703 1786 lt ACK gt US lt SPC gt 1683 1703 3018 ED 1283 1703 1F06 2E2E SYN lt ETX gt ETB 1806 2 30 1003 1886 1403 1683 1703 DEA lt gt lt ESC gt 0 DEB DEC BED 2 2 301E 8A 6 390F CR CR lt VT gt 3E44 1803 ASA 82 2 54 2E6B 2E84 2 8 D gt lt ETX gt CAN 5 2EA7 2ED3 2EF8 2F1B 2F51 2F5B 2E28 2E28 6 6 8 ESC 10 2E28 2E28 2E28 2E28 1683 1703 1386 1683 C C GC f lt SYN gt lt 1703 867 EB 866 EC 3010 ED 301E lt gt lt ETB gt g B5 9 3064 2F82 1283 1703 1386 1683 d0 f DC2 1703 1786 2E28 1683 1703 1386 1683 1703 lt ETX gt lt gt t lt ETB 3001 EA 30E3 EB 87F EC 3018 ED lt SOH gt 06 806 lt 301E 9 3070 8 282 1283 1703 1386 lt 5 gt 0 0 7 1683 1703 1786 2 28 1383 186C
340. equested baud rate is too low then calculated parameter for calling Delay exceeeds Delay Cyc argument range If requested baud rate is too high then rounding error of Delay argument cor rupts Software UART timings This will initialize software UART and establish the communication at 9600 bps char error error Soft UART Init amp PORTC 7 6 14400 0 Initialize Soft UART at 9600 bps 434 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Soft UART Read Prototype char Soft UART Read char error Byte received via UART 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 Break routine Description Parameters error Error flag Error code is returned through this variable 0 no error 1 stop bit error 255 user abort Soft UART Break called Software UART must be initialized before using this function See the Soft UART Init routine char data error wait until data is received do data Soft UART Read amp error while error Now we can work with data Xf data saat MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 435 7 Libraries mikroC PRO for PIC Soft UART Write Prototype void Soft UART Write char udata This routine sends one byte via the Softwa
341. er as used initialization see Hid Enable Parameter len Description should specify a length of the data to be transmitted Function call needs to be repeated as long as data is not successfuly sent Requires USB HID needs to be enabled before using this function See Hid Enable retry until success while Hid Write amp my Usb Buff 1 560 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Hid Disable CHAPTER 7 Libraries Disables USB HID communication USB HID needs to be enabled before using this function See Hid Enable Library Example The following example continually sends sequence of numbers 0 255 to the PC via Universal Ser usbdsc c must be included in the project via mikroC PRO for PIC IDE tool or via include mechanism in source code ial Bus unsigned short m k unsigned short userRD buffer 64 unsigned short userWR buffer 64 void interrupt asm CALL Hid InterruptProc asm nop void Init Main 1 Disable all interrupts Disable GIE PEIE TMROIE INTOIE RBIE ICON e s 2 0 5 0 0 IN INI INT Disable Priority Levels on interrupts RCON 1 2 PIRI PIR2 IPEN 0 0 0 0 0 Configure all ports with analog function as digital ADCON1 p Bot RISA TRISB E a E RISC RISE
342. er s internal register address Data data to be written Requires Port Expander must be initialized See Expander Init Write a byte to the Port Expander s register Expander Write Byte 0 1 FF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 391 CHAPTER 7 Libraries mikroC PRO for PIC Expander Read PortA Prototype char Expander Read PortA char ModuleAddress Description The function reads byte from Port Expander s PortA Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as an 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 input read data Expander Read PortA 0 Expander Read PortB Prototype char Expander Read PortB char ModuleAddress Description The function reads byte from Port Expander s PortB Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as input See Expander Set Direc tionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTB char read data
343. er will report a stack overflow error 134 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 5 mikroC PRO for PIC PIC Specifics PIC18FxxJxx Specifics Shared Address SFRs mikroC PRO for PIC does not provide auto setting of bit for acessing alternate reg ister This is new feature added to pic18fxxjxx family and will be supported in future In several locations in the SFR bank a single address is used to access two differ ent hardware registers In these cases a legacy register of the standard PIC18 SFR set such as OSCCON T1CON etc shares its address with an alternate reg ister These alternate registers are associated with enhanced configuration options for peripherals or with new device features not included in the standard PIC18 SFR map A complete list of shared register addresses and the registers associated with them is provided in datasheet PIC16 Specifics Breaking Through Pages In applications targeted at PIC16 no single routine should exceed one page 2 000 instructions If routine does not fit within one page linker will report an error When confront with this problem maybe you should rethink the design of your application try breaking the particular routine into several chunks etc Limits of Indirect Approach Through FSR Pointers with PIC16 are near they carry only the lower 8 bits of the address Com piler will automatically clear the 9th bit upon startup so that
344. erence between the first dif fering 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 2 and vice versa void memcpy void dl void s1 int n Function copies characters from the object pointed to by s1 into the object point ed to by If copying takes place between objects that overlap the behavior is undefined The function returns address of the object pointed to by void memmove void to void from register int n Function copies n characters from the object pointed to by from into the object pointed to by to Unlike memcpy the memory areas to and from may overlap The function returns address of the object pointed to by void memset void p1 char character int n 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 pl MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC strcat Prototype Description strchr Prototype Description strcmp Prototype Description strcpy Prototype Description strlen CHAPTER 7 char strcat char to char from Function appends 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
345. ermi nal of mikroC PRO for PIC Tools USB HID Terminal The default name for descriptor file is but you may rename it The provided code in the Examples folder works at 48MHz and the flags should not be modified without consulting the appropriate datasheet first Library Routines Hid Enable Hid Read Hid Write Hid Disable MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 559 7 Libraries mikroC PRO for PIC Hid Enable Prototype void Hid Enable unsigned readbuff unsigned writebuff Enables USB HID communication Parameters readbuff and writebuff are the Read Buffer and the Write Buffer respectively which are used for HID com Description munication This function needs to be called before using other routines of USB HID Library Example Hid Enable amp rd amp wr Hid Read Prototype unsigned char Hid Read void Number of characters in the Read Buffer received from the host Description Receives message from host and stores it in the Read Buffer Function returns P the number of characters received in the Read Buffer USB HID needs to be enabled before using this function See Hid Enable Example Hid Write Prototype unsigned short Hid Write unsigned writebuff unsigned short len Returns 1 if data was successfuly sent 0 if not Function sends data from Write Buffer writebuf to host Write Buffer is the same paramet
346. ers 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 O then zeros are padded instead of blanks The width field never truncates a field If the length of the out put value exceeds the specified width all characters are output Description The precision field is a non negative number that specifies the number of char acters to print number of significant digits or number of decimal places The pre cision field can cause truncation or rounding of the output value in the case of a floating point number as specified in the following table MeaningMeaning of the precision field precision field is where you specify the minimum number of digits that will be included in the output value Digits are not trun cated 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 ke precision field is where you specify the maximum number of significant digits in the output value precision field has no effect on
347. es SPI Glcd Set Font SPI Glcd Write Char SPI Glcd Write Text SPI Glcd Image Spi Glcd Init mikroC PRO for PIC Prototype void SPI Glcd Init char DeviceAddress Initializes the GLCD module via SPI interface Parameters Description DeviceAddress spi expander hardware address see schematic at the bottom of this page Global variables SPExpanderCS SPExpanderRST Direction Direction of the Chip Select pin SPExpanderCS SPExpanderRST Chip Select line Reset line Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See SPI1 Init and SPI1 Init Advanced routines Port Expander module connections sbit SPExpanderRST at RCO bit sbit SPExpanderCS at bit sbit SPExpanderRST Direction at TRISCO bit SPExpanderCS Direction at TRISC1 bit End Port Expander module connections If Port Expander Library uses SPI module 5 1 Init Initialize SPI module used with PortExpander Glad 480 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI Glcd Set Side Prototype void SPI Glcd Set Side char x pos Selects Glcd side Refer to the Glcd datasheet for detail explanation Parameters x pos position on x axis Valid values 0 127 Description The parameter os specifies the Glcd
348. es the color of the box fill O white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a box between dots 5 15 and 20 40 SPI Gled Box b 15 20 40 19 486 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI Glcd Circle void SPI Gled Circle int center int y center int radius char Prototype Draws 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 Description The parameter color determines the color of the circle line 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Init routine Draw a circle with center in 50 50 and radius 10 SPI Gled Circle 50 50 10 1 SPI Glcd Set Font Prototvpe 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 Parameters activeFont font to be set Needs to be formatted as an array of char aFontWidth width of the font characters in dots Description aFontHeight height of the font characters in dots
349. escription Parameters wrdata data to be sent You need PIC MCU with hardware integrated SPI SPI must be initialized and communication established before using this func tion See SPI1 Init Advanced or SPI1_ Init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 445 7 Libraries mikroC PRO for PIC 446 SPI Set Active Prototype void SPI Set Active char read ptr char Nothing Sets the active SPI module which will be used by the SPI routines Description Parameters read ptr Read handler Routine is available only for MCUs with two SPI modules Used SPI module must be initialized before using this function See the SPI1 Init SPI1 Init Advanced Example 221 set Active amp SPI2 Read Sets the SPI2 module active Library Example The code demonstrates how to use SPI library functions for communication between SPI module of the MCU Microchip s 4921 12 bit D A converter DAC module connections Sbit Chip Select at ROO bit sbit Chip Select Direction at TRISCO bit End DAC module connections unsigned int value void InitMain TRISBO bit 1 Set RAO pin as input TRISBI bit 1 Set RAL pin as input Chip Select 1 Deselect DAC Chip Select Direction 0 Set as Output SPIL Zssti f Initialize SPI module DAC increments 0 4095 gt output voltage 0 Vref void DAC Output unsigned i
350. ether the CANSPI module is in Normal mode and if it is do something if CANSPIGetOperationMode CANSPI MODE NORMAL 7 mikroC PRO for PIC Libraries CANSPIlinitialize void CANSPIInitialize char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CANSPI CONFIG FLAGS Initializes the CANSPI module 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 CONFIG FLAGS value Description SAM SEG2PHTS and DBEN bits set according to CANSPI CONFIG FLAGS value Parameters sJW as defined CAN controller s datasheet as defined in CAN controller s datasheet PHSEG1 as defined CAN controller s datasheet PHSEG2 as defined in CAN controller s datasheet PROPSEG as defined in CAN controller s datasheet CAN CONFIG FLAGS is formed from predefined constants see CANSPI con stants Global variables CanSpi cs Chip Select line CanSpi Rst Resetline 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 rou
351. example int al 10 int pil gal 0 int pi2 amp a 4 i s pi pil i equals 8 i gt gt 1 pi2 pi2 4 pi2 now points to 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 addi tion a structure member can be a bit field Unlike arrays structures are considered to be single objects The mikroC PRO for PIC structure type lets you handle complex data structures almost as easily as sin gle variables Note the mikroC PRO for PIC does not support anonymous structures ANSI diver gence 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 fol lowing example struct mystruct mystruct illegal struct myst
352. f the call so the call doesn t count against the nested call limit This routine generates nested loops using registers R13 R12 R11 and R10 The number of used registers varies from 0 to 4 depending on requested time in us Delay us 10 Ten microseconds pause MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 127 4 Specifics 128 Delay ms Creates a software delay in duration of time ms milliseconds a constant Range of applicable constants depends on the oscillator frequency Description 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 This routine generates nested loops using registers R13 R12 R11 and R10 The number of used registers varies from 0 to 4 depending on requested time in ms Delay ms 1000 One second pause Vdelay ms Prototype void Vdelay ms unsigned time in ms Creates a software delay in duration of time ms milliseconds a variable Generated delay is not as precise as the delay created by Delay ms Description Note that vdelay ms is library function rather than a built in routine it is pre sented in this topic for the sake of convenience pause 1000 44 Vdelay ms pause one second pause MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC 4 mikroC PRO for PIC Specifics Del
353. f the pattern up to the first and the last alternative contains everything from the last to the next pattern delim iter 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 rou tine only the rou part will match as that is the first alternative tried and it successfuly matches the target string this might not seem important but it is impor tant 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 71 2 Environment mikroC PRO for PIC Metacharacters Subexpressions The bracketing construct may also be used for define regular subexpres sions Subexpressions are numbered based on the left to right order of their open ing parenthesis First subexpression has number 1 Examples int 8 10 matches strings which contain 8 9 or 10 instances of the int routi 0 9 at e matches routiOe routile
354. finition file is in XML format lt LIB gt lt ALIAS gt Example Library lt ALIAS gt lt FILE gt Lib Example lt FILE gt lt TYPE gt REGULAR lt TYPE gt 98 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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 mc1 file For example UART library for 16F887 is different from UART library for 18F4520 MCU Therefore two different UART Library versions were made see 1 files for these two MCUs Note that these two libraries have the same Library Alias UART in both files This approach enables you to have identical representation of library for both MCUs in Library Manager Related topics Library Manager Project Manager Managing Source Files MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 99 2 Environment mikroC PRO for PIC 100 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER MIKROICD IN CIRCUIT DEBUGGER mikrolCD is highly effective tool for Real Time debugging on hardware level ICD debugger enables you to execute a mikroC PRO for PIC
355. for PIC HW connection OSCRLATOR FE 48849514 9IN2 LCD 2X16 LCD HW connection 358 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries MANCHESTER CODE LIBRARY The mikroC PRO for PIC 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 Send Byte format st1 st2 ctr 7 Be B5 B4 B3 2 B1 B0 Bi phase coding Mm 2ms Example of transmission 11000100011 Notes The Manchester receive routines are blocking calls van Receive Init and Man Synchro This means that MCU will wait until the task has been per formed e g byte is received synchronization achieved etc Note 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 proj ects using Manchester Code Library extern sfr sbit MAN Receive line sbit MANRXPIN at RXPIN ROO bit
356. format and CRC calculations How is CRC checksum calculated on RS485 Master side START BYTE 0x96 10010110 STOP BYTE 0 9 10101001 PACKAGE START BYTE 0x96 ADDRESS DATALEN DATA1 if exists DATA2 exists DATA3 if exists CRC STOP BYTE OxA9 DATALEN bits bit7 1 MASTER SENDS 0 SLAVE SENDS bit6 1 ADDRESS WAS XORed with 1 IT WAS EQUAL TO START BYTI 0 ADDRESS UNCHANGED bit5 0 FIXED bit4 1 DATA3 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE 0 DATA3 if exists UNCHANGED bit DATA2 if exists WAS XORed with 1 IT WAS EQUAL TO START BYTE or STOP BYTE 0 DATA2 if exists UNCHANGED bit2 1 DATA1 if exists WAS XORed with 1 WAS EQUAL TO START BYTE or STOP BYTE 0 1 if exists UNCHANGED bitlbitO 0 to 3 NUMBER DATA BYTES SEND E CRC generation crc send datalen address crc send datal 0 if exists crc send data 1 if exists crc send datal 2 if exists ere send cro send it send START BYTE ete send STOP BYTE crc sendtt NOTE DATALEN 4 0 take the START lt 4 0 gt STOP lt 4 0 gt values 420 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Lib
357. from 1 to 1 sinh Prototype double sinh double x Description Function returns the hyperbolic sine of x defined mathematically as ex e x 2 If the value of x is too large if overflow occurs the function fails sqrt Prototype double sqrt double x Function returns the non negative square root of x 570 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries tan Prototype Prototype double can double 002000000000 tan double x MEN returns the tangent in radians The return value spans the allowed range of floating point in the mikroC PRO for PIC tanh Parr Function returns the hyperbolic tangent of x defined mathematically as Description sinh x cosh x ANSI C Stdlib Library The mikroC PRO for PIC provides a set of standard ANSI C library functions of general utility Note Not all of the standard functions have been included Note Functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC programming Be sure to skim through the description before using standard C functions Library Functions abs atof atoi atol div div uldiv labs max min rand srand xtoi MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 571 7 Li
358. 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 recog nized 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 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 4 EVERLOOP if error Lcd Out Cp ERR MSG break MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 231 6 Language Reference mikroC PRO for PIC 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 512 endif The middle line is bypassed if BLOCK srzz is currently defined if BLOCK SIZE is not currently defined the middle line is invoked to define it Macros with Parameters The follow
359. g T Parameters Description n cursor blinking enable disable parameter Valid values o disable cursor blinking and 1 enable cursor blinking Toshiba Glcd module needs to be initialized See SPI 6963 Config routine enable cursor blinking SPI T6963C cursor blinkil Library Example The following drawing demo tests advanced routines of the SPI T6963C library Hardware configurations in this example are made for the T6963C 240x128 display EasyPIC5 board and 16F887 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 523 CHAPTER 7 Libraries mikroC PRO for PIC include SPITG963C h bitmap pictures stored in ROM Ej extern const code char me extern const code char einstein Port Expander module connections sbit SPExpanderRST at RCO bit sbit SPExpanderCS at bit sbit SPExpanderRST Direction at TRISCO bit sbit SPExpanderCS Direction at TRISC1 bit End Port Expander module connections void main char txtl1 EINSTEIN WOULD HAVE LIKED mE char txt GLCD LIBRARY DEMO WELCOME unsigned char panel current panel unsigned int 1 general purpose register unsigned char curs cursor visibility unsigned int eposz cursor x y position TRISA Oxf Configure PORTA as input ANSEL 0 Configure AN pins as digital I O ANSELH 0 If Port E
360. g strings and RAM memory Note Not all of the standard functions have been included Note Functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC programming Be sure to skim through the description before using standard C functions Library Functions memchr memcmp memmove memset strcat strchr strcmp strcpy strlen strncat strncpy strspn strncmp strstr strcspn strpbrk strrchr MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 575 7 Libraries 576 memchr Prototype void memchr void p char n unsigned int v Function locates the first occurrence of n in the initial bytes of memory area starting at the address The function returns the pointer to this location or 0 if Description memcmp Prototype Description memcpy Prototype Description memmove Prototype Description memset Prototype Description mikroC PRO for PIC the 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 Of amp PO int memcmp void sl void s2 int n Function compares the first n characters of objects pointed to by si and s2 and returns zero if the objects are equal or returns a diff
361. gger Icon from the Debugger Toolbar Starting the Software Sim ulator 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 instruc tion lines but it cannot fully emulate PIC device behavior i e it doesn t update timers interrupt flags etc 92 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Breakpoints Window CHAPTER 2 Environment The Breakpoints window manages the list of currently set breakpoints in the project Doubleclicking the desired breakpoint will cause cursor to navigate to the correspon ding location in source code Breakpoints Line File Name 50 Lcd c 54 Lcd c 58 Lcd c 64 Lcd c 75 Lcd c 76 Lcd c Watch Window The Software Simulator Watch Window is the main Software Simulator window which allows you to monitor program items while simulating your program To show the Watch Window select View Debug Windows Watch from the drop down menu The Watch Window displays variables and registers of the MCU along with their addresses and values There are two ways of adding variable register to the watch list by its real name variable s name in C code Just select desired variable reg ister from Select variable from list drop down menu and click the Add Bu
362. gned int remotePort unsigned int 1 unsigned int reqLength unsigned int len 0 my reply length unsigned int general purpose integer 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 i 0 i lt 10 getRequest i SPI Ethernet getByte getRequest i 0 if memcmp getRequest httpMethod 5 only GET method is supported here MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 473 7 Libraries mikroC PRO for PIC return 0 httpCounter one more request done if getRequest 5 s if request path name starts with s store dynamic data in 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 add AN2 value to reply IntToStr ADC Read 2 dyna len putConstString var 2 len putString dyna len putConstotring add AN3 value to reply IntToStr ADC Read 3 dyna len putConstString var AN3 len putString dyna len putCconstotrzng r s add PORTB value buttons to reply len putConstString var PORTB IntToSEr PORTB dyna len putString dyna
363. h more than two rows SPI Lcd8 Out 4 15 text For Lcd modules with more than two rows MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 505 7 Libraries mikroC PRO for PIC HW Connection 148849514 8 58 SPI LCD8 HW connection 506 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI T6963C GRAPHIC LCD LIBRARY The mikroC PRO for PIC provides a library for working with Glcds based on TOSHIBA T6963C controller via SPI interface The Toshiba T6963C is a very popu lar 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 out line 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 dis playing and merging text and graphics and it manages all interfacing signals to the displays Row and Column drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Note The library uses the SPI module for communication The user must initialize SPI module before using the SPI T6963C Library For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the Set Active routine Note This Library is designed to wor
364. har color Draws a dot Glcd at coordinates x pos v pos Parameters x pos X position Valid values 0 127 y pos y position Valid values 0 63 Description color color parameter Valid values 0 2 The parameter color determines the dot state 0 clears dot 1 puts dot and 2 inverts dot state Note For x and y axis layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Invert the dot in the upper left corner SPI Glcd Dot 0 0 2 SPI Glcd Line void SPI Glcd Line int x start int y start int x end int y end char 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 Description Parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a line between dots 0 0 and 20 30 SPI Gled Lin 0 0 20 30 1 484 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI Glcd V Line void SPI Glcd V Line char y start char y end char x pos char color
365. he SPI Glcd Set Font to specify the font for display if no font is specified then the default 5x8 font supplied with the library will be used Write character C on the position 10 inside the page 2 SPI Gled Write Char C 10 2 1 488 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi Glcd Write Text Prototype Description void SPI Glcd Write Text char text char x pos char page num char color Nothing 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 Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Use the SPI Glcd Set Font to specify the font for display if no font is specified then the default 5x8 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 world 10 2 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 489 CHAPTER 7 Libraries mikroC PRO for PIC Spi Glcd Image Prototype Description Requires
366. hernet CS Direc Ethernet CS Direc tion i at TRISC1 bit extern sfr sbit SPI Ethernet RST Dire Direction of the ENC28J60 reset pin Ethernet Rst Dire ction at TRISCO bit The following routines must be defined in all project using SPI Description Ethernet Library unsigned int MEL Ethernet DUIS MN example at the bot char remoteHost unsigned TCP request handler tom of this page for int remotePort unsigned int de impl localPort unsigned int a e implementa ION Refer to the library unsigned int 2 example at the bot m UDP request handler of this page for remotePort unsigned int destPort unsigned int code implementa reqLength tion Refer to the library 450 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Routines PIC16 and PIC18 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 PIC18 Only SPI Ethernet getlpAddress SPI Ethernet getGwlpAddress SPI Ethernet getDnslpAddress SPI Ethernet getlpMask SPI Ethernet confNetwork SPI Ethernet arpResolve SPI Ethernet s
367. herwise 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 successfuly 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 getDnslpAddress fetch DNS IP address SPI Ethernet getlpMask fetch IP subnet mask Description UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP serv er port Parameters time in seconds to wait for an reply Note The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time Note When DHCP module is used global library variable SPI Ethernet userTimerSec 18 used to keep track of time It is user responsi bility to increment this variable each second in it s code Ethernet module has to be initialized See SPI Ethernet Init Available for PIC18 family MCUs only SPI Ethernet initDHCP 5 get network configuration from DHCP server wait 5 sec for the response 468 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI Ethernet doDHCPLeaseTime Prototype uns
368. hich assumes that neither lt 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 neader name gt Or header name formats exists 234 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Preprocessor Operators The pound sign is a preprocessor directive when it occurs as the first non white space character on line Also and perform operator replacement and merg ing 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 Lcb PRINT for printing variable name and value on Lcd define LCD PRINT val Lcd Custom Out Cp val Lcd Custom Out Cp IntToStr val Now the following code LCD PRINT temp will be preprocessed to this Lcd Custom Out Cp temp Lcd Custom Out Cp IntToStr temp Opera
369. hould not be a reply to the request Length of UDP reply data field otherwise This is UDP module routine It is internally called by the library The user access es to the UDP request by using some of the Ethernet get routines The user puts data in the transmit buffer by using some of the Ethernet put routines The func tion 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 Description remoteHost client s IP address remotePort client s port destPort port to which the request is sent regLength UDP request data field length Note The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply Ethernet module has to be initialized See Ethernet Init Example This function is internally called by the library and should not be called by the user s code Ethernet getlpAddress Prototype unsigned char Ethernet getlIpAddress Returns Ponter to the global variable holding IP address This routine should be used when DHCP server is present on the network to fetch assigned IP address Note 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 an
370. ibrary Example This example reads the temperature using DS18x20 connected to pin PORTA B5 After reset MCU obtains temperature from the sensor and prints it on the Lcd Make sure to pull up PORTA B5 line and to turn off the PORTA LEDs LCD module connections sbit LCD RS at RB4 bit sbit LCD EN at RB5 bit sbit LCD D4 at RBO bit sbit LCD D5 at RBl1 bit sbit LCD D6 at RB2 bit sbit LCD D7 at RB3 bit sbit LCD RS Direction at TRISB4 bit sbit LCD EN Direction at TRISB5 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 Set TEMP RESOLUTION to the corresponding resolution of used DS18x20 sensor jf 189205 9 default setting be 9 10 11 or 12 19B20 12 const unsigned short TEMP RESOLUTION 9 char text 000 0000 unsigned temp void Display Temperature unsigned int temp2write const unsigned short RES SHIFT TEMP RESOLUTION 8 char temp whole unsigned int temp fraction check if temperature is negativ if temp2write amp 0 8000 text 0 temp2write temp2write 1 extract temp whole temp whole temp2write gt gt RES SHIFT convert temp whole to characters if temp_whole 100 text 0 temp whole 100 48 else text 0 0 386 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIO
371. ibute If TE xt succeeds unsigned long size size Cf Fat Get Swap File 1000 if size 1 mikrob txt 0x20 5 UART Write UART Write UART Write OxAA Lo size Hi size UART Write UART Write UART Write Library Example Higher size Highest size OxAA The following example demonstrates various aspects of the Cf Fat16 library Creation of new file and writing down to it Opening existing file and re writing it writing from start of file Opening existing file and appending data to it writing from end of file Opening a file and reading data from it sending it to USART terminal Creating and modifying several files at once set compact flash pinout 288 char Cf Data Port at PORTD sbit CF RDY at RB7 bit sbit CF WE at RB6 bit sbit CF OE at RB5 bit sbit CF CD1 at RB4 bit sbit CF at RES bit sbit CF A2 at RB2 bit sbit CF Al RBl bit sbit CF AO at RBO bit sbit CF direction at TRISB7 bit sbit CF WE direction at TRISB6 bit sbit CF OE direction at TRISB5 bit sbit CF CD1 direction at TRISB4 bit sbit CF direction at TRISB3 bit sbit CF A2 direction at TRISB2 bit sbit CF direction at TRISB1 bit sbit CF AQ direction at TRISBO 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 Rieckertn MIKROELEKT
372. ich means it supports MCUs with more than 256 bytes of EEPROM Description Be aware that all interrupts will be disabled during execution of EEPROM Write routine GIE bit of INTCON register will be cleared Routine will restore previ ous state of this bit on exit Requires EEPROM module Ensure minimum 20ms delay between successive use of routines EEPROM Write and Read Although PIC will write the correct value EEPROM Read might return an undefined result EEPROM Write 0x32 19 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Library Example CHAPTER 7 Libraries The example demonstrates use of EEPROM Library char ii loop variable void main ANSEL ANSELH 0 PORTB 0 PORTC 0 PORTD 0 TRISB 0 TRISC 0 TRISD 0 for ii 0 ii lt 32 11 EEPROM 0 80 ii 77 EEPROM Write 0x02 0xAA EEPROM Write 0x50 0x55 Delay ms 1000 PORTB OxFF PORTC OxFF Delay 1000 PORTB 0x00 PORTC 0x00 Delay ms 1000 PORTB EEPROM Read 0x02 77 display it PORTB PORTC EEPROM Read 0x50 display it on PORTC Delay ms 1000 0 Configure AN pins as digital I O 0 Fill data buffer Write data to address 0 80 11 Write some data at address 2 Write some data at add
373. ifference 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 timelib h which can be found in the mikroC PRO for PIC Time Library Demo example folder Library Routines Time dateToEpoch Time epochToDate Time dateDiff MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 601 7 Libraries mikroC PRO for PIC Time dateToEpoch Prototype long Time dateToEpoch TimeStruct ts Number of seconds since January 1 1970 OhOOmn00s This function returns the unix time number of seconds since January 1 1970 OhOOmn00s Description Parameters ts time and date value for calculating unix time include timelib h TimeStruct tgl long epoch what is the of the date in ts poch Time dateToEpoch amp tsl Time epochToDate Prototype void Time epochToDate long e TimeStruct ts Nothing Converts the unix time to time and date Description Parameters e unix time seconds since unix epoch ts time and date structure for storing conversion output Requires Nothing include timelib h TimeStruct CS2 long epoch je what date is epoch 1234567890 p epoch 123456
374. igned char SPI Ethernet doDHCPLeaseTime 0 lease time has not expired yet 1 lease time has expired it s time to renew it This is DHCP module routine It takes care of IP address lease time by decre Description menting the global lease time library counter When this time expires it s time to contact DHCP server and renew the lease Ethernet doDHCPLeaseTime it s time to renew the IP address lease SPI Ethernet renewDHCP Prototype unsigned char SPI Ethernet renewDHCP unsigned char tmax 1 upon success lease time was renewed 0 otherwise renewal request timed out This is DHCP module routine It sends IP address lease time renewal request to DHCP server Description Parameters tmax time in seconds to wait for an reply if SPI Ethernet doDHCPLeaseTime SPI Ethernet renewDHCP 5 it s time to renew the IP address lease with 5 secs for a reply MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 469 CHAPTER 7 Libraries mikroC PRO for PIC 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 ret
375. ikroC PRO for PIC Soft I2C Init Rohe Global variables Soft I2C Scl Soft 1 clock line Soft I2C Sda Softl C data line Soft I2C Scl Pin Direction Direction of the Soft I C clock pin Soft I2C Sda Pin Direction Direction of the Soft I C data pin must be defined before using this function Software I2C connections sbit Soft I2C Scl at RCS bit sbit Soft I2C Sda at RC4 bit sbit Soft I2C Scl Direction at 2 bit sbit Soft 2 Sda Direction at TRISC4 bit End Software I2C connections soft IZC Soft I2C Start Determines if the I2C bus is free and issues START signal Software 2 must be configured before using this function See Soft I2C Init routine Issue START signal soft I2C Start 7 422 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Soft I2C Read Prototype Description unsigned short Soft I2C Read unsigned int ack One byte from the Slave Reads one byte from the slave Parameters ack acknowledge signal parameter If the ack 0 not acknowledge signal will be sent after reading otherwise the acknowledge signal will be sent Soft 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
376. ikroC PRO for PIC Libraries LIBRARY I C full master MSSP module is available with a number of PIC MCU models mikroC PRO for PIC provides library which supports the master mode Note Some MCUs have multiple Il C modules In order to use the desired 1 library routine sim ply change the number 1 in the prototype with the appropriate module number i e 2 1 Init 100000 Library Routines 1261 Init 12C1_ Start 12C1_Repeated_ Start 1261 15 1261 Rd 1261 Wr 1261 Stop I2C1 Init Prototype void 2 1 Init unsigned long clock Initializes I C with desired clock refer to device data sheet for correct values in respect with Fosc Needs to be called before using other functions of I C Library Description You don t need to configure ports manually for using the module library will take care of the initialization Library requires MSSP module on PORTB or PORTC Note Calculation of the I C clock value is carried out by the compiler as it would produce a relatively large code if performed on the libary level Therefore compiler needs to know the value of the parameter in the compile time That is why this parameter needs to be a constant and not a variable Example i201 rnit 100000 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 341 7 Libraries mikroC PRO for PIC I2C1 Start Returns If there is no error function retur
377. iles hex asm and 15 lt files see output files These files can not be added or removed from project other files 82 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Project Manager TES MESES EO 4 7 T6963C 240x128 mcppi a Sources T6963C 240x128 c amp bitmap c 4 Header Files T6963C h 4 Binaries bitmap2 mcl Project level defines 4 Image Files sample jpg 7 Output Files 23 T6963C 240x128 hex T6963C 240x128 asm T6963C 240x128 lst 4 Other Files DATA doc3286 pdf The list of relevant source files is stored in the project file extension mcppi To add source file to the project click the Add File to Project Icon a 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 ea Project Level Defines Project Level Defines 1 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 lt symbol gt lt value gt symbol a b gt lt value gt 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
378. ility 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 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 MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE TITLE AND NON INFRINGEMENT WITH REGARD TO SOFTWARE AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL INCIDENTAL INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER INCLUDING WITHOUT LIMITATION DAMAGES FORLOSS 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 S
379. ing lst 73 Other Files Following options are available in the Project Manager MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 2 Environment Icon Description Save project Group Open project group Close the active project Close project group Add project to the project group Remove project from the project group Add file to the active project Remove selected file from the project Build the active project Ty 05 Er Gee 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 43 2 Environment mikroC PRO for PIC 44 PROJECT SETTINGS WINDOW Following options are available in the Project Settings Window Device select the appropriate device from the device drop down list Oscillator enter the oscillator frequency value Build Debugger Type choose debugger type pu mm Sorter Value MHz E Build D Build Type Release ICD Debug Debugger Related topics Edit Project Customizing Projects MIKROELEKTRONIKA SOFTWARE AND HARDWARE
380. ing syntax is used to define a macro with parameters define macro identifier 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 argu ment 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 delimit ed 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 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 for mal arguments occurring in the token sequence are replaced by the corresponding real arguments appearing in actual arg list Like with simple macro definitions rescanning occurs to detect any embedded macro identifiers eligible for expansion Here is a simple example simple macro which returns greater
381. ing this function mikroC PRO for PIC he SPI module needs to be initialized See the SPI1 Init and SPI1 Init Advanced routines Port Expander module connections sbit SPExpanderRST sbit SPExpanderCS sbit SPExpanderRST at RCO bit at ROCI bit Direction at SPExpanderCS Direction at 1 Init Initialize SPI module SPI T6963C Config 240 TRISC bit TRISCl bit End Port Expander module connections void SPI T6963C writeData unsigned char Ddata Nothing Writes data to T6963C controller via SPI interface Description Parameters Ddata data to be written Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example SPI T6963C writeData AddrL Spi T6963C WriteCommand void SPI T6963C writeCommand unsigned char Ddata Nothing Writes command to T6963C controller via SPI interface Parameters Ddata command to be written Toshiba module needs to be initialized See SPI 6963 Config routine _wri ER SET SPI T6963C writeCommand SPI T6963C CURSOR POINT 510 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi T6963C SetPtr Prototype void SPI T6963C setPtr unsigned int p unsigned char c Sets the memory pointer p for command c Description Parameters p address where command should be written c command to be written SToshib
382. initialized Note In order to use the desired SPI library routine simply change the number 1 in the prototype with the appropriate module number i e SPI2 Init Library Routines Init Init Advanced Spi1 Read Spi1 Write Spi Set Active Spi Init This routine configures and enables SPI module with the following settings master mode 8 bit data transfer most significant bit sent first serial clock low when idle data sampled on leading edge serial clock fosc 4 You need PIC MCU with hardware integrated SPI Example SPI1 Init Initialize the SPI module with default settings Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 443 CHAPTER 7 Libraries mikroC PRO for PIC Spi1 Init Advanced Prototype Description Requires void 5 1 Init Advanced unsigned short master slav unsigned short data sample unsigned short clock idle unsigned short transmit edge Nothing Configures and initializes SPI SPI1 Init or SPI1 Init Advanced needs to be called before using other functions of SPI Library Parameters mode data sample and clock idle configure the SPI module and can have the following values SPI work mode Mastey clock Fosc 4 PI MASTER OSC DIV4 Master clock Fosc 16 PI MASTER OSC DIV16 Master clock Fosc 64 PI MASTER OSC DIV64 Master clock source TMR2 PI MASTER
383. ionMode CANInitialize CANSetBaudRate CANSetMask CANSetFilter CANRead CANWrite Following routines are for the internal use by compiler only RegsToCANID CANIDToRegs Be sure to check CAN constants necessary for using some of the functions CANSetOperationMode void gnc EUN short mode unsigned short wait flag Sets CAN to requested mode i e copies mode to CANSTAT Parameter mode needs to be one of cau MODE constants see CAN constants Prototype Parameter wait flag needs to be either 0 or OxFF Deseripuon E f set to OxFF this is a blocking call the function won t return until the requested mode is set W f 0 this is a non blocking call It does not verify if CAN module is switched to requested mode or not Caller must use CANGetOperationMode to verify cor rect operation mode before performing mode specific operation CAN routines are currently supported only by P18XXX8 PIC MCUs Microcon troller must be connected to CAN transceiver MCP2551 or similar which is connected to CAN bus Example CANSetOperationMode CAN MODE CONFIG OxFF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 245 7 Libraries mikroC PRO for PIC 246 CANGetOperationMode Prototype unsigned short CANGetOperationMode Returns Current opmode Function returns current operational mode of CAN module CAN routines are currently supported only by P18XXX
384. is inserted do asm nop while Cf Detect Cf Enable Enables the device Routine needs to be called only if you have disabled the Description 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 Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init enable compact flash Cf Enable Cf Disable Routine disables the device and frees the data lines for other devices To enable Description the device again call Cf Enable These two routines in conjunction allow you to free occupy data line when working with multiple devices Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init disable compact flash Cf Disable MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 277 7 Libraries mikroC PRO for PIC Cf Read Init void Cf Read Init unsigned long address unsigned short Prototype z a sector count Initializes CF card for reading PS Parameters Description address the first sector to be prepared for reading operation sector count number of sectors to be prepared for reading operation The corresponding ports must be appropriately initialized for CF card See Requires Cf Init initialize compact flash for reading from sector 590 Read Imrt 590 1 Cf R
385. is set Therefore more than one type of network traf fic 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 disFlt network traffic receive filter flags Each bit corresponds to the appro priate network traffic receive filter const MAC Broadcast traffic receive filter flag When z set MAC broadcast traffic will be disabled MAC Multicast traffic receive filter flag When _ set MAC multicast traffic will be disabled Da not used none not used none CRC check flag When set CRC check will 0x20 be disabled and packets with invalid CRC _Ethernet CRC field will be accepted 1 2 3 5 6 0x40 MAC Unicast traffic receive filter flag When set MAC unicast traffic will be disabled Note Advance filtering available in the MCU s internal Ethernet module such as Pattern Match Magic Packet and Hash Table be disabled by this routine Note 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 MCU s internal Ethernet module The MCU s internal Ethernet module should be properly cofigured by the means of Ethernet Init routine 7 mikroC PRO for PIC Libraries Requires Ethernet module has to be initialized See Ethernet Init E
386. ive routine B CANSPI module refers to mikroElektronika s CANSPI Add on board connected to SPI module of MCU External dependecies of CANSPI Library The following variables must be defined in all Description projects using CANSPI Library extern sfr sbit Chip Select line sbit CanSpi CS at CanSpi CS RCO bit extern sfr sbit sbit CanSpi Rst at Reset line E CanSpi Rst RCZ xt extern sfr sbit Direction of the Chip sbit CanSpi CS Direction CanSpi CS Direction Select pin at TRISCO bit extern sfr sbit sbit CanSpi Rst Direction CanSpi Rst Direction Direction of the Reset pin at TRISC2 bit 256 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialize CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIread CANSPIWrite The following routines are for an internal use by the library only RegsToCANSPIID CANSPIIDToRegs Be sure to check CANSPI constants necessary for using some of the functions MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 257 7 Libraries mikroC PRO for PIC CANSPISetOperationMode Prototype Description void CANSPISetOperationMode char mode char WAIT Nothing Sets the CANSPI module to requested mode Parameters mode CANSPI modu
387. ive filter lag When Spi Ethernet BRO set MAC broadcast traffic will be disabled ADCAST 1 46 MAC Multicast traffic receive filter flag When Spi Ethernet MUL set MAC multicast traffic will be disabled TICAST siete check flag When set check will 5 0x20 be disabled and packets with invalid CRC i Ethernet CRC field will be accepted MAC Unicast traffic receive filter flag When set MAC unicast traffic will be disabled Spi Ethernet UNI Note Advance filtering available in the Nc28760 module such as Pattern Match Magic Packet and Hash Table can not be disabled by this routine Note 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 28760 module The 28 760 module should be properly cofigured by the means of SPI Ethernet Init routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 455 7 Libraries mikroC PRO for PIC 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 Spi Ethernet doPacket Prototype unsigned char SPI Ethernet doPacket 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or rec
388. ived Parameters data buffer 6 byte buffer for storing received data in the following manner data 0 2 message content 3 number of message bytes received 1 3 4 is set to 255 when message is received data 5 is set to 255 if error has occurred Description The function automatically adjusts 4 and datal 5 upon every received message These flags need to be cleared by software Requires MCU must be initialized as a Slave for RS 485 communication See q RS485slave_Init char mso 8 RS485Slave Read msg 414 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries RS485slave Send Prototype void RS485Slave Send char data buffer char datalen Nothing Sends message to Master Message format can be found at the bottom of this page Description Parameters data buffer data to be sent datalen number of bytes for transmition Valid values 0 3 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 only one device sends data via 485 bus at a time char 8 send 2 bytes of data to the Master RS485Slave Send msg 2 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
389. ize Description Parameters n cursor height Valid values 0 7 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Emme beige Spi T6963C graphics Prototype void SPI T6963C graphics char n Enable disable graphic displaying Description Parameters n graphic enable disable parameter Valid values o disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See SPI 6963 Config routine enable graphic displaying SPI T6963C graphics 1 Spi T6963C text Enable disable text displaying Description 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 522 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi T6963C cursor Prototype void SPI T6963C cursor char n Nothing Set cursor on off Description Parameters n on off parameter Valid values 0 set cursor off and 1 set cursor on Toshiba Glcd module needs to be initialized See SPI 6963 Config routine 77 cursor on SPI T6963C cursor 1 Spi T6963C cursor blink Prototype void SPI T6963C cursor blink char n Nothing Enable disable cursor blinkin
390. ject for more information The syntax of the include directive has two formats include header name include header name 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 there fore influence the scope and duration of any identifiers in the included file The difference between these two formats lies in searching algorithm employed in MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 233 6 Language Reference mikroC PRO for PIC trying to locate the include file If the include directive is used with the lt header name version the search is made successively in each of the following locations in this particular order 1 the mikroC PRO for PIC installation folder include folder 2 User s custom search paths The header name version specifies a user supplied include file the mikroC PRO for PIC will look for the header file in the following locations in this particular order 1 the project folder folder which contains the project file mcpp 2 the mikroC PRO for PIC 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 filesNtest h Note There is also a third version of the include directive rarely used w
391. k 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 dura tion For example void local duration variable init a upon every call to f int a 1 Statico duration Variable init b only upon first call to static int b 1 checkpoint void main At checkpoint we will have 22 mfter first call t after second call 97 If a 1 after third call etc 166 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference TYPES The mikroC PRO for PIC is a strictly typed language which means that every object function and expression must have a strictly defined type known in the time of com pilation Note that the mikroC PRO for PIC works exclusively with numeric types The type serves to determine the correct memory allocation required initially E to interpret the bit patterns found in the object during subsequent access Bin many type checking situations to ensure that illegal assignments are trapped The mikroC PRO for PIC 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 additi
392. k Ck Ck k ck Ck ck ck kckok ROM constant strings const unsigned char httpHeader 1 1 200 OKnContent type HTTP header const unsigned char httpMimeTypeHTMI text htmlnn i HTML MIME type const unsigned char httpMimeTypeScript text plainnn TEXT MIME type unsigned char httpMethod GET web page splited into 2 parts when coming short of ROM fragmented data is handled more effi ciently by linker this HTML page calls the boards to get its status and builds itself with javascript const 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 lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt lt h1 gt PIC18FxxJ60 Mini Web Server lt hl1 gt lt a href gt Reload lt a gt lt script src s script lt table gt lt tr gt lt td valign top gt lt table border 1 style font size 20px font family terminal gt lt tr gt lt th colspan 2 gt ADC lt th gt lt tr gt lt tr gt lt td AN2 lt td gt lt td gt lt script gt document write AN2 lt script gt lt td gt lt tr gt tr td AN3 td td script document write AN3 lt script gt lt td gt lt tr gt MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 313 7 Libraries mikroC PRO for PIC lt table gt lt td gt lt td gt lt table border 1 style fo
393. k with mikroElektronika s Serial Glcd 240x128 and 240x64 Adapter Boards pinout see schematic at the bottom of this page for details Note 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 C D 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 dependen cies MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 507 7 Libraries mikroC PRO for PIC Library Routines SPI T6963C Config SPI T6963C writeData SPI T6963C writeCommand SPI T6963C setPtr SPI T6963C waitReady SPI 6963 fill SPI T6963C dot SPI T6963C write char SPI T6963C write text SPI T6963C line SPI T6963C rectangle SPI T6963C box SPI T6963C circle SPI T6963C image SPI T6963C sprite SPI T6963C set cursor SPI T6963C clearBit SPI T6963C setBit SPI T6963C negBit Note The following low level library routines are implemented as macros These macros be found in the s 76963c n header file which is located in the SPI T6963C example projects folders SPI T6963C displayGrPanel SPI T6963C displayTxtPanel SPI T6963C setGrPanel SPI T6963C setTxt
394. known memory model s small memory model used instead IRP bit must be set manually for indirect access to s variable Variable sj has been declared but not used Illegal file type sj Linker Error Messages Redefinition of gt s already defined in gt s main function is not defined System routine is not found for initialization of 551 Bad aggregate definition gt s Unresolved extern 251 Bad function absolute address 551 Not enough RAM s MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 91 2 Environment mikroC PRO for PIC SOFTWARE SIMULATOR OVERVIEW The Source level Software Simulator is an integral component of the mikroC PRO for PIC environment It is designed to simulate operations of the PIC MCUs and assist the users in debugging C code written for these devices Upon completion of writing your program choose Release build Type in the Project Settings window Project Settings E3 CON Name P16F877A Value 8 000000 MHz Choose Release type if you want to use software simulator E Build Debugger Build Type Release ICD Debug Debugger Software mikroICD After you have successfuly compiled your project you can run the Software Simu lator by selecting Run Start Debugger from the drop down menu or by clicking the Start Debu
395. ktronkalmkroC PRO Time 2 24 2009 8 57 44 AM PIC Examples Development 54 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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 Macros 2 bd J SR Macro3 The Macro offers the following commands Icon Description Starts recording keystrokes for later playback a Stops capturing keystrokesthat was started when the Start Recordig com mand was selected 5 Allows macro that has been recorded to be replayed 25 New macro e Delete macro Related topics Advanced Code Editor Code Templates MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 55 2 Environment mikroC PRO for PIC INTEGRATED TOOLS USART Terminal The mikroC PRO for PIC includes the USART communication terminal for RS232 communication You can launch it from the drop down menu Tools USART Termi nal or by clicking the USART Terminal Icon A from Tools toolbar Bg Settings Communication Com Port i i Echo o Baud Append CR E Send as typing Stop Bits P LF as number S i 2 xc Clear Histo Connected to COM3 lt
396. l 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 cell phones mp3 players digital cameras and PDAs Notes Library works with PIC18 family only The library uses the SPI module for communication User must initialize SPI module before using the SPI Graphic Lcd Library For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the Set Active routine 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 FAT1 table is corrupted Note The SPI module has to be initialized through sP11 Init Advanced routine with the following parameters SPI Master 8bit mode primary prescaler 16 Slave Select disabled data sampled in the middle of data output time clock idle low Serial output data changes on transition from idle clock state to active clock state SPI1_Init_Advanced _SPI_ MASTER OSC DIV16 SPI DATA SAMPLE MIDDLE SPI CLK IDLE LOW SPI LOW 2 HIGH must be called before initializing Mmc Init 368 MIKROELEKTRONIKA
397. l Defines casa ee e ERE REIR Rome ge 83 Source Files PTT 84 Managing Source Files 84 Creating new source file 84 Opening an existing file 84 Printing an open ia 84 AVINGMNG athe dg Ea iut EE 85 Saving file under a different name 85 ISl qr 85 Clean Project Folder ed Ed RR E rens 86 euni 87 Output 225 6 gt aye a oe 87 Assembly VIEW rreri toide ES 87 Error 55 5 cede 24 edu EE ye hed ee ae 88 Compiler Error Messages 88 VI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Table of Contents Compiler Warning Messages 91 Linker Error Messages 2 2 2 91 Software Simulator Overview 92 Breakpoints Window 93 Watch Window 93 View RAM Window 95 Stopwatch Window 0 cece 96 Soft
398. l to the previous one int days 431 29 91 20 31 9290 91 91 90 31 90 921 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 mem In case of array of char you can use a shorter string literal notation For example The two declarations are identical const char e T TET 09 const char msg2 Test For more information on string literals refer to String Constants Arrays n Expressions When the name of an array comes up in expression evaluation except with opera tors and sizeof itis 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 some times referred to as vectors 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
399. lcd Set X unsigned short x pos Sets x axis position to pos dots from the left border of Glcd within the select ed side Parameters Description x pos position on x axis Valid values 0 63 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine Example MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 329 7 Libraries mikroC PRO for PIC Glcd Set Page Prototype void Glcd Set Page unsigned short page Selects page of the Glcd Parameters Description page page number Valid values 0 7 Note For side x axis and page layout explanation see schematic at the bottom of this page GLCD needs to be initialized see Glcd Init routine Example 00000 Glcd Read Data Returns One byte from GLCD memory er Reads data from from the current location of Glcd memory and moves to the Description next location 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 Set X and Set Page unsigned short data data Glcd Read Data 330 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Glcd Write Data Prototype void Glcd Write Data unsigned short Writes
400. le 2 Write 0xA3 I2C1 Stop Issues STOP signal I2C must be configured before using this function See 2 1 Init Example oct O y OS MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 343 7 Libraries mikroC PRO for PIC Library Example This code demonstrates use of 1 library PIC MCU is connected SCL SDA pins to 24 02 EEPROM Program sends data to EEPROM data is written at address 2 Then we read data via I C from EEPROM and send its value to PORTB to check if the cycle was successful see the figure below how to interface 24c02 to PIC void main ANSEL 0 Configure AN pins as digital I O ANSELH 0 PORTB 0 TRISB 0 Configure PORTB as output 1 Trace 100000 7 initialize I2C communication 1201 Scart issue I2C start signal 2 1 Wr 0xA2 send byte via I2C device address W 2 1 Wr 2 send byte address of EEPROM location 2 1 Wr OxF0 send data data to be written 12 1 Stop issue 120 stop signal Delay 100ms 1201 Start issue I2C start signal 2 1 Wr 0xA2 send byte via I2C device address W TOI Wed send byte data address 12 1 Repeated Start issue I2C signal repeated start 2 1 Wr 0xA3 send byte device address PORTB 2 Rd 0u Read the data NO acknowledge I261 Step 4 issue I2C stop signal 344 MIKROELEK
401. le operation mode Valid values CANSPI MODE con stants see CANSPI constants WAIT CANSPI mode switching verification request If via 17 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 cor rect operation mode before performing mode specific operation If wart the call is blocking the function won t return until the requested mode is set 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 CANSPIGetOperationMode Prototype char CANSPIGetOperationMode Returns Current operation mode Description 258 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD The function returns current operation mode of the CANSPI module Check cax SPI OP MODE constants see CANSPI constants or device datasheet for opera tion mode codes 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 wh
402. lize the SPI module before using the SPI Lcd Library For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the Set Active routine Note This Library is designed to work with mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details 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 dependen cies Library Routines SPI Lcd8 Config SPI Out SPI Lcd8 Out Cp SPI Lcd8 Chr SPI Chr SPI 500 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi Lcd8 Config Prototype void SPI Lcd8 Config char DeviceAddress Initializes the LCD module via SPI interface Description Parameters DeviceAddress spi expander hardware address see schematic at the bottom of this page Global variables SPExpanderCS Chip Select line SPExpanderRST Resetline 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 SPI1 Init and SPI1 Init Advanced routines Port Expander module connections sbit SPExpanderRST at RCO bit shi
403. llowing VERY com plex 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 spe cific solutions for the code building bricks that further reduce output code size Related topics PIC specifics mikroC PRO for PIC specifics Memory type specifiers MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 131 4 Specifics mikroC PRO for PIC 132 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER PIC SPECIFICS In order to get the most from your mikroC PRO for PIC compiler you should be familiar with certain aspects of PIC MCU This knowledge is not essential but it can provide you a better understanding of PICs capabilities and limitations and their impact on the code writing 133 5 PIC Specifics mikroC PRO for PIC Types Efficiency First of all you should know that PIC s ALU which performs arithmetic operations is optimized for working with bytes Although mikroC PRO for PIC is capable of han dling very complex data types PIC may choke on them especially if you are work ing on some of the older models This can dramatically increase the time needed for performing even simple oper
404. loating point constants are of the type double Note that the mikroC PRO for PIC s implementation of ANSI Standard considers float and double together with the long double variant to be the same type 150 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Character Constants A character constant is one or more characters enclosed in single quotes such as or n In the mikroC PRO for PIC single character constants are of the unsigned int type Multi character constants are referred to as string con stants or string literals For more information refer to String Constants Escape Sequences A backslash character is used to introduce an escape sequence which allows visual representation of certain nongraphic characters One of the most common escape constants is the newline character n A backslash 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 PIC can be used Larger numbers will generate the compiler error Out of range 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
405. ly instruction to C code asm assembly instruction and asm assembly instruction Note semicolon and LF are terminating asm scope for single assembly instructions This is the reason why the following syntax is not asm block asm block of assembly instructions This code will be interpreted as single empty asm line followed by C compound statement The mikroC PRO for PIC comments both single line and multi line are allowed in embedded assembly code if you have a global variable g_var that is of type long i e 4 bytes you are to access it like this MOVE _g var 0 0 puts least significant byte of var in N register MOVE od vartl 0 second byte of var corresponds to Hi g var MOVE 0 var MOVE _g vart 0 Highest g_var If you want to know details about asm syntax supported by mikroC PRO for PIC it is recomended to study asm and Ist files generated by compiler It is also recomend ed to check Include source lines in output files checkbox in Output settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 199 6 Language Reference mikroC PRO for PIC Note Compiler doesn t expect memory banks to be changed inside the assembly code If the user wants to do this then he must restore the previous bank selection Related topics mikroC PRO for PIC specifcs Initialization The initial value of a declared object can be set
406. mber and 8 bit CRC so multiple slaves can co exist on the same bus Note that oscillator frequency Fosc needs to be at least 4MHz in order to use the routines with Dallas digital thermometers Note This library implements time based activities so interrupts need to be dis abled when using OneWire library Library Routines Ow Reset Ow Read Ow Write 384 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Ow Reset Prototype unsigned short Ow Reset unsigned short port unsigned short pin 0 if D81820 is present and 1 if not present Description Issues OneWire reset signal for 051820 Parameters PORT and pin specify the P location of 051820 Works with Dallas 051820 temperature sensor only To reset the 051820 that is connected to the pin Ow Reset amp PORTA 5 Ow Read Prototype unsigned short Ow Read unsigned short port unsigned short pin Data read from an external device over the OneWire bus Reads one byte of data via the OneWire bus unsigned short tmp tmp Ow Read amp PORTA 5 Ow Write void Ow Write unsigned short port unsigned short pin unsigned Prototype 9 p g p g short par Writes one byte of data argument par via OneWire bus Example Ow Write amp PORTA 5 OxCC MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 385 7 Libraries mikroC PRO for PIC L
407. mc Fat Reset Mmc Fat Read mydata Mmc Fat Delete Deletes currently assigned file from MMC SD card MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign delete current fil Mmc Fat Delete Mmc Fat Write Prototype void Mmc Fat Write char fdata unsigned data len Procedure writes a chunk of bytes fdata to the currently assigned file at the Description position of the file pointer The file must be assigned see Mmc Fat Assign Also file pointer must be ini tialized see Mmc Fat Append or Mmc Fat Rewrite Fat Write txt 255 Mmc Fat Write Hello world 255 Requires 376 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Mmc Fat Set File Date void Mmc Fat Set File Date unsigned int year unsigned short Prototype month unsigned short day unsigned short hours unsigned short mins unsigned short seconds Writes system timestamp to a file Use this routine before each writing to file otherwise the file will be appended an unknown timestamp Description The file must be assigned see Mmc Fat Assign Also file pointer must be ini tialized see Mmc Fat Reset f April 2005 18 07 00 Mmc Fat Set File Date 2005 4 Mmc Fat Get File Date Requires void Fat Get File Date unsigned
408. med as array name and composed of elements of type 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 elements of array can be approached as variables array name 0 array namel 1 of type Here are a few examples of array declaration define MAX 50 int vector ome 101 7 declares an array of 10 integers float vector two declares an array of 50 floats float vector three MAX 20 declares an array of 30 floats d MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 173 6 Language Reference mikroC PRO for PIC Array Initialization An array can be initialized 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 131 29 91 390 31 30 31 31 30 91 90 31 2 This declaration is identica
409. 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 int i j double d aa aaa struct 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 desti nation have the same type aa aaa OK same type member by member assignment aa bb ILLEGAL different types but you can assign member by member 1 bblj aa j bb j aa d bb d MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 187 6 Language Reference mikroC PRO for PIC 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 mem space Note The mikroC PRO for PIC does not support anonymous unions ANSI diver gence Unions 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 char ch mu
410. ment in the list needs its own type specifier and possible qualifier const or volatile Function Prototype 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 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 ctriport char dataport 7 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 202 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
411. module connections char GLCD DataPort at PORTD sbit GLCD CS1 at RBO bit sbit GLCD C32 at REL bit sbit GLCD RS at RB2 bit sbit GLCD RW at bit sbit GLCD EN at RB4 bit sbit GLCD RST at RB5 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 End Glcd module connections void 1 25 2 seconds delay function Delay ms 2000 void main unsigned short ii char define COMPLETE EXAMPLE comment this line to simpler smaller example ANSEL 0 Configure AN pins as digital ANSELH 0 C1ON bit 0 Disable comparators C20N bit 0 Gled Tare 2 Initialize GLCD Gled_Fill 0x00 Clear GLCD while 1 338 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC ifdef COMPLETE EXAMPLE Glcd Image truck bmp delay2S delay28 0 fendif Gled br11 00x00 Glcd Box 62 40 124 56 1 Gled Rectangle 5 5 84 35 1 7 CHAPTER 7 Libraries Draw image Clear GLCD Draw box Draw rectangle Gled nrme 0 0 127 63 19 Draw line delay28 for ii 5 ii lt 60 5 Draw horizontal and vertical lines Delay ms 250 Gled V Line 2 54 ii 1 Gica
412. mple The example is a simple demonstration of how to use the Sound Library for play ing tones on a piezo speaker 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 onel Tone2 Tone3 Tone3 onel Tone2 Tone3 Tone3 onel one2 Tone3 onel Tone2 Tone3 Tone3 onel Tone2 Tone3 one3 Tone3 Tone2 Tone2 Tonel 440 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries void ToneA Sound Play 880 50 void ToneC Sound Play 1046 50 void ToneE Sound Play 1318 50 void Melody2 1 unsigned short i for 1 9 i 0 ToneA ToneC ToneE void main ANSEL 0 Configure AN pins as digital I O ANSELH 0 TRISB OxF8 Configure RB7 RB3 as input TRISD OxF7 Configure RD3 as output Sound Init amp PORTD 3 Sound Play 1000 1000 while 1 if Button amp PORTB 7 1 1 RB7 plays Tonel Tonel while PORTB amp 0x80 Wait for button to be released if Button amp PORTB 6 1 1 RB6 plays Tone2 Tone2 while PORTB amp 0x40 Wait for button to be rel
413. n char CAN TX MSG FLAGS Returns Returns zero if message cannot be queued buffer full If at least one empty transmit buffer is found function sends message on queue for transmission If buffer is full function returns 0 Parameters id is CAN message identifier Only 11 or 29 bits may be used depending on message type standard or extended data is array of bytes up to 8 bytes in length datalen is data length from 1 8 Description CAN TX MSG FLAGS is value formed from constants see CAN constants CAN must be in Normal mode CAN routines are currently supported only by P18XXX8 PIC MCUs Microcontroller must be connected to CAN transceiver MCP2551 or similar which is connected to CAN bus char tx data long id aus tx CAN TX PRIORITY 0 CAN TX XTD FRAME y dus CANWrite id data 2 tx MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 249 7 Libraries mikroC PRO for PIC CAN Constants There is a number of constants predefined in CAN library To be able to use the library effectively you need to be familiar with these You might want to check the example at the end of the chapter CAN OP MODE CAN OP MODE constants define operation mode Function CANSetOperationMode expects one of these as its argument const char CAN MODE BITS OxEO Use this to access opmode bits MODE NORMAL 0x00 MODE SLEEP 0
414. n 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 char snd port char snd pin Configures the appropriate MCU pin for sound generation Parameters Description snd port sound output port address snd pin Sound output pin Requires Nothing Initialize the pin RD3 for playing sound Sound Init amp PORTD 3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 439 7 Libraries mikroC PRO for PIC Sound Play Prototype void Sound Play unsigned freq in hz unsigned duration ms Generates the square wave signal on the appropriate pin Parameters freq in Hz Signal frequency in Hertz Hz er duration ms signal duration in miliseconds ms Description Note frequency range is limited by Delay_Cyc parameter Maximum frequency that can be produced by this function is Freq max Fosc 80 3 Minimum fre quency is Freq min Fosc 80 255 Generated frequency may differ from the freq in hz parameter due to integer arithmetics In order to hear the sound you need a piezo speaker or other hardware on des ignated port Also you must call Sound Init to prepare hardware for output before using this function Play sound of 1KHz in duration of 100ms Sound Play 1000 100 Library Exa
415. n 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 aint int ptt a pointer to an array of integers double double ptr pointer to a matrix of doubles You can also use asterisk as an operator to either dereference a pointer or as mul tiplication operator Snt a be 3 14 For more information see the Pointers Equal Sign 160 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Equal sign separates variable declarations from initialization lists ime Best 5 1 1 2 3 4 5 5 int x 5 Equal sign is also used as an assignment operator in expressions d Gi ab For more information see Assignment Operators Pound Sign Preprocessor Directive Pound sign 4 indicates a preprocessor directive when it occurs as the first non whitespace character on a line It signifies a compiler action not necessarily asso ciated with a code generation See the Preprocessor Directives for more informa tion and are also used as operators to perform token replacement and merging dur ing the preprocessor scanning phase See the Preprocessor Operators MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 161 6 Language Reference mikroC PRO f
416. n returns a sequence of pseudo random numbers between 0 and 32767 Description The function will always produce the same sequence of numbers unless srand is called to seed the start point MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 573 7 Libraries mikroC PRO for PIC srand Prototype void srand unsigned x Function uses as a starting point for a new sequence of pseudo random num Description bers to be returned by subsequent calls to rand No values are returned by this function xtoi Prototype unsigned xtoi register char 5 Function converts the input string s consisting of hexadecimal digits into an inte ger value The input parameter s should consist exclusively of hexadecimal dig Description its 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 Div Structures typedef struct divstruct int quot int rem diy t typedef struct ldivstruct long quot long rem dux ti typedef struct uldivstruct unsigned long quot unsigned long rem uldsv t 574 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries ANSI C String Library The mikroC PRO for PIC provides a set of standard ANSI C library functions useful for manipulatin
417. n time There are two kinds of duration sfatic and local MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 165 6 Language Reference mikroC PRO for PIC Static Duration Memory is allocated to objects with static duration as soon as execution is under way 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 or extern storage class specifiers In the mikroC PRO for PIC 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 bloc
418. n varies greatly between MCUs MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 203 6 Language Reference mikroC PRO for PIC Function Calls and Argument Conversion 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 statement 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 func tion 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 argu ments in the calling routine A scalar object can be passed
419. nce mikroC PRO for PIC For Statement The for statement implements an iterative loop The syntax of the for statement IS for init expression condition expression increment expres sion 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 expression is checked before the first entry into the block statement is executed repeatedly until the value of condition expression is false After each iteration of the loop increment expression increments a loop counter Conse quently i is functionally the same as i All expressions are optional If condition expression is left out it is assumed to be always true Thus empty for statement is commonly used to create an end less loop in C for 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 state ment for 8 0 21 0 4 n itt s ali Bl al There is another way to do this for 8 x Us Be 8 4 ile yalig but ugly 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 226 MIKROELEKTRONIKA SOF
420. nd values Values are updated as you go through the simulation Use the drop down menu to add and remove the items that you want to monitor Recently changed items are colored red 0 000005 Cycle 0 00 110 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 mikroC PRO for PIC mikrolCD Double clicking an item opens the Edit Value window in which you can assign a new value to the selected variable register Also you can change view to binary hex char or decimal for the selected item 3 Edit Value ACD 0100 0000 1000 0011 0001 0010 0110 1111 Representation Dec Hex Bin Float Char EEPROM Watch Window mikrolCD EEPROM Watch Window is available from the drop down menu View gt Debug Windows View EEPROM The EEPROM Watch window shows current values written into PIC internal EEPROM memory There are two action buttons concerning EEPROM Watch win dow Write EEPROM and Read EEPROM Write EEPROM writes data from EEPROM Watch window into PIC internal EEPROM memory Read EEPROM reads data from PIC internal EEPROM memory and loads it up in EEPROM window EEPROM Watch Read EEPROM Write EEPROM STATUS Idle MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 111 3 mikrolCD mikroC PRO for PIC Code Watch Window mikrolCD Code Watch Window is available from the drop down m
421. nd bus MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 255 7 Libraries mikroC PRO for PIC CANSPI LIBRARY The SPI module is available with a number of the PIC compliant MCUs The mikroC PRO for PIC provides a library driver for working with mikroElektronika s CANSPI Add on boards with MCP2515 or MCP2510 via SPI interface The CAN is a very robust protocol that has error detection and signalization self checking and fault confinement Faulty CAN data and remote frames are re transmitted automatically similar to the Ethernet Data transfer rates depend on distance For example 1 Mbit s can be achieved at net work lengths below 40m while 250 Kbit s can be achieved at network lengths below 250m The greater distance the lower maximum bitrate that can be achieved The lowest bitrate defined by the standard is 200Kbit s Cables used are shielded twisted pairs CAN supports two message formats Standard format with 11 identifier bits and B Extended format with 29 identifier bits Note B Consult the CAN standard about CAN bus termination resistance An effective CANSPI communication speed depends on SPI and certainly is slower than real CAN The library uses the SPI module for communication User must initialize SPI module before using the SPI Graphic Lcd Library For MCUs with two SPI modules it is possible to initialize both of them and then switch by using the set Act
422. nd returns inde int arrpf char char addC subC mulC divC modC int res char i void main for i 0 i lt 5 it res arrpf i 10 20 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Pointer Arithmetic Pointer arithmetic in the mikroC PRO for PIC 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 The internal arithmetic performed on pointers depends on the memory specifier in force and the presence of any overriding pointer modifiers When performing arith metic 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 PIC 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 f id exp where either idis a pointer and exp is an integer or idis an integer and is a pointer The following statements are true amp a i ati a i ia dox According to these guidelines it can be written
423. ned short row unsigned short column char Prototype bus cher Prints character on LCD at specified position Both variables and literals can be passed as character x dr Parameters Description row Writing position row number column Writing position column number out char character to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines IT Write character i at row 2 column 3 SPI Lcd8 Chr 2 3 em 502 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi Lcd8 Chr Cp Prototype void SPI Lcd8 Chr CP char out char Prints character on LCD at current cursor position Both variables and literals can be passed as character Description Parameters out char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Print at current cursor position Write character e at current cursor position SPI Leds Chr Cp e r Spi Lcd8 Cmd Sends command to LCD Parameters Description P out char command to be sent Note Predefined constants can be passed to the function see Available LCD Commands Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Clear Lcd display SPI Lcd8 Cmd LCD CLEAR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 503
424. needs to be initialized for working with the Keypad library see Keypad Init char kp kp Keypad Key Press Keypad Key Click The code of a clicked key 1 16 If no key is clicked returns 0 Call to 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 Description the key If more than one key is pressed simultaneously the function will wait until all pressed keys are released After that the function will return the code of the first pressed key Port needs to be initialized for working with the Keypad library see Keypad Init char kp kp Keypad Key Click MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 347 CHAPTER 7 Libraries Library Example mikroC PRO for PIC This is a simple example of using the Keypad Library It supports keypads with 1 4 rows and 1 4 columns The code being returned by Keypad Key Click function is in range from 1 16 In this example the code returned is transformed into ASCII codes 0 9 A F and displayed on LCD In addition a small single byte counter dis plays in the second LCD row number of key presses unsigned short kp char txt 6l Keypad module connections char End Keypad module connections keypadPort at PORTD LCD module connections at RB4 bit at RB5 bit at RBO bit at bit at RB2 bit
425. ng position on x axis num number of page on which text will be written Valid values 0 7 Description 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 Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine Use Glcd_Set_Font to specify the font for display if no font is specified then default 5x8 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 19 void Glcd Image code const unsigned short image Nothing Displays bitmap on GLCD Parameters image image to be displayed Bitmap array must be located in code memory Use the mikroC PRO for PIC integrated Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd Glcd needs to be initialized see Glcd Init routine Draw image my image on Glcd Glcd Image my image MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 337 7 Libraries mikroC PRO for PIC Library Example The following example demonstrates routines of the Glcd library initialization clear pattern fill image displaying drawing lines circles boxes and rectangles text displaying and handling declarations Glcd
426. ng the expression All side effects from this evaluation are completed before the next statement starts executing Most of expression statements are assignment state ments or function calls Anull statement 6 a special case consisting of a single semicolon The null statement does nothing and therefore is useful in situations where the mikroC PRO for PIC syntax expects a statement but the program does not need one For exam ple a null statement is commonly used in loops for pt 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 statement is used to implement a conditional statement The syntax of the if statement is if expression statementl else statement2 If expression evaluates to true statement1 executes If statement is false statement2 executes The expression must evaluate to an integral value other wise the condition is ill formed Parentheses around the expression are mandato ry The else keyword is optional but no statements can come between if and else 222 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Nested If Statement Nested statements require additional attention A g
427. nment mikroC PRO for PIC PROJECTS The mikroC PRO for PIC organizes applications into projects consisting of a single project file extension mcppi and one or more source files extension mikroC PRO for PIC 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 mc1 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 New Project The easiest way to create a project is by means of the New Project Wizard drop down menu Project New Project or by clicking the New Project Icon from Project Toolbar x 78 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment New Project Wizard Steps Start creating your New project by clicking Next button NewPrjetWgard 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 and choose device flags e Select desired memory model Add project files Click Next to continue
428. no stack no packet reconstruction ARP client with cache DNS client UDP client DHCP client packet fragmentation is NOT supported Note Global library variable 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 Note For advanced users there are header files eth j60LibDef h and eth j60LibPrivate h in Uses P18 folder of the compiler with description of all routines and global variables relevant to the user implemented in the Ethernet PIC18FxxJ60 Library 296 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Library Routines Ethernet Init Ethernet Enable Ethernet Disable Ethernet doPacket Ethernet putByte Ethernet putBytes Ethernet putString Ethernet putConstString Ethernet putConstBytes Ethernet getByte Ethernet getBytes Ethernet UserTCP Ethernet UserUDP Ethernet getlpAddress Ethernet getGwlpAddress Ethernet getDnslpAddress Ethernet getlpMask Ethernet confNetwork Ethernet arpResolve Ethernet sendUDP Ethernet dnsResolve Ethernet initDHCP Ethernet doDHCPLeaseTime Ethernet renewDHCP MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 297 CHAPTER 7 Libraries mikroC PRO for P
429. ns O Determines if I2C bus is free and issues START signal 2 must be configured before using this function See I2C1 Init 2 1 Repeated Start Issues repeated START signal I2C must be configured before using this function See I2C1 Init Example 1221 I2C1 Is Idle Returns Returns 1 if I2C bus is free otherwise returns Tests if IC bus is free 2 must be configured before using this function See I2C1 Init Example i Ts pie 2 I2C1 Rd Prototype unsigned short I2C1 Rd unsigned short ack Returns Returns one byte from the slave Reads one byte from the slave and sends not acknowledge signal if parameter Description ack is 0 otherwise it sends acknowledge Requires 2 must be configured before using this function See 2 1 Init Also START signal needs to be issued in order to use this function See I2C1 Start Read data and send not acknowledge signal unsigned short take take I2C1 Rd 0 342 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries I2C1 Wr Prototype unsigned short I2C1 Wr unsigned short data Returns Returns 0 if there were no errors Sends data byte parameter data via I2C bus 2 must be configured before using this function See 2 1 Init Also START signal needs to be issued in order to use this function See I2C1 Start Examp
430. ns from within the interrupt routine is now possible The compiler takes care about the registers being used both in interrupt and in main thread and performs smart context switching between the two saving only the registers that have been used in both threads Check functions reentrancy Interrupt Examples Here is a simple example of handling the interrupts from if no other interrupts are allowed void interrupt counterdt TMRO 96 INTCON 20 In case of multiple interrupts enabled you need to test which of the interrupts occurred and then proceed with the appropriate code interrupt handling void interrupt if INTCON TMROIF counLtertt TMRO 96 INTCON TMROF 0 else if INTCON RBIF countertt TMRO 96 INTCON RBIF 0 4 mikroC PRO for PIC Specifics Linker Directives The mikroC PRO uses an internal algorithm to distribute objects within memory If you need to have a variable or routine at specific predefined address use the link er directives absolute and org Directive absolute Directive absolute specifies the starting address in RAM for a variable If the vari able is multi byte higher bytes will be stored at the consecutive locations Directive absolute is appended to declaration of a variable short x absolute 0x22 Variable x will occupy 1 byte at address 0x22 int y absolute 0x23 Variable y will occupy 2 bytes at addresses 0
431. nse Ethernet sendUDP unsigned char Ethernet sendUDP unsigned char destIP unsigned int sourcePort unsigned int destPort unsigned char pkt unsigned int pktLen 1 UDP packet was sent successfully 0 otherwise This is UDP module routine It sends an UDP packet on the network Parameters destIP remote host IP address sourcePort local UDP source port number destPort destination UDP port number pkt packet to transmit pktLen length in bytes of packet to transmit Ethernet module has to be initialized See Ethernet Init unsigned char IpAddr 4 192 168 1 1 remote IP address Description Ethernet sendUDP IpAddr 10001 10001 Hello 5 send Hello mes sage to the above IP address from UDP port 10001 to UDP port 10001 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 309 7 Libraries mikroC PRO for PIC Ethernet dnsResolve unsigned char Ethernet dnsResolve unsigned char host unsigned char tmax Prototype pointer to the location holding the IP address the requested host name was resolved 0 otherwise 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
432. nsigned bcdnum Returns Converted decimal value Converts 16 bit BCD numeral to its decimal equivalent Description Parameters bcdnum 16 bit BCD numeral to be converted unsigned a b 0x1234 a equals 4660 b 2 16 b equals 1234 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 587 7 Libraries mikroC PRO for PIC Dec2Bcd16 Prototype unsigned Dec2Bcd16 unsigned decnum Returns Converted BCD value Converts unsigned 16 bit decimal value to its BCD equivalent Description Parameters decnum unsigned 16 bit decimal number to be converted unsigned a b 2345 Dec2Bcd16 a b equals 9029 588 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries PRINTOUT LIBRARY The mikroC PRO for PIC provides the PrintOut routine for easy data formatting and printing Note Library works with PIC18 family only Library Routines PrintOut PrintOut Prototype void PrintOut void prntoutfunc char ch const char f Nothing PrintOut is used to format data and print 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
433. nsigned int unsigned long int E 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 ifa constant has both L and U suffixes LU or UL its data type will be unsigned l ng int 148 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Decimals 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 interpret ed as an octal constant Thus int i 10 decimal 10 int i 010 decimal 8 int i OF decimal 0 octal 0 In the absence of any overriding suffixes the data type of a decimal constant is derived from its value as shown below 2147483648 32769 32768 129 bk 56 32767 int 65536 2147483647 Hexadecimal Constants 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 treat ed as unsigned int MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 149 6 Language Reference mikroC PRO for PIC Binary Constants All constants
434. nt 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 xpressionl expression2 The expressioniis an object memory location to which the value of expression2 is assigned Operand expression has to be lvalue and expression2 can be expression The assignment expression itself is not Ivalue If expressionl and expression are of different types the result of the expres sion2 Will be converted to the type of expression1 if necessary Refer to Conversions for more information Compound Assignment Operator C allows more comlex assignments by means of compound assignment operators The syntax of compound assignment operators is expressionl op expression2 where be one of binary operators 5 lt lt OF gt gt Thus we have 10 different compound assignment operators 5 and gt gt All of them associate from right to left Spaces sepa rating compound operators e g will generate an error Compound assignment has the same effect as expressionl expressionl op expression2 except the lvalue expressioni is evaluated only once For example expres 1 expression2 is the same as expressionl expressionl expres sion2 MI
435. nt number using the format d dddde dd Floating point number using the format d ddddE dd Description Floating point number using either e or f ormat whichever is more compact for the specified value and precision 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 96 is written No argument is converted he complete conversion specification shall be 9696 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 597 7 Libraries mikroC PRO for PIC 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 justify the output in the specified field width Prefix the output value with or sign if the output is a signed type 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 ox when used with o x x field types respectively When used with the g ield types the flag forces the output value to include a decimal point In any other case the flag is ignored t gnore format specifier The width field is a non negative number that specifies a minimum number of printed characters If a number of charact
436. nt size 20px terminal tr th colspan 2 gt PORTB lt th gt lt tr gt script Var Str 1 stra for is 0 1 8 1T strt lt tr gt lt td bgcolor pink gt BUTTON it lt td gt if PORTB amp 1 lt lt i strt t lt td bgcolor red gt ON else str4 td bgcolor cccccc gt OFFE Strec e td etr i document write str lt script gt o const char indexPage2 lt table gt lt td gt lt td gt lt table border 1 style font size 20px font family tr th colspan 3 gt PORTD lt th gt lt tr gt amp soripte Nar Str str for i 0 i1 lt 3 1i strt lt tr gt lt td bgcolor yellow gt LED it lt td gt if PORTD 1 lt lt i strt lt td bgcolor red gt ON else strt lt td bgcolor cccccc gt OFF strt 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 font family terminal gt This as request f script document write REQ script BODY HTML JRCKCKCKCKCkCkCkCkCkCkCkCk ck Ck kCk ck Ck Ck k ck Ck ck Ck ck k ck ck ckck kck KK RAM variables y unsigned char myMacAddr 6 0x00 0x14 5 0x76 0x19 0 3 my MAC address unsigned char myIpAddr 4 1192 168 20 60 qs my IP address unsigned char qwipAddy 1192 168 20 6 Y gateway router IP address unsigned char
437. nt valueDAC char temp Chip Select 0 Select DAC chip Send High Byte temp valueDAC gt gt 8 amp 0 0 Store valueDAC 11 8 to temp 3 0 temp 0x30 Define DAC setting see MCP4921 datasheet SPI1 Write temp Send high byte via SPI Send Low Byte MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC temp valueDAC SPI1 Write temp Chap Select 1 void main ANSEL 0 ANSELH 0 InitMain value 2048 while 1 amp RAD bit ks value else i 1 bit value DAC Output value Delay ms 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Fi 77 21 if Lif Store valueDAC 7 01 CHAPTER 7 Libraries to templ 7 0 Send low byte via SPI Deselect DAC Perform main When program the output Endless loop value lt 4095 value gt 0 vy chip initialization starts DAC gives in the mid range If RAO button is pressed increment value If button is pressed decrement value Send value to DAC chip Slow down key repeat pace 447 7 Libraries mikroC PRO for PIC HW Connection All lines are disconnected Vref line is connected Vcc line is connected J310 OSCHLATOR VOCO DAC CONNECTOR MCP 4921 SPI HW connec
438. nterrupt low void You are expected to write your own definition function body to handle interrupts in your application mikroC PRO for PIC saves the following SFR on stack when entering interrupt and pops them back upon return PIC12 family w STATUS FSR PCLATH PIC16 family w STATUS FSR PCLATH PIC18 family fast context is used to save WREG STATUS BSR Use the pragma disablecontexsaving to instruct the compiler not to automatical ly perform context switching This means that no regiser will be saved restored by the compiler on entrance exit from interrupt service routine This enables the user to manually write code for saving registers upon entrance and to restore them before exit from interrupt MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 121 4 Specifics 122 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC P18 priority interrupts Note For the P18 family both low and high interrupts are supported 1 function with name interrupt will be linked as ISR interrupt service routine for high level interrupt 2 function with name will be linked as ISR for low level inter rupt low If interrupt priority feature is to be used then the user should set the appropriate SFR bits to enable it For more information refer to datasheet for specific device Function Calls from Interrupt Calling functio
439. null termination into ENC28J60 RAM starting from current ENc28 760 write pointer location Deseripuan Parameters ptr String to be written into 28 760 RAM Ethernet module has to be initialized See Spi Ethernet Init char buffer mikroElektronika SPI Ethernet putString buffer put a RAM string into ENC28J60 buffer 458 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi Ethernet putConstString Prototype unsigned int SPI Ethernet putConstString const unsigned char ptr Returns Number of bytes written into c28760 RAM This is MAC module routine It stores whole const string excluding null termination into 28760 RAM starting from current lt 28 760 write pointer zwar location Description Parameters ptr const string to be written into ENc28760 RAM Ethernet module has to be initialized See Spi_Ethernet_Init const char buffer mikroElektronika SPI Ethernet putConstString buffer put a const string into 28060 buffer Spi Ethernet getByte Prototype unsigned char SPI Ethernet getByte Returns Byte read from 28760 RAM This is MAC module routine It fetches a byte from address pointed to by cur Description i f rent 2 60 read pointer ERDPT Ethernet module has to
440. numerators 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 Anomous 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 1 ors 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 enun type are required Anonymous enum type enum black red green blue violet white color Enumeration Scope Enumeration tags share the same name space as structure and union tags Enu merators share the same name space as ordinary variable identifiers int blue s 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 ant 1 Jj ILLEGAL colors duplicate tag double red 2 ILLEGAL redefinition of red blue 37 back in int blue scope MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 171 6 Language Reference mikroC PRO for PIC 172 Void void is a special type indicating the absence of any value There are no objects of void instead void is used for deriving mo
441. nvironment mikroC PRO for PIC Step Two Enter the oscillator frequency value New Project Wizard Setup the clock for example 11 0592 MHz Device Clock 11 059200 MHz 4 Back Next Cancel Step Three Specify the location where your project will be saved New Project Wizard LX Step 3 5 Specify where your project will be saved Project File Name Back Next gt Cancel 76 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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 x sess 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 D Projects FirstProject Definit h File Name D Projects FirstProject Definit h Remove Remove All 4 Back Next gt Cancel Step Five Click Finish button to create your New Project New Project Wizard x Step 5 5 You have successfully created a new project Click Finish to save the changes and to close the wizard Back Finish Cancel Related topics Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 77 2 Enviro
442. oC PRO for PIC Environment An item s value can be also changed by double clicking item s value field and typing the new value directly 0100 0000 1000 0011 0001 0010 0110 1111 Representation Dec Hex Bin Float D Char View RAM Window Debugger View RAM Window is available from the drop down menu View Debug Windows View RAM The View RAM Window displays the map of PIC s RAM with recently changed items colored red gi RAM History MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 95 2 Environment mikroC PRO for PIC 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 Soft ware Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has started and ended Note The user can change the clock in the Stopwatch Window which will recalcu late values for the latest specified frequency Changing the clock in the Stopwatch Window does not affect actual project settings it only provides a simulation Cycles Time ResetToZero e 96 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS
443. ock in KHz rounded to the nearest integer Description Note that Get is library function rather than a built in routine it is pre sented in this topic for the sake of convenience Code Optimization Optimizer has been added to extend the compiler usability cut down the amount of code gener ated and speed up its execution The main features are Constant folding All expressions that can be evaluated in the compile time i e are constant are being replaced by their results 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 vari able remains unchanged 130 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 4 mikroC PRO for PIC Specifics 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 there fore eliminate the entire computation for one of them Dead code elimination 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 rationally a
444. oduction mikroC PRO for PIC After Receiving 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 PIC at the time of activation Notes The license key is valid until you format your hard disk In case you need to for mat the hard disk you should request a new activation key Please keep the activation program in a safe place Every time you upgrade the compiler you should start this program again in order to reactivate the license 10 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Environment The mikroC PRO for PIC is an user friendly and intuitive environment CHAPTER 2 Environment mikroC PRO for PIC IDE Overview 595 555555 eit Se 2 2 Code Assistant bu function Delay const unsigned long Delay ms const uragas unsigned Clock to unsigned short Clock Mz vod Delay The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant Auto Correct for common typos and Code Tem plates Auto Complete The Code Explorer is at your disposal for easier proje
445. 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 com ments the C method and the method Both are supported by mikroC PRO for PIC 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 comment is any sequence of characters placed after the symbol pair The com ment 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 PIC int type i identifier parses as int i Note that the mikroC PRO for PIC 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 PIC 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 jj parses as int i ant j MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 145 6 Language Reference mikroC PRO for PIC Nested comments ANSI C doesn t allow nested comments
446. of its 2 arguments 232 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference define B gt A Tess call its 2 x MAX a Preprocessor will transform the previous line into x b gt edd s 8 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 undef directive is used to undefine a macro undef macro identifier The directive undef detaches any previous token sequence from macro identi fier the macro definition has been forgotten and macro identifier is undefined No macro expansion occurs within the 4unae lines The state of being defined or undefined is an important property of an identifier regardless of the actual definition The ifdef ifndef conditional directives used to test whether any identifier is currently defined or not offer a flexible mech anism 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 extension see Add Remove Files from Pro
447. of predefined globals and constants All PIC SFR registers and their bits are implicitly declared as global variables These identifiers have an external linkage and are visible in the entire project When creating a project the mikroC PRO for PIC will include an appropriate file from defs folder containing declarations of available SFR registers and constants For complete set of predefined globals and constants look for Defs in the mikroC PRO for PIC installation folder or probe the Code Assistant for specific letters Ctrl Space in the Code Editor 4 mikroC PRO for PIC Specifics Predefined project level defines There are four predefined project level defines for any project you make These defines are based on values that you have entered edited in the current project First one is equal to the name of selected device for the project i e if 16F887 is selected device then 16F887 token will be defined as 1 so it can be used for conditional compilation ifdef P16F887 fendif second one is FOSC value of frequency in Khz for which the project is built Third one is for identifying mikroC PRO for PIC compiler ifdef PRO FOR PIC endif Fourth one is for identifying the build version For instance if a desired build ver sion is 142 user should put this in his code if PRO FOR PIC BUILD 142 endif User can define custom project level
448. of this page send messag xtended CAN message with the appropriate ID and data char tx flags 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 5 TX XTD FRAME set message flags CANSPIWrite msg id data 2 tx flags MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 265 7 Libraries 266 CANSPI Constants mikroC PRO for PIC 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 effectively Check the exam ple at the end of the chapter CANSPI OP MODE The CANSPI OP MODI E constants define CANSPI operation mode Function CANSPISetOperationMode expects one of these as it s argument const char CANSPI MODE CANSPI MODE CANSPI MODE CANSPI MODE CANSPI MODE CANSPI MODE E UJ H D z 2 TS ES AL SLEEP LOOP LISTEN _60 PIG CANSPI CONFIG FLAGS OxEO 0x00 0x20 0x40 0x60 0x80 Use this to access opmode bats The CANSPI CONFIG FLAGS constants define flags related to the CANSPI module configuration The functions CANSPIInitialize CANSPISetBaudRate CANSPISetMask and CANSPISetFilter expect one of these or a bitwise combina
449. oint 2 will be used only to start the Stopwatch B Halt on Stop Condition Breakpoint 3 when checked the program execution will stop on Breakpoint 3 Otherwise Breakpoint 3 will be used only to stop the Stopwatch B Reset Stopwatch on Run when checked the Stopwatch will be cleared before continuing program execution and the next counting will start from zero wise the next counting will start from the previous Stopwatch value 116 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Other CHAPTER mikroC PRO for PIC Specifics The following topics cover the specifics of mikroC PRO for PIC compiler ANSI Standard Issues Predefined Globals and Constants Accessing Individual Bits Interrupts PIC Pointers Linker Directives Built in Routines Code Optimization Memory Type Specifiers 117 4 Specifics Kg OE LVEKROUBUIAHT REOROA ABR DAINDARERANTAREREDVAR DSIGLRORONGHEDD E D BEDR mikroC PRO for PIC ANSI Standard Issues Divergence from the ANSI C Standard Tentative declarations are not supported C Language Exstensions mikroC PRO for PIC has additional set of keywords that do not belong to the ANSI standard C language keywords code data IX at sbit bit sfr Related topics Keywords PIC Specific Predefined Globals and Constants To facilitate programming of PIC compliant MCUs the mikroC PRO for PIC imple ments a number
450. olbar can easily be customized by adding new tools in Options F12 window Related topics Keyboard shortcuts Integrated Tools Debugger Windows 24 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment PROJECT MENU OPTIONS Build Ctrl F9 Build All Projects Shift F9 gt Build Program Ctrl Fi1 View Assembly Edit Search Paths Clean Project Folder Add File To Project Remove File From Project Import Project Ctrl I New Project Shift Ctrl N Open Project Shift Ctrl O Save Project Edit Project Shift Ctrl E Open Project Group Close Project Group Save Project As Recent Projects b Close Project MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 25 2 Environment mikroC PRO for PIC Project Description A Ctrl F9 Build active project Build All Projects Shift F9 Build all projects Bud alProjects Build and program active project View Assembly Edit search paths Clean Project Folder Add file to project Remove file from project Import Project Ctrl I Import projects from previous versions of mikroC Fer Mew Project Open New Project Wizard 3X OpenProject Shift Ctrl O existing project Save Project Save current project Edit Proje
451. om x0 y0 to x1 y1 Prototype Parameters x0 X coordinate of the line start y0 y coordinate of the line end 1 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 Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Description SPI T6963C I rne 0 0 239 127 69630 WHITE Spi T6963C rectangle void SPI 6963 rectangle int x0 int y0 int xl int yl unsigned char pcolor Draws a rectangle on GLCD Prototype Parameters Description 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 yl y coordinate of the lower right rectangle corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Requires Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C rectangle 20 219 107 T6963C WHITE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 515 7 Libraries mikroC PRO for PIC Spi T6963C box void SPI T6963C box int x0 int 0 int x1 int yl unsigned char Prototype pcolor Draws a box on the GLCD Parameters x0 X coordinate of the upper left box corner y0 y coordinate of the upper left box corner x1 X
452. on point ers 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 pro gram 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 allowed 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 PIC 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 PIC can consistently access interpret and possibly change the bit pat terns 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 vari ants of some of them For more information on fundamental types refer to the topic Fun damental Types The derived types are also known as structured types and they include pointers to other types arrays of other types function types str
453. on LCD at current cursor position Both variables and literals can be passed as character Description Parameters Out Char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write character e at current cursor position SPI Led Chr Cp e Spi Lcd Cmd Sends command to LCD Parameters Description P out char command to be sent Note Predefined constants can be passed to the function see Available Lcd Commands Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Clear Lcd display SPI Led Cmd LCD CLEAR 496 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Available LCD Commands a NNNM Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected D RETURN HOME MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 497 CHAPTER 7 Libraries mikroC PRO for PIC Library Example This example demonstrates how to communicate Lcd via the SPI module using serial to parallel convertor 23517 char text mikroElektronika Port Expander module connections sbit SPExpanderRST at RCO bit sbit SPExpanderCS at bit sbit SPExpanderRST Direction at TRISCO bit sbit SPExpanderCS Direction at T
454. on UART1 transmit INTCON PEIE 1 227 peripheral interrupts INTCON GIE 1j enable all interrupts while 1 upon completed valid message receiving is set to 255 Chott 416 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries dat 5 4 if an error detected signal it PORTD 24 by setting portd to if 41 if message received successfully cnt 0 dat 4 0 clear message received flag J dati 3 for i 1 i lt dati 3 show data on PORTB PORTB dat 1 1 increment received dat 0 dat 0 1 send back to master Delay ms 1 RS485Master Send dat 1 160 cnt gt 100000 4 PORTD cnt 0 RS485Master Send dat 1 160 Af P 10 if sending failed 10 times RS485Master Send dat 1 50 send message on broadcast address 77 function to be properly linked RS485 Slave code char dat 9 buffer for receving sending messages char i j sbit rs485 rxtx at RC2 bit set transcieve pin sbit rs485 rxtx pin direction at TRISC2 bit set transcieve pin direction Interrupt routine void interrupt RS485Slave Receive dat void main ANSEL 0 ANSELH 0 Configure AN pins as digital I O PORTB 0 PORTD 0 0 0 TRISB TRISD MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EM
455. on date and file size via UART void M Test File Exist 1 unsigned long fsize unsigned int year unsigned short month day hour minute unsigned char outstr 12 filename 7 uncomment this line to search for file that DOES exists filename 7 F uncomment this line to search for file that DOES NOT exist 290 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries if Cf Fat Assign filename 0 4 file has been found get its date Cf Fat Get File Date amp year amp month amp day amp hour amp minute WordToStr year outstr UART1 Write Text outstr ByteToStr month outstr UART1 Write Text outstr WordToStr day outstr UART1 Write Text outstr WordloSotr ihour Ooutstr 4 UART1 Write Text outstr WordToStr minute outstr UART1 Write Text outstr 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 Tries to create 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 LE
456. one byte to the current location in Glcd memory and moves to the next location Description Parameters ddata data to be written 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 Set Page unsigned short data Glcd Write Data data Glcd Fill Prototype void Fill unsigned short pattern Fills memory with the byte pattern Parameters Description pattern byte to fill Glcd memory with To clear the Glcd screen use 11 0 To fill the screen completely use Gicd Fill 0xFF Glcd needs to be initialized see Glcd Init routine Clear screen Gleda FILLOY MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 331 7 Libraries mikroC PRO for PIC Glcd Dot void Glcd Dot unsigned short x pos unsigned short Prototype g Pes g 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 Description color color parameter Valid values 0 2 The parameter color determines a dot state 0 clears dot 1 puts a dot and 2 inverts dot state Note For x and y axis layout explanation see schematic at the bottom of this page Requires Glcd needs to Glcd needs to be initialized see Initrouine
457. one of the subfolders of the compiler s Uses folder DriveName Program Files Mikroelektronika mikroC PRO for PIC Uses P16 DriveName Program Files Mikroelektronika mikroC PRO for Uses P18 If you are creating library for PIC16 MCU family the file should be saved in P16 folder If you are creating library for PIC18 MCU family the file should be saved in P18 fodler If you are creating library for PIC16 and PIC18 MCU families the file should be saved in both folders 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 Compiled file Lib Example mci should appear in mikroc PRO for PIC Uses folder 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 PIC Defs and it is named MCU NAME mlk for example 16F887 mlk Add the the following segment of code to lt LIBRARIES gt node of the definition file de
458. only exceptions are vVdelay ms Delay Cyc and Get Fosc kHz Which are actual C routines Note Lo Hi Higher and Highest functions are not implemented in compiler any more If you want to use these functions you must include built in ninto your project Lo Hi Higher Highest Delay us Delay ms Vdelay ms Delay Cyc Clock Khz Clock Mhz Get Fosc kHz Lo Returns Returns the lowest 8 bits byte of number bits 0 7 Function returns the lowest byte of number Function does not interpret bit pat terns of number it merely returns 8 bits as found in register Description 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 Arguments must be variable of scalar type i e Arithmetic Types and Pointers d OxlACSOR tmp Lo d Equals OxF4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 125 4 Specifics 126 Description Requires Higher Hi Returns Returns next to the lowest byte of number bits 8 15 mikroC PRO for PIC Function returns next to the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Arguments must be variable of scalar type i e Arithmeti
459. or PIC 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 expres sion 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 attrib utes storage class and type sometimes referred to as data type The mikroC PRO for PIC compiler deduces these attributes from implicit or explicit declarations in the source code Usually only the type is explicitly specified and the storage class spec ifier assumes the automatic value auto Generally speaking an identifier cannot be legally used in a program before its
460. or more information refer to the Compound Statements Comma Comma separates the elements of a function argument list 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 Fune i 19 call fune with two args func expl exp2 exp3 exp4 exp5 also calls func with two args 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 PIC might ignore it add Evaluate a b but discard value tta Side effect on a but discard value of 3 Empty expression or a null statement MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 159 6 Language Reference mikroC PRO for PIC Semicolons are sometimes used to create an empty statement for 5 62 54 For more information see the Statements Colon Use colon to indicate the labeled statement start x 0 obo did Labels are discussed in the Labeled Statements Asterisk Pointer Declaration Asterisk in a variable declaration denotes the creatio
461. ory elements com monly 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 routines are not performed directly but suc cessively through 512B buffer Note Routines for file handling can be used only with FAT16 file system Note Library functions create and read files from the root directory only Note 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 Note 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 Note 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMB
462. ou should receive the Init OK message Then you can experiment with MMC read and write functions and observe the results through the Usart Terminal MMC module connections sbit Mmc Chip Select at RC2 bit sbit Mmc Chip Select Direction at TRISC2 bit eof MMC module connections Nariables for MMC routines unsigned char SectorData 512 Buffer for MMC sector reading writing unsigned char data for registers 16 buffer for CID and CSD registers 1 write text and new line carriage return line feed void Write Line char uart text UART1 Write Text uart text UARTI Write 13 UART1 Write 10 Display byte in hex void PrintHex unsigned char i unsigned char hi lo hi i amp OxF0 High nibble hai hi gt gt hi s 4 Q if h15 9 lo e x amp TOT Low nibble Af 105 98 Lo lo 7 UART1 Write hi VARTI Write lo void main const char FILL CHAR m unsigned int i SectorNo char mmc error bit data ok ADCON1 OxOF Configure AN pins as digital CMCON 7 Turn off comparators Initialize UART1 module 380 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries UARTL Tart 19200 3 Delay 10 VARTI Write Line PIC Started PIC present report Initialize SPI1 module SPIl Init Advanced SPI MASTER OSC DIV64 S
463. out Help Description Help Fi Open Help File Migration Document Open Code Migration Document Check For Updates Check if new compiler version is available mikroElektronika Support Forums Open mikroElektronika Support Forums in a default browser Open mikroElektronika Web Page in mikroElektronika Web Page defa lt browser 2 How To Register Information on how to register Open About window Related topics Keyboard shortcuts MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 29 2 Environment 30 KEYBOARD SHORTCUTS mikroC PRO for PIC Below is a complete list of keyboard shortcuts available in mikroC PRO for PIC IDE EShortcuts 1 F11 Start mE Programmer Shift F4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Ctrl Shift S Ctrl V Ctrl X Ctrl Y Ctrl Z Ctrl Shift Z Advanced Editor Shortcuts Ctrl Space Ctrl Shift Space Ctrl D Ctrl L Ctrl G Ctrl J Ctrl Shift Ctrl Shift Ctrl number Ctrl Shifttnumber Ctrl Shift l Ctrl Shift U AB Shift TAB Alt Select Ctrl Alt Select Ctri Alt L Ctri Alt U Ctri Alt T Convert selection to lowercase Convert selection to uppercase Convert to Titlecase 2 mikroC PRO for PIC Environment Simulator Shortcuts gu cd MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 31
464. p Library Time Library Trigonometry Library 580 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries BUTTON LIBRARY The Button library contains miscellaneous routines useful for a project development Library Routines Button Button unsigned short Button unsigned short port eum short pin unsigned short time unsigned short active state Returns lt 0 255 Function eliminates the influence of contact flickering upon pressing a button debouncing Prototype Description Parameter port specifies the location of the button parameter pin is the pin number on designated port and goes from 0 7 parameter time is a debounce period milliseconds parameter active state can be either 0 or 1 and it deter mines if the button is active upon logical zero or logical one Button pin must be configured as input Example reads RBO to which the button is connected on transition from 1 to 0 release of button PORTD is inverted do if Button amp PORTB 0 1 1 oldstate 1 if oldstate 68 Button amp PORTB 0 1 0 4 PORTD PORTD oldstate 0 while 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 581 7 Libraries mikroC PRO for PIC CONVERSIONS LIBRARY The mikroC PRO for PIC Conversions Library provides routines for numerals to strings and BCD decimal conversions
465. pending on clock speed 292 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries HW Connection OSCRLATOR 0cSt 48LOld m Compact Flash Card ee te See Pin diagram of CF memory card MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 293 7 Libraries mikroC PRO for PIC 294 EEPROM LIBRARY EEPROM data memory is available with a number of PIC MCUs mikroC PRO for PIC includes library for comfortable work with EEPROM Library Routines Eeprom Read Eeprom Write EEPROM Read Prototype unsigned short EEPROM Read unsigned int address Returns Returns byte from specified address Reads data from specified address Parameter address is of integer type which means it supports MCUs with more than 256 bytes of EEPROM Description unsigned short take Requires EEPROM module Requires Ensure minimum 20ms delay between successive use of routines EEPROM Write and EEPROM Read Although PIC will write the correct value EEPROM Read might return an undefined result take EEPROM 0 3 EEPROM Write Prototype void EEPROM Write unsigned int address unsigned short data Writes data to specified address Parameter address is of integer type wh
466. plates Auto Complete Auto Correct for common typos Spell Checker Bookmarks and Goto Line Comment Uncomment You can configure the Syntax Highlighting Code Templates and Auto Correct from the Editor Settings dialog To access the Settings click Tools Options from the drop down menu click the Show Options Icon a or press 12 key Editor Settings Editor Settings Project Files Restore Last Opened Project Restore All Opened Files 177 Editor Colors V Save Breakpoints V Save Bookmarks 2 e Opened File Is Externally Modified Prompt for action Reload but do not prompt Ignore externally made changes Auto Correct Auto Save 2 Timeout Interval 3 minutes Auto Complete Enable Auto Save Highli Highlighter gt Highlight begin end pairs V Highlight brackets Spelling H V Check Spelling Comment style qi single line Advanced Editor Options Open options dialog Code Folding V Enable code folding Show Ident Guides J Tools Dutput Cancel 36 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Code Assistant If you type the first few letters of a word and then press Ctrl Space all valid iden tifiers 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
467. plays functions by their addresses in the ascending order Functions Sorted by Name Chart Sorts and displays functions by their names in a chart like form 100 120 140 160 180 200 220 240 260 280 30 320 340 C Program FilesiMikroelektronkalnkroC PRO PIC Examples Develepment 52 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Functions Sorted by Size Chart Sorts and displays functions by their sizes in a chart like form 100 120 140 160 180 200 20 240 20 20 30 30 Project Name C Program PRO PIC Examoles Development Systems EasyPICS Gled Gled meppi Functions sorted by Address Chart Sorts and displays functions by their addresses in a chart like form 1000 1400 1 1300 1 400 Fol Crogan Pey PIC Examoles Development _ Systems EasyPICS Gled Gled mcppi MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 53 2 Environment mikroC PRO for PIC Function Tree Displays Function Tree with the relevant data for each function Brint to file Project Name C Program FleslMbroelektronkalmkroC PRO Time 2 24 2009 8 57 44 AM Memory Summary Displays summary of RAM and ROM memory in a pie like form Brint to file Project Name C Program FleeslMizcele
468. ple mented 2 Read and Write operations supported write is executed as erase and write For this group of MCU s read and write functions are implemented Note that write operation which is executed as erase and write may write less bytes than it erases 3 Read Write and Erase operations supported For this group of MCU s read write and erase functions are implemented Further more flash memory block has to be erased prior to writting write operation is not executed as erase and write Please refer to MCU datasheet before using flash library Library Routines FLASH Read FLASH Read N Bytes FLASH Write FLASH Write 8 FLASH Write 16 FLASH Write 32 FLASH Write 64 FLASH Erase FLASH Erase 64 FLASH Erase 1024 FLASH Erase Write FLASH Erase Write 64 FLASH Erase Write 1024 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 321 7 Libraries mikroC PRO for PIC FLASH Read for PICLE unsigned FLASH Read unsigned address for PIC18 unsigned short FLASH Read long address 4 Returns data byte from Flash memory Reads data from the specified address in Flash memory J tor PICIS unsigned short tmp tmp FLASH Read 0x0D00 FLASH Read N Bytes Prototype void FLASH Read N Bytes long address char data unsigned int N Description _ data from the specified address in Flash memory to varibale pointed by FLASH Read N 0x0D
469. pm The identifier mu of the type myunion can be used to hold a 2 byte int 4 byte dou ble 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 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 188 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference tmp mu i peculiar result pm gt i 3 tmp OK maci 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 Bit Fields Bit fields are specified numbers of bits that may or may not have an associated iden tifier Bit fields offer a way of subdividing structures into named parts of user defined sizes Structures and unions
470. pointers will refer to banks 0 and 1 To access the objects in banks 2 or 3 via pointer user should man ually set the IRP and restore it to zero after the operation The stated rules apply to any indirect approach arrays structures and unions assignments etc Note It is very important to take care of the IRP properly if you plan to follow this approach If you find this method to be inappropriate with too many variables you might consider upgrading to 18 Note If you have many variables in the code try rearranging them with the linker directive absolute Variables that are approached only directly should be moved to banks 3 and 4 for increased efficiency Related topics mikroC PRO for PIC specifics MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 135 5 PIC Specifics mikroC PRO for PIC MEMORY TYPE SPECIFIERS The mikroC PRO for PIC 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 IX sfr Memory type specifiers can be included in variable declaration For example char data data buffer puts data buffer in data ram const char code txt ENTER PARAMETER puts text in program memory code puts txt in program memory const char code txt
471. points Advanced Breakpoints can be used with PIC18 and PIC18FJ MCUs To enable Advanced Breakpoints set the Advanced Breakpoints checkbox inside Watch window v Advanced Breakpoints To configure Advanced Breakpoints start mikrolCD F9 and select View gt Debug Windows Advanced Breakpoints option from the drop down menu or use Ctrl Shift A shortcut Advanced Breakpoints Breakpoint 1 Memory Break Address 0200 File Register Break Breakpoint 2 Program Memory Break File Register Break Address Read Access F8 Write Access Breakpoint 3 Program Memory Break File Register Break MI F er Equal File Register Equal File Reg q 0 Value 9 00 Passcount 1 Passcount 2 Emulator Features Event Breakpoints Enable Stopwatch Break on Stack Over Underflo or ar ndi r point 2 Break on Watchdog Timer Halt on ndit Br Break on SLEEP Reset Stopwatch on Run OK Cancel Apply Note When Advanced Breakpoints are enabled mikrolCD operates in Real Time mode so it will support only the following set of commands start Debugger F9 Run Pause Debugger F6 and Stop Debugger Ctrl F2 Once the Advanced Breakpoint is reached the Advanced Breakpoints feature can be disabled and mikrolCD debugging can be continued with full set of commands If needed Advanced Breakepoints can be re enabled without restarting mikrolCD Note Number of Advanced Breakpoints is eq
472. port T6963C_negBit 0x03 T6963C_displayGrPanel Prototype void T6963C displayGrPanel char Display selected graphic panel Description Parameters graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See the T6963C_ init routine display graphic panel 1 T6963C displayGrPanel 1 T6963C displayTxtPanel Prototype void T6963C displayTxtPanel char n Display selected text panel Description Parameters n text panel number Valid values o and Toshiba Glcd module needs to be initialized See the T6963C init routine display text panel 1 T69623C displayTxtPanel 1 542 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries T6963C setGrPanel Prototype void T6963C setTxtPanel char n Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel Description Parameters graphic panel number Valid values 0 and 1 Toshiba module needs to be initialized See the T6963C_ init routine set text panel 1 as current text panel T6963C setTxtPanel 1 T6963C_SetTxtPanel Prototype void T6963C setTxtPanel char n Compute start address for selected text panel and set appropriate internal point ers All subsequent text operations will be preformed at this text panel
473. pose that the object s is of the struct type s and n a member identifier of the type declared in s then the expression s m direct access to member m is of the type and represents the member object m in 5 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 iden tifier of the type declared in s the expression ps m indirect access to member m identical to ps m is of the type and represents the member object m in s The expression ps gt m is a convenient shorthand for 55 m For example struct mystruct int 1 char sta 21 2 double d 5 sptr 5 s i 3 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 lvalue providing that s is lvalue and m is not an array type The expression sptr gt m is an lvalue unless is an array type 186 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Accessing Nested Structures If the structure contains a field whose type is the structure a the members of a can be accessed by two applications of the member selectors struct A int j double x E3 struct B int i struct A aa double d EQ Asper s i 3 assign 3 to the i member of B S aa j 2 assign 2 to the j
474. project folder Please note that selected files will be permanently deleted from your disk if 277111172 SpiEthernet asm SpiEthernet c SpiEthernet c ini SpiEthernet cp SpiEthernet dbg SpiEthernet dct SpiEthernet dlt SpiEthernet hex SpiEthernet Ist SpiEthernet mcl SpiEthernet mcppi SpiEthernet mcppi callertable txt SpiEthernet mil SpiEEhernet user dic s S3 3 S S 3 5 S Clean Cancel C Program Files Mikroelektronika mikroC PRO for PIC Related topics Customizing Projects 86 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment 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 the Project Toolbar If more more than one project is open you can compile all open projects by selecting Project Build All from the drop down menu or click the Build All Icon ka from the Project Toolbar Progress bar will appear to inform you about the status of compiling If there are some errors you will be notified in the Error Window If no errors are encountered the mikroC PRO for PIC will generate output files Output Files Upon successful compilation the mikroC PRO for PIC will generate output files in the project folder folder which contains the projec
475. ption otherwise returns zero islower Prototype Prototype int islower char character Function returns 1 if the character is a lowercase letter a z otherwise returns Description zero ispunct Prototype unsigned short ispunct char character Function returns 1 if the character is a punctuation decimal 32 47 58 63 91 96 123 126 otherwise returns zero Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 565 7 Libraries mikroC PRO for PIC isspace Prototype unsigned short isspace char character Function returns 1 if the character is a white space space tab CR VT NL FF otherwise returns zero isupper Prototype unsigned short isupper char character Function returns 1 if the character is an uppercase letter A Z otherwise Description returns zero isxdigit Prototype unsigned short isxdigit char character Function returns 1 if the character is a hex digit 0 9 A F a f otherwise Description returns zero toupper Prototype unsigned short toupper char character If the character is a lowercase letter a z the function returns an uppercase pesaripion letter Otherwise the function returns an unchanged input parameter tolower Prototype unsigned short tolower char character If the character is an uppercase letter A Z function returns a lowercase let ter Otherwise func
476. 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 Q 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 X 4 unsigned int SPI Ethernet UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength unsigned int len my reply length unsigned char ptr pointer to the dynamic buffer reply is made of the remote host IP address in human read able format ByteToStr remoteHost 0 dyna first IP address byte 3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 475 7 Libraries mikroC PRO for PIC ByteToStr remoteHost 1 dyna 4 second dyna 7 e ByteToS remoteHost 2 dyna 8 JJ Shaw 11 ByteToStr remoteHost 3 dyna 12 fourth Bodo c dyna 15 rim add separator then remote host port number WordToStr remotePort dyna 16 dyna 21 WordToStr destPort dyna 22 dyna 27 28 0 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 conver
477. r PIC18 family MCUs only char ipMask 4 1255 255 02 network mask ifor example 255 255 255 0 char gwIpAddr 4 192 168 15 l 3 gateway router IP address char dnsIpAddr 4 1 192 168 i 17 Jf DNS server IP address SPI Ethernet confNetwork ipMask gwIpAddr dnsIpAddr set network configuration parameters MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI Ethernet arpResolve unsigned char SPI Ethernet arpResolve unsigned char ip unsigned char tmax MAC address behind the IP address the requested IP address was resolved 0 otherwise 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 P18 folder Prototype Description Parameters ip IP address to be resolved tmax time in seconds to wait for an reply Note The Ethernet services are not stopped while this routine waits for ARP reply The incoming packets will be processed normaly during this time Ethernet module has to be initialized See SPI Ethernet Init 4 Available for PIC18 family MCUs only unsigned char IpAddr 4 192 168 11 IP address
478. r SPI communication see SPI Glcd Init routines Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI Glcd Set X and SPI Set Page char data data SPI Glcd Read Data 482 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI Glcd Write Data Prototype void SPI Gl1cd Write Data char Ddata Writes one byte to the current location in Glcd memory and moves to the next location Description Parameters Ddata data to be written Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI Glcd Set X and SPI Set Page char data SPI Gled Write Data data SPI Glcd Fill Prototype void SPI Fill char pattern Fills Glcd memory with byte pattern Parameters Description pattern byte to fill Glcd memory with To clear the screen use SPI Fill 0 To fill the screen completely use SPI 1 Fill 0xFF Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Clear screen SPI Glcd Fill 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 483 7 Libraries mikroC PRO for PIC SPI Glcd Dot Prototype void SPI Glcd Dot char x pos char y pos c
479. r counter 0 void interrupt if INTCON TOIF if counter gt 20 Soft I2C counter 0 reset counter else increment counter INTCON TOIF Clear Timer0 overflow interrupt flag 424 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries oid main OPTION REG 0x04 TMRO prescaler set to 1 32 try Soft I2C Init with blocking prevention mechanism INTCON GIE 1 Global interrupt enable INTCON TOIE 1 Enable TimerO overflow interrupt Sort Tnit 7 INTCON GIE 0 Global interrupt disable Library Example The example demonstrates Software I C Library routines usage The PIC MCU is connected SCL SDA pins to PCF8583 RTC real time clock Program reads date and time are read from the RTC and prints it on Lcd char seconds minutes hours day month year Global date time variables Software I2C connections Soft I20 Sol at ROS bit sbit Soft I2C Sda at RC4 bit sbit Soft I2C Scl Direction at TRISC3 bit sbit Soft I2C Sda Direction at TRISC4 bit End Software I2C connections LCD module connections sbit LCD RS at RB4 bit sbit LCD EN at RB5 bit sbit LCD D4 at RBO bit sbit LCD D5 at RBl bit sbit LCD D6 at RB2 bit sbit LCD D7 at RB3 bit sbit LCD RS Direction at TRISB4 bit sbit LCD EN Direction at TRISB5 bit sbit LCD D4 Di
480. racter Cf Fat Read amp character MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 283 7 Libraries mikroC PRO for PIC Cf Fat Rewrite n currently assigned file for writing If the file is not empty its content will be CF card and CF library must be initialized for file operations See Cf Fat Init The file must be previously assigned See Cf Fat Assign open file for writing Fat Rewrite Cf Fat Append Opens currently assigned file for appending Upon this function execution file Description pointers will be positioned after the last byte in the file so any subsequent file writ ing operation will start from there 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 Cf Fat Delete Deletes currently assigned file from CF card CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign delste current fil Cf Fat Delete 284 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Cf Fat Write Prototype void Cf Fat Write char fdata unsigned data len Reus Noms Writes requested number of bytes to currently assigned file opened for writing Description Parameters fdata d
481. raries SOFTWARE FC LIBRARY The mikroC PRO for PIC provides routines for implementing Software 2 commu nication These routines are hardware independent and can be used with any MCU The Software I2C library enables you to use MCU as Master in 12C communication Multi master mode is not supported Note This library implements time based activities so interrupts need to be dis abled when using Software 2 Note All Software 12C Library functions are blocking call functions they are waiting for 12 clock line to become logical one Note The pins used for the Software 2 communication should be connected to the pull up resistors Turning off the LEDs connected to these pins may also be required External dependecies of Soft I2C Library The following variables must be defined in all T projects using Software Description 2 Library 2 sbit Soft I2C Scl at Soft lt Clock line RC3 bit 2 sbit Soft I2C Sda at Soft I C Data line RC4 bit extern sbit Direction of the Soft sbit Soft I2C Scl Direction Soft I2C Scl Direction 2 Clock pin at TRISC3 bit extern sbit Direction of the Soft spit soft 12C Direction Soft Sda Direction 2 Data pin at TRISCA bit Library Routines Soft I2C Init Soft I2C Start Soft I2C Read Soft I2C Write Soft I2C Stop Soft I2C Break MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 421 7 Libraries m
482. rary The user access es to the TCP HTTP 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 HTTP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP HTTP requests just define this function with return 0 as a single statement Description Parameters remoteHost Client s IP address remotePort Client s TCP port localPort port to which the request is sent regLength TCP HTTP request data field length Note The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply Ethernet module has to be initialized See Spi Ethernet Init This function is internally called by the library and should not be called by the user s code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 461 7 Libraries mikroC PRO for PIC Spi Ethernet UserUDP unsigned int SPI Ethernet UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength 0 there should not be a reply to the request Length of UDP reply data field otherwise This is UDP module routine It is internally called by the library The user access es to the UDP request by using some of the SPI Ethernet get routines The user puts
483. re UART bus Deseripuen Parameters udata data to be sent Software UART must be initialized before using this function See the Soft UART Init routine 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 Soft Uart Break Soft UART Read is blocking routine and it can block the program flow Calling this routine from the interrupt will unblock the program execution This mecha Description nism is similar to WDT Note Interrupts should be disabled before using Software UART routines again see note at the top of this page char datal error counter 0 void interrupt if INTCON TOIF if counter gt 20 Soft UART Break counter 0 reset counter else countertt increment counter INTCON TOIF j Clear Timer0 overflow interrupt flag 436 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries void main OPTION REG 0x04 TMRO prescaler set to 1 32 if Soft Init amp PORTC 7 6 9600 0 0 Soft UART Write 0x55 try Soft UART Read with blocking prevention mechanism INTCON GIE 1 Global interrupt enable INTCON TO IE 1 Enable Timer0 overflow interrupt datal Soft UART Read amp error
484. re 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 Led Out Cp Temperaturet Lcd Out Cp temp Lcd Chr Cp 223 degree character nog Che Use void as a function heading if the function does not take any parameters Alter natively you can just write empty parentheses main void same as main Generic Pointers Pointers be declared as void which means that they can point to any type These pointers are sometimes called generic MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 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 ele ments 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 na
485. rection Direction of the Ready pin CF WE direction Direction of the Write enable pin CF OE direction Direction of the Output enable CF CD1 direction Direction of the Chip detect direction Direction of the Chip enable CF A2 direction Direction of the Address 2 pin CF 1 direction Direction of the Address 1 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 PORTD sbit CF RDY at RB7 bit sbit CF WE at RB6 bit sbit CF OE at RB5 bit sbit CF CD1 at bit sbit CF CE1 at bit sbit CF A2 at RB2 bit sbit CF Al at RBl bit sbit CF AO at RBO bit sbit CF_RDY direction at TRISB7 bit sbit CF WE direction at TRISB6 bit sbit CF OE direction at TRISB5 bit Sbit CF CDI direction at TRISB4 bit sbit CF CEI direction at TRISB3 bit sbit CF A2 direction at TRISB2 bit sbit CF direction at TRISBL bit sbit CF A0 direction at TRISBO bit end of compact flash pinout Cl utt initialize CF 276 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Cf Detect Prototype unsigned short Cf Detect void 1 if CF card was detected 0 otherwise Checks for presence of CF card by reading the chip detect pin 2 MCU ports must be appropriately initialized for card See Wait until CF card
486. rection at TRISBO bit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 425 CHAPTER 7 Libraries mikroC PRO for PIC 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 ota Reads time and date information from RTC PCF8583 void Read Time Sort 122 Start Issue start signal 0 Soft I2C Write 0xAO0 Address PCF8583 see PCF8583 datasheet Soft I2C Write 2 Start from address 2 Soft Start Issue repeated start signal Soft I2C Write 1 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 12 Stop Issue stop signal 1 Formats date and time void Transform Time seconds seconds amp OxF0 gt gt 4 10 seconds amp 0 0 4 Transform seconds minutes minutes OxFO gt gt 4 10 minutes amp OxO0F JJ Transform months hours hours amp OxFO0 gt gt 4 10 hours 6 O0x0F 2 Transform hours year amp 0 0 gt gt 6 77 Transform year day day amp 0x30 gt gt 4 10 day amp OxOF 27 Transform day month month 5 0 10 gt gt
487. ress 0150 Blink PORTB and PORTC diodes to indicate reading start Read data from address 2 and Read data from address 0x50 and for ii 0 ii lt 32 Read 32 bytes block from address 0x80 PORTD Delay ms 250 EEPROM Read 0x80 ii and display data on PORTD MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 295 7 Libraries mikroC PRO for PIC ETHERNET PIC18FXXJ60 LIBRARY PIC18FxxJ60 family of microcontrollers feature an embedded Ethernet controller module This is a complete connectivity solution including full implementations of both Media Access Control MAC and Physical Layer transceiver PHY modules Two pulse transformers and a few passive components are all that are required to connect the microcontroller directly to an Ethernet net work The Ethernet module meets all of the IEEE 802 3 specifications for 10 BaseT connectivity to a twisted pair network It incorporates a number of packet filtering schemes to limit incoming pack ets It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calculations Provisions are also made for two LED outputs to indicate link and network activity This library provides the posibility to easily utilize ethernet feature of the above mentioned MCUs Ethernet PIC18FxxJ60 library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests
488. ression 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 sizeof returns the size of the specified type The unit for type size is sizeof char which is equivalent to one byte The operation size of char gives the result 1 whether char is signed Or unsigned Thus sizeof char returns 1 sizeof int 2 sizeof unsigned long returns 4 sizeof float returns 4 218 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference 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 i Jy e LOZ j sizeof s lj J SizeoE int 2 7 i sizeof a T 210 tegESOF rDE 20 w 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 EXPRESSION Expression is a sequence of operators operands and pun
489. 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 Operators Precedence of logical relational and arithmetic operators was designated in such a way to allow complex expressions without parentheses to have an expected meaning Che lt TRES reads asi gt 0 amp amp lt 9 F 1 x 4 reads s la 1 B 4 Logical AND 55 returns 1 only if both expressions evaluate to be nonzero otherwise 214 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference returns 0 If the first expression evaluates to false the second expression will not be evaluated For example a c b Be e di reads as a gt b 55 c if gt b is false 0 c lt 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 eval uated For example a amp amp b c amp amp d reads as 55 b c ae d xt xs true 1 amp amp d will mot be evaluated Logical Expressions and Side Effects General rule regarding complex logical expressions is
490. ription power x ex fabs Function returns the absolute i e positive value of a floor Prototype double floor double x Function returns the value of parameter x rounded down to the nearest integer frexp Prototype double frexp double value int eptr Function splits a floating point value into a normalized fraction and an integral Description power of 2 The return value is the normalized fraction and the integer exponent is stored the object pointed to by gt Idexp Prototype double ldexp double value int newexp Function returns the result of multiplying the floating point number num by 2 raised to the power n i e returns 2n Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 569 7 Libraries mikroC PRO for PIC log Function returns the natural logarithm of x i e Loge x log10 Function returns the base 10 logarithm of x i e 16510 x modf Prototype double modf double val double iptr Returns argument va split to the fractional part function return val and integer part in number iptr pow Prototype double pow double x double y m Function returns the value of raised to the power i e If x is negative Description the function will automatically cast into unsigned long S in Function returns the sine of in radians The return value is
491. roC PRO for PIC RS485Master Receive Prototype void RS485Master Receive char data buffer 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 in the following manner 2 21 message content Description number of message bytes received 1 3 is set to 255 when message is received is set to 255 if error has occurred address of the Slave which sent the message The function automatically adjusts 4 and datal 51 upon every received message These flags need to be cleared by software Requires MCU must be initialized as a Master for RS 485 communication See q RS485master_Init char RS485Master Receive msg RS485Master_Send void RS485Master_Send char data_buffer char datalen char Prototype Slave address Sends message to Slave s Message format can be found at the bottom of this page Peer Parameters Description data buffer data to be sent datalen number of bytes for transmition Valid values 0 3 slave address Slave s address 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 8 send 3 bytes of data to Slave with address 0 12 RS485Master Send msg 3 0x12 412 MIKROELEKTRONIKA SO
492. roElektronika Ethernet putConstBytes buffer 16 put a const array into Ethernet controller s buffer Ethernet putString Prototype unsigned int Ethernet putString unsigned char ptr Number of bytes written into Ethernet controller s RAM This is MAC module routine It stores whole string excluding null termination into Ethernet controller s RAM starting from current Ethernet controller s write pointer EWRPT location Description Parameters ptr String to be written into Ethernet controller s RAM Requires Ethernet module has to be initialized See Ethernet Init char buffer mikroElektronika Ethernet putString buffer put a RAM string into Ethernet controller s buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 303 7 Libraries mikroC PRO for PIC 304 Ethernet putConstString Prototype unsigned int Ethernet putConstString const unsigned char ptr Returns Number of bytes written into Ethernet controller s RAM This is MAC module routine It stores whole const string excluding null termina tion into Ethernet controller s RAM starting from current Ethernet controller s Description write pointer EwRPT location Parameters ptr const string to be written into Ethernet controller s RAM Ethernet module has to be initialized See Ethernet Init const char buffer mikroElektronika
493. rototype void T6963C image const code char pic Description 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 PIC pointer to const and pointer to RAM equivalency Use the mikroC PRO s integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for display ing on Glcd Note Image dimension must match the display dimension Toshiba Glcd module needs to be initialized See the T6963C init routine T6963C sprite Prototype void T6963C sprite unsigned char px unsigned char py const code char pic unsigned char sx unsigned char sy Description 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 Note If ox and sx parameters are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width Toshiba Glcd module needs to be initialized See the T6963C init routine Example 76963 sprite 76 4 einstein 88 119 draw a sprite 540 SOFTWARE AND HA
494. routine It stores requested number of bytes into ENC28360 RAM starting from current ENc28760 write pointer location Description Parameters RAM buffer containing bytes to be written into ENc28760 RAM n humber of bytes to be written 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 457 7 Libraries mikroC PRO for PIC Spi Ethernet putConstBytes void SPI Ethernet putConstBytes const unsigned char unsigned Prototype p P ee This is MAC module routine It stores requested number of const bytes into ENC28J60 RAM starting from current ENc28760 write pointer Ew location Description Parameters ptr const buffer containing bytes to be written into 28 760 RAM n number of bytes to be written Requires Ethernet module has to be initialized See Spi Ethernet Init const char buffer mikroElektronika SPI Ethernet putConstBytes buffer 16 put a const array into 28060 buffer Spi Ethernet putString Prototype unsigned int SPI Ethernet putString unsigned char Returns Number of bytes written into ENc28760 RAM This is MAC module routine It stores whole string excluding
495. rrence of the string s2 in the string si excluding the terminating null character Description The function returns pointer to first occurrence of s2 in 51 if no string was found function returns o If s2 is a null string the function returns o strcspn Prototype char strcspn char sl char s2 Function computes the length of the maximum initial segment of the string point ed to by s that consists entirely of characters that are not in the string pointed Description to by s2 The function returns the length of the initial segment strpbrk Prototype char strpbrk char 51 char s2 Function searches s1 for the first occurrence of any character from the string 52 The terminating null character is not included in the search The function returns pointer to the matching character in s1 If si contains no characters from s2 the function returns 0 Description strrchr Prototype char strrchr char ptr unsigned int chr 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 if no matching character was found function returns 0 Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 579 7 Libraries mikroC PRO for PIC MISCELLANEOUS LIBRARIES Button Library Conversions Library Sprint Library Setjm
496. ruct mystruct ps OK 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 lo 91 declare variables 1 and o2 of Circle MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 183 6 Language Reference mikroC PRO for PIC 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 and q struct Dot p 5 12 q 1347 90 5 Declare and initialize circle ol struct Circle ol 1 0 0 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 before has been declared struct A incomplete struct B struct 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 incomplet
497. ry data needed by the library Note MMC SD card has to be formatted to FAT16 file system 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 SPI1 Init SPI1 Init Advanced routines MMC module connections sfr sbit Mme Chip Select at RC2 bit sfr sbit Mmc Chip Select Direction at TRISC2 bit MMC module connections Initialize SPIL module and set pointer s to SPIL functions 5 1 Init Advanced MASTER OSC DIV64 DATA SAMPLE MIDDLE CLK IDLE LOW LOW 2 HIGH use fatl6 quick format instead of init routine if a formatting is needed af 4 reinitialize 5 1 at higher speed SPI1 Init Advanced MASTER OSC DIV4 DATA SAMPLE MIDDLE CLK IDLE LOW LOW 2 HIGH 372 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC Mmc Fat QuickFormat CHAPTER 7 Libraries Prototype unsigned char Mmc Fat QuickFormat char mmc fat label 0 if MMC SD was detected and successfuly initialized 1 if FAT16 format was u nseccessful 255 if MMC SD card was not detected Formats to FAT 16 and initializes MMC SD card Parameters mmc fat label volume label 11 characters in length If less than 11 charac ters are provided th
498. ry 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 CAN node unsigned char Can Init Flags Can Send Fl unsigned char Rx Data Len char RxTx 8 char Msg Rcvd const long ID 1st long Rx ID 123111 ID gad e 3 void main ags Can Rcv Flags can flags received data length in bytes can rx tx data buffer reception flag node IDs PORTC 0 clear PORTC TRISC D set PORTC as output Can Init Flags 0 if Can Send Flags 0 clear flags Can Rev Flags 0 Can Send Flags TX PRIORITY 0 amp form value to be used CAN TX XTD FRAME amp with CANWrite CAN TX NO RTR FRAME Can Init Flags CAN CONFIG SAMPLE THRICE amp form value to be used CAN CONFIG PHSEG2 PRG ON with CANInit CAN CONFIG XTD MSG amp CAN CONFIG DBL BUFFER ON 6 CAN CONFIG VALID XTD MSG CANInitialize 1 3 3 3 1 Can Init Flags Initialize CAN module CANSetOperationMode CAN MOD E CONFIG 0x FF set CONFIGURATION mode set all maskl bits to lf set all mask2 bits to CANSetMask CAN MASK 1 1 CAN CONFIG XTD MSG ones CANSetMask CAN MASK 2 1 CAN CONFIG XTD MSG ones CANSetFilter CAN FIL
499. s a minimum number of printed 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 out put value exceeds the specified width all characters are output The precision field is a non negative number that specifies the number of char acters to print number of significant digits or number of decimal places The pre cision field can cause truncation or rounding of the output value in the case of a floating point number as specified in the following table MeaningMeaning of the precision field he precision field is where you specify the minimum number of digits that will be included in the output value Digits are not trun cated 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 he precision field is where you specify the number of digits to he right of the decimal point The last digit is rounded he precision field is where you specify the number of digits to he right of the decimal point The last digit is rounded ES _ he precision field is where you specify the maximum number of significant digits in the output valu
500. s 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 70 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikroC PRO for PIC Environment Examples count r 8 matches strings like counter countelkjdflkj9r and countr count 4r matches strings like counter countelkjdflkj9r but countr count r matches strings like counter countar and countr but not countelkj9r counte 2 r matches string counteer counte 2 x matches strings like counteer counteeer counteeer counte 2 3 r matches strings like counteer 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 b 2 3Y 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 bot in the target string as would b The first alternative includes everything from the last pat tern delimiter or the beginning o
501. s for duty ratio be calculated as Percent 255 100 MCU must have CCP module PWM 1 Init must be called before using this routine Set duty ratio to 75 PWM1 Set Duty 192 PWMA Start Prototype MCU must have CCP module PWM 1 Init must be called before using this routine Example startO PWMA Stop MCU must have CCP module PWM1 Init must be called before using this rou tine PWM1 Start should be called before using this routine otherwise it will have no effect as the PWM module is not running MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 407 7 Libraries Library Example mikroC PRO for PIC The example changes PWM duty ratio on RC1 and RC2 pins continually If LED is connected to these pins you can observe the gradual change of emitted light unsigned short current duty old duty current dutyl old dutyl void InitMain ANSEL Configure pins as digital I O ANSELH 0 PORTA 255 TRISA 255 configure PORTA pins as input PORTB 0 set PORTB to 0 TRISE 03 designate PORTB pins as output PORTC 0 set PORTC to 0 TRISC 0 designate PORTC pins as output PWM1 Init 5000 Initialize PWM1 module at 5KHz PWM2 Init 5000 Initialize PWM2 module at 5KHz void main InitMain current duty 16 initial value for current_duty current dutyl 16 initial value for current dut
502. sable cursor blinking Parameters Description Requires n on off parameter Valid values 0 disable cursor blinking and 1 enable cursor blinking Toshiba Glcd module needs to be initialized See the T6963C init routine enable cursor blinking T6963C cursor blink 1 Library Example The following drawing demo tests advanced routines of the T6963C Glcd library Hardware con figurations in this example are made for the T6963C 240x128 display EasyPIC5 board and 16F887 include T6963C h T6963C module connections char sbit sbit sbit sbit sbit sbit sbit sbit T6963C dataPort at PORTD T696030 at RC2 T6963C ctrlrd RCI Dit T6963C at RCO bib To963C ctrlrst at RC4 bit T6963C ctrlwr Direction at T6963C ctrlrd Direction T6963C ctrlocd Direction at TO963C Gtrlrst Direction at 2 Signals not used by library sbit sbit sbit sbit sbit sbit 546 T6963C trice at bit T6963C ctrlfs at RCG bit T6963C ctrlmd at RC5 bit T69623 ctrloce Direction T6963C ctrltfs Direction T6963C ctrlmd Direction at at at End T6963C module connections TRISC2 bit bit TRISCO bit TRISC4 bit they are set in main B E TRISC3 bit URISC6 bit 5 5 bit DATA port WR write signal RD read signal CD command data signal RST reset signal WR write signal RD read signal C
503. seripton Parameters v Value to store Ethernet module has to be initialized See Ethernet Init char data Ethernet putByte data put an byte into Ethernet controller s buffer Ethernet putBytes Prototype void Ethernet putBytes unsigned char ptr unsigned char n This is MAC module routine It stores requested number of bytes into Ethernet controller s RAM starting from current Ethernet controller s write pointer EWRPT location Description Parameters ptr RAM buffer containing bytes to be written into Ethernet controller s RAM n number of bytes to be written Requires Ethernet module has to be initialized See Ethernet Init char buffer mikroElektronika Ethernet putBytes buffer 16 put an RAM array into Ethernet controller s buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Ethernet putConstBytes void Ethernet putConstBytes const unsigned char ptr unsigned char n This is MAC module routine It stores requested number of const bytes into Eth ernet controllers RAM starting from current Ethernet controller s write pointer EWRPT location Prototype Descnption Parameters ptr const buffer containing bytes to be written into Ethernet controllers RAM n number of bytes to be written Ethernet module has to be initialized See Ethernet Init const char buffer mik
504. side values from 0 to 63 specify the left side values from 64 to 127 specify the right side Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines The following two lines are equivalent and both of them select the left side of Glcd SPI Glod Sade 0 SPI Gled Set Side 10 SPI Glcd Set Page Prototype void SPI Glcd Set Page char page Selects page of Glcd Parameters Description page page number Valid values 0 7 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 481 7 Libraries mikroC PRO for PIC SPI Glcd Set X Sets x axis position to x pos dots from the left border of Glcd within the select ed side Parameters Description x pos position on x axis Valid values 0 63 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines O Spi Glcd Read Data Returns One byte from Glcd memory T Reads data from the current location of Glcd memory and moves to the next Description location Glcd needs to be initialized fo
505. 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 191 6 Language Reference mikroC PRO for PIC Note Conversion of floating point data into 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 Details Here are the steps the mikroC PRO for PIC uses to convert the operands in an arith metic expression First any small integral types are converted according to the following rules 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 int with the same value zero filled enum converts to int with the same value 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 PIC
506. signal take Soft I2C Read 0 Soft I2C Write Prototype unsigned short Soft I2C Write unsigned short Data Description 0 if there were no errors 1 if write collision was detected on the I C bus Sends data byte via the I C bus Parameters Data data to be sent Soft 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 2 Start routine unsigned short data error error Dort Wrrte data error Soft I2C Write 0xA3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 423 7 Libraries mikroC PRO for PIC Soft I2C Stop Prototype Issues STOP signal Soft IC must be configured before using this function See Soft I2C Init routine Issue STOP signal Soft I20 Soft I2C Break All Software 12 Library functions can block the program flow see note at the top of this page Calling this routine from interrupt will unblock the program execu tion This mechanism is similar to WDT Description Note Interrupts should be disabled before using Software I2C routines again see note at the top of this page Requires Noting Software I2C connections sbit Sort 120 Scl at RCO bur sbit Soft I2C Sda at RCl bit Sbit Soft I2C Sol Direction at TRISCO bit sbit Soft I2C Sda Direction at TRISCI bit End Software I2C connections cha
507. ss loop Man Send 0x0B Send start byte Delay ms 100 Wait for a while eharaetee 0 Take first char from string index 0 Initialize index variable while character String ends with zero Man Send character Send character Delay ms 90 Wait for a while Increment index variable character index Take next char from string 0 0 Send end byte Delay ms 1000 366 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Connection Example Transmitter RF module Antenna y O VCC 1l PSSCRLATOR VCC O vcc o c9 vec NEUES lt RT4 mn GND Simple Transmitter connection Receiver Antenna N 4 GND OSCILLATOR o vec iF RR4 ow y GND Simple Receiver connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 367 7 Libraries mikroC PRO for PIC MULTI MEDIA CARD LIBRARY The Multi Media Card MMC is a flash memory card standard MMC cards are cur rently available in sizes up to and including 1 GB and are used in cell phones mp3 players digital cameras and PDAs mikroC PRO for PIC provides a library for accessing data on Multi Media Card via SPI communication This library also supports SD Secure Digita
508. stants 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 dec laration Negative initializers are allowed See Enumerations for details about enum declarations MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 153 6 Language Reference mikroC PRO for PIC 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 int 15 i is an int Int pis 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 amp cpc is a constant pointer to a constant int The following assignments are legal i ci i Assign Constant to int Assign const int to object pointed at by a const pointer Increment a pointer to const Assign a const pointer to a const to a pointer to const The following assignments are illegal ei e NO cannot assign to a const int pies NO cannot change a const int pci 3 NO cannot assign to an object
509. 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 b But c and d are not of the same type although their structure descriptions are identical struct int mi o struct int ml d Size of Structure The size of the structure in 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 1 returns a structure mystruct func2 void func2 returns pointer to structure A structure can be passed as an argument to a function in the following ways void funci mystruct 5 directly void func2 mystruct sptr via a pointer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 185 6 Language Reference mikroC PRO for PIC Structure Member Access Structure and union members are accessed using the following two selection oper ators period right arrow The operator is called the direct member selector and it is used to directly access one of the structure s members Sup
510. t Find next occurence of text in active editor 2 Find Previous Shift F3 Find previous occurence of text in active editor Replace CtrltR Replace text in active editor Find In Files AkiF3 Find text in current file in all opened files or in files from desired folder Goto Line Ctrl G Goto to the desired line in active editor Advanced Code Editor options MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 15 2 Environment mikroC PRO for PIC Advanced Description Comment selected code or put single line com ment if there is no selection Uncomment selected code or remove single line Uncomment _ Shift Ctri comment if there is no selection Indent Shift Ctrl I Indent selected code 5 Outdent Shift Ctrl U Outdent selected code owercase Changes selected text case to lowercase 1 Comment Shift Ctrl4 aA Uppercase Changes selected text case to uppercase C lad Titlecase Ctr AlE T Changes selected text case to titlercase Find Text Dialog box for searching the document for the specified text The search is per formed in the direction specified If the string is not found a message is displayed Search for init Options Direction Case sensitivity Forward Whole words only 16 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS
511. t 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 inte gers they have their own rules and restrictions for declarations assignments con versions and arithmetic The examples in the next few sections illustrate these rules and restrictions MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 175 6 Language Reference mikroC PRO for PIC Pointer Declarations Pointers are declared the same as any other variable but with gt ahead of identifier A type at the beginning of declaration specifies the type of a pointed object A point er must be declared as pointing to some particular type even if that type is 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 PIC 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 All scoping duration and visibility rules are applied to the object just declared You can view the declaration in this way if 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 point er p
512. t day unsigned short hours unsigned short mins Nothing Reads time date attributes of currently assigned file Parameters year buffer to store year attribute to Upon function execution year attribute is returned through this parameter month buffer to store month attribute to Upon function execution month Description 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 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 Set File Size Returns Size of the currently assigned file in bytes This function reads size of currently assigned file in bytes Reauires CF card and CF library must be initialized for file operations See Cf Fat Init 4 File must be previously assigned See Cf Fat Assign unsigned long my file size my file size Fat File Srze 286 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED W
513. t Init unsigned char dnsIpAddr 4 user DNS IP address buffer iene donde Ethernet getDnsIpAddress 4 fetch DNS server address MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 307 7 Libraries mikroC PRO for PIC Ethernet getlpMask Prototype Returns Ponter to the global variable holding IP subnet mask This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask Description Note 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 Ethernet module has to be initialized See Ethernet Init unsigned char IpMask 4 user IP subnet mask buffer memcpy IpMask Ethernet getlIpMask 4 fetch IP subnet mask Ethernet confNetwork void Ethernet confNetwork char ipMask char gwIpAddr char dnsIpAddr Nothing Configures network parameters IP subnet mask gateway IP address DNS IP address when DHCP is not used Parameters Description ipMask IP subnet mask gwlpAddr gateway IP address dnsIpAddr DNS IP address Note The above mentioned network parameters should be set by this routine only if DHCP module is not used Otherwise DHCP will override these settings Ethernet module has to be initialized See Ethernet Init unsigned char ipMask 4
514. t SPExpanderCS at bit sbit SPExpanderRST Direction at TRISCO bit SPExpanderCS Direction at TRISC1 bit End Port Expander module connections Port Expander Library uses SPI module Ipit Initialize SPI module used with PortExpander SPI Lcd8 Config 0 intialize Lcd in 8bit mode via SPI Spi Lcd8 Out void SPI Lcd8 Out unsigned short row unsigned short column char text Prints text on LCD starting from specified position Both string variables and lit erals can be passed as a text Prototype m Parameters Description row Starting position row number column Starting position column number text text to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Write text Hello on Lcd starting from row 1 column 3 SPI Leds Outil 3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 501 7 Libraries mikroC PRO for PIC Spi Lcd8 Out Cp Prototype void SPI Lcd8 Chr CP char out char Prints character on Lcd at current cursor position Both variables and literals can be passed as character Description Parameters text text to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Write text Here at current cursor position SPI Leds Out Cp Herel Spi Lcd8 Chr void SPI Lcd8 Chr unsig
515. t UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength unsigned int len my reply length reply is made of the remote host IP address in human read able format ByteToStr remoteHost 0 dyna first IP address byte dyna 3 ByteToStr remoteHost 1 dyna 4 second dynal 7 27 ByteToStr remoteHost 2 dyna 8 77 third dyna 11 ByteToStr remoteHost 3 dyna 12 If ourth dyna 15 te add separator then remote host port number WordToStr remotePort dyna 16 7 mikroC PRO for PIC Libraries dyna 21 WordToStr destPort dyna 22 dyna 27 dyna 28 0 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 Ethernet putBytes dyna 28 then puts the request string converted into upper char into the transmit buffer while reqLength Ethernet putByte toupper Ethernet getByte return len back to the library with the length of the UDP reply main entry void main ADCON1 0x0B ADC convertors will be used with AN2 AN3 CMCON 0x07 turn off comparators PORTA 0 TRISA Oxfc set PORTA as input for ADC except RAO RA1 which will be used as ethernet s LEDA and LEDB
516. t and graph ic data shown on display are combined via the logical AND function TEXT 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 module needs to be initialized See the T6963C init routine 536 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries T6963C write text void T6963C write text unsigned char unsigned char x Prototype 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 node mode parameter Valid values 6963 ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation Description 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
517. t file mcppi Output files are summarized in the table below Intel style hex records Use this file to program Intel HEX PIC MCU Binar mikro Compiled Library Binary distribution of y application that can be included in other projects hex Overview of PIC memory allotment instruction List File sist addresses registers routines and labels Human readable assembly with symbolic names Assembler File asm extracted from the List File Assembly View After compiling the program in the mikroC PRO for PIC you can click the View Assembly icon or select Project View Assembly from the drop down menu to review the generated assembly code asm file in a new tab window Assembly is human readable with symbolic names Related topics Project Menu Project Toolbar Error Window Project Manager Pro ject Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 87 2 Environment mikroC PRO for PIC ERROR MESSAGES Compiler Error Messages Syntax error Expected s but s found Array element cannot be function Function cannot return array Inconsistent storage class Inconsistent type s tag redefined 251 Illegal typecast 5 125 55 is not valid identifier Invalid statement Constant expression required Internal error gt s Too many actual parameters Not enough parameters Invalid expression Identifier expect
518. t the moment the modifier register technically has no special meaning mikroC PRO for PIC compiler simply ignores requests for register allocation Static A global name declared with the static specifier has internal linkage meaning that it is local for a given file See Linkage for more information Alocal name declared with the static specifier has static duration Use static with a local variable to preserve the last value between successive calls to that function See Duration for more information Extern A name declared with the extern specifier has external linkage unless it has been previously declared as having internal linkage A declaration is not a definition if it has the extern specifier and is not initialized The keyword extern is optional for a function prototype Use the extern modifier to indicate that the actual storage and initial value of the variable or body of the function is defined in a separate source code module Func tions declared with extern are visible throughout all source files in the program unless the function is redefined as static See Linkage for more information Type Qualifiers The type qualifiers const and volatile are optional in declarations and do not actually affect the type of declared object Qualifiers Const The qualifier const implies that a declared object will not change its value during runtime In declarations with the const qualifier all objects need to be initialized
519. tart the upload just click on the Start Bootloader button Your program will written to the PIC flash Bootloader will report an errors that may occur 9 Reset your PIC and start to execute 9 mikroElektronika mikroBootloader v1 0 0 2 3 History Window Setup Port Connect Open HEX file Start bootloader Terminal Window Connect Tx Rx C Program FilessMikroelektronika mikroC PRO for PICXE xamplessDevelopment Systems E asyPICBALc MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 63 2 Environment mikroC PRO for PIC Features The boot code gives the computer 5 seconds to get connected to it If not it starts running the existing user code If there is a new user code to be downloaded the boot code receives and writes the data into program memory The more common features a bootloader may have are listed below Code at the Reset location Code elsewhere in a small area of memory Checks to see if the user wants new user code to be loaded Starts execution of the user code if no new user code is to be loaded Receives new user code via a communication channel if code is to be loaded Programs the new user code into memory Integrating User Code and Boot Code The boot code almost always uses the Reset location and some additional program memory It is a simple piece of code that does not need to use interrupts therefore
520. te 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 amp CANSPI CONFIG XTD MSG 262 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries CANSPISetFilter void CANSPISetFilter char CANSPI FILTER long val char CANSPI CONFIG FLAGS Nothing Configures message filter The parameter value is bit adjusted to the appropri ate filter registers Parameters FILTER CANSPI module filter number Valid values CANSPI FILTE constants see CANSPI constants Description va1 filter register value CONFIG FLAGS Selects type of message to filter Valid values CANSPI CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG STD MSG CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG XTD MSG see CANSPI constants 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 modul
521. ted into upper char into the transmit buffer while reqLength SPI Ethernet putByte toupper SPI Ethernet getByte return len back to the library with the length of the UDP reply main entry void main ANSEL 0 0 AN2 and AN3 convertors will be used PORTA 0 TRISSA Dwff set PORTA as input for ADC ANSELH 0 Configure other AN pins as digital I O PORTB 0 TRISB Oxff set PORTB as input for buttons PORTD 0 TRISD Oy set PORTD as output 476 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries starts ENC28J60 with reset bit on RCO Cs DLE REL my MAC amp IP address full duplex Ey SPIT Pave SPI Ethernet Init myMacAddr myIpAddr Spi Ethernet FULLDU X PLEX while 1 do forever if necessary test the return value to get error code SPI Ethernet 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 477 7 Libraries mikroC PRO for PIC HW Connection 148849514
522. ted value in the edit boxes You can launch it from the drop down menu Tools 7 Segment Convertor or by clicking the Seven Segment Convertor Icon Ei from Tools toolbar Common cathode 0x71 Common anode _0 8 LCD Custom Character mikroC PRO for PIC includes the Lcd Custom Character Output is mikroC PRO for PIC compatible code You can launch it from the drop down menu Tools Lcd Cus tom Character P 8 5 10 Save Load Fill all Clear all Invert Font Preview C 5 10 cursor line A B CGRAM address Char 0 0 EI Char data row GENERATE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 59 2 Environment mikroC PRO for PIC Graphic LCD Bitmap Editor The mikroC PRO for PIC includes the Graphic Lcd Bitmap Editor Output is the mikroC PRO for PIC compatible code You can launch it from the drop down menu Tools Glcd Bitmap Editor ronika Graphic LCD Bitmap generator 53 T6963 Nokia3110 Load BMP Picture 3 ATE e File loaded truck bmp 022 25 237 Picture preview 128x64 pix bw m Create CODE Invert PICTURE GLCD Size controller 77 GLCD Picture name truck bmp GLCD Model KS81808 128x64 te eal array 18241 of byte lt B 0 248 8 8 8 8 8 12 12 12 12
523. ter 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 UART HW module must be initialized and communication established before using this function See UART1_ Init Read text until the sequence OK is received and send back what s been received 1 Init 4800 initialize UART1 module Delay ms 100 while 1 if UART1 Data Ready 1 if data is received UART1 Read Text output delim 10 reads text until delim is found UART1 Write Text output sends back text UART1 Write Prototype Description void UART1 Write char data Nothing The function transmits a byte via the UART module Parameters data data to be sent UART HW module must be initialized and communication established before using this function See UARTI1 Init unsigned char data VARTI Write data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Libraries 555 7 Libraries mikroC PRO for PIC 556 UART4 Write Text Prototype void UART1 Write Text char UART text Sends text parameter text via UART Text should be zero terminated UART HW module must be initialized and communication established before using this function See UARTI1 Init Read text until the sequence OK is received and send b
524. th the putConstString def inition above the define line below should be commented out idi define putConstString SPI Ethernet putConstString put the string pointed to by s to the ENC transmit buffer ay unsigned int purstring char unsigned int ctr 0 while Spi Ethernet putByte sti CEPUE return ctr 472 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries it will be much faster to use library Spi Ethernet putString rou tine instead of putString routine above However the code will be a pit bigger User should choose between size and speed and pick the implementation that suites him best If you choose to go with the putString defini tion above the define line below should be commented out define putString SPI Ethernet putString 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 unsigned int SPI Ethernet UserTCP unsigned char remoteHost unsi
525. that the evaluation of consec utive logical operands stops at the very moment the final result is known For exam ple if we an expression ss b lt 5 c where a is false 0 then operands b and c will not be evaluated This is very important if and c are expressions as their possible side effects will not take place Logical versus Bitwise Be aware of the principle difference between how bitwise and logical operators work For example 0222222 0555555 equals 000000 0222222 amp amp 0555555 equals 1 0x1234 equals OxEDCB 0x1234 equals 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 215 6 Language Reference mikroC PRO for PIC Conditional Operator The conditional operator is the only ternary operator in C Syntax of the condi tional operator is expressionl expression2 expression3 The expressioni is evaluated first If its value is true then expression2 evaluates and expression3 ignored If expression1 evaluates to false then expression3 evaluates and expression is ignored The result will be a value of either expres sion2 Of expression3 depending upon which of them evaluates Note The fact that only one of these two expressions evaluates is very important if they are expected to produce side effects Conditional operator associates from right to left Here are a couple of practical examples Find b
526. the result If copying takes place between objects that overlap the behavior is unde fined to string must have enough space to store the result The function returns address of the object pointed to by to char strchr char ptr char chr Function locates the first occurrence of character chr in the string ptr The func tion 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 int strcmp char sl char 2 Function compares strings si and s2 and returns zero if the strings are equal or returns a difference between the first differing characters in a left to right evalu ation Accordingly the result is greater than zero if s1 is greater than s2 and vice versa char strcpy char to char from 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 ve Function returns the length of the string s the terminating null character does not count against string s length MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Libraries 577 7 Libraries mikroC PRO for PIC strncat Prototype char strncat char to char from int size Function appends not more than size characters from the string from to to The
527. the Read Write signal pin LCD EN Direction Direction of the Enable signal pin LCD RST Direction Direction of the Reset signal pin LCD DataPort at PORTD LCD CS1 at RBO bit LCD CS2 at 1 bit LCD RS at RB2 bit LCD RW at RB3 bit glcd pinout settings char Gl sbit Gl sbit Gl sbit Gl sbit Gl sbit j 1 sbit GLCD sbit Gl sbit Gl sbit Gl ELH Glcd Init CD EN at RB4 bit LCD RST at RB5 bit LCD CS1 Direction at TRISBO bit LCD CS2 Direction at TRISBI bit LED RS Direction at TRISB2 bit LCD RW Direction at TRISB3 bit LCD EN Direction at TRISB4 bit D RST Direction at TRISB5 bit 0 0 328 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Glcd Set Side Prototype void Glcd Set Side unsigned short x pos Selects Glcd side Refer to the Glcd datasheet for detailed explaination Parameters x pos position on x axis Valid values 0 127 Description 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 Note For side x axis and page layout explanation see schematic at the bottom of this page 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 Glcd Select Side 0 Gled Select Side 10 Glcd Set X Prototype void G
528. 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 V For instance metacharacter matches beginning of string but 1 matches character and WV matches etc Examples unsigned matches string unsigned M unsigned matches string unsigned Escape sequences Characters may be specified using a escape sequences in matches a newline M a tab etc More generally nn 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 char with hex code nn x nnnn char with hex code nnnn one byte for plain text and two bytes for Unicode t tab HT TAB same as x09 in newline NL same as x0a r car return CR same as x0d f form feed FF same as 0 a alarm bell BEL same as x07 e escape ESC same as x1b MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 67 2 Environment mikroC PRO for PIC 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 th
529. thernet Disable Ethernet Ethernet UNICAST disable CRC checking and Unicast traffic Ethernet doPacket Prototype unsigned char Ethernet doPacket 0 upon successful packet processing zero packets received or received packet processed successfuly 1 upon reception error or receive buffer corruption Ethernet 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 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 Ethernet UserTCP function is called for further processing upon UDP request the Ethemet UserUDP function is called for further processing Description Note Ethernet doPacket must be called as often as possible in user s code Requires Ethernet module has to be initialized See Ethernet Init Ethernet doPacket 0 process received packets MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 301 7 Libraries mikroC PRO for PIC 302 Ethernet putByte Prototype void Ethernet putByte unsigned char v This is MAC module routine It stores one byte to address pointed by the cur rent Ethernet controller s write pointer EWRPT De
530. thernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength 0 there should not be a reply to the request Length of TCP HTTP reply data field otherwise This is TCP module routine It is internally called by the library The user access es to the TCP HTTP request by using some of the Ethernet get routines The user puts data in the transmit buffer by using some of the Ethernet put routines The function must return the length in bytes of the TCP HTTP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP HTTP requests just define this function with return 0 as a single statement Description Parameters remoteHost client s IP address remotePort client s TCP port localPort port to which the request is sent regLength TCP HTTP request data field length Note The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply Ethernet module has to be initialized See Ethernet Init This function is internally called by the library and should not be called by the user s code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 305 7 Libraries mikroC PRO for PIC Ethernet UserUDP unsigned int Ethernet UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength 0 there s
531. these field types precision field is where you specify the maximum number of characters in the output value Excess characters are not output 598 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries The optional characters 1 or L may immediately precede conversion type to respectively specify long versions of the integer types i u o x and x Description 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 sprintl char wh const char 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 sprinti char wh const char f sd char sprinti char wh const char f sd const char f Returns The function returns the number of Jude actually written to destination string The same as sprintf except it doesn t support long integers and float type num bers Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 599 7 Libraries mikroC PRO for PIC Library Example This is a demonstration of the standard C library sprintf routine usage Three differ ent representations of the same floating poing number obtained by using the sprintf routine
532. though 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 vari ables must be defined S Description in all projects using PS 2 Library extern sfr sbit sbit PS2 Data at extern sfr sbit sbit PS2 Clock at PS2 Clock 5 2 Clock line bit extern sfr sbit sbit PS2 Data Direction PS2 Data Direction Direction of the PS 2 Data at TRISCO bit extern sfr sbit sbit PS2 Clock Direction PS2 Clock Direction Direction of the PS 2 Clock pin at TRISCI bit Library Routines Ps2 Config Ps2 Key Read 400 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Ps2 Config Initializes the MCU for work with the PS 2 keyboard Global variables PS2 Data Data signal line R dq ires PS2 Clock Clock signal line in 4 PS2 Data Direction Direction of the Data pin PS2 Clock Direction Direction of the Clock pin must be defined before using this function sbit PS2 Data at RCO bit shit PS2 Clock at bit sbit PS2 Data Direction at TRISCO bit sbit PS2 Clock Direction at TRISC1 bit Ps2 Contig Init PS 2 Keyboard MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 401 7 Libraries mikroC PRO for PIC
533. tic at the bottom of this page Data data to be written to the PortB direction register Each bit corresponds to the appropriate pin of the PortB register Set bit configures the correspon ding pin as an input Cleared bit configures the corresponding pin as an output Port Expander must be initialized See Expander Init Example Set Port Expander s PORTB to be input Expander Set DirectionPortB 0 0xFF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 395 CHAPTER 7 Libraries mikroC PRO for PIC Expander Set DirectionPortAB Description Requires void Expander Set DirectionPortAB char ModuleAddress unsigned int Direction Nothing The function sets Port Expander s PortA and PortB direction Parameters ModuleAddress 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 Direction s higher byte Data to be written to the PortB direction register are passed Di rect ion s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit configures the corresponding pin as an input Cleared bit configures the corre sponding pin as an 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
534. tic 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 pro gram Each instance of a particular identifier with internal linkage represents the same object or function within one file only 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 195 6 Language Reference mikroC PRO for PIC 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 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 dec laration No more than one external definition can be given for each identifier in a translation unit
535. tine Draw a vertical line between dots 10 5 and 10 25 Gled V Line 5 25 10 1 Glcd H Line void Glcd H Line unsigned short x start unsigned short x end unsigned short y pos unsigned short color Nothing Draws a horizontal line on Glcd Parameters x start X coordinate of the line start Valid values 0 127 Description 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 Requires Glcd needs to be initialized see Glcd Init routine Draw a horizontal line between dots 10 20 and 50 20 Glcd Line 10 50 20 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 333 7 Libraries mikroC PRO for PIC 334 Glcd Rectangle void Glcd Rectangle unsigned short x upper left unsigned short y upper left unsigned short x bottom right unsigned short y bottom right unsigned short color 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 Description values 0 127 y bottom right y coordinate of the lower right rectangle corner
536. tines Ethernet getlpAddress fetch IP address Ethernet getGwlpAddress fetch gateway IP address Ethernet getDnslpAddress fetch DNS IP address Ethernet getlpMask fetch IP subnet mask Description UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP serv er port Parameters time in seconds to wait for an reply Note The Ethernet services are not stopped while this routine waits for DNS reply The incoming packets will be processed normaly during this time Note When DHCP module is used global library variable Ethernet userTimerSec Is used to keep track of time It is user responsibility to increment this variable each second in it s code Ethernet module has to be initialized See Ethernet Init Ethernet initDHCP 5 get network configuration from DHCP server wait 5 sec for the response MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 311 7 Libraries mikroC PRO for PIC 312 Ethernet doDHCPLeaseTime Prototype unsigned char Ethernet doDHCPLeaseTime 0 lease time has not expired yet 1 lease time has expired it s time to renew it This is DHCP module routine It takes care of IP address lease time by decre Description menting the global lease time library counter When this time expires it s time to contact DHCP server and renew the lease Ethernet module has to be initialized See Ethernet Init while 1
537. tines SPI Lcd Config SPI Lcd Out SPI Lcd Out Cp SPI Lcd Chr SPI Lcd Chr Cp SPI Lcd Cmd MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 493 CHAPTER 7 Libraries mikroC PRO for PIC Spi Lcd Config Prototype void SPI Lcd Config char DeviceAddress Description Initializes the LCD module via SPI interface Parameters DeviceAddress Spi expander hardware address see schematic at the bottom of this page 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 SPI1 Init and SPI1 Init Advanced routines Port Expander module connections sbit SPExpanderRST at RCO bit sbit SPExpanderCS at RCI bit Sbit SPExpanderRST Direction at TRISCO bit SPExpanderCS Direction at 5 bit End Port Expander module connections void main If Port Expander Library uses SPI module Init Initialize SPI module used with PortExpander SPI Led Config 0 initialize Led over SPI interface 494 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Spi Lcd Out Prototype void SPI Lcd Out char row char column char text Prints text on the L
538. tines are supported only by MCUs with the SPI module The SPI module needs to be initialized See the 5 1 Init and SPI1 Init Advanced routines MCU has to be properly connected to mikroElektronikas CANSPI Extra Board or sim ilar hardware See connection example at the bottom of this page MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 259 7 Libraries mikroC PRO for PIC CANSPI module connections sbit CanSpi CS at RCO bit sbit CanSpi CS Direction at TRISCO bit sbit CanSpi at RC2 bit sbit CanSpi Rst Direction at TRISC2 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 27 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 SETI initialize SPI module CANSPIInitialize 1 3 3 3 1 CanSpi Init Flags initialize external CANSPI module 260 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries CANSPISetBaudRate Description void CANSPISetBaudRate char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CANSPI CONFIG FLAGS Nothing
539. tion 2 direction at TRISB2 bit extern sfr sbit Direction of the Address 1 sbit CF A1 direction CF AI direction pin at bit extern sfr sbit Direction of the Address 0 sbit CF A0 direction CF A0 direction pin at TRISBO bit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries 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 Size Cf Fat Get Swap File The following routine is for the internal use by compiler only Cf Issue ID Command MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 275 7 Libraries mikroC PRO for PIC Cf Init Prototype Initializes ports appropriately for communication with CF card Global variables CF Data Port Compact Flash data port cr Ready signal line CF WE Write enable signal line CF OE Output enable signal line CF CD1 Chip detect signal line Enable signal line CF A2 Address 2 CF A1 Address pin 1 Requires CF ao Address 0 CF RDY di
540. tion 448 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SPI ETHERNET LIBRARY The 28760 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 enc28760 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 calcula tions 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 lt 28 760 It works with any PIC 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 PIC should be clocked by 28 760 clock output due to its silicon bug in SPI hardware If you try lower PIC clock speed there 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
541. tion as their argument const char CANSPI CONFIG DEFAULT CANSPI CONFIG PHSEG2 PRG BIT CANSPI CONFIG PHSEG2 PRG ON CANSPI CONFIG PHSEG2 PRG OFF CANSPI CONFIG LINE FILTER BIT CANSPI CONFIG LINE FILTER ON CANSPI CONFIG LINE FILTER OFF CANSPI CONFIG SAMPLE BIT CANSPI CONFIG SAMPLE ONCE CANSPI CONFIG SAMPLE THRICE CANSPI CONFIG MSG TYPE BIT CANSPI CONFIG STD MSG CANSPI CONFIG XTD MSG OxFF 0x01 OxFF OxFE 03025 OxFF OxFD 0x04 OxEF OxFB 0x08 OxFF OxF7 yy 1IL XXXXxXXX0 PF XXXXXXOX JJ QXXXXTXX JI XxEXXXXOXX LE ff XXXXOXXX MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 7 Libraries CANSPI CONFIG DBL BUFFER BIT 9x10 CANSPI CONFIG DBL BUFFER ON OxFF XXX1XXXX CANSPI CONFIG DBL BUFFER OFF OxEF XXX XXXX CANSPI CONFIG MSG BITS 0x60 CANSPI CONFIG ALL MSG OxFF XILIXXXXX CANSPI CONFIG VALID XTD MSG OxDF ft XXX CANSPI CONFIG VALID STD MSG OxBF Jf X IlXXXXX CANSPI CONFIG ALL VALID MSG Ox9F XOOXXXXX You may use bitwise AND amp to form config byte out of these values For example mud CANSPI CONFIG SAMPLE THRIC i amp CANSPI CONFIG CANSPI CONFIG ST
542. tion returns an unchanged input parameter Description 566 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries ANSI C Math Library The mikroC PRO for PIC provides a set of standard ANSI C library functions for floating point math handling Note Not all of the standard functions have been included Note The functions have been mostly implemented according to the ANSI C stan dard but certain functions have been modified in order to facilitate PIC program ming Be sure to skim through the description before using standard C functions Library Functions acos asin atan atan2 ceil COS cosh eval_poly exp fabs floor frexp log log10 modf pow sin sinh sqrt tan tanh MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 567 7 Libraries mikroC PRO for PIC acos Prototype double acos double x Function returns the arc cosine of parameter that is the value whose cosine Description is gt The input parameter must be between 1 and 1 inclusive The return value is in radians between 0 and 1 inclusive asin Prototype double asin double x Function returns the arc sine of parameter x that is the value whose sine is Description The input parameter must be between 1 and 1 inclusive The return value is in radians between
543. to be called before using other functions of this library 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 sfr sbit Mmc Chip Select at RC2 bit sfr sbit Mmc Chip Select Direction at TRISC2 bit MMC module connections error Mme Init Init with CS line at RC2 bit Mmc Read Sector Prototype unsigned char Mmc Read Sector unsigned long sector char dbuff Returns Returns 0 if read was successful or 1 if an error occurred Function reads one sector 512 bytes from MMC card at sector address sector Description Read data is stored in the array data Function returns 0 if read was successful or 1 if an error occurred rror Mmc Read Sector sector data Requires Library needs to be initialized see Mmc Init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Mmc Write Sector Prototype unsigned char Mmc Write Sector unsigned long sector char dbuff Returns 0 if write was successful returns 1 if there was an error in sending write command returns 2 if there was an error in writing Function writes 512 bytes of data to MMC card at sector address sector Description Function returns 0 if write was successful or 1 if there was an error in sending write command or 2 if there w
544. to z and A to Z underscore character and digits O to 9 The only restriction is that the first character must be a letter or an underscore Case Sensitivity The mikroC PRO for PIC identifiers aren t case sensitive by default so that Sum sum and sum represent an equivalent identifier Case sensitivity can be activated or sus pended in Output Settings window Even if case sensitivity is turned off Keywords remain case sensitive and they must be written in lower case 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 Identifier Examples Here are some valid identifiers temperature V1 Pressure no hit dat2string SUM3 _vtext and here are some invalid identifiers 7 NO cannot begin with a numeral Shigher NO cannot contain special characters ipte NO cannot match reserved word j23 07 04 NO cannot contain special characters dot MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 157 6 Language Reference mikroC PRO for PIC PUNCTUATORS The mikroC PRO for PIC punctuators also known as separators are Brackets Parentheses
545. tor Operator is used for token pasting Two tokens can be pasted merged together by placing 2 in between them plus optional whitespace on either side The pre processor 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 5 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 239 6 Language Reference mikroC PRO for PIC Note The mikroC PRO for PIC does not support the older nonportable method of token pasting using 1 r 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 PIC 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 else and endif The conditional directives if elif else and endif work very similar to the common C conditional statements If the expression you write after 1 has nonzero value the line group immediately following the i directive is retained in
546. tors Precedence and Associativity Arithmetic Operators Relational Operators Bitwise Operators Logical Opeartors Conditional Operators Assignment Operators 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 Jump Statements Break and Continue Statements Goto Statement Return Statement Compound Statements Blocks MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 141 6 Language Reference mikroC PRO for PIC Preprocessor Introduction to Preprocessor Preprocessor Directives Macros File Inclusion Preprocessor Operators Conditional Compilation 142 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference LEXICAL ELEMENTS OVERVIEW The following topics provide a formal definition of the mikroC PRO for PIC lexical elements They describe different categories of word like units tokens recognized by the mikroC PRO for PIC In the tokenizing phase of compilation the source code file is parsed that is bro ken down into tokens and whitespace The tokens in the mikroC PRO for PIC are derived from a series of operations performed on your programs by the compiler and its built in preprocessor
547. tring Requires Destination string should be at least 5 characters in length short t char txt 5 ShortToStrt b txt txt 24 one blank here MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 583 7 Libraries mikroC PRO for PIC WordToStr Prototype void WordToStr unsigned input char output 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 Deseripuon Parameters input word to be converted output destination string Destination string should be at least 6 characters in length unsigned t 437 char txt 6 WordToStr t txt j Jf ie 437 two blanks here IntToStr Prototype void IntToStr int input char output Converts input 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 Description Parameters input Signed integer number to be converted output destination string Requires Destination string should be at least 7 characters in length int j 4220 char txt 7 IntToStr j txt txt is 4220 one blank here 58
548. tton by its name ID assembly variable name Simply type name ID of they variable register you want to display into Search the variable by assemby name box and click the Add Button E MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 93 CHAPTER 2 Environment mikroC PRO for PIC Variables can also be removed from the Watch window just select the variable that you want to remove and then click the Remove Button Remove Add All Button Add all adds all variables Remove All Button Remove All removes all variables You can also expand collapse complex variables i e struct type variables strings Values are updated as you go through the simulation Recently changed items are colored red 159 Bi Ex Select variable from list FARG T6963C circles Peripherals Freeze Advance Breakpoints T6963C cntlrst T6963C grWidth 0 0009 Cycle 560 00 Double clicking a variable or clicking the Properties Button Properties 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 94 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 2 mikr
549. ual to number of Hardware break points and it depends on used MCU MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 mikroC PRO for PIC mikrolCD Program Memory Break Program Memory Break is used to set the Advanced Breakpoint to the specific address in program memory Because of PIC pipelining mechanism program exe cution may stop one or two instructions after the address entered in the Address field Value entered in the Address field must be in hex format Note Program Memory Break can use the Passcount option The program execu tion will stop when the specified program address is reached for the N th time where N is the number entered in the Passcount field When some Advanced Breakpoint stops the program execution passcount counters for all Advanced Breakpoints will be cleared Program Memory Break Program Memory Break is used to set the Advanced Breakpoint to the specific address in program memory Because of PIC pipelining mechanism program exe cution may stop one or two instructions after the address entered in the Address field Value entered in the Address field must be in hex format Note Program Memory Break can use the Passcount option The program execu tion will stop when the specified program address is reached for the N th time where N is the number entered in the Passcount field When some Advanced Breakpoint stops the program execution passcount counters for all Advanced
550. uctures and unions For more information on derived types refer to the topic Derived Types MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 167 6 Language Reference mikroC PRO for PIC Fundamental Types The fudamental types represent types that cannot be divided into more basic ele ments and are the model for representing elementary data on machine level The fudamental types are sometimes referred to as unstructured types and are used as elements in creating more complex derived or user defined types 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 In the 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
551. uence 364 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries if error Exit so we do not loop forever break do temp Man Receive amp error Attempt byte receive if error 1 If error occured Led Che CP PT Write question mark on LCD ErrorCount tt Update error counter if ErrorCount 20 In case of multiple errors temp Man Synchro Try to synchronize again Man Receive Init Alternative try to Initialize Receiver again ErrorCount 0 Reset error counter else No error occured if temp OxOE If End byte was received see Transmitter example Lcd Chr temp do not write received byte on LCD Delay ms 25 while temp 0x0E If End byte was received exit do loop MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 365 7 Libraries mikroC PRO for PIC The following code is code for the Manchester transmitter it shows how to use the Manchester Library for transmitting data Manchester module connections sbit MANRXPIN at RCO bit sbit MANRXPIN Direction at TRISCO bit sbit MANTXPIN at ROL bit sbit MANTXPIN Direction at TRISC1 bit End Manchester module connections char index character char 51 mikroElektronika void main Man Send Init Initialize transmitter while 1 Endle
552. uence of any number of characters surrounded by double quotes UIhis Ts as tris 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 152 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference The Name is preceded by two tabs The Address is preceded by one tab The line is followed by two new lines The 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 This is o just an example is equivalent to This is just an example Line Continuation with Backslash You can also use the backslash Y as a continuation character to extend a string constant across line boundaries This is really X a one line string Enumeration Constants Enumeration constants are identifiers defined in enum type declarations The identi fiers are usually chosen as mnemonics to contribute to legibility Enumeration con stants are of int type They can be used in any expression where integer con
553. uipment in hazardous environments requir ing 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 the Software could lead directly to death personal injury or severe physical or environmental damage High Risk Activities mikroElektronika and its suppliers specifically disclaim any express or implied warranty of fitness for High Risk Activities LICENSE AGREEMENT By using the mikroC PRO for PIC compiler you agree to the terms of this agreement Only one person may use licensed version of mikroC PRO for PIC compiler at a time Copyright mikroElektronika 2003 2009 This manual covers mikroC PRO for PIC version 1 1 and the related topics Newer ver sions may contain changes without prior notice COMPILER BUG REPORTS The compiler has been carefully tested and debugged It is however not possible to guarantee a 100 error free product If you would like to report a bug please contact us at the address office mikroe com Please include next information in your bug report Your operating system Version of mikroC PRO for PIC Code sample Description of a bug CONTACT US mikroElektronika Voice 381 11 36 28 830 Fax 381 11 36 28 831 Web www mikroe com E mail office mikroe com Windows is a Registered trademark of Microsoft Corp All other trade and or
554. uisition memory displays conversions communication etc W Monitor your program structure variables and functions in the Code Explorer W Generate commented human readable assembly and standard HEX compati ble with all programmers Use the integrated mikrolCD In Circuit Debugger Real Time debugging tool to 2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC CHAPTER 1 Introduction monitor program execution on the hardware level Inspect program flow and debug executable logic with the integrated Software Simulator Get detailed reports and graphs RAM and ROM map code statistics assembly listing calling tree and more mikroC PRO for PIC 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 PIC microcontrollers read care fully the PIC Specifics chapter It might give you some useful pointers on PIC constraints code portability and good programming practices If you are experienced in C programming you will probably want to consult mikroC PRO for PIC 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 PIC Libraries If you are not very experienced in C programming don t panic
555. ule needs to be initialized See SPI T6963C Config routine Spi T6963C Sprite 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 Prototype Parameters px X coordinate of the upper left picture corner Valid values multiples of the font width Description 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 Note If and sx parameters not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width Toshiba module needs to be initialized See SPI T6963C Config routine Poe ie _T6963C_sprite 76 4 einstein 88 119 draw a sprite MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 517 7 Libraries mikroC PRO for PIC Spi T6963C set cursor Prototype void SPI T6963C set cursor unsigned char x unsigned char y Sets cursor to row x and column y Description Parameters x cursor position row number y cursor position column number Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example __ Spi T6963C clearBit Prototype void SPI T6963C clearBit char b Clears control
556. ule needs to be initialized See SPI1 Init and SPI1 Init Advanced routines Port Expander module connections sbit SPExpanderRST at RCO bit sbit SPExpanderCS at 1 bit sbit SPExpanderRST Direction at TRISCO bit SPExpanderCS Direction at TRISC1 bit End Port Expander module connections 0 Configure AN pins as digital I O ELH 0 If Port Expander Library uses SPI module Initialize SPI module used with PortExpander Expander Init 0 Initialize Port Expander MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Expander Read Byte Prototype char Expander Read Byte char ModuleAddress char RegAddress The function reads byte from Port Expander Parameters Description ModuleAddress 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 read data Expander Read Byte 0 1 Expander Write Byte void Expander Write Byte char ModuleAddress char RegAddress char Data Nothing Routine writes a byte to Port Expander Prototype Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expand
557. unsigned when used on their own mean signed int and unsigned 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 168 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference ed me Run mea 3 Lee p Floating point Types unsigned short in The types float and double together with the long double variant are consid ered to be floating point types The mikroC PRO for PIC s implementation of an ANSI Standard considers all three to be the same type Floating point in the mikroC PRO for PIC 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 169 6 Language Reference mikroC PRO for PIC Enumerations An enumeration data type is used for representing an abstract discreet set of val ues 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 comma delimited list of discreet values enumerators or enumeration constants Each enu merator is assigned a fixed integral
558. urn board status as text string t7 will toggle RDO to RD7 bit and return HTML main page all other requests return also HTML main page duplex config flags define Spi Ethernet HALFDUPLEX 0x00 half duplex define Spi Ethernet FULLDUPLEX Ox01 full duplex mE ehternet NIC pinout sfr sbit SPI Ethernet at RCO bit sfr sbit SPI Ethernet CS at bit sfr sbit SPI Ethernet Rst Direction at TRISCO bit sfr sbit SPI Ethernet CS Direction at TRISCIl bit end ethernet NIC definitions J 8CKCKCKCK kk Ck Ck Kk Ck Ck Kk Kk Kk CK Ck CKCKCKCkCKCkCkCk ck Ck CkCk CkCkCkCKCkCkCkCkCkCkCkCKCKCKCkCk Ck Ck Ck Ck ck Ck ck ck ROM constant strings ey const unsigned char httpHeader HTTP 1 1 200 OKnContent type HTTP header const unsigned char httpMimeTypeHTMI text htmlnn HTML type const unsigned httpMimeTypeScript text plainnn TEXT MIME type unsigned char httpMethod GET web page splited into 2 parts when coming short of ROM fragmented data is handled more effi ciently by linker this HTML page calls the boards to get its status and builds itself with javascript Sy const 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 470 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
559. utine Write character e at current cursor position Lcd Chr CP e 354 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Lcd Cmd Sends command to LCD Parameters Description out char command to be sent Note Predefined constants can be passed to the function see Available LCD Commands The LCD module needs to be initialized See Lcd Init table Clear Lcd display Lcd Cmd LCD CLEAR Available LCD Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected Underline cursor on MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 355 D RETURN HOME CHAPTER 7 Libraries Library Example mikroC PRO for PIC The following code demonstrates usage of the Lcd Library routines LJ sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit char char char char char he he Lie E X LC i K EasyPIC5 H it D module connections LCD RS at EN at D4 at D5 at D6 at D7 at RB4 bit RBS bat RB bit bit RB2 bit bit LCD RS Direction at LCD EN Direction at LCD 4 Direction at LCD D5 Direction at LCD D6 Direction at LCD D7 Direction at End LCD module connections TRISB4 bit TRISBS bit
560. 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 PIC a variable of an enumerated type can be assigned any value of the type int no type checking beyond that is enforced That is OK eom Also OK means the same 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 2 7 9 74 value 1 green value 2 blue 6 value 6 violet fl value 7 white 4 value 4 170 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 6 mikroC PRO for PIC Language Reference Initializer expression can include previously declared e
561. void SPI Glcd Image const code char image Nothing 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 PIC pointer to const and pointer to RAM equivalency Use the mikroC PRO s integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for display ing on Glcd Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw image my image on Glcd SPI Glcd Image my image Library Example The example demonstrates how to communicate to KS0108 Glcd via the SPI module using seri al to parallel convertor MCP23S17 const code char truck 1024 Port Expander module connections sbit SPExpanderRST at RCO bit sbit SPExpanderCS at bit sbit SPExpanderRST Direction at TRISCO bit sbit SPExpanderCS Direction at TRISCI bit 77 End Port Expander module connections void Delay2s 2 seconds delay function void main 490 Delay ms 2000 char someText char counter If Port Expander Library uses SPI1 module SPIT Initialize SPI module used with PortExpander If Port Expander Library uses SPI2 module MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC if SPI Gled Inzt 0 SPI Gled Fill 0200 SPI
562. w down key repeat pace 432 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries SOFTWARE UART LIBRARY The mikroC PRO for PIC provides routines for implementing Software UART com munication 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 Note 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 433 7 Libraries mikroC PRO for PIC Soft UART Init char Soft UART Init char port char rx pin char tx pin Prototype FE E unsigned long baud rate char inverted 2 error requested baud rate is too low 1 error requested baud rate is too high 0 successful initialization Configures and initializes the software UART module Parameters port port to be used rx pin Sets rx pin to be used tx pin Sets tx pin to be used baud rate baud rate to be set Maximum baud rate depends on the MCU s clock and working conditions inverted inverted output flag When set to a non zero value inverted logic on output is used Description Software UART routines use Delay routine If r
563. ware Simulator 1 97 Creating New Library oe eee ede e Pe E Ce p ue eee 98 Multiple Library Versions 99 CHAPTER 3 mikrolCD Debugger Options 104 mikrolCD Debugger Examples 105 mikrolCD In Circuit Debugger Overview 109 Breakpoints Window 109 Watch WindOW 232 EE ERES ato e rtr podre 110 EEPROM Watch 111 Code Watch Window 112 mikrolCD Code Watch sense ki ppm ved 112 View RAM Memory 255522232545 9495 pr ege ERA 113 Common EMOS eR Er RE pumps Treue 113 mikrolCD Advanced 114 Program Memory 115 Program Memory 115 File Register Break 115 Emulator Features i i exe RE pex EB REX ER nx d on eee OD oe Rn 116 Ev nt Breakpoints 225 2205 RR 116 Stopwatch 116 4 ANSI Standard Issues
564. x20 MODE LOOP 0x40 CAN MODE LISTEN 0x60 MODE CONFIG 0x80 CAN CONFIG FLAGS CAN CONFIG FLAGS constants define flags related to CAN module configuration Functions cANInitialize and CANSetBaudRate expect one of these or a bitwise combination as their argument const char CAN CONFIG DEFAULT OxFF 1311123911 CAN CONFIG PHSEG2 PRG BIT 0 01 CAN CONFIG PHSEG2 PRG ON OxFF fi See CAN CONFIG PHSEG2 PRG OFF OxFE 7 XXXXXXxo CAN CONFIG LINE FILTER BIT 0x02 CAN CONFIG LINE FILTER ON OxFF CAN CONFIG LINE FILTER OFF OxFD ff XXXXXXOX CAN CONFIG SAMPLE BIT 0x04 CAN CONFIG SAMPLE ONCE OxFF Jg SOO CAN CONFIG SAMPLE THRICE OxFB Jg SRO CAN CONFIG MSG TYPE BIT 0x08 CAN CONFIG STD MSG OxFF 27 IKISIRI CAN CONFIG XTD MSG OxF7 fi XXEXOXXEX CAN CONFIG DBL BUFFER BIT 0 10 CAN CONFIG DBL BUFFER ON y4 SODIUM CAN CONFIG DBL BUFFER OFF OxEF XXXO0XXXX 250 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries CAN CONFIG MSG BITS o0 CAN CONFIG ALL MSG OxFF Jg XLIXXXXX CAN CONFIG VALID XTD MSG 0DF Ff XXTOXXXXX CAN CONFIG VALID STD MSG CAN CONFIG ALL VALID MSG OxBF 2 XOITXXNXX Ox9F Ju OOK You may use bitwise AND amp to form config byte out
565. x23 and 0x24 Be careful when using the absolute directive as you may overlap two variables by accident For example char i absolute 0x33 Variable i will occupy 1 byte at address 0x33 long jjjj absolute 0x30 Variable will occupy 4 bytes at 0x30 0x31 0x32 0x33 thus changing i changes jjjj highest byte at the same time and vice versa 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 defin ing declarations will be ignored with an appropriate warning issued by the linker Here is a simple example void func int par org 0x200 Function will start at address 0x200 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 123 4 Specifics mikroC PRO for PIC void UART Writel char data org 0x200 Note Directive org can be applied to any routine except for interrupt 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 0x200 Directive funcorg You can use the pragma funcorg directive to specify the starting address of a rou tine in ROM using routine name only pragma funcorg func name
566. xpander Library uses SPI1 module Tit Gy Initialize SPI module used with PortExpander Port Expander Library uses SPI2 module SPI2 Init Initialize SPI module used with PortExpander init display for 240 pixel width and 128 pixel height 8 bits character width data bus on 23517 porstB control bus on MCP23S17 portA bit JWR Eu L IRD que Que LED Out 4 zs RST chip enable reverse on 8x8 font internaly set in library SPI T6963C Config 240 128 8 0 2 1 0 4 Delay ms 1000 524 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for PIC uti SPI T6963C graphics 1 SPI T6963C text 1 CHAPTER 7 Libraries Enable both graphics and text display at the same time panel 0 0 curs 0 cposx cposy 0 Text messages y SPI T6963C write text txt 0 0 SPI T6963C ROM MODE SPI T6963C write text txtl 0 15 SPI T6963C ROM MODE XOR Cursor m SPI T6963C cursor height 8 8 pixel height SPI 169030 set cursor 0 0 3 move cursor to top left SPI T6963C cursor 0 cursor off ys Draw rectangles d SPL T6963C rectangle 0 239 127 SPI 6953 WHITE 7 SPI 6963 r otangle 20 20 219 107 SPI T6963C WHITE SPI T6963C rectangle 40 40 199 87 SPI T6963C WHITE SPI T6963C rectangle 60 60
567. y case Ethernet module has to be initialized See Ethernet Init unsigned char ipAddr 4 user IP address buffer memcpy ipAddr Ethernet getIpAddress 4 fetch IP address 306 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries Ethernet getGwlpAddress Prototype unsigned char Ethernet getGwIpAddress Returns Ponter to the global variable holding gateway IP address This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address Description Note 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 module has to be initialized See Ethernet Init unsigned char gwIpAddr 4 user gateway IP address buffer memcpy gwIpAddr Ethernet getGwIpAddress 4 fetch gateway IP address Ethernet getDnslpAddress Returns Ponter to the global variable holding DNS IP address This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address Descnipuon Note 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 Ethernet module has to be initialized See Etherne
568. yl PWM1 Start start PWM1 PWM2 Start start PWM2 1 Set Duty current duty Set current duty for PWM2 Set Duty current dutyl Set current duty for PWM2 while 1 endless loop if RAO bit button on RAO pressed Delay ms 40 current dutytt increment current duty 1 Set Duty current duty if RAL bit i Delay ms 40 current duty if Set Duty current duty if bait 4 y Delay ms 40 current dutyl tt PWM2 Set Duty current dutyl 408 button on 1 pressed decrement current duty button on RA2 pressed increment current dutyl MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 mikroC PRO for PIC Libraries if bit button on pressed Delay ms 40 current dutyl decrement current dutyl PWM2 Set Duty current dutyl Delay ms 5 slow down change pace a little HW Connection MUL 4 OSCILLATOR VCC 28849514 300R 300R PWM demonstration MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 409 7 Libraries mikroC PRO for PIC RS 485 LIBRARY RS 485 is a multipoint communication which allows multiple devices to be connect ed to a single bus The mikroC PRO for PIC provides a set of library routines for comfortable work with RS485 system using Master Slave architecture M
569. you can select one from the list using the keyboard arrows and Enter Sp variable sfr unsigned char SPDR variable sfr unsigned char SPSR variable sfr unsigned char SPCR Code Folding Code folding is IDE feature which allows users to selectively hide and display sec tions 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 symbol and appear automatically Use the fold ing symbols to hide unhide the code subsections nes main PORTA 0 PORTB D Lcd Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay 1000 Lcd 1 LCD Out 1 1 txt 1 LCD Out 2 4 txt 2 delay ms 500 void main If you place mouse cursor over the tooltip box the collapsed text will be shown in a tooltip style box MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 37 2 Environment mikroC PRO for PIC void main void main E PORTA 0 PORTS 0 Lcd Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay_ms 1000 Lcd 1 LCD Out 1 1 txt 1 LCD Out 2 4 txt 2 delay ms 500 Parameter Assistant The Parameter Assistant will be automatically invoked when you open parenthesis or press Shift Ctrl Space If th
Download Pdf Manuals
Related Search
Related Contents
SP110 Skype Phone Adapter デコルーフ グレー PDF形式 - テクノエイド協会 Broadway 3D Security System OM, Gardena, Turbotrimmer, Art 02407-20, 2007-06 PSA-T Series Instruction Manual (Italian) Quick Start Guide Guide de démarrage Serso, stockage saisonnier solaire pour le dégivrage d`un pont LG Electronics 50PC3DX Flat Panel Television User Manual Copyright © All rights reserved.
Failed to retrieve file