Home

ABL electronic PIC18 User's Manual

image

Contents

1. PIC16F877A RS485 communication line MCLR Vpp THV RB7 PGD RAO ANO RB6 PGC E dide Up to 32 devices can 5 os be connected to RA2 AN2 Vref RS485 line RA3 AN3 Vreft RB3 PGM RA4 TOCKI RB2 RA5 ANA RB1 x 45V Uv REO RD AN5 RBO INT 9 RE1 WR ANG e lo 45V Vdd T RE2 CS AN7 Vss Vdd RD7 PSP7 Vss RD6 PSP6 OSC1 RD5 PSP5 OSC2 RD4 PSP4 Hn RCO T1OSO RC7 RX DT LTC485 1 1051 RC6 TX CK xd RC2 CCP1 RC5 Shielded pair RCS net less than 300m Salat RDO PSPO RD3 PSP3 long RD1 PSP1 RD2 PSP2 5V a N amp GND 1 5 Riin 14 E R1out ai LTC485 RX Lt Tx T2in S RTS R2out x ume J GND Le 2 7 ILL TA MM dL H am RS232 to RS485 converter L N page 2202109 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Secure Digital Library Secure Digital SD is a flash memory 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 mikroC provides a lib
2. 5V 5V 5 T PIC16F877A xxix F mao peared b 1 RB5 45V 9 RA2 AN2 Vref RB4 8 RA3 AN3 Vref RA4 TOCKI RB2 TX CAN Vdd 4 RB1 RX CAN RST REO RD AN5 RBO INT CLKOUT CS RE1 WR ANG Vdd TXORTS SO T RE2 CS AN7 Vss TXIRTS 5 Vdd RD7 PSP7 TORTS SCK Vss RD6 PSP6 ier EE osci RD5 PSP5 isa eae OSC2 RD4 PSP4 RCO T1IOSO RC7 RX DT MCP2510 1 1051 RC6 TX CK iL N RC2 CCP1 RC5 RC3 RC4 RDO PSPO RD3 PSP3 T RD1 PSP1 RD2 PSP2 5V PCA82C250 v 12 2 Shielded pair less than 300m long MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 64 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Compact Flash Library Compact Flash Library provides routines for accessing data on Compact Flash card abbrev CF further in text CF cards are widely used memory elements commonly found in digital cameras Great capacity 8MB 2GB and more and excellent access time of typically few microseconds make them very attractive for microcontroller applications In CF card data is divided into sectors one sector usually comprising 512 bytes few older models have sectors of 256B Read and write operations are not per formed directly but successively through 512B buffer Following routines can
3. strcmp Prototype char strcmp char 51 char 52 Description Function compares strings s1 and s2 and returns zero if the strings are equal or returns a difference between the first differing characters in a left to right evaluation Accordingly the result is greater than zero if s1 is greater than s2 and vice versa strcpy Prototype char strcpy char 51 char s2 Description Function copies the string s2 into the string s1 If successful function returns s1 The strings may not overlap strlen Prototype unsigned strlen char 5 Description Function returns the length of the string s the terminating null character does not count against string s length MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 220 MIKROE C CGDMPIEER FOR MICROCHIP PIC MICROCONTROLLERS making amp simple 2 strncat Prototype char strncat char 51 char s2 int n Description Function appends not more than n characters from the string s2 to s1 The initial char acter of s2 overwrites the null character at the end of s1 A terminating null character 1s always appended to the result Function returns s1 strncpy Prototype char strncpy char 51 char s2 int n Description Function copies not more than n characters from string s2 to s1 The strings may not overlap If s2 is shorter than n characters then s1 will be padd
4. General purpose registers GPR Special function registers SFR Aes Ox000C empy OMFE7 INDFI Ox000D OMFEB OMD0E empy OWFES5 POSTDECI Ox000F OMFE4 PREINCI 00010 empy OMFE3 PLUSWI 0011 __ OxOFE2 FSRIH 040012 __ OKOFET FSRIL 040013 empy OMFED 04014 OMFDF INDF2 090015 main global i 1 OMFDE 5 2 00016 main global i 2 O FDD POSTDEC2 080017 compact C F cf wiite byte param 1 OMFDC PREINC2 00017 compact cf set reg adt param 1 OMFDB PLUSW2 00018 compact C F cf wiite byte param 2 OMDA FSR2H 080018 compact C F cf set reg adr param 2 O FDS FSR2L 0x0019 compact C F cf wiite byte param dataport 1 OWFDB STATUS 000139 compact C F set req param adr O FD TMROH compact cf wiite byte param dataport 2 OMFDG TMROL 090018 compact C F cf wie byte param bdata OXOFDS 09001 compact C F cf wie init param 1 OWFD3 DSCCON ROM Window Lists op codes and their addresses in form of a human readable hex code Statistics Memory usage Procedures Graph Procedures locations Procedures details RAM 8 g P FFFF FFFF 0100 0000 0012 0100 S0EF 1401 6E00 5019 C018 FFEA C000 FFEF 0012 0100 core FFEF C017 FFES cog FFEA 6E00 500 E103 0000
5. Operator Operation Precedence addition 12 subtraction 12 multiplication 13 division 13 returns the remainder of integer division can E not be used with floating points unary unary plus does not affect the operand 14 unary unary minus changes the sign of operand 14 increment adds one to the value of the 14 operand u decrement subtracts one from the value of the 14 Note Operator is context sensitive and can also represent the pointer reference operator See Pointers for more information d 0 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Binary Arithmetic Operators Division of two integers returns an integer while remainder is simply truncated for example To Ay equals 1 7 3 equals 5 but 7 3 4 equals 5 25 as we are working with floats Remainder operand works only with integers sign of result is equal to the sign of first operand for example 9 3 equals 0 7 3 equals 1 3 equals 1 oe 99 We use arithmetic operators for manipulating characters 32 equals a ASCII only CA equals g both ASCII and EBCDIC Unary Arithmetic Operators Unary operators and are the only operators in C which can be either prefix
6. pieg 32eduio9 OL AG z 80 Mm Soe 9 Pee ae 4 o g a M M ei 2 0 y Mn ve 9 05 AS LdSd Qs dSd qu OdSd 0qs voy Sou LdoO zou MO XL SOH ISOLL LON LO XY LON OSOLL OOM 2250 050 998 9 SSA 1dSd 4Q8 PPA SSA INV SO C3H PPA 9NV HANL3H SNV QN 03H vNV SVH IIOOL PVH WOd tgH J9W ENv EvH vay JeJNENV ZVY say INVI 29 99 GOd gH AHL ddA d10W 228391 21 XOL AS jesesy page 11 774 COMPILERS BOOKS DEVELOPMENT TOOLS MIKROELEKTRONIKA MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making e simple EEPROM Library EEPROM data memory is available with a number of PICmicros mikroC includes library for comfortable work with EEPROM Library Routines Eeprom Read Eeprom Write Eeprom_Read Prototype char Eeprom Read char address Returns Returns byte from the specified address Description Reads data from the specified address Parameter address is of byte type which me
7. Description Initializes LCD at Control port ctrlport and Data port dataport with pin settings you specify Parameters RS EN and WR need to be in range 0 7 Parameters D7 DO need to be a combination of values 0 7 e g 3 6 5 0 7 2 1 4 Example Lcd8 Config PORTC PORTD 0 1 2 6 5 4 3 7 1 2 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 20M8 MIKROG COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Lcd8 Init Prototype void Lcd8 Init char ctrlport char dataport Description Initializes LCD at Control port ctrlport and Data port dataport with default pin set tings see the connection scheme at the end of the chapter E gt ctrlport 3 RS gt ctrlport 2 R W gt ctrlport 0 D7 gt dataport 7 D6 gt dataport 6 D5 gt dataport 5 D4 gt dataport 4 D3 gt dataport 3 D2 gt dataport 2 D1 gt dataport 1 DO gt dataport 0 Example Lcd8 Init PORTB PORTO Lcd8 Out Prototype void Lcd8 Out char row char col char text Description Prints text on LCD at specified row and column parameter row and co1 Both string variables and literals can be passed as text Requires Ports with LCD must be initialized See Config orLcd8 Init Example Out 1 3 Hello Print Hello at line 1 char 3 Lcd8 Out Cp Prototype void Lcd8 Out Cp char text Description Prints text on LCD at current cu
8. MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROD C COMPILER FOR MICROCHIP MICROCONTROLLERS Mmc_Fat_Read Prototype void Mmc Fat Read unsigned short data Description Function reads the byte at which the file pointer points to and stores data into parameter data The file pointer automatically increments with each call of Mnc Fat Read Requires File pointer must be initialized see Fat Reset Example Mmc Fat Read amp mydata Mmc Fat Write Prototype void Mmc Fat Write char fdata unsigned data len Description Function writes a chunk of data len bytes fdata to the currently assigned file at the position of the file pointer Requires File pointer must be initialized see Mnc Fat Append or Fat Rewrite Example Mmc Fat Write txt 21 Fat Write HelloWNnworld 1 Mmc Set File Date Prototype void Mmc Set File Date unsigned year char month char day char hours char min char sec Description Writes system timestamp to a file Use this routine before each writing to the file other wise file will be appended a random timestamp Requires File pointer must be initialized see Mnc Fat Append or Fat Rewrite Example April 1st 2005 18 07 00 Mmc Set File Date 2005 4 1 18 7 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS m
9. MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple New File Paths for Header Files h Header files are included by means of preprocessor directive include If you place an explicit path to the header file in preprocessor directive only that location will be searched If include directive was used with the header name version the search is made successively in each of the following locations in this particular order 1 mikroC installation folder gt include folder 2 your custom search paths The header_name version specifies a user supplied include file mikroC will look for the header file in following locations in this particular order 1 the project folder folder which contains the project file ppc 2 mikroC installation folder gt include folder 3 your custom search paths Managing Source Files Creating a new source file To create a new source file do the following Select File gt New from drop down menu or press CTRL N or click the New File icon A new tab will open named Untitled1 This is your new source file Select File gt Save As from drop down menu to name it the way you want If you have used New Project Wizard an empty source file named after the proj ect with extension c 15 created automatically mikroC does not require you to have source file named same as the project it s just a matter of convenience MIKROELEKTRONIKA
10. Prototype void Cf Write Byte char data Description Writes one byte data to CF 512 bytes are transferred to a buffer Requires must be initialized for write operation See Write Init Example Write Byte 100 Cf Write Word Prototype void Cf Write Word int data Description Writes one word data to 512 bytes are transferred to a buffer Requires CF must be initialized for write operation See Write Init Example Cf Write Word 1000 Cf Find File Prototype void Cf Find File char find first char file name Description Routine looks for files on CF card Parameter ind first can be non zero or zero if non zero routine looks for the first file on card in order of physical writing Otherwise routine moves forward to the next file from the current position again in physical order If file is found routine writes its name and extension in the string 1 If no file is found the string will be filled with zeroes Requires Ports must be initialized See C Init Example Cf Find File 1 file if file 0 lt gt 0 if first file found handle it page 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot MIKROG Cf File Write Init Prototype void Cf File Write Init void Description Initializes CF card for file writing operation FAT1
11. library Requires Both Data and Clock lines need to be in pull up mode Ps2 Config Prototype void Ps2 Config char port char clock char data Description Initializes port for work with PS 2 keyboard with custom pin settings Parameters data and clock specify pins of port for Data line and Clock line respectively Data and clock need to be in range 0 7 and cannot point to the same pin You need to call either 2 Init or Ps2 Config before using other routines of PS 2 library Requires Both Data and Clock lines need to be in pull up mode Example Ps2 Config amp PORTB 2 3 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 728 MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple Ps2_Key_Read Prototype char Ps2 Key Read char value char special char pressed Returns Returns 1 if reading of a key from the keyboard was successful otherwise 0 Description The function retrieves information about key pressed Parameter value holds the value of the key pressed For characters numerals punctua tion marks and space value will store the appropriate ASCII value Routine recog nizes the function of Shift and Caps Lock and behaves appropriately Parameter special is a flag for special function keys F1 Enter Esc etc If key pressed is one of these special will be set to 1 otherwise 0 Parameter pressed is set to 1 if the key is pressed and 0 if r
12. MICROCONTROLLERS 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 CAN operation mode Function CANSetOperationMode expects one of these as its argument define CAN MODE BITS OxEO Use it to access mode bits define CAN MODE NORMAL 0 define CAN MODE SLEEP 0x20 define CAN MODE LOOP 0x40 define CAN MODE LISTEN 0x60 define CAN 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 define CONFIG DEFAULT OxFF 11111111 define CONFIG PHSEG2 PRG BIT 0x01 define CAN CONFIG PHSEG2 PRG ON OxFF XXXXXXX1 define CAN CONFIG PHSEG2 PRG OFF OxFE XXXXXXX0 define CAN CONFIG LINE FILTER BIT 0x02 define CONFIG LINE FILTER ON OxFF XXXXXX1X define CONFIG LINE FILTER OFF OxFD XXXXXXOX define CAN CONFIG SAMPLE BIT 0x04 define CAN CONFIG SAMPLE ONCE OxFF XXXXX1XX define CAN CONFIG SAMPLE THRICE OxFB XXXXXOXX define CAN CONFIG MSG TYPE BIT 0x08 define CAN CONFIG STD MSG OxFF XXXX1XXX define CONFIG XTD MSG OxF7 XXXXOXXX continues MIKROELEK
13. Sequence Value Char What it does a 0x07 BEL Audible bell b 0x08 BS Backspace 0 Formfeed Ox0A LF Newline Linefeed Nr CR Carriage Return t 0x09 HT Tab horizontal v 0x0B VT Vertical Tab Ox5C Backslash Single quote iod Apostrophe 0x22 i Double quote Ox3F Question mark string of up to 3 gt octal digits string of hex dig its m string of hex dig its MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 219 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS 1 460 60 admo String Constants String constants also known as string literals are a special type of constants which store fixed sequences of characters A string literal is a sequence of any number of characters surrounded by double quotes This is string The null string or empty string is written like A literal string is stored inter nally as the 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 e g t Name tAddress n n Adjacent string literals separated only by whitespace are concatenated during the parsing phase For example This is just an example is an equivalent to This is just an example Line continuation with backslash You can also use the backslash X as a continuation ch
14. MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Glcd_Circle Prototype void Glcd Circle int x int y int radius char color Description Draws a circle on the GLCD centered at x y with radius Parameter color defines the circle line 0 draws an empty line clear dots 1 draws a solid line put dots and 2 draws a smart line invert each dot Requires GLCD needs to be initialized See Glcd_Init Example Glcd Circle 63 31 25 2 Glcd Set Font Prototype void Glcd Set Font const char font unsigned short font width unsigned short font height Description Sets font for routines Glcd Write Char and Glcd Write Text Parameter font needs to formatted in an array of byte Parameters ont width and font height specify the width and height of characters in dots Font width should not exceed 128 dots and font height shouldn t exceed 8 dots You can create your own fonts by following the guidelines given in file GLced Fonts c This file contains the default fonts for GLCD and is located in your installation folder Examples gt GLCD Requires GLCD needs to be initialized See Glcd_Init Example Use the array myfont 5x8 with custom 5x8 font Glcd Set Font myfont 5x8 5 8 RI Al MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICR
15. Prototype void Eth Load Tcp Header void Description Loads various TCP Header data into PIC s Ethernet variables Requires This function must be called in a proper sequence i e immediately after retrieving the source and destination port socket of the TCP message Example retrieve source port tcp source port Eth Inport NIC DATA lt lt 8 tcp source port Eth Inport NIC DATA retrieve destination port tcp dest port Eth Inport NIC DATA lt lt 8 tcp dest port Eth Inport NIC DATA We only respond to port 80 HTML requests if tcp dest port 80u Eth Load Tcp Header retrieve TCP Header data most of it al 83 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS Eth_Get_Tcp_Hdr_Offset Prototype unsigned short Eth Get Tcp Hdr Offset void Returns Returns the length or offset of the TCP packet header in bytes Description The function returns the length or offset of the TCP packet header in bytes Upon receiving a valid TCP packet its header is to be analyzed in order to respond properly e g respond to other s request merge several packets into the message etc The head er length is important to know in order to be able to extract the information contained in it Requires This function must be called after the Eth_Load_Tcp_ Header sin
16. 5V RB1 RB2 RB3 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Flash Memory Library This library provides routines for accessing microcontroller Flash memory Note that prototypes differ for PIC16 and PIC18 families Library Routines Flash Read Flash Write Flash Read Prototype unsigned Flash Read unsigned address for 6 char Flash Read long unsigned address for PIC18 Returns Returns data byte from Flash memory Description Reads data from the specified address in Flash memory Example Flash Read 0x0D00 Flash Write Prototype void Flash Write unsigned address unsigned data for PIC16 void Flash Write unsigned long address char data for PIC18 Description Writes chunk of data to Flash memory With PIC18 data needs to be exactly 64 bytes in size Keep in mind that this function erases target memory before writing Data to it This means that 1f write was unsuccessful previous data will be lost Example Write consecutive values in 64 consecutive locations char toWrite 64 initialize array for i 0 i lt 63 i toWrite i i Flash Write 0x0D00 toWrite a BO MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROL
17. MICROCONTROLLERS Auto Correct The Auto Correct feature corrects common typing mistakes To access the list of recognized typos select Tools gt Options from the drop down menu or click the Tools Icon and then select the Auto Correct Tab You can also add your own pref erences to the list peu Comment Uncomment Comment Code Editor allows you to comment or uncomment selected block of code by Uncomment Icon 2 gt a simple click of a mouse using Comment Uncomment icons from the Code Toolbar Bookmarks Bookmarks make navigation through large code easier CTRL lt number gt Go to a bookmark CTRL SHIFT lt number gt Set a bookmark Goto Line Goto Line option makes navigation through large code easier Select Search gt Goto Line from the drop down menu or use the shortcut CTRL G MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS CODE EXPLORER Collapse Expand The Code Explorer is placed to the left of the main window by default and gives a clear view of every declared item in the source code You can jump to a declara tion of any item by clicking it or by clicking the Find Declaration icon To expand or collapse treeview in Code Explorer use the Collapse Expand icon Also two more tabs are available in Code Explorer QHelp Tab lists all the avail able built in and library functions for a quick referen
18. s sptr heas S l 3 assign 3 to the i member of B S24 assign 2 to the j member of A sptr d 1 23 assign 1 23 to the d member of B sptr gt a x 3 14 assign 3 14 to x member of A Structure Uniqueness Each structure declaration introduces a unique structure type so that in struct A int i j double d aa aaa struct B int i j double d bb the objects aa and aaa are both of type struct A but the objects aa and bb are of different structure types Structures can be assigned only if the source and destina tion 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 aa i bb i aa j bb j aa d bb d Veo MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Union types are derived types sharing many of the syntactic and functional fea tures of structure types The key difference is that a union allows only one of its members to be active at any given time the most recently changed member Note mikroC does not support anonymous unions ANSI divergence Union Declaration Unions are declared same 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 Le
19. Form value to be used with CANSPISendMessage aal CAN TX PRIORITY 0 amp CAN TX XTD FRAME amp CAN TX NO RTR FRAME PORTC FO 1 Set PORTC 0 continues MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS 26609 as continued Initialize external CAN module CANSPIInitialize 1 1 3 3 1 aa Set CANSPI to CONFIG mode CANSPISetOperationMode CAN MODE CONFIG TRUE ID 1 Set all mask1 bits to ones CANSPISetMask CAN MASK B1 id CAN CONFIG XTD MSG Set all mask2 bits to ones CANSPISetMask CAN MASK B2 id CAN CONFIG XTD MSG Set id of filter B1 F1 to 12111 CANSPISetFilter CAN FILTER B2 F4 12111 CAN CONFIG XTD MSG Set CANSPI to NORMAL mode CANSPISetOperationMode CAN MODE NORMAL TRUE while 1 zr CANSPIRead amp id amp Data amp len amp aa2 Receive data if any if id 12111 zr PORTB data 0O Output data on PORTB id 3 Delay ms 500 Send incremented data back CANSPIWrite id amp data 1 aal If message contains 2 data bytes output second byte at PORTD if len 2 PORTD 11 850 MIKROELEKTRONIKA DEVELOPMENT TOOLS Books COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Hardware Connection
20. MICROCONTROLLERS making 42 simple Any processed section can contain further conditional clauses nested to any depth Each nested else elif or endif directive belongs to the closest pre ceding if directive The net result of the preceding scenario is that only one code section possibly empty will be compiled Directives ifdef and ifndef You can use the ifdef and ifndef directives anywhere if can be used The ifdef and ifndef conditional directives let you test whether an identifier is currently defined or not The line ifdef identifier has exactly the same effect as if 1 if identifier is currently defined and the same effect as if 0 if identifier is currently undefined The other directive ifndef tests true for the not defined condition producing the opposite results The syntax thereafter follows that of the if elif else and endif An identifier defined as NULL is considered to be defined 4 224 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS CHAPTER mikroC Libraries mikroC provides a number of built in and library routines which help you develop your application faster and easier Libraries for ADC CAN USART SPI I2C 1 Wire LCD PWM RS485 numeric formatting bit manipulation and many other are included along with practical ready to use code examples MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MI
21. case 0 Lo break case 1 Mid break case 2 Hi break default Message Invalid state 4 il MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Iteration Statements Iteration statements let you loop a set of statements There are three forms of itera tion statements in C while do and for While Statement Use the while keyword to conditionally iterate a statement Syntax of while statement is while expression statement The statement executes repeatedly until the value of expression is false The test takes place before statement executes Thus if expression evaluates to false on the first pass the loop does not execute Parentheses around expression are mandatory Here is an example of calculating scalar product of two vectors using the while statement int 0 0 while i lt S ali blil i Note that body of a loop can be a null statement For example while MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 9 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Do Statement The do statement executes until the condition becomes false Syntax of do state ment 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 itera
22. exp Prototype double exp double x Description Function returns the value of e the base of natural logarithms raised to the power of x i e fabs Prototype double fabs double num Description Function returns the absolute i e positive value of num MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Z2 91 MIKROE C CGDMPIEER FOR MICROCHIP PIC MICROCONTROLLERS se Seo c etie making 42 simple floor Prototype double floor double num Description Function returns value of parameter num rounded down to the nearest integer frexp Prototype double frexp double num int exp Description Function splits a floating point value num into a normalized fraction and an integral power of 2 Return value is the normalized fraction and the integer exp is stored in the object pointed to by exp Idexp Prototype double ldexp double num int exp Description Function returns the result of multiplying the floating point number num by 2 raised to the power exp i e returns x 2 P log Prototype double log double x Description Function returns the natural logarithm of x i e log x page 0 2229309 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making simple O EEES EAEE Mino ce CEMPICER FOR MICROCHIP MEE log10 Prototype double 10910 double x Descri
23. mikroC Language Reference C offers unmatched power and flexibility in programming microcontrollers mikroC adds even more power with an array of libraries specialized for PIC HW modules and communications This chapter should help you learn or recollect C syntax along with the specifics of programming PIC microcontrollers If you are experienced in C programming you will probably want to consult mikroC Specifics first MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple PIC SPECIFICS In order to get the most from your mikroC 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 Types Efficiency First of all you should know that PIC s ALU which performs arithmetic opera tions is optimized for working with bytes Although mikroC is capable of han dling very complex data types PIC may choke on them especially if you are working on some of the older models This can dramatically increase the time needed for performing even simple operations Universal advice is to use the smallest possible type in every situation It applies to all programming in general and doubly so with microcontrollers When it comes down to calculus not all PICmicros are of equal performance For exampl
24. MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Macros with Parameters The following syntax is used to define a macro with parameters define macro identifier arg list token sequence Note there can be no whitespace between the macro identifier and the The optional arg list is a sequence of identifiers separated by commas not unlike the argument list of a C function Each comma delimited identifier plays 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 delim ited token sequences known as actual arguments as found in the formal arg list ofthe define line there must be an actual argument for each for mal argument n error will be reported if the number of arguments in the two lists 1s different 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 the actual arg list As with simple macro defini tions rescanning occurs to detect
25. Procedures Details Window Displays complete call tree along with details for each function Statistics Memory usage Procedures Graph Procedures locations Procedures details RAM ROM 5 main 5 compact C F cf init Unit compact C compact c detect Procedure Name compact 91 read wor RealName CF Read Word compact C F cf wiite ini compact_C_F_ct_write_byte Size 234 Frequency fi delays delay lus Fea PS word compact C F cf sel reg compact C F cf wiite word Start Address 625 04272 delays delay lus EndAddress 859 00358 compact C read word delays delay lus Memory Page 0 compact C F cf write byte Variables 050010 compact_C_F_cf_tead_word_param_ctrlport_2 xl zi delays delay 1 Constants compact_C_F_cf_read_init compact_C_F_cf_write_byte delays delay lus compact C F cf set reg adr compact C F cf read byte delays delay lus size start and end address calling frequency return type etc MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS E MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple RAM Window Summarizes all GPR and SFR registers and their addresses Also displays symbol ic names of variables and their addresses Statistics Memory usage Procedures Graph Procedures locations Procedures details RAM
26. Then simply use the functions listed below Note USART library functions support module on PORTB PORTC or PORTG and will not work with modules on other ports Examples for PICmicros with module on other ports can be found in Examples in mikroC installation folder Library Routines Usart Init Usart Data Ready Usart Read Usart Write Note Certain PICmicros with two USART modules such as P18F8520 require you to specify the module you want to use Simply append the number 1 or 2 to a function name For example Usart Write2 Usart Init Prototype void Usart Init const long baud rate Description Initializes hardware USART module with the desired baud rate Refer to the device data sheet for baud rates allowed for specific Fosc If you specify the unsupported baud rate compiler will report an error Usart Init needs to be called before using other functions from USART Library Requires You need PIC MCU with hardware USART Example Usart Init 2400 Establish communication at 2400 bps MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2 d MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Usart_Data_Ready Prototype char Usart Data Ready void Returns Function returns 1 if data is ready or 0 if there is no data Description Use the function to test if data is ready for transmission Requires USART HW module must be initializ
27. d Al 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot making a simple MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS CANInitialize Prototype void CANInitialize char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CAN CONFIG FLAGS Description Initializes CAN All pending transmissions are aborted Sets all mask registers to 0 to allow all messages Filter registers are set according to flag value if CONFIG FLAGS amp CAN CONFIG VALID MSG 0 Set all filters to XTD_MSG else if config amp CONFIG VALID STD MSG 0 Set all filters to STD MSG else Set half the filters to STD and the rest to XTD MSG Parameters SJW as defined in 18 8 datasheet 1 4 BRP as defined in 18 8 datasheet 1 64 PHSEG1 as defined in 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 Requires CAN must be in Config mode otherwise the function will be ignored Example init CAN CONFIG SAMPLE THRICE CAN CONFIG PHSEG2 PRG ON CAN CONFIG STD MSG CAN CONFIG DBL BUFFER ON CAN CONFIG VALID XTD MSG CAN CONFIG LINE FILTER OFF CANInitialize 1 1 3 3 1 init initialize CAN MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 219 MIKROG C COMP
28. making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS 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 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 Library Routines Hid_Enable Hid Read Hid Write Hid Disable Hid Enable Prototype void Hid Enable unsigned readbuff unsigned writebuff Description Enables USB HID communication Parameters readbuff and writebuff are the Read Buffer and the Write Buffer respectively which are used for HID communication This function needs to be called before using other routines of USB HID Library Example Hid Enable amp rd amp wr MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 72 7 5 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Hid_Read Prototype unsigned short Hid Read void Returns Number of characters in Read Buffer received from Host Description Receives message from host and stores it in the Read Buffer Function returns the num ber of characters received in Read Buffer Requires USB HID needs to be enabled before using this function
29. 0 0 Ports Configuration TRISA 0 TRISB 0 TRISC OxFF TRISD OxFF TRISE 0x07 LATA 0 LATB 0 LATC 0 LATD 0 LATE 0 Clear user RAM Banks 00 07 8 x 256 2048 Bytes asm LFSR FSRO 0x000 MOVLW 0x08 CLRF POSTINCO 0 CPFSEQ FSROH 0 BRA 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2 7f 7f MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS 126608 amp simple 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 0 255 k Prepare send buffer userWR buffer 0 k Send the number via USB Hid Write amp userWR buffer 1 while 1 Hid Disable 83 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making a simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS HW Connection PIC18F4550 8V MCLR Vpp RE3 RB7 KBI3 PGD Y RAQ ANO RB6 KBI2 PGC 2 1 1 RBS KBH PGM move OMNI RA3IAN3 Vref RB3 AN9 CCP2 VPO CIOUTRCV RB2 ANB INT2 IVMO RAS ANAISSI RB1 AN10 INT1 HLVDIN C20UT SCK SCL 3 REOIANSICKiSPP RBOIANIZINTO RE4 AN6 CK2SPP Vdd RE2 AN7 OESPP Vss Vdd RD7 SPP7 P1D Vss RD6 SPP6 P1C OSC1 CLKI RD
30. 8 13 gt 5 8 1 0 14 gt 5 lt 3 returns 1 1455 3 1 3 1 lt lt 5 returns 1 a b 5 0 or 1 lt 5 1 MA MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 4 simplere 1 MIKROC C COMPILER FOR MICROCHIP IPIE MICROCONTROLLERS Bitwise Operators Use the bitwise operators to modify the individual bits of numerical operands Bitwise operators associate from left to right The only exception is the bitwise complement operator which associates from right to left Bitwise Operators Overview Operator Operation Precedence bitwise AND returns 1 if both bits are 1 oth 9 erwise returns 0 bitwise inclusive OR returns 1 if either or 9 both bits are 1 otherwise returns 0 bitwise exclusive OR returns 1 if the i 10 bits are complementary otherwise 0 bitwise complement unary inverts each bit 10 bitwise shift left moves the bits to the left gt gt 10 see below bitwise shift right moves the bits to the right lt lt 10 see below Note Operator amp can also be the pointer reference operator Refer to Pointers for more information Bitwise operators amp and perform logical operations on appropriate pairs of bits of their operands For example 0x1234 amp 0x5678 equals 0x1230 because 0 1234 0001 0010 0011 0100 0x5678 0101 0110 0111 1000 amp 0001 0010 0011 0000 that is 0x1230 M
31. RC3 RC4 RDO PSPO RD3 PSP3 RD1 PSP1 RD2 PSP2 1 T2 T4 5 TO mm T m TO to 19 Tom TU T O Tim T4 T5 T16 pn 5V 5 4 Jo 2 i 5V 4MHz page MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS LCD Library 4 bit interface mikroC provides a library for communicating with commonly used LCD 4 bit interface Figures showing HW connection of PIC and LCD are given at the end of the chapter Note Be sure to designate port with LCD as output before using any of the fol lowing library functions Library Routines Lcd Config Lcd Init Lcd Out Lcd Out Cp Lcd Chr Lcd Chr Cp Lcd Cmd Lcd Config Prototype void Lcd Config char port char RS char EN char WR char D7 char D6 char D5 char D4 Description Initializes LCD at port with pin settings you specify parameters RS EN WR D7 D4 need to be a combination of values 0 7 e g 3 6 0 7 2 1 4 Example Lcd Config PORTD 1 2 0 3 5 4 6 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER MICROCHIP PIG MICROCONTROLLERS L ling 60 dimple Lcd Init Prototyp
32. bler For linker to recognize these functions you need to make a call in C code outside of interrupt body is a simple example of handling the interrupts from TMRO if no other interrupts are allowed void interrupt counter TMRO 96 INTCON 20 BAL MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 3 MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Linker Directives mikroC uses internal algorithm to distribute objects within memory If you need to have variable or routine at specific predefined address use linker directives absolute and org Directive absolute Directive absolute specifies the starting address in RAM for variable If variable is multi byte higher bytes are stored at consecutive locations Directive absolute is appended to the declaration of variable int foo absolute 0x23 Variable will occupy 2 bytes at addresses 0x23 and 0x24 Be careful when using absolute directive as you may overlap two variables by mistake 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 so changing i changes jjjj highest byte at the same time Directive org Directive org specifies the starting address of routine in ROM Directive org is appended to the function definition Directives applied to non def
33. ch function call Since it has the function prototype for unc this program converts 1imit 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 have been placed on the stack as an integer and a character respectively in that case the stack passed to func would not match in size or content what func was expecting leading to problems MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 99 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple OPERATORS Operators are tokens that trigger some computation when applied to variables and other objects in an expression mikroC recognizes following operators Arithmetic Operators Assignment Operators Bitwise Operators Logical Operators Reference Indirect Operators see Pointer Arithmetic Relational Operators Structure Member Selectors see Structure Member Access Comma Operator see Comma Expressions Conditional Operator Array subscript operator see Arrays Function call operator see Function Calls sizeof Operator Preprocessor Operators and see Preprocessor Operators Operators Precedence and Associativity There are 15 precedence categories some of which contain only one operator Operators in the same category have equal precedence with each other Table on the following page
34. for i 1 i lt size i Write whole file to USART Mmc_Fat_Read amp character Usart_Write character Delay 200 22 935 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Hardware Connection 5V PIC18F458 MC33269 3 3 3V3 A 5V MCLRIVpp RB7 PGD RAQ ANO Cvref RB6 PGC 10K RA1 AN1 RB5 PGM RA2 AN2 Vref RB4 RA3 AN3 Vref RB3 CANRX RA4 TOCKI RB2 CANTX INT2 RAS AN4 SS LVDIN RB1 INT1 z REO ANS RD RBO INTO RE1 ANGIWRIC10UT Vdd oc RE2 AN7 CS C20UT Vss Vdd RD7 PSP7 P1D Vss RD6 PSP6 P1C OSCAICLKI RDS PSPSIP1B OsczicLKO RAe RD4 PSP4 ES amp amp 1 1 RCOTIOSO TICKI RC7 RX DT ICS RC1 TAOSI RC6 TXICK Data IN GND RC2 CCP4 RCS SDO 3V3 RC3 SCK SCL RC4 SDISDA g g g CLK RDO PSPO C1IN RD3 PSP3 C2IN GND RD1 PSP1 C1IN RD2 PSP2 C2IN Data OUT d SV1 Back view 2D 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS OneWire Library OneWire library provides routines for communication via OneWire bus for exam ple with DS1820 digital thermometer This is a Master Slave protocol
35. making a simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Hardware Connection 35V PIC16F877A Transmitter RF Module T MCLR Vpp THV RB7 PGD 5V RB6 PGC Antenna 5 RAT AN1 RB5 RA2 AN2 Vref RB4 RAS AN3 Vret RB3 PGM ca RA4 TOCKI RB2 RB1 10 REO RD ANS RBO INT 2 45V RE1 WR ANG Vdd T RE2 CS AN7 Vss RD7 PSP7 RD6 PSP6 RD5 PSP5 RD4 PSP4 1050 RC7 RXIDT l H 1 1 5 RC6 TX CK RC2 CCP1 RC5 RC3 RC4 4MHz RDO PSPO RD3 PSP3 RD1 PSP1 RD2 PSP2 PIC16F877A 5V MCLRIVpp THV RB7 PGD RAO ANO RB6 PGC xs RA1 AN1 22 RA2 AN2 Vref RB4 RA3 AN3 Vref RB3 PGM Antenna Kanec RA5 AN4 RR3 9 REO RD ANS RBO INT Receiver RF Module s RE2 CS AN7 45V RD7 PSP7 RD6 PSP6 RD5 PSP5 RD4 PSP4 RCO T OSO RC7 RX DT n 1 RCi TIOSI RC6 TX CK RC2 CCP1 RC3 4MHz RDO PSPO RD3 PSP3 L RD1 PSP1 RD2 PSP2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS DPR MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Multi Media Card Library mikroC provides a library for accessing data on Multi Media Card via SPI communication Notes Library works with PIC18 family only Library functions create and re
36. program simulation Check the Nested Calls Limitations for more information Note Real scenarios may differ from the simulation depending on runtime program parameters Watch Window Sb o9 er Variables Stopwatch Call Stack CALL delays delay 5500us CALL led lcd init GOTO main 131 10 ms 262204 cycles lg 8 000000 MHz 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making a simple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS 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 the message tab and displays location and type of errors compiler has encountered The compiler also reports warnings but these do not affect the output only errors can interefere with generation of hex E Messages Find Convertor Line Column Invalid expresion C AProgram expected but found Program Fil kroelektronika mikro d Internal error c Program Files Mikroelektronika mikroC E Double click the message line in the Error Window to highlight the line where the error was encountered Consult the Error Messages for more information about errors recognized by the compiler MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER
37. string constants strings literals enumeration constants The data type of a constant is deduced by the compiler using such clues as numer ic value and the 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 1 attached to any constant forces the constant to be represented as a long Similarly the suffix U or u forces the constant to be unsigned You can use both L and U suffixes on the same constant in any order or case ul Lu UL etc In the absence of any suffix U u L or 1 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 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 220 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Otherwise If the constant has a U or u suffix its data type will be the first of the following that can accommodate its value unsigned short unsigned int unsigned long int If the constant has an L or 1 suffix its data type will be the first of the following that can accommodate its value long int unsigned long int If the constant has both U and L suffixes ul lu U1 1U uL Lu LU o
38. this line can be omitted MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Function Calls A function is called with actual arguments placed in the same sequence as their matching formal parameters Use a 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 dis agree implicit type conversions rules apply Actual arguments can be of any com plexity but you should not depend on their order of evaluation because it is not specified Upon function call all formal parameters are created as local objects initialized by values of actual arguments Upon return from a function temporary object is cre ated in the place of the call and it is initialized by the expression of return state ment This means that function call as an operand in complex expression is treated as the function result If the function is without result type void or you don t need the result you can write the function call as a self contained expression In C scalar parameters are always passed to function by value A function can modify the values of its formal parameters but this has no effect on the actual arguments in the calling routine You can pass scalar object by the address by declaring a formal parameter to be a pointer Then use the indi
39. tmp Adc Read 1 read analog value from channel 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS d 5230 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Library Example This code snippet reads analog value from channel 2 and displays it on PORTD lower 8 bits and PORTB 2 most significant bits unsigned temp_res void main ADCON1 0x80 Configure analog inputs and Vref TRISA OxFF PORTA is input TRISB Ox3F Pins RB7 RB6 are outputs TRISD 0 PORTD is output do temp res Adc Read 2 Get results of AD conversion PORTD temp res Send lower 8 bits to PORTD PORTB temp res 2 Send 2 most significant bits to RB7 RB6 while 1 Hardware Connection PIC16F877A 5 330R AA 5V MCLR Vpp THV RB7 PGD LB T RAO ANO RB6 PGC RA1 AN1 RB5 330R 77 ige RA2 AN2IVref RB4 Di 1 RAS AN3 Vref RB3 PGM E RA4 TOCKI RB2 330R 771g RAS AN4 RB1 gt REO RD ANS RBO INT P RE1 WR ANG Vdd 330R a LD6 x 19 RE2 CS AN7 Vss RD7 PSP7 330R 77 rps l RD6 PSP6 1 OSC1 RD5 PSP5 OSC2 RD4 PSP4 mE LD4 RCO T10SO RC7 RX DT RC1 T10SI_ RC6 TX CK 330R 77 LD3 RC2 CCP1 RC5 gt RC3 RC4 4MHz RDO PSPO RD3 PSP3
40. 3 increment the last element void main AM en func a You can initialize a multi dimensional array with an appropriate set of values within braces For example int a 3 2 12 2 2 6 3 7 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Pointers Pointers are special objects for holding or pointing to memory addresses In C address of an object in memory can be obtained by means of unary operator amp To reach the pointed object we use indirection operator on a pointer A pointer of type pointer to object of type holds the address of that is points to an object of type Since pointers are objects you can have a pointer pointing to a pointer and so on Other objects commonly pointed at include arrays structures and unions A pointer to a function is best thought of as an address usually in a code segment where that function s executable code is stored that is the address to which con trol is transferred when that function is called Although pointers contain numbers with most of the characteristics of unsigned integers they have their own rules and restrictions for declarations assignments conversions and arithmetic The examples in the next few sections illustrate these rules and restrictions Note Currently mikroC does not support pointers to functions but this feature will be implemented in future versions Pointer
41. 330R is RD1 PSP1 RD2 PSP2 Di 1 3308 77 ig 330R 7 E 4 40 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS mikroC making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS CAN Library mikroC provides a library driver for working with the CAN module CAN is a very robust protocol that has error detection and signalling self check ing and fault confinement Faulty CAN data and remote frames are re transmitted automatically 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 1s 1000m CAN supports two message formats Standard format with 11 identifier bits and Extended format with 29 identifier bits Note CAN routines are currently supported only by P1I8XXX8 PICmicros Microcontroller must be connected to CAN transceiver MCP2551 or similar which is connected to CAN bus Note Be sure to check CAN constants necessary for using some of the functions See page 145 Library Routines CANSetOperationMode CANGetOperationMode CANInitialize CANSetBaudRate CANSetMask CANSetFilter CANRead CANWrite Following routines are for the internal use by compiler only RegsToCANID CANIDToRegs MIKROELEKTRONIKA
42. Clear Clear LCD display MIKROELEKTRONIKA DEVELOPMENT TOOLS Books COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making simple Library Example default pin settings char text mikroElektronika void main TRISB 0 PORTB is output TRISC 0 PORTC is output Lcd8 Init amp PORTB amp PORTC Initialize LCD at PORTB and PORTC Lcd8 CURSOR OFF Turn off cursor Lcd8 Out 1 1 text Print text on LCD Hardware Connection PIC MCU any port with 8 pins Control Port Data Port PINO 2 PINO PIN1 2 PIN3 4 PINS 6 lt LCD contrast ty 20M6 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making simple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example custom pin settings char text mikroElektronika void main TRISB Qs PORTB is output TRISD 0 PORTD is output Initialize LCD at PORTB and PORTD with custom pin settings Lcd8 Config amp PORTB amp PORTD 3 2 0 0 1 2 3 4 5 6 7 CURSOR OFF Turn off cursor Lcd8 Out 1 1 text Print text at LCD Hardware Connection PIC MCU any port with 8 pins Control Port Data Port PINO
43. DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Opening an Existing File Select File gt Open from drop down menu or press CTRL O or click the Open Open File icon File icon The Select Input File dialog opens In the dialog browse to the location of the file you want to open and select it Click the Open button The selected file is displayed in its own tab If the selected file is already open its current Editor tab will become active 2 Printing an Open File Make sure that window containing the file you want to print is the active window Select File gt Print from drop down menu or press CTRL P or click the Print icon In the Print Preview Window set the desired layout of the document and click the OK button The file will be printed on the selected printer 2 Saving File Make sure that window containing the file you want to save is the active window Select File gt Save from drop down menu or press CTRL S or click the Save icon The file will be saved under the name on its window Print File Icon Save File Icon B Saving File Under a Different Name Save Fileas Make sure that window containing the file you want to save is the active window Select File gt Save As from drop down menu or press SHIFT CTRL S The New File Name dialog will be displayed In the dialog browse to the folder where you want to save the file In the
44. DEVELOPMENT TOOLS BOOKS COMPILERS 7 d MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple CANSetOperationMode Prototype void CANSetOperationMode char mode char wait flag Description Sets CAN to requested mode i e copies mode to CANSTAT Parameter mode needs to be one of CAN OP MODE constants see CAN constants Parameter wait flag needs to be either 0 or OxFF If set to OxFF this is a blocking call the function won t return until the requested mode is set If 0 this is a non blocking call It does not verify if CAN module is switched to requested mode or not Caller must use function CANGetOperationMode to verify correct operation mode before performing mode specific operation Requires CAN routines are currently supported only by PI8XXXS8 PICmicros Microcontroller must be connected to CAN transceiver MCP2551 or similar which is connected to CAN bus Example CANSetOperationMode MODE CONFIG OxFF CANGetOperationMode Prototype char CANGetOperationMode void Returns Current opmode Description Function returns current operational mode of CAN module Requires CAN routines are currently supported only by PI8XXXS8 PICmicros Microcontroller must be connected to CAN transceiver MCP2551 or similar which is connected to CAN bus Example if CANGetOperationMode CAN MODE NORMAL Age
45. Declarations Pointers are declared same as any other variable but with ahead of identifier 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 void which really means a pointer to anything Pointers to void are often called gener ic pointers and are treated as pointers to char in mikroC If type is any predefined or user defined type including void the declaration type p Uninitialized pointer declares p to be of type pointer to type All the scoping duration and visibility rules apply to the p object just declared You can view the declaration in this way if p is an object of type then p has to be a pointer to such objects Ais MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Note You must initialize pointers before using them Our previously declared pointer p is not initialized i e assigned a value so it cannot be used yet Note In case of multiple pointer declarations each identifier requires an indirect operator For example int pa pb pc is same as int pa int pb int pc Once declared though a pointer can usually be reassigned so that it points to an object of another type mikroC lets you reassign pointers without typecasting but the compiler will warn you unless the pointer was
46. Description Loads and returns the header checksum of the received IP packet Requires The card NIC must be properly initialized See Eth Init Also a proper sequence of calls must be obeyed see the Event function in the supplied Ethernet example Example Eth Get Hdr Chksum Eth Get Source Address Prototype void Eth Get Source Ip Address void Description Loads and returns the IP address of the sender of the received IP packet Requires The card NIC must be properly initialized See Eth Init Also a proper sequence of calls must be obeyed see the Event function in the supplied Ethernet example Example Eth Get Source Ip Address Eth Get Dest Address Prototype void Eth Get Dest Ip Address void Description Loads the IP address of the received IP packet for which the packet 1s designated Requires The card NIC must be properly initialized See Eth Init Also a proper sequence of calls must be obeyed see the Event function in the supplied Ethernet example Example Eth Get Dest Ip Address Jpage MIKROELEKTRONIKA DEVELOPMENT TOOLS Books COMPILERS mikrot MIKROG Eth Arp Response COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Prototype void Eth Arp Response void Description An automated ARP response User should simply call this function once he detects
47. EF22 FFES cos FFEA SCEF FOOO 0100 core FFES FFEA 5000 E104 00 FFEA GEEF 12 26 9 FFES FFEA oe 00 BEEF 12 Fooo core FFEA E103 0000 SAEF FFES core FFEA 1 Al MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making a simple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS INTEGRATED TOOLS USART Terminal mikroC includes the USART Universal Synchronous Asynchronous Receiver Transmitter communication terminal for RS232 communication You can launch it from the drop down menu Tools gt Terminal or by clicking the Terminal icon Hs Communication Terminal Settings Communication Port z Send Clear Rev Baud z Append V Stop Bits t 7 Connected to COM1 Sent at Parity None Check Parity Recieved OK Data bits Commands RIS DIR C Off C On On C Connect Disconnect Status Send Receive CTS DSR ASCII Chart The ASCII Chart is a handy tool particularly useful when working with LCD dis play You can launch it from the drop down menu Tools gt ASCII chart ASCII Chart DEC iO o Qm 10 w NH MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MIC
48. PIN2 PIN3 PINO PINI 2 PIN3 PIN4 PIN5 6 PIN7 n lt LCD contrast MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 20 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple GLCD Library mikroC provides a library for drawing and writing on Graphic LCD These rou tines work with commonly used GLCD 128x64 and work only with the PIC18 family Note Be sure to designate port with GLCD as output before using any of the fol lowing functions Library Routines Basic routines Glcd_Init Glcd Disable Glcd Set Side Glcd Set Page Glcd Set X Glcd Read Data Glcd Write Data Advanced routines Glcd Fill Dot Glcd Line Glcd V Line Glcd Line Glcd Rectangle Glcd Box Glcd Circle Glcd Set Font Glecd Write Char Glcd Write Text Glecd Image Glcd Partial Image ZX 0 t83 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Glcd Init Prototype void Glcd Init unsigned char ctrl port char 1 char cs2 char rs char rw char rst char en unsigned char data port Description Initializes GLCD at lower byte of data port with pin settings you specify Parameters CS1 cs2
49. PORTC Cf Read Byte Read byte and display on PORTC Delay 1000 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 50 MIKROG mikroC COMPILER FOR MICROCHIP PIG MICROCONTROLLERS making 442 acute Next example waits until the CF card is inserted and when plugged it creates 5 text files on the card Each file will be appended the same timestamp unsigned short index unsigned 11 char fname ext void Init void TRESC S 105 PORTC is output Cf Init PORTB PORTD Initialize ports do nop while Cf Detect Wait until CF card is inserted Delay ms 50 Wait until the card is stabilized void main ext TXT index 0 Index of file to be written while index 5 PORTC 2 0 Init PORTC index Cf File Write Init Initialization for writing to new file Write 50 000 bytes to file while 11 lt 50000 Cf File Write Byte 48 index 1 fname MY TEST1 Name must be 8 character long in uppercase fname 8 48 index Ensure that files have different name Cf Set File Date 2005 1 1 0 0 0 Append a timestamp Cf File Write Complete fname ext Close the file index PORTC OXFF 7 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS HW Connection MIIA dO 40328uuo3 usejJ 32eduio3 C
50. Pti Array 10 Here Pt i is synonym for type pointer to int and Array is synonym for type array of 10 int elements 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS asm Declaration C allows embedding assembly in the source code by means of asm declaration Declarations asm and asm are also allowed in mikroC and have the same meaning Note that you cannot use numerals as absolute addresses for SFR or GPR variables in assembly instructions You may use symbolic names instead listing will display these names as well as addresses You can group assembly instructions by the asm keyword or asm or asm asm block of assembly instructions comments both single line and multi line are allowed in embedded assembly code Assembly style comments starting with semicolon are not allowed If you plan to use a certain C variable in embedded assembly only be sure to at least initialize it in C code otherwise linker will issue an error This does not apply to predefined globals such as PORTB For example the following code will not be compiled as linker won t be able to recognize variable myvar unsigned myvar void main asm MOVLW 10 just a test MOVLW test main global myvar 1 Adding the following line or similar above asm block would let linker know that variable is used myvar 0 Note mikroC will n
51. RC6 TX CK RC5 SDO RC4A SDISDA RD3 PSP3 C2IN RD2 PSP2 C2IN 5V PCA82C250 or gt MCP2551 PCA82C250 or gt MCP2551 E 10K Reset o 10R 10R Shielded pair less than 300m long 18 458 MCLR Vpp RB7 PGD RAO ANO Cvref RB6 PGC RBS PGM RAZIAN2IVref RB4 RAS AN3 Vref RB3 CANRX RAAITOCKI RB2 CANTX INT2 RAS AN4 SS LVDIN RBA INT1 REO ANS RD RBO INTO RET ANG WRIC4OUT REZ ANTICSIC20UT Vss RD7 PSP7IP1D RD6 PSPG PIC OSC1 CLKI RDS PSP5 P1B RD4 PSP4 ECCP1 P1A RC7 RX DT OSC2 CLKO RA6 RCO TIOSO TICKI RC1 T1OSI RC6 TXICK RC2 CCP1 RC5 SDO RC3 SCK SCL RCA SDI SDA RDO PSPO C1IN RD3 PSP3 C2IN RD1 PSP1 C1IN RD2 PSP2 C2IN page 1572 COMPILERS Books DEVELOPMENT TOOLS MIKROELEKTRONIKA making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS CANSPI Library SPI module is available with a number of PICmicros mikroC provides a library driver for working with the external CAN modules such as MCP2515 or MCP2510 via SPI In mikroC each routine of CAN library has its CANSPI counterpart with identical syntax For more information on the Controller Area Network consult the CAN Library Note that the effective communica
52. See Hid_Enable Example get Hid Read Hid_Write Prototype void Hid Write unsigned writebuff unsigned short len Description Function sends data from wrbuff to host Write Buffer is the same parameter as used in initialization Parameter 1en should specify a length of the data to be transmitted Requires USB HID needs to be enabled before using this function See Hid_Enable Example Hid Write amp wr len Hid Disable Prototype void Hid Disable void Description Disables USB HID communication Requires USB HID needs to be enabled before using this function See Hid Enable Example Hid Disable Age MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example The following example continually sends sequence of numbers 0 255 to the PC via Universal Serial 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 Disable all interrupts Disable GIE PEIE TMROIE INTOIE RBIE INTCON 0 INTCON2 OxF5 INTCON3 0 0 Disable Priority Levels interrupts RCON IPEN 0 1 0 PIE2 0 PIRI 0 PIR2 0 Configure all ports with analog function as digital ADCON1
53. Soft I2C Config Prototype void Soft I2C Config char port const char SDI const char 5 0 const char SCK Description Configures software Parameter port specifies port of MCU on which SDA and SCL pins are located Parameters SCL and SDA need to be in range 0 7 and cannot point at the same pin Soft I2C Config needs to be called before using other functions from Soft I2C Library Example Soft I2C Config PORTB 1 2 25l MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot making 42 simple MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Soft_I2C_Start Prototype void Soft I2C Start void Description Issues START signal Needs to be called prior to sending and receiving data Requires Soft PC must be configured before using this function See Soft I2C Config Example Soft I2C Start Soft_I2C_Read Prototype char Soft I2C Read char ack Returns Returns one byte from the slave Description Reads one byte from the slave and sends not acknowledge signal if parameter ack is 0 otherwise it sends acknowledge Requires START signal needs to be issued in order to use this function See Soft_I2C Start Example tmp Soft I2C Read 0 Read data send not acknowledge signal MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 255 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct
54. T10SO RC7 RX DT RC1 T10SI_ RC6 TX CK RC2 CCP1 RC5 RC3 RC4 4MHz RDO PSPO RD3 PSP3 RD1 PSP1 RD2 PSP2 330R 22 gt DAD MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS RS 485 Library RS 485 is a multipoint communication which allows multiple devices to be con nected to a single signal cable mikroC provides a set of library routines to provide you comfortable work with RS 485 system using Master Slave architecture Master and Slave devices interchange packets of information each of these pack ets containing synchronization bytes CRC byte address byte and the data Each Slave has its unique address and receives only the packets addressed to it Slave can never initiate communication It is programmer s responsibility to ensure that only one device transmits via 485 bus at a time RS 485 routines require USART module on PORTC Pins of USART need to be attached to RS 485 interface transceiver such as LTC485 or similar Pins of trans ceiver Receiver Output Enable and Driver Outputs Enable should be connected to PORTC pin 2 check the figure at end of the chapter Note Address 50 is the common address for all Slaves packets containing address 50 will be received by all Slaves The only exceptions are Slaves with addresses 150 and 169 which require their particular address to be specified in th
55. UART Library Sound Library USART Library USB HID Library Util Library ANSI C Standard Libraries Conversions Library Trigonometry Library 229 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS ADC Library ADC Analog to Digital Converter module is available with a number of PIC MCU models Library function Adc_Read is included to provide you comfortable work with the module Adc_Read Prototype unsigned Adc Read char channel Returns 10 bit unsigned value read from the specified ADC channel Description Initializes PIC s internal ADC module to work with RC clock Clock determines the time period necessary for performing AD conversion min 12TAD Parameter channel represents the channel from which the analog value is to be acquired For channel to pin mapping please refer to documentation for the appropriate PIC MCU Requires PIC MCU with built in ADC module You should consult the Datasheet documentation for specific device most devices from PIC16 18 families have it Before using the function be sure to configure the appropriate TRISA bits to designate the pins as input Also configure the desired pin as analog input and set Vref voltage reference value The function is currently unsupported by the following PICmicros P18F2331 P18F2431 P18F4331 and P18F4431 Example unsigned tmp
56. Wr 2 Send byte address of EEPROM location I2C Wr OxFO0 Send data data to be written I2C Stop Delay ms 100 I2C Start Issue I2C start signal I2C Wr 0xA2 Send byte via I2C device address W I2C Wr 2 Send byte data address I2C Repeated Start Issue I2C signal repeated start I2C Wr 0xA3 Send byte device address PORTB I2C Rd 0u Read the data NO acknowledge I2C Stop MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple HW Connection 5V 5V PIC16F877A 1 MCLR Vpp THV RB7 PGD RAO ANO RB6 PGC x x RA1 AN1 RB5 e RA2 AN2 Vref RB4 RAS AN3 Vref RB3 PGM RA4 TOCKI RB2 RAS AN4 RB1 p 9 o REO RD AN5 RBO INT t 6 r 45V RET WRIANG Vdd T RE2 CS AN7 Vss Vdd RD7 PSP7 Vss RD6 PSP6 OSC1 RD5 PSP5 i OSC2 RD4 PSP4 RCO T10SO RC1 T10SI RC6 TX CK RC2 CCP1 RCS RC3 RC4 RDO PSPO RD3 PSP3 RD1 PSP1 RD2 PSP2 EM 24C04 ally d Q 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Keypad Library mikroC provides library for working with 4x4 keypad routines can also be used with 4x1 4x2 or 4x3 keypad Check the connection sc
57. any embedded macro identifiers eligible for expansion d 22693 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 20 MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Here is a simple example A simple macro which returns greater of its 2 arguments define B gt B A Let s call it x c Preprocessor will transform the previous line into x a b gt d a b It is highly recommended to put parentheses around each of the arguments in macro body this will avoid possible problems with operator precedence Undefining Macros You can undefine a macro using the undef directive undef macro_identifier Directive undef detaches any previous token sequence from the macro_iden tifier the macro definition has been forgotten and the macro_identifier is undefined No macro expansion occurs within undef lines The state of being defined or undefined is an important property of an identifier regardless of the actual definition The ifdef and ifndef conditional direc tives used to test whether any identifier is currently defined or not offer a flexible mechanism for controlling many aspects of a compilation After a macro identifier has been undefined it can be redefined with define using the same or a different token sequence MIKROG C COMP
58. as its argument define CAN MASK Bl 0 define CAN MASK B2 1 CAN FILTER CAN FILTER constants define filter codes Function canSet Filter expects one of these as its argument define CAN FILTER B1 F1 define CAN FILTER B1 F2 define CAN FILTER B2 F1 define CAN FILTER B2 F2 define CAN FILTER B2 define CAN FILTER B2 F4 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS d Z9 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Library Example unsigned short aa aal len aa2 unsigned char data 8 long id unsigned short zr cont oldstate void main PORTC TRISC PORTD TRISD aal 2 ooo i D gt gt Form value to be used with CANSendMessage aal TX PRIORITY 0 amp CAN TX XTD FRAME amp CAN TX NO RTR FRAME Form value to be used with CANInitialize aa CONFIG SAMPLE THRICE amp 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 data 0 0 Initialize CAN CANInitialize 1 1 3 3 1 aa Set CAN to CONFIG mode CANSetOperationMode MODE CONFIG OxFF continues 50 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making a dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS continued Set all mask1 bits to ones CANSetMask CA
59. at sector address sector Read data 1s stored in the array data Function returns 0 if read was successful or 1 if an error occurred Requires Library needs to be initialized see Init Example error Mmc Read Sector sector data Mmc Write Sector Prototype unsigned short Mmc Write Sector unsigned long sector char data Returns Returns 0 if write was successful returns 1 if there was an error in sending write com returns 2 if there was an error in writing Description Function writes 512 bytes of data to MMC card at sector address sector Function returns 0 if write was successful or 1 if there was an error in sending write command or 2 if there was an error in writing Requires Library needs to be initialized see Init Example error Mmc Write Sector sector data MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2022 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Mmc_Read_Cid Prototype unsigned short Mmc Read Cid unsigned short data for registers Returns Returns 0 if read was successful or 1 if an error occurred Description Function reads CID register and returns 16 bytes of content into data for registers Requires Library needs to be initialized see Init Example error Mmc Read Cid data Mmc Read Csd Prototype unsigned short Mmc
60. char color Description Similar to Line draws a horizontal line on the GLCD from y to x2 y Requires GLCD needs to be initialized See Glcd_Init Example Glcd H Line 0 127 0 1 COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Glcd Rectangle Prototype void Glcd Rectangle unsigned short x1 unsigned short yl unsigned short x2 unsigned short y2 char color Description Draws a rectangle on the GLCD Parameters x1 y1 set the upper left corner x2 y2 set the bottom right corner Parameter color defines the border 0 draws an empty border clear dots 1 draws a solid border put dots and 2 draws a smart bor der invert each dot Requires GLCD needs to be initialized See Glcd_Init Example Gled Rectangle 10 0 30 35 1 Box Prototype void Glcd Box unsigned short x1 unsigned short yl unsigned short x2 unsigned short y2 char color Description Draws a box on the GLCD Parameters x1 y1 set the upper left corner x2 y2 set the bottom right corner Parameter color defines the fill 0 draws a white box clear dots 1 draws a full box put dots and 2 draws an inverted box invert each dot Requires GLCD needs to be initialized See Glcd_Init Example Box 10 0 30 35 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 22 3
61. declarations from the previous example Declare and initialize dots p and struct Dot p 1 1 q 3 7 0 5 Initialize already declared circles ol and o2 ol 1 0 is 1 center is at 0 0 o2 4 1 2 3 is 4 center is at 1 2 3 Incomplete Declarations Incomplete declarations are also known as forward declarations A pointer to a structure type A can legally appear in the declaration of another structure B before A has been declared struct A incomplete struct B struct A pa struct A struct B pb The first appearance of A is called incomplete because there is no definition for it at that point An incomplete declaration is allowed here because the definition of B doesn t need the size of A Untagged Structures and Typedefs If you omit the structure tag you get an untagged structure You can use untagged structures to declare the identifiers in the comma delimited struct id list to be of the given structure type or derived from it but you cannot declare addition al objects of this type elsewhere It is possible to create a typedef while declaring a structure with or without a tag typedef struct Mystruct Mystruct s ps arrs 10 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 7 15 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Structure Assignment Variables of same structured type ma
62. e g k k or postfix e g k k When used as prefix operators and preincrement and predecrement add or subtract one from the value of operand before the evaluation When used as suffix operators and add or subtract one from the value of operand after the evalu ation For example int j 5 j k k 1 1 which gives us j 6 6 int j 5 j k j 1 which gives us j 5 6 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 0 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Relational Operators Use relational operators to test equality or inequality of expressions If the expres sion evaluates to true it returns 1 otherwise it returns 0 All relational operators associate from left to right Relational Operators Overview Operator Operation Precedence equal 9 not equal 9 gt greater than 10 lt less than 10 gt greater than or equal 10 lt less than or equal 10 Relational Operators in Expressions Precedence of arithmetic and relational operators was designated in such a way to allow complex expressions without parentheses to have expected meaning 5 gt 1 0 i e 5 gt c 1 0 e Always bear in mind that relational operators return either 0 or 1 Consider the fol lowing examples 8 13 gt returns 0
63. evaluates and expression2 is ignored The result will be the value of either expression2 expression3 depending upon which evaluates The fact that only one of these two expressions evaluates is very important if you expect them to produce side effects Conditional operator associates from right to left Here are a couple of practical examples Find max a b max gt b a b Convert small letter to capital no parentheses are actually necessary gt amp amp C lt 7 32 Conditional Operator Rules 1 must be a scalar expression expression2 and expression3 must obey one of the following rules 1 Both of arithmetic type expression2 and expression3 are subject to the usual arithmetic conversions which determines the resulting type 2 Both of compatible struct or union types The resulting type is the structure or union type of expression2 and expression3 3 Both of void type The resulting type is void MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 MS mikroC MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making e simple 4 Both of type pointer to qualified or unqualified versions of compatible types The resulting type is a pointer to a type qualified with all the type qualifiers of the types pointed to by both operands 5 One operand is a pointer and the other is a null pointer constant The resultin
64. example 0611101 will be treated as short Octal Constants 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 suf fixes 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 You can omit either the decimal integer or the decimal fraction but not both You can omit either the decimal point or the letter e or E and the signed integer expo nent but not both These rules allow for conventional and scientific exponent notations Negative floating constants are taken as positive constants with the unary operator minus prefixed mikroC limits floating point constants to range 1 17549435082 38 6 80564774407 38 mikroC floating point constants are of type double Note that mikroC s imple mentation of ANSI Standard considers 1oat and double together with the long double variant to be the same type MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Character Constants A character constant is one or more characters enclosed in single quotes such as A
65. given below Would you like to become mikroElektronika s distributor We in mikroElektronika are looking forward to new partnerships If you would like to help us by becoming distributor of our products please let us know Other If you have any other question comment or a business proposal please contact us mikroElektronika Admirala Geprata 1B 11000 Belgrade EUROPE Phone 381 11 30 66 377 381 11 30 66 378 Fax 381 11 30 66 379 E mail office mikroelektronika co yu Website www mikroelektronika co yu BOA MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS
66. id is CANSPI message identifier Only 11 or 29 bits may be used depend ing on message type standard or extended data is array of bytes up to 8 bytes in length datalen is data length from 1 8 CAN TX MSG FLAGS is value formed from constants see CAN constants Requires CANSPI must be in Normal mode Example char tx data long id tx CAN TX PRIORITY 0 amp CAN TX XTD FRAME CANSPIWrite id data 2 tx 156 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example The code is a simple demonstration of CANSPI protocol It is a simple data exchange between 2 PIC s where data is incremented upon each bounce Data is printed on PORTC lower byte and PORTD higher byte for a visual check char data 8 aa aal len aa2 long id char zr const char TRUE OxFF const char FALSE 0x00 void main TRISB 0 Spi_Init Initialize SPI module TRISC F2 0 Clear TRISC 2 PORTC F2 0 Clear 2 PORTC F0 1 Set PORTC 0 TRISC F0 0 Clear TRISC 0 PORTD 0 TRISD 0 aa 0 1 0 2 0 Form value to be used with CANSPIInitialize aa CONFIG SAMPLE THRICE CAN CONFIG PHSEG2 PRG ON amp CAN CONFIG STD MSG amp CAN CONFIG DBL BUFFER ON amp CAN CONFIG VALID XTD MSG PORTC F2 1 Set PORTC 2
67. identifiers with optional initial izers Each of the variables is declared to be of type if omitted type defaults to int Specifier storage class can take values extern static register the default auto Optional type qualifier can take values const or volatile For more details refer to Storage Classes and Type Qualifiers Here is an example of variable declaration Create 3 integer variables called x y and z and initialize x and y to the values 1 and 2 respectively int x 1 2 Z z remains uninitialized These are all defining declarations storage is allocated and any optional initializ ers are applied SE MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making amp simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS An executable program is usually created by compiling several independent trans lation units then linking the resulting object files with preexisting libraries The term translation unit refers to a source code file together with any included files but less any source lines omitted by conditional preprocessor directives A problem arises when the same identifier is declared in different scopes for example in dif ferent files or declared more than once in the same scope Linkage is the 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 rel
68. it allows you to use comma as a sequence opera tor to form the so called comma expressions or sequences Comma expression is a comma delimited list of expressions it is formally treated as a single expression so it can be used in places where an expression is expected The following sequence expression_1 expression_2 results in the left to right evaluation of each expression with the value and type of expression 2 giving the result of the whole expression Result of expres sion 1is discarded MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple Binary operator comma has the lowest precedence and associates from left to right so thata b cissameas a b c This allows us to write sequences with any number of expressions expression 1 expression 2 expression n this 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 5 b 2 c returns preincremented value of variable c but also intializes a divides b by 2 and increments c result 10 y 3 X Z X 3 y returns computed value of variable z and also computes x and y Note Do not confuse comma operator sequen
69. line continuation symbol MIKROC C COMPILER FOR MICROCHIP MICROCONTROLLERS 460 amp simples Now the following code LCD PRINT temp will be preprocessed to this Lcd Out Cp temp Lcd Out Cp IntToStr temp Operator Operator 1s used for token pasting you can paste or merge two tokens togeth er by placing in between them plus optional whitespace on either side The preprocessor removes the whitespace and the combining the separate tokens into one new token This is commonly used for constructing identifiers For example we could define macro SPLICE for pasting two tokens into one iden tifier define SPLICE x y x HH y Now the call SPLICE cnt 2 expands to identifier 2 Note mikroC 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 mikroC supports conditional compilation by replacing the appropriate source code lines with a blank line conditional compilation directives must be completed in the source or include file in which they are begun d 2 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Directives if elif else and The conditional direc
70. of the following literals enumeration con stants 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 You can use a constant expression anywhere that a constant is legal MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple KEYWORDS Keywords are words reserved for special purposes and must not be used as normal identifier names Beside standard C keywords all relevant SFR are defined as global variables and represent reserved words that cannot be redefined for example TMRO PCL etc Probe the Code Assistant for specific letters Ctrl Space in Editor or refer to Predefined Globals and Constants Here is the alphabetical listing of keywords in C asm enum signed auto extern sizeof break float static case for struct char goto switch const if typedef continue int union default long unsigned do register void double return volatile else short while Also mikroC includes a number of predefined identifiers used in libraries You could replace these by your own definitions if you plan to develop your own libraries For more information see mikroC Libraries 5 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MIC
71. of the newly expanded text This allows for the possibility of nested macros The expanded text can contain macro identifiers that are subject to replacement However if the macro expands into what looks like a preprocessing directive such a directive will not be recognized by the preprocessor Any occurrences of the macro identifier found within literal strings character constants or comments in the source code are not expanded d AO MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS A macro won t be expanded during its own expansion so define MACRO MACRO won t expand indefinitely Let s have an example Here are some simple macros define ERR MSG Out of range define EVERLOOP for which we could use like this main EVERLOOP if error Lcd Out Cp ERR MSG break Attempting to redefine an already defined macro identifier will result in a warning unless the new definition is exactly the same token by token definition as the existing one The preferred strategy where definitions might exist in other header files is as follows ifndef BLOCK SIZE define BLOCK SIZE 512 The middle line is bypassed if BLOCK SIZE is currently defined if BLOCK SIZE Is not currently defined the middle line is invoked to define it MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS p
72. originally declared to be point ing to void You can assign a void pointer to a non void pointer refer to Void Type for details 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 Instead of zero the mnemonic NULL defined in the stan dard library header files such as stdio h can be used for legibility All pointers can be successfully tested for equality or inequality to NULL For example int pn 0 Here s one null pointer int pn NULL This is an equivalent declaration We can test the pointer like this if pn Las or like this if NULL MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 89 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Pointer Arithmetic Pointer arithmetic in C is limited to assigning one pointer to another comparing two pointers comparing pointer to zero NULL adding subtracting pointer and an integer value subtracting two pointers The internal arithmetic performed on pointers depends on the memory model in force and the presence of any overriding pointer modifiers When performing arithmetic with pointers it is assumed that the pointer points to an array of objects Arrays and Pointers Arrays and pointers are not completely in
73. program in which the identifier can be used to access its object There are different categories of scope block or local function function prototype and file These depend on how and where identifiers are declared Block Scope The scope of an identifier with block or local scope starts at the declaration point and ends at the end of the block containing the declaration such a block is known as the enclosing block Parameter declarations with a function definition also have block scope limited to the scope of the function body File Scope 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 Scope The only identifiers having function scope are statement labels Label names can be used with goto statements anywhere in the function in which the label is declared Labels are declared implicitly by writing label_name followed by a statement Label names must be unique within a function Function Prototype Scope Identifiers declared within the list of parameter declarations in a function proto type not part of a function definition have function prototype scope This scope ends at the end of the function prototype Tag Scope Structure union and enumeration tags are somewhat specific in mikroC Due to separate name space tags are virtually removed from normal scope rules they have file scope but override any bloc
74. simple Soft_I2C_Write Prototype char Soft I2C Write char data Returns Returns 0 if there were no errors Description Sends data byte parameter data via PC bus Requires START signal needs to be issued in order to use this function See Soft I2C Start Example Soft I2C Write 0xA3 Soft I2C Stop Prototype void Soft I2C Stop void Description Issues STOP signal Requires START signal needs to be issued in order to use this function See Soft I2C Start Example Soft I2C Stop Age 256 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example The example demonstrates use of Software I C Library PIC MCU is connected SCL SDA pins to PCF8583 RTC real time clock Program sends date data to RTC void main Soft I2C Config amp PORTD 4 3 Initialize full master mode Soft I2C Start Issue start signal Soft I2C Write 0xAO0 Address PCF8583 Soft I2C Write 0 Start from word at address 0 config word Soft I2C Write 0x80 Write 0x80 to config pause counter Soft I2C Write 0 Write 0 to cents word Soft I2C Write 0 Write 0 to seconds word Soft I2C Write 0x30 Soft I2C Write 0x11 Soft I2C Write 0x30 Soft I2C Write 0x08 2 Write 0x30 to minutes word Write 0x11 to hours word Write 0x24 to
75. the ARP event on the NIC Requires As specified for the entire library Example Eth Arp Response Eth Get Info Prototype void Eth Get Icmp Info void Description Loads ICMP protocol information from the header of the received ICMP packet and stores it to the PIC s Ethernet variables Requires The card NIC must be properly initialized See Eth Init Also this function must be called in a proper sequence and before the Eth Ping Response Example Eth Get Icmp Info Eth Ping Response Prototype void Eth Ping Response void Description An automated ICMP Ping response User should call this function when answerring to an ICMP IP event Requires As specified for the entire library Example Eth Ping Response MIKROELEKTRONIKA DEVELOPMENT TOOLS Books COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Eth_Get_Udp_Source_Port Prototype unsigned Eth Get Udp Source Port void Returns Returns the source port socket of the received UDP packet Description The function returns the source port socket of the received UDP packet After the reception of valid IP packet is detected and its type is determined to be UDP the UDP packet header must be interpreted UDP source port is the first data in the UDP header Requires This function must be called in a proper sequence 1 e immediately aft
76. the entire running time of the program or dur ing execution of some blocks of code Storage class can be established by the syntax of the declaration by its placement in the source code or by both of these factors storage class type identifier The storage class specifiers in mikroC are auto register static extern Auto Use the auto modifer to define a local variable as having a local duration This is the default for local variables and is rarely used You cannot use auto with glob als See also Functions Register By default mikroC stores variables within internal microcontroller memory Thus modifier register technically has no special meaning mikroC compiler simply ignores requests for register allocation MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 839 MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple Static Global name declared with static specifier has internal linkage meaning that it is local for a given file See Linkage for more information Local name declared with 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 Name declared with extern specifier has external linkage unless it has been pre viously declared as having internal linkage Declaration is not a definition if it has extern specifier and is not initialized The keywo
77. to make assumptions concerning the value of the object while evaluating expressions in which it occurs because the value could change at any moment MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Typedef Specifier Specifier typedef introduces a synonym for a specified type You can use type def declarations to construct shorter or more meaningful names for types already defined by the language or for types that you have declared You cannot use the typedef specifier inside a function definition The specifier typedef stands first in the declaration typedef lt type definition gt synonym The typedef keyword assigns the synonym to the lt type definition gt The synonym needs to be a valid identifier Declaration starting with the typedef specifier does not introduce an object or function of a given type but rather a new name for a given type That is the typedef declaration is identical to 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 C 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 typedef declaration as in any declaration you can declare several types at once For example typedef int
78. to prepare hardware for output Example To play sound of IKHz T 1 f 1000 cycles 4MHz This gives us our first parameter 1000 10 100 Play 150 periods like this Sound Play 100 150 Zl MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Library Example The example is a simple demonstration of how to use sound library for playing tones on a piezo speaker The code can be used with any MCU that has PORTB and ADC on PORTA Sound frequencies in this example are generated by reading the value from ADC and using the lower byte of the result as base for T f 1 T int adcValue void main PORTB 0 Clear PORTB TRISB 0 PORTB is output INTCON 0 Disable all interrupts ADCON1 0x82 Configure VDD as Vref and analog channels TRISA OxFF PORTA is input Sound Init PORTB 2 Initialize sound on RB2 while 1 Play in loop adcValue ADC Read 2 Get lower byte from ADC Sound Play adcValue 200 Play the sound MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS A226 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple SPI Library SPI module is available with a number of PIC MCU models mikroC provides a library for initializing Slave mode and comfortable work with Master mode PIC can easily communicate with other devices via SPI A D c
79. unsigned short Sd Write Sector unsigned long sector char data Returns Returns 0 if write was successful returns 1 if there was an error in sending write com returns 2 if there was an error in writing Description Function writes 512 bytes of data to SD card at sector address sector Function returns 0 if write was successful or 1 if there was an error in sending write command or 2 if there was an error in writing Requires Library needs to be initialized see 54 Init Example error 54 Write Sector sector data page SS 250 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot making amp imple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Sd_Read_Cid Prototype unsigned short Sd Read Cid unsigned short data for registers Returns Returns 0 if read was successful or 1 if an error occurred Description Function reads CID register and returns 16 bytes of content into data for registers Requires Library needs to be initialized see 54 Init Example error 54 Read Cid data Sd Read Csd Prototype unsigned short Sd Read Csd unsigned short data for registers Returns Returns 0 if read was successful or 1 if an error occurred Description Function reads CSD register and returns 16 bytes of content into data for registers Requires Library needs to be initialized see 54 Init Example error Sd Read Cs
80. within which an identifier must be unique C uses four distinct categories of identifiers Goto label names These must be unique within the function in which they are declared Structure union and enumeration tags These must be unique within the block in which they are defined Tags declared outside of any function must be unique Structure and union member names These 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 Variables typedefs functions and enumeration members These must be unique within the scope in which they are defined Externally declared identifiers must be unique among externally declared variables Duplicate names are legal for different name spaces regardless of scope rules For example int blue 73 open a block enum colors black red green blue violet white c enumerator blue hides outer declaration of int blue struct colors int i j ILLEGAL colors duplicate tag double red 2 ILLEGAL redefinition of red blue 37 back in int blue scope 56 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS DURATION Duration closely related to storage class defines the period during which the declared identifiers have real physical objects allocated i
81. year date word Write 0x08 to weekday month Soft I2C Stop Issue stop signal Soft I2C Start Tssue start signal Soft I2C Write 0xAO0 Address PCF8530 Soft I2C Write 0 Start from word at address 0 Soft I2C Write 0 Write 0 to config word enable counting Soft I2C Stop Issue stop signal M MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 25 7f MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Software SPI Library mikroC provides library which implement software SPI These routines are hard ware independent and can be used with any MCU You can easily communicate with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc Note These functions implement time based activities so interrupts need to be disabled when using the library Library Routines Soft_Spi_Config Soft_Spi_Read Soft_Spi_Write Soft_Spi_Config Prototype void Soft_Spi_Config char port const char SDI const char SDO const char SCK Description Configures and initializes software SPI Parameter port specifies port of MCU on which SDI SDO and SCK pins will be located Parameters SDI SDO and SCK need to be in range 0 7 and cannot point at the same pin Soft_Spi_Config needs to be called before using other functions from Soft SPI Library Example This will set SPI to master mode clock 50kHz data sampled at the middle of interval clock id
82. 0 200 OK nContent type text html n lt html gt n lt body gt n lt 1 gt 11 0 world lt h1 gt n lt body gt n lt html gt PE Eth Set Tcp Data httpPagel Lf sve Eth_Tcp_Response Prototype void Eth Tcp Response void Description Performs user response to TCP IP event User specifies data to be sent depending on the request received HTTP HTTPD FTP etc This is performed by the function Eth Set Tcp Data Requires Hardware requirements are as specified for the entire library Prior to using this func tion user must prepare the data to be sent through TCP see Eth Set Tcp Data Example Eth Tcp Response a au MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS mikroC making a simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example Check the supplied Ethernet example in the Examples folder HW Connection 200 5V K T1 FL1012 es 1K 8 9 3 10 6 n 5V 3 14 J2 0 1u 5V m 2 15 1 16 RJ45 7 0 1u 0 1u 0 1u co co SR 1 s RTL8019AS lt RD3 U5 lt 02 RES IOW IOR
83. 18 imple mented as a lookup table maximum error obtained is 1 Example res SinE3 45 result is 707 CosE3 Prototype int CosE3 unsigned angle deg Returns Function returns the cosine of input parameter multiplied by 1000 1E3 and rounded up to the nearest integer The range of return values is from 1000 to 1000 Description Function takes parameter angle deg which represents angle in degrees and returns its cosine multiplied by 1000 and rounded up to the nearest integer The function is imple mented as a lookup table maximum error obtained is 1 Example res CosE3 196 result is 193 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS X03 mikroC MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 4 94 Contact us If you are experiencing problems with any of our products or you just want addi tional information please let us know Technical Support for compiler If you are experiencing any trouble with mikroC please do not hesitate to con tact us itis in our mutual interest to solve these issues Discount for schools and universities mikroElektronika offers a special discount for educational institutions If you would like to purchase mikroC for purely educational purposes please contact us Problems with transport or delivery If you want to report a delay in delivery or any other problem concerning distri bution of our products please use the link
84. 2C Stop I2C Init Prototype void I2C Init long clock Description Initializes PC with desired clock refer to device data sheet for correct values in respect with Fosc Needs to be called before using other functions of I2C Library Requires Library requires MSSP module on PORTB or PORTC Example I2C Init 100000 Page ES a MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroG I tkde I2C Start Prototype char I2C Start void Returns If there is no error function returns 0 Description Determines if PC bus is free and issues START signal Requires PC must be configured before using this function See I2C Init Example I2C Start I2C Repeated Start Prototype void I2C Repeated Start void Description Issues repeated START signal Requires PC must be configured before using this function See I2C Init Example I2C Repeated Start I2C Is Idle Prototype char I2C Is Idle void Returns Returns 1 if PC bus is free otherwise returns 0 Description Tests if I C bus is free Requires PC must be configured before using this function See I2C Init Example if I2C Is Idle MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROOR POMPILER EOR MIEROENIR PIC MIEROCONTROATT ERN making 42 simple I2C Rd Prototype char I2C Rd char ack
85. 5 SPP5 P1B OSC2 CLKO RAG RD4 SPP4 TEM CN4 RCO T1OSO T13CKI RC7 RX DT SDO vec RCI TIOSUCCP2 UOE RC6 TXICK D RC2 CCP1 P1A RC5 D VP D Vusb RC4 D IVM GND RDO SPPO RD3 SPP3 1 USBB RD1 SPP1 RD2 SPP2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 72 9 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Util Library Util library contains miscellaneous routines useful for project development Button Prototype char Button char port char pin char time char active state Returns Returns 0 or 255 Description Function eliminates the influence of contact flickering upon pressing a button debounc ing Parameters port and pin specify location of the button parameter time specifies the minimum time pin has to be in active state in order to return TRUE parameter active state can be either 0 or 1 and it determines if button is active upon logical zero or logical one Example 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 amp amp Button amp PORTB 0 1 0 PORTD PORTD oldstate 0 while 1 Age 22209300 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS ANSI C Ctype Li
86. 55 equals 1 0x1234 equals OxEDCB 0x1234 equals 0 1 OB MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Logical Operators Operands of logical operations are considered true or false that 1s non zero or zero Logical operators always return 1 or 0 Operands in a logical expression must be of scalar type Logical operators amp amp and associate from left to right Logical negation operator associates from right to left Logical Operators Overview Operator Operation Precedence amp amp logical AND 5 1 logical OR 4 logical negation 14 Precedence of logical relational and arithmetic operators was chosen in such a way to allow complex expressions without parentheses to have expected meaning 9 gt 0 688 c lt 9 at1 b 1 reads as reads as Logical AND amp amp returns 1 only if both expressions evaluate to be nonzero oth erwise returns 0 If the first expression evaluates to false the second expression is not evaluated For example gt 66 lt reads a b 6868 c d if a b is false 0 c d will not be evaluated Logical OR returns 1 if either of the expressions evaluate to be nonzero oth erwise returns 0 If the first expression evaluates to true the second
87. 6 only Requires Ports must be initialized See C Init Example Cf File Write Init Cf File Write Byte Prototype void Cf File Write Byte char data Description Adds one byte data to file You can supply ASCII value as parameter for example 48 for zero Requires CF must be initialized for file write operation See C File Write Init Example Write 50 000 zeroes bytes to file for 1 0 lt 50000 1 Cf File Write Byte 48 Cf Read Sector Prototype void Cf Read Sector int sector number unsigned short buffer Description Reads one sector sector number into buffer Requires CF must be initialized for file write operation See C Init Example Cf Read Sector 22 data COMPILER FOR MiCROCHIP MICROCONTROLLERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Cf_Write_Sector Prototype void Cf Write Sector int sector number unsigned short buffer Description Writes value from buffer to CF sector at sector number Requires CF must be initialized for file write operation See C Init Example Cf Write Sector 22 data Cf Set File Date Prototype void Cf Set File Date int year char month day hours min sec Description Writes system timestamp to a file Use this routine before finalizing a file otherwise file will be a
88. ALID XTD MSG CAN CONFIG LINE FILTER OFF CANSPISetBaudRate 1 1 3 3 1 init 5G MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS CANSPISetMask Prototype void CANSPISetMask char CAN MASK long value char CAN CONFIG FLAGS Description Function sets mask for advanced filtering of messages Given value is bit adjusted to appropriate buffer mask registers Parameters 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 Requires CANSPI must be in Config mode otherwise the function will be ignored Example Set all mask bits to 1 i e all filtered bits are relevant CANSPISetMask CAN MASK B1 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 CANSPISetFilter Prototype void CANSPISetFilter char CAN FILTER long value char CAN CONFIG FLAGS Description Function sets mask for advanced filtering of messages Given value is bit adjusted to appropriate buffer mask registers Parameters MASK is one of predefined constant values see CAN constants value is the filter register value CAN CONFIG FLAGS selects t
89. CROCONTROLLERS making ct simple BUILT IN ROUTINES mikroC compiler provides a set of useful built in utility functions Built in func tions do not require any header files to be included you can use them in any part of your project Currently mikroC includes following built in functions Delay_us Delay ms Delay Cyc Clock Khz Delay us Prototype void Delay us const time in us Description Creates a software delay in duration of time in us microseconds a constant Range of applicable constants depends on the oscillator frequency Example Delay us 10 microseconds pause Delay ms Prototype void Delay ms const time in ms Description Creates a software delay in duration of time in ms milliseconds a constant Range of applicable constants depends on the oscillator frequency Example Delay ms 1000 One second pause page 0 0 0 A5 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot making simple cee eee ee eee il i Z E CEMPICER a Sn pana AN bay esi Vdelay_ms Prototype void Vdelay ms unsigned time in ms Description Creates a software delay in duration of time in ms milliseconds a variable Generated delay is not as precise as the delay created by Delay ms Example pause 1000 Vdelay ms pause one second pause Delay Cyc Prototype void Delay Cyc char Cycles div by 10 Description Create
90. DAC module is 5 V In this exam ple the entire DAC s resolution range 12bit 4096 increments is covered meaning that you ll need to hold a button for about 7 minutes to get from mid range to the end of range const char CHIP SELECT 1 TRUE OxFF unsigned value void InitMain Soft SPI Config amp PORTB 4 5 3 TRISB amp CHIP SELECT ClearBit TRISC CHIP SELECT TRISC 0x03 DAC increments 0 4095 output voltage 0 Vref void DAC Output unsigned valueDAC char temp PORTB amp CHIP SELECT ClearBit PORTC CHIP SELECT temp valueDAC 8 amp OxOF Prepare hi byte for transfer temp 0x30 It s a 12 bit number so only Soft Spi Write temp lower nibble of high byte is used temp valueDAC Prepare lo byte for transfer Soft Spi Write temp PORTB _CHIP SELECT SetBit PORTC CHIP SELECT void main InitMain DAC Output 2048 When program starts DAC gives value 2048 the output in the mid range while 1 Main loop if Button amp PORTC 0 1 1 TRUE Test button on BO increment amp amp value 4095 value eise if Button amp PORTC 1 1 1 TRUE If RBO is not active then test amp amp value gt 0 RB1 decrement value DAC Output value Perform output Delay 100 Slow down key repeat pace page ES 2S0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS CO
91. E eo eee eee LongToStr Prototype void LongToStr long number char output Description Function creates an output string out of a large signed number numerical value of long type Output string has fixed width of 11 characters remaining positions on the left 1f any are filled with blanks Example long jj 3700000 char txt LongToStr jj txt is 3700000 three blanks here FloatToStr Prototype void FloatToStr float number char output Description Function creates an output string out of a floating point number The output string contains a normalized format of the number mantissa between 0 and 1 with sign at the first position Mantissa has fixed format of six digits 0 ddddd i e there will always be 5 digits following the dot The output string must be at least 13 characters long Example float ff 374 2 char txt ferus FloatToStr ff txt txt is 0 37420e3 Bcd2Dec Prototype unsigned short Bcd2Dec unsigned short bcdnum Returns Returns converted decimal value Description Converts 8 bit BCD numeral bcdnunm to its decimal equivalent Example unsigned short a Bcd2Dec 0x52 equals 52 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 22004 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS MIKROELEKTRONIKA DEVELO
92. ERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS mikroBootloader mikroBootloader can be used only with PICmicros that support flash write Load the with the appropriate hex file using the conventional programming techniques e g for PIC16F877A use p16f877a hex 2 Start mikroBootloader from the drop down menu Tools gt 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 6 The last line in then history window should now read Connected 7 To start the upload just click on the Start Bootloader button 8 Your program will written to the PIC flash Bootloader will report an errors that may occur 9 Reset your PIC and start to execute 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 u
93. Example Glcd Fill 0 Clear screen Glcd Dot Prototype void Glcd Dot unsigned short x unsigned short y char color Description Draws a dot on the GLCD at coordinates x y Parameter color determines the dot state 0 clears dot 1 puts a dot and 2 inverts dot state Requires GLCD needs to be initialized See 1 Init Example Glcd Dot 0 0 2 Invert the dot in the upper left corner MIKROELEKTRONIKA DEVELOPMENT TOOLS Books COMPILERS MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Glcd Line Prototype void Glcd Line int x1 int yl int x2 int y2 char color Description Draws a line on GLCD from x1 1 to x2 y2 Parameter color determines the dot state 0 draws an empty line clear dots 1 draws a full line put dots and 2 draws a smart line invert each dot Requires GLCD needs to be initialized See Glcd_Init Example Glcd Line 0 63 50 0 2 Glcd V Line Prototype void Glcd V Line unsigned short yl unsigned short y2 unsigned short x char color Description Similar to GLcd Line draws a vertical line on GLCD from x y1 to x y2 Requires GLCD needs to be initialized See Glcd_Init Example Glcd V Line 0 63 0 1 Glcd H Line MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS Prototype void Glcd H Line unsigned short x1 unsigned short x2 unsigned short y
94. FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple STATISTICS After successful compilation you can review statistics of your code Select Project gt View Statistics from the drop down menu or click the Statistics icon There are Statistics Icon six tab windows Memory Usage Window Provides overview of RAM and ROM memory usage in form of histogram 9 Statistics Procedures Graph Procedures locations Procedures details RAM ROM RAM Memory Usage locations ROM Memory Usage locations 99 of 1 640 1 617 Free Free ROM 93 of 32 767 30 591 Free ROM 23 Used RAM 2 176 Used ROM 1 of 1 640 Free ROM Procedures Graph Window Displays functions in form of histogram according to their memory allotment Statistics Procedures locations Procedures details ROM ROM usage by procedure ROM locations CF Write Word CF Write Init CF Read Word CF Read Init CF Read Byte CF Init Port CF Detect CF Write Byte CF Set Reg Adr delay 1us 500 ROM locations d D MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making a simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Procedures Locations Window Displays how functions are distributed in microcontroller s memory Statistics Memory usage Procedures Graph Pro ions Procedures details RAM ROM Procedures by ROM location
95. File Name field modify the name of the file you want to save Click the Save button Closing a File 5 Close File Make sure that tab containing the file you want to close is the active tab Select File gt Close from drop down menu or right click the tab of the file you want to close in Code Editor If the file has been changed since it was last saved you will be prompted to save your changes MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple COMPILATION When you have created the project and written the source code you will want to compile it Select Project gt Build from drop down menu or click Build Icon or simply hit CTRL F9 Compile Icon Progress bar will appear to inform you about the status of compiling If there are errors you will be notified in the Error Window If no errors are encountered mikroC will generate output files Output Files Upon successful compilation mikroC will generate output files in the project fold er folder which contains the project file ppc Output files are summarized below Intel HEX file hex Intel style hex records Use this file to program PIC MCU Binary mikro Compiled Library mc1 Binary distribution of application that can be included in other projects List File 1st Overview of PIC memory allotment instruction addresses registers routin
96. Flash Memory Library 186 2 Library 188 Keypad Library 193 LCD Library 4 bit interface 197 LCD8 Library 8 bit interface 203 Graphic LCD Library 208 Manchester Code Library 219 Multi Media Card Library 224 OneWire Library 233 PS 2 Library 237 PWM Library 240 RS 485 Library 243 Secure Digital Library 249 Software I2C Library 254 Software SPI Library 258 Software UART Library 260 Sound Library 264 page 00000 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making a dimple MIKROC C COMPILER FOR MICROCHIP PIG MIBEECONTISEPEERE SPI Library 266 USART Library 271 USB HID Library 275 Util Library 280 ANSI C Ctype Library 281 ANSI C Math Library 285 ANSI C Stdlib Library 291 ANSI C String Library 295 Conversions Library 299 Trigonometry Library 303 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple page Ee E MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS CHAPTER mikroC IDE QUICK OVERVIEW mikroC is a powerful feature rich development tool for PICmicros It is designed to provide the customer with the easiest possible solution for developing applica tions for embedded systems without compromising performance or control PIC and C fit together well PIC is the most popular 8 bit chip in the world used
97. ICROCHIP MICROCONTROLLERS 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 code replacing specific lexical symbols with other symbols conditional compiling which conditionally includes or omits parts of code Note that preprocessor analyzes text at token level not at individual character level Preprocessor is controled by means of preprocessor directives and pre processor operators Preprocessor Directives Any line in source code with a leading is taken as a preprocessing directive or control line unless the is within a string literal in a character constant or embedded in a comment The initial can be preceded or followed by whitespace excluding new lines The null directive consists of a line containing the single character This line is always ignored Preprocessor directives are usually placed at the beginning of the source code but they can legally appear at any point in a program The mikroC preprocessor detects preprocessor directives and parses the tokens embedded in them Directive is in effect from its declaration to the end of the program file mikroC supports standard preprocessor directives null directive Hif define ifndef elif ifndef else include line error undef Note pragma directive is under construction MIK
98. IKA DEVELOPMENT TOOLS BOOKS COMPILERS 5 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Eth Set Inport Prototype unsigned short Eth Inport unsigned short address Returns One byte from the specified address Description Retrieves a byte from the specified address of the Ethernet card chip Requires The card NIC must be properly initialized See Eth Init Example udp length Eth Inport NIC DATA Eth Scan For Event Prototype unsigned Eth Scan For Event unsigned short next ptr Returns Type of the ethernet packet received Two types are distinguished ARP MAC IP address data request and IP Internet Protocol Description Retrieves sender s MAC hardware address and type of the packet received The function argument is an internal pointer to the next data packet RTL8019 s buffer and is of no particular importance to the end user Requires The card NIC must be properly initialized See Eth Init Also the function must be called in a proper sequence i e right after the card init and IP address UDP port init Example Eth Init amp PORTB amp PORTD amp PORTE 2 1 0 Eth Set Ip Address 192u 168u 20u 25u Eth Set Udp Port 10001 do Main block of every Ethernet example event type Eth Scan For Event amp next ptr if event type switch event type case ARP Arp Event break case IP Ip Event Eth Outpor
99. IKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Arithmetic Conversions When you use an arithmetic expression such as a b where and b are of differ ent arithmetic types mikroC performs implicit type conversions before the expres sion is evaluated These standard conversions include promotions of lower types to higher types in the interests of accuracy and consistency Assigning a signed character object such as a variable to an integral object results in automatic sign extension Objects of type signed char always use sign extension objects of type unsigned char always set the high byte to zero when converted to int Converting a longer integral type to a shorter type truncates the higher order bits and leaves low order bits unchanged Converting a shorter integral type to a longer type either sign extends or zero fills the extra bits of the new value depending on whether the shorter type is signed or unsigned respectively Note Conversion of floating point data into 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 First any small integral types are converted according to the following rules 1 char converts to int 2 signed char converts to int with the same value 3 short converts to int with the same value sig
100. IKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 0 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Similarly 0x1234 0x5678 equals 0x567C 0x1234 0x5678 equals 0x444C 0x1234 equals OxEDCB Bitwise Shift Operators Binary operators and move the bits of the left operand for 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 left most bits are discarded and new bytes on the right are assigned zeros Thus shifting unsigned operand to left by n positions is equivalent to multiplying it by 2n if all the discarded bits are zero This is also true for signed operands if all the discarded bits are equal to sign bit 000001 5 equals 000040 0x3801 lt lt 4 equals 0x8010 overflow With shift right gt gt right most bits are discarded and the freed bytes on the left are assigned zeros in case of unsigned operand or the value of the sign bit zeros in case of signed operand Shifting operand to right by n positions is equiv alent to dividing it by 2n OxFF56 gt gt 4 equals 5 OxFF56u gt gt 4 equals 0x0FF5 Bitwise vs Logical Be aware of the principle difference between how bitwise and logical operators work For example 0222222 amp 0555555 equals 000000 0222222 amp amp 05555
101. ILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple 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 c see Projects for more information The syntax of include directive has two formats include lt header_name gt include header name The preprocessor removes the include line and replaces it with the entire text of the header file at that point in the source code The placement of the include can therefore influence the scope and duration of any identifiers in the included file The difference between the two formats lies in the searching algorithm employed in trying to locate the include file If include directive was used with the lt header_name gt version the search is made successively in each of the following locations in this particular order 1 mikroC installation folder gt include folder 2 your custom search paths The header_name version specifies a user supplied include file mikroC will look for the header file in following locations in this particular order 1 the project folder folder which contains the project file ppc 2 mikroC installation folder gt include folder 3 your custom search paths Explicit Path If you place an explicit path in the header_name only that directory will be searched For example include C my_files tes
102. ILER FOR MICROCHIP PIG MICROCONTROLLERS __________________________ 44 2 CANSetBaudRate Prototype void CANSetBaudRate char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CAN CONFIG FLAGS Description 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 SJW as defined in 18 8 datasheet 1 4 BRP as defined 18 8 datasheet 1 64 PHSEG1 as defined in 18XXX8 datasheet 1 8 PHSEG2 as defined in 18XXX8 datasheet 1 8 PROPSEG as defined in 18 8 datasheet 1 8 CAN CONFIG FLAGS is formed from predefined constants see CAN constants Requires CAN must be in Config mode otherwise the function will be ignored Example init CAN CONFIG SAMPLE THRICE CAN CONFIG PHSEG2 PRG ON CAN CONFIG STD MSG CAN CONFIG DBL BUFFER ON CAN CONFIG VALID XTD MSG CAN CONFIG LINE FILTER OFF CANSetBaudRate 1 1 3 3 1 init 4 41 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS mikrot making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS CANSetMask Prototype void CANSetMask char CAN MASK long value char CAN CONFIG FLAGS Description Function sets mask for advanced filtering of messages Given value is bit adjusted to appropriate buffer mask registers Parameter
103. ISB 0 j 4 for 1 0 i lt 20u i Eeprom Write i j for i 0 i lt 20u i PORTB Eeprom Read Delay_ms 500 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 3 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Ethernet Library This library is designed to simplify handling of the underlying hardware RTL8019AS However certain level of knowledge about the Ethernet and Ethernet based protocols ARP IP TCP IP UDP IP ICMP IP is expected from the user The Ethernet is a high speed and versatile protocol but it is not a simple one Once you get used to it however you will make your favorite PIC available to a much broader audience than you could do with the RS232 485 or CAN Library Routines Eth Init Eth_Set_Ip Address Eth_Inport Eth Scan For Event Eth Get Ip Hdr Len Eth Load Ip Packet Eth Get Hdr Chksum Eth Get Source Ip Address Eth Get Dest Ip Address Eth Arp Response Eth Get Icmp Info Eth Ping Response Eth Get Udp Source Port Eth Get Udp Dest Port Eth Get Udp Port Eth Set Udp Port Eth Send Udp Eth Load Tcp Header Eth Get Tcp Hdr Offset Eth Get Tcp Flags Eth Set Tcp Data Eth Tcp Response 7 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Eth Init Prototype void Eth Init char addrP char d
104. Indirect Approach Through FSR Pointers with PIC16 are near they carry only the lower 8 bits of the address Compiler will automatically clear the 9th bit upon startup so that pointers will refer to banks 0 and 1 To access the objects in banks 3 or 4 via pointer user should manually 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 PIC18 Note If you have many variables in the code try rearranging them with linker directive absolute Variables that are approached only directly should be moved to banks 3 and 4 for increased efficiency MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple mikroC SPECIFICS ANSI Standard Issues Divergence from the ANSI C Standard mikroC diverges from the ANSI C standard in few areas Some of these modifica tions are improvements intenteded to facilitate PIC programming while others are result of PICmicro hardware limitations Function cross calling and recursion are unsupported due to the PIC s limitations of no easily usable stack and limited memory Pointers to variables and pointers to constants are not compatible i e no assigning or comparison is possible between
105. LER FOR MICROCHIP PIG MICROCONTROLLERS Thus we have 10 different compound assignment operators amp lt lt and gt gt All of these associate from right to left Spaces separating compound operators e g will generate error Compound assignment has the same effect as expressionl expressionl op expression2 except the lvalue expression1 is evaluated only once For example expressionl expression2 is the same as expressionl 1 expression2 Assignment Rules For both simple and compound assignment the operands expressioni and expression2 must obey one of the following rules 1 1 is a qualified or unqualified arithmetic type and expression2 is an arithmetic type 2 expressionl has a qualified or unqualified version of a structure or union type compatible with the type of expression2 3 expressionl and expression2 are pointers to qualified or unqualified versions of compatible types and the type pointed to by the left has all the qualifiers of the type pointed to by the right 4 Either 1 or expression2 is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void The type pointed to by the left has all the qualifiers of the type pointed to by the right 5 expressionl is a pointer and expression2 is a null pointer constant MIKROG CO
106. LERS Library Example The example demonstrates simple data exchange via USART When PIC MCU receives data it immediately sends the same data back If PIC is connected to the PC see the figure below you can test the example from mikroC terminal for RS232 communication menu choice Tools gt Terminal char i 0 j 0 long addr unsigned short datakd unsigned short dataWr 64 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 poy Oy 17 7 Oy 17 27 3547 576 1 859 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 5 17253494 1 2 3 446 1 2 3 4 121 void main PORTB 0 TRISB 0 PORTC 0 TRISC 0 addr 0x00000A30 valid for P18F452 Flash Write addr dataWr addr 0x00000A30 for i 0 i lt 64 i dataRd Flash Read addr PORTB dataRd Delay 500 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple I2C Library PC full master MSSP module is available with a number of PIC MCU models mikroC provides I2C library which supports the master PC mode Note This library supports module on PORTB or PORTC and will not work with modules on other ports Examples for PICmicros with module on other ports can be found in your mikroC installation folder subfolder Examples Library Routines I2C Init I2C Start I2C Repeated Start I2C Is Idle I2C Rd I2C Wr I
107. Lcd Init Example Out 2 3 i Print i at line 2 char 3 Lcd Chr Cp Prototype void Lcd Chr Cp char character Description Prints character on LCD at current cursor position Both variables and literals can be passed as character Requires Port with LCD must be initialized See Lcd Config or Lcd Init Example Lcd Out Cp e Print at current cursor position Lcd Cmd Prototype void Lcd Cmd char command Description Sends command to LCD You can pass one of the predefined constants to the function The complete list of available commands is shown on the following page Requires Port with LCD must be initialized See Lcd Config or Lcd Init Example Cmd Lcd Clear Clear LCD display MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 9G MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS LCD Commands LCD Command Purpose LCD_FIRST_ROW Move cursor to 1st row LCD SECOND ROW Move cursor to 2nd row LCD THIRD ROW Move cursor to 3rd row LCD FOURTH ROW Move cursor to 4th row LCD CLEAR Clear display LCD RETURN HOME Return cursor to home position returns a shifted display to original posi tion Display data RAM is unaffected LCD CURSOR OFF Turn off cursor LCD UNDERLINE ON Underline cursor on LCD BLINK CURSOR ON Blink cursor on LCD MOVE CURSOR LEFT Move cursor l
108. MASTER OSC DIVA Master clock Fosc 4 MASTER OSC DIV16 Master clock Fosc 16 MASTER OSC DIV64 Master clock Fosc 64 MASTER TMR2 Master clock source TMR2 SLAVE SS ENABLE Master Slave select enabled SLAVE SS DIS Master Slave select disabled The data sample determines when data is sampled can have the values DATA SAMPLE MIDDLE Input data sampled in middle of interval DATA SAMPLE END Input data sampled at the end of interval Parameter clock idle determines idle state for clock can have the following values CLK IDLE HIGH Clock idle HIGH CLK IDLE LOW Clock idle LOW Parameter transmit edge can have the following values LOW 2 HIGH Data transmit on low to high edge HIGH 2 LOW Data transmit on high to low edge Requires You need PIC MCU with hardware integrated SPI Example This will set SPI to master mode clock Fosc 4 data sampled at the middle of interval clock idle state low and data transmitted at low to high edge Spi Init Advanced MASTER OSC DIV4 DATA SAMPLE MIDDLE CLK IDLE LOW LOW 2 HIGH MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 6 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS 111111 hing 42 simple Spi_Read Prototype char Spi_Read char buffer Returns Returns the received data Description Provides clock by sending buffer and receives data at the end of period Requires SPI must be initialized and communication es
109. MPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Sizeof Operator Prefix unary operator sizeof returns an integer constant that gives the size in bytes of how much memory space is used by its operand determined by its type with some exceptions Operator sizeof can take either a type identifier or an unary expression as an operand You cannot use sizeof with expressions of function type incomplete types parenthesized names of such types or with an lvalue that designates a bit field object Sizeof Applied to Expression If applied to expression size of the operand is determined without evaluating the expression and therefore without side effects 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 Unit for type size is the sizeof char which is equivalent to one byte Operation sizeof char gives the result 1 whether the char is signed or unsigned sizeof char returns 1 sizeof int returns 2 sizeof unsigned long returns 4 When the operand is a non parameter of array type the result is the total number of bytes in the array in other words an array name is not converted to a pointer type int i 3 10 rg due j 11 1 sizeof int 2 i sizeof a i 10 sizeof int 20 If the operand is a parameter declared a
110. MPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Software UART Library mikroC provides library which implements software UART These routines are hardware independent and can be used with any MCU You can easily communi cate with other devices via RS232 protocol simply use the functions listed below Note This library implements time based activities so interrupts need to be dis abled when using Soft UART Library Routines Soft_Uart_Init Soft Uart Read Soft Uart Write Soft Uart Init Prototype void Soft Uart Init unsigned short port unsigned short rx unsigned short tx unsigned short baud rate char inverted Description Initalizes software UART Parameter port specifies port of MCU on which RX and TX pins are located parameters rx and tx need to be in range 0 7 and cannot point at the same pin baud rate is the desired baud rate Maximum baud rate depends on PIC s clock and working conditions Parameter inverted if set to non zero value indicates inverted logic on output Soft Uart Init needs to be called before using other functions from Soft UART Library Example Soft Uart Init amp PORTB 1 2 9600 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Z2 84 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Soft_Uart_Read Prototype unsigned short Soft Uart Read unsigned short error Returns Returns a re
111. MPLAB is a Registered trademark of Microchip company Windows is a Registered trademark of Microsoft Corp All other trade and or services marks are the property of the respective owners Lu MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS User s Table of Contents CHAPTER 1 mikroC IDE CHAPTER 2 Building Applications CHAPTER 3 mikroC Reference CHAPTER 4 mikroC Libraries MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKRO C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS 0000000 0 0 0 E admite CHAPTER 1 mikroC IDE 1 Quick Overview 1 Code Editor 3 Code Explorer 6 Debugger 7 Error Window 11 Statistics 12 Integrated Tools 15 Keyboard Shortcuts 19 CHAPTER 2 Building Applications 21 Projects 22 Source Files 23 Search Paths 23 Managing Source Files 24 Compilation 26 Output Files 26 Assembly View 26 Error Messages 27 CHAPTER 3 mikroC Language Reference 29 PIC Specifics 30 mikroC Specifics 32 ANSI Standard Issues 32 Predefined Globals and Constants 33 Accessing Individual Bits 33 Interrupts 34 Linker Directives 35 Lexical Elements 36 Tokens 38 Constants 39 Integer Constants 39 Floating Point Constants 41 Character Constants 42 String Constants 44 Enumeration Constants 45 Pointer Constants 45 Constant Expressions 45 o MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG COMPILER FOR MICROCHIP PIG MIBEBBDONTIREPEERE Keywords 46 Identi
112. N MASK B1 ID CAN CONFIG XTD MSQ Set all mask2 bits to ones CANSetMask CAN MASK B2 ID CAN CONFIG XTD MSG Set id of filter B1 F1 to 3 CANSetFilter CAN FILTER B2 F3 3 CAN CONFIG XTD MSG Set CAN to NORMAL mode CANSetOperationMode CAN MODE NORMAL OxFF PORTD OxFF id 12111 CANWrite id data 1 aa1 Send message via CAN while 1 oldstate 0 zr CANRead amp id data amp len amp aa2 if id 3 amp zr PORTD OxAA PORTC data 0 Output data at PORTC data O If message contains two data bytes output second byte at PORTD if len 2 PORTD 11 data 1 OxFF id s 12111 CANWrite id data 2 aa1 Send incremented data back MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS d mikroC making it simple C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS MIKROG Hardware Connection Reset 5 10K E HIH PIC18F458 MCLRIVpp RAO ANO Cvref RAZIAN2IVref RAS AN3 Vref RAS AN4 SS LVDIN REO ANSIRD RE ANGIWRIC1OUT RE2 AN7 CS C20UT OSC1 CLKI OSC2ICLKO RAG RCO T1OSO T1CKI RC1 T10S1 RC2ICCP1 RC3 SCK SCL RDO PSPO C1IN RD1 PSP1 C1IN RB7 PGD RB6 PGC RB5 PGM RB4 RB3 CANRX RB2 CANTXIINT2 RB4 INT4 RBO INTO Vss RD7 PSP7 P1D RD6 PSP6 P1C RD5 PSP5 P1B RD4 PSP4 ECCP1 P1A RCTIRXIDT
113. NT TOOLS BOOKS COMPILERS 728 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Hardware Connection 5V x 5 PIC16F877A IMCLR Vpp THV RB7 PGD RB6 PGC RB5 IRA2 AN2 Vref RB4 RA3 AN3 Vref RB3 PGM RB2 z RB1 RBO INT c Vdd Vss D7 RD7 PSP7 DE RD6 PSP6 5V D5 4125 oc RD5 PSP5 RD4 PSP4 1050 RC7 RX DT 1 71051 RC6 TX CK 55 4MHz IRC2 CCP1 RC5 RC4 E IRDO PSPO RD3 PSP3 RS RD1 PSP1 RD2 PSP2 n g E l LCD contrast 2256 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS PS 2 Library mikroC provides a library for communicating with common PS 2 keyboard The library does not utilize interrupts for data retrieval and requires oscillator clock to be 6MHz and above Library Routines Ps2_Init Ps2_Config Ps2 Key Read Ps2 Init Prototype void Ps2 Init unsigned short port Description Initializes port for work with PS 2 keyboard with default pin settings Port pin 0 is Data line and port pin 1 is Clock line You need to call either 2 Init or Ps2 Config before using other routines of PS 2
114. NT TOOLS BOOKS COMPILERS Zoo C a FOR MICROCHIP PIC MICROCONTROLLERS eerie ets making 42 simple ShortToStr Prototype void ShortToStr short number char output Description Function creates an output string out of a small signed number numerical value less than 0x100 Output string has fixed width of 4 characters remaining positions on the left if any are filled with blanks Example short t 24 char txt EL ByteToStr t txt txt is 24 one blank here WordToStr Prototype void WordToStr unsigned number char output Description Function creates an output string out of an unsigned number numerical value of unsigned type Output string has fixed width of 5 characters remaining positions on the left 1f any are filled with blanks Example unsigned t 437 char txt WordToStr t txt txt is 437 two blanks here IntToStr Prototype void IntToStr int number char output Description Function creates an output string out of a signed number numerical value of int type Output string has fixed width of 6 characters remaining positions on the left 1f any are filled with blanks Example int j 4220 char txt PA IntToStr j txt txt is 4220 one blank here page ES ZO MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroG making m simple EEE O EES TO
115. OCONTROLLERS Glcd Write Char Prototype void Glcd Write Char unsigned short character unsigned short x unsigned short page char color Description Prints character at page one of 8 GLCD lines 0 7 x dots away from the left bor der of display Parameter color defines the fill 0 prints a white letter clear dots 1 prints a solid letter put dots and 2 prints a smart letter invert each dot Requires GLCD needs to be initialized See Glcd_Init Example Glcd Write Char C 0 0 1 Glcd Write Text Prototype void Glcd Write Text char text unsigned short x unsigned short page unsigned short color Description Prints text at page one of 8 GLCD lines 0 7 x dots away from the left border of display Parameter color defines the fill 0 prints a white letters clear dots 1 prints solid letters put dots and 2 prints smart letters invert each dot Requires GLCD needs to be initialized See Glcd_Init Example Glcd Write Text Hello world 0 0 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 24 C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS iioc eroe eerie making 42 simple Glcd Image Prototype void Glcd Image const char image Description Displays bitmap image on the GLCD Parameter image should be formatted as an array of integers Use the mikroC s integrated Bitmap
116. OPMENT TOOLS BOOKS COMPILERS mikroG making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS RS485Master_Send Prototype void RS485Master Send char data char datalen char address Description Sends data from buffer to Slave s specified by address via RS 485 datalen is a number of bytes in message 1 lt datalen lt 3 Requires MCU must be initialized as Master in RS 485 communication in order to be assigned an address See RS485Master Init It is programmer s responsibility to ensure by protocol that only one device sends data via 485 bus at a time Example unsigned short 8 RS485Master Send msg 3 0x12 RS485Slave_Init Prototype void RS485Slave Init char address Description Initializes MCU as Slave with a specified address in RS 485 communication Slave address can take any value between 0 and 255 except 50 which is common address for all slaves Requires USART HW module needs to be initialized See USART_Init Example RS485Slave Init 160 Initialize MCU as Slave with address 160 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 221 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple RS485Slave_Receive Prototype void RS485Slave Receive char data Description Receives message addressed to it Messages are multi byte so this function must be called for each byte
117. PMENT TOOLS Books Dec2Bcd Prototype unsigned short Dec2Bcd unsigned short decnum Returns Returns converted BCD value Description Converts 8 bit decimal value decnum to BCD Example unsigned short a Dec2Bcd 52 equals 0x52 Bcd2Dec16 Prototype unsigned Bcd2Dec16 unsigned bcdnum Returns Returns converted decimal value Description Converts 16 bit BCD numeral bcdnum to its decimal equivalent Example unsigned a 2 16 1234 equals 4660 Dec2Bcd16 Prototype unsigned Dec2Bcd unsigned decnum Returns Returns converted BCD value Description Converts 16 bit decimal value decnum to BCD Example unsigned a Dec2Bcd16 4660 equals 1234 page SS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Trigonometry Library mikroC implements fundamental trigonometry functions These functions are implemented as lookup tables and return the result as integer multiplied by 1000 and rounded up Library Routines SinE3 CosE3 SinE3 Prototype int SinE3 unsigned angle deg Returns Function returns the sine of input parameter multiplied by 1000 1E3 and rounded up to the nearest integer The range of return values is from 1000 to 1000 Description Function takes parameter angle deg which represents angle in degrees and returns its sine multiplied by 1000 and rounded up to the nearest integer The function
118. ROCHIP PIG MICROCONTROLLERS 7 Segment Display Decoder mikroC The 7seg Display Decoder 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 desired value in the edit boxes You can launch it from the drop down menu Tools gt 7 Segment Display 7 segment display decoder EEPROM Editor Common cathode ED Common anode Decode in 12 decimal value hex value EEPROM Editor allows you to easily manage EEPROM of PIC microcontroller EEprom Dump 8x 08 FF 98 78 56 FF FF FF FF FF FF FF FF FF FF FF FF FF FF 98 78 FF FF FF FF FF FF FF FF FF FF FF FF FF 56 FF 98 FF FF FF FF FF FF FF FF FF FF FF FF FF 66 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 66 55 FF FF FF FF FF FF FF FF FF FF FF FF FF FF Data Memory Size 255 Bytes FF 44 FF FF FF FF FF FF FF FF FF FF FF FF FF FF Lise this EEPROM definition FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF MIKROELEKTRONIKA DEVELOPMENT TOOLS Books COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPIL
119. ROCONTROLLERS IDENTIFIERS Identifiers are arbitrary names of any length given to functions variables symbol ic constants user defined data types and labels All these program elements will be referred to as objects throughout the help not to be confused with the meaning of object in object oriented programming 55 Identifiers can contain the letters to z and A to 7 the underscore character and the digits 0 to 9 The only restriction is that the first character must be a letter or an underscore Case Sensitivity mikroC identifiers are not case sensitive at present so that Sum sum and suM rep resent an equivalent identifier However future versions of mikroC will offer the option of activating suspending case sensitivity The only exceptions at present are the reserved words main and interrupt which must be written in lowercase Uniqueness and Scope Although identifier names are arbitrary within the rules stated errors result if the same name is used for more than one identifier within the same scope and sharing the same name space Duplicate names are legal for different name spaces regard less of scope rules For more information on scope refer to Scope and Visibility MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Al MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple PUNCTUATORS The mikroC punctuators also known as separators include brackets parenthese
120. ROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS D MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Line Continuation with Backslash If you need to break directive into multiple lines you can do it by ending the line with a backslash define MACRO This directive continues to the following line Macros Macros provide a mechanism for 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 lt token_sequence gt Each occurrence of macro_identifier in the source code following this control line will be replaced in the original position with the possibly empty token_sequence there are some exceptions which are noted later Such replacements are known as macro expansions The token_sequence is some times called body of the 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 the macro expansion The token_sequence terminates at the first non backslashed new line encountered Any sequence of whitespace including comments in the token sequence is replaced with a single space character After each individual macro expansion a further scan is made
121. Read Csd unsigned short data for registers Returns Returns 0 if read was successful or 1 if an error occurred Description Function reads CSD register and returns 16 bytes of content into data for registers Requires Library needs to be initialized see Init Example error Mmc Read Csd data page 0 22G MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Mmc Fat Init Prototype unsigned short Mmc Fat Init unsigned short port unsigned short pin Returns Returns 0 1f MMC card is present and successfully initialized otherwise returns 1 Description Initializes hardware SPI communication designated CS line for communication is RC2 The function returns 0 if MMC card is present and successfully initialized otherwise returns 1 This function needs to be called before using other functions of MMC FAT library Example Loop until MMC FAT is initialized at RC2 while Mmc Fat Init amp PORTC 2 Mmc Fat Assign Prototype void Mmc Fat Assign char filename Description This routine designates assigns the file we ll be working with Function looks for the file specified by the filename in the root directory If the file is found routine will ini tialize it by getting its start sector size etc If the file is not found an empty f
122. Returns Returns one byte from the slave Description Reads one byte from the slave and sends not acknowledge signal if parameter ack is 0 otherwise it sends acknowledge Requires START signal needs to be issued in order to use this function See I2C Start Example temp I2C Rd 0 Read data and send not acknowledge signal I2C Wr Prototype char I2C Wr char data Returns Returns 0 if there were no errors Description Sends data byte parameter data via PC bus Requires START signal needs to be issued in order to use this function See I2C Start Example I2C Write 0xA3 2 Stop Prototype void I2C Stop void Description Issues STOP signal Requires PC must be configured before using this function See I2C Init o0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Library Example This code demonstrates use of Library functions PIC MCU is connected SCL SDA pins to 24c02 EEPROM Program sends data to EEPROM data is written at address 2 Then we read data via I2C from EEPROM and send its value to PORTD to check if the cycle was successful see the figure below how to interface 24c02 to PIC void main PORTB 0 TRISB 0 I2C_Init 100000 I2C Start Tssue I2C start signal I2C Wr 0xA2 Send byte via I2C command to 24cO2 I2C
123. TRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 7 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple continued define CONFIG DBL BUFFER 0x10 define CAN CONFIG DBL BUFFER_ON OxFF XXX1XXXX define CAN CONFIG DBL BUFFER OFF OxEF XXXOXXXX define CAN CONFIG MSG BITS 0x60 define CAN CONFIG ALL MSG OxFF X11XXXXX define CAN CONFIG VALID XTD MSG OxDF X10XXXXX define CAN CONFIG VALID STD MSG OxBF XOIXXXXX define CAN CONFIG ALL VALID MSG Ox9F X00XXXXX You may use bitwise AND amp to form config byte out of these values For exam ple init CAN CONFIG SAMPLE THRICE amp 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 Z4 w CANInitialize 1 1 3 3 1 init initialize CAN CAN TX MSG FLAGS CAN TX MSG FLAGS are flags related to transmission of a CAN message define CAN TX PRIORITY BITS 0x03 define CAN TX PRIORITY 0 OxFC XXXXXX00 define CAN TX PRIORITY 1 OxFD 1 define CAN TX PRIORITY 2 OxFE XXXXXX10 define CAN TX PRIORITY 3 OxFF XXXXXX11 define CAN TX FRAME 0x08 define CAN TX STD FRAME OxFF XXXXX1XX define CAN TX XTD FRAME OxF7 XXXXXOXX define CAN TX 0x40 define CAN TX NO RTR FRAME OxFF X1XXXXXX define CAN TX RTR FRAME OxBF XOXXXXX
124. X You may use bitwise AND amp to adjust the appropriate flags For example form value to be used with CANSendMessage send config CAN TX PRIORITY 0 amp amp CAN TX XTD FRAME amp CAN TX NO RTR FRAME CANSendMessage id data 1 send config 2108 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS RX MSG FLAGS CAN RX MSG FLAGS are flags related to reception of CAN message If a particular bit is set corresponding meaning is TRUE or else it will be FALSE define CAN RX FILTER BITS 0x07 Use it to access filter bits define CAN RX FILTER 1 0x00 define CAN RX FILTER 2 0x01 define RX FILTER 3 0x02 define CAN RX FILTER 4 0x03 define CAN RX FILTER 5 0x04 define CAN RX FILTER 6 0x05 define CAN RX OVERFLOW 0 08 Set if Overflowed else clear define CAN RX INVALID MSG 0x10 Set if invalid else clear define RX XTD FRAME 0 20 Set if XTD msg else clear define FRAME Ox40 Set if RTR msg else clear define CAN DBL BUFFERED 0x80 Set if msg was hardware double buffered You may use bitwise AND amp to adjust the appropriate flags For example if MsgFlag amp CAN RX OVERFLOW O Receiver overflow has occurred previous message is lost CAN MASK CAN MASK constants define mask codes Function CANSetMask expects one of these
125. ad files from the root directory only Library functions populate both FAT 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 T1 table is corrupted Library Routines Mmc Init Mmc Read Sector Mmc Write Sector Mmc Read Cid Mmc Read Csd Mmc Fat Init Mmc Fat Assign Mmc Fat Reset Mmc Fat Rewrite Mmc Fat Append Mmc Fat Read Mmc Fat Write Mmc Set File Date Mmc Init Prototype unsigned short Mmc Init char port char pin Returns Returns 0 1f MMC card is present and successfully initialized otherwise returns 1 Description Initializes MMC through hardware SPI communication with chip select pin being given by the parameters port and pin communication port and pins are designated by the hardware SPI settings for the respective MCU Function returns if MMC card is pres ent and successfully initialized otherwise returns 0 Example while Mmc_Init Loop until MMC is initialized page 0 202204 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS mikroC making amp MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Mmc Read Sector Prototype unsigned short Mmc Read Sector unsigned long sector char data Returns Returns 0 if read was successful or 1 if an error occurred Description Function reads one sector 512 bytes from MMC card
126. alue as shown in the figure below Manchester RF_Send_Byte format St1 St2 Ctr B7 B6 B5 B4 B2 B1 BO Bi phase coding ri 2 4ms Example of transmission Notes Manchester receive routines are blocking calls Man_Receive_Config Man Receive Init Receive This means that PIC will wait until the task is performed e g byte 15 received synchronization achieved etc Routines for receiving are limited to a baud rate scope from 340 560 bps Library Routines Man Receive Config Man Receive Init Man Receive Man Send Config Man Send Init Man Send MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 22 9 MIKROG COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Man_Receive_Config Prototype void Man Receive Config char port char rxpin Description The function prepares PIC for receiving signal You need to specify the port and rxpin 0 7 of input signal In case of multiple errors on reception you should call Man Receive Init once again to enable synchronization Example Man Receive Config amp PORTD 6 Man Receive Init Prototype void Man Receive Init char port Description The function prepares PIC for receiving signal You need to specify the port rxpin is pin 6 by default In case of multiple errors on reception you should call Man Receive Init once again to enable synchronization Example Man Receive Init amp PORTD Man Recei
127. and all the cabling required is a single wire Because of the hardware configuration it uses single pullup and open collector drivers it allows for the slaves even to get their power supply from that line Some basic characteristics of this protocol are single master system low cost low transfer rates up to 16 kbps fairly long distances up to 300 meters small data transfer packages Each OneWire device also has a unique 64 bit registration number 8 bit device type 48 bit serial number and 8 bit CRC so multiple slaves can co exist on the same bus Note that oscillator frequency Fosc needs to be at least 4MHz in order to use the routines with Dallas digital thermometers Library Routines Ow Reset Ow Read Ow Write MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 72 370 making 42 simple 8 Ow Reset Prototype char Ow Reset char port char pin Returns Returns 0 if DS1820 is present 1 if not present Description Issues OneWire reset signal for 051820 Parameters port and specify the location of 051820 Requires Works with Dallas DS1820 temperature sensor only Example Ow Reset amp PORTA 5 reset DS1820 connected to the RA5 pin Ow Read Prototype char Ow Read char port char pin Returns Data read from an external device over the OneWire b
128. and then press CTRL SPACE all the valid identifiers matching the letters you typed will be prompted in a floating panel see the image Now you can keep typing to narrow the choice or you can select one from the list using the keyboard arrows and Enter r function unsigned int Flash Head unsigned int af function void Flash_Write unsigned int unsigned int sfr FSR const F 1 const FERR 2 Parameter Assistant CTRL SHIFT SPACE The Parameter Assistant will be automatically invoked when you open a parenthe sis or press CTRL SHIFT SPACE If name of a valid function precedes the parenthesis then the expected parameters will be prompted in a floating panel As you type the actual parameter the next expected parameter will become bold channel char ADC Rea Code Template CTR J You can insert the Code Template by typing the name of the template for instance whileb then press CTRL J and the Code Editor will automatically generate the code Or you can click a button from the Code toolbar and select a template from the list You can add your own templates to the list Just select Tools gt Options from the drop down menu or click the Tools Icon from Settings Toolbar and then select the Auto Complete Tab Here you can enter the appropriate keyword description and code of your template Al MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP
129. ans it can address only 256 locations For PIC18 micros with more EEPROM data locations it is programmer s responsibility to set SFR EEADRH register appropriately Requires Requires EEPROM module 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 Example char take take Eeprom Read 0x3F T 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Eeprom_Read Prototype void Eeprom Write char address char data Description Writes data to the specified address Parameter address is of byte type which means it can address only 256 locations For PIC18 micros with more EEPROM data locations it is programmer s responsibility to set SFR EEADRH register appropriately Be aware that all interrupts will be disabled during execution of EEPROM Write rou tine GIE bit of INTCON register will be cleared Routine will set this bit on exit Requires Requires EEPROM module 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 Example Eeprom Write 0x32 Library Example unsigned short i 0 j 0 void main PORTB 0 TR
130. aracter to extend a string constant across line boundaries This is really a one line string 2 4 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Al MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Enumeration Constants Enumeration constants are identifiers defined in enum type declarations The iden tifiers are usually chosen as mnemonics to assist legibility Enumeration constants are of int type They can be used in any expression where integer constants are valid For example enum weekdays SUN 0 MON TUE WED THU FRI SAT The identifiers enumerators used must be unique within the scope of the enum declaration Negative initializers are allowed See Enumerations for details of enum declarations Pointer Constants A pointer or the pointed at object can be declared with the const modifier Anything declared as a const cannot be have its value changed It is also illegal to create a pointer that might violate the nonassignability of a constant object Constant Expressions A constant expression is an expression that always evaluates to a constant and consists only of constants literals or symbolic constants It is evaluated at com pile time and it must evaluate to a constant that is in the range of representable values for its type Constant expressions are evaluated just as regular expressions are Constant expressions can consist only
131. are Connection 5V 18 458 MC33269 3 3 5V MCLRIVpp RB7 PGD 2 RAO ANO Cvref RB6 PGC RB5 PGM RA2 AN2 Vref RB4 RA3 AN3 Vref RB3 CANRX RA4 TOCKI RB2 CANTX INT2 RAS AN4 SS LVDIN RBA INT1 0 REO ANS RD RBO INTO o RE1 ANG WR C1OUT Vdd e 5V RE2 AN7 CS C20UT Vss Vdd RD7 PSPT P1D Vss RD6 PSP6 P1C SD OSCA CLKI e si gl OSC2I CLKO RAG COPPA RCO TIOSO TACK RCTIRXIDT ICS H 0 H RCA T1OSI RCGITXICK T Data IN F 4 GND RC2 CCP1 RC5 SDO 5 P 3V3 RC3 SCK SCL RCA SDI SDA x RDO PSPO C1IN C2IN 4MHz RD3 PSP3 GND RD1 PSP1 C1IN RD2 PSP2 C2IN Data_OUT MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2 B MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Software I2C Library mikroC provides routines which implement software These routines are hard ware independent and can be used with any MCU Software I2C enables you to use MCU as Master in I2C communication Multi master mode is not supported Note This library implements time based activities so interrupts need to be dis abled when using Soft PC Library Routines Soft I2C Config Soft I2C Start Soft I2C Read Soft I2C Write Soft I2C Stop
132. are a few examples of array declaration define 50 int vector one 10 an array of 10 integers float vector two MAX an array of 50 floats float vector three MAX 20 an array of 30 floats MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 8 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Array Initialization 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 acording to the number of elements assigned For example An array which holds number of days in each month int days 12 31 28 31 30 31 30 31 31 30 31 30 31 This declaration is identical to the previous int days 31 28 31 30 31 30 31 31 30 31 30 31 If you specify both the length and starting values the number of starting values must not exceed the specified length Vice versa is possible when the trailing excess elements will be assigned some encountered runtime values from memo In case of array of char you can use a shorter string literal notation For example The two declarations are identical const char msgl T e s t 0 const char msg2 Test For more information on string literals refer to String Constants Arrays in Expressions When name of the array
133. ariables of volatile unsigned short These identifiers have external linkage and are visible in the entire project When creating a project mikroC will include an appropriate def file containing declarations of available SFR and constants such as TOIE INTF etc Identifiers are all in uppercase identical to nomenclature in Microchip datasheets For the complete set of predefined globals and constants look for Defs in your mikroC installation folder or probe the Code Assistant for specific letters Ctrl Space in Editor Device Clock Constants There are two built in constants related to device clock __ Foscand X rcv Constant FOSC equals the frequency that is provided by an external oscillator while is the operating frequency of PIC Both constants can be used any where in the code and are automatically updated as you change target PIC in your project Source files that use these constants are recompiled any time the clock is changed in IDE Accessing Individual Bits mikroC allows you to access individual bits of 8 bit variables types char and unsigned short Simply use the direct member selector with a variable followed by one of identifiers FO F1 F7 For example If RBO is set set RCO if PORTB FO PORTC FO 1 There is no need for any special declarations this kind of selective access is an intrinsic feature of mikroC and can be used anywhere in the code Identifiers F0 F7 not
134. ataP char ctrlP char pinReset char pinIOW char pinIOR Description Performs initialization of Ethernet card and library This includes Setting of control and data ports nitialization of the Ethernet card also called the Network Interface Card or NIC Retrieval and local storage of the NIC s hardware MAC address Putting the NIC into the LISTEN mode Parameter addrP is a pointer to address port which handles the addressing lines Parameter is pointer to data port Parameter ctr1P is the control port Parameter pinReset is the reset enable pin for the ethernet card chip on control port Parameter pinIOW is the I O Write request control pin Parameter pinIOR is the I O read request control pin Requires As specified for the entire library please see top of this page Example Eth Init amp PORTB amp PORTD amp PORTE 2 1 0 Eth Set Ip Address Prototype void Eth Set Ip Address char char ip2 char ip3 char ip4 Description Sets the IP address of the connected and initialized Ethernet network card The arguments are the IP address numbers in IPv4 format e g 127 0 0 1 Requires This function should be called immediately after the NIC initialization see Eth Init You can change your IP address at any time anywhere in the code Example Set IP address 192 168 20 25 Eth Set Ip Address 192u 168u 20u 25u MIKROELEKTRON
135. ated to their scope external linkage or internal link age These attributes are determined by the placement and format of your declara tions together with the explicit or implicit by default use of the storage class specifier static or extern Each instance of a particular identifier with external linkage represents the same object or function throughout the entire set of files and libraries making up the program Each instance of a particular identifier with internal linkage represents the same object or function within one file only Linkage Rules Local names have internal linkage same identifier can be used in different files to signify different objects Global names have external linkage identifier signifies the same object throughout all program files If the same identifier appears with both internal and external linkage within the same file the identifier will have internal linkage Internal Linkage Rules 1 names having file scope explicitly declared as static have internal linkage 2 names having file scope explicitly declared as const and not explicitly declared as extern have internal linkage 3 typedef names have internal linkage 4 enumeration constants have internal linkage MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple External Linkage Rule 1 names having file scope that do not comply to any of previousl
136. ation menu choice Tools gt Terminal unsigned short i void main Initialize USART module 8 bit 2400 baud rate no parity bit Usart Init 2400 do if Usart Data Ready If data is received i Usart Read Read the received data Usart Write i Send data via USART while 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2 3 mikroC MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Hardware Connection PIC16F877A 5V 5V T MCLR Vpp THV RB7 PGD RAO ANO RB6 PGC 1 RB5 u bs RA2 AN2 Vref RB4 un D RA3 AN3 Vref SUB D 9 pin connector N Tout RA4 TOCKI RB2 amp diae RAS AN4 RB1 Eh 1 c3 8 REO RD ANS RBO INT 2 T2 4 RE1 WR AN6 Vdd 7 T2in c lo 5V 2 Rin H2out RE2 CS AN7 Vss 2 y i m Vdd RD7 PSP7 12 mm ES t MAX232 Vss RD6 PSP6 5 1 RD5 PSP5 BA xL OSC2 RD4 PSP4 NE RCO T10SO RC7 RX DT serial cable 1 1051 RC6 TX CK 101 RC2 CCP1 RC5 RC3 RC4 1 9 Receive data Rx 4MHz RDO PSPO RD3 PSP3 2 RD1 PSP1 RD2 PSP2 3 Send data Tx Ei T Po 5 DYE MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS
137. bdoozou MOXLION ISOLL LONT OSOLLOOY 4MHz SdSd SQ4 9dSd 904 1dSd dH SSA znviso zay PPA ONV MW vasi SNv au oas bay ooa Wod egu eyveNvieva vay 3eJNeNVIev say ood 98y onwove AHLddA H1oW VL2839L2Id XOL X9 vods 1936 9935 9938 198 A 2938 3935 90935 9938 1noa avol solid 91 eld cold 9910 6L2ZXVIN COMPILER FOR MICROCHIP PIC MICROCONTROLLERS HW Connection MIKROG COMPILERS Books DEVELOPMENT TOOLS MIKROELEKTRONIKA page 2UO making 42 simple MIKROD C COMPILER FOR MICROCHIP MICROCONTROLLERS USART Library USART hardware module is available with a number of PICmicros mikroC USART Library provides comfortable work with the Asynchronous full duplex mode You can easily communicate with other devices via RS232 protocol for example with PC see the figure at the end of the topic RS232 HW connection You need a PIC MCU with hardware integrated USART for example PIC16F877
138. be used for CF with FAT16 and FAT32 file system Note that routines for file han dling can be used only with FAT16 file system Important Before write operation make sure you don t overwrite boot or FAT sector as it could make your card on PC or digital cam unreadable Drive mapping tools such as Winhex can be of a great assistance Library Routines Cf Init Cf Detect Cf Total Size Cf Enable Cf Disable Cf Read Init Cf Read Byte Cf Read Word Cf Write Init Cf Write Byte Cf Write Word Cf Find File Cf File Write Init Cf File Write Byte Cf Read Sector Cf Write Sector Cf Set File Date Cf File Write Complete Function Set Reg Adr is for compiler internal purpose only d 6 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making simple TR EAT EEE id piii Cf Init Prototype void Cf Init char ctrlport char dataport Description Initializes ports appropriately for communication with CF card Specify two different ports ctrlport and dataport Example Cf Init amp PORTB amp PORTD Cf Detect Prototype char Cf Detect void Returns Returns 1 if CF is present otherwise returns 0 Description Checks for presence of CF card on ctrlport Example Wait until CF card is inserted do nop while Cf Detect 0 Cf Total Size Prototype unsigned long Cf Total Si
139. brary mikroC provides a set of standard ANSI C library functions for testing and map ping characters Note Not all of the standard functions have been included Functions have been implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC programming Library Routines isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit toupper tolower isalnum Prototype char isalnum char character Description Function returns 1 if the character is alphanumeric A Z a z 0 9 otherwise returns Zero MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Z2 834 C OCOMMLER FOR MICROCHIP PIC MICROCONTROLLERS making 42 simple 2 isalpha Prototype char isalpha char character Description Function returns 1 if the character is alphabetic A Z a z otherwise returns zero iscntrl Prototype char iscntrl char character Description Function returns 1 if the character is a control character or delete decimal 0 31 and 127 otherwise returns zero isdigit Prototype char isdigit char character Description Function returns 1 if the character is a digit 0 9 otherwise returns zero isgraph Prototype char isgraph char character Description Function returns 1 if the character is a printable character excluding the space deci mal 32
140. case sensitive and have a specific namespace Provided you are familiar with the particular chip you can access bits by their name INTCON TMROF 0 Clear TMROF MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 22253 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Interrupts Interrupts can be easily handled by means of reserved word interrupt mikroC implictly declares function interrupt which cannot be redeclared Its prototype is void interrupt void Write your own definition function body to handle interrupts in your application mikroC saves the following SFR on stack when entering interrupt and pops them back upon return PIC12 and PIC16 family STATUS FSR PCLATH PIC18 family FSR fast context is used to save WREG STATUS BSR Note mikroC does not support low priority interrupts for PIC18 family interrupts must be of high priority Function Calls from Interrupt You cannot call functions from within interrupt routine but you can make a function call from embedded assembly in interrupt For this to work the called function func1 in further text must fulfill the following conditions 1 func1 does not use stack or the stack is saved before call and restored after 2 func1 must use global variables only The stated rules also apply to all the functions called from within unc1 Note mikroC linker ignores calls to functions that occur only in interrupt assem
141. ce Double clicking a routine QHelp Tab opens the relevant Help topic Keyboard Tab lists all the available Al Toon keyboard shortcuts in mikroC Code Explorer le GHelp Keyboard Code Explorer 5 Keyboard Code Explorer E Keyboard 9 COMPACT FLASH IDE Shortcuts s Init Fl mam CF Detect CTRL N New Unit constants CF Wiite Byte CTRL 0 Open variables CF Word CTRL F9 Compile Sec CF Read Byte CTRL F11 Code Explorer on off Min Read Word CTRL SHIFT F5 View breakpoints Hr CF_Set_Reg_Adr Advanced Editor shortcuts Day CF_Write_Init CTRL SPACE Code Assistant Mn Read Init CTRL SHIFT SPACE Parameters Assistar Year CTRL D Find declaration 126 Wait For Read CTRL G Goto line Zero fill 2 Wait For 19 CTRL 4J Insert Code Template H constants 12 Init CTRL lt number gt Goto bookmark variables I2C Start CTRL SHIFT lt number gt Set bookmark Read time 2 Repeated Start CTRL SHIFT Indent selection constants 12C_Stop CTRL SHIFT U Unindent selection variables I2C wi CTRL ALT SELECT Select columns Sec I2C Rd ALT SELECT Select columns Min Close I2C Debugger Shortcuts Hr PwM F4 Run to Cursor Day PwM Init F5 Toggle breakpoint Mn Duty Run Pause Debugger Year PwM Stop Step into Transform time ADC Step over Display time Read Debug EE SPI CTRL F2 Reset a variables SPI Init amp dvanced Basic Editor shortcuts ne Spi Ini
142. ce it initializes the private variables used for this function Example calculate offset TCP header length tcp options Eth Get Tcp Hdr Offset 20 Eth Get Tcp Flags Prototype unsigned short Eth Get Tcp Flags void Returns Returns the flags data from the header of the received TCP packet Description The function returns the flags data from the header of the received TCP packet TCP flags show various information e g SYN syncronize request ACK acknowledge receipt and similar It is upon these flags that for example a proper HTTP communi cation is established Requires This function must be called after the Eth Load Tcp Header since it initializes the private variables used for this function Example flags Eth Get Tcp Flags MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 838 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Eth_Set_Tcp_ Data Prototype void Eth Set Tcp Data const unsigned short data Description Prepares data to be sent on HTTP request This library can handle only HTTP requests so sending other TCP based protocols such as FTP will cause an error Note that TCP IP was not designed with 8 bit MCU s in mind so be gentle with your HTTP requests Requires As specified for the entire library Example Let s prepare a simple HTML page in our string const char httpPagel HTTP 1
143. ce operator with the comma punctuator which separates elements in a function argument list and initializator lists Mixing the two uses of comma is legal but you must use parentheses to distinguish them To avoid ambiguity with the commas in function argument and initializer lists use parentheses For example func i 31 1 j 4 k calls function func with three arguments i 5 k not four MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS STATEMENTS Statements specify the flow of control as a 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 Every statement in program can be labeled Label is an identifier added before the statement like this label_identifier statement There is no special declaration of a label it just tags the statement Label identifier has a function scope and 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
144. ceived byte Description Function receives a byte via software UART Parameter error will be zero if the transfer was successful This is a non blocking function call so you should test the error manually check the example below Requires Soft UART must be initialized and communication established before using this func tion See Soft Uart Init Example Here s a loop which holds until data is received do data Soft Uart Read amp error while error Now we can work with it if data Soft_Uart_Write Prototype void Soft Write char data Description Function transmits a byte data via UART Requires Soft UART must be initialized and communication established before using this func tion See Soft Uart Init 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 Example char some byte 0 0 Soft Uart Write some byte page 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example The example demonstrates simple data exchange via software UART When PIC MCU receives data it immediately sends the same data back If PIC is connected to the PC see the figure below you can test the example from mikroC terminal for RS232 communicatio
145. character 15 a lowercase letter a z function returns an uppercase letter Otherwise function returns an unchanged input parameter tolower Prototype char tolower int character Description If the character is an uppercase letter A Z function returns a lowercase letter Otherwise function returns an unchanged input parameter page 0 226934 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS ANSI C Math Library mikroC provides a set of standard ANSI C library functions for floating point math handling Note Functions have been implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC programming Library Routines acos asin atan atan2 ceil cos cosh exp fabs floor frexp ldexp log 10410 modf pow sin sinh sqrt tan tanh acos Prototype double acos double x Description Function returns the arc cosine of parameter x that is the value whose cosine is x Input parameter x must be between 1 and 1 inclusive The return value is in radians between 0 and pi inclusive MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Z2 91 MIKROG C COMPILER MICROCHIP PIG MICROCONTROLLERS ing amp Mile s asin Prototype double asin double x Description Function returns the arc sine of
146. comes up in expression evaluation except with operators amp and sizeof it is implicitly converted to the pointer pointing to array s first element See Arrays and Pointers for more information OO MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 8 MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Multi dimensional Arrays An array is one dimensional if it is of scalar type One dimensional arrays are sometimes referred to as vectors Multidimensional arrays are constructed by declaring arrays of array type 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 2 dimensional array float m 50 20 2 dimensional array of size 50x20 Variable m is an array of 50 elements which in turn are arrays of 20 floats each Thus we have a matrix of 50x20 elements the first element is m 0 0 the last one is m 49 19 First element of the 5th row would be m 0 5 If you are not initializing the array in the declaration you can omit the first dimen sion of multi dimensional array In that case array is located elsewhere e g in another file This is a commonly used technique when passing arrays as function parameters int a 3 2 41 3 dimensional array of size 3x2x4 void func int 2 4 we can omit first dimension n 2 1
147. cting complex objects 5 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Lvalues An value is an object locator an expression that designates an object An example of an lvalue expression is P where P is any expression evaluating to a non null pointer A modifiable lvalue is an identifier or expression that relates to an object that can be accessed and legally changed in memory A const pointer to a constant for example is not a modifiable Ivalue A pointer to a constant can be changed but its dereferenced value cannot Historically the stood for left meaning that an lvalue could legally stand on the left the receiving end of an assignment statement Now only modifiable lval ues can legally stand to the left of an assignment operator For example if a and b are nonconstant integer identifiers with properly allocated memory storage they are both modifiable lvalues and assignments such asa 1andb a bare legal Rvalues The expression bisnotanlvalue a b 15 illegal because the expres sion on the left is not related to an object Such expressions are sometimes called rvalues short for right values MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS E MIKROG C COMPILER MICROCHIP PIG MICROCONTROLLERS L ling 60 dimple SCOPE AND VISIBILITY Scope The scope of identifier is the part of the
148. d remainder rem labs Prototype long labs long num Description Function returns the absolute 1 e positive value of a long integer num max Prototype int max int int Description Function returns greater of the two integers a and 5 min Prototype int min int a int b Description Function returns lower of the two integers a and b MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 20 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS 1111111 hing 42 rand Prototype int rand void Description Function returns a sequence of pseudo random numbers between 0 and 32767 Function will always produce the same sequence of numbers unless srand is called to seed the starting point srand Prototype void srand unsigned seed Description Function uses the seed as a starting point for a new sequence of pseudo random num bers to be returned by subsequent calls to No values are returned by this func tion xtoi Prototype int xtoi char s Description Function converts the input string s consisting of hexadecimal digits into an integer value Input parametes s should consist exclusively of hexadecimal digits with an optional whitespace and a sign at the beginning The string will be processed one char acter at a time until the function reaches a character which
149. d unions MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple FUNDAMENTAL TYPES Arithmetic Types The arithmetic type specifiers are built from the following keywords void char int float and double together with prefixes short long signed and unsigned From these keywords you can build the integral and floating point types Overview of types is given on the following page Integral Types Types char and int together with their variants are considered integral data types Variants are created by using one of the prefix modifiers short long signed and unsigned The table below is the 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 unsigned prefix signed is automatically assumed for integral types The only exception is the char which is unsigned by default The keywords signed and unsigned when used on their own mean signed int and unsigned int respectively The modifiers short and long can be applied only to the int The keywords short and long used on their own mean short int and long int respective ly Floating point Types Types float and double together with the long double variant are consid ered floating point types mikroC s implementation of ANSI Standard considers all three to be the same type Floating point in mikroC is implemented using
150. d Glcd Set X unsigned short x pos Description Positions to x dots from the left border of GLCD within the given page Requires GLCD needs to be initialized See Glcd_Init Example 25 Glcd Read Data Prototype unsigned short Glcd Read Data void Returns One word from the GLCD memory Description Reads data from from the current location of GLCD memory Use the functions Glcd Set Side Set and Glcd Set Page to specify an exact position on GLCD Then you can use 1 Write Data orGlcd Read Data on that location Requires Reads data from from the current location of GLCD memory Example tmp Glcd Read Data page 00 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROD C COMPILER FOR MICROCHIP MICROCONTROLLERS Glcd Write Data Prototype void Glcd Write Data unsigned short data Description Writes data to the current location in GLCD memory and moves to the next location Requires GLCD needs to be initialized See 1 Init Example Glcd Write Data data Fill Prototype void Glcd Fill unsigned short pattern Description Fills the GLCD memory with byte pattern To clear the GLCD screen use Glcd Fill 0 to fill the screen completely use 1 4 Fill FF Requires GLCD needs to be initialized See 1 Init
151. d data MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 72 d MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Library Example The following code tests SD library routines First we fill the buffer with 512 M characters and write it to sector 56 then we repeat the sequence with character E at sector 56 Finally we read the sectors 55 and 56 to check if the write was successful unsigned i unsigned short tmp unsigned short data 512 void main Usart Init 9600 Initialize ports tmp Sd Init amp PORTC 2 Fill the buffer with the M character for i 0 i lt 511 i data i M Write it to SD card sector 55 tmp Sd Write Sector 55 data Fill the buffer with the E character for 1 0 i lt 511 1 data i E Write it to SD card sector 56 tmp Sd Write Sector 56 data Now to check sectors 55 and 56 Read from sector 55 tmp Sd Read Sector 55 data Send 512 bytes from buffer to USART if tmp 0 for i 0 i lt 512 i Usart Write data il Read from sector 56 tmp Sd Read Sector 56 data Send 512 bytes from buffer to USART if tmp 0 for i 0 i lt 512 i Usart Write data il 22522 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS making a simple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Hardw
152. d for use or resale as on line control equipment in hazardous environments requiring fail safe per formance 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 fail ure of the Software could lead directly to death personal injury or severe physical or envi ronmental damage High Risk Activities mikroElektronika and its suppliers specifically dis claim any express or implied warranty of fitness for High Risk Activities LICENSE AGREEMENT By using the mikroC compiler you agree to the terms of this agreement Only one person may use licensed version of mikroC compiler at a time Copyright mikroElektronika 2003 2005 This manual covers mikroC version 2 1 and the related topics Newer versions 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 mikroelektronika co yu Please include next information in your bug report Your operating system Version of mikroC Code sample Description of a bug CONTACT US mikroElektronika Voice 381 11 30 66 377 381 11 30 66 378 Fax 381 11 30 66 379 Web www mikroelektronika co yu E mail office mikroelektronika co yu PIC PICmicro and
153. d to by s2 into the object pointed to by s1 Objects may not overlap Function returns the value of s1 memmove Prototype void memmove void s1 void s2 int n Description Function copies n characters from the object pointed to by s2 into the object pointed to by s1 Unlike with memcpy memory areas s1 and s2 may overlap Function returns the value of s1 memset Prototype void memset void s int c int n Description Function copies the value of character c converted to char into each of the first n characters of the object pointed by s Function returns the value of s strcat Prototype char strcat char s1 char s2 Description Function appends the string s2 to the string s1 overwriting the null character at the end of s1 Then a terminating null character is added to the result Strings may not overlap and 1 must have enough space to store the result Function returns a resulting string 81 page 0 206 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making PER bie uat strchr Prototype char strchr char s char c Description Function locates the first occurrence of character c in the string s Function returns a pointer to the c or a null pointer if c does not occur in s The terminating null character is considered to be a part of the string
154. dding an integral value to the pointer advances the pointer by that number of objects of type Informally you can think of P n as advancing the pointer P by n sizeof type bytes as long as the pointer remains within the legal range first element to one beyond the last ele ment If type has size of 10 bytes then adding 5 to a pointer to type advances the pointer 50 bytes in memory In case of void type size of the step is one byte For example int a 10 array a containing 10 elements of int int pa amp a 0 pa is pointer to int pointing to a 0 3 6 pa 3 is a pointer pointing to a 3 so a 3 now equals 6 pa now points to the next element of array a 1 There is no such element as past the last element of course but a pointer is allowed to assume such a 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 1 is legal but 2 is undefined 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS 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 a pointer pointing to one element past an array which is legal However applying the indi rection operator to a pointer to one past the last el
155. declarations simply make their identifiers and types known to the compiler Here is an overview Declaration is also a definition except if it declares a function without specifying its body it has an extern specifier and has no initializator or body in case of func it is a typedef declaration There be many referencing declarations for the same identifier especially in a multifile program but only one defining declaration for that identifier is allowed MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Let s have an example Here is a nondefining declaration of function max it merely informs compiler that max is a function int max Here is a definition of function max int max int x int y return x y y int i Definition of variable i int i Error i is already defined Declarations and Declarators A declaration is a list of names The names are sometimes referred to as declara tors or identifiers The declaration begins with optional storage class specifiers type specifiers and other modifiers The identifiers are separated by commas and the list is terminated by a semicolon Declarations of variable identifiers have the following pattern storage class type qualifier type 1 initi var2 init2 where var1 var2 are any sequence of distinct
156. dependent types in C When name of the array comes up in expression evaluation except with operators amp and sizeof it is implicitly converted to the pointer pointing to array s first element Due to this fact arrays are not modifiable lvalues Brackets 1 indicate array subscripts The expression id exp 18 defined as id exp where either idis a pointer and exp is an integer or idis an integer and exp is a pointer The following is true amp 1 7 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS According to these guidelines we can write pa amp a 4 pa points to 4 x pa 3 x a 7 y pa 3 y 41 3 Also you need to be careful with operator precedence is equal to increments the pointer pa increments the pointed object Following examples are also valid but better avoid this syntax as it can make the code really illegible a 1 i 3 same as a 1 i 3 i e afi 1 3 i 2 0 same as i 2 a 0 i e afi 2 0 Assignment and Comparison You can use a simple assignment operator 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 neces
157. e The following code can be used for testing the keypad It supports keypads with 1 to 4 rows and 1 to 4 columns The code returned by the keypad functions 1 16 is transformed into ASCII codes 0 9 A F In addition a small single byte counter displays the total number of keys pressed in the second LCD row unsigned short kp cnt char txt 5 void main ent 0 Keypad Init amp PORTC Lcd Init amp PORTB Initialize LCD on PORTC Lcd Cmd LCD CLEAR Clear display Lcd Cmd LCD CURSOR OFF Cursor off Lcd Out 1 1 Key Lcd Out 2 1 Times do kp 0 Wait for key to be pressed do un comment one of the keypad reading functions kp Keypad Released kp Keypad Read while kp cnt prepare value for output if kp gt 10 kp 54 else kp 47 print it on LCD Lcd Chr 1 10 kp WordToStr cnt txt Lcd Out 2 10 txt while 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 9 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS HW Connection PIC16F877A MCLR Vpp THV RB7 PGD RAO ANO RB6 PGC RA1 AN1 RB5 RA2 AN2 Vref RB4 RA3 AN3 Vref RB3 PGM RA4 TOCKI RB2 RA5 AN4 RB1 REO RD ANS RBO INT RE1 WR AN6 Vdd RE2 CS AN7 Vss Vdd RD7 PSP7 Vss RD6 PSP6 OSC1 RD5 PSP5 OSC2 RD4 PSP4 RCO T1OSO RC7 RX DT 1 1051 RC6 TX CK RC2 CCP1 RC5
158. e PIC16 family lacks hardware resources to multiply 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 recur sive calls or to another function Recursive calls as form of cross calling are unsupported by mikroC due to the PIC s stack and memory limitations mikroC limits the number of non recursive nested calls to 8 calls for PIC12 family 8 calls for PIC16 family 31 calls for PIC18 family The number of allowed nested calls decreases by one if you use any of the follow ing operators in the code It further decreases by one if you use interrupt in the program If the allowed number of nested calls is exceeded compiler will report stack overflow error 2220 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS B MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS 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
159. e packet Library Routines RSA85Master Init RSA85Master Receive RS485Master Send RSA85Slave Init RSA85Slave Receive RS485Slave Send MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2204193 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple RS485Master Init Prototype void RS485Master Init void Description Initializes PIC MCU as Master in RS 485 communication Requires USART HW module needs to be initialized See Init Example RS485Master Init RS485Master Receive Prototype void RS485Master Receive char data Description Receives any message sent by Slaves Messages are multi byte so this function must be called for each byte received see the example at the end of the chapter Upon receiving a message buffer is filled with the following values data 0 2 is the message data 3 is number of message bytes received 1 3 data 4 is set to 255 when message is received data 5 is set to 255 if error has occurred data 6 is the address of the Slave which sent the message Function automatically adjusts data 4 and data 5 upon every received message These flags need to be cleared from the program Requires MCU must be initialized as Master in RS 485 communication in order to be assigned an address See RS485Master Init Example unsigned short msg 8 RSA485Master Receive msg DAA MIKROELEKTRONIKA DEVEL
160. e root of MMC card and fills them with some data You can check the file dates which should be different char FAT_ERROR 20 FAT16 not found char file_contents 50 XX MMC SD FAT16 library by Anton Rieckert char filename 14 MIKROOOxTXT File names unsigned short tmp character loop long i size void main PORTB 0 TRISB 0 Usart Init 19200 Set up USART for reading the files if Mmc Fat Init amp PORTC 2 Try to find the FAT tmp 0 while FAT ERROR tmp Usart Write FAT ERROR tmp for loop 1 loop lt 5 1 We want 5 files on our MMC card filename 7 loop 64 Set number 1 2 3 4 or 5 Mmc Fat Assign amp filename If file not found create new file Mmc Fat Rewrite Clear the file start with new data file contents 0 loop 10 48 file contents 1 loop 10 48 Mmc Fat Write file contents 41 Write data to the assigned file Mmc Fat Append Add more data to file Mmc Fat Write file contents 41 Write data to file Delay ms 200 Now if we want to add more data to those same files for loop 1 loop lt 5 loop filename 7 loop 64 Mmc Fat Assign amp filename Assign a file Mmc Fat Append Mmc Set File Date 2005 6 21 10 100p 0 Fat Write for mikroElektronika 2005 r n 30 Mmc Fat Append Mmc Fat Write file contents 41 Mmc Fat Reset amp size To read file returns file size
161. e routines support module on RC2 and won t work with modules on other ports You can find examples for PICmicros with module on other ports in mikroC installation folder subfolder Examples Also mikroC does not support enhanced PWM modules Library Routines Pwm_Init Pwm_Change_Duty Pwm Start Pwm_Stop Pwm_lnit Prototype void Pwm Init long freq Description Initializes the PWM module with duty ratio 0 Parameter req is a desired PWM fre quency in Hz refer to device data sheet for correct values in respect with Fosc Pwm Init needs to be called before using other functions from PWM Library Requires You need a CCP module on PORTC to use this library Check mikroC installation fold er subfolder Examples for alternate solutions Example Pwm Init 5000 Initialize module at 5KHz DAO MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot MIKROG Pwm Change Duty COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Prototype void Pwm Change Duty char duty ratio Description Changes PWM duty ratio Parameter duty_ratio takes values from 0 to 255 where 0 is 0 127 is 50 and 255 is 100 duty ratio Other specific values for duty ratio can be calculated as Percent 255 100 Requires You need a CCP module on PORTC to use this library To use this function module needs to be initalized see Pwm_Ini
162. e void Lcd Init char port Description Initializes LCD at port with default pin settings see the connection scheme at the end of the chapter D7 gt PORT 7 D6 gt PORT 6 D5 gt 5 D4 gt PORTA E gt PORT RS gt PORTA Example Lcd Init PORTB Lcd Out Prototype void Lcd Out char row char col char text Description Prints text on LCD at specified row and column parameter row and 1 Both string variables and literals can be passed as text Requires Port with LCD must be initialized See Lcd Config or Lcd Init Example Lcd Out 1 3 Hello Print Hello at line 1 char 3 Lcd Out Cp Prototype void Lcd Out Cp char text Description Prints text on LCD at current cursor position Both string variables and literals can be passed as text Requires Port with LCD must be initialized See Lcd Config or Lcd Init Example Lcd Out Cp Here Print Here at current cursor position page ES a MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making de Mino ce CEMPICER FOR MICROCHIP PIE Mur Lcd Chr Prototype void Lcd Chr char row char col char character Description Prints character on LCD at specified row and column parameters row and co1 Both variables and literals can be passed as character Requires Port with LCD must be initialized See Lcd Config or
163. ed and user defined data types includ ing signed and unsigned integers in various sizes floating point numbers in vari ous precisions arrays structures and unions In addition pointers to most of these objects can be established and manipulated in memory The type determines how much memory is allocated to an object and how the 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 on those values The compile time operator sizeof lets you determine the size in bytes of any standard or user defined type The mikroC standard libraries and your own program and header files must pro vide unambiguous identifiers or expressions derived from them and types so that mikroC can consistently access interpret and possibly change the bit patterns in memory corresponding to each active object in your program Type Categories The fudamental types represent types that cannot be separated into smaller parts They are sometimes referred to as unstructured types The fundamental types are void char int float and double together with short long signed and unsigned variants of some of these The derived types are also known as structured types The derived types include pointers to other types arrays of other types function types structures an
164. ed and communication established before using this function See Usart Init Example int receive If data is ready read it if Usart Data Ready receive Usart Read Usart Read Prototype char Usart Read void Returns Returns the received byte If byte is not received returns 0 Description Function receives a byte via USART Use the function Usart Data Ready to test if data 15 ready first Requires USART HW module must be initialized and communication established before using this function See Usart Init Example int receive If data is ready read it if Usart Data Ready receive Usart Read Age DYR MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Usart_Write Prototype char Usart Write char data Description Function transmits a byte data via USART Requires USART HW module must be initialized and communication established before using this function See Usart Init Example int chunk Usart Write chunk send data chunk via USART Library Example The example demonstrates simple data exchange via USART When PIC MCU receives data it immediately sends the same data back If PIC is connected to the PC see the figure below you can test the example from mikroC terminal for RS232 communic
165. ed out with null charac ters to make up the difference Function returns the resulting string s1 strspn Prototype int strspn char s1 char s2 Description Function returns the length of the maximum initial segment of s1 which consists entire ly of characters from s2 The terminating null character character at the end of the string is not compared page 000 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Conversions Library mikroC Conversions Library provides routines for converting numerals to strings and routines for BCD decimal conversions Library Routines You can get text representation of numerical value by passing it to one of the fol lowing routines ByteToStr ShortToStr WordToStr IntToStr LongToStr FloatToStr Following functions convert decimal values to BCD Binary Coded Decimal and vice versa Bcd2Dec Dec2Bcd Bcd2Dec16 Dec2Bcd16 ByteToStr Prototype void ByteToStr unsigned short number char output Description Function creates an output string out of a small unsigned number numerical value less than 0x100 Output string has fixed width of 3 characters remaining positions on the left 1f any are filled with blanks Example unsigned short t 24 char txt ByteToStr t txt txt is 24 one blank here MIKROELEKTRONIKA DEVELOPME
166. eft without changing display data RAM LCD MOVE CURSOR RIGHT Move cursor right without changing display data RAM LCD TURN ON Turn LCD display on LCD TURN OFF Turn LCD display off LCD SHIFT LEFT Shift display left without changing display data RAM LCD SHIFT RIGHT Shift display right without changing display data RAM MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making a simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example default pin settings char text mikroElektronika void main TRISB 0 PORTB is output Lcd Init amp PORTB Initialize LCD connected to PORTB Lcd Cmd Lcd CLEAR Clear display Lcd Cmd Lcd CURSOR OFF Turn cursor off Lcd Out 1 1 text Print text to LCD 2nd row 1st column Hardware Connection PIC MCU any port with 8 pins PINO PIN1 PIN2 PIN3 4 5 6 gt a lt LCD PI7 gt D7 PING PINS D5 lt gt D4 lt gt RS PIN1 PINO o c c o a o l MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 20M4 MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple Library Example custom pin
167. eleased Requires PS 2 keyboard needs to be initialized see Ps2 Init or Ps2 Config Example Press Enter to continue do if Ps2 Key Read amp value amp special amp pressed if value 13 amp amp special 1 break while 1 2203693 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making a dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example This simple example reads values of keys pressed on PS 2 keyboard and sends them via USART unsigned short keydata special down void main CMCON 0x07 Disable analog comparators comment this for PIC18 INTCON 0 Disable all interrupts Ps2 Init amp PORTA Init PS 2 Keyboard on PORTA Delay ms 100 Wait for keyboard to finish do if Ps2 Key Read amp keydata amp special amp down if down amp amp keydata 16 Backspace do something with a backspace else if down amp amp keydata 13 Enter Usart Write 13 else if down amp amp special amp amp keydata Usart Write keydata Delay 10 debounce while 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS D amp S MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making e simple PWM Library CCP module is available with a number of PICmicros mikroC provides library which simplifies using PWM HW Module Note Thes
168. ement leads to undefined behavior For example void f some type al int n function f handles elements of array a array a has n elements of some type int i some type p amp 0 for i 0 lt n i 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 Pointer Subtraction Similar to addition you can use operators and to subtract an integral value from a pointer Also you may subtract two pointers Difference will equal the distance between the two pointed addresses in bytes For example int a 10 int pil amp a 0 pi2 6141 i pi2 pil i equals 8 pi2 i gt gt 1 pi2 pi2 4 pi2 now points to 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 33 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Structures A structure is a derived type usually representing a user defined collection of named members or components The members can be of any type either funda mental or derived with some restrictions to be noted later in any sequence In addition a structure member can be a bit field type not allowed elsewhere Unlike arrays structures are considered single objects The mikroC structure type lets you handle complex data structures almost as easily as single variables Note mik
169. en Glcd Write Text Circles 0 0 1 j 4 while j lt 31 Glcd Circle 63 31 1 2 J 4 Delay_ms 4000 Draw boxes Glcd Fill 0 Clear screen Glcd Write Text Rectangles 0 0 1 j 0 while j lt 31 Glcd Box j 0 j 20 j 25 2 j 4 Delay_ms 4000 Draw Lines Glcd Fill 0 Clear screen Glcd Write Text Lines 0 0 1 for j 0 j lt 16 j k 3 4 3 Glcd Line 0 0 127 k 2 for j 0 j lt 31 j k 3 4 3 Glcd Line 0 63 k 0 2 Delay ms 4000 while 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 24 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Hardware Connection O 5000000000000000000 0 2 d MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS Manchester Code Library mikroC provides a library for handling Manchester coded signals 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 a 0 or a 1 second half is the true bit value and the first half is the complement of the true bit v
170. er interpretation of the IP packet header at the very beginning of UDP packet header retrieval Example udp source port Eth Get Udp Source Port Eth Get Udp Dest Port Prototype unsigned Eth Get Udp Dest Port void Returns Returns the destination port of the received UDP packet Description The function returns the destination port of the received UDP packet The second information contained in the UDP packet header is the destination port socket to which the packet is targeted Requires This function must be called in a proper sequence i e immediately after calling the Eth Get Udp Source Port function Example udp dest port Eth Get Udp Dest Port a 920 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making amp imple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Eth_Get_Udp Port Prototype unsigned short Eth Get Udp Port void Returns Returns the UDP port socket number that is set for the PIC s Ethernet card Description The function returns the UDP port socket number that is set for the PIC s Ethernet card After the UDP port is set at the beginning of the session Eth_Set_Udp_ Port its number is later used to test whether the received UDP packet is targeted at the port we are using Requires The network card must be properly initialized see Eth_Init and the UDP port propely set see Eth_Set_Udp Por
171. es 8 000000 MHz Double clicking one of the items opens a window in which you can assign a new value to the selected variable or register and change number formatting page ES MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making a simple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Stopwatch Window The Stopwatch Window displays the current count of cycles time since the last Debugger action Stopwatch measures the execution time number of cycles from the moment the Debugger is started and can be reset at any time Delta represents the number of cycles between the previous instruction line line where the Debugger action was performed and the active instruction line where the Debugger action landed Note You can change the clock in the Stopwatch Window this will recalculate values for the newly specified frequency Changing the clock in the Stopwatch Window does not affect the actual project settings it only provides a simulation Watch Window OIA Eh Eh 08 a H Variables Stopwatch Call Stack Cycles Time Delta 1 00 us Current Count 36 00 us Stopwatch 0 8 36 00 us 72 cycles 8 000000 MHz MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple Call Stack Window The Call Stack Window keeps track of depth and order of nested routine calls in
172. es etc Assembler File asm Human readable assembly with symbolic names extracted from the List File Assembly View After compiling your program in mikroC you can click View Assembly Icon or A select Project View Assembly from drop down menu to review generated assem View Assembly PIY code asm file in a new tab window Assembly is human readable with sym Icon bolic names physical addresses and other information can be found in Statistics or in list file 1st If the program is not compiled and there is no assembly file starting this option will compile your code and then display assembly 2G MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS ERROR MESSAGES Error Messages Specifier needed Invalid declarator Expected or identifier Integer const expected Array dimension must be greater then 0 Local objects cannot be extern Declarator error Bad storage class Arguments cannot be of void type Specifer qualifier list expected Address must be greater than 0 Identifier redefined case out of switch default label out of switch switch exp must evaluate to integral type continue outside of loop break outside of loop or switch void func cannot return values Unreachable code Illegal expression with void Left operand must be pointer Function requi
173. essage from receive buffer or zero if no message found Description 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 id is message identifier data is an array 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 Requires CAN must be in mode in which receiving is possible Example char rcv rx len data 8 long id rcv CANRead id data len 0 CANWrite Prototype char CANWrite long id char data char datalen char CAN TX MSG FLAGS Returns Returns zero if message cannot be queued buffer full Description If at least one empty transmit buffer 1s 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 CAN TX MSG FLAGS is value formed from constants see CAN constants Requires CAN must be in Normal mode Example char tx data long id tx CAN TX PRIORITY 0 amp CAN TX XTD FRAME CANWrite id data 2 tx ES 4 456 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP
174. exclusively of decimal digits with an optional whitespace and a sign at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize this includes a null character atol Prototype long atol char s Description Function converts the input string s into a long integer value and returns the value Input string s should consist exclusively of decimal digits with an optional whitespace and a sign at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize this includes a null charac ter div Prototype div t div int numer int denom Description Function computes the result of the division of the numerator numer by the denominator denom function returns a structure of type div t comprising quotient quot and remainder rem page 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS making m simple TEE S P TOE eo eee eee Idiv Prototype ldiv t ldiv long numer long denom Description Function is similar to the div function except that the arguments and the result struc ture members all have type 1ong Function computes the result of the division of the numerator numer by the denominator denom function returns a structure of type div t comprising quotient quot an
175. expression is not evaluated For example a amp b c amp amp d reads as amp amp b c amp amp d if a amp amp b is true 1 c amp amp d will not be evaluated Books COMPILERS MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Logical Expressions and Side Effects General rule with complex logical expressions is that the evaluation of consecutive logical operands stops the very moment the final result is known For example if we have an expression a amp amp b amp amp c where a 18 false 0 then operands b and c will not be evaluated This is very important if b and c are expressions as their possible side effects will not take place Logical vs Bitwise Be aware of the principle difference between how bitwise and logical operators work For example 0222222 amp 0555555 0222222 amp amp 0555555 0x1234 0x1234 equals equals equals equals 000000 1 OxEDCB MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Conditional Operator The conditional operator is the only ternary operator in C Syntax of the con ditional operator is expressionl expression2 expression3 1 evaluates first If its value is true then expression2 evaluates and expression3 is ignored If expressioni evaluates to false then expres sion3
176. ext 0000 0000 7 004E i 0000 0000 itor 0027 Istri 00100000 01000001 0 cycles 8 000000 MHz m variable unsigned int tmp Project Setup Project Summary variable unsigned short T1_count Breakpoints w Module Line Number Devoe TOSH counter 100 P18F8720 x TOSL counter 117 Clock ann counters 88 008 000000 MHz E il 150 lines in file 1 G Messages 5 Find lil QConvertor Line Column Message No Message Test unit 0 0 5 Warning Identifier FisPin overrides declaration in init Icd Pointers lest E rror 00 5 Warming Identifier EnPin overrides declaration in irit Icd_4bit Pointers_test Identifier k was not declared Pointers test Win d OW 00 101 Build failed Code Breakpoints Assistant Window mikroC allows you to quickly develop and deploy complex applications Write your C source code using the highly advanced Code Editor Use the included mikroC libraries to dramatically speed up the development data acquisition memory displays conversions communications Monitor your program structure variables and functions in the Code Explorer Generate commented human readable assembly and standard HEX compatible with all programmers Inspect program flow and debug executable logic with the integrated Debugger Get detailed reports and graphs on code statistics assembly listing calling tree We have provided plenty of examples for you to expand develop and use a
177. f bits that may or may not have an associated identifier Bit fields offer a way of subdividing structures into named parts of user defined sizes mikroC implementation of bit fields requires you to set aside a structure for the purpose i e you cannot have a structure containing bit fields and other objects Bit fields structure can contain up to 8 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 solu tion is to use mikroC 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 Declare a structure normally and assign individual fields like this fields need to be unsigned struct tag unsigned bitfield declarator list 9300 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS Here tag is an optional name of the structure bitfield declarator list is a list of bit fields Each component identifer requires a colon and its width in bits to be explicitly specified Total width of all components cannot exceed one byte 8 bits As an object bit fields structure takes one byte Individual fields are packed with in byte from right to left In bitfield declarator list you can om
178. f enum type are declared 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 colors a variable c of this type and a set of enumerators with constant integer values black 0 1 InC a variable of an enumerated type can be assigned any value of type int no type checking beyond that is enforced That is c red OK 1 Also OK means the same Q ll 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 initializ ers will then increase by one These values are usually unique but duplicates are legal O 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS The order of constants can be explicitly re arranged For example enum colors black value 0 red value 1 green value 2 blue 6 value 6 violet value 7 white 4 value 4 Initializer expression can include previously declared enumerators For example in the following declaration enum memory sizes bit 1 nibble 4 bit byte 2 nibble kilobyte 1024 byte nibble would acquire the value 4 byte the value 8 and kilobyte the value 8192 Anonymous Enu
179. fier in a prototype parameter it is used only for any later error messages involving that parameter it has no other effect VHA MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 9 MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Function Definition Function definition consists of its declaration and a 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 This means that func tion declarations cannot be nested To return the function result use the return statement Statement return in functions of void type cannot have a parameter in fact you can omit the return statement 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 y Here is a sample function which depends on side effects rather than return value function converts Descartes coordinates x y to polar coordinates r fi include math h void polar double x double y double r double fi sqrt x x y y fi x 0 amp amp y 0 0 atan2 y x return
180. fiers 47 Punctuators 48 Objects and Lvalues 52 Scope and Visibility 54 Name Spaces 56 Duration 57 Types 59 Fundamental Types 60 Arithmetic Types 60 Enumeration Types 62 Void Type 64 Derived Types 65 Arrays 65 Pointers 68 Pointer Arithmetic 70 Structures 74 Unions 79 Bit Fields 80 Types Conversions 82 Standard Conversions 82 Explicit Typecasting 84 Declarations 85 Linkage 87 Storage Classes 89 Type Qualifiers 91 Typedef Specifier 92 asm Declaration 93 Initialization 94 Functions 95 Function Declaration 95 Function Prototypes 96 Function Definition 97 Function Calls 98 Operators 100 Precedence and Associativity 100 Arithmetic Operators 102 Relational Operators 104 Bitwise Operators 105 Logical Operators 107 Conditional Operator 109 Assignment Operators 110 sizeof Operator 112 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS 0000000 iMG 62 ames Expressions 113 Statements 115 Labeled Statements 115 Expression Statements 116 Selection Statements 116 Iteration Statements 119 Jump Statements 122 Compound Statements Blocks 124 Preprocessor 125 Preprocessor Directives 125 Macros 126 File Inclusion 130 Preprocessor Operators 131 Conditional Compilation 132 CHAPTER 4 mikroC Libraries 135 Built in Routines 136 Library Routines 138 ADC Library 139 CAN Library 141 CANSPI Library 153 Compact Flash Library 162 EEPROM Library 172 Ethernet Library 174
181. g MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2022 MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Library Example unsigned short error ErrorCount IdleCount temp LetterCount void main ErrorCount 0 TRISC 0 Error indicator PORTC 03 Man Receive Config amp PORTD 6 Synchronize receiver Lcd Init amp PORTB Initialize LCD on PORTB while 1 Endless loop IdleCount 0 Reset idle counter do temp Man Receive error Attempt byte receive if error ErrorCount else PORTC 0 if ErrorCount gt 20 Tf there are too many errors ErrorCount 0 syncronize the receiver again PORTC OxAA Indicate error Man Receive Init amp PORTD Synchronize receiver IdleCount if IdleCount gt 18 If nothing received after some time IdleCount 0 try to synchronize again Man Receive Init amp PORTD Synchronize receiver while temp End of message marker if error 255 If no error then write the message Lcd Cmd LCD CLEAR LetterCount 0 while LetterCount lt 17 Message is 16 chars long LetterCount j temp Man Receive error if error p 255 Lcd Chr Cp temp else ErrorCount break temp Man Receive error if temp OxOE ErrorCount end if end while page T MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS
182. g type is a pointer to a type qualified with all the type qualifiers of the types pointed to by both operands 6 One operand 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 operand Assignment Operators Unlike many other programming languages C treats value assignment as an oper ation represented by an operator rather than instruction Simple Assignment Operator For a common value assignment we use a simple assignment operator expressionl expression2 Expression1 is an object memory location to which we assign value of expression2 Operand expression1 has to be a lvalue and expression2 can be any expression The assignment expression itself is not an lvalue If 1 and 2 are of different types result of the expres sion2 will be converted to the type of 1 if necessary Refer to Conversions for more information Compound Assignment Operators C allows more comlex assignments by means of compound assignment operators Syntax of compound assignment operators 15 expressionl op expression2 where op can be one of binary operators amp lt lt gt gt 4 il 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPI
183. heme at the end of the topic Library Routines Keypad_Init Keypad_Read Keypad_Released Keypad Init Prototype void Keypad Init char port Description Initializes port to work with keypad The function needs to be called before using other routines of the Keypad library Example Keypad Init amp PORTB Keypad Read Prototype unsigned Keypad Read void Returns 1 16 depending on the key pressed or 0 if no key is pressed Description Checks if any key is pressed Function returns 1 to 16 depending on the key pressed or 0 if no key is pressed Requires Port needs to be appropriately initialized see Keypad Init Example kp Keypad Read MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making simple Keypad_Released Prototype unsigned Keypad Released void Returns 1 16 depending on the key Description Call to Keypad_Released is a blocking call function waits until any key is pressed and released When released function returns to 16 depending on the key Requires Port needs to be appropriately initialized see Keypad_Init Example kp Keypad Released page 0 a 9l MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS mikroC making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS Library Exampl
184. here needed without any user interference Also you can explicitly convert an operand to another type using the prefix unary typecast operator type object For example char a b Following line will coerce a to unsigned int unsigned int a Following line will coerce a to double then coerce b to double automatically resulting in double type value double a b equivalent to double a b 9302 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS DECLARATIONS Introduction to Declarations Declaration introduces one or several names to a program it informs the compil er what the name represents what is its type what are allowed operations 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 Declarations and Definitions Defining declarations also known as definitions beside introducing the name of an object also establish the creation where and when of the object that is the allocation of physical memory and its possible initialization Referencing declara tions or just
185. ically to give the six tokens The ASCII characters representing whitespace can occur within literal strings in which case they are protected from the normal parsing process they remain as part of the string BIO MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 3 MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Comments Comments are pieces of text used to annotate a program and are technically another form of whitespace Comments are for the programmer s use only they are stripped from the source text before parsing There are two ways to delineate comments the C method and the C method Both are supported by mikroC C comments C comment is any sequence of characters placed after the symbol pair The comment terminates at the first occurrence of the pair following the initial The entire sequence including the four comment delimiter symbols is replaced by one space after macro expansion In mikroC int type i identifier parses as int i Note that mikroC does not support the nonportable token pasting strategy using For more on token pasting refer to Preprocessor topics C comments mikroC allows single line comments using two adjacent slashes The com ment start in any position and extends until the next new line The following code int i this is a comment int j parses as int i in
186. 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 DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Expression Statements Any expression followed by a semicolon forms an expression statement expression mikroC executes an expression statement by evaluating the expression All side effects from this evaluation are completed before the next statement is executed Most expression statements are assignment statements or function calls The null statement is a special case consisting of a single semicolon The null statement does nothing and is therefore useful in situations where the mikroC syn tax expects a statement but your program does not need one For example null statement is commonly used in empty loops for q p body of this loop is a null statement Selection Statements Selection or flow control statements select from alternative courses of action by testing certain values There are two types of selection statements in C if and switch If Statement Use if to implement a conditional statement Syntax of if statement is if expression statementi else statement2 When expression eval
187. ikroC MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Library Example The following code tests MMC library routines First we fill the buffer with 512 M characters and write it to sector 56 then we repeat the sequence with character E at sector 56 Finally we read the sectors 55 and 56 to check if the write was successful unsigned i unsigned short tmp unsigned short data 512 void main Usart Init 9600 Wait until MMC is initialized while Mmc Init amp PORTC 2 Fill the buffer with the M character for i 0 i lt 511 i data i M Write it to MMC card sector 55 tmp Mmc Write Sector 55 data Fill the buffer with the E character for i 0 i lt 511 i data i E Write it to MMC card sector 56 tmp Mmc Write Sector 56 data Now to check sectors 55 and 56 Read from sector 55 tmp Mmc Read Sector 55 data Send 512 bytes from buffer to USART if tmp 0 0 for i 0 i lt 512 i Usart Write data il Read from sector 56 tmp Mmc Read Sector 56 data Send 512 bytes from buffer to USART if tmp 0 0 for i 0 i lt 512 i Usart Write data il MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Library Example The following program tests MMC FAT routines It creates 5 different files in th
188. ile will be created with the given name The ilename must be 8 3 characters in uppercase Requires Library needs to be initialized see Fat Init Example Assign the file EXAMPLE1 TXT in the root directory of MMC If the file is not found routine will create one Mmc Fat Assign EXAMPLE1TXT MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 202 MIKROG COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Mmc_Fat_Reset Prototype void Mmc Fat Reset unsigned long size Description Function resets the file pointer moves it to the start of the file of the assigned file so that the file can be read Parameter size stores the size of the assigned file in bytes Requires Library needs to be initialized see Mmc_Fat_Init Example Mmc Fat Reset amp filesize Mmc_Fat_Rewrite Prototype void Mmc Fat Rewrite void Description Function resets the file pointer and clears the assigned file so that new data can be writ ten into the file Requires Library needs to be initialized see Mmc_Fat_Init Example Mmc Fat Rewrite Mmc Fat Append Prototype void Mmc Fat Append void Description The function moves the file pointer to the end of the assigned file so that data can be appended to the file Requires Library needs to be initialized see Fat Init Example Mmc Fat Append page 0 0
189. in a wide variety of applications and C prized for its efficiency is the natural choice for developing embedded systems mikroC provides a successful match featuring highly advanced IDE ANSI compliant compiler broad set of hardware libraries comprehensive documentation and plenty of ready to run examples MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple mikroC for PIC by mikroElektronika DES Watch File Edit Search Project Run View Tools Help Window e wA X S GH P M View Statistics View Assembly Eh Stat Debugger Eh Eh eo 9 cec Code Explorer GHelp Keyboard Watch Window B Eh er e C E Functions F Variables Stopwatch Call Stack interrupt SEC Extract Digit 2 Address Name Explorer Master digi 0047 input pend 0048 SPlib S A spi read 0000 0000 0047 dala 0000 0000 dgi3 s 0048 temp 0000 0000 main 004 _getADC 0000 C506 EH global e 0052 measurement 0000 0000 LED MASK 0054 lastValue 0000 0001 0040 channel 0000 0000 2 004E tmp 33 P on 0048 0000 0000 mitis 0040 0000 0000 send flag 0048 Column 0000 0000 C d 3SaveFSRL 004C Row 0000 0000 oqe 3SaveFSRH 004D t
190. ining declarations will be ignored with an appropriate warning issued by link er Directive org cannot be applied to an interrupt routine Here is a simple example void func char par org 0x200 Function will start at address 0x200 nop MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple LEXICAL ELEMENTS These topics provide a formal definition of the mikroC lexical elements They describe the different categories of word like units tokens recognized by a lan guage In the tokenizing phase of compilation the source code file is parsed that is bro ken down into tokens and whitespace The tokens in mikroC are derived from a series of operations performed on your programs by the compiler and its built in preprocessor A mikroC program starts as a sequence of ASCII characters representing the source code created by keystrokes using a suitable text editor such as the mikroC editor The basic program unit in mikroC is the file This usually corresponds to a named file located in RAM or on disk and having the extension c Whitespace Whitespace is the collective name given to spaces blanks horizontal and vertical tabs newline characters and comments Whitespace can serve to indicate where tokens start and end but beyond this function any surplus whitespace is discard ed For example the two sequences int i float f and int i float f are lexically equivalent and parse ident
191. is changing it to the same object of another type i e applying another type to a given object C defines a set of standard conver sions for built in types provided by compiler when necessary Conversion is required in following situations if statement requires an expression of particular type according to language definition and we use an expression of different type if operator requires an operand of particular type and we use an operand of different type if a function requires a formal parameter of particular type and we pass it an object of different type if an expression following the keyword return does not match the declared function return type if intializing an object in declaration with an object of different type In these situations compiler will provide an automatic implicit conversion of types without any user interference Also user can demand conversion explicitly by means of typecast operator For more information refer to Explicit Typecasting Standard Conversions Standard conversions are built in C These conversions are performed automatical ly whenever required in the program They can be also explicitly required by means of typecast operator refer to Explicit Typecasting The basic rule of automatic implicit conversion 1s that the operand of simpler type is converted promoted to the type of more complex operand Then type of the result is that of more complex operand 8 2 M
192. is void function also does not take any arguments note that this 15 the only case when void can be used as an argument s type Unlike with variable declaration each argument in the list needs its own type specifier and a possible qualifier const or volatile Function Prototypes A given function can be defined only once in a program but can be declared sev eral times provided the declarations are compatible If you write a nondefining declaration of a function i e without the function body you do not have to specify the formal arguments This kind of declaration commonly known as the function prototype allows better control over argument number and type checking and type conversions Name of the parameter in function prototype has its scope limited to the prototype This allows different parameter names in different declarations of the same func tion 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 greatly aid in documenting code For example the function Cf Init takes two parameters Control Port and Data Port The question is which is which The function prototype void Cf Init char ctrlport char dataport makes it clear If a header file contains function prototypes you can that file to get the information you need for writing programs that call those functions If you include an identi
193. it doesn t recognize this includes a null character 22941 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS ANSI C String Library mikroC provides a set of standard ANSI C library functions useful for manipulat ing strings and arrays of char Note Not all of the standard functions have been included Functions have been implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC programming Library Routines memcmp memcpy memmove memset strcat strchr strcmp strcpy strlen strncat strncpy strspn memcmp Prototype int memcmp void 51 void s2 int n Description Function compares the first n characters of objects pointed to by s1 and s2 and returns zero if the objects are equal or returns a difference between the first differing characters in a left to right evaluation Accordingly the result is greater than zero if the object pointed to by s1 is greater than the object pointed to by s2 and vice versa MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 220 mecnm decies making 52 simple i memcmp Prototype void memcpy void 51 void s2 int n Description Function copies n characters from the object pointe
194. it identi fier s to create artificial padding thus skipping irrelevant bits For example if we need to manipulate only bits 2 4 of a register as one block we could create a structure struct unsigned 2 Skip bits 0 and 1 no identifier here mybits 3 Relevant bits 2 3 4 Bits 5 6 and 7 are implicitly left out myreg Here is an example typedef struct prescaler 2 timeronoff 1 postscaler 4 mybitfield which declares structured type mybitfield containing three components prescaler bits 0 and 1 timeronoff bit 2 and postscaler bits 3 4 5 and 6 Bit Fields Access Bit fields can be accessed in same way as the structure members Use direct and indirect member selector and gt For example we could work with our previously declared mybit field like this Declare a bit field TimerControl mybitfield TimerControl void main TimerControl prescaler 0 TimerControl timeronoff 1 TimerControl postscaler 3 T2CON TimerControl MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS al MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple TYPES CONVERSIONS C is 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
195. k rules Thus deeply nested declaration of structure 1s identical to an equivalent global declaration As a consequence once that you have defined a tag you cannot redefine it in any block within file G l MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Visibility The visibility of an identifier is that region of the program source code from which legal access can be made to the identifier s associated object 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 is ended Technically visibility cannot exceed scope but scope can exceed visibility Take a look at the following example void f int i int j auto by default int i j are in scope and visible nested block double j j is local name in the nested block j 0 1 i and double j are visible int j 3 in scope but hidden double j out of scope J e ais int j visible and 4 i 1 are both out of scope MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 55 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making e simple NAME SPACES Name space is the scope
196. le PROJECTS mikroC organizes applications into projects consisting of a single project file extension ppc and one or more source files extension c You can compile source files only if they are part of a project Project file carries the following information project name and optional description target device device flags config word and device clock list of project source files with paths ES New Project The easiest way to create project is by means of New Project Wizard drop down menu Project gt New Project Just fill the dialog with desired values project name and description location device clock config word and mikroC will create the appropriate project file Also an empty source file named after the project will be created by default Editing Project Edit Project Later you can change project settings from drop down menu Project gt Edit Project You can rename the project modify its description change chip clock config word etc To delete a project simply delete the folder in which the project file is stored New Project Add Remove Files from Project e Project can contain any number of source files extension c The list of relevant source files is stored in the project file extension ppc To add source file to your project select Project Add to Project from drop down menu Each added gl source file must be self contained i e it must have a
197. le state low and data transmitted at low to high edge SDI pin is RB1 SDO pin is RB2 and SCK pin is RB3 Soft_Spi_Config PORTB 1 2 3 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Soft_Spi_Read Prototype char Soft Spi Read char buffer Returns Returns the received data Description Provides clock by sending buffer and receives data Requires Soft SPI must be initialized and communication established before using this function See Soft Spi Config Example tmp Soft Spi Read buffer Soft Spi Write Prototype void Soft Spi Write char data Description Immediately transmits data Requires Soft SPI must be initialized and communication established before using this function See Soft Spi Config Example Soft Spi Write 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2 9 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Library Example This is a sample program which demonstrates the use of the Microchip s MCP4921 12 bit D A converter with PIC mcu s This device accepts digital input number from 0 4095 and transforms it to the output voltage ranging from 0 Vref In this example the D A is connected to PORTC and communicates with PIC through the SPI The reference voltage on the mikroElektronika s
198. ll the necessary definitions after preprocessing To remove file s from your project select Project gt Remove from Project from drop down menu Add to Project Remove from Project Note For inclusion of header files use the preprocessor directive include 2022 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS SOURCE FILES MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 72 9 Source files containing C code should have the extension c List of source files relevant for the application is stored in project file with extension ppc along with other project information You can compile source files only if they are part of a project Use the preprocessor directive include to include headers Do not rely on pre processor to include other source files see Projects for more information Search Paths Paths for source files c You can specify your own custom search paths This can be configured by select ing Tools gt Options from drop down menu and then tab window Advanced In project settings you can specify either absolute or relative path to the source file If you specify a relative path mikroC will look for the file in following loca tions in this particular order 1 the project folder folder which contains the project file ppc 2 your custom search paths 3 mikroC installation folder gt uses folder
199. m Type In our previous declaration the identifier colors is the optional enumeration tag that can be used in subsequent declarations of enumeration variables of type colors enum colors bg border declare variables bg and border As with struct and union declarations you can omit the tag if no further variables of this enum type are required Anonymous enum type enum black red green blue violet white color Enumeration Scope Enumeration tags share the same name space as structure and union tags Enumerators share the same name space as ordinary variable identifiers For more information consult Name Spaces MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 8 83 MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple void is a special type indicating the absence of any value There are no objects of void instead void is used for deriving more complex types Void Functions Use the void keyword as a function return type if the function does not return a value For example void print_temp char temp Lcd Out Cp Temperature Lcd Out Cp temp Lcd Chr Cp 223 degree character Chr Cp C Use void as a function heading if the function does not take any parameters Alternatively you can just write empty parentheses main void same as main ae Generic Pointers Pointers can be declared as void meaning that they can point to any type These poi
200. m predefined constants see CAN constants page 145 Requires CANSPI must be in Config mode otherwise the function will be ignored Example init CAN CONFIG SAMPLE THRICE amp 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 CANSPIInitialize 1 1 3 3 1 init initialize CANSPI MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 55 MEBHE f COMENER EOR MICROCHIP PIC MEHOCONTROLCERS a ki NG E IMPE CANSPISetBaudRate Prototype void CANSPISetBaudRate char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CAN CONFIG FLAGS Description Sets CANSPI baud rate Due to complexity of CANSPI protocol you cannot simply force a bps value Instead use this function when CANSPI is in Config mode Refer to datasheet for details Parameters SJW as defined in 18 8 datasheet 1 4 BRP as defined 18 8 datasheet 1 64 PHSEG1 as defined in 18XXXS8 datasheet 1 8 PHSEG2 as defined in 18 8 datasheet 1 8 PROPSEG as defined in 18 8 datasheet 1 8 CAN CONFIG FLAGS is formed from predefined constants see CAN constants Requires CANSPI must be in Config mode otherwise the function will be ignored Example init CAN CONFIG SAMPLE THRICE CAN CONFIG PHSEG2 PRG ON CAN CONFIG STD MSG CAN CONFIG DBL BUFFER ON CAN CONFIG V
201. mikroElektronika Development tools Books Compilers www mikroelektronika co yu DC COMPILER FOR MICROCHIP PIG MICROCONTROLLERS mikroC Making it simple Develop your applications quickly and easily with the world s most intuitive C compiler for PIC Microcontrollers families PIC12 PIC16 and PIC18 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 makes a fast and reliable tool which can satisfy needs of experi enced engineers and beginners alike 927 E A ro oo e mikroC MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making e simple Reader s note DISCLAIMER mikroC 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 copy righted 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 compiler is not fault tolerant and is not designed manufactured or intende
202. n menu choice Tools gt Terminal unsigned short data unsigned short er 0 Dr void main er amp ro Init 8 bit 2400 baud rate no parity bit Soft Uart Init amp PORTB non inverted logic 1 2 2400 0 do do data Soft Uart Read er Receive data while er Soft Uart Write data Send data via UART while 1 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS page Books COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Sound Library mikroC provides a Sound Library which allows you to use sound signalization in your applications You need a simple piezo speaker or other hardware on desig nated port Library Routines Sound_Init Sound_Play Sound Init Prototype void Sound Init char port char pin Description Prepares hardware for output at specified port and pin Parameter pin needs to be within range 0 7 Example Sound Init PORTB 2 Initialize sound RB2 Sound Play Prototype void Sound Play char period div 10 unsigned num of periods Description Plays the sound at the specified port and pin see Sound Init Parameter period div 10 is a sound period given in MCU cycles divided by ten and generated sound lasts for a specified number of periods num of periods Requires To hear the sound you need a piezo speaker or other hardware on designated port Also you must call Sound Init
203. n argument list void func int n float f char ch The comma is also used as an operator in comma expressions Mixing the 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 call func with two args func i j also calls func with two args func expl exp2 exp3 4 exp5 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Zho MIKROD D COMPILER FOR MICROCHIP PIC MICROCONTROLLERS _________________________ 42 aime Semicolon The 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 mikroC might ignore it a b evaluate a b but discard value side effect on a but discard value of empty expression or a null statement Semicolons are sometimes used to create an empty statement for i 0 i lt n i For more information see Statements Colon Use the colon to indicate a labeled statement For example start x 0 goto start Labels are discussed in Labeled Statements Asterisk Pointer Declaration The asterisk in a declaration denotes the creation of a pointer to a type char char ptr a pointer to char is decla
204. n extended 4 unsigned short converts to unsigned int with the same value zero filled 5 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 they are float equivalent with double and long double in mikroC 1 If either operand is float the other operand is converted to float 2 Otherwise if either operand is unsigned long the other operand is converted to unsigned long 3 Otherwise if either operand is Long the other operand is converted to long 4 Otherwise if either operand is unsigned the other operand is converted to unsigned 5 Otherwise both operands are int MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Qu MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple The result of the expression is the same type as that of the two operands Here are several examples of implicit conversion 2 3 1 2 3 1 5 1 5 4 3 5 4 3 1 3 1 3 3 0 3 5 4 J 3 5 4 3 5 4 15 4 15 4 3 75 Pointer Conversions Pointer types can be converted to other pointer types using the typecasting mecha nism char str int ip str char ip More generally the cast type will convert a pointer to type pointer to type Explicit Types Conversions Typecasting In most situations compiler will provide an automatic implicit conversion of types w
205. n memory We also dis tinguish between compile time and run time objects Variables for instance unlike typedefs and types have real memory allocated during run time There are two kinds of duration static and local Static Duration Memory is allocated to objects with static duration as soon as execution is under way this storage allocation lasts until the program terminates Static duration objects usually reside in fixed data segments allocated according to the memory model 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 mikroC static duration objects are not initialized to zero or null in the absence of any explicit initializer An object can have static duration and local scope see the example on the fol lowing page Local Duration Local duration objects are also known as automatic objects They are created on the stack or in a register when the enclosing block or 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 vari ables but is usually redundant because auto is the default for variables declared within a block An object with l
206. nctions 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 This name can be a simple identifier or it can be a complex expression that uniquely references the object Objects and Declarations Declarations establish the necessary mapping between identifiers and objects Each declaration associates an identifier with a data type Associating identifiers with objects requires each identifier to have at least two attributes storage class and type sometimes referred to as data type The mikroC compiler deduces these attributes from implicit or explicit declarations in the source code Commonly only the type is explicitly specified and the storage class specifier assumes automatic value auto Generally speaking an identifier cannot be legally used in a program before its declaration point in the source code Legal exceptions to this rule known as for ward references are labels calls to undeclared functions and struct or union tags The range of objects that can be declared includes variables functions types arrays of other types structure union and enumeration tags structure members union members enumeration constants statement labels preprocessor macros The recursive nature of the declarator syntax allows complex declarators You ll probably want to use typedefs to improve legibility if constru
207. ng the following two selection oper ators period gt right arrow The operator is called the direct member selector and it is used to directly access one of the structure s members Suppose that the object s is of struct type S Then if mis a member identifier of type M declared in s the expression s m direct access to member m is of type M and represents the member object m in s The operator gt is called the indirect or pointer member selector Suppose that ps is a pointer to s Then if m is a member identifier of type M declared in s the expression ps m indirect access to member m identical to ps m is of type M and represents the member object m in s The expression ps gt is a convenient shorthand for ps m For example struct mystruct int i char str 10 double d s sptr amp s S l 3 assign to the i member of mystruct s sptr gt 4 1 23 assign to the d member of mystruct s The expression s m is an lvalue provided that is an lvalue and m is not an array type The expression sptr gt is an lvalue unless m is an array type MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Accessing Nested Structures If structure B contains a field whose type is structure A the members of A can be accessed by two applications of the member selectors struct A int j double x struct B int i struct A a double d
208. nstruction following the call Step Out Ctrl F8 o Execute the current C single or multi cycle instruction then halt If the instruc Step Out tion is within a routine execute the instruction and halt at the first instruction fol lowing the call eI Run to cursor F4 Executes all instructions between the current instruction and the cursor position Run to Cursor MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Toggle Breakpoint F5 Toggle breakpoint at current cursor position To view all the breakpoints select Run gt View Breakpoints from the drop down menu Double clicking an item in Toggle Breakpoint window list locates the breakpoint Watch Window Variables The Watch Window allows you to monitor program items while running your pro gram It displays variables and special function registers of PIC MCU their addresses and values Values are updated as you go through the simulation Watch Window DER Eh oe er Variables Stopwatch Call Stack Address Value 1 a Master 0000 0002 input 0000 0000 SPllib S spi read 0000 0000 data 0000 0000 temp 0000 0000 _getADC 0000 C506 measurement 0000 0000 lastValue 0000 0001 channel 0000 0000 tmp 33 py 0000 0000 0000 0000 Column 0000 0000 Row 0000 0000 text 0000 0000 0000 0000 Istr1_ 00100000 Istri 01000001 131 10 ms 262204 cycl
209. nters are sometimes called generic Sl MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS DERIVED TYPES The derived types are also known as structured types These types are used as ele ments in creating more complex user defined types Arrays Array is the simplest and most commonly used structured type 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 named as array name composed of elements of type The type can be scalar type except void user defined type pointer enumera tion or another array Result of the constant expression within the brackets determines the 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 the number of elements in the array Each of the elements of an array is numbered from 0 through the number of ele ments minus one If the number is n elements of array can be approached as variables array name 0 array 1 of type Here
210. ocal duration also has local scope because it does not exist out side of its enclosing block The converse is not true a local scope object can have static duration MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 5 7f mikro MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making simple Here is an example of two objects with local scope but with different duration void 0 local duration var init a upon every call to f int a 1 static duration var init b only upon 1st call to f Static int b 1 checkpoint att bet void main At checkpoint we will have 0 a 1 b 1 after first call 0 1 b 2 after second call t0 1 b 3 after third call etc DS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 9 MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS C is strictly typed language which means that every object function and expres sion need to have a strictly defined type known in the time of compilation Note that C works exclusively with numeric types The type serves to determine the correct memory allocation required initially to interpret the bit patterns found in the object during subsequent accesses in many type checking situations to ensure that illegal assignments are trapped mikroC supports many standard predefin
211. ode Explorer on off View breakpoints Find Find Next Select All Copy Find Print Replace Save unit Save As Paste Cut Redo Undo Code Assistant Parameters Assistant Find declaration Goto line Insert Code Template Goto bookmark Set bookmark Indent selection Unindent selection Select columns MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making deut t RR iz eee ee Debugger Shortcuts F4 Run to Cursor F5 Toggle breakpoint F6 Run Pause Debugger F7 Step into F8 Step over F9 Debug CTRL F2 Reset S page MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 9 MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple 2200 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS CHAPTER Building Applications Creating applications in mikroC is easy and intuitive Project Wizard allows you to set up your project in just few clicks name your application select chip set flags and get going mikroC allows you to distribute your projects in as many files as you find appro priate You can then share your mikroCompiled Libraries mc1 files with other developers without disclosing the source code The best part is that you can use mc1 bundles created by mikroPascal or mikroBasic MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simp
212. oint the loop continuation condition is re evaluat ed This means that continue demands the next iteration if loop continuation con dition is true Goto Statement Use the goto statement to unconditionally jump to a local label for more infor mation on labels refer to Labeled Statements Syntax of goto statement is goto label identifier This will transfer control to the location of a local label specified by label identifier The label identifier has to be a name of the label within the same function in which the goto statement is The goto line can come before or after the label d 22 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 22 MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS You can use goto to break out from any level of nested control structures But goto cannot be used to jump into block while skipping that block s initializations for example jumping into loop s body etc Use of goto statement is generally discouraged as practically every algorithm can be realized without it resulting in legible structured programs One possible appli cation of goto statement is breaking out from deeply nested control structures for for if disaster goto Error Error error handling code Return Statement Use the return statement to exit from the current function back to the calling routine opti
213. on PIC receives only packets addressed to it address 160 in our example and general messsages with target address 50 The received data is forwarded to PORTB and sent back to Master unsigned short dat 8 buffer for receiving sending messages char i 0 j 0 void interrupt Every byte is received by RS485Slave Read dat If message is received without errors data 4 is set to 255 if RCSTA OERR PORTD 0x81 548551 Read dat void main TRISB 0 TRISD 0 Usart_Init 9600 Initialize usart module RS485Slave Init 160 Initialize MCU as Slave with address 160 PIE1 RCIE sed Enable interrupt INTCON PEIE 1 A on byte received PIE2 TXIE 2 via USART RS485 INTCON GIE EX PORTB 0 PORTD 0 dat 4 0 Ensure that msg received flag is 0 dat 5 0 Ensure that error flag is 0 do if dat 5 PORTD OxAA If there is error set PORTD to SAA if dat 4 If message received dat 4 0 Clear message received flag j dat 3 Number of data bytes received for i 1 lt J i PORTB dat i ZZ Output received data bytes dat 0 Sf Increment received dat 0 RS485Slave Write dat 1 Send it back to Master while 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS Dal MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Hardware Connection Connecting PC and PIC via
214. onally returning a value Syntax is return expression This will evaluate the expression and return the result Returned value will be automatically converted to the expected function type if needed The expres sion is optional if omitted function will return a random value from memory Note Statement return in functions of void type cannot have an expression in fact you can omit the return statement altogether if it is the last statement in the function body MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Compound Statements Blocks A compound statement or block is a list possibly empty of statements enclosed in matching braces Syntactically a block be considered to be a single statement but it also plays a role in the scoping of identifiers An identifier declared within a 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 or loop expects one statement in its body so we can pass it a com pound statement for i 0 lt n i int temp alil ali b il b i temp Note that unlike other statements compound statements do not end with semi colon i e there is never a semicolon following the closing brace d Deal MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR M
215. onverters D A convert ers MAX7219 LTC1290 etc You need PIC MCU with hardware integrated SPI for example PIC16F877 Note This library supports module on PORTB or PORTC and will not work with modules on other ports Examples for PICmicros with module on other ports can be found in your mikroC installation folder subfolder Examples Library Routines Spi_Init Spi Init Advanced Spi Read Spi Write Spi Init Prototype void Spi Init void Description Configures and initializes SPI with default settings SPI Init Advanced or SPI Init needs to be called before using other functions from SPI Library Default settings are Master mode clock Fosc 4 clock idle state low data transmitted on low to high edge and input data sampled at the middle of interval For custom configuration use Spi Init Advanced Requires You need PIC MCU with hardware integrated SPI Example Spi Init Age ABS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Spi Init Advanced Prototype void Spi Init Advanced char master char data sample char clock idle char transmit edge Description Configures and initializes SPI Spi Init Advanced SPI Init needs to be called before using other functions of SPI Library Parameter mast slav determines the work mode for SPI have the values
216. oop is by means of break statement Here 15 an example of calculating scalar product of two vectors using the or statement for s 0 0 lt n i s ali You can also do it like this valid but ugly for 0 0 i lt n s ali b il i but this 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 we used a null statement for a loop body MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Jump Statements A jump statement when executed transfers control unconditionally There are four such statements in mikroC break continue goto and return Break Statement Sometimes you might need to stop the loop from within its body Use the break statement within loops to pass control to the first statement following the inner most switch for while or do block Break is commonly used in 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 You can use the continue statement within loops while do for to skip the cycle It passes control to the end of the innermost enclosing end brace belonging to a looping construct At that p
217. or n In C single character constants have data type int Multi character constants are referred to as string constants or string literals For more information refer to String Constants Escape Sequences The backslash character V is used to introduce an escape sequence which allows the visual representation of certain nongraphic characters One of the most com mon escape constants is the newline character backslash 15 used with octal or hexadecimal numbers to represent the ASCII symbol or control code corresponding to that value for example for the question mark You can use any string of up to three octal or any number of hexa decimal numbers in an escape sequence provided that the value 18 within legal range for data type char 0 to OxFF for mikroC Larger numbers will generate the compiler error Numeric constant too large For example the octal number 5 777 is larger than the maximum value allowed 4377 and will generate an error The first nonoctal or nonhexadecimal character encountered in an octal or hexadecimal escape sequence marks the end of the sequence Note You must use to represent an ASCII backslash as used in operating sys tem paths Al 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS The following table shows the available escape sequences in mikroC
218. orted by any PIC MCU that has SPI interface on PORTC Also CS pin of MCP2510 or MCP2515 must be connected to RCO Example CANSPISetOperationMode CAN MODE CONFIG OxFF CANSPIGetOperationMode Prototype char CANSPIGetOperationMode void Returns Current opmode Description Function returns current operational mode of CAN module Example if CANSPIGetOperationMode CAN MODE NORMAL Jpage 5 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS CANSPIInitialize Prototype void CANSPIInitialize char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CAN CONFIG FLAGS Description Initializes CANSPI pending transmissions are aborted Sets all mask registers to 0 to allow all messages Filter registers are set according to flag value if CONFIG FLAGS amp CAN 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 else Set half the filters to STD and the rest to XTD MSG Parameters SJW as defined in 18 8 datasheet 1 4 BRP as defined in 18 8 datasheet 1 64 PHSEG1 as defined in 18XXX8 datasheet 1 8 PHSEG2 as defined 18XXX8 datasheet 1 8 PROPSEG as defined in 18 8 datasheet 1 8 CAN CONFIG FLAGS is formed fro
219. ot check if the banks are set appropriately for your variable You need to set the banks manually in assembly code MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 99 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Initialization At the time of declaration you can set the initial value of a declared object 1 e initialize it Part of the declaration which specifies the initialization is called the initializer Initializers for globals and static objects must be constants or constant expressions The initializer for an automatic object can be any legal expression that evaluates to an assignment compatible value for the type of the variable involved Scalar types are initialized with a single expression which can optionally be enclosed in braces The initial value of the object is that of the expression the same constraints for type and conversions apply as for simple assignments For example int i 1 char s hello struct complex c 0 1 0 2 where complex is a structure float float For structures or unions with automatic storage duration the initializer must be one of the following an initializer list a single expression with compatible union or structure type In this case the initial value of the object is that of the expression For more information refer to Structures and Unions Also you can initialize arrays of character type with a literal string o
220. otherwise returns zero page 0 202 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS mikrot EU eredi Mano M MM M islower Prototype char islower char character Description Function returns 1 if the character is a lowercase letter a z otherwise returns zero isprint Prototype char isprint char character Description Function returns 1 if the character is printable decimal 32 126 otherwise returns Zero ispunct Prototype char ispunct char character Description Function returns 1 if the character is punctuation decimal 32 47 58 63 91 96 123 126 otherwise returns zero isspace Prototype char isspace char character Description Function returns 1 if the character is white space space CR HT VT NL FF other wise returns zero MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 206 2 MIKROU UD COMPILER EOR MIEROENIR PIC MIEROCONTROAT ERN making 52 simple 8 isupper Prototype char isupper char character Description Function returns 1 if the character is an uppercase letter A Z otherwise returns 0 isxdigit Prototype char isxdigit char character Description Function returns 1 if the character is a hex digit 0 9 A F a f otherwise returns Zero toupper Prototype char toupper int character Description If the
221. parameter x that is the value whose sine is x Input parameter x must be between 1 and 1 inclusive The return value is in radians between pi 2 and 1 2 inclusive atan Prototype double atan double x Description Function computes the arc tangent of parameter x that 1s the value whose tangent is x The return value is in radians between pi 2 and pi 2 inclusive atan2 Prototype double atan2 double x Description This is the two argument arc tangent function It is similar to computing the arc tangent of y x except that the signs of both arguments are used to determine the quadrant of the result and x is permitted to be zero The return value is in radians between pi and pi inclusive ceil Prototype double ceil double num Description Function returns value of parameter num rounded up to the next whole number page 0 0 0 0 AiG MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making m simple TEE S GO TOE Mino ce CEMPICER FOR MICROCHIP ee cos Prototype double cos double x Description Function returns the cosine of x in radians The return value is from 1 to 1 cosh Prototype double cosh double x Description Function returns hyperbolic cosine of x defined mathematically as e e X 2 If the value of x 15 too large 1f overflow occurs the function fails
222. ppended a random timestamp Requires CF must be initialized for file write operation See C File Write Init Example April 1st 2005 18 07 00 Cf Set File Date 2005 4 1 18 7 0 Cf File Write Complete Prototype void Cf File Write Complete char filename 8 char extension Description Finalizes writing to file Upon all data has be written to file use this function to close the file and make it readable Parameter ilename must be 8 chars long in uppercase Requires CF must be initialized for file write operation See C File Write Init Example Cf File Write Complete MY FILE1 txt Age MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making a dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example The following example writes 512 bytes at sector no 590 and then reads the data and prints on PORTC for a visual check unsigned i void main TRISC 0 PORTC is output Cf Init PORTB PORTD Initialize ports do nop while Cf Detect Wait until CF card is inserted Delay ms 500 Cf Write Init 590 1 Initialize write at sector address 590 Write 512 bytes to sector 590 for i 0 i lt 512 i Cf Write Byte i 11 PORTC OxFF Delay 1000 Cf Read 590 1 Initialize read at sector address 590 Read 512 bytes from sector 590 for i 0 i lt 512 i
223. ption Function returns the base 10 logarithm of x i e 1094 x modf Prototype double modf double num double whole Description Function returns the signed fractional component of num placing its whole number component into the variable pointed to by whole pow Prototype double pow double x double y Description Function returns the value of x raised to the power of y i e xv If the x is negative function will automatically cast the y into unsigned long sin Prototype double sin double x Description Function returns the sine of x in radians The return value is from 1 to 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 29 MIKROG C COMPILER MICROCHIP PIG MICROCONTROLLERS 111111126600 60 dimple sinh Prototype double sinh double x Description Function returns the hyperbolic sine of x defined mathematically as e e 2 If the value of x is too large if overflow occurs the function fails sqrt Prototype double sqrt double num Description Function returns the non negative square root of num tan Prototype double tan double x Description Function returns the tangent of x in radians The return value spans the allowed range of floating point in mikroC tan Prototype double tanh double x Description Function returns the hyperbolic tangent of x defined mathematically a
224. ptionally enclosed in braces Each character in the string including the null terminator ini tializes successive elements in the array For more information refer to Arrays Automatic Initialization mikroC does not provide automatic initialization for objects Uninitialized globals and objects with static duration will take random values from memory Ql MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making amp imple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS 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 a function can be used in expressions technically function call is considered an operator like any other C allows a function to create results other than its return value referred to as side effects Often 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
225. r UL its data type will be unsigned long int Decimal Constants 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 In the absence of any overriding suffixes the data type of a decimal constant is derived from its value as shown below lt 2147483648 Error Out of range 2147483648 32769 long 32768 129 int 128 127 short 128 255 unsigned short 256 32767 32768 65535 unsigned int 65536 2147483647 long 2147483648 4294967295 unsigned long gt 4294967295 Error Out of range Hexadecimal Constants constants starting with 0x or 0X are taken to be hexadecimal In the absence of any overriding suffixes the data type of an hexadecimal constant is derived from its value according to the rules presented above For example 0xC367 will be treated as unsigned int 450 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 14 MIKROD COMPILER FOR MICROCHIP MICROCONTROLLERS Binary Constants constants starting with 0b or 0B are taken to be binary In the absence of any overriding suffixes the data type of an binary constant is derived from its value according to the rules presented above For
226. rary for accessing data on SD Card via SPI communication Note Secure Digital Library works only with PIC18 family Library Routines Sd_Init Sd Read Sector Sd Write Sector Sd Read Cid Sd Read Csd Sd Init Prototype unsigned short Sd Init unsigned short port unsigned short pin Returns Returns 0 1f SD card is present and successfully initialized otherwise returns 1 Description Initializes hardware SPI communication parameters port and pin designate the CS line used in the communication parameter pin should be 0 7 The function returns 0 1f SD card is present and successfully initialized otherwise returns 1 54 Init needs to be called before using other functions of this library Example error Sd Init amp PORTC 2 Init with CS line at RC2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS PA MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Sd_Read_Sector Prototype unsigned short Sd Read Sector unsigned long sector char data Returns Returns 0 if read was successful or 1 if an error occurred Description Function reads one sector 512 bytes from SD card at sector address sector Read data 1s stored in the array data Function returns 0 if read was successful or 1 if an error occurred Requires Library needs to be initialized see 54 Init Example error Sd Read Sector sector data Sd Write Sector Prototype
227. rd extern is optional for a function prototype Use the extern modifier to indicate that the actual storage and initial value of a variable or body of a function is defined in a separate source code module Functions declared with extern are visible throughout all source files in a pro gram unless you redefine the function as static See Linkage for more information 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 9 el MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Type Qualifiers Type qualifiers const and volatile are optional in declarations and do not actu ally affect the type of declared object Qualifier const Qualifier const implies that the declared object will not change its value during runtime In declarations with const qualifier you need to initialize all the objects in the declaration Effectively mikroC treats objects declared with const qualifier same as literals or preprocessor constants Compiler will report an error if trying to change an object declared with const qualifier For example const double PI 3 14159 Qualifier volatile Qualifier volatile implies that variable may change its value during runtime indepent from the program Use the volatile modifier to indicate that a variable can be changed by a background routine an interrupt routine or an I O port Declaring an object to be volatile warns the compiler not
228. received see the example at the end of the chapter Upon receiving a message buffer is filled with the following values data 0 2 is the message data 3 is number of message bytes received 1 3 data 4 is set to 255 when message is received data 5 is set to 255 if error has occurred data 6 is the address of the Slave which sent the message Function automatically adjusts data 4 and data 5 upon every received message These flags need to be cleared from the program Requires MCU must be initialized as Slave in 5 485 communication in order to be assigned an address See RS485S1ave Init Example unsigned short msg 8 RS485Slave Read msg RS485Slave Send Prototype void RS485Slave Send char data char datalen Description Sends data from buffer to Master via RS 485 datalen is a number of bytes in mes sage 1 lt datalen lt 3 Requires MCU must be initialized as Slave in 5 485 communication in order to be assigned an address See RS485S1ave Init It is programmer s responsibility to ensure by protocol that only one device sends data via 485 bus at a time Example unsigned short msg 8 RS485Slave Send msg 2 DAB MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making a dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example The example demonstrates working with PIC as Slave nod in RS 485 communicati
229. rection operator to access the pointed object Argument Conversions When a function prototype has not been previously declared mikroC converts integral arguments to a function call according to the integral widening expan sion rules described in Standard Conversions When a function prototype is in scope mikroC converts the given argument to the type of the declared parameter as if by assignment Oe MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS 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 You can always use an explicit cast to convert an argument to a type that is acceptable to a function prototype Note If your function prototype does not match the actual function definition mikroC will detect this if and only if that definition is in the same compilation unit as the prototype If you create a library of routines with a corresponding header file of prototypes consider including that header file when you compile the library so that any discrepancies between the prototypes and the actual definitions will be caught The compiler is also able to force arguments to the proper type Suppose you have the following code int limit 32 char ch A long res extern long func long parl long par2 prototype main res func limit
230. red You can also use the asterisk as an operator to either dereference a pointer or as the multiplication operator i char ptr For more information see Pointers 50 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS el MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Equal Sign The equal sign separates variable declarations from initialization lists int test 5 1 2 3 4 5 int x 5 The equal sign is also used as the assignment operator in expressions int a b c For more information see Assignment Operators Pound Sign Preprocessor Directive The pound sign indicates a preprocessor directive when it occurs as the first nonwhitespace character on a line It signifies a compiler action not necessarily associated with code generation See Preprocessor Directives for more informa tion and are also used as operators to perform token replacement and merging during the preprocessor scanning phase See Preprocessor Operators MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple OBJECTS AND LVALUES Objects An object is a specific region of memory that can hold a fixed or variable value or set of values To prevent confusion this use of the word object is different from the more general term used in object oriented languages Our definiton of the word would encompass fu
231. red Too many chars Undefined struct Nonexistent field Aggregate init error Incompatible types Identifier redefined Function definition not found Signature does not match Cannot generate code for expression Too many initializers of subaggregate Nonexistent subaggregate Stack Overflow func call in complex expression Syntax Error expected s but s found Array element cannot be function Function cannot return array MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 2 MIKROG C COMPILER FOR MIGROCHIP PIC MICROCONTROLLERS making 42 simple Inconsistent storage class Inconsistent type tag redefined Illegal typecast s is not a valid identifier Invalid statement Constant expression required Internal error s Too many arguments Not enough parameters Invalid expresion Identifier expected but s found Operator s not applicable to this operands s Assigning to non lvalue s Cannot cast s to s Cannot assign s to s lvalue required Pointer required Argument is out of range Undeclared identifier s in expression Too many initializers Cannot establish this baud rate at s MHz clock Compiler Warning Messages Highly inefficent code func call in complex expression Inefficent code func call in complex expression MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS CHAPTER
232. restricted by using the static storage class specifier in function declaration see Storage Classes and Linkage Note Check the PIC Specifics for more info on functions limitations on PIC micros Function Declaration Functions are declared in your source files or made available by linking precom piled libraries Declaration syntax of a function is type function name parameter declarator list The function name must be a valid identifier This name is used to call the function see Function Calls for more information The type represents the type of function result and can be any standard or user defined type For functions that do not return value you should use void type The type can be omitted in global function declarations and function will assume int type by default Function type can also be a pointer For example 1oat means that the func tion result is a pointer to float Generic pointer void is also allowed Function cannot return array or another function MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 9 mikroC MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple 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 function calls for validity If the list is empty function does not take any arguments Also if the list
233. roC does not support anonymous structures ANSI divergence Structure Declaration and Initialization Structures are declared using the keyword struct struct tag member declarator list Here tag is the name of the structure member declarator list is list of structure members actually a list of variable declarations Variables of structured type are declared 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 s illegal struct mystruct mystruct ps OK Also a structure can contain previously defined structure types when declaring an instance of a declared structure Here is an example Structure defining a dot struct Dot float x y Structure defining a circle struct Circle double r struct Dot center o1 o2 declare variables 1 and o2 of circle type 7 4 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS Note that you can omit structure tag but then you cannot declare additional objects of this type elsewhere For more information see the Untagged Structures below Structure is initialized by assigning it a comma delimited sequence of values with in braces similar to array Referring to
234. rs rw rst and en can be pins of any available port This function needs to be called befored using other routines of GLCD library Example Glcd Init PORTB PORTC 3 5 7 1 2 Glcd Disable Prototype void Glcd Disable void Description Routine disables the device and frees the data line for other devices To enable the device again call any of the library routines no special command is required Requires GLCD needs to be initialized See 1 Init Example Glcd Disable Glcd Set Side Prototype void Glcd Set Side unsigned short x Description Selects side of GLCD left or right Parameter x specifies the side values from 0 to 63 specify the left side and values higher than 64 specify the right side Use the functions Glcd Set Side Set and Glcd Set Page to specify an exact position on GLCD Then you can use 1 Write Data orGlcd Read Data on that location Requires GLCD needs to be initialized See Glcd_Init Example Glcd Select Side 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Glcd Set Page Prototype void Glcd Set Page unsigned short page Description Selects page of GLCD technically a line on display parameter page can be 0 7 Requires GLCD needs to be initialized See Glcd_Init Example Glcd Set Page 5 Glcd Set X Prototype voi
235. rsor position Both string variables and literals can be passed as text Requires Ports with LCD must be initialized See Config orLcd8 Init Example Out Cp Here Print Here at current cursor position page 00 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS d bii MM ET NOU INO Mino ce CEMPICER FOR MICROCHIP PIE Mur Lcd8 Chr Prototype void Lcd8 Chr char row char col char character Description Prints character on LCD at specified row and column parameters row and co1 Both variables and literals can be passed as character Requires Ports with LCD must be initialized See Lcd8_Config or Lcd8 Init Example Out 2 3 i Print i at line 2 char 3 Lcd8 Chr Cp Prototype void Lcd8 Chr Cp char character Description Prints character on LCD at current cursor position Both variables and literals can be passed as character Requires Ports with LCD must be initialized See Config or Lcd8 Init Example Out Cp e Print at current cursor position Lcd8 Cmd Prototype void Lcd8 Cmd char command Description Sends command to LCD You can pass one of the predefined constants to the function The complete list of available commands is on the page 186 Requires Ports with LCD must be initialized See Lcd8 Config or Lcd8 Init Example Leds
236. s braces comma semicolon colon asterisk equal sign and pound sign Most of these punctuators also function as operators Brackets Brackets indicate single and multidimensional array subscripts char ch str mikro int mat 3 4 3 x 4 matrix eh str 3 4th element Parentheses Parentheses are used to group expressions isolate conditional expressions and indicate function calls and function parameters a b override normal precedence if d 2 essential with conditional statement func function call no args void func2 int n function declaration with parameters Parentheses are recommended in macro definitions to avoid potential precedence problems during expansion define x x x For more information refer to Expressions and Operators Precedence 219 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Braces indicate the start and end of a compound statement if d z TX func The closing brace serves as a terminator for the compound statement so a semi colon is not required after the except in structure declarations Often the semi colon is illegal as in if statement ew d illegal semicolon else i For more information refer to Compound Statements Comma The comma separates the elements of a functio
237. s CAN_MASK is one of predefined constant values see CAN constants value is the mask register value CONFIG FLAGS selects type of message to filter either CONFIG XTD MSG or CAN CONFIG STD MSG Requires CAN must be in Config mode otherwise the function will be ignored Example Set all mask bits to 1 i e all filtered bits are relevant CANSetMask CAN MASK B1 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 Function sets mask for advanced filtering of messages Given value is bit adjusted to appropriate buffer mask registers Parameters MASK is one of predefined constant values see CAN constants value is the filter register value CONFIG FLAGS selects type of message to filter either CAN CONFIG XTD MSG or CAN CONFIG STD MSG Requires CAN must be in Config mode otherwise the function will be ignored Example Set id of filter 1 F1 to 3 CANSetFilter CAN FILTER B1 F1 3 CAN CONFIG XTD MSG MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 7 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS 000000000 tN 62 adele CANRead Prototype char CANRead long id char data char datalen char CAN RX MSG FLAGS Returns M
238. s building bricks in your projects 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making amp imple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS CODE EDITOR The Code Editor is an advanced text editor fashioned to satisfy the needs of pro fessionals General code editing is same as working with any standard text editor including familiar Copy Paste and Undo actions common for Windows environ ment Advanced Editor features include Adjustable Syntax Highlighting Code Assistant Parameter Assistant Code Templates Auto Complete Auto Correct for common typos Bookmarks and Goto Line You can customize these options from the Editor Settings dialog To access the settings choose Tools gt Options from the drop down menu or click the Tools icon ay Editor Settings Editor Colors Colors Tools Icon Auto Correct Scheme Zedar Auto Complete Tools Compiler Assembler Dutput Background Directive Identifier number Key Label Number String Symbol TFormi ButtoniClick TOb New scheme Delete number CS een Text Attributes Bold Underline Italic Strikeout Cancel MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Code Assistant CTRL SPACE If you type a first few letter of a word
239. s sinh x cosh x page 290 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS ANSI C Stdlib Library mikroC provides a set of standard ANSI C library functions of general utility Note Not all of the standard functions have been included Functions have been implemented according to the ANSI C standard but certain functions have been modified in order to facilitate PIC programming Library Routines abs atof atoi atol div ldiv labs max min rand srand xtoi abs Prototype int abs int num Description Function returns the absolute i e positive value of num atof Prototype double atof char s Description Function converts the input string s into a double precision value and returns the value Input string s should conform to the floating point literal format with an optional white space at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize this includes a null character MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 22074 C CDMPIEER FOR MICROCHIP PIC MICROCONTROLLERS making amp simple 2 atoi Prototype int atoi char s Description Function converts the input string s into an integer value and returns the value Input string s should consist
240. s a delay based on MCU clock Delay lasts for 10 times the input parameter in MCU cycles Input parameter needs to be in range 3 255 Note that Delay is library function rather than a built in routine it is presented in this topic for the sake of convenience Example Delay Cyc 10 Hundred MCU cycles pause Clock Khz Prototype unsigned Clock Khz void Returns Device clock in KHz rounded to the nearest integer Description Returns device clock in KHz rounded to the nearest integer Example Clock Khz MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple LIBRARY ROUTINES mikroC provides a set of libraries which simplifies the initialization and use of PIC MCU and its modules Library functions do not require any header files to be included you can use them anywhere in your projects Currently available libraries are ADC Library CAN Library CANSPI Library Compact Flash Library Conversions Library EEPROM Library Ethernet Library Flash Memory Library Graphic LCD Library I2C Library Keypad Library LCD Library LCD8 Library Manchester Code Library Multi Media Card Library OneWire Library PS 2 Library PWM Library RS 485 Library Secure Digital Library Software I2C Library Software SPI Library Software
241. s 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 Operator sizeof cannot be applied to a function 22 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS EXPRESSIONS An expression is a sequence of operators operands and punctuators that specifies a computation Formally expressions are defined recursively subexpressions can be nested without formal limit However the compiler will report an out of mem ory 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 iden tifier and expression defined recursively Expressions are evaluated according to certain conversion grouping associativity and precedence rules that depend on the operators used the presence of parenthe ses and the data types of the operands The precedence and associativity of the operators are summarized in Operator Precedence and Associativity The way operands and subexpressions are grouped does not necessarily specify the actual order in which they are evaluated by mikroC Expressions can produce an lvalue an 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
242. sary if one of the pointers is generic of void type Assigning the integer constant 0 to a pointer assigns a null pointer value to it The mnemonic NULL defined in the standard library header files such as stdio h can be used for legibility Two pointers pointing into the same array may be compared by using relational operators lt lt gt and gt Results of these operations are same as if they were used on subscript values of array elements in question int pa amp a 4 pb amp a 2 if pa gt pb this will be executed as 4 is greater than 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 mikroC MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making e simple You can also compare pointers to zero value this tests if pointer actually points to anything All pointers can be successfully tested for equality or inequality to NULL if pa NULL if pb NULL Note Comparing pointers pointing to different objects arrays can be performed at programmer s responsibility precise overview of data s physical storage is required Pointer Addition You can use operators and to add an integral value to a pointer The result of addition is defined only if pointer points to an element of an array and if the result is a pointer pointing into the same array or one element beyond it If a pointer is declared to point to type a
243. ser 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 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 MIKROG COMPILER FOR MICROCHIP PIG MICROCONTROLLERS KEYBOARD SHORTCUTS Below is the complete list of keyboard shortcuts available in mikroC IDE You can also view keyboard shortcuts in Code Explorer window tab Keyboard IDE Shortcuts Fl CTRL N CTRL O CTRL F9 CTRL F11 CTRL SHIFT F5 Basic Editor shortcuts F3 CTRL A CTRL C CTRL F CTRL P CTRL R CTRL S CTRL SHIFT S CTRL V CTRL X CTRL Y CTRL Z Advanced Editor shortcuts CTRL SPACE CTRL SHIFT SPACE CTRL D CTRL G CTRL J CTRL lt number gt CTRL SHIFT lt number gt CTRL SHIFT I CTRL SHIFT U CTRL ALT SELECT Help New Unit Open Compile C
244. settings char text mikroElektronika void main TRISD 0 PORTD is output Lcd Config amp PORTD 1 2 0 3 5 4 6 Initialize LCD on PORTD Lcd Cmd Lcd CURSOR OFF Turn off cursor Lcd Out 1 1 text Print Text at LCD Hardware Connection PIC MCU PORTD PINO 1 PIN2 PIN3 PINS PING o lt LCD PIN7 PING D4 PINS D6 PIN4 D5 gt gt D7 46 E RS PINO ED LCD contrast AO MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS LCD8 Library 8 bit interface mikroC provides a library for communicating with commonly used 8 bit interface LCD with Hitachi HD44780 controller Figures showing HW connection of PIC and LCD are given at the end of the chapter Note Be sure to designate Control and Data ports with LCD as output before using any of the following functions Library Routines Lcd8 Config Lcd8 Init Lcd8 Out Lcd8 Out Cp Chr Chr Cp Lcd8 Lcd8 Config Prototype void Lcd8 Config char ctrlport char dataport char RS char EN char WR char D7 char D6 char D5 char D4 char D3 char D2 char D1 char D0
245. st the expression condition is evaluated The switch statement then compares it to all the available constant expressions following the keyword case If the match is found switch passes control to that matching case at which point the statement following the match evaluates Note that constant expressions must evaluate to integer There cannot be two same constant expressions evaluating to same value Parantheses around expression are mandatory mikro MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making simple Upon finding a match program flow continues normally following instructions will be executed in natural order regardless of the possible case label If no case satisfies the condition the default case evaluates if the label default is speci fied For example if variable i has value between 1 and 3 following switch would always return it as 4 switch i case 1 1 case 2 i case 3 i To avoid evaluating any other cases and relinquish control from the switch ter minate each case with break Conditional switch statements can be nested labels case and default are then assigned to the innermost enclosing switch statement Here is a simple example with switch Let s assume we have a variable 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 state
246. sums all mikroC operators Where duplicates of operators appear in the table the first occurrence is unary the second binary Each category has an associativity rule left to right or right to left In the absence of parentheses these rules resolve the grouping of expressions with operators of equal precedence 1 0 00 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making ero eee eee Precedence Operands Operators Associativity 15 2 gt left to right 14 1 t NN e D 7 right to left 13 2 left to right 12 2 left to right 11 2 gt gt left to right 10 2 gt gt left to right 9 2 l left to right 8 2 amp left to right 7 2 6 left to right 6 2 left to right 5 2 amp amp left to right 4 2 left to right 3 3 left to right 2 2 A ni um right to left 1 2 left to right MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 004 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Arithmetic Operators Arithmetic operators are used to perform mathematical computations They have numerical operands and return numerical results Type char technically represents small integers so char variables can used as operands in arithmetic operations All of arithmetic operators associate from left to right
247. t Find Gni Write RS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS DEBUGGER The source level Debugger is an integral component of mikroC development envi ronment It is designed to simulate operations of Microchip Technology s PICmicros and to assist users in debugging software written for these devices Start Debugger The Debugger simulates program flow and execution of instruction lines but does not fully emulate PIC device behavior it does not update timers interrupt flags etc After you have successfully compiled your project you can run the Debugger by selecting Run gt Debug from the drop down menu or by clicking the Debug Icon Starting the Debugger makes more options available Step Into Step Over Run to Cursor etc Line that 1s to be executed is color highlighted Debug F9 Eii Start the Debugger Pause Debugger Run Pause Debugger F6 Run or pause the Debugger Step Into F7 Execute the current C single or multi cycle instruction then halt If the instruc Step Into tion is a routine call enter the routine and halt at the first instruction following the call e Step Over F8 BLU Execute the current C single or multi cycle instruction then halt If the instruc Step Over tion is a routine call skip it and halt at the first i
248. t Example Pwm Change Duty 192 Set duty ratio to 75 Pwm Start Prototype void Pwm Start void Description Starts PWM Requires You need a CCP module on PORTC to use this library To use this function module needs to be initalized see Pwm_Init Example Pwm Start Pwm Stop Prototype void Pwm Stop void Description Stops PWM Requires You need a CCP module on PORTC to use this library To use this function module needs to be initalized see Init Example Pwm Stop MIKROELEKTRONIKA DEVELOPMENT TOOLS Books COMPILERS MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple Library Example The example changes PWM duty ratio on pin RC2 continually If LED is connected to RC2 you can observe the gradual change of emitted light char i 0 j 0 void main PORTC OxFF PORTC is output Pwm Init 5000 Initialize PWM module at 5KHz Pwm Start Start PWM while 1 Slow down allow us to see the change on LED for i 0 i lt 20 i Delay us 500 j Pwm Change Duty j Change duty ratio Hardware Connection PIC16F877A 5V MCLR Vpp THV RB7 PGD RAO ANO RB6 PGC RA1 AN1 RB5 RA2 AN2 Vref RB4 RA3 AN3 Vref RB3 PGM RAA TOCKI RB2 RAS AN4 RB1 zlo REO RD AN5 RBO INT 9 RE1 WR ANG 19 RE2 CS AN7 Vdd RD7 PSP7 Vss RD6 PSP6 OSC1 RD5 PSP5 osc2 RD4 PSP4 RCO
249. t This library currently supports working with only one UDP port socket at a time Example if udp dest port Eth Get Udp Port Respond to action Eth Set Udp Port Prototype void Eth Set Udp Port unsigned udp port Description Sets up the default UDP port which will handle user requests The user can decide upon receiving the UDP packet which port was this packet sent to and whether it will be handled or rejected Requires As specified for the entire library Example Eth Set Udp Port 10001 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 83 11 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Eth_Send_Udp Prototype void Eth Send Udp char msg Description Sends the prepared UDP message msg of up to 16 bytes characters Unlike ICMP and TCP the UDP packets are generally not generated as a response to the client request UDP provides no guarantees for message delivery and sender retains no state on UDP messages once sent onto the network This is why UDP packets are simply sent instead of being a response to someone s request Requires As specified for the entire library Also the message to be sent must be formatted as a null terminated string The message length including the trailing 0 must not exceed 16 characters Example Eth Send Udp udp tx message Eth Load Tcp Header
250. t s have a simple example union myunion union tag is myunion int i double d char ch mu pm amp mu The identifier mu of type union myunion can be used to hold a 2 byte int a 4 byte double or a single byte char but only one of these at any given time 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 an int object and 3 bytes are unused when mu holds a char Union Member Access Union members can be accessed with the structure member selectors and gt but care is needed Check the example on the following page MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 9 MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple Referring to declarations from the previous example mu d 4 016 Lcd Out Cp FloatToStr mu d OK displays mu d 4 016 Lcd Out Cp IntToStr mu i peculiar result pm i 3 Lcd Out Cp IntToStr mu i OK displays mu i 3 The second Lcd Out Cp 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 does not provide a 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 o
251. t CR 0x22 Eth Outport BNDRY next ptr while 1 776 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot making 42 simple MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Eth Get Hdr Len Prototype unsigned short Eth Get Ip Hdr Len void Returns Header length of the received IP packet Description Returns header length of the received IP packet Before other data based upon the IP protocol TCP UDP ICMP can be analyzed the sub protocol data must be properly loaded from the received IP packet Requires The card NIC must be properly initialized See Eth Init The function must be called in a proper sequence i e immediately after determining that the packet received is the IP packet Example Receive IP Header opt len Eth Get Ip Hdr Len 20 Eth Load lp Packet Prototype void Eth Load Ip Packet void Description Loads various IP packet data into PIC s Ethernet variables Requires The card must be properly initialized See Eth Init Also a proper sequence of calls must be obeyed see the Event function in the supplied Ethernet example Example Eth Load Ip Packet MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 7f 7f MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Eth Get Hdr Chksum Prototype void Eth Get Hdr Chksum void
252. t h MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 3 MIKROD COMPILER FOR MICROCHIP MICROCONTROLLERS Note There is also a third version of include directive rarely used which assumes that neither nor appears as the first non whitespace character follow ing include include macro identifier It assumes a macro definition exists that will expand the macro identifier into a valid delimited header name with either ofthe header name or header name formats Preprocessor Operators The pound sign 15 a preprocessor directive when it occurs as the first non whitespace character on a line Also and perform operator replacement and merging during the preprocessor scanning phase Operator In C preprocessor 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 result of preprocessing you can use the operator in macro body It can be placed in front of a formal macro argument in definition in order to convert the actual argument to a string after replacement For example let s have macro LCD PRINT for printing variable name and value on LCD define LCD PRINT val Out Cp dval Lcd Out Cp IntToStr val note the backslash as a
253. t j MIKROG C COMPILER FOR MICROCHIP MICROCONTROLLERS making 42 simple TOKENS Token is the smallest element of a C program that is meaningful to the compiler The parser separates tokens from the input stream by creating the longest token possible using the input characters in a left to right scan mikroC recognizes following kinds of tokens keywords identifiers constants operators punctuators also known as separators Token Extraction Example Here is an example of token extraction Let s have the following code sequence inter First note that inter would be parsed as a single identifier rather than as the keyword int followed by the identifier er The programmer who wrote the code might have intended to write inter a b but it won t work that way The compiler would parse it as the following seven tokens inter identifier assignment operator a identifier postincrement operator 4 addition operator b identifier semicolon separator Note that parses as the longest token possible followed by 229 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG COMPILER FOR MICROCHIP MICROCONTROLLERS CONSTANTS Constants or literals are tokens representing fixed numeric or character values mikroC supports integer constants floating point constants character constants
254. tablished before using this function See Spi_Init_Advanced or Spi_Init Example short take buffer take Spi_Read buffer Spi_Write Prototype void Spi_Write char data Description Writes byte data to SSPBUF and immediately starts the transmission Requires SPI must be initialized and communication established before using this function See Spi_Init_Advanced or Spi_Init Example Spi_Write 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example The code demonstrates how to use SPI library functions Assumed HW configura tion 1s max7219 chip select pin connected to and SDO SDI SCK pins are connected to corresponding pins of max7219 Function Declarations void max7219_init1 char i void main Spi Init Standard configuration TRISC amp OxFD max7219 init1 Initialize max7219 for i 1 i lt 8u i PORTC amp OXFD Select max7219 Spi Write i Send i to max7219 digit place Spi Write 8 i Send i to max7219 digit PORTC 2 Deselect max7219 TRISB 0 PORTB i MIKROELEKTRONIKA DEVELOPMENT TOOLS Books COMPILERS mikroC making it simple iasanau dsd eqM odsd oqu vou Sou
255. the Microchip AN575 32 bit for mat IEEE 754 compliant 650 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Below is the overview of arithmetic types Type Size Range unsigned char 8 bit 0 255 signed char 8 bit 128 127 signed short int 8 bit 128 127 unsigned short int 8 bit 0 255 signed int 16 bit 32768 32767 unsigned int 16 bit 0 65535 signed long int 32 bit 2147483648 2147483647 unsigned long int 32 bit 0 4294967295 za sa MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 84 MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple 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 list of discreet values enumerators The enumerators listed inside the braces are also known as enumeration constants Each is assigned a fixed integral value In the absence of explicit initializers the first enumerator is set to zero and each suc ceeding enumerator is set to one more than its predecessor Variables o
256. the number of sectors prepared for reading operation Requires Ports must be initialized See C Init Example Cf Read Init 590 1 page 0 1 S4 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS mikroC making amp imple MIKROG COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Cf_Read_Byte Prototype char Cf Read Byte void Returns Returns byte from CF Description Reads one byte from CF Requires must be initialized for read operation See C Read Init Example PORTC Cf Read Byte Read byte and display it on PORTC Cf Read Word Prototype unsigned Cf Read Word void Returns Returns word 16 bit from CF Description Reads one word from CF Requires CF must be initialized for read operation See Read Init Example PORTC Cf Read Word Read word and display it on PORTC Cf Write Init Prototype void Cf Write Init long address char sectcnt Description Initializes CF card for writing Parameter address specifies sector address where data will be stored and is total number of sectors prepared for write operation Requires Ports must be initialized See C Init Example Write Init 590 1 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROG C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Cf_Write_Byte
257. the two Function calls from within interrupts are a special case See Interrupts mikroC treats identifiers declared with const qualifier as true constants C style This allows using const objects in places where ANSI C would expect a constant expression If aiming at portability use the traditional preprocessor defined constants See Type Qualifiers and Constants Tags scope is specific Due to separate name space tags are virtually removed from normal scope rules they have file scope but override any block rules Ellipsis in formal argument lists is unsupported mikroC allows C style single line comments using two adjacent slashes Features under construction pointers to functions and anonymous structures Implementation defined Behavior Certain sections of the ANSI standard have implementation defined behavior This means that the exact behavior of some C code can vary from compiler to compiler Throughout the help are sections describing how the mikroC compiler behaves in such situations The most notable specifics include Floating point Types Storage Classes and Bit Fields 9 2 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS making 42 simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Predefined Globals and Constants To facilitate PIC programming mikroC implements a number of predefined glob als and constants All PIC SFR registers are implicitly declared as global v
258. tion 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 semi colon Other control structures end with statement which means that they implicitly include a semicolon or a closing brace Here is an example of calculating scalar product of two vectors using the do statement s ali i while i lt n For Statement The for statement implements an iterative loop Syntax of for statement is for init exp condition exp increment exp statement Before the first iteration of the loop expression init exp sets the starting vari ables for the loop You cannot pass declarations in init exp Expression condition exp 18 checked before the first entry into the block statement is executed repeatedly until the value of condition exp is false After each iteration of the loop increment exp increments a loop counter Consequently 1 is functionally the same as 41 d 2200 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP MICROCONTROLLERS All the expressions are optional If condition exp is left out it is assumed to be always true Thus empty for statement is commonly used to create an endless loop in C for The only way to break out of this l
259. tion speed depends on the SPI and is certainly slower than the real CAN Note CANSPI functions are supported by any PIC MCU that has SPI interface on PORTC Also CS pin of MCP2510 or MCP2515 must be connected to RCO Example of HW connection is given at the end of the chapter Note Be sure to check CAN constants necessary for using some of the functions See page 145 Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialize CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIRead CANSPIWrite Following routines are for the internal use by compiler only RegsToCANSPIID CANSPIIDToRegs MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS B MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS making ct simple CANSPISetOperationMode Prototype void CANSPISetOperationMode char mode char wait flag Description Sets CAN to requested mode i e copies mode to CANSTAT Parameter mode needs to be one of CAN OP MODE constants see CAN constants page 145 Parameter wait flag needs to be either 0 or OxFF If set to OxFF this is a blocking call the function won t return until the requested mode is set If 0 this is a non blocking call It does not verify 1f CAN module is switched to requested mode or not Caller must use function CANSPIGetOperationMode to verify correct operation mode before performing mode specific operation Requires CANSPI functions are supp
260. tives if elif else and endif work very similar to the common C conditional statements If the expression you write after the if has a nonzero value the line group immediately following the if directive is retained in the translation unit Syntax is dif constant expression 1 section 1 felif constant expression 2 section 2 gt elif constant expression n section n telse final section Each if directive in a source file must be matched by closing tendi f direc tive Any number of elif directives can appear between the if and endif directives but at most one else directive is allowed The 1 directive if present must be the last directive before endif The sections can be any program text that has meaning to the compiler or the pre processor The preprocessor selects a single section by evaluating the constant expression following each if or e1if directive until it finds a true nonzero constant expression The constant expressions are subject to macro expansion If all occurrences of constant expression are false or if no e1if directives appear the preprocessor selects the text block after the e1se clause If the else clause is omitted and all instances of constant expressionin the if block are false no section is selected for further processing MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 4 229 mikroC MIKROG C COMPILER FOR MICROCHIP
261. to LCD editor menu option Tools gt BMP2LCD to convert image to a constant array suitable for display on GLCD Requires GLCD needs to be initialized See Glcd_Init Example Glcd_Image my_image Glcd Partial Image Prototype void Glcd Partial Image unsigned short x1 unsigned short yl unsigned short x2 unsigned short y2 unsigned short color const char image Description Displays partial bitmap image on the GLCD Parameter image should be formatted as an array of 1024 bytes Parameters x1 y1 set the upper left corner and x2 y2 set the lower right corner of the clip Parameter color defines the fill 0 draws a white image clear dots 1 draws a black image put dots and 2 draws an inverted image each dot Use the mikroC s integrated Bitmap to LCD editor menu option Tools gt Graphic LCD Editor to convert image to a constant array suitable for display on GLCD Requires GLCD needs to be initialized See Glcd_Init Example Glcd Partial Image 0 0 32 64 1 my image page IS 23 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making a dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example The following drawing demo tests advanced routines of GLCD library unsigned short j k void main Glcd_Init PORTB 2 0 3 5 7 1 PORTD do Draw circles Glcd Fill 0 Clear scre
262. uates to true statement1 executes If expression is false statement2 executes The expression must evaluate to an integral value otherwise the condition is ill formed Parentheses around the expression are mandatory The else keyword is optional but no statements can come between the if and the else 6 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Nested if statements Nested if statements require additional attention General rule is that the nested conditionals are parsed starting from the innermost conditional with each else bound to the nearest available if on its left if expressionl statementl else if expression2 if expression3 statement2 else statement3 this belongs to if expression3 else statement4 this belongs to if expression2 Note The if and 1 preprocessor statements directives look similar to the if and else statements but have very different effects They control which source file lines are compiled and which are ignored See Preprocessor for more information Switch Statement Use the switch statement to pass control to a specific program branch based on a certain condition Syntax of switch statement is switch expression case constant expression 1 statement 1 case constant expression n statement n default statement Fir
263. us Description Reads one byte of data via the OneWire bus Example tmp Ow Read amp PORTA 5 Ow Write Prototype void Ow Write char port char pin char par Description Writes one byte of data argument par via OneWire bus Example Ow Write amp PORTA 5 OxCC page 2294 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikroC making dimple MIKROC C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Library Example unsigned temp unsigned short j void Display_Temperature unsigned int temp IT eu void main ADCON1 OxFF Configure RA5 pin as digital I O PORTA OxFF TRISA OxOF PORTA is input PORTB 0 TRISB 0 PORTB is output Initialize LCD on PORTB and prepare for output do OW Reset amp PORTA 5 Onewire reset signal OW Write amp PORTA 5 0xCC Issue command SKIP ROM OW Write amp PORTA 5 0x44 Issue command CONVERT Delay us 120 OW Reset amp PORTA 5 OW Write amp PORTA 5 0xCC Issue command SKIP ROM OW Write amp PORTA 5 0xBE Issue command READ SCRATCHPAD Delay 400 OW Read amp PORTA 5 Get temperature LSB temp OW Read amp PORTA 5 Get temperature MSB temp 8 temp j Form the result Display Temperature temp Format and display result on LCD Delay 500 while 1 MIKROELEKTRONIKA DEVELOPME
264. ve Prototype void Man Receive char error Returns Returns one byte from signal Description Function extracts one byte from signal If signal format does not match the expected error flag will be set to 255 Requires To use this function you must first prepare the PIC for receiving See Man Receive Config Receive Init Example temp Man Receive error if error error handling page 0 MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS mikrot making amp simple MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS Man_Send_Config Prototype void Man Send Config char port char txpin Description The function prepares PIC for sending signal You need to specify port and txpin 0 7 for outgoing signal Baud rate is const 500 bps Example Man Send Config amp PORTD 0 Man Send Init Prototype void Man Receive Init char port Description The function prepares PIC for sending signal You need to specify port for outgoing signal txpin is pin 0 by default Baud rate is const 500 bps Example Man Send Init amp PORTD Man_Send Prototype void Man Send unsigned short data Description Sends one byte data Requires To use this function you must first prepare the PIC for sending See Man Send Config Send Init Example unsigned short msg Man Send ms
265. y 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 complexitiy of a given structure Note that two variables are of same structured type only if they were both defined by the same instruction or were defined using the same type identifier For exam ple a and b are of the same type struct int ml m2 a b But c and d are _not_ of the same type although their structure descriptions are identical struct int ml m2 c struct int ml m2 d Size of Structure You can get size of the structure in memory by means of operator sizeof Size of the structure does not necessarily need to be 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 funcl returns a structure mystruct func2 func2 returns pointer to structure A structure can be passed as an argument to a function in the following ways void funcl mystruct s directly void func2 mystruct sptr via pointer MO MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 7f 7f MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Structure Member Access Structure and union members are accessed usi
266. y stated internal linkage rules have external linkage The storage class specifiers auto and register cannot appear in an external declaration For each identifier in a translation unit declared with internal linkage no more than one external definition can be given An external definition is an external declaration that also defines an object or function that is it also allocates 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 mikroC allows later declarations of external names such as arrays structures and unions to add information to earlier declarations Here s an example int al No size struct mystruct Tag only no member declarators int a 3 1 2 3 Supply size and initialize struct mystruct int i j Add member declarators MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS MIKROD COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Storage Classes Associating identifiers with objects requires each identifier to have at least two attributes storage class and type sometimes referred to as data type The mikroC compiler deduces these attributes from implicit or explicit declarations in the source code Storage class dictates the location data segment register heap or stack of the object and its duration or lifetime
267. ype of message to filter either CAN CONFIG XTD MSG or CAN CONFIG STD MSG Requires CANSPI must be in Config mode otherwise the function will be ignored Example Set id of filter Bl F1 to 3 CANSPISetFilter CAN FILTER B1 Fl 3 CAN CONFIG XTD MSG MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS COMPILERS 5 7f MIKROG C COMPILER FOR MICROCHIP PIC MICROCONTROLLERS 62 adele CANSPIRead Prototype char CANSPIRead long id char data char datalen char CAN RX MSG FLAGS Returns Message from receive buffer or zero if no message found Description 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 id is message identifier data 1s an array 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 Requires CANSPI must be in mode in which receiving is possible Example char rcv rx len data 8 long id rcv CANSPIRead id data len 0 CANSPIWrite Prototype char CANSPIWrite long id char data char datalen char CAN TX MSG FLAGS Returns Returns zero if message cannot be queued buffer full Description If at least one empty transmit buffer 1s found function sends message on queue for transmission If buffer is full function returns 0 Parameters
268. ze void Returns Card size in kilobytes Description Returns size of Compact Flash card in kilobytes Requires Ports must be initialized See C Init Example size Cf Total Size 16 page MIKROELEKTRONIKA DEVELOPMENT TOOLS BOOKS GOMPILERS 4 8 8 MIKROC C COMPILER FOR MICROCHIP PIG MICROCONTROLLERS Ming amp simple Cf_Enable Prototype void Cf Enable void Description Enables the device Routine needs to be called only if you have disabled the device by means of C Disable These two routines in conjuction allow you to free occupy data line when working with multiple devices Check the example at the end of the chapter Requires Ports must be initialized See Init Example Cf Enable Cf Disable Prototype void Cf Disable void Description Routine disables the device and frees the data line for other devices To enable the device again call C Enable These two routines in conjuction allow you to free occu py data line when working with multiple devices Check the example at the end of the chapter Requires Ports must be initialized See C Init Example Cf Disable Cf Read Init Prototype void Cf Read Init long address char sectcnt Description Initializes CF card for reading Parameter address specifies sector address from where data will be read and sectcnt is

Download Pdf Manuals

image

Related Search

Related Contents

"取扱説明書"  Catalogo sistemi idronici 2013  電源の工事は電気工事店におまか 掘 ぎ 器具のワッ  Raptor Gaming H5 5.1 USB  Contents  Betriebsanleitung    Sondeur couleur ALF 500 (optionnel)  

Copyright © All rights reserved.
Failed to retrieve file