mikroElektronika User’s manual Development tools - Books - Compilers www.mikroelektronika.co.yu C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 copyrighted material (e.g., a book). The manual and the compiler may not be copied, partially or as a whole without the written consent from the mikroEelktronika.
mikroC User’s manual Table of Contents CHAPTER 1 mikroC IDE CHAPTER 2 Building Applications CHAPTER 3 mikroC Reference CHAPTER 4 mikroC Libraries MikroElektronika: Development tools - Books - Compilers
mikroC making it simple...
mikroC making it simple...
mikroC making it simple...
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CHAPTER 1 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 applications 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 in a wide variety of applications, and C, prized for its efficiency, is the natural choice for developing embedded systems.
mikroC making it simple...
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers CODE EDITOR The Code Editor is an advanced text editor fashioned to satisfy the needs of professionals. General code editing is same as working with any standard text-editor, including familiar Copy, Paste, and Undo actions, common for Windows environment.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Code Assistant [CTRL+SPACE] If you type a first few letter of a word 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Auto Correct The Auto Correct feature corrects common typing mistakes. To access the list of recognized typos, select Tools > Options from the drop-down menu, or click the Tools Icon, and then select the Auto Correct Tab. You can also add your own preferences to the list. Comment/Uncomment Comment / Uncomment Icon.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... CODE EXPLORER 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 declaration 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. Collapse/Expand All Icon. Also, two more tabs are available in Code Explorer.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers DEBUGGER Start Debugger The source-level Debugger is an integral component of mikroC development environment. It is designed to simulate operations of Microchip Technology's PICmicros and to assist users in debugging software written for these devices. 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers Toggle Breakpoint. making it simple... Toggle Breakpoint [F5] Toggle breakpoint at current cursor position. To view all the breakpoints, select Run > View Breakpoints from the drop-down menu. 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 program.
mikroC making it 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Call Stack Window The Call Stack Window keeps track of depth and order of nested routine calls in program simulation. Check the Nested Calls Limitations for more information. Note: Real scenarios may differ from the simulation, depending on runtime program parameters.
mikroC making it 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... STATISTICS Statistics Icon. After successful compilation, 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 ROM memory usage in form of histogram. Procedures (Graph) Window Displays functions in form of histogram, according to their memory allotment.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Procedures (Locations) Window Displays how functions are distributed in microcontroller’s memory. Procedures (Details) Window Displays complete call tree, along with details for each function: size, start and end address, calling frequency, return type, etc.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... RAM Window Summarizes all GPR and SFR registers and their addresses. Also displays symbolic names of variables and their addresses. ROM Window Lists op-codes and their addresses in form of a human readable hex code.
mikroC making it 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 > Terminal or by clicking the Terminal icon. ASCII Chart The ASCII Chart is a handy tool, particularly useful when working with LCD display. You can launch it from the drop-down menu Tools > ASCII chart.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 7 Segment Display Decoder 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 > 7 Segment Display. EEPROM Editor EEPROM Editor allows you to easily manage EEPROM of PIC microcontroller.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers mikroBootloader mikroBootloader can be used only with PICmicros that support flash write. 1. Load the PIC 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 > 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CHAPTER 2 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 appropriate. You can then share your mikroCompiled Libraries (.mcl files) with other developers without disclosing the source code. The best part is that you can use .
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers SOURCE FILES 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 preprocessor to include other source files — see Projects for more information.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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 version, the search is made successively in each of the following locations, in this particular order: 1. mikroC installation folder > “include” folder, 2.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Opening an Existing File Open File Icon. Select File > Open from drop-down menu, or press CTRL+O, or click the Open 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... COMPILATION Compile Icon. When you have created the project and written the source code, you will want to compile it. Select Project > Build from drop-down menu, or click Build Icon, or simply hit CTRL+F9. 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.
mikroC making it simple... mikroC - 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers - making it simple...
CHAPTER 3 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 operations, is optimized for working with bytes.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 modifications 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Predefined Globals and Constants To facilitate PIC programming, mikroC implements a number of predefined globals and constants. All PIC SFR registers are implicitly declared as global variables 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 .
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 language. In the tokenizing phase of compilation, the source code file is parsed (that is, broken down) into tokens and whitespace.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 /*.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers CONSTANTS Constants or literals are tokens representing fixed numeric or character values. mikroC supports: - integer constants, - floating point constants, - character constants, - string constants (strings literals), - enumeration constants. The data type of a constant is deduced by the compiler using such clues as numeric value and the format used in the source code.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 l suffix, its data type will be the first of the following that can accommodate its value: long int, unsigned long int.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Binary Constants All constants starting with 0b (or 0B) are taken to be binary. In the absence of any overriding suffixes, the data type of an binary constant is derived from its value, according to the rules presented above. For example, 0b11101 will be treated as short. Octal Constants All constants with an initial zero are taken to be octal. If an octal constant contains the illegal digits 8 or 9, an error is reported.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Character Constants A character constant is one or more characters enclosed in single quotes, such as 'A', '+', or '\n'. In C, single-character constants have data type int. Multicharacter constants are referred to as string constants or string literals. For more information refer to String Constants.
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... String Constants String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: "This is a string." The null string, or empty string, is written like "". A literal string is stored internally as the given sequence of characters plus a final null character.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Enumeration Constants Enumeration constants are identifiers defined in enum type declarations. The identifiers 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers KEYWORDS Keywords are words reserved for special purposes and must not be used as normal identifier names. Beside standard C keywords, all relevant SFR are defined as global variables and represent reserved words that cannot be redefined (for example: TMR0, PCL, etc). Probe the Code Assistant for specific letters (Ctrl+Space in Editor) or refer to Predefined Globals and Constants.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers IDENTIFIERS Identifiers are arbitrary names of any length given to functions, variables, symbolic constants, user-defined data types, and labels. All these program elements will be referred to as objects throughout the help (not to be confused with the meaning of object in object-oriented programming). Identifiers can contain the letters a to z and A to Z, the underscore character “_”, and the digits 0 to 9.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... PUNCTUATORS The mikroC punctuators (also known as separators) include brackets, parentheses, braces, comma, semicolon, colon, asterisk, equal sign, and pound sign. Most of these punctuators also function as operators.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Braces Braces { } indicate the start and end of a compound statement: if (d == z) { ++x; func(); } The closing brace serves as a terminator for the compound statement, so a semicolon is not required after the }, except in structure declarations. Often, the semicolon is illegal, as in if (statement) { ... }; else { ... }; /* illegal semicolon! */ For more information, refer to Compound Statements.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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; a = b + c; For more information, see Assignment Operators.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 functions, variables, symbolic constants, user-defined data types, and labels.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Lvalues An lvalue 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 lvalue.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... SCOPE AND VISIBILITY Scope The scope of identifier is the part of the program in which the identifier can be used to access its object. There are different categories of scope: block (or local), function, function prototype, and file. These depend on how and where identifiers are declared.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... NAME SPACES Name space is the scope 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.
mikroC making it simple... mikroC - 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 in memory. We also distinguish between compile-time and run-time objects. Variables, for instance, unlike typedefs and types, have real memory allocated during run time. There are two kinds of duration: static and local.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Here is an example of two objects with local scope, but with different duration: void f() { /* 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! */ a++; b++; } void main() { /* At checkpoint, we will f(); // a=1, b=1, after f(); // a=1, b=2, after f(); // a=1, b=3, after // etc.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers TYPES C is strictly typed language, which means that every object, function, and expression need to have a strictly defined type, known in the time of compilation. Note that C works exclusively with numeric types.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - 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 float 32-bit ±1.17549435082E-38 ..
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Enumerations An enumeration data type is used for representing an abstract, discreet set of values with appropriate symbolic names. Enumeration Declaration Enumeration is declared like this: enum tag {enumeration-list}; Here, tag is an optional name of the enumeration; enumeration-list is a list of discreet values, enumerators. The enumerators listed inside the braces are also known as enumeration constants.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers The order of constants can be explicitly re-arranged. For example: enum colors { black, red, green, blue=6, violet, white=4 }; // // // // // // value value value value value value 0 1 2 6 7 4 Initializer expression can include previously declared enumerators.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Void Type void is a special type indicating the absence of any value. There are no objects of void; instead, void is used for deriving more complex types. Void Functions Use the void keyword as a function return type if the function does not return a value.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers DERIVED TYPES The derived types are also known as structured types. These types are used as elements 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 elements of an array and are identified by their position in array.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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”.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 &. 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.
mikroC making it simple... mikroC - C 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 indirection operator (*) to a “pointer to one past the last element” leads to undefined behavior.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 fundamental 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 within braces, similar to array. Referring to declarations from the previous example: /* Declare and initialize dots p and q: */ struct Dot p = {1., 1.}, q = {3.7, -0.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Structure Assignment Variables of same structured type may be assigned one to another by means of simple assignment operator (=). This will copy the entire contents of the variable to destination, regardless of the inner 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Structure Member Access Structure and union members are accessed using the following two selection operators: . (period) -> (right arrow) The operator . is called the direct member selector and it is used to directly access one of the structure’s members. Suppose that the object s is of struct type S. Then if m is a member identifier of type M declared in s, the expression s.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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; } s, *sptr; //... // // // // s.i = 3; s.a.j = 2; sptr->d = 1.23; sptr->a.x = 3.14; assign assign assign assign 3 to 2 to 1.23 3.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Unions Union types are derived types sharing many of the syntactic and functional features 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).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Referring to declarations from the previous example: mu.d = 4.016; Lcd_Out_Cp(FloatToStr(mu.d)); Lcd_Out_Cp(IntToStr(mu.i)); // OK: displays mu.d = 4.016 // 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 within byte from right to left.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 is changing it to the same object of another type (i.e. applying another type to a given object).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Arithmetic Conversions When you use an arithmetic expression, such as a+b, where a and b are of different arithmetic types, mikroC performs implicit type conversions before the expression is evaluated. These standard conversions include promotions of “lower” types to “higher” types in the interests of accuracy and consistency.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 5/4*3. 3.*5/4 // = 2. + 3.1 = 5.1 // = (5/4)*3. = 1*3. = 1.*3. = 3.0 // = (3.*5)/4 = (3.*5.)/4 = 15./4 = 15./4. = 3.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers DECLARATIONS Introduction to Declarations Declaration introduces one or several names to a program – it informs the compiler 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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) ? x : y; } int i; int i; /* Definition of variable i */ /* Error: i is already defined! */ Declarations and Declarators A declaration is a list of names.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Linkage An executable program is usually created by compiling several independent translation 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... External Linkage Rule: 1. names having file scope, that do not comply to any of previously stated internal linkage rules, have external linkage. The storage class specifiers auto and register cannot appear in an external declaration. For each identifier in a translation unit declared with internal linkage, no more than one external definition can be given.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Type Qualifiers Type qualifiers const and volatile are optional in declarations and do not actually 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Typedef Specifier Specifier typedef introduces a synonym for a specified type. You can use typedef 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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).
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Initialization At the time of declaration, you can set the initial value of a declared object, i.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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers FUNCTIONS Functions are central to C programming. Functions are usually defined as subprograms which return a value based on a number of input parameters. Return value of 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 function declarations cannot be nested.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 disagree, implicit type conversions rules apply.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers OPERATORS Operators are tokens that trigger some computation when applied to variables and other objects in an expression.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Precedence Operands Operators Associativity 15 2 () 14 1 ! & ~ ++ (type) 13 2 * / 12 2 + - 11 2 << 10 2 < 9 2 == 8 2 & left-to-right 7 2 ^ left-to-right 6 2 | left-to-right 5 2 && left-to-right 4 2 || left-to-right 3 3 ?: left-to-right 2 2 = &= 1 2 , [] .
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Binary Arithmetic Operators Division of two integers returns an integer, while remainder is simply truncated: /* for example: */ 7 / 4; // equals 1 7 * 3 / 4; // equals 5 /* but: */ 7. * 3./ 4.; // equals 5.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Relational Operators Use relational operators to test equality or inequality of expressions. If the expression evaluates to true, it returns 1; otherwise it returns 0. All relational operators associate from left to right.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... /* Similarly: */ /* equals 0x567C */ /* equals 0x444C */ /* equals 0xEDCB */ 0x1234 | 0x5678; 0x1234 ^ 0x5678; ~ 0x1234; Bitwise Shift Operators Binary operators << and >> move the bits of the left operand for a number of positions specified by the right operand, to the left or right, respectively. Right operand has to be positive.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Logical Operators Operands of logical operations are considered true or false, that is non-zero or zero. Logical operators always return 1 or 0. Operands in a logical expression must be of scalar type. Logical operators && and || associate from left to right. Logical negation operator ! associates from right to left.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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 && b && c where a is false (0), then operands b and c will not be evaluated. This is very important if b and c are expressions, as their possible side effects will not take place! Logical vs.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Conditional Operator ? : The conditional operator ? : is the only ternary operator in C. Syntax of the conditional operator is: expression1 ? expression2 : expression3 Expression1 evaluates first. If its value is true, then expression2 evaluates and expression3 is ignored. If expression1 evaluates to false, then expression3 evaluates and expression2 is ignored.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 resulting type is a pointer to a type qualified with all the type qualifiers of the types pointed to by both operands. 6.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Thus, we have 10 different compound assignment operators: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, and >>=. All of these associate from right to left. Spaces separating compound operators (e.g. + =) will generate error. Compound assignment has the same effect as expression1 = expression1 op expression2 except the lvalue expression1 is evaluated only once.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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-memory error if it can’t compile an expression that is too complex.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Binary operator comma (,) has the lowest precedence and associates from left to right, so that a, b, c is same as (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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 (;).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Nested if statements Nested if statements require additional attention.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 specified).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Iteration Statements Iteration statements let you loop a set of statements. There are three forms of iteration 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Do Statement The do statement executes until the condition becomes false. Syntax of do statement is: do statement while (expression); The statement is executed repeatedly as long as the value of expression remains non-zero. The expression is evaluated after each iteration, so the loop will execute statement at least once. Parentheses around expression are mandatory.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 loop is by means of break statement.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 innermost switch, for, while, or do block.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Compound Statements (Blocks) A compound statement, or block, is a list (possibly empty) of statements enclosed in matching braces {}. Syntactically, a block can 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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;} ...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Macros with Parameters The following syntax is used to define a macro with parameters: #define macro_identifier() 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Here is a simple example: // A simple macro which returns greater of its 2 arguments: #define _MAX(A, B) ((A) > (B)) ? (A) : (B) // Let's call it: x = _MAX(a + b, c + d); /* Preprocessor will transform the previous line into: x = ((a + b) > (c + d)) ? (a + b) : (c + d) */ It is highly recommended to put parentheses around each of the arguments in macro body – this will avoid possible problems with operator precedence.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 following #include: #include macro_identifier It assumes a macro definition exists that will expand the macro identifier into a valid delimited header name with either of the or "header_name" formats.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Now, the following code, LCD_PRINT(temp) will be preprocessed to this: Lcd_Out_Cp("temp" ": "); Lcd_Out_Cp(IntToStr(temp)); Operator ## Operator ## is used for token pasting: you can paste (or merge) two tokens together 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Directives #if, #elif, #else, and #endif The conditional directives #if, #elif, #else, and #endif work very similar to the common C conditional statements. If the expression you write after the #if has a nonzero value, the line group immediately following the #if directive is retained in the translation unit. Syntax is: #if constant_expression_1 [#elif constant_expression_2 ] ...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Any processed section can contain further conditional clauses, nested to any depth. Each nested #else, #elif, or #endif directive belongs to the closest preceding #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.
CHAPTER 4 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, 1Wire, LCD, PWM, RS485, numeric formatting, bit manipulation, and many other are included along with practical, ready-to-use code examples.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... BUILT-IN ROUTINES mikroC compiler provides a set of useful built-in utility functions. Built-in functions do not require any header files to be included; you can use them in any part of your project.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 Creates a delay based on MCU clock.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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).
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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–checking and fault confinement. Faulty CAN data and remote frames are re-transmitted automatically, similar to the Ethernet.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 0xFF: If set to 0xFF, this is a blocking call – the function won’t “return” until the requested mode is set. If 0, this is a non-blocking call.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... mikroC - 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... CANRead Prototype char CANRead(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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers // ..
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Library Example unsigned short aa, aa1, len, aa2; unsigned char data[8]; long id; unsigned short zr, cont, oldstate; //........
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers // ..
+5V +5V 10K RB6/PGC RB7/PGD +5V TX-CAN RS GND CANH VCC CANL RXD Vref PCA82C250 or MCP2551 RS +5V 10K PIC18F458 RA0/AN0/Cvref RB4 MCLR/Vpp RB3/CANRX RB5/PGM RA2/AN2/Vref- RA1/AN1 RA3/AN3/Vref+ RB2/CANTX/INT2 RB1/INT1 RA4/TOCKI RA5/AN4/SS/LVDIN RB0/INT0 Vdd RE0/AN5/RD/ RE1/AN6/WR/C1OUT RD7/PSP7/P1D Vss Vdd RD5/PSP5/P1B RD6/PSP6/P1C +5V TX-CAN GND VCC RXD CANH CANL Vref 10R 10R RE2/AN7/CS/C2OUT OSC1/CLKI RC7/RX/DT RD4/PSP4/ ECCP1/P1A Vss RC0/T1OSO/T1CKI RC6/TX/CK OSC2/CLKO/RA
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 0xFF: If set to 0xFF, this is a blocking call – the function won’t “return” until the requested mode is set.
mikroC making it simple... mikroC - 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. All pending transmissions are aborted. Sets all mask registers to 0 to allow all messages.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... mikroC - 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... 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, aa1, len, aa2; long id; char zr; const char _TRUE = 0xFF; const char _FALSE = 0x00; void main(){ TRISB = 0; Spi_Init(); TRISC.F2 = 0; PORTC.F2 = 0; PORTC.F0 = 1; TRISC.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers // ..
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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(&PORTB, &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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 Cf_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 Cf_Init.
mikroC making it simple... mikroC - C 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 CF must be initialized for read operation. See Cf_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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Cf_Write_Byte Prototype void Cf_Write_Byte(char data); Description Writes one byte (data) to CF. All 512 bytes are transferred to a buffer. Requires CF must be initialized for write operation. See Cf_Write_Init. Example Cf_Write_Byte(100); Cf_Write_Word Prototype void Cf_Write_Word(int data); Description Writes one word (data) to CF. All 512 bytes are transferred to a buffer.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Cf_File_Write_Init Prototype void Cf_File_Write_Init(void); Description Initializes CF card for file writing operation (FAT16 only). Requires Ports must be initialized. See Cf_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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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 Cf_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.
mikroC making it simple... 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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.
MikroElektronika: Development tools - Books - Compilers +5V 4MHz 10K +5V Vdd Vss RD2/PSP2 RC4 RC3 RD1/PSP1 RC5 RC2/CCP1 RD3/PSP3 RC6/TX/CK RC1/T1OSI RD0/PSP0 RD4/PSP4 RC7/RX/DT OSC1 RCO/T1OSO RD6/PSP6 RD5/PSP5 Vss OSC2 RD7/PSP7 Vdd RE2/CS/AN7 RB0/INT RE1/WR/AN6 RB2 RB1 RE0/RD/AN5 RA5/AN4 RA4/TOCKI RA3/AN3/Vref+ RB4 RB3/PGM RB5 RA1/AN1 RA2/AN2/Vref- RB6/PGC RA0/AN0 MCLR/Vpp/THV RB7/PGD PIC16F877A +5V 10K +5V 25 Compact Flash Card Compact Flash Connector (TOP VIEW) 24 4
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 means it can address only 256 locations.
mikroC making it simple... mikroC - 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Eth_Init Prototype void Eth_Init(char *addrP, char *dataP, char *ctrlP, char pinReset, char pinIOW, char pinIOR); Description Performs initialization of Ethernet card and library.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Eth_Get_Ip_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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Eth_Get_Hdr_Chksum 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 sequence of calls must be obeyed (see the Ip_Event function in the supplied Ethernet example).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Eth_Arp_Response Prototype void Eth_Arp_Response(void); Description An automated ARP response. User should simply call this function once he detects the ARP event on the NIC. Requires As specified for the entire library.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.).
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Library Example Check the supplied Ethernet example in the Examples folder. 200 +5V 1K 8 9 1K 7 10 6 11 3 14 2 15 1 16 0.1u +5V +5V 0.1u 0.1u 0.1u BD3 BD2 GND BD1 BD0 GND SD15 SD14 Vdd SD13 SD12 SD11 SD10 SD9 SD8 IOCS16B INT7 INT6 INT5 INT4 OSCI TX+ TXVdd LD HD GND SD7 SD6 SD5 SD4 SD3 SD2 SD1 SD0 IOCHRDY AEN RSTDRV SMEMWB SMEMRB RTL8019AS U5 J2 0.1u 2KV 0.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 PIC16 char Flash_Read(long unsigned address); // for PIC18 Returns Returns data byte from Flash memory.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 > Terminal.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... I2C Library I²C full master MSSP module is available with a number of PIC MCU models. mikroC provides I2C library which supports the master I²C 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”.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers I2C_Start Prototype char I2C_Start(void); Returns If there is no error, function returns 0. Description Determines if I²C bus is free and issues START signal. Requires I²C 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... I2C_Rd Prototype char I2C_Rd(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 I2C_Start.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Library Example This code demonstrates use of I²C 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).
mikroC making it simple...
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 scheme 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 1 to 16, depending on the key. Requires Port needs to be appropriately initialized; see Keypad_Init.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Library Example 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.
mikroC making it simple...
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 following library functions.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Lcd_Init Prototype 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 -> PORT.7, D6 -> PORT.6, D5 -> PORT.5, D4 -> PORT.4, E -> PORT.3, RS -> PORT.2. 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 col).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 col). Both variables and literals can be passed as character. Requires Port with LCD must be initialized. See Lcd_Config or Lcd_Init.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 position. Display data RAM is unaffected.
mikroC making it simple...
mikroC making it simple...
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Lcd8_Init Prototype void Lcd8_Init(char *ctrlport, char *dataport); Description Initializes LCD at Control port (ctrlport) and Data port (dataport) with default pin settings (see the connection scheme at the end of the chapter): E -> ctrlport.3, RS -> ctrlport.2, R/W -> ctrlport.0, D7 -> dataport.7, D6 -> dataport.6, D5 -> dataport.5, D4 -> dataport.4, D3 -> dataport.3, D2 -> dataport.2, D1 -> dataport.1, D0 -> dataport.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 col). Both variables and literals can be passed as character. Requires Ports with LCD must be initialized. See Lcd8_Config or Lcd8_Init.
mikroC making it simple...
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... GLCD Library mikroC provides a library for drawing and writing on Graphic LCD. These routines 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 following functions.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Glcd_Init Prototype void Glcd_Init(unsigned char *ctrl_port, char cs1, 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, 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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 void Glcd_Set_X(unsigned short x_pos); Description Positions to x dots from the left border of GLCD within the given page.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 Glcd_Init. Example Glcd_Write_Data(data); Glcd_Fill Prototype void Glcd_Fill(unsigned short pattern); Description Fills the GLCD memory with byte pattern.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Glcd_Line Prototype void Glcd_Line(int x1, int y1, int x2, int y2, char color); Description Draws a line on the GLCD from (x1, y1) 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Glcd_Rectangle Prototype void Glcd_Rectangle(unsigned short x1, unsigned short y1, 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” border (invert each dot).
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 border 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).
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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-to-LCD editor (menu option Tools > BMP2LCD) to convert image to a constant array suitable for display on GLCD. Requires GLCD needs to be initialized. See Glcd_Init.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Library Example The following drawing demo tests advanced routines of GLCD library.
mikroC making it simple...
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Manchester Code Library mikroC provides a library for handling Manchester coded signals.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... mikroC - 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(&PORTD, 0); Man_Send_Init Prototype void Man_Receive_Init(char *port); Description The function prepares PIC for sending signal.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 read files from the root directory only; - Library functions populate both FAT1 and FAT2 tables when writing to files, but the file data is being read from the FAT1 table only; i.e. there is no recovery if T1 table is corrupted.
mikroC making it simple... mikroC - C 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 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 Mmc_Init.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Mmc_Fat_Init Prototype unsigned short Mmc_Fat_Init(unsigned short *port, unsigned short pin); Returns Returns 0 if 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 Mmc_Fat_Read. Requires File pointer must be initialized; see Mmc_Fat_Reset.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Library Example The following program tests MMC FAT routines. It creates 5 different files in the root of MMC card, and fills them with some data. You can check the file dates which should be different.
mikroC making it simple...
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers OneWire Library OneWire library provides routines for communication via OneWire bus, for example with DS1820 digital thermometer. This is a Master/Slave protocol, 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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 DS1820. Parameters port and pin specify the location of DS1820. Requires Works with Dallas DS1820 temperature sensor only.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Library Example unsigned temp; unsigned short j; void Display_Temperature(unsigned int temp) { //...
mikroC making it simple...
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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, punctuation marks, and space, value will store the appropriate ASCII value.
mikroC making it simple... 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... PWM Library CCP module is available with a number of PICmicros. mikroC provides library which simplifies using PWM HW Module. Note: These 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Pwm_Change_Duty 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_Init.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers RS-485 Library RS-485 is a multipoint communication which allows multiple devices to be connected 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 packets containing synchronization bytes, CRC byte, address byte, and the data.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 USART_Init. Example RS485Master_Init(); RS485Master_Receive Prototype void RS485Master_Receive(char *data); Description Receives any message sent by Slaves.
mikroC making it simple... mikroC - 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 <= datalen <= 3). Requires MCU must be initialized as Master in RS-485 communication in order to be assigned an address. See RS485Master_Init.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 received (see the example at the end of the chapter). Upon receiving a message, buffer is filled with the following values: data[0..
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Library Example The example demonstrates working with PIC as Slave nod in RS-485 communication. 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.
mikroC making it simple...
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 library for accessing data on SD Card via SPI communication. Note: Secure Digital Library works only with PIC18 family.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 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 Sd_Init.
mikroC making it simple... mikroC - 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 Sd_Init.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Software I2C Library mikroC provides routines which implement software I²C. These routines are hardware 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 disabled when using Soft I²C.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 I²C 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 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_I2C_Stop Prototype void Soft_I2C_Stop(void); Description Issues STOP signal.
mikroC making it simple... 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Software SPI Library mikroC provides library which implement software SPI. These routines are hardware 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.
mikroC making it simple... mikroC - 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 DAC module is 5 V.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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 communicate with other devices via RS232 protocol – simply use the functions listed below. Note: This library implements time-based activities, so interrupts need to be disabled when using Soft UART.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Soft_Uart_Read Prototype unsigned short Soft_Uart_Read(unsigned short *error); Returns Returns a received 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).
mikroC making it simple... mikroC - 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 communication, menu choice Tools > Terminal.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 designated 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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).
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 converters, D/A converters, MAX7219, LTC1290, etc. You need PIC MCU with hardware integrated SPI (for example, PIC16F877).
mikroC making it simple... mikroC - 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 or SPI_Init needs to be called before using other functions of SPI Library.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 established before using this function. See Spi_Init_Advanced or Spi_Init. Example short take, buffer; ...
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Library Example The code demonstrates how to use SPI library functions. Assumed HW configuration is: max7219 (chip select pin) connected to RC1, and SDO, SDI, SCK pins are connected to corresponding pins of max7219. //------------------- Function Declarations void max7219_init1(); //-------------------------------- F.D.
DIG5 DIG1 LOAD SEGA CLK DOUT SEGD SEGDP SEGE SEGC V+ ISET SEGG SEGB SEGF 10K +5V +5V Vdd Vss RE1/WR/AN6 RD6/PSP6 RD5/PSP5 RD4/PSP4 Vss OSC1 OSC2 RD2/PSP2 RD1/PSP1 RC4 RC3 RD3/PSP3 RC5 RC2/CCP1 RD0/PSP0 RC6/TX/CK RC1/T1OSI RCO/T1OSO RC7/RX/DT RD7/PSP7 Vdd RE2/CS/AN7 RB0/INT RB2 RB1 RB4 RB3/PGM RB5 RE0/RD/AN5 RA5/AN4 RA4/TOCKI RA2/AN2/VrefRA3/AN3/Vref+ RA1/AN1 MCLR/Vpp/THV RB7/PGD RA0/AN0 RB6/PGC PIC16F877A e f f d d g K K a a 8 e g c dp c b b dp 8. 8. 8. 8.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 initialized and communication established before using this function. See Usart_Init. Example int receive; ...
mikroC making it simple... mikroC - 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Hardware Connection PIC16F877A +5V +5V + 4.7uF C1+ V+ C1C2+ C2VT2out 4.7uF R2in Vcc GN D T1out R1in R1out T1in T2in R2out RA0/AN0 RB6/PGC RA1/AN1 RB5 RA2/AN2/VrefRA3/AN3/Vref+ RA4/TOCKI RA5/AN4 Reset + + 1 6 2 7 3 8 4 9 5 4.7uF SUB-D 9-pin connector + 4.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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 number of characters received in Read Buffer. Requires USB HID needs to be enabled before using this function. See Hid_Enable.
mikroC making it simple... 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... // Timer 0 T0CON = 0x07; TMR0H = (65536-156) >> 8; TMR0L = (65536-156) & 0xFF; // Enable T0IE INTCON.T0IE = 1; T0CON.
mikroC making it simple...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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 (debouncing).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers ANSI C Ctype Library mikroC provides a set of standard ANSI C library functions for testing and mapping 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... asin Prototype double asin(double x); Description Function returns the arc sine of 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 pi/2 (inclusive). atan Prototype double atan(double x); Description Function computes the arc tangent of parameter x; that is, the value whose tangent is x.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers log10 Prototype double log10(double x); Description Function returns the base-10 logarithm of x (i.e. log10(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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... sinh Prototype double sinh(double x); Description Function returns the hyperbolic sine of x, defined mathematically as (ex-e-x)/2. If the value of x is too large (if overflow occurs), the function fails. sqrt Prototype double sqrt(double 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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 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).
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers ldiv Prototype ldiv_t ldiv(long numer, long denom); Description Function is similar to the div function, except that the arguments and the result structure members all have type 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).
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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 numbers to be returned by subsequent calls to rand().
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers ANSI C String Library mikroC provides a set of standard ANSI C library functions useful for manipulating 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... memcmp Prototype void *memcpy(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. 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.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... strncat Prototype char *strncat(char *s1, char *s2, int n); Description Function appends not more than n characters from the string s2 to s1. The initial character of s2 overwrites the null character at the end of s1. A terminating null character is always appended to the result. Function returns s1.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers Conversions Library mikroC Conversions Library provides routines for converting numerals to strings, and routines for BCD/decimal conversions.
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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; //...
mikroC making it simple... mikroC - C Compiler for Microchip PIC microcontrollers 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 (if any) are filled with blanks. Example long jj = -3700000; char *txt; //...
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... 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; ... 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; .
mikroC making it simple... mikroC - C Compiler for Microchip PIC 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.
mikroC mikroC - C Compiler for Microchip PIC microcontrollers making it simple... Contact us: If you are experiencing problems with any of our products or you just want additional information, please let us know. Technical Support for compiler If you are experiencing any trouble with mikroC, please do not hesitate to contact us - it is in our mutual interest to solve these issues. Discount for schools and universities mikroElektronika offers a special discount for educational institutions.