background image

MikroElektronika:  Development  tools  -  Books  -  Compilers

225

page

mikroC - C Compiler for Microchip PIC microcontrollers

mikroC

making it simple...

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 at sector address 

sector

. Read

data is 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 

Mmc_Init

.

Example

error = Mmc_Read_Sector(sector, data);

Mmc_Read_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-
mand; 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 

Mmc_Init

.

Example

error = Mmc_Write_Sector(sector, data);

Mmc_Write_Sector

Содержание PIC Microcontrollers PIC12

Страница 1: ...sed 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 satis...

Страница 2: ...tly 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 H...

Страница 3: ...MikroElektronika Development tools Books Compilers Table of Contents CHAPTER 1 mikroC IDE CHAPTER 2 Building Applications CHAPTER 3 mikroC Reference CHAPTER 4 mikroC Libraries mikroC User s manual...

Страница 4: ...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 E...

Страница 5: ...eclarations 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 Definitio...

Страница 6: ...ANSPI Library 153 Compact Flash Library 162 EEPROM Library 172 Ethernet Library 174 Flash Memory Library 186 I2C Library 188 Keypad Library 193 LCD Library 4 bit interface 197 LCD8 Library 8 bit inter...

Страница 7: ...type 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 vii pag...

Страница 8: ...mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple viii MikroElektronika Development tools Books Compilers page...

Страница 9: ...systems without compromising performance or control PIC and C fit together well PIC is the most popular 8 bit chip in the world used in a wide variety of applications and C prized for its efficiency i...

Страница 10: ...emory 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 pr...

Страница 11: ...ith 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 Ass...

Страница 12: ...ed in a floating panel As you type the actual parameter the next expected parameter will become bold Code Template CTR J You can insert the Code Template by typing the name of the template for instanc...

Страница 13: ...selected block of code by a simple click of a mouse using the Comment Uncomment icons from the Code Toolbar Bookmarks Bookmarks make navigation through large code easier CTRL number Go to a bookmark C...

Страница 14: ...p 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 All icon Also two more tabs are availabl...

Страница 15: ...available Step Into Step Over Run to Cursor etc Line that is to be executed is color highlighted Debug F9 Start the Debugger Run Pause Debugger F6 Run or pause the Debugger Step Into F7 Execute the cu...

Страница 16: ...u Double clicking an item in 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 specia...

Страница 17: ...nstruction 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 recalculat...

Страница 18: ...ogram simulation Check the Nested Calls Limitations for more information Note Real scenarios may differ from the simulation depending on runtime program parameters mikroC C Compiler for Microchip PIC...

Страница 19: ...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 t...

Страница 20: ...you can review statistics of your code Select Project View Statistics from the drop down menu or click the Statistics icon There are six tab windows Memory Usage Window Provides overview of RAM and R...

Страница 21: ...PIC microcontrollers mikroC making it simple Procedures Locations Window Displays how functions are distributed in microcontroller s memory Procedures Details Window Displays complete call tree along...

Страница 22: ...splays symbol ic names of variables and their addresses ROM Window Lists op codes and their addresses in form of a human readable hex code mikroC C Compiler for Microchip PIC microcontrollers mikroC m...

Страница 23: ...USART Universal Synchronous Asynchronous Receiver Transmitter communication terminal for RS232 communication You can launch it from the drop down menu Tools Terminal or by clicking the Terminal icon A...

Страница 24: ...g 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 7 Segment Display EEPROM Editor EEPROM Editor allows you to easily ma...

Страница 25: ...oaded 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...

Страница 26: ...orer on off CTRL SHIFT F5 View breakpoints Basic Editor shortcuts F3 Find Find Next CTRL A Select All CTRL C Copy CTRL F Find CTRL P Print CTRL R Replace CTRL S Save unit CTRL SHIFT S Save As CTRL V P...

Страница 27: ...sor F5 Toggle breakpoint F6 Run Pause Debugger F7 Step into F8 Step over F9 Debug CTRL F2 Reset MikroElektronika Development tools Books Compilers 19 page mikroC C Compiler for Microchip PIC microcont...

Страница 28: ...mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple 20 MikroElektronika Development tools Books Compilers page...

Страница 29: ...our 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...

Страница 30: ...appropriate project file Also an empty source file named after the project will be created by default Editing Project Later you can change project settings from drop down menu Project Edit Project Yo...

Страница 31: ...e files c You can specify your own custom search paths This can be configured by select ing Tools Options from drop down menu and then tab window Advanced In project settings you can specify either ab...

Страница 32: ...folder which contains the project file ppc 2 mikroC installation folder include folder 3 your custom search paths Managing Source Files Creating a new source file To create a new source file do the fo...

Страница 33: ...e 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 Saving File Under a Different Name Make sure that window containing the file you w...

Страница 34: ...tion that can be included in other projects List File lst Overview of PIC memory allotment instruction addresses registers routines etc Assembler File asm Human readable assembly with symbolic names e...

Страница 35: ...cannot return values Unreachable code Illegal expression with void Left operand must be pointer Function required Too many chars Undefined struct Nonexistent field Aggregate init error Incompatible t...

Страница 36: ...nds 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 est...

Страница 37: ...ng 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 spe...

Страница 38: ...erformance For example 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 multipl...

Страница 39: ...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...

Страница 40: ...rtability 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...

Страница 41: ...y that is provided by an external oscillator while ___FCY 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 y...

Страница 42: ...hin 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...

Страница 43: ...o 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...

Страница 44: ...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...

Страница 45: ...e 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 supp...

Страница 46: ...code sequence inter a b 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...

Страница 47: ...ng suffixes the data type of an integer constant is derived from its value Long and Unsigned Suffixes The suffix L or l attached to any constant forces the constant to be represented as a long Similar...

Страница 48: ...nt 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 2147483648 Error...

Страница 49: ...er Decimal point Decimal fraction e or E and a signed integer exponent optional Type suffix f or F or l or L optional You can omit either the decimal integer or the decimal fraction but not both You c...

Страница 50: ...trol code corresponding to that value for example x3F 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 va...

Страница 51: ...g it simple Sequence Value Char What it does a 0x07 BEL Audible bell b 0x08 BS Backspace f 0x0C FF Formfeed n 0x0A LF Newline Linefeed r 0x0D CR Carriage Return t 0x09 HT Tab horizontal v 0x0B VT Vert...

Страница 52: ...ored 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 duri...

Страница 53: ...ility 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...

Страница 54: ...tical 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...

Страница 55: ...um 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 wor...

Страница 56: ...solate conditional expressions and indicate function calls and function parameters d c a b override normal precedence if d z x essential with conditional statement func function call no args void func...

Страница 57: ...ents Comma The comma separates the elements of a function 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...

Страница 58: ...es used to create an empty statement for i 0 i 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 Labe...

Страница 59: ...icates 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...

Страница 60: ...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 storag...

Страница 61: ...g 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...

Страница 62: ...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 mus...

Страница 63: ...d 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 a...

Страница 64: ...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 u...

Страница 65: ...kroC 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 Lo...

Страница 66: ...static duration var init b only upon 1st call to f static int b 1 checkpoint a b void main At checkpoint we will have f a 1 b 1 after first call f a 1 b 2 after second call f a 1 b 3 after third call...

Страница 67: ...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 siz...

Страница 68: ...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...

Страница 69: ...ed 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...

Страница 70: ...ype 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 int...

Страница 71: ...s 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 dec...

Страница 72: ...t_Cp Temperature Lcd_Out_Cp temp Lcd_Chr_Cp 223 degree character Lcd_Chr_Cp C Use void as a function heading if the function does not take any parameters Alternatively you can just write empty parenth...

Страница 73: ...e 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...

Страница 74: ...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 ry In case of array of char you can use...

Страница 75: ...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 arr...

Страница 76: ...etic 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...

Страница 77: ...n 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 Ass...

Страница 78: ...jects Arrays and Pointers Arrays and pointers are not completely independent types in C When name of the array comes up in expression evaluation except with operators and sizeof it is implicitly conve...

Страница 79: ...y are of different types you must use a typecast operator Explicit type conversion is not necessary if one of the pointers is generic of void type Assigning the integer constant 0 to a pointer assigns...

Страница 80: ...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 the...

Страница 81: ...e_type int i some_type p a 0 for i 0 i n i here we do something with p p and with the last iteration p exceeds the last element of array a at this point p is undefined Pointer Subtraction Similar to a...

Страница 82: ...the name of the structure member declarator list is a list of structure members actually a list of variable declarations Variables of structured type are declared same as variables of any other type...

Страница 83: ...tructure 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 A...

Страница 84: ...struct int m1 m2 c struct int m1 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...

Страница 85: ...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 obj...

Страница 86: ...ess 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 obje...

Страница 87: ...xample union myunion union tag is myunion int i double d char ch mu pm 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...

Страница 88: ...r 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 c...

Страница 89: ...entifier here mybits 3 Relevant bits 2 3 and 4 Bits 5 6 and 7 are implicitly left out myreg Here is an example typedef struct prescaler 2 timeronoff 1 postscaler 4 mybitfield which declares structured...

Страница 90: ...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 situa...

Страница 91: ...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 t...

Страница 92: ...Conversions Typecasting In most situations compiler will provide an automatic implicit conversion of types where needed without any user interference Also you can explicitly convert an operand to anot...

Страница 93: ...de 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 jus...

Страница 94: ...orage class type qualifier type var1 init1 var2 init2 where var1 var2 are any sequence of distinct identifiers with optional initial izers Each of the variables is declared to be of type if omitted ty...

Страница 95: ...ic 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...

Страница 96: ...cates 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 somew...

Страница 97: ...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 aut...

Страница 98: ...usly declared as having internal linkage Declaration is not a definition if it has extern specifier and is not initialized The keyword extern is optional for a function prototype Use the extern modifi...

Страница 99: ...ng 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 t...

Страница 100: ...ather 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 wi...

Страница 101: ...th 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 p...

Страница 102: ...ex 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...

Страница 103: ...s can be restricted by using the static storage class specifier in function declaration see Storage Classes and Linkage Note Check the PIC Specifics for more info on functions limitations on PIC micro...

Страница 104: ...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...

Страница 105: ...unctions 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 re...

Страница 106: ...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 scala...

Страница 107: ...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...

Страница 108: ...cessor 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 eq...

Страница 109: ...le Precedence Operands Operators Associativity 15 2 left to right 14 1 type sizeof right to left 13 2 left to right 12 2 left to right 11 2 left to right 10 2 left to right 9 2 left to right 8 2 left...

Страница 110: ...he pointer reference operator See Pointers for more information mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple 102 MikroElektronika Development tools Books Compilers page...

Страница 111: ...a equals g both ASCII and EBCDIC Unary Arithmetic Operators Unary operators and are the only operators in C which can be either prefix e g k k or postfix e g k k When used as prefix operators and pre...

Страница 112: ...ay to allow complex expressions without parentheses to have expected meaning a 5 c 1 0 e i e a 5 c 1 0 e Always bear in mind that relational operators return either 0 or 1 Consider the fol lowing exam...

Страница 113: ...5678 equals 0x1230 because 0x1234 0001 0010 0011 0100 0x5678 0101 0110 0111 1000 0001 0010 0011 0000 that is 0x1230 MikroElektronika Development tools Books Compilers 105 page mikroC C Compiler for Mi...

Страница 114: ...l the discarded bits are equal to sign bit 000001 5 equals 000040 0x3801 4 equals 0x8010 overflow With shift right right most bits are discarded and the freed bytes on the left are assigned zeros in c...

Страница 115: ...a 1 b f x Logical AND 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 a b c...

Страница 116: ...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...

Страница 117: ...al operator associates from right to left Here are a couple of practical examples Find max a b max a b a b Convert small letter to capital no parentheses are actually necessary c c a c z c 32 c Condit...

Страница 118: ...y an operator rather than instruction Simple Assignment Operator For a common value assignment we use a simple assignment operator expression1 expression2 Expression1 is an object memory location to w...

Страница 119: ...n2 is an arithmetic type 2 expression1 has a qualified or unqualified version of a structure or union type compatible with the type of expression2 3 expression1 and expression2 are pointers to qualifi...

Страница 120: ...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...

Страница 121: ...ds 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 si...

Страница 122: ...able c but also intializes a divides b by 2 and increments c result x 10 y x 3 x z x 3 y returns computed value of variable z and also computes x and y Note Do not confuse comma operator sequence oper...

Страница 123: ...nt 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 la...

Страница 124: ...or 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 select...

Страница 125: ...ch 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 c...

Страница 126: ...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 examp...

Страница 127: ...f 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...

Страница 128: ...calculating scalar product of two vectors using the do statement s 0 i 0 do s a i b i i while i n For Statement The for statement implements an iterative loop Syntax of for statement is for init exp...

Страница 129: ...tors using the for statement for s 0 i 0 i n i s a i b i You can also do it like this valid but ugly for s 0 i 0 i n s a i b i i but this is considered a bad programming style Although legal calculati...

Страница 130: ...o skip the cycle It passes control to the end of the innermost enclosing end brace belonging to a looping construct At that point the loop continuation condition is re evaluat ed This means that conti...

Страница 131: ...Return Statement Use the return statement to exit from the current function back to the calling routine optionally returning a value Syntax is return expression This will evaluate the expression and r...

Страница 132: ...eclaration and ending at the closing brace Blocks can be nested to any depth up to the limits of memory For example for loop expects one statement in its body so we can pass it a com pound statement f...

Страница 133: ...aracter 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 a...

Страница 134: ...cted 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 expansio...

Страница 135: ...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 f...

Страница 136: ...rences 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 of the define line there must be an actua...

Страница 137: ...e 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 p...

Страница 138: ...in trying to locate the include file 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 in...

Страница 139: ...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...

Страница 140: ...ier define SPLICE x y x _ y Now the call SPLICE cnt 2 expands to identifier cnt_2 Note mikroC does not support the older nonportable method of token pasting using l r Conditional Compilation Condition...

Страница 141: ...ve is allowed The else 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...

Страница 142: ...nal 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...

Страница 143: ...roC 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 manipul...

Страница 144: ...oElektronika Development tools Books Compilers page BUILT IN ROUTINES Prototype void Delay_us const time_in_us Description Creates a software delay in duration of time_in_us microseconds a constant Ra...

Страница 145: ...built in routine it is presented in this topic for the sake of convenience Example Delay_Cyc 10 Hundred MCU cycles pause Delay_Cyc Prototype unsigned Clock_Khz void Returns Device clock in KHz rounded...

Страница 146: ...lash 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 Sec...

Страница 147: ...ry 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 approp...

Страница 148: ...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 4MHz 5V 5V PIC16F877A RA0 AN0 R...

Страница 149: ...h is 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 P18XXX8 PICmicros Micr...

Страница 150: ...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...

Страница 151: ...onfig 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 18XXX8 datasheet 1 4 BRP as defined in 18XXX8 datasheet 1...

Страница 152: ...Refer to datasheet for details Parameters SJW as defined in 18XXX8 datasheet 1 4 BRP as defined in 18XXX8 datasheet 1 64 PHSEG1 as defined in 18XXX8 datasheet 1 8 PHSEG2 as defined in 18XXX8 datasheet...

Страница 153: ...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 0xFFFFFFFF Complement will do the trick and fi...

Страница 154: ...stants 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 CANRead Prototype char CANWrite long id char data char datalen char...

Страница 155: ...ions CANInitialize and CANSetBaudRate expect one of these or a bitwise combination as their argument define CAN_CONFIG_DEFAULT 0xFF 11111111 define CAN_CONFIG_PHSEG2_PRG_BIT 0x01 define CAN_CONFIG_PHS...

Страница 156: ..._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 0xFC XXXXXX00 define CAN_TX_PRIORITY_1 0xFD XXXXXX01 define CAN...

Страница 157: ...RTR msg else clear define CAN_RX_DBL_BUFFERED 0x80 Set if msg was hardware double buffered You may use bitwise AND to adjust the appropriate flags For example if MsgFlag CAN_RX_OVERFLOW 0 Receiver ov...

Страница 158: ...TRISC 0 PORTD 0 TRISD 0 aa 0 aa1 0 aa2 0 Form value to be used with CANSendMessage aa1 CAN_TX_PRIORITY_0 CAN_TX_XTD_FRAME CAN_TX_NO_RTR_FRAME Form value to be used with CANInitialize aa CAN_CONFIG_SAM...

Страница 159: ...G_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 0xFF PORTD 0xFF id 12111 CANWrite id data 1 aa1 Send...

Страница 160: ...NT0 Vdd Vss RD6 PSP6 P1C RD7 PSP7 P1D RD5 PSP5 P1B RD4 PSP4 ECCP1 P1A RC7 RX DT RC6 TX CK RC5 SDO RC4 SDI SDA RD3 PSP3 C2IN RD2 PSP2 C2IN 10K Reset 5V 5V PIC18F458 RA0 AN0 Cvref RA2 AN2 Vref RA3 AN3 V...

Страница 161: ...ported by any PIC MCU that has SPI interface on PORTC Also CS pin of MCP2510 or MCP2515 must be connected to RC0 Example of HW connection is given at the end of the chapter Note Be sure to check CAN c...

Страница 162: ...equested 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 CANSPIGetOperationMode to verify correct operation...

Страница 163: ...NFIG_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 18XXX8 datasheet 1 4 BRP as defined in 18XXX8 datasheet 1 64 PHSEG...

Страница 164: ...e Refer to datasheet for details Parameters SJW as defined in 18XXX8 datasheet 1 4 BRP as defined in 18XXX8 datasheet 1 64 PHSEG1 as defined in 18XXX8 datasheet 1 8 PHSEG2 as defined in 18XXX8 datashe...

Страница 165: ...le 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 0xFFFFFFFF Complement will do the trick and fill...

Страница 166: ...ires 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 CANSPIRead Prototype char CANSPIWrite long id char data char datalen char...

Страница 167: ...aa aa1 len aa2 long id char zr const char _TRUE 0xFF const char _FALSE 0x00 void main TRISB 0 Spi_Init Initialize SPI module TRISC F2 0 Clear TRISC 2 PORTC F2 0 Clear PORTC 2 PORTC F0 1 Set PORTC 0 T...

Страница 168: ..._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...

Страница 169: ...OSI RC3 RD0 PSP0 RD1 PSP1 MCLR Vpp THV RC2 CCP1 RA1 AN1 RB7 PGD RB6 PGC RB5 RB4 RB3 PGM RB2 RB1 RB0 INT Vdd Vss RD6 PSP6 RD7 PSP7 RD5 PSP5 RD4 PSP4 RC7 RX DT RC6 TX CK RC5 RC4 RD3 PSP3 RD2 PSP2 4MH z...

Страница 170: ...T32 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 ca...

Страница 171: ...trlport and dataport Example Cf_Init PORTB PORTD Cf_Init Prototype unsigned long Cf_Total_Size void Returns Card size in kilobytes Description Returns size of Compact Flash card in kilobytes Requires...

Страница 172: ...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 the number of...

Страница 173: ...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 sectcnt is total number of...

Страница 174: ...must be initialized for write operation See Cf_Write_Init Example Cf_Write_Word 1000 Cf_Write_Word Prototype void Cf_Find_File char find_first char file_name Description Routine looks for files on CF...

Страница 175: ...Write_Init Example Write 50 000 zeroes bytes to file for i 0 i 50000 i Cf_File_Write_Byte 48 Cf_File_Write_Byte Prototype void Cf_Read_Sector int sector_number unsigned short buffer Description Reads...

Страница 176: ...File_Write_Complete MY_FILE1 txt Cf_File_Write_Complete Prototype void Cf_Write_Sector int sector_number unsigned short buffer Description Writes value from buffer to CF sector at sector_number Requir...

Страница 177: ...ck 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 a...

Страница 178: ...TB 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...

Страница 179: ...18 19 20 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 50 46 47 48 49 42 43 44 45 4MHz 5V 5V PIC16F877A RA0 AN0 RA2 AN2 Vref RA3 AN3 Vref RA4 TOCKI RA5 AN4 RE0 RD AN5 RE1 WR AN6 RE2 CS AN7 Vdd Vss O...

Страница 180: ...s Returns byte from the specified address Description Reads data from the specified address Parameter address is of byte type which means it can address only 256 locations For PIC18 micros with more E...

Страница 181: ...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 e...

Страница 182: ...ould do with the RS232 485 or CAN 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 E...

Страница 183: ...ta port Parameter ctrlP 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...

Страница 184: ...AC 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 pa...

Страница 185: ...Example Eth_Load_Ip_Packet Eth_Load_Ip_Packet 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 pac...

Страница 186: ...ress Prototype void Eth_Get_Hdr_Chksum void 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 se...

Страница 187: ...h_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 initia...

Страница 188: ...lling the Eth_Get_Udp_Source_Port function Example udp_dest_port Eth_Get_Udp_Dest_Port Eth_Get_Udp_Dest_Port Prototype unsigned Eth_Get_Udp_Source_Port void Returns Returns the source port socket of t...

Страница 189: ...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 se...

Страница 190: ...e only respond to port 80 HTML requests if tcp_dest_port 80u Eth_Load_Tcp_Header retrieve TCP Header data most of it Eth_Load_Tcp_Header Prototype void Eth_Send_Udp char msg Description Sends the prep...

Страница 191: ...zes the private variables used for this function Example flags Eth_Get_Tcp_Flags Eth_Get_Tcp_Flags Prototype unsigned short Eth_Get_Tcp_Hdr_Offset void Returns Returns the length or offset of the TCP...

Страница 192: ...epare the data to be sent through TCP see Eth_Set_Tcp_Data Example Eth_Tcp_Response Eth_Tcp_Response Prototype void Eth_Set_Tcp_Data const unsigned short data Description Prepares data to be sent on H...

Страница 193: ...CSB BA14 BA15 BA16 BA17 Vdd BA18 BA19 BA20 BA21 JP AUI LED2 LED1 LED0 RTL8019AS U5 SA13 SA14 SA15 SA16 SA17 LEDBNC TPIN TPIN Vdd RX SA18 SA19 GND IORB IOWB RX CD CD GND OSCO 81 82 83 84 85 86 87 88 89...

Страница 194: ...from Flash memory Description Reads data from the specified address in Flash memory Example Flash_Read 0x0D00 Flash_Read Prototype void Flash_Write unsigned address unsigned data for PIC16 void Flash...

Страница 195: ...ools Books Compilers 187 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple char i 0 j 0 long addr unsigned short dataRd unsigned short dataWr 64 1 2 3 4 5 6 7 8 9 0 1 2...

Страница 196: ...mples I2C_Init I2C_Start I2C_Repeated_Start I2C_Is_Idle I2C_Rd I2C_Wr I2C_Stop mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple 188 MikroElektronika Development tools Books...

Страница 197: ...igured before using this function See I2C_Init Example I2C_Start I2C_Start Prototype void I2C_Repeated_Start void Description Issues repeated START signal Requires I C must be configured before using...

Страница 198: ...quires 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_Rd Prototype char I2C_Wr char data Returns Return...

Страница 199: ...roC C Compiler for Microchip PIC microcontrollers mikroC making it simple void main PORTB 0 TRISB 0 I2C_Init 100000 I2C_Start Issue I2C start signal I2C_Wr 0xA2 Send byte via I2C command to 24cO2 I2C_...

Страница 200: ...c WP SCL SDA 24C04 5V 5V PIC16F877A RA0 AN0 RA2 AN2 Vref RA3 AN3 Vref RA4 TOCKI RA5 AN4 RE0 RD AN5 RE1 WR AN6 RE2 CS AN7 Vdd Vss OSC1 OSC2 RCO T1OSO RC1 T1OSI RC3 RD0 PSP0 RD1 PSP1 MCLR Vpp THV RC2 CC...

Страница 201: ...ibrary Routines 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_I...

Страница 202: ...e 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 ret...

Страница 203: ...e byte counter displays the total number of keys pressed in the second LCD row unsigned short kp cnt char txt 5 void main cnt 0 Keypad_Init PORTC Lcd_Init PORTB Initialize LCD on PORTC Lcd_Cmd LCD_CLE...

Страница 204: ...ef RA3 AN3 Vref RA4 TOCKI RA5 AN4 RE0 RD AN5 RE1 WR AN6 RE2 CS AN7 Vdd Vss OSC1 OSC2 RCO T1OSO RC1 T1OSI RC3 RD0 PSP0 RD1 PSP1 MCLR Vpp THV RC2 CCP1 RA1 AN1 RB7 PGD RB6 PGC RB5 RB4 RB3 PGM RB2 RB1 RB0...

Страница 205: ...Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd LCD Library 4 bit interface Library Routines Prototype void Lcd_Config char port char RS char EN char WR char D7 char D6 char D5 char D4 Description Initializes LCD at po...

Страница 206: ...ut char row char col char text Description Prints text on LCD at specified row and column parameter row and col Both string variables and literals can be passed as text Requires Port with LCD must be...

Страница 207: ...ine 2 char 3 Lcd_Chr 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 L...

Страница 208: ...turn 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 Blin...

Страница 209: ...n TRISB 0 PORTB is output Lcd_Init 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...

Страница 210: ...ext mikroElektronika void main TRISD 0 PORTD is output Lcd_Config 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 1 R W D4 E RS D3...

Страница 211: ...before using any of the following functions Lcd8_Config Lcd8_Init Lcd8_Out Lcd8_Out_Cp Lcd8_Chr Lcd8_Chr_Cp Lcd8_Cmd LCD8 Library 8 bit interface Library Routines Prototype void Lcd8_Config char ctrlp...

Страница 212: ...1 D0 dataport 0 Example Lcd8_Init PORTB PORTC Lcd8_Init Prototype void Lcd8_Out char row char col char text Description Prints text on LCD at specified row and column parameter row and col Both string...

Страница 213: ...line 2 char 3 Lcd8_Chr 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 w...

Страница 214: ...ektronika void main TRISB 0 PORTB is output TRISC 0 PORTC is output Lcd8_Init PORTB PORTC Initialize LCD at PORTB and PORTC Lcd8_Cmd Lcd_CURSOR_OFF Turn off cursor Lcd8_Out 1 1 text Print text on LCD...

Страница 215: ...0 PORTB is output TRISD 0 PORTD is output Initialize LCD at PORTB and PORTD with custom pin settings Lcd8_Config PORTB PORTD 3 2 0 0 1 2 3 4 5 6 7 Lcd8_Cmd Lcd_CURSOR_OFF Turn off cursor Lcd8_Out 1 1...

Страница 216: ...c routines Glcd_Init Glcd_Disable Glcd_Set_Side Glcd_Set_Page Glcd_Set_X Glcd_Read_Data Glcd_Write_Data Advanced routines Glcd_Fill Glcd_Dot Glcd_Line Glcd_V_Line Glcd_H_Line Glcd_Rectangle Glcd_Box G...

Страница 217: ...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 Requ...

Страница 218: ...rt 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 Glcd_Set_X 25 Glcd_Set_X Prototype unsigned shor...

Страница 219: ...ill 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 Glcd_Fill FF Requires GLCD needs to be initial...

Страница 220: ...eeds to be initialized See Glcd_Init Example Glcd_Line 0 63 50 0 2 Glcd_Line Prototype void Glcd_V_Line unsigned short y1 unsigned short y2 unsigned short x char color Description Similar to GLcd_Line...

Страница 221: ...r 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 Glcd_Rectangle 10 0 30 35 1 Glcd_Rectangle Prototype void...

Страница 222: ...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...

Страница 223: ...tters 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 Glcd_Write_Text Prototype void Glcd_Write_Char u...

Страница 224: ...e clear dots 1 draws a black image put dots and 2 draws an inverted image invert each dot Use the mikroC s integrated Bitmap to LCD editor menu option Tools Graphic LCD Editor to convert image to a co...

Страница 225: ...nit PORTB 2 0 3 5 7 1 PORTD do Draw circles Glcd_Fill 0 Clear screen Glcd_Write_Text Circles 0 0 1 j 4 while j 31 Glcd_Circle 63 31 j 2 j 4 Delay_ms 4000 Draw boxes Glcd_Fill 0 Clear screen Glcd_Write...

Страница 226: ...trollers mikroC making it simple 218 MikroElektronika Development tools Books Compilers page 1 18 K GND Vcc Vee RS R W E D0 D1 D2 D3 D4 D5 D6 D7 5V 10k 10 KS0108 GLCD Test Hello world mikroElektronika...

Страница 227: ...eive routines are blocking calls Man_Receive_Config Man_Receive_Init Man_Receive This means that PIC will wait until the task is performed e g byte is received synchronization achieved etc Routines fo...

Страница 228: ...d 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 M...

Страница 229: ...bps Example Man_Send_Config PORTD 0 Man_Send_Config Prototype void Man_Receive_Init char port Description The function prepares PIC for sending signal You need to specify port for outgoing signal txp...

Страница 230: ...e if error ErrorCount else PORTC 0 if ErrorCount 20 If there are too many errors ErrorCount 0 syncronize the receiver again PORTC 0xAA Indicate error Man_Receive_Init PORTD Synchronize receiver IdleCo...

Страница 231: ...C RB5 RB4 RB3 PGM RB2 RB1 RB0 INT Vdd Vss RD6 PSP6 RD7 PSP7 RD5 PSP5 RD4 PSP4 RC7 RX DT RC6 TX CK RC5 RC4 RD3 PSP3 RD2 PSP2 10K Reset R T 4 Vcc I n A GND Antenna Transmitter RF Module 5V 4MHz 5V 5V PI...

Страница 232: ...ad Mmc_Fat_Write Mmc_Set_File_Date mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple 224 MikroElektronika Development tools Books Compilers page Prototype unsigned short Mmc...

Страница 233: ...urred Requires Library needs to be initialized see Mmc_Init Example error Mmc_Read_Sector sector data Mmc_Read_Sector Prototype unsigned short Mmc_Write_Sector unsigned long sector char data Returns R...

Страница 234: ...CID register and returns 16 bytes of content into data_for_registers Requires Library needs to be initialized see Mmc_Init Example error Mmc_Read_Cid data Mmc_Read_Cid Prototype unsigned short Mmc_Re...

Страница 235: ...her functions of MMC FAT library Example Loop until MMC FAT is initialized at RC2 while Mmc_Fat_Init PORTC 2 Mmc_Fat_Init Prototype void Mmc_Fat_Assign char filename Description This routine designate...

Страница 236: ...needs to be initialized see Mmc_Fat_Init Example Mmc_Fat_Reset filesize Mmc_Fat_Reset Prototype void Mmc_Fat_Rewrite void Description Function resets the file pointer and clears the assigned file so t...

Страница 237: ...a 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 Mmc_Fat...

Страница 238: ...unsigned short data 512 void main Usart_Init 9600 Wait until MMC is initialized while Mmc_Init PORTC 2 Fill the buffer with the M character for i 0 i 511 i data i M Write it to MMC card sector 55 tmp...

Страница 239: ..._Write FAT_ERROR tmp for loop 1 loop 5 loop We want 5 files on our MMC card filename 7 loop 64 Set number 1 2 3 4 or 5 Mmc_Fat_Assign filename If file not found create new file Mmc_Fat_Rewrite Clear t...

Страница 240: ...8F458 RA0 AN0 Cvref RA2 AN2 Vref RA3 AN3 Vref RA4 TOCKI RA5 AN4 SS LVDIN RE0 RD AN5 RE1 WR C1OUT AN6 RE2 CS C2OUT AN7 Vdd Vss OSC1 CLKI OSC2 CLKO RA6 RC0 T1OSO T1CKI RC1 T1OSI RC3 SCK SCL RD0 PSP0 C1I...

Страница 241: ...ter 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 t...

Страница 242: ...pecify the location of DS1820 Requires Works with Dallas DS1820 temperature sensor only Example Ow_Reset PORTA 5 reset DS1820 connected to the RA5 pin Ow_Reset Prototype char Ow_Read char port char pi...

Страница 243: ...ISB 0 PORTB is output Initialize LCD on PORTB and prepare for output do OW_Reset PORTA 5 Onewire reset signal OW_Write PORTA 5 0xCC Issue command SKIP_ROM OW_Write PORTA 5 0x44 Issue command CONVERT_T...

Страница 244: ...Vref RA3 AN3 Vref RA4 TOCKI RA5 AN4 RE0 RD AN5 RE1 WR AN6 RE2 CS AN7 Vdd Vss OSC1 OSC2 RCO T1OSO RC1 T1OSI RC3 RD0 PSP0 RD1 PSP1 MCLR Vpp THV RC2 CCP1 RA1 AN1 RB7 PGD RB6 PGC RB5 RB4 RB3 PGM RB2 RB1...

Страница 245: ...Port pin 0 is Data line and port pin 1 is Clock line You need to call either Ps2_Init or Ps2_Config before using other routines of PS 2 library Requires Both Data and Clock lines need to be in pull up...

Страница 246: ...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 sp...

Страница 247: ...unsigned short keydata special down void main CMCON 0x07 Disable analog comparators comment this for PIC18 INTCON 0 Disable all interrupts Ps2_Init PORTA Init PS 2 Keyboard on PORTA Delay_ms 100 Wait...

Страница 248: ...Microchip PIC microcontrollers mikroC making it simple 240 MikroElektronika Development tools Books Compilers page PWM Library Library Routines Prototype void Pwm_Init long freq Description Initializ...

Страница 249: ...quires 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_Change_Duty 192 Set duty ratio to 75 Pwm_Change_Duty Prototype voi...

Страница 250: ...pp THV RC2 CCP1 RA1 AN1 RB7 PGD RB6 PGC RB5 RB4 RB3 PGM RB2 RB1 RB0 INT Vdd Vss RD6 PSP6 RD7 PSP7 RD5 PSP5 RD4 PSP4 RC7 RX DT RC6 TX CK RC5 RC4 RD3 PSP3 RD2 PSP2 330R 10K Reset The example changes PWM...

Страница 251: ...e 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 Outpu...

Страница 252: ...t 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 byt...

Страница 253: ...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 msg 8 RS485Master_S...

Страница 254: ...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 R...

Страница 255: ...Read dat If message is received without errors data 4 is set to 255 if RCSTA OERR PORTD 0x81 RS485Slave_Read dat void main TRISB 0 TRISD 0 Usart_Init 9600 Initialize usart module RS485Slave_Init 160 I...

Страница 256: ...B Vcc RE LTC485 R0 DE DI GND A B Vcc RE 4MHz 5V 5V 5V 5V PIC16F877A RA0 AN0 RA2 AN2 Vref RA3 AN3 Vref RA4 TOCKI RA5 AN4 RE0 RD AN5 RE1 WR AN6 RE2 CS AN7 Vdd Vss OSC1 OSC2 RCO T1OSO RC1 T1OSI RC3 RD0...

Страница 257: ...Compilers 249 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple Secure Digital Library Library Routines Prototype unsigned short Sd_Init unsigned short port unsigned s...

Страница 258: ...occurred Requires Library needs to be initialized see Sd_Init Example error Sd_Read_Sector sector data Sd_Read_Sector Prototype unsigned short Sd_Write_Sector unsigned long sector char data Returns Re...

Страница 259: ...ads CID register and returns 16 bytes of content into data_for_registers Requires Library needs to be initialized see Sd_Init Example error Sd_Read_Cid data Sd_Read_Cid Prototype unsigned short Sd_Rea...

Страница 260: ...short tmp unsigned short data 512 void main Usart_Init 9600 Initialize ports tmp Sd_Init PORTC 2 Fill the buffer with the M character for i 0 i 511 i data i M Write it to SD card sector 55 tmp Sd_Wri...

Страница 261: ...z 5V 5V PIC18F458 RA0 AN0 Cvref RA2 AN2 Vref RA3 AN3 Vref RA4 TOCKI RA5 AN4 SS LVDIN RE0 RD AN5 RE1 WR C1OUT AN6 RE2 CS C2OUT AN7 Vdd Vss OSC1 CLKI OSC2 CLKO RA6 RC0 T1OSO T1CKI RC1 T1OSI RC3 SCK SCL...

Страница 262: ...I2C_Stop mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple 254 MikroElektronika Development tools Books Compilers page Software I2C Library Library Routines Prototype void S...

Страница 263: ...ust be configured before using this function See Soft_I2C_Config Example Soft_I2C_Start Soft_I2C_Start Prototype char Soft_I2C_Read char ack Returns Returns one byte from the slave Description Reads o...

Страница 264: ...here were no errors Description Sends data byte parameter data via I C bus Requires START signal needs to be issued in order to use this function See Soft_I2C_Start Example Soft_I2C_Write 0xA3 Soft_I2...

Страница 265: ...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 wor...

Страница 266: ...Books Compilers page Software SPI Library Library Routines Prototype void Soft_Spi_Config char port const char SDI const char SD0 const char SCK Description Configures and initializes software SPI Pa...

Страница 267: ...ock 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_Rea...

Страница 268: ...e end of range const char _CHIP_SELECT 1 _TRUE 0xFF unsigned value void InitMain Soft_SPI_Config PORTB 4 5 3 TRISB _CHIP_SELECT ClearBit TRISC CHIP_SELECT TRISC 0x03 DAC increments 0 4095 output volta...

Страница 269: ...mikroC making it simple Software UART Library Library Routines Prototype void Soft_Uart_Init unsigned short port unsigned short rx unsigned short tx unsigned short baud_rate char inverted Description...

Страница 270: ...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 error while error Now we can wo...

Страница 271: ...munication menu choice Tools Terminal MikroElektronika Development tools Books Compilers 263 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple Library Example unsigned...

Страница 272: ...to be within range 0 7 Example Sound_Init PORTB 2 Initialize sound on RB2 Sound_Init Prototype void Sound_Play char period_div_10 unsigned num_of_periods Description Plays the sound at the specified p...

Страница 273: ...e for T f 1 T MikroElektronika Development tools Books Compilers 265 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple Library Example int adcValue void main PORTB 0 Cl...

Страница 274: ...folder subfolder Examples Spi_Init Spi_Init_Advanced Spi_Read Spi_Write mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple 266 MikroElektronika Development tools Books Compi...

Страница 275: ...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...

Страница 276: ...at the end of period Requires SPI must be initialized and communication established before using this function See Spi_Init_Advanced or Spi_Init Example short take buffer take Spi_Read buffer Spi_Rea...

Страница 277: ...ls Books Compilers 269 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple Library Example Function Declarations void max7219_init1 F D end char i void main Spi_Init Stan...

Страница 278: ...IG3 GND DIG5 V DIG1 LOAD SEGA CLK 4MHz 5V 8 8 8 8 8 8 8 8 PIC16F877A RA0 AN0 RA2 AN2 Vref RA3 AN3 Vref RA4 TOCKI RA5 AN4 RE0 RD AN5 RE1 WR AN6 RE2 CS AN7 Vdd Vss OSC1 OSC2 RCO T1OSO RC1 T1OSI RC3 RD0...

Страница 279: ...a_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 e...

Страница 280: ...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_Data_Ready Prototype char Usart_Read void Returns Return...

Страница 281: ...IC microcontrollers mikroC making it simple Prototype char Usart_Write char data Description Function transmits a byte data via USART Requires USART HW module must be initialized and communication est...

Страница 282: ...C1 C2 C2 V T2out R2in R2out T2in T1in R1out R1in T1out GN D Vcc 5V 4 7uF 4 7uF 4 7uF 4 7uF 4MHz 5V 5V PIC16F877A RA0 AN0 RA2 AN2 Vref RA3 AN3 Vref RA4 TOCKI RA5 AN4 RE0 RD AN5 RE1 WR AN6 RE2 CS AN7 Vd...

Страница 283: ...graphics tablet and the like Hid_Enable Hid_Read Hid_Write Hid_Disable MikroElektronika Development tools Books Compilers 275 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making i...

Страница 284: ...before using this function See Hid_Enable Example get Hid_Read Hid_Read Prototype void Hid_Write unsigned writebuff unsigned short len Description Function sends data from wrbuff to host Write Buffer...

Страница 285: ...uffer 64 void interrupt asm CALL _Hid_InterruptProc asm nop void Init_Main Disable all interrupts Disable GIE PEIE TMR0IE INT0IE RBIE INTCON 0 INTCON2 0xF5 INTCON3 0xC0 Disable Priority Levels on inte...

Страница 286: ...Compilers page Timer 0 T0CON 0x07 TMR0H 65536 156 8 TMR0L 65536 156 0xFF INTCON T0IE 1 Enable T0IE T0CON TMR0ON 1 Main Program Routine void main Init_Main Hid_Enable userRD_buffer userWR_buffer do fo...

Страница 287: ...SPP RE1 AN6 CK2SPP RE2 AN7 OESPP Vdd Vss OSC1 CLKI OSC2 CLKO RA6 RC0 T1OSO T13CKI RC1 T1OSI CCP2 UOE Vusb RD0 SPP0 RD1 SPP1 MCLR Vpp RE3 RC2 CCP1 P1A RA1 AN1 RB7 KBI3 PGD RB6 KBI2 PGC RB5 KBI1 PGM RB4...

Страница 288: ...nfluence 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 orde...

Страница 289: ...order to facilitate PIC programming isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit toupper tolower MikroElektronika Development tools Books Compilers 281 pag...

Страница 290: ...otherwise returns zero iscntrl Prototype char isdigit char character Description Function returns 1 if the character is a digit 0 9 otherwise returns zero isdigit Prototype char isgraph char characte...

Страница 291: ...o isprint 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 ispunct Prototype char isspace c...

Страница 292: ...int character Description If the character is a lowercase letter a z function returns an uppercase letter Otherwise function returns an unchanged input parameter toupper Prototype char tolower int ch...

Страница 293: ...fabs floor frexp ldexp log log10 modf pow sin sinh sqrt tan tanh MikroElektronika Development tools Books Compilers 285 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simp...

Страница 294: ...cription Function computes the arc tangent of parameter x that is the value whose tangent is x The return value is in radians between pi 2 and pi 2 inclusive atan Prototype double atan2 double x Descr...

Страница 295: ...o 1 cos Prototype double cosh double x Description Function returns the hyperbolic cosine of x defined mathematically as ex e x 2 If the value of x is too large if overflow occurs the function fails c...

Страница 296: ...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 poi...

Страница 297: ...double whole Description Function returns the signed fractional component of num placing its whole number component into the variable pointed to by whole modf Prototype double pow double x double y De...

Страница 298: ...value of x is too large if overflow occurs the function fails sinh Prototype double sqrt double num Description Function returns the non negative square root of num sqrt Prototype double tan double x...

Страница 299: ...C Compiler for Microchip PIC microcontrollers mikroC making it simple ANSI C Stdlib Library Library Routines Prototype int abs int num Description Function returns the absolute i e positive value of n...

Страница 300: ...t recognize this includes a null character atoi 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 consis...

Страница 301: ...pe long 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 ldiv Prototyp...

Страница 302: ...scription Function uses the seed as a starting point for a new sequence of pseudo random num bers to be returned by subsequent calls to rand No values are returned by this func tion srand Prototype in...

Страница 303: ...y strspn MikroElektronika Development tools Books Compilers 295 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple ANSI C String Library Library Routines Prototype int m...

Страница 304: ...s2 into the object pointed to by s1 Unlike with memcpy memory areas s1 and s2 may overlap Function returns the value of s1 memmove Prototype void memset void s int c int n Description Function copies...

Страница 305: ...rcmp char s1 char s2 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 evaluat...

Страница 306: ...result Function returns s1 strncat Prototype char strncpy char s1 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 shorte...

Страница 307: ...2Dec Dec2Bcd Bcd2Dec16 Dec2Bcd16 MikroElektronika Development tools Books Compilers 299 page mikroC C Compiler for Microchip PIC microcontrollers mikroC making it simple Conversions Library Library Ro...

Страница 308: ...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 charac...

Страница 309: ...alue of long type Output string has fixed width of 11 characters remaining positions on the left if any are filled with blanks Example long jj 3700000 char txt LongToStr jj txt txt is 3700000 three bl...

Страница 310: ...mple unsigned a a Dec2Bcd16 4660 equals 1234 Dec2Bcd16 Prototype unsigned Bcd2Dec16 unsigned bcdnum Returns Returns converted decimal value Description Converts 16 bit BCD numeral bcdnum to its decima...

Страница 311: ...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 is imple mented as a lookup...

Страница 312: ...d 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...

Отзывы: