MikroC Users Guide
MikroC Users Guide
mikroCmaking it simple...
Highly sophisticated IDE provides the power you need with the
simplicity of a Windows based point-and-click environment.
Reader’s note
DISCLAIMER:
mikroC and this manual are owned by mikroElektronika and are protected by copyright law
and international copyright treaty. Therefore, you should treat this manual like any other copy-
righted material (e.g., a book). The manual and the compiler may not be copied, partially or
as a whole without the written consent from the mikroEelktronika. The PDF-edition of the
manual can be printed for private or local use, but not for distribution. Modifying the manual
or the compiler is strictly prohibited.
LICENSE AGREEMENT:
By using the mikroC compiler, you agree to the terms of this agreement. Only one person
may use licensed version of mikroC compiler at a time.
Copyright © MikroElektronika 2003 - 2005.
This manual covers mikroC version 1.01 and the related topics. New versions may contain
changes without prior notice.
CONTACT US:
mikroElektronika
Voice: + 381 (11) 30 66 377, + 381 (11) 30 66 378
Fax: + 381 (11) 30 66 379
Web: www.mikroelektronika.co.yu
E-mail: office@mikroelektronika.co.yu
page
ii
MikroElektronika: Development tools - Books - Compilers
mikroC User’s manual
Table of Contents
Quick Overview 1
Code Editor 3
Code Explorer 6
Debugger 7
Error Window 9
Statistics 10
Integrated Tools 13
Keyboard Shortcuts 15
Projects 18
Source Files 19
Search Paths 19
Managing Source Files 20
Compilation 22
Output Files 22
Assembly View 22
Error Messages 23
mikroC Specifics 26
ANSI Standard Issues 26
Predefined Globals and Constants 27
Accessing Individual Bits 27
Interrupts 28
Linker Directives 29
Lexical Elements 30
Tokens 32
Constants 33
Integer Constants 33
Floating Point Constants 35
Character Constants 36
String Constants 38
Enumeration Constants 39
Pointer Constants 39
Constant Expressions 39
Keywords 40
Identifiers 41
page
iv
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Punctuators 42
Objects and Lvalues 46
Scope and Visibility 48
Name Spaces 50
Duration 51
Types 53
Fundamental Types 54
Arithmetic Types 54
Enumeration Types 56
Void Type 58
Derived Types 59
Arrays 59
Pointers 62
Pointer Arithmetic 64
Structures 68
Unions 73
Bit Fields 74
Types Conversions 76
Standard Conversions 76
Explicit Typecasting 78
Declarations 79
Linkage 81
Storage Classes 83
Type Qualifiers 85
Typedef Specifier 86
asm Declaration 87
Initialization 88
Functions 89
Function Declaration 89
Function Prototypes 90
Function Definition 91
Function Calls 92
Operators 94
Precedence and Associativity 94
Arithmetic Operators 96
Relational Operators 98
Bitwise Operators 99
Logical Operators 101
Conditional Operator ? : 103
Assignment Operators 104
sizeof Operator 106
page
v
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Expressions 107
Comma Expressions 107
Statements 109
Labeled Statements 109
Expression Statements 110
Selection Statements 110
Iteration Statements 113
Jump Statements 116
Compound Statements (Blocks) 118
Preprocessor 119
Preprocessor Directives 119
Macros 120
File Inclusion 124
Preprocessor Operators 125
Conditional Compilation 126
page
vi
MikroElektronika: Development tools - Books - Compilers
CHAPTER
1
mikroC IDE
QUICK OVERVIEW
PIC and C fit well together: 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 a natural
choice for developing microcontroller applications. mikroC provides a successful
match featuring highly advanced IDE, ANSI compliant compiler, broad set of
hardware libraries, comprehensive documentation, and plenty of ready to run
example programs.
Watch
Window
Code
Explorer
Code
Editor
Error
Window
Code Call Stack
Assistant Window
Write your C source code using the built-in Code Editor (Code and Parameter
Assistants, Syntax Highlighting, Auto Correct, Code Templates, and more…)
Use the included mikroC libraries to dramatically speed up the development: data
acquisition, memory, displays, conversions, communications…
Inspect program flow and debug executable logic with integrated Debugger.
Get detailed reports and graphs on code statistics, assembly listing, calling tree…
We have provided plenty of examples for you to expand, develop, and use as build-
ing bricks in your projects.
page
2
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
CODE EDITOR
Code Editor is 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.
You can customize these options from Editor Settings dialog. To access the set-
tings, click Tools > Options from drop-down menu, or click the Tools icon.
Tools Icon.
page
3
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
If you type first few letter of a word and then press CTRL+SPACE, all valid iden-
tifiers matching the letters you typed will be prompted to you 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 keyboard arrows and Enter.
You can insert Code Template by typing the name of the template (for instance,
whileb), then press CTRL+J, and Editor will automatically generate code. Or you
can click button from Code toolbar and select template from the list.
You can add your own templates to the list. Just select Tools > Options from drop-
down menu, or click Tools Icon from Settings Toolbar, and then select Auto
Complete Tab. Here you can enter the appropriate keyword, description, and code
of your template.
page
4
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Auto Correct
Auto Correct corrects common typing mistakes. To access the list of recognized
typos, select Tools > Options from drop-down menu, or click Tools Icon from
Settings Toolbar, and then select Auto Correct Tab. You can also add your own
preferences to the list.
Comment/Uncomment
Comment / Code Editor allows you to comment or uncomment selected block of code by a
Uncomment Icon.
simple click of a mouse, using the Comment/Uncomment icons from the Code
Toolbar.
Bookmarks
Goto Line
Goto Line option makes navigation through large code easier. Select Search >
Goto Line from drop-down menu, or use the shortcut CTRL+G.
page
5
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CODE EXPLORER
Code Explorer is placed to the left of the main window by default, and gives clear
view of every declared item in the source code. You can jump to declaration of
Find Declaration any item by right clicking it, or by clicking the Find Declaration icon. To expand
Icon. or collapse treeview in Code Explorer, use the Collapse/Expand All icon.
Also, two more tab windows are available in Code Explorer. QHelp Tab lists all
the available built-in and library functions, for a quick reference. Double-clicking
Collapse/Expand a routine in QHelp Tab opens the relevant Help topic. Keyboard Tab lists all avail-
All Icon. able keyboard shortcuts in mikroC.
page
6
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
DEBUGGER
Source-level Debugger is an integral component of mikroC development environ-
ment. It is designed to simulate operations of Microchip Technology's PICmicros
and to assist users in debugging software written for these devices.
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.
Debug Icon.
After you have successfully compiled your project, you can run Debugger by
selecting Run > Debug from drop-down menu, or by clicking Debug Icon .
Starting the Debugger makes more options available: Step Into, Step Over, Run to
Cursor etc. Line that is to be executed is color highlighted.
Debug [F9]
Starts Debugger.
page
7
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Watch Window
Watch Window allows you to monitor program items while running your program.
It displays variables and special function registers of PIC MCU, their addresses
and values. Values are updated as you go through the simulation. See the image
below.
Double clicking one of the items opens a window in which you can assign new
value to the selected variable or register and change number formatting.
page
8
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
ERROR WINDOW
In case that errors were encountered during compiling, compiler will report them
and won't generate a hex file. Error Window will be prompted at the bottom of the
main window.
Error Window is located under message tab, and displays location and type of
errors compiler has encountered. Compiler also reports warnings, but these do not
affect generating hex code. Only errors can interefere with generation of hex.
Double click the message line in Error Window to highlight the line where the
error was encountered.
Consult the Error Messages for more information about errors recognized by the
compiler.
page
9
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
STATISTICS
After successful compilation, you can review statistics of your code. Select Project
> View Statistics from drop-down menu, or click the Statistics icon. There are five
Statistics Icon. tab windows:
page
10
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
size, start and end address, calling frequency, return type, etc.
page
11
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
RAM Window
Summarizes all GPR and SFR registers and their addresses. Also displays symbol-
ic names of variables and their addresses.
ROM Window
Lists op-codes and their addresses in form of a human readable hex code.
page
12
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
INTEGRATED TOOLS
USART Terminal
mikroC includes USART (Universal Synchronous Asynchronous Receiver
Transmitter) communication terminal for RS232 communication. You can launch
it from drop-down menu Tools > Terminal or by clicking the Terminal icon.
ASCII Chart
ASCII Chart is a handy tool, particularly useful when working with LCD display.
You can launch it from drop-down menu Tools > ASCII chart.
page
13
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
EEPROM Editor
EEPROM Editor allows you to easily manage EEPROM of PIC microcontroller.
page
14
MikroElektronika: Development tools - Books - Compilers
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.
IDE Shortcuts
F1 Help
CTRL+N New Unit
CTRL+O Open
CTRL+F9 Compile
CTRL+F11 Code Explorer on/off
CTRL+SHIFT+F5 View breakpoints
page
15
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Debugger Shortcuts
F4 Run to Cursor
F5 Toggle breakpoint
F6 Run/Pause Debugger
F7 Step into
F8 Step over
F9 Debug
CTRL+F2 Reset
page
16
MikroElektronika: Development tools - Books - Compilers
CHAPTER
2
Building
Applications
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 does not include files in same fashion as preprocessor does. Each source
file in the project must be self-contained, i.e. it must have all the necessary defini-
tions after preprocessing.
New Project
The easiest way to create project is by means of New Project Wizard, drop-down
menu Project > New Project. Just fill the dialog with desired values (project name
and description, location, device, clock, config word) and mikroC will create the
appropriate project file.
Also, an empty source file named after the project will be created by default.
mikroC does not require you to have source file named same as the project, it’s
just a matter of convenience.
Editing Project
Later, you can change project settings from drop-down menu Project > Edit. You
can add or remove source files from project, rename the project, modify its
description, change chip, clock, config word, etc.
To delete a project, simply delete the folder in which the project file is stored.
page
18
MikroElektronika: Development tools - Books - Compilers
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.
Note that project does not include files in same fashion as preprocessor does. Each
source file in the project must be self-contained, i.e. it must have all the necessary
definitions after preprocessing.
Search Paths
You can specify your own custom search paths. This can be configured by select-
ing Options > Settings from drop-down menu and then tab window Advanced.
In project settings, you can specify either absolute or relative path to the source
file. If you specify a relative path, mikroC will look for the file in following loca-
tions, in this particular order:
1. the project folder (folder which contains the project file .ppc),
2. your custom search paths,
3. mikroC installation folder > “uses” folder.
page
19
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
If #include directive was used with the <header_name> version, the search is
made successively in each of the following locations, in this particular order:
1. the project folder (folder which contains the project file .ppc),
2. mikroC installation folder > “include” folder,
3. your custom search paths.
Select File > New from drop-down menu, or press CTRL+N, or click the New
File icon. A new tab will open, named “Untitled1”. This is your new source file.
Select File > Save As from drop-down menu to name it the way you want.
If you have used New Project Wizard, an empty source file, named after the proj-
ect with extension .c, is created automatically. mikroC does not require you to
have source file named same as the project, it’s just a matter of convenience.
page
20
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Select File > Open from drop-down menu, or press CTRL+O, or click the Open
Open File Icon.
File icon. The Select Input File dialog opens. In the dialog, browse to the location
of the file you want to open and select it. Click the Open button.
The selected file is displayed in its own tab. If the selected file is already open, its
current Editor tab will become active.
Saving File
Make sure that window containing the file you want to save is the active window.
Select File > Save As from drop-down menu, or press SHIFT+CTRL+S. The New
File Name dialog will be displayed. In the dialog, browse to the folder where you
want to save the file. In the File Name field, modify the name of the file you want
to save. Click the Save button.
Closing a File
Make sure that tab containing the file you want to close is the active tab. Select
File > Close from drop-down menu, or right click the tab of the file you want to
close in Code Editor. If the file has been changed since it was last saved, you will
be prompted to save your changes.
page
21
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
COMPILATION
When you have created the project and written the source code, you will want to
compile it. Select Run > Compile from drop-down menu, or click Compile Icon,
Compile 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.
Output Files
Upon successful compilation, mikroC will generate output files in the project fold-
er (folder which contains the project file .ppc). Output files are summarized
below:
Assembly View
After compiling your program in mikroC, you can click View Assembly Icon or
select Project › View Assembly from drop-down menu to review generated assem-
View Assembly bly code (.asm file) in a new tab window. Assembly is human readable with sym-
Icon. bolic names. All physical addresses and other information can be found in
Statistics or in list file (.lst).
If the program is not compiled and there is no assembly file, starting this option
will compile your code and then display assembly.
page
22
MikroElektronika: Development tools - Books - Compilers
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. must evaluate to integral type
- continue outside of loop
- break outside of loop or switch
- void func cannot return values
- Unreachable code
- Illegal expression with void
- Left operand must be pointer
- Function required
- Too many chars
- Undefined struct
- Nonexistent field
- Aggregate init error
- Incompatible types
- Identifier redefined
- Function definition not found
- Signature does not match
- Cannot generate code for expression
- Too many initializers of subaggregate
- Nonexistent subaggregate
- Stack Overflow: func call in complex expression
- Syntax Error: expected %s but %s found
- Array element cannot be function
- Function cannot return array
page
23
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
page
24
MikroElektronika: Development tools - Books - Compilers
CHAPTER
3
mikroC Reference
mikroC SPECIFICS
ANSI Standard Issues
mikroC diverges from the ANSI C standard in few areas. Some of these modifica-
tions are improvements intenteded to facilitate PIC programming, while others are
result of PICmicro hardware limitations:
Function cross-calling and recursion are unsupported due to the PIC’s limitations
of no easily-usable stack and limited memory.
Pointers to variables and pointers to constants are not compatible, i.e. no assigning
or comparison is possible between the two.
mikroC treats identifiers declared with const qualifier as “true constants” (C++
style). This allows using const objects in places where ANSI C would expect a
constant expression. Also, const declarations have internal linkage. If aiming at
portability, stick to the old-school preprocessor defined constants.
Tags scope is specific. Due to separate name space, tags are virtually removed
from normal scope rules: they have file scope, but override any block rules.
mikroC allows C++ style single–line comments using two adjacent slashes (//).
Implementation-defined Behavior
page
26
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
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 .def file, con-
taining declarations of available SFR and constants (such as T0IE, INTF, etc).
Identifiers are all in uppercase, identical to nomenclature in Microchip datasheets.
For the complete set of predefined globals and constants, look for “Defs” in your
mikroC installation folder, or probe the Code Assistant for specific letters
(CTRL+SPACE in Editor).
mikroC allows you to access individual bits of 8-bit variables, types char and
unsigned short. Simply use the direct member selector (.) with a variable,
followed by one of identifiers F0, F1, … , F7, with F7 being the most significant
bit.
For example:
There is no need for any special declarations; this kind of selective access is an
intrinsic feature of mikroC and can be used anywhere in the code. Identifiers
F0–F7 are not case sensitive and have a specific namespace. You may override
these with your own members F0–F7 within any given structure.
Note: If aiming at portability, avoid this style of accessing individual bits, and use
the bit fields instead.
page
27
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Interrupts
void interrupt(void);
Write your own definition (function body) to handle interrupts in your application.
Please note that you cannot call functions from within interrupt due to stack limi-
tations, and that mikroC does not support low priority interrupts -- for PIC18 fami-
ly, interrupts must be of high priority.
mikroC saves the following SFR on stack when entering interrupt and pops them
back upon return:
Here is a simple example of handling the interrupts from TMR0 (if no other
interrupts are allowed):
void interrupt() {
counter++;
TMR0 = 96;
INTCON = $20;
}
page
28
MikroElektronika: Development tools - Books - Compilers
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. Directive absolute is
appended to the declaration of variable:
Be careful when using absolute directive, as you may overlap two variables by
mistake. For example:
Directive org
page
29
MikroElektronika: Development tools - Books - Compilers
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 lan-
guage.
In the tokenizing phase of compilation, the source code file is parsed (that is, bro-
ken down) into tokens and whitespace. The tokens in mikroC are derived from a
series of operations performed on your programs by the compiler and its built-in
preprocessor.
Whitespace
Whitespace is the collective name given to spaces (blanks), horizontal and vertical
tabs, newline characters, and comments. Whitespace can serve to indicate where
tokens start and end, but beyond this function, any surplus whitespace is discard-
ed. For example, the two sequences
int i; float f;
and
int i;
float f;
are lexically equivalent and parse identically to give the six tokens.
The ASCII characters representing whitespace can occur within literal strings, in
which case they are protected from the normal parsing process (they remain as
part of the string).
page
30
MikroElektronika: Development tools - Books - Compilers
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 /*. The
comment terminates at the first occurrence of the pair */ following the initial /*.
The entire sequence, including the four comment-delimiter symbols, is replaced by
one space after macro expansion.
In mikroC,
parses as:
int i;
Note that mikroC does not support the nonportable token pasting strategy using
/**/. For more on token pasting, refer to Preprocessor topics.
C++ comments
mikroC allows single-line comments using two adjacent slashes (//). The com-
ment can start in any position, and extends until the next new line. The following
code,
parses as:
int i;
int j;
page
31
MikroElektronika: Development tools - Books - Compilers
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.
- keywords,
- identifiers,
- constants,
- operators,
- punctuators (also known as separators).
Here is an example of token extraction. Let’s have the following code sequence:
inter = a+++b;
First, note that inter would be parsed as a single identifier, rather than as the key-
word int followed by the identifier er.
The programmer who wrote the code might have intended to write inter = a
+ (++b), but it won’t work that way. The compiler would parse it as the follow-
ing seven tokens:
inter // identifier
= // assignment operator
a // identifier
++ // postincrement operator
+ // addition operator
b // identifier
; // semicolon separator
page
32
MikroElektronika: Development tools - Books - Compilers
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 numer-
ic value and the format used in the source code.
Integer Constants
Integer constants can be decimal (base 10), hexadecimal (base 16), binary (base
2), or octal (base 8). In the absence of any overriding suffixes, the data type of an
integer constant is derived from its value.
The suffix L (or l) attached to any constant forces the constant to be represented
as a long. Similarly, the suffix U (or u) forces the constant to be unsigned.
You can use both L and U suffixes on the same constant in any order or case: ul,
Lu, UL, etc.
In the absence of any suffix (U, u, L, or l), constant is assigned the “smallest” of
the following types that can accommodate its value: short, unsigned short,
int, unsigned int, long int, unsigned long int.
page
33
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Otherwise:
If the constant has a U or u suffix, its data type will be the first of the following
that can accommodate its value: unsigned short, unsigned int,
unsigned long int.
If the constant has an L or l suffix, its data type will be the first of the following
that can accommodate its value: long int, unsigned long int.
If the constant has both U and L suffixes, (ul, lu, Ul, lU, uL, Lu, LU, or UL), its
data type will be unsigned long int.
Decimal Constants
In the absence of any overriding suffixes, the data type of a decimal constant is
derived from its value, as shown below:
Hexadecimal Constants
All constants starting with 0x (or 0X) are taken to be hexadecimal. In the absence
of any overriding suffixes, the data type of an hexadecimal constant is derived
from its value, according to the rules presented above. For example, 0xC367 will
be treated as unsigned int.
page
34
MikroElektronika: Development tools - Books - Compilers
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. In the absence of any overriding suf-
fixes, the data type of an octal constant is derived from its value, according to the
rules presented above. For example, 0777 will be treated as int.
- Decimal integer,
- Decimal point,
- Decimal fraction,
- e or E and a signed integer exponent (optional),
- Type suffix: f or F or l or L (optional).
You can omit either the decimal integer or the decimal fraction (but not both). You
can omit either the decimal point or the letter e (or E) and the signed integer expo-
nent (but not both). These rules allow for conventional and scientific (exponent)
notations.
Negative floating constants are taken as positive constants with the unary operator
minus (-) prefixed.
mikroC floating-point constants are of type double. Note that mikroC’s implemen-
tation of ANSI Standard considers float and double (together with the long
double variant) to be the same type.
page
35
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Character Constants
Escape Sequences
The backslash character (\) is used to introduce an escape sequence, which allows
the visual representation of certain nongraphic characters. One of the most com-
mon escape constants is the newline character (\n).
For example, the octal number \777 is larger than the maximum value allowed
(\377) and will generate an error. The first nonoctal or nonhexadecimal character
encountered in an octal or hexadecimal escape sequence marks the end of the
sequence.
Note: You must use \\ to represent an ASCII backslash, as used in operating sys-
tem paths.
page
36
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
\b 0x08 BS Backspace
\f 0x0C FF Formfeed
\\ 0x5C \ Backslash
Single quote
\' 0x27 '
(Apostrophe)
O = string of up to 3
\O any
octal digits
H = string of hex dig-
\xH any
its
H = string of hex dig-
\XH any
its
page
37
MikroElektronika: Development tools - Books - Compilers
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 of data type “array
of const char” and storage class static, written as 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 inter-
nally as the given sequence of characters plus a final null character ('\0'). A null
string is stored as a single '\0' character.
The characters inside the double quotes can include escape sequences, e.g.
"\t\"Name\"\\\tAddress\n\n"
Adjacent string literals separated only by whitespace are concatenated during the
parsing phase. For example:
is an equivalent to
You can also use the backslash (\) as a continuation character to extend a string
constant across line boundaries:
"This is really \
a one-line string."
page
38
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Enumeration Constants
Enumeration constants are identifiers defined in enum type declarations. The iden-
tifiers are usually chosen as mnemonics to assist legibility. Enumeration constants
are of int type. They can be used in any expression where integer constants are
valid.
For example:
The identifiers (enumerators) used must be unique within the scope of the enum
declaration. Negative initializers are allowed. See Enumerations for details of
enum declarations.
Pointer Constants
A pointer or the pointed-at object can be declared with the const modifier.
Anything declared as a const cannot be have its value changed. It is also illegal
to create a pointer that might violate the nonassignability of a constant object.
Constant Expressions
Constant expressions can consist only of the following: literals, enumeration con-
stants, simple constants (no constant arrays or structures), sizeof operators.
Constant expressions cannot contain any of the following operators, unless the
operators are contained within the operand of a sizeof operator: assignment,
comma, decrement, function call, increment.
page
39
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
KEYWORDS
Keywords are words reserved for special purposes and must not be used as normal
identifier names.
Beside standard C keywords, all relevant SFR are defined as global variables and
represent reserved words that cannot be redefined (for example: TMR0, PCL, etc).
Probe the Code Assistant for specific letters (CTRL+SPACE in Editor) or refer to
Predefined Globals and Constants.
page
40
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
IDENTIFIERS
Identifiers are arbitrary names of any length given to functions, variables, symbol-
ic constants, user-defined data types, and labels. All these program elements will
be referred to as objects throughout the help (not to be confused with the meaning
of object in object-oriented programming).
Identifiers can contain the letters a to z and A to Z, the underscore character '_',
and the digits 0 to 9. The only restriction is that the first character must be a letter
or an underscore.
Case Sensitivity
mikroC identifiers are not case sensitive at present, so that Sum, sum, and suM
represent an equivalent identifier. However, next versions of mikroC will offer the
option of activating/suspending case sensitivity.
Although identifier names are arbitrary (within the rules stated), errors result if the
same name is used for more than one identifier within the same scope and sharing
the same name space. Duplicate names are legal for different name spaces regard-
less of scope rules. For more information on scope, refer to Scope and Visibility.
page
41
MikroElektronika: Development tools - Books - Compilers
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.
Brackets
Parentheses
page
42
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Braces
if (d == z) {
++x;
func();
}
The closing brace serves as a terminator for the compound statement, so a semi-
colon is not required after the }, except in structure declarations. Often, the semi-
colon is illegal, as in
if (statement)
{ ... }; /* illegal semicolon! */
else
{ ... };
Comma
The comma is also used as an operator in comma expressions. Mixing the two
uses of comma is legal, but you must use parentheses to distinguish them. Note
that (exp1, exp2) evalutates both but is equal to the second:
page
43
MikroElektronika: Development tools - Books - Compilers
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.
Colon
start: x = 0;
...
goto start;
You can also use the asterisk as an operator to either dereference a pointer or as
the multiplication operator:
i = *char_ptr;
page
44
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Equal Sign
The equal sign (=) separates variable declarations from initialization lists:
int a, b, c;
a = b + c;
The pound sign (#) indicates a preprocessor directive when it occurs as the first
nonwhitespace character on a line. It signifies a compiler action, not necessarily
associated with code generation. See Preprocessor Directives for more informa-
tion.
# and ## are also used as operators to perform token replacement and merging
during the preprocessor scanning phase. See Preprocessor Operators.
page
45
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
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.
Each value has an associated name and type (also known as a data type). The
name is used to access the object. This name can be a simple identifier, or it can
be a complex expression that uniquely references the object.
Associating identifiers with objects requires each identifier to have at least two
attributes: storage class and type (sometimes referred to as data type). The mikroC
compiler deduces these attributes from implicit or explicit declarations in the
source code. Commonly, only the type is explicitly specified and the storage class
specifier assumes automatic value auto.
variables; functions; types; arrays of other types; structure, union, and enumeration
tags; structure members; union members; enumeration constants; statement labels;
preprocessor macros.
The recursive nature of the declarator syntax allows complex declarators. You’ll
probably want to use typedefs to improve legibility if constructing complex
objects.
page
46
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Lvalues
Historically, the l stood for “left”, meaning that an lvalue could legally stand on
the left (the receiving end) of an assignment statement. Now only modifiable lval-
ues can legally stand to the left of an assignment operator. For example, if a and b
are nonconstant integer identifiers with properly allocated memory storage, they
are both modifiable lvalues, and assignments such as a = 1 and b = a + b
are legal.
Rvalues
page
47
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
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.
Block Scope
The scope of an identifier with block (or local) scope starts at the declaration point
and ends at the end of the block containing the declaration (such a block is known
as the enclosing block). Parameter declarations with a function definition also
have block scope, limited to the scope of the function body.
File Scope
File scope identifiers, also known as globals, are declared outside of all blocks;
their scope is from the point of declaration to the end of the source file.
Function Scope
The only identifiers having function scope are statement labels. Label names can
be used with goto statements anywhere in the function in which the label is
declared. Labels are declared implicitly by writing label_name: followed by a
statement. Label names must be unique within a function.
Tag Scope
Structure, union, and enumeration tags are somewhat specific in mikroC. Due to
separate name space, tags are virtually removed from normal scope rules: they
have file scope, but override any block rules. Thus, deeply nested declaration of
structure is identical to an equivalent global declaration. As a consequence, once
that you have defined a tag, you cannot redefine it in any block within file.
page
48
MikroElektronika: Development tools - Books - Compilers
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.
Scope and visibility usually coincide, though there are circumstances under which
an object becomes temporarily hidden by the appearance of a duplicate identifier:
the object still exists but the original identifier cannot be used to access it until the
scope of the duplicate identifier is ended.
Technically, visibility cannot exceed scope, but scope can exceed visibility. Take a
look at the following example:
void f (int i) {
int j; // auto by default
j = 3; // int i and j are in scope and visible
{ // nested block
double j; // j is local name in the nested block
j = 0.1; // i and double j are visible;
// int j = 3 in scope but hidden
}
// double j out of scope
j += 1; // int j visible and = 4
}
// i and j are both out of scope
page
49
MikroElektronika: Development tools - Books - Compilers
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:
Duplicate names are legal for different name spaces regardless of scope rules.
For example:
{ // open a block
enum colors { black, red, green, blue, violet, white } c;
/* enumerator blue hides outer declaration of int blue */
double red = 2;
// ILLEGAL: redefinition of red
}
page
50
MikroElektronika: Development tools - Books - Compilers
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 dis-
tinguish between compile-time and run-time objects. Variables, for instance, unlike
typedefs and types, have real memory allocated during run time. There are two
kinds of duration: static and local.
Static Duration
In mikroC, static duration objects are not initialized to zero (or null) in the absence
of any explicit initializer.
An object can have static duration and local scope – see the example on the fol-
lowing page.
Local Duration
Local duration objects are also known as automatic objects. They are created on
the stack (or in a register) when the enclosing block or function is entered. They
are deallocated when the program exits that block or function. Local duration
objects must be explicitly initialized; otherwise, their contents are unpredictable.
The storage class specifier auto can be used when declaring local duration vari-
ables, but is usually redundant, because auto is the default for variables declared
within a block.
An object with local duration also has local scope, because it does not exist out-
side of its enclosing block. The converse is not true: a local scope object can have
static duration.
page
51
MikroElektronika: Development tools - Books - Compilers
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;
/* checkpoint! */
a++;
b++;
}
void main() {
/* At checkpoint, we will have: */
f(); // a=1, b=1, after first call,
f(); // a=1, b=2, after second call,
f(); // a=1, b=3, after third call,
// etc.
}
page
52
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
TYPES
C is strictly typed language, which means that every object, function, and expres-
sion need to have a strictly defined type, known in the time of compilation. Note
that C works exclusively with numeric types.
mikroC supports many standard (predefined) and user-defined data types, includ-
ing signed and unsigned integers in various sizes, floating-point numbers in vari-
ous precisions, arrays, structures, and unions. In addition, pointers to most of these
objects can be established and manipulated in memory.
The type determines how much memory is allocated to an object and how the pro-
gram will interpret the bit patterns found in the object’s storage allocation. A given
data type can be viewed as a set of values (often implementation-dependent) that
identifiers of that type can assume, together with a set of operations allowed on
those values. The compile-time operator, sizeof, lets you determine the size in
bytes of any standard or user-defined type.
The mikroC standard libraries and your own program and header files must pro-
vide unambiguous identifiers (or expressions derived from them) and types so that
mikroC can consistently access, interpret, and (possibly) change the bit patterns in
memory corresponding to each active object in your program.
Type Categories
The fudamental types represent types that cannot be separated into smaller parts.
They are sometimes referred to as unstructured types. The fundamental types are
void, char, int, float, and double, together with short, long, signed,
and unsigned variants of some of these.
The derived types are also known as structured types. The derived types include
pointers to other types, arrays of other types, function types, structures, and
unions.
page
53
MikroElektronika: Development tools - Books - Compilers
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. Variants are created by using one of the prefix modifiers short, long,
signed, and unsigned.
The table below is the overview of the integral types – keywords in parentheses
can be (and often are) omitted.
The modifiers signed and unsigned can be applied to both char and int. In
the absence of unsigned prefix, signed is automatically assumed for integral types.
The only exception is the char, which is unsigned by default. The keywords
signed and unsigned, when used on their own, mean signed int and
unsigned int, respectively.
The modifiers short and long can be applied only to the int. The keywords
short and long used on their own mean short int and long int, respective-
ly.
Floating-point Types
Types float and double, together with the long double variant, are consid-
ered floating-point types. mikroC’s implementation of ANSI Standard considers all
three to be the same type.
Floating point in mikroC is implemented using the Microchip AN575 32-bit for-
mat (IEEE 754 compliant).
page
54
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
page
55
MikroElektronika: Development tools - Books - Compilers
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 val-
ues with appropriate symbolic names.
Enumeration Declaration
Variables of enum type are declared same as variables of any other type. For
example, the following declaration
establishes a unique integral type, colors, a variable c of this type, and a set of
enumerators with constant integer values (black = 0, red = 1, ...). In C, a
variable of an enumerated type can be assigned any value of type int – no type
checking beyond that is enforced. That is:
c = red; // OK
c = 1; // Also OK, means the same
With explicit integral initializers, you can set one or more enumerators to specific
values. The initializer can be any expression yielding a positive or negative integer
value (after possible integer promotions). Any subsequent names without initializ-
ers will then increase by one. These values are usually unique, but duplicates are
legal.
page
56
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
nibble would acquire the value 4, byte the value 8, and kilobyte the value
8192.
In our previous declaration, the identifier colors is the optional enumeration tag
that can be used in subsequent declarations of enumeration variables of type enum
colors:
As with struct and union declarations, you can omit the tag if no further variables
of this enum type are required:
Enumeration Scope
Enumeration tags share the same name space as structure and union tags.
Enumerators share the same name space as ordinary variable identifiers. For more
information, consult Name Spaces.
page
57
MikroElektronika: Development tools - Books - Compilers
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. For example:
Use void as a function heading if the function does not take any parameters.
Alternatively, you can just write empty parentheses:
Generic Pointers
Pointers can be declared as void, meaning that they can point to any type. These
pointers are sometimes called generic.
page
58
MikroElektronika: Development tools - Books - Compilers
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 ele-
ments in creating more complex user-defined types.
Arrays
Array is the simplest and most commonly used structured type. Variable of array
type is actually an array of objects of the same type. These objects represent ele-
ments of an array and are identified by their position in array. An array consists of
a contiguous region of storage exactly large enough to hold all of its elements.
Array Declaration
Array declaration is similar to variable declaration, with the brackets added after
identifer:
<type> <identifier>[<constant-expression>]
Each of the elements of an array is numbered from 0 through the number of ele-
ments minus one. If the number is n, elements of array can be approached as vari-
ables a[0] .. a[n-1] of <type>.
#define MAX = 50
page
59
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Array Initialization
If you specify both the length and starting values, the number of starting values
must not exceed the specified length. Vice versa is possible, when the trailing
“excess” elements will be assigned some encountered runtime values from memo-
ry.
In case of array of char, you can use a shorter string literal notation. For example:
Arrays in Expressions
When name of the array comes up in expression evaluation (except with operators
& and sizeof ), it is implicitly converted to the pointer pointing to array’s first
element. See Arrays and Pointers for more information.
page
60
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Multi-dimensional Arrays
If you are not initializing the array in the declaration, you can omit the first dimen-
sion of multi-dimensional array. In that case, array is located elsewhere, e.g. in
another file. This is a commonly used technique when passing arrays as function
parameters:
void main() {
int a[4][2][7]++; // 3-dimensional array of size 4x2x7
...
func(a);
}
page
61
MikroElektronika: Development tools - Books - Compilers
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. Since pointers are objects, you can have a pointer pointing to a
pointer (and so on). Other objects commonly pointed at include arrays, structures,
and unions.
Note: Currently, mikroC does not support pointers to functions, but this feature
will be implemented in the following versions.
Pointer Declarations
Pointers are declared same as any other variable, but with * ahead of identifier.
Type at the beginning of declaration specifies the type of a pointed object. A point-
er must be declared as pointing to some particular type, even if that type is void,
which really means a pointer to anything. Pointers to void are often called gener-
ic pointers, and are treated as pointers to char in mikroC.
declares p to be of type “pointer to <type>”. All the scoping, duration, and visi-
bility rules apply to the p object just declared. You can view the declaration in this
way: if *p is object of type <type>, then p has to be a pointer to such objects.
page
62
MikroElektronika: Development tools - Books - Compilers
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.
/* is same as: */
int *pa;
int *pb;
int *pc;
Null Pointers
A null pointer value is an address that is guaranteed to be different from any valid
pointer in use in a program. Assigning the integer constant 0 to a pointer assigns a
null pointer value to it. Instead of zero, the mnemonic NULL (defined in the stan-
dard library header files, such as stdio.h) can be used for legibility. All pointers
can be successfully tested for equality or inequality to NULL.
For example:
/* .. or like this: */
if ( pn == NULL ) { ... }
page
63
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Pointer Arithmetic
Arrays and pointers are not completely independent types in C. When name of the
array comes up in expression evaluation (except with operators & and sizeof ), it
is implicitly converted to the pointer pointing to array’s first element. Due to this
fact, arrays are not modifiable lvalues.
<exp1>[exp2]
is defined as
*((exp1) + (exp2))
where either exp1 is a pointer and exp2 is an integer, or exp1 is an integer and
exp2 is a pointer.
&a[i] = a + i
a[i] = *(a + i)
page
64
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Following examples are also valid, but better avoid this syntax as it can make the
code really illegible:
(a + 1)[i] = 3;
// same as: *((a + 1) + i) = 3, i.e. a[i + 1] = 3
(i + 2)[a] = 0;
// same as: *((i + 2) + a) = 0, i.e. a[i + 2] = 0
You can use a simple assignment operator (=) to assign value of one pointer to
another if they are of the same type. If they are of different types, you must use a
typecast operator. Explicit type conversion is not necessary if one of the pointers is
generic (of void type).
Assigning the integer constant 0 to a pointer assigns a null pointer value to it. The
mnemonic NULL (defined in the standard library header files, such as stdio.h)
can be used for legibility.
Two pointers pointing into the same array may be compared by using relational
operators ==, !=, <, <=, >, and >=. Results of these operations are same as if they
were used on subscript values of array elements in question:
page
65
MikroElektronika: Development tools - Books - Compilers
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:
Pointer Addition
You can use operators +, ++, and += to add an integral value to a pointer. The
result of addition is defined only if pointer points to an element of an array and if
the result is a pointer pointing into the same array (or one element beyond it).
For example:
There is no such element as “one past the last element”, of course, but a pointer is
allowed to assume such a value. C “guarantees” that the result of addition is
defined even when pointing to one element past array. If P points to the last array
element, P+1 is legal, but P+2 is undefined.
page
66
MikroElektronika: Development tools - Books - Compilers
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 indi-
rection operator (*) to a “pointer to one past the last element” leads to undefined
behavior.
For example:
int i;
some_type *p=&a[0];
Pointer Subtraction
Similar to addition, you can use operators -, --, and -= to subtract an integral
value from a pointer.
Also, you may subtract two pointers. Difference will equal the distance between
the two pointed addresses, in bytes.
For example:
int a[10];
int *pi1 = &a[0], *pi2 = &[4];
i = pi2 - pi1; // i equals 8
pi2 -= (i >> 1); // pi2 = pi2 - 4: pi2 now points to a[0]
page
67
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Structures
Unlike arrays, structures are considered single objects. The mikroC structure type
lets you handle complex data structures almost as easily as single variables.
The member type cannot be the same as the struct type being currently declared.
However, a member can be a pointer to the structure being declared, as in the fol-
lowing example:
Also, a structure can contain previously defined structure types when declaring an
instance of a declared structure. Here is an example:
page
68
MikroElektronika: Development tools - Books - Compilers
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.
Incomplete Declarations
struct A; // incomplete
struct B {struct A *pa};
struct A {struct B *pb};
If you omit the structure tag, you get an untagged structure. You can use untagged
structures to declare the identifiers in the comma-delimited struct-id-list to
be of the given structure type (or derived from it), but you cannot declare addition-
al objects of this type elsewhere.
page
69
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Structure Assignment
Note that two variables are of same structured type only if they were both defined
by the same instruction or were defined using the same type identifier. For exam-
ple:
Size of Structure
You can get size of the structure in memory by means of operator sizeof. Size of
the structure does not necessarily need to be equal to the sum of its members’
sizes. It is often greater due to certain limitations of memory storage.
page
70
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Structure and union members are accessed using the following two selection oper-
ators:
. (period)
-> (right arrow)
The operator . is called the direct member selector and it is used to directly access
one of the structure’s members. 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
The operator -> is called the indirect (or pointer) member selector. Suppose that
ps is a pointer to s. Then if m is a member identifier of type M declared in s, the
expression
For example:
struct mystruct {
int i; char str[10]; double d;
} s, *sptr = &s;
.
.
.
s.i = 3; // assign to the i member of mystruct s
sptr -> d = 1.23; // assign to the d member of mystruct s
The expression s.m is an lvalue, provided that s is an lvalue and m is not an array
type. The expression sptr->m is an lvalue unless m is an array type.
page
71
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
struct A {
int j; double x;
};
struct B {
int i; struct A a; double d;
} s, *sptr;
//...
Structure Uniqueness
struct A {
int i,j; double d;
} a, a1;
struct B {
int i,j; double d;
} b;
the objects a and a1 are both of type struct A, but the objects a and b are of differ-
ent structure types. Structures can be assigned only if the source and destination
have the same type:
page
72
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Unions
Union types are derived types sharing many of the syntactic and functional fea-
tures of structure types. The key difference is that a union allows only one of its
members to be “active” at any given time, the most recently changed memeber.
Unions correspond to the variant record types of Pascal programming language.
Union Declaration
Unions are declared same as structures, with the keyword union used instead of
struct:
Unlike structures’ members, the value of only one of union’s members can be
stored at any time. Let’s have a simple example:
The identifier mu, of type union myunion, can be used to hold a 2-byte int, a
4-byte double, or a single-byte char, but only one of these at any given time.
Size of Union
The size of a union is the size of its largest member. In our previous example, both
sizeof(union myunion) and sizeof(mu) return 4, but 2 bytes are unused
(padded) when mu holds an int object, and 3 bytes are unused when mu holds a
char.
Union members can be accessed with the structure member selectors (. and ->),
but care is needed. Check the example on the following page.
page
73
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
mu.d = 4.016;
LCD_Out_CP(FloatToStr(mu.d)); // OK: displays mu.d = 4.016
LCD_Out_CP(IntToStr(mu.i)); // peculiar result
pm->i = 3;
LCD_Out_CP(IntToStr(mu.i)); // OK: displays mu.i = 3
The second LCD_Out_CP is legal, since mu.i is an integral type. However, the bit
pattern in mu.i corresponds to parts of the previously assigned double. As such,
it probably does not provide a useful integer interpretation.
When properly converted, a pointer to a union points to each of its members, and
vice versa.
Bit Fields
Bit fields are specified numbers of bits that may or may not have an associated
identifier. Bit fields offer a way of subdividing structures into named parts of user-
defined sizes.
mikroC implementation of bit fields requires you to set aside a structure for the
purpose, i.e. you cannot have a structure containing bit fields and other objects.
Bit fields structure can contain up to 8 bits.
Note: If you need to handle specific bits of 8-bit variables (char and unsigned
short) or registers, you don’t need to declare bit fields. Much more elegant solu-
tion is to use mikroC’s intrinsic ability for individual bit access — see Accessing
Individual Bits for more information.
Bit fields can be declared only in structures. Declare a structure normally, and
assign individual fields like this (fields need to be unsigned):
page
74
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
As an object, bit fields structure takes one byte. Individual fields are packed with-
in byte from right to left. In bitfield-declarator-list, you can omit identifier(s) to
create artificial “padding”, thus skipping irrelevant bits.
For example, if we need to manipulate only bits 2–4 of a register as one block, we
could create a structure:
struct {
unsigned : 2, // Skip bits 0 and 1, no identifier here
mybits : 3; // Relevant bits 2, 3, and 4
// Bits 5, 6, and 7 are implicitly left out
} myreg;
Here is an example:
typedef struct {
prescaler : 2; timeronoff : 1; postscaler : 4;} mybitfield;
Bit fields can be accessed in same way as the structure members. Use direct and
indirect member selector (. and ->). For example, we could work with our
previously declared mybitfield like this:
void main() {
TimerControl.prescaler = 0;
TimerControl.timeronoff = 1;
TimerControl.postscaler = 3;
T2CON = TimerControl;
}//~!
page
75
MikroElektronika: Development tools - Books - Compilers
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). C defines a set of standard conver-
sions for built-in types, provided by compiler when necessary.
Standard Conversions
The basic rule of automatic (implicit) conversion is that the operand of simpler
type is converted (promoted) to the type of more complex operand. Then, type of
the result is that of more complex operand.
page
76
MikroElektronika: Development tools - Books - Compilers
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 differ-
ent arithmetic types, mikroC performs implicit type conversions before the expres-
sion is evaluated. These standard conversions include promotions of “lower” types
to “higher” types in the interests of accuracy and consistency.
Converting a longer integral type to a shorter type truncates the higher order bits
and leaves low-order bits unchanged. Converting a shorter integral type to a longer
type either sign-extends or zero-fills the extra bits of the new value, depending on
whether the shorter type is signed or unsigned, respectively.
First, any small integral types are converted according to the following rules:
After this, any two values associated with an operator are either int (including the
long and unsigned modifiers), or they are of type double, float, or long double.
page
77
MikroElektronika: Development tools - Books - Compilers
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.
Pointer Conversions
Pointer types can be converted to other pointer types using the typecasting mecha-
nism:
char *str;
int *ip;
str = (char *)ip;
More generally, the cast (type*) will convert a pointer to type “pointer to type”.
(type_name) <object>
For example:
char a, b;
page
78
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
DECLARATIONS
Introduction to Declarations
- Variables
- Constants
- Functions
- Types
- Structure, union, and enumeration tags
- Structure members
- Union members
- Arrays of other types
- Statement labels
- Preprocessor macros
There can be many referencing declarations for the same identifier, especially in a
multifile program, but only one defining declaration for that identifier is allowed.
page
79
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
where var1, var2,... are any sequence of distinct identifiers with optional initial-
izers. Each of the variables is declared to be of <data-type>; if omitted, it
defaults to int. Specifier <storage-class> can take values extern, static,
register, or the default auto. Optional <qualifier> can take values const
or volatile. For more details, refer to Storage Classes and Type Qualifiers.
These are all defining declarations; storage is allocated and any optional initializ-
ers are applied.
page
80
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Linkage
Each instance of a particular identifier with external linkage represents the same
object or function throughout the entire set of files and libraries making up the
program. Each instance of a particular identifier with internal linkage represents
the same object or function within one file only.
Linkage Rules
Local names have internal linkage; same identifier can be used in different files to
signify different objects. Global names have external linkage; identifier signifies
the same object throughout all program files.
If the same identifier appears with both internal and external linkage within the
same file, the identifier will have internal linkage.
1. names having file scope, explicitly declared as static, have internal linkage,
2. names having file scope, explicitly declared as const and not explicitly,
declared as extern, have internal linkage,
3. typedef names have internal linkage,
4. enumeration constants have internal linkage .
page
81
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
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. An external definition is an
external declaration that also defines an object or function; that is, it also allocates
storage. If an identifier declared with external linkage is used in an expression
(other than as part of the operand of sizeof), then exactly one external definition
of that identifier must be somewhere in the entire program.
mikroC allows later declarations of external names, such as arrays, structures, and
unions, to add information to earlier declarations. Here's an example:
page
82
MikroElektronika: Development tools - Books - Compilers
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.
Storage class dictates the location (data segment, register, heap, or stack) of the
object and its duration or lifetime (the entire running time of the program, or dur-
ing execution of some blocks of code). Storage class can be established by the
syntax of the declaration, by its placement in the source code, or by both of these
factors:
auto
register
static
extern
Auto
Use the auto modifer to define a local variable as having a local duration. This is
the default for local variables and is rarely used. You cannot use auto with glob-
als. See also Functions.
Register
page
83
MikroElektronika: Development tools - Books - Compilers
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.
Extern
Name declared with extern specifier has external linkage, unless it has been pre-
viously declared as having internal linkage. Declaration is not a definition if it has
extern specifier and is not initialized. The keyword extern is optional for a
function prototype.
Use the extern modifier to indicate that the actual storage and initial value of a
variable, or body of a function, is defined in a separate source code module.
Functions declared with extern are visible throughout all source files in a pro-
gram, unless you redefine the function as static.
page
84
MikroElektronika: Development tools - Books - Compilers
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 actu-
ally affect the type of declared object.
Qualifier const
Qualifier const implies that the declared object will not change its value during
runtime. In declarations with const qualifier, you need to initialize all the objects
in the declaration.
Effectively, mikroC treats objects declared with const qualifier same as literals or
preprocessor constants. Compiler will report an error if trying to change an object
declared with const qualifier.
For example:
const double PI = 3.14159;
Qualifier volatile
Qualifier volatile implies that variable may change its value during runtime
indepent from the program. Use the volatile modifier to indicate that a variable
can be changed by a background routine, an interrupt routine, or an I/O port.
Declaring an object to be volatile warns the compiler not to make assumptions
concerning the value of the object while evaluating expressions in which it occurs
because the value could change at any moment.
page
85
MikroElektronika: Development tools - Books - Compilers
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 type-
def declarations to construct shorter or more meaningful names for types already
defined by the language or for types that you have declared. You cannot use the
typedef specifier inside a function definition.
The typedef keyword assigns the synonym to the data type definition <type
definition>.
Declaration starting with the typedef specifier does not introduce an object or
function of a given type, but rather a new name for a given type. That is, the
typedef declaration is identical to “normal” declaration, but instead of objects, it
declares types. It is a common practice to name custom type identifiers with start-
ing capital letter — this is not required by C.
For example:
In typedef declaration, as in any declaration, you can declare several types at once.
For example:
Here, Pti is synonym for type “pointer to int”, and Array is synonym for type
“array of 10 int elements”.
page
86
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
asm Declaration
You can group assembly language statements by beginning the block of statements
with the asm keyword (or _asm, or __asm), then surrounding the statements with
braces:
asm {
... // block of assembly instructions
};
Be careful when embedding assembly code – mikroC will not check if assembler
instruction changed memory locations already used by C variables. You can write
C comments in assembly.
asm {
MOVLW 0
MOVWF $5
MOVWF PORTA // here's a comment
};
page
87
MikroElektronika: Development tools - Books - Compilers
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.
The initializer for an automatic object can be any legal expression that evaluates to
an assignment-compatible value for the type of the variable involved.
Scalar types are initialized with a single expression, which can optionally be
enclosed in braces. The initial value of the object is that of the expression; the
same constraints for type and conversions apply as for simple assignments.
For example:
int i = 1;
char *s = "hello";
struct complex c = {0.1, -0.2};
// where 'complex' is a structure (float, float)
For structures or unions with automatic storage duration, the initializer must be
one of the following:
- an initializer list,
- a single expression with compatible union or structure type. In this case, the
initial value of the object is that of the expression.
Also, you can initialize arrays of character type with a literal string, optionally
enclosed in braces. Each character in the string, including the null terminator, ini-
tializes successive elements in the array. For more information, refer to Arrays.
Automatic Initialization
mikroC does not provide automatic initialization for objects. Uninitialized globals
and objects with static duration will take random values from memory.
page
88
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
FUNCTIONS
Functions are central to C programming. Functions are usually defined as subpro-
grams which return a value based on a number of input parameters. Return value
of a function can be used in expressions – technically, function call is considered
an operator like any other.
C allows a function to create results other than its return value, referred to as side
effects. Often, function return value is not used at all, depending on the side
effects. These functions are equivalent to procedures of other programming lan-
guages, such as Pascal. C does not distinguish between procedure and function –
functions play both roles.
Each program must have a single external function named main marking the entry
point of the program. Functions are usually declared as prototypes in standard or
user-supplied header files, or within program files. Functions have external linkage
by default and are normally accessible from any file in the program. This can be
restricted by using the static storage class specifier in function declaration (see
Storage Classes and Linkage).
Function Declaration
Functions are declared in your source files or made available by linking precom-
piled libraries. Declaration syntax of a function is:
<type> func(parameter-declarator-list);
The <type> represents the type of function result, and can be any standard or
user-defined type. For functions that do not return value, you should use void
type. The type can be omitted in global function declarations, and function will
assume int type by default. For example, main() returns an int value.
Function type can also be a pointer. For example, float* means that the function
result is a pointer to float. Generic pointer, void* is also allowed.
page
89
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Unlike with variable declaration, each argument in the list needs its own type
specifier and a possible qualifier const or volatile.
Function Prototypes
A given function can be defined only once in a program, but can be declared sev-
eral times, provided the declarations are compatible. If you write a nondefining
declaration of a function, i.e. without the function body, you do not have to specify
the formal arguments. This kind of declaration, commonly known as the function
prototype, allows better control over argument number and type checking, and
type conversions.
Name of the parameter in function prototype has its scope limited to the prototype.
This allows different parameter names in different declarations of the same func-
tion:
Function prototypes greatly aid in documenting code. For example, the function
CF_Init_Port takes two parameters: Control Port and Data Port. The question
is, which is which? The function prototype
makes it clear. If a header file contains function prototypes, you can that file to get
the information you need for writing programs that call those functions. If you
include an identifier in a prototype parameter, it is used only for any later error
messages involving that parameter; it has no other effect.
page
90
MikroElektronika: Development tools - Books - Compilers
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 func-
tion declarations cannot be nested.
To return the function result, use the return statement. Statement return in
functions of void type cannot have a parameter – in fact, you can omit the
return statement altogether if it is the last statement in the function body.
Here is a sample function which depends on side effects rather than return value:
#include <math.h>
page
91
MikroElektronika: Development tools - Books - Compilers
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 ():
Each expression in the function call is an actual argument. Number and types of
actual arguments should match those of formal function parameters. If types dis-
agree, implicit type conversions rules apply. Actual arguments can be of any com-
plexity, but you should not depend on their order of evaluation, because it is not
specified.
Upon function call, all formal parameters are created as local objects initialized by
values of actual arguments. Upon return from a function, temporary object is cre-
ated in the place of the call, and it is initialized by the expression of return state-
ment. This means that function call as an operand in complex expression is treated
as the function result.
If the function is without result (type void) or you don’t need the result, you can
write the function call as a self-contained expression.
Argument Conversions
When a function prototype has not been previously declared, mikroC converts
integral arguments to a function call according to the integral widening (expan-
sion) rules described in Standard Conversions. When a function prototype is in
scope, mikroC converts the given argument to the type of the declared parameter
as if by assignment.
page
92
MikroElektronika: Development tools - Books - Compilers
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.
Note: If your function prototype does not match the actual function definition,
mikroC will detect this if and only if that definition is in the same compilation unit
as the prototype. If you create a library of routines with a corresponding header
file of prototypes, consider including that header file when you compile the
library, so that any discrepancies between the prototypes and the actual definitions
will be caught.
The compiler is also able to force arguments to the proper type. Suppose you have
the following code:
main() {
//...
res = func(limit, ch); // function call
}
Since it has the function prototype for func, this program converts limit and ch
to long, using the standard rules of assignment, before it places them on the stack
for the call to func.
Without the function prototype, limit and ch would have been placed on the
stack as an integer and a character, respectively; in that case, the stack passed to
func would not match in size or content what func was expecting, leading to
problems. Using function prototypes aids greatly in tracking down bugs.
page
93
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
OPERATORS
Operators are tokens that trigger some computation when applied to variables and
other objects in an expression.
- Arithmetic Operators
- Assignment Operators
- Bitwise Operators
- Logical Operators
- Reference/Indirect Operators (see Pointer Arithmetic)
- Relational Operators
- Structure Member Selectors (see Structure Member Access)
- sizeof Operator
There are 15 precedence categories, some of which contain only one operator.
Operators in the same category have equal precedence with each other.
Where duplicates of operators appear in the table, the first occurrence is unary, the
second binary. Each category has an associativity rule: left-to-right or right-to-left.
In the absence of parentheses, these rules resolve the grouping of expressions with
operators of equal precedence.
page
94
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
15 2 () [] . -> left-to-right
! ~ ++ -- + - *
14 1 & (type) sizeof
right-to-left
13 2 * / % left-to-right
12 2 + - left-to-right
9 2 == != left-to-right
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 &= ^= |= <<= >>=
right-to-left
1 2 , left-to-right
page
95
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Arithmetic Operators
+ addition 12
- subtraction 12
* multiplication 13
/ division 13
returns the remainder of integer division
% 13
(cannot be used with floating points)
+ (unary) unary plus does not affect the operand 14
Note: Operator * is context sensitive and can also represent the pointer reference
operator. See Pointers for more information.
page
96
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
/* for example: */
7 / 4; // equals 1
7 * 3 / 4; // equals 5
/* but: */
7. * 3./ 4.; // equals 5.25 as we are working with floats
Remainder operand % works only with integers; sign of result is equal to the sign
of first operand:
/* for example: */
9 % 3; // equals 0
7 % 3; // equals 1
-7 % 3; // equals -1
Unary operators ++ and -- are the only operators in C which can be either prefix
(e.g. ++k, --k) or postfix (e.g. k++, k--).
For example:
int j = 5; j = ++k;
/* k = k + 1, j = k, which gives us j = 6, k = 6 */
int j = 5; j = k++;
/* j = k, k = k + 1, which gives us j = 5, k = 6 */
page
97
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Relational Operators
== equal 9
!= not equal 9
You should always bear in mind that relational operators return either 0 or 1.
Consider the following examples:
page
98
MikroElektronika: Development tools - Books - Compilers
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.
Note: Operator & can also be the pointer reference operator. Refer to Pointers for
more information.
/* because ..
page
99
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
/* Similarly: */
Binary operators << and >> move the bits of the left operand for a number of posi-
tions specified by the right operand, to the left or right, respectively. Right operand
has to be positive.
With shift left (<<), left most bits are discarded, and “new” bytes on the right are
assigned zeros. Thus, shifting unsigned operand to left by n positions is equivalent
to multiplying it by 2n if all the discarded bits are zero. This is also true for signed
operands if all the discarded bits are equal to sign bit.
With shift right (>>), right most bits are discarded, and the “freed” bytes on the
left are assigned zeros (in case of unsigned operand) or the value of the sign bit
zeros (in case of signed operand). Shifting operand to right by n positions is equiv-
alent to dividing it by 2n.
Be aware of the principle difference between how bitwise and logical operators
work. For example:
page
100
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Logical Operators
Logical operators && and || associate from left to right. Logical negation operator
! associates from right to left.
|| logical OR 4
! logical negation 14
c >= '0' && c <= '9'; // reads as: (c>='0') && (c<='9')
a + 1 == b || ! f(x;) // reads as: ((a+1)== b) || (!(f(x)))
Logical AND (&&) returns 1 only if both expressions evaluate to be nonzero, oth-
erwise returns 0. If the first expression evaluates to false, the second expression is
not evaluated. For example:
page
101
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
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!
Be aware of the principle difference between how bitwise and logical operators
work. For example:
page
102
MikroElektronika: Development tools - Books - Compilers
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 con-
ditional operator is:
2. Both of compatible struct or union types. The resulting type is the structure or
union type of expression2 and expression3.
page
103
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
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.
Assignment Operators
expression1 = expression2
page
104
MikroElektronika: Development tools - Books - Compilers
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 errors.
Assignment Rules
For both simple and compound assignment, the operands expression1 and
expression2 must obey one of the following rules:
page
105
MikroElektronika: Development tools - Books - Compilers
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).
If applied to a type identifier, sizeof returns the size of the specified type. Unit
for type size is the sizeof(char) which is equivalent to one byte. Operation
sizeof(char) gives the result 1, whether the char is signed or unsigned.
sizeof(char) /* returns 1 */
sizeof(int) /* returns 2 */
sizeof(unsigned long) /* returns 4 */
When the operand is a non-parameter of array type, the result is the total number
of bytes in the array (in other words, an array name is not converted to a pointer
type):
int i, j, a[10];
//...
j = sizeof(a[1]); /* j = sizeof(int) = 2 */
i = sizeof(a); /* i = 10*sizeof(int) = 20 */
page
106
MikroElektronika: Development tools - Books - Compilers
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-mem-
ory error if it can’t compile an expression that is too complex.
For ANSI C, the primary expressions are: constant (also referred to as literal),
identifier, and (expression).
Comma Expressions
One of the specifics of C is that it allows you to use comma as a sequence opera-
tor to form the so-called comma expressions or sequences. Comma expression is a
comma-delimited list of expressions – it is formally treated as a single expression
so it can be used in places where an expression is expected. The following
sequence:
expression_1, expression_2;
results in the left-to-right evaluation of each expression, with the value and type of
expression_2 giving the result of the whole expression. Result of expres-
sion_1 is discarded.
page
107
MikroElektronika: Development tools - Books - Compilers
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:
this results in the left-to-right evaluation of each expression, with the value and
type of expression_n giving the result of the whole expression. Results of other
expressions are discarded, but their (possible) side-effect do occur.
For example:
result = (a = 5, b /= 2, c++);
/* returns preincremented value of variable c, but also
intializes a, divides b by 2, and increments c */
Note
Do not confuse comma operator (sequence operator) with the comma punctuator
which separates elements in a function argument list and initializator lists. Mixing
the two uses of comma is legal, but you must use parentheses to distinguish them.
To avoid ambiguity with the commas in function argument and initializer lists, use
parentheses. For example,
calls function func with three arguments (i, 5, k), not four.
page
108
MikroElektronika: Development tools - Books - Compilers
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.
- Labeled Statements
- Expression Statements
- Selection Statements
- Iteration Statements (Loops)
- Jump Statements
- Compound Statements (Blocks)
Labeled Statements
Every statement in program can be labeled. Label is an identifier added before the
statement like this:
<label-identifier>: <statement>
There is no special declaration of a label – it just “tags” the statement. Label iden-
tifier has a function scope and label cannot be redefined within the same function.
Labels have their own namespace: label identifier can match any other identifier in
the program.
1. The label identifier serves as a target for the unconditional goto statement,
2. The label identifier serves as a target for the switch statement. For this purpose,
only case and default labeled statements are used:
page
109
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Expression Statements
expression;
The null statement is a special case, consisting of a single semicolon (;). The null
statement does nothing, and is therefore useful in situations where the mikroC syn-
tax expects a statement but your program does not need one. For example, null
statement is commonly used in “empty” loops:
Selection Statements
If Statement
The else keyword is optional, but no statements can come between an if state-
ment and an else. The <statement> in both if and else block cannot be a
single declaration statement. Of course, it can be a compound statement containing
some declarations.
page
110
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Nested if statements
Nested if statements require additional attention. General rule is that the nested
conditionals are parsed starting from the innermost conditional, with each else
bound to the nearest available if on its left:
if (<expression1>) <statement1>
else if (<expression2>)
if (<expression3>) <statement2>
else <statement3> // belongs to: if (<expression3>)
else <statement4> // belongs to: if (<expression2>)
Note: The #if and #else preprocessor statements (directives) look similar to the
if and else statements, but have very different effects. They control which
source file lines are compiled and which are ignored. See Preprocessor for more
information
Switch Statement
Use the switch statement to pass control to a specific program branch, based on a
certain condition. Syntax of switch statement is:
switch (<expression>) {
case <constant-expression_1> : <statement_1>;
case <constant-expression_2> : <statement_2>;
.
.
.
case <constant-expression_n> : <statement_n>;
[default : <statement>;]
}
page
111
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
For example, if variable i had value between 1 and 3, following switch would
always return it as 4:
switch (i) {
case 1: i++;
case 2: i++;
case 3: i++;
}
To avoid evaluating any other cases and relinquish control from the switch, ter-
minate each case with break.
Conditional switch statements can be nested – labels case and default are
then assigned to the innermost enclosing switch statement.
Here is a simple example with switch. Let’s assume we have a variable with only
3 different states (0, 1, or 2) and a corresponding function (event) for each of these
states. This is how we could switch the code to the appopriate routine:
switch (state) {
case 0: Lo(); break;
case 1: Mid(); break;
case 2: Hi(); break;
default: Message("Invalid state!");
}
page
112
MikroElektronika: Development tools - Books - Compilers
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 itera-
tion statements in C: while, do, and for.
While Statement
Here is an example of calculating scalar product of two vectors, using the while
statement:
int s = 0, i = 0;
while (i < n) {
s += a[i] * b[i];
i++;
}
page
113
MikroElektronika: Development tools - Books - Compilers
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 state-
ment is:
Note that do is the only control structure in C which explicitly ends with semi-
colon (;). Other control structures end with <statement> which means that they
implicitly include a semicolon or closing brace.
Here is an example of calculating scalar product of two vectors, using the do state-
ment:
s = 0; i = 0;
do {
s += a[i] * b[i];
i++;
} while (i < n);
For Statement
The for statement implements an iterative loop. Syntax of for statement is:
Before the first iteration of the loop, <init-expression> sets the starting vari-
ables for the loop. You cannot pass declarations in <init-expression>.
The <condition-expression> is checked before the first entry into the block;
<statement> is executed repeatedly until the value of <condition-expres-
sion> is false. After each iteration of the loop, <increment-expression>
increments a loop counter. Consequently, i++ is functionally the same as ++i.
page
114
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
for ( ; ; ) {...}
The only way to break out of this loop is by means of break statement.
Here is an example of calculating scalar product of two vectors, using the for
statement:
but this is considered a bad programming style. Though it is valid, calculating the
sum should not be a part of the incrementing expression, because it is not in the
service of loop routine. Note that we used a null statement (;) for a loop body.
page
115
MikroElektronika: Development tools - Books - Compilers
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 inner-
most switch, for, while, or do block.
Break is commonly used in switch statements to stop its execution upon the first
positive match. For example:
switch (state) {
case 0: Lo(); break;
case 1: Mid(); break;
case 2: Hi(); break;
default: Message("Invalid state!");
}
Continue Statement
You can use the continue statement within loops (while, do, for) to “skip the
cycle”. It passes control to the end of the innermost enclosing end brace belonging
to a looping construct. At that point the loop continuation condition is re-evaluat-
ed. This means that continue demands the next iteration if loop continuation con-
dition is true.
Goto Statement
Use the goto statement to unconditionally jump to a local label — for more infor-
mation on labels, refer to Labeled Statements. Syntax of goto statement is:
goto <identifier>;
This will transfer control to the location of a local label specified by <identifi-
er>. The <identifier> has to be a name of the label within the same function
in which the goto statement is. The goto line can come before or after the label.
page
116
MikroElektronika: Development tools - Books - Compilers
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.
for (...) {
for (...) {
...
if (disaster) goto Error;
...
}
}
.
.
.
Error: /* error handling code */
Return Statement
Use the return statement to exit from the current function back to the calling
routine, optionally returning a value. Syntax is:
return [<expression>];
page
117
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
For example, for loop expects one statement in its body, so we can pass it a com-
pound statement:
Note that, unlike other statements, compound statements do not end with semi-
colon (;), i.e. there is never a semicolon following the closing brace.
page
118
MikroElektronika: Development tools - Books - Compilers
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:
Note that preprocessor analyzes text at token level, not at individual character
level. Preprocessor is controled by means of preprocessor directives and pre-
processor operators.
Preprocessor Directives
Any line in source code with a leading # is taken as a preprocessing directive (or
control line), unless the # is within a string literal, in a character constant, or
embedded in a comment. The initial # can be preceded or followed by whitespace
(excluding new lines).
The null directive consists of a line containing the single character #. This line is
always ignored.
Preprocessor directives are usually placed at the beginning of the source code, but
they can legally appear at any point in a program. The mikroC preprocessor
detects preprocessor directives and parses the tokens embedded in them. Directive
is in effect from its declaration to the end of the program file.
page
119
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
If you need to break directive into multiple lines, you can do it by ending the line
with a backslash (\):
Macros
After each individual macro expansion, a further scan is made of the newly
expanded text. This allows for the possibility of nested macros: The expanded text
can contain macro identifiers that are subject to replacement. However, if the
macro expands into what looks like a preprocessing directive, such a directive will
not be recognized by the preprocessor. Any occurrences of the macro identifier
found within literal strings, character constants, or comments in the source code
are not expanded
page
120
MikroElektronika: Development tools - Books - Compilers
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).
main() {
EVERLOOP {
...
if (error) {LCD_Out_CP(ERR_MSG); break;}
...
}
}
#ifndef BLOCK_SIZE
#define BLOCK_SIZE 512
#endif
page
121
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
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.
macro_identifier<whitespace>(<actual_arg_list>)
in the subsequent source code. The syntax is identical to that of a function call;
indeed, many standard library C “functions” are implemented as macros.
However, there are some important semantic differences, side effects, and poten-
tial pitfalls.
A macro call results in two sets of replacements. First, the macro identifier and the
parenthesis-enclosed arguments are replaced by the token sequence. Next, any for-
mal arguments occurring in the token sequence are replaced by the corresponding
real arguments appearing in the actual_arg_list. As with simple macro defini-
tions, rescanning occurs to detect any embedded macro identifiers eligible for
expansion.
page
122
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
It is highly recommended that you put parentheses around each of the arguments
in macro body – this will avoid possible problems with operator precedence.
Undefining Macros
#undef macro_identifier
Directive #undef detaches any previous token sequence from the macro identifi-
er; the macro definition has been forgotten, and the macro identifier is undefined.
No macro expansion occurs within #undef lines.
After a macro identifier has been undefined, it can be redefined with #define,
using the same or a different token sequence.
page
123
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
File Inclusion
The #include directive pulls in other named files, known as include files, or
headers, into the source code. The syntax has two formats:
#include <header_name>
#include "header_name"
The preprocessor removes the #include line and replaces it with the entire text
of the header file at that point in the source code. The placement of the #include
can therefore influence the scope and duration of any identifiers in the included
file.
The difference between the two formats lies in the searching algorithm employed
in trying to locate the include file.
If #include directive was used with the <header_name> version, the search is
made successively in each of the following locations, in this particular order:
1. the project folder (folder which contains the project file .ppc),
2. mikroC installation folder > “include” folder,
3. your custom search paths.
Explicit Path
If you place an explicit path in the header_name, only that directory will be
searched. For example:
#include "C:\my_files\test.h"
page
124
MikroElektronika: Development tools - Books - Compilers
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 follow-
ing #include:
#include macro_identifier
It assumes a macro definition exists that will expand the macro identifier into a
valid delimited header name with either of the <header_name> or
"header_name" formats.
Preprocessor Operators
The # (pound sign) is a preprocessor directive when it occurs as the first non-
whitespace character on a line. Also, # and ## perform operator replacement and
merging during the preprocessor scanning phase.
Operator #
If you need an actual argument (the exact sequence of characters within quotes) as
result of preprocessing, you can use the # operator in macro body. It can be placed
in front of a formal macro argument in definition in order to convert the actual
argument to a string after replacement.
For example, let’s have macro LCD_PRINT for printing variable name and value
on LCD:
page
125
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
LCD_PRINT(temp)
Operator ##
Operator ## is used for token pasting: you can paste (or merge) two tokens togeth-
er by placing ## in between them (plus optional whitespace on either side). The
preprocessor removes the whitespace and the ##, combining the separate tokens
into one new token. This is commonly used for constructing identifiers.
For example, we could define macro SPLICE for pasting two tokens into one
identifier:
#define SPLICE(x,y) x ## _ ## y
Note: mikroC does not support the older nonportable method of token pasting
using (l/**/r).
Conditional Compilation
page
126
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
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
<section_1>
[#elif constant_expression_2
<section_2>]
...
[#elif constant_expression_n
<section_n>]
[#else
<final_section>]
#endif
Each #if directive in a source file must be matched by a closing #endif direc-
tive. Any number of #elif directives can appear between the #if and #endif
directives, but at most one #else directive is allowed. The #else directive, if
present, must be the last directive before #endif.
The sections can be any program text that has meaning to the compiler or the pre-
processor. The preprocessor selects a single section by evaluating the con-
stant_expression following each #if or #elif directive until it finds a true
(nonzero) constant expression. The constant_expressions are subject to
macro expansion.
page
127
MikroElektronika: Development tools - Books - Compilers
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 section (possibly empty)
will be compiled.
You can use the #ifdef and #ifndef directives anywhere #if can be used. The
#ifdef and #ifndef conditional directives let you test whether an identifier is
currently defined or not. The line
#ifdef identifier
has exactly the same effect as #if 1 if identifier is currently defined, and the
same effect as #if 0 if identifier is currently undefined. The other directive,
#ifndef, tests true for the “not-defined” condition, producing the opposite
results.
The syntax thereafter follows that of the #if, #elif, #else, and #endif.
page
128
MikroElektronika: Development tools - Books - Compilers
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, 1-
Wire, LCD, PWM, RS485, numeric formatting, bit manipulation, and many other
are included along with practical, ready-to-use code examples.
BUILT-IN ROUTINES
mikroC compiler provides a set of useful built-in utility functions. Built-in func-
tions do not require any header files to be included; you can use them in any part
of your project.
Delay_us
Delay_ms
Delay_Cyc
Delay_us
Description Creates a software delay in duration of count microseconds. Range of applicable con-
stants depends on oscillator frequency.
Delay_ms
Description Creates a software delay in duration of count milliseconds. Range of applicable con-
stants depends on oscillator frequency.
page
130
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Delay_Cyc
Description Creates a delay based on MCU clock. Delay lasts for 10 times the input parameter in
MCU cycles. Input parameter needs to be in range 3 .. 255.
Note that Delay_Cyc is library function rather than a built-in routine; it is presented in
this topic for the sake of convenience.
page
131
MikroElektronika: Development tools - Books - Compilers
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.
- ADC Library
- CAN Library
- CANSPI Library
- Compact Flash Library
- Conversions Library
- EEPROM Library
- Flash Memory Library
- Graphic LCD Library
- I²C Library
- LCD Library
- LCD8 Library
- Manchester Code Library
- OneWire Library
- PWM Library
- RS-485 Library
- Software I²C Library
- Software SPI Library
- Software UART Library
- Sound Library
- USART Library
- Conversions Library
- Util Library
page
132
MikroElektronika: Development tools - Books - Compilers
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
Returns 10-bit unsigned value read from the specified ADC channel.
Description Initializes PIC’s internal ADC module to work with RC clock. Clock determines the
time period necessary for performing AD conversion (min 12TAD). RC sources typical-
ly have Tad 4uS.
Parameter channel represents the channel from which the analog value is to be
acquired. For channel-to-pin mapping please refer to documentation for the appropriate
PIC MCU.
Required PIC MCU with built-in ADC module. You should consult the Datasheet documentation
for specific device (most devices from PIC16/18 families have it).
Before using the function, be sure to configure the appropriate TRISA bits to designate
the pins as input. Also, configure the desired pin as analog input, and set Vref (voltage
reference value).
page
133
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Example
/* This code snippet reads analog value from channel 2 and displays
it on PORTD (lower 8 bits) and PORTB (2 most significant bits). */
unsigned temp_res;
void main() {
ADCON1 = 0x80; // Configure analog inputs and Vref
TRISA = 0xFF; // PORTA is input
TRISB = 0x3F; // Pins RB7, RB6 are outputs
TRISD = 0; // PORTD is output
do {
temp_res = ADC_Read(2); // Get results of AD conversion
PORTD = temp_res; // Send lower 8 bits to PORTD
PORTB = temp_res >> 2; // Send 2 most significant bits to RB7, RB6
} while(1);
}
Hardware Connection
PIC16F877A
+5V 330R
+5V LB7
MCLR/Vpp/THV RB7/PGD
RA0/AN0 RB6/PGC
10K
330R
RE1/WR/AN6 Vdd LD6
+5V
RE2/CS/AN7 Vss
Vdd RD7/PSP7 330R
LD5
Vss RD6/PSP6
OSC1 RD5/PSP5
330R
OSC2 RD4/PSP4 LD4
RCO/T1OSO RC7/RX/DT
RC1/T1OSI RC6/TX/CK 330R LD3
RC2/CCP1 RC5
RC3 RC4
RD0/PSP0 RD3/PSP3 330R
4MHz LD2
RD1/PSP1 RD2/PSP2
330R LD1
330R
LD0
page
134
MikroElektronika: Development tools - Books - Compilers
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–check-
ing and fault confinement. Faulty CAN data and remote frames are re-transmitted
automatically, similar to the Ethernet.
Data transfer rates vary from up to 1 Mbit/s at network lengths below 40m to 250
Kbit/s at 250m cables, and can go even lower at greater network distances, down
to 200Kbit/s, which is the minimum bitrate defined by the standard. Cables used
are shielded twisted pairs, and maximum cable length is 1000m.
Note: Be sure to check CAN constants necessary for using some of the functions.
See page 141.
Library Routines
CANSetOperationMode
CANGetOperationMode
CANInitialize
CANSetBaudRate
CANSetMask
CANSetFilter
CANRead
CANWrite
RegsToCANID
CANIDToRegs
page
135
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CANSetOperationMode
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).
Required CAN routines are currently supported only by P18XXX8 PICmicros. Microcontroller
must be connected to CAN transceiver (MCP2551 or similar) which is connected to
CAN bus.
CANGetOperationMode
Required CAN routines are currently supported only by P18XXX8 PICmicros. Microcontroller
must be connected to CAN transceiver (MCP2551 or similar) which is connected to
CAN bus.
page
136
MikroElektronika: Development tools - Books - Compilers
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.
Parameters:
Required CAN must be in Config mode; otherwise the function will be ignored.
page
137
MikroElektronika: Development tools - Books - Compilers
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.
Parameters:
Required CAN must be in Config mode; otherwise the function will be ignored.
page
138
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
CANSetMask
Description Function sets mask for advanced filtering of messages. Given value is bit adjusted to
appropriate buffer mask registers.
Required CAN must be in Config mode; otherwise the function will be ignored.
Example // Set all mask bits to 1, i.e. all filtered bits are relevant:
CANSetFilter
Description Function sets mask for advanced filtering of messages. Given value is bit adjusted to
appropriate buffer mask registers.
Required CAN must be in Config mode; otherwise the function will be ignored.
page
139
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CANRead
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.
CANWrite
Description If at least one empty transmit buffer is found, function sends message on queue for
transmission. If buffer is full, function returns 0.
page
140
MikroElektronika: Development tools - Books - Compilers
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_CONFIG_FLAGS
// continues..
page
141
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
// ..continued
You may use bitwise AND (&&) to form config byte out of these values. For exam-
ple:
init = CAN_CONFIG_SAMPLE_THRICE && CAN_CONFIG_PHSEG2_PRG_ON &&
CAN_CONFIG_STD_MSG && CAN_CONFIG_DBL_BUFFER_ON &&
CAN_CONFIG_VALID_XTD_MSG && CAN_CONFIG_LINE_FILTER_OFF;
//...
CANInitialize(1, 1, 3, 3, 1, init); // initialize CAN
CAN_TX_MSG_FLAGS
You may use bitwise AND (&&) to adjust the appropriate flags. For example:
/* form value to be used with CANSendMessage: */
send_config = CAN_TX_PRIORITY_0 && CAN_TX_XTD_FRAME &&
CAN_TX_NO_RTR_FRAME;
//...
CANSendMessage(id, data, 1, send_config);
page
142
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
CAN_RX_MSG_FLAGS
You may use bitwise AND (&&) to adjust the appropriate flags. For example:
CAN_MASK
#define CAN_MASK_B1 0
#define CAN_MASK_B2 1
CAN_FILTER
#define CAN_FILTER_B1_F1 0
#define CAN_FILTER_B1_F2 1
#define CAN_FILTER_B2_F1 2
#define CAN_FILTER_B2_F2 3
#define CAN_FILTER_B2_F3 4
#define CAN_FILTER_B2_F4 5
page
143
MikroElektronika: Development tools - Books - Compilers
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;
//........
void main() {
PORTC = 0;
TRISC = 0;
PORTD = 0;
TRISD = 0;
aa = 0;
aa1 = 0;
aa2 = 0;
data[0] = 0;
// Initialize CAN
CANInitialize(1,1,3,3,1,aa);
id = -1;
// continues ..
page
144
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
// .. continued
PORTD = 0xFF;
id = 12111;
CANWrite(id,data,1,aa1); // Send message via CAN
while (1) {
oldstate = 0;
zr = CANRead(&id, data , &len, &aa2);
if ((id == 3) && zr) {
PORTD = 0xAA;
PORTC = data[0]; // Output data at portC
data[0]++ ;
data[1] = 0xFF;
id = 12111;
CANWrite(id, data, 2,aa1); // Send incremented data back
}
}
}//~!
page
145
MikroElektronika: Development tools - Books - Compilers
making it simple...
mikroC
10K
RA1/AN1 RB5/PGM RA1/AN1 RB5/PGM
RA2/AN2/Vref- RB4 RA2/AN2/Vref- RB4
RA3/AN3/Vref+ RB3/CANRX RA3/AN3/Vref+ RB3/CANRX
RA4/TOCKI RB2/CANTX/INT2 RA4/TOCKI RB2/CANTX/INT2
RA5/AN4/SS/LVDIN RB1/INT1 RA5/AN4/SS/LVDIN RB1/INT1
RE0/AN5/RD/ RB0/INT0 TX-CAN RS
Reset
RE0/AN5/RD/ RB0/INT0
Reset
+5V GND CANH
RE1/AN6/WR/C1OUT Vdd RE1/AN6/WR/C1OUT Vdd
+5V VCC +5V
RE2/AN7/CS/C2OUT Vss CANL RE2/AN7/CS/C2OUT Vss
RXD Vref
10R
Vdd RD7/PSP7/P1D Vdd RD7/PSP7/P1D
Vss RD6/PSP6/P1C PCA82C250 Vss RD6/PSP6/P1C
mikroC - C Compiler for Microchip PIC microcontrollers
10R
RD0/PSP0/C1IN+ RD3/PSP3/C2IN- RD0/PSP0/C1IN+ RD3/PSP3/C2IN-
RD1/PSP1/C1IN- RD2/PSP2/C2IN+ RD1/PSP1/C1IN- RD2/PSP2/C2IN+
PCA82C250
or
MCP2551
Hardware Connection
146
page
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. Note that the effective communication speed depends on the SPI, and is
certainly slower than the “real” CAN.
Note: CANSPI functions are supported by any PIC MCU that has SPI interface on
PORTC. Also, CS pin of MCP2510 or MCP2515 must be connected to RC0.
Example of HW connection is given at the end of the chapter.
Note: Be sure to check CAN constants necessary for using some of the functions.
See page 141.
Library Routines
CANSPISetOperationMode
CANSPIGetOperationMode
CANSPIInitialize
CANSPISetBaudRate
CANSPISetMask
CANSPISetFilter
CANSPIRead
CANSPIWrite
RegsToCANSPIID
CANSPIIDToRegs
page
147
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CANSPISetOperationMode
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 141).
Required CANSPI functions are supported by any PIC MCU that has SPI interface on PORTC.
Also, CS pin of MCP2510 or MCP2515 must be connected to RC0.
CANSPIGetOperationMode
page
148
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
CANSPIInitialize
Description Initializes CANSPI. All pending transmissions are aborted. Sets all mask registers to 0
to allow all messages.
Parameters:
Required CANSPI must be in Config mode; otherwise the function will be ignored.
page
149
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CANSPISetBaudRate
Description Sets CANSPI baud rate. Due to complexity of CANSPI protocol, you cannot simply
force a bps value. Instead, use this function when CANSPI is in Config mode. Refer to
datasheet for details.
Parameters:
Required CANSPI must be in Config mode; otherwise the function will be ignored.
page
150
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
CANSPISetMask
Description Function sets mask for advanced filtering of messages. Given value is bit adjusted to
appropriate buffer mask registers.
Required CANSPI must be in Config mode; otherwise the function will be ignored.
Example // Set all mask bits to 1, i.e. all filtered bits are relevant:
CANSPISetFilter
Description Function sets mask for advanced filtering of messages. Given value is bit adjusted to
appropriate buffer mask registers.
Required CANSPI must be in Config mode; otherwise the function will be ignored.
page
151
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CANSPIRead
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.
CANSPIWrite
Description If at least one empty transmit buffer is found, function sends message on queue for
transmission. If buffer is full, function returns 0.
page
152
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Library Example
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(); // Initialize SPI module
asm {
BSF STATUS,RP0 // ClearBit(TRISC,2);
BCF TRISC,2
BCF STATUS,RP0
}
asm BCF PORTC,2; // ClearBit(portc,2);
asm BSF PORTC,0; // SetBit(PORTC,0);
asm BSF STATUS,RP0;
asm BCF TRISC,0; // ClearBit(TRISC,0);
asm BCF STATUS,RP0;
PORTD = 0;
TRISD = 0;
aa = 0;
aa1 = 0;
aa2 = 0;
aa = CAN_CONFIG_SAMPLE_THRICE & // Form value to be used
CAN_CONFIG_PHSEG2_PRG_ON & // with CANSPIInitialize
CAN_CONFIG_STD_MSG &
CAN_CONFIG_DBL_BUFFER_ON &
CAN_CONFIG_VALID_XTD_MSG;
// continues ..
page
153
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
// .. continued
while (1) {
zr = CANSPIRead(&id , &Data , &len, &aa2); // Receive data, if any
if (id == 12111 && zr ) {
PORTB = data[0]++ ; // Output data on PORTB
id = 3;
Delay_ms(500);
page
154
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Hardware Connection
+5V
10K
+5V
PIC16F877A
MCLR/Vpp/THV RB7/PGD
100K
100K
100K
RA0/AN0 RB6/PGC
RA1/AN1 RB5
Reset
+5V RA2/AN2/Vref- RB4
RA3/AN3/Vref+ RB3/PGM
RA4/TOCKI RB2
TX-CAN Vdd RA5/AN4 RB1
RX-CAN RST RE0/RD/AN5 RB0/INT
CLKOUT CS RE1/WR/AN6 Vdd
TX0RTS SO +5V
RE2/CS/AN7 Vss
TX1RTS SI
Vdd RD7/PSP7
TX2RTS SCK
Vss RD6/PSP6
OSC2 INT
OSC1 RD5/PSP5
OSC1 RX0BF
Vss OSC2 RD4/PSP4
RX1BF
8MHz RCO/T1OSO RC7/RX/DT
MCP2510 4MH z RC1/T1OSI RC6/TX/CK
RC2/CCP1 RC5
RC3 RC4
RD0/PSP0 RD3/PSP3
RD1/PSP1 RD2/PSP2
TX-CAN RS
GND CANH
+5V VCC CANL
RXD
10R
Vref
PCA82C250
page
155
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
In CF card, data is divided into sectors, one sector usually comprising 512 bytes
(few older models have sectors of 256B). Read and write operations are not per-
formed directly, but successively through 512B buffer. Following routines can be
used for CF with FAT16, and FAT32 file system. Note that routines for file han-
dling (CF_File_Write_Init, CF_File_Write_Byte, and
CF_File_Write_Complete) can be used only with FAT16 file system.
Important! File accessing routines can write file. File names must be exactly 8
characters long and written in uppercase. User must ensure different names for
each file, as CF routines will not check for possible match.
Important! Before write operation, make sure you don’t overwrite boot or FAT
sector as it could make your card on PC or digital cam unreadable. Drive mapping
tools, such as Winhex, can be of a great assistance.
Library Routines
CF_Init_Port
CF_Detect
CF_Read_Init
CF_Read_Byte
CF_Read_Word
CF_Write_Init
CF_Write_Byte
CF_Write_Word
CF_File_Write_Init
CF_File_Write_Byte
CF_File_Write_Complete
page
156
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
CF_Init_Port
Description Initializes ports appropriately for communication with CF card. Specify two different
ports: ctrlport and dataport.
CF_Detect
CF_Read_Init
Description Initializes CF card for reading. Parameters: ctrlport is control port, dataport is data
port , address specifies sector address from where data will be read, and sectcnt is
total number of sectors prepared for read operation.
page
157
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CF_Read_Byte
CF_Read_Word
CF_Write_Init
Description Initializes CF card for writing. Parameter ctrlport is control port, dataport is data
port , address specifies sector address where data will be stored, and sectcnt is total
number of sectors prepared for write operation.
page
158
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
CF_Write_Byte
Description Writes one byte (data) to CF. All 512 bytes are transferred to a buffer.
CF_Write_Word
Description Writes one word (data) to CF. All 512 bytes are transferred to a buffer.
CF_File_Write_Init
page
159
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
CF_File_Write_Byte
Description Adds one byte (data) to file. You can supply ASCII value as parameter, for example 48
for zero.
CF_File_Write_Complete
Description Finalizes writing to file. Upon all data has be written to file, use this function to close
the file and make it readable. Parameter filename must be 8 character long in upper
case.
Example CF_File_Write_Complete(PORTB,PORTD,"my_file1","txt");
page
160
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Library Example
// CF-FAT example
long i1;
void initCF() {
CF_Init_Port(&PORTC,&PORTD); // Initialize ports
while (CF_Detect(&PORTC) == 0); // Wait until CF card is inserted
Delay_ms(50); // Wait for a while until the card is stabilized
}//~
void initLCD() {
Lcd_Init(&PORTB);
Lcd_Cmd(LCD_CLEAR);
Lcd_Cmd(LCD_CURSOR_OFF);
LCD_BarGraph_Init();
}//~
void main() {
char index, indexWrt;
long ii1;
initLCD();
index = 0;
while (index < 8u) {
initCF();
CF_File_Write_Init(&vPORTC,&PORTD);
fName[7] = indexWrt;
LCD_Out(1,1, fName);
LCD_Chr_CP('.');
LCD_Out_CP(ext);
// continues ..
page
161
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
// .. continued
i1 = 0; ii1 = 0;
LCD_BarGraph_Draw(2,1,13,ii1);
while (i1++ < 10000) {
CF_File_Write_Byte(&PORTC,&PORTD, indexWrt);
if ((i1>>7)!=ii1) {
ii1 = i1>>7;
LCD_BarGraph_Draw(2,1,16,ii1);
}
}
CF_File_Write_Complete(&PORTC,&PORTD, fName,ext);
index++ ;
}
fName = "finished ";
LCD_Out(1,1, fName);
}//~!
page
162
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple...
HW Connection
+5V
PIC16F877A
+5V
MCLR/Vpp/THV RB7/PGD
RA0/AN0 RB6/PGC
50
10K
RA1/AN1 RB5 25
49
24
RA2/AN2/Vref- RB4 48
23
47
RA3/AN3/Vref+ RB3/PGM 22
46
21
RA4/TOCKI RB2 45
20
44
RB1 19
RA5/AN4 43
18
42
RE0/RD/AN5 RB0/INT 17
41
16
RE1/WR/AN6 Vdd 40 Compact Flash Card
+5V 15
39
Reset
RE2/CS/AN7 Vss 14
38
13
Vdd RD7/PSP7 37
12
36
Vss RD6/PSP6 11
35
10
OSC1 RD5/PSP5 34
9
33
8
page
163
mikroC - C Compiler for Microchip PIC microcontrollers
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
Description Reads data from 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.
Ensure minimum 20ms delay between successive use of routines EEPROM_Write and
EEPROM_Read. Although PIC will write the correct value, EEPROM_Read might
return an undefined result.
page
164
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
EEPROM_Read
Description Writes data to specified address. Parameter address is of byte type, which means it can
address only 256 locations. For PIC18 micros with more EEPROM data locations, it is
programmer’s responsibility to set SFR EEADRH register appropriately.
Be aware that all interrupts will be disabled during execution of EEPROM_Write rou-
tine (GIE bit of INTCON register will be cleared). Routine will set this bit on exit.
Ensure minimum 20ms delay between successive use of routines EEPROM_Write and
EEPROM_Read. Although PIC will write the correct value, EEPROM_Read might
return an undefined result.
Example EEPROM_Write(0x32);
Library Example
unsigned short i = 0, j = 0;
void main() {
PORTB = 0;
TRISB = 0;
j = 4;
for (i = 0; i < 20u; i++)
EEprom_Write(i, j++);
page
165
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Routines
Flash_Read
Flash_Write
Flash_Read
Example Flash_Read(0x0D00);
Flash_Write
Description Writes chunk of data to Flash memory. With PIC18, data needs to be exactly 64 bytes in
size. Keep in mind that this function erases target memory before writing Data to it.
This means that if write was unsuccessful, previous data will be lost.
// initialize array:
for (i = 0; i < 63; i++) toWrite[i] = i;
Flash_Write(0x0D00, toWrite);
page
166
MikroElektronika: Development tools - Books - Compilers
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.
char i = 0, j = 0;
long addr;
unsigned short dataRd;
unsigned short dataWr[64] =
{1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,
1,2,3,4};
void main() {
PORTB = 0;
TRISB = 0;
PORTC = 0;
TRISC = 0;
addr = 0x00000A30;
for (i = 0; i < 64; i++) {
dataRd = Flash_Read(addr++);
PORTB = dataRd;
Delay_ms(500);
}
}//~!
page
167
MikroElektronika: Development tools - Books - Compilers
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”.
Library Routines
I2C_Init
I2C_Start
I2C_Repeated_Start
I2C_Is_Idle
I2C_Rd
I2C_Wr
I2C_Stop
I2C_Init
Description Initializes I²C with desired clock (refer to device data sheet for correct values in
respect with Fosc). Needs to be called before using other functions of I2C Library.
Example I2C_Init(100000);
page
168
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
I2C_Start
Required I²C must be configured before using this function. See I2C_Init.
Example I2C_Start();
I2C_Repeated_Start
Required I²C must be configured before using this function. See I2C_Init.
Example I2C_Repeated_Start();
I2C_Is_Idle
Required I²C must be configured before using this function. See I2C_Init.
page
169
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
I2C_Rd
Description Reads one byte from the slave, and sends not acknowledge signal if parameter ack is 0,
otherwise it sends acknowledge.
Required START signal needs to be issued in order to use this function. See I2C_Start.
Example temp = I2C_Rd(0); // Read data and send not acknowledge signal
I2C_Wr
Required START signal needs to be issued in order to use this function. See I2C_Start.
Example I2C_Write(0xA3);
I2C_Stop
Required I²C must be configured before using this function. See I2C_Init.
page
170
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Library Example
This code demonstrates use of I²C Library procedures and functions. PIC MCU is
connected (SCL, SDA pins ) to 24c02 EEPROM. Program sends data to EEPROM
(data is written at address 2). Then, we read data via I2C from EEPROM and send
its value to PORTD, to check if the cycle was successful (see the figure below
how to interface 24c02 to PIC).
void main(){
PORTB = 0;
TRISB = 0;
I2C_Init(100000);
I2C_Start(); // Issue I2C start signal
I2C_Wr(0xA2); // Send byte via I2C (command to 24cO2)
I2C_Wr(2); // Send byte (address of EEPROM location)
I2C_Wr(0xf0); // Send data (data to be written)
I2C_Stop();
Delay_ms(100);
page
171
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
HW Connection
PIC16F877A
+5V +5V
MCLR/Vpp/THV RB7/PGD
RA0/AN0 RB6/PGC
10K RA1/AN1
10K
RB5
10K
RA2/AN2/Vref- RB4
RA3/AN3/Vref+ RB3/PGM
RA4/TOCKI RB2
RA5/AN4 RB1
+5V
Reset
RE0/RD/AN5 RB0/INT
RE1/WR/AN6 Vdd
+5V
RE2/CS/AN7 Vss
1 8
Vdd RD7/PSP7
A0 Vcc
2 7 Vss RD6/PSP6
A1 WP
3 6 OSC1 RD5/PSP5
NC SCL
4 5 OSC2 RD4/PSP4
GND SDA RCO/T1OSO RC7/RX/DT
4MHz
RC1/T1OSI RC6/TX/CK
24C04 RC2/CCP1 RC5
RC3 RC4
RD0/PSP0 RD3/PSP3
RD1/PSP1 RD2/PSP2
page
172
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Note: Be sure to designate port with LCD as output, before using any of the fol-
lowing library functions.
Library Routines
LCD_Config
LCD_Init
LCD_Out
LCD_Out_CP
LCD_Chr
LCD_Chr_CP
LCD_Cmd
LCD_Config
Prototype void LCD_Config(char *port, char RS, char EN, char WR, char D7,
char D6, char D5, char D4);
Description Initializes LCD at port with pin settings you specify: parameters RS, EN, WR, D7 .. D4
need to be a combination of values 0–7 (e.g. 3,6,0,7,2,1,4).
Example LCD_Config(PORTD,1,2,0,3,5,4,6);
page
173
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
LCD_Init
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
Description Prints text on LCD at specified row and column (parameter row and col). Both string
variables and literals can be passed as text.
LCD_Out_CP
Description Prints text on LCD at current cursor position. Both string variables and literals can be
passed as text.
page
174
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
LCD_Chr
Description Prints character on LCD at specified row and column (parameters row and col).
Both variables and literals can be passed as character.
LCD_Chr_CP
Description Prints character on LCD at current cursor position. Both variables and literals can be
passed as character.
LCD_Cmd
Description Sends command to LCD. You can pass one of the predefined constants to the function.
The complete list of available commands is shown on the following page.
page
175
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
LCD Commands
page
176
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
void main() {
TRISB = 0; // PORTB is output
LCD_Init(&PORTB); // Initialize LCD connected to PORTB
LCD_Cmd(LCD_CLEAR); // Clear display
LCD_Cmd(LCD_CURSOR_OFF); // Turn cursor off
LCD_Out(1, 1, text); // Print text to LCD, 2nd row, 1st column
}//~!
Hardware Connection
PIC MCU
any port (with 8 pins)
+5V
LCD cont rast
PIC LCD
PIN7 D7
PIN6 D6
PIN5 D5 1
Vss Vdd Vee RS R/W E D0 D1 D2 D3 D4 D5 D6 D7
PIN4 D4
PIN3 E
PIN2 RS m i k ro el E kt ron i ka
PIN1
PIN0
page
177
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
void main() {
TRISD = 0; // PORTD is output
LCD_Config(&PORTD,1,2,0,3,5,4,6); // Initialize LCD on PORTD
LCD_Cmd(LCD_CURSOR_OFF); // Turn off cursor
LCD_Out(1, 1, text); // Print Text at LCD
}
Hardware Connection
PIC MCU
PORTD
+5V
LCD cont rast
PIC LCD
PIN7
PIN6 D4
PIN5 D6 1
Vss Vdd Vee RS R/W E D0 D1 D2 D3 D4 D5 D6 D7
PIN4 D5
PIN3 D7
PIN2 E m i k ro el E kt ron i ka
PIN1 RS
PIN0
page
178
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Note: Be sure to designate Control and Data ports with LCD as output, before
using any of the following functions.
Library Routines
LCD8_Config
LCD8_Init
LCD8_Out
LCD8_Out_CP
LCD8_Chr
LCD8_Chr_CP
LCD8_Cmd
LCD8_Config
Description Initializes LCD at Control port (ctrlport) and Data port (dataport) with pin settings
you specify: Parameters RS, EN, and WR need to be in range 0–7; Parameters D7 .. D0
need to be a combination of values 0–7 (e.g. 3,6,5,0,7,2,1,4).
Example LCD8_Config(PORTC,PORTD,0,1,2,6,5,4,3,7,1,2,0);
page
179
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
LCD8_Init
Description Initializes LCD at Control port (ctrlport) and Data port (dataport) with default pin set-
tings (see the connection scheme at the end of the chapter):
E -> 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.0
LCD8_Out
Description Prints text on LCD at specified row and column (parameter row and col). Both string
variables and literals can be passed as text.
LCD8_Out_CP
Description Prints text on LCD at current cursor position. Both string variables and literals can be
passed as text.
page
180
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
LCD8_Chr
Description Prints character on LCD at specified row and column (parameters row and col).
Both variables and literals can be passed as character.
LCD8_Chr_CP
Description Prints character on LCD at current cursor position. Both variables and literals can be
passed as character.
LCD8_Cmd
Description Sends command to LCD. You can pass one of the predefined constants to the function.
The complete list of available commands is on the page 176.
page
181
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
program LCD8_test;
begin
TRISB := 0; // PORTB is output
TRISC := 0; // PORTC is output
LCD8_Init(PORTB, PORTC); // Initialize LCD at PORTB and PORTC
LCD8_Cmd(LCD_CURSOR_OFF); // Turn off cursor
Text := 'mikroElektronika';
LCD8_Out(1, 1, Text); // Print at LCD
end.
Hardware Connection
PIC MCU
any port (with 8 pins)
PIN0 PIN2 PIN3 PIN0 PIN1 PIN2 PIN3 PIN4 PIN5 PIN6 PIN7
E
R/W
RS
+5V
LCD cont rast
1
Vss Vdd Vee RS R/W E D0 D1 D2 D3 D4 D5 D6 D7
m i k ro el E ktron i ka
page
182
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
program LCD8_test;
var Text: array[17] of char;
begin
TRISB := 0; // PORTB is output
TRISD := 0; // PORTD is output
Hardware Connection
PIC MCU
any port (with 8 pins)
PIN0 PIN2 PIN3 PIN0 PIN1 PIN2 PIN3 PIN4 PIN5 PIN6 PIN7
E
R/W
RS
+5V
LCD cont rast
1
Vss Vdd Vee RS R/W E D0 D1 D2 D3 D4 D5 D6 D7
m i k ro el E ktron i ka
page
183
MikroElektronika: Development tools - Books - Compilers
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 rou-
tines work with commonly used GLCD 128x64, and work only with the PIC18
family.
Note: Be sure to designate port with GLCD as output, before using any of the fol-
lowing library procedures or functions.
Library Routines
Basic routines:
Glcd_Init
Glcd_Set_Side
Glcd_Set_Page
Glcd_Set_X
Glcd_Read_Data
Glcd_Write_Data
Advanced routines:
Glcd_Clear
Glcd_Dot
Glcd_Line
Glcd_V_Line
Glcd_H_Line
Glcd_Rectangle
Glcd_Box
Glcd_Circle
Glcd_Write_Char
Glcd_Write_Text
Glcd_Image
page
184
MikroElektronika: Development tools - Books - Compilers
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 procedure needs to be called befored using other routines of GLCD library.
Glcd_Set_Side
Description Selects side of GLCD, left or right. Parameter x specifies the side: values from 0 to 63
specify the left side, and values higher than 64 specify the right side.
Example The following two lines are equivalent, and select the left side of GLCD:
Glcd_Select_Side(0);
Glcd_Select_Side(10);
page
185
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Glcd_Set_Page
Description Selects page of GLCD, technically a line on display; parameter page can be 0..7.
Example Glcd_Set_Page(5);
Glcd_Set_X
Description Positions to x dots from the left border of GLCD within the given page.
Example Glcd_Set_X(25);
Glcd_Read_Data
Description Positions to x dots from the left border of GLCD within the given page.
Required Reads data from from the current location of GLCD memory.
page
186
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Glcd_Write_Data
Description Writes data to the current location in GLCD memory and moves to the next location.
Example Glcd_Write_Data(data);
Glcd_Clear
Example Glcd_Clear();
Glcd_Dot
Description Draws a dot on the GLCD at coordinates (x, y). Parameter color determines the dot
state: 0 clears dot, 1 puts a dot, and 2 inverts dot state.
Example Glcd_Dot(0, 0, 2); // Invert the dot in the upper left corner
page
187
MikroElektronika: Development tools - Books - Compilers
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).
Glcd_V_Line
Description Similar to GLCD_Line, draws a vertical line on the GLCD from (x, y1) to
(x, y2).
Glcd_H_Line
Description Similar to GLCD_Line, draws a horizontal line on the GLCD from (x1, y) to
(x2, y).
page
188
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Glcd_Rectangle
Description Draws a rectangle on the GLCD. Parameters (x1, y1) set the upper left corner,
(x2, y2) set the bottom right corner. Parameter color defines the border: 0 draws an
empty border (clear dots), 1 draws a solid border (put dots), and 2 draws a “smart” bor-
der (invert each dot).
Glcd_Box
Description Draws a box on the GLCD. Parameters (x1, y1) set the upper left corner, (x2, y2)
set the bottom right corner. Parameter color defines the fill: 0 draws a white box (clear
dots), 1 draws a full box (put dots), and 2 draws an inverted box (invert each dot).
page
189
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Glcd_Circle
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).
Glcd_Write_Char
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).
page
190
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Glcd_Write_Text
Description Prints text at page (one of 8 GLCD lines, 0..7), x dots away from the left border of
display. Parameter color defines the “fill”: 0 prints a “white” letters (clear dots), 1
prints solid letters (put dots), and 2 prints “smart” letters (invert each dot).
Glcd_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.
Example Glcd_Image(my_image);
page
191
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Example
#include "GLCD18.h"
void main() {
do {
// Drawing demo
Glcd_Clear;
Glcd_Box(10,10,30,30,1); // draw filled box
Delay_ms(2000);
Glcd_Box(15,15,25,45,2); // draw another box on top
Glcd_Line(60,10,80,40,1); // draw line
Glcd_Circle(64,32,20,2); // draw circle
// Print a message
Glcd_Write_Text('mikroElektronika',5,3,2);
} while (1);
}
Hardware Connection
"Hello world"
mikroElektronika
K 18 1
GND
VOUT
RESET
CS2
CS1
D7
D6
D5
D4
D3
D2
D1
D0
E
R/ W
RS
Vee
Vcc
10k
GND
10
+ 5V
page
192
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Bi-phase coding
1 0
2.4ms Example of transmission
1 1 0 0 01 0 0 01 1
Library Routines
Man_Receive_Config
Man_Receive_Init
Man_Receive
Man_Send_Config
Man_Send_Init
Man_Send_Byte
page
193
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Man_Receive_Config
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.
Man_Receive_Init
Description The function prepares PIC for receiving signal. You need to specify the port; rxpin is
pin 6 by default. In case of multiple errors on reception, you should call
Man_Receive_Init once again to enable synchronization.
Example Man_Receive_Init(PORTD);
Man_Receive
Description Function extracts one byte from signal. If signal format does not match the expected,
error flag will be set to 255.
Required To use this function, you must first prepare the PIC for receiving. See
Man_Receive_Config or Man_Receive_Init.
page
194
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Man_Send_Config
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.
Man_Send_Init
Description The function prepares PIC for sending signal. You need to specify port for outgoing
signal; txpin is pin 0 by default. Baud rate is const 500 bps.
Example Man_Send_Init(PORTD);
Man_Send_Byte
Required To use this function, you must first prepare the PIC for sending. See
Man_Send_Config or Man_Send_Init.
page
195
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Example
void main() {
ErrorCount = 0;
TRISC = 0; // Error indicator
PORTC = 0;
Man_Receive_Config(PORTD, 6); // Synchronize receiver
LCD_Init(PORTB); // Initialize LCD on PORTB
page
196
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Hardware Connection
RA1/AN1 RB5
RA2/AN2/Vref- RB4
RA3/AN3/Vref+ RB3/PGM
RA4/TOCKI RB2
Vcc
RA5/AN4 RB1
Reset
PIC16F877A
+5V
MCLR/Vpp/THV RB7/PGD
RA0/AN0 RB6/PGC
10K
RA1/AN1 RB5
RA2/AN2/Vref- RB4
RA3/AN3/Vref+ RB3/PGM
Ant en na
RA4/TOCKI RB2
RA5/AN4 RB1
RR3
Reset
RE0/RD/AN5 RB0/INT
RE1/WR/AN6 Vdd
Receiver RF Module +5V
RE2/CS/AN7 Vss
+5V Vdd RD7/PSP7
Vss RD6/PSP6
OSC1 RD5/PSP5
OSC2 RD4/PSP4
RCO/T1OSO RC7/RX/DT
RC1/T1OSI RC6/TX/CK
RC2/CCP1 RC5
RC3 RC4
page
197
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
OneWire Library
OneWire library provides routines for communication via OneWire bus, for exam-
ple 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.
Each OneWire device also has a unique 64-bit registration number (8-bit device
type, 48-bit serial number and 8-bit CRC), so multiple slaves can co-exist on the
same bus.
Note that oscillator frequency Fosc needs to be at least 4MHz in order to use the
routines with Dallas digital thermometers.
Library Routines
OW_Reset
OW_Read
OW_Write
page
198
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
OW_Reset
Description Issues OneWire reset signal for DS1820. Parameters port and pin specify the location
of DS1820.
OW_Read
Returns Data read from an external device over the OneWire bus.
OW_Write
Description Writes one byte of data (argument par) via OneWire bus.
page
199
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Example
unsigned temp;
unsigned short j;
void main() {
ADCON1 = 0xFF; // Configure RA5 pin as digital I/O
PORTA = 0xFF;
TRISA = 0x0F; // PORTA is input
PORTB = 0;
TRISB = 0; // PORTB is output
do { // main loop
OW_Reset(&PORTA,5);
OW_Write(&PORTA,5,0xCC); // Issue command SKIP_ROM
OW_Write(&PORTA,5,0xBE); // Issue command READ_SCRATCHPAD
Delay_ms(400);
} while (1);
}//~!
page
200
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Hardware Connection
+5V
10K
PIC16F877A
MCLR/Vpp/THV RB7/PGD
RA0/AN0 RB6/PGC
RA1/AN1 RB5
RA2/AN2/Vref- RB4
RA3/AN3/Vref+ RB3/PGM
RA4/TOCKI RB2
RA5/AN4 RB1
Reset
RE0/RD/AN5 RB0/INT
RE1/WR/AN6 Vdd
+5V
RE2/CS/AN7 Vss
D7
Vdd RD7/PSP7
D6
Vss RD6/PSP6
DS1820 +5V D5
+125 O
C OSC1 RD5/PSP5
D4
OSC2 RD4/PSP4
RCO/T1OSO RC7/RX/DT
GND
Vdd
DQ
RC1/T1OSI RC6/TX/CK
-55 4MHz
RC2/CCP1 RC5
RC3 RC4
E
RD0/PSP0 RD3/PSP3
RS
RD1/PSP1 RD2/PSP2
4K7
+5V
LCD contrast
1
Vss Vdd Vee RS R/W E D0 D1 D2 D3 D4 D5 D6 D7
m i k ro el E kt ron i ka
page
201
MikroElektronika: Development tools - Books - Compilers
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.
Library Routines
PWM_Init
PWM_Change_Duty
PWM_Start
PWM_Stop
PWM_Init
Description Initializes the PWM module with duty ratio 0. Parameter freq is a desired PWM fre-
quency in Hz (refer to device data sheet for correct values in respect with Fosc).
PWM_Init needs to be called before using other functions from PWM Library.
Required You need a CCP module on PORTC to use this library. Check mikroC installation fold-
er, subfolder “Examples”, for alternate solutions.
page
202
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
PWM_Change_Duty
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.
Required You need a CCP module on PORTC to use this library. To use this function, module
needs to be initalized – see PWM_Init.
PWM_Start
Required You need a CCP module on PORTC to use this library. To use this function, module
needs to be initalized – see PWM_Init.
Example PWM_Start();
PWM_Stop
Required You need a CCP module on PORTC to use this library. To use this function, module
needs to be initalized – see PWM_Init.
Example PWM_Stop();
page
203
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Example
/*The example changes PWM duty ratio on pin RC2 continually. If LED is connected
to RC2, you can observe the gradual change of emitted light. */
char i = 0, j = 0;
main() {
PORTC = 0xFF; // PORTC is output
PWM_Init(5000); // Initialize PWM module at 5KHz
PWM_Start(); // Start PWM
while (1) {
// Slow down, allow us to see the change on LED:
for (i = 0; i < 20; i++) Delay_us(500);
j++;
PWM_Change_Duty(j); // Change duty ratio
}
}
Hardware Connection
PIC16F877A
+5V
MCLR/Vpp/THV RB7/PGD
RA0/AN0 RB6/PGC
10K
RA1/AN1 RB5
RA2/AN2/Vref- RB4
RA3/AN3/Vref+ RB3/PGM
RA4/TOCKI RB2
RA5/AN4 RB1
RE0/RD/AN5 RB0/INT
Reset
RE1/WR/AN6 Vdd
+5V
RE2/CS/AN7 Vss
Vdd RD7/PSP7
Vss RD6/PSP6
OSC1 RD5/PSP5
OSC2 RD4/PSP4
RCO/T1OSO RC7/RX/DT
RC1/T1OSI RC6/TX/CK
RC2/CCP1 RC5
RC3 RC4
330R
page
204
MikroElektronika: Development tools - Books - Compilers
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 con-
nected to a single signal cable. mikroC provides a set of library routines to provide
you comfortable work with RS-485 system using Master/Slave architecture.
Master and Slave devices interchange packets of information, each of these pack-
ets containing synchronization bytes, CRC byte, address byte, and the data. Each
Slave has its unique address and receives only the packets addressed to it. Slave
can never initiate communication. It is programmer’s responsibility to ensure that
only one device transmits via 485 bus at a time.
Note: Address 50 is the common address for all Slaves (packets containing
address 50 will be received by all Slaves). The only exceptions are Slaves with
addresses 150 and 169, which require their particular address to be specified in the
packet.
Library Routines
RS485Master_Init
RS485Master_Receive
RS485Master_Send
RS485Slave_Init
RS485Slave_Receive
RS485Slave_Send
page
205
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
RS485Master_Init
Example RS485Master_Init();
RS485Master_Receive
Description Receives any message sent by Slaves. Messages are multi-byte, so this procedure 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:
Function automatically adjusts data[4] and data[5] upon every received message.
These flags need to be cleared from the program.
page
206
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
RS485Master_Send
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).
It is programmer’s responsibility to ensure (by protocol) that only one device sends data
via 485 bus at a time.
RS485Slave_Init
Description Initializes MCU as Slave with a specified address in RS-485 communication. Slave
address can take any value between 0 and 255, except 50, which is common address
for all slaves.
page
207
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
RS485Slave_Receive
Description Receives message addressed to it. Messages are multi-byte, so this procedure 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:
Function automatically adjusts data[4] and data[5] upon every received message.
These flags need to be cleared from the program.
RS485Slave_Send
Description Sends data from buffer to Master via RS-485; datalen is a number of bytes in mes-
sage (1 <= datalen <= 3).
It is programmer’s responsibility to ensure (by protocol) that only one device sends data
via 485 bus at a time.
page
208
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Library Example
unsigned short dat[8]; // buffer for receiving/sending messages
char i = 0, j = 0;
void interrupt(void) {
/* Every byte is received by RS485Slave_Read(dat);
If message is received without errors,
data[4] is set to 255 */
main() {
TRISB = 0;
TRISD = 0;
USART_Init(9600); // Initialize usart module
RS485Slave_Init(160); // Initialize MCU as Slave with address 160
SetBit(PIE1, RCIE); // Enable interrupt
SetBit(INTCON, PEIE); // on byte received
ClearBit(PIE2, TXIE); // via USART (RS485)
SetBit(INTCON, GIE);
PORTB = 0;
PORTD = 0;
dat[4] = 0; // Ensure that msg received flag is 0
dat[5] = 0; // Ensure that error flag is 0
while (1) {
if dat[5] PORTD = 0xAA; // If there is error, set PORTD to $AA
if dat[4] { // If message received:
dat[4] = 0; // Clear message received flag
j = dat[3]; // Number of data bytes received
for (i = 1; i < j; i++)
PORTB = dat[--i]; // Output received data bytes
dat[0]++; // Increment received dat[0]
RS485Slave_Write(dat, 1); // Send it back to Master
}
}
}
page
209
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Hardware Connection
RA1/AN1 RB5
be connected to
RA2/AN2/Vref- RB4 +5V
RS485 line
RA3/AN3/Vref+ RB3/PGM
RA4/TOCKI RB2
RA5/AN4 RB1
10K
+5V
Reset
RE0/RD/AN5 RB0/INT
RE1/WR/AN6 Vdd
+5V
RE2/CS/AN7 Vss
R0 Vcc
Vdd RD7/PSP7
RE B
Vss RD6/PSP6
DE A
OSC1 RD5/PSP5 GND
DI
OSC2 RD4/PSP4
RCO/T1OSO RC7/RX/DT LTC485
4MHz
RC1/T1OSI RC6/TX/CK
RC2/CCP1 RC5
Shielded pair
RC3 RC4
less than 300m
RD0/PSP0 RD3/PSP3
long
RD1/PSP1 RD2/PSP2
4.7uF +5V
+
620R
C1+ Vcc R0 Vcc
+
4.7uF
V+ GND RE B
C1- T1out DE A
+
4.7uF
page
210
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Routines below are intended for PIC MCUs with MSSP module. By using these,
you can configure and use PIC MCU as master in I²C communication.
Library Routines
Soft_I2C_Config
Soft_I2C_Start
Soft_I2C_Read
Soft_I2C_Write
Soft_I2C_Stop
Soft_I2C_Config
Prototype void Soft_I2C_Config(char *port, const char SDI, const char SD0,
const char SCK);
Description Configures software I²C. Parameter port specifies port of MCU on which SDA and SCL
pins are located. Parameters SCL and SDA need to be in range 0–7 and cannot point at
the same pin.
Soft_I2C_Config needs to be called before using other functions from Soft I2C
Library.
page
211
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Soft_I2C_Start
Description Issues START signal. Needs to be called prior to sending and receiving data.
Required Soft I²C must be configured before using this function. See Soft_I2C_Config.
Example Soft_I2C_Start();
Soft_I2C_Read
Description Reads one byte from the slave, and sends not acknowledge signal if parameter ack is 0,
otherwise it sends acknowledge.
Required START signal needs to be issued in order to use this function. See Soft_I2C_Start.
page
212
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Soft_I2C_Write
Required START signal needs to be issued in order to use this function. See Soft_I2C_Start.
Example Soft_I2C_Write(0xA3);
Soft_I2C_Stop
Required START signal needs to be issued in order to use this function. See Soft_I2C_Start.
Example Soft_I2C_Stop();
page
213
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Example
void main() {
}//~!
page
214
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Library Routines
Soft_SPI_Config
Soft_SPI_Read
Soft_SPI_Write
Soft_SPI_Config
Prototype void Soft_SPI_Config(char *port, const char SDI, const char SD0,
const char SCK);
Description Configures and initializes software SPI. Parameter port specifies port of MCU on which
SDI, SDO, and SCK pins will be located. Parameters SDI, SDO, and SCK need to be in
range 0–7 and cannot point at the same pin.
Soft_SPI_Config needs to be called before using other functions from Soft SPI
Library.
Example This will set SPI to master mode, clock = 50kHz, data sampled at the middle of interval,
clock idle state low and data transmitted at low to high edge. SDI pin is RB1, SDO pin
is RB2 and SCK pin is RB3:
Soft_SPI_Config(PORTB, 1, 2, 3);
page
215
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Soft_SPI_Read
Required Soft SPI must be initialized and communication established before using this function.
See Soft_SPI_Config.
Soft_SPI_Write
Required Soft SPI must be initialized and communication established before using this function.
See Soft_SPI_Config.
Example Soft_SPI_Write(1);
page
216
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Library Example
unsigned value;
void InitMain() {
Soft_SPI_Config(&PORTB, 4,5,3);
TRISB &= ~(_CHIP_SELECT); // ClearBit(TRISC,CHIP_SELECT);
TRISC = 0x03;
}//~
void main() {
InitMain();
DAC_Output(2048); // When program starts, DAC gives
value = 2048; // the output in the mid-range
page
217
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Routines
Soft_UART_Init
Soft_UART_Read
Soft_UART_Write
Soft_UART_Init
Prototype void Soft_UART_Init(char *port, const char rx, const char tx,
const char baud_rate);
Description Initalizes software UART. Parameter port specifies port of MCU on which RX and TX
pins are located; parameters RX and TX need to be in range 0–7 and cannot point at the
same pin; baud_rate is the desired baud rate. Maximum baud rate depends on PIC’s
clock and working conditions.
Soft_UART_Init needs to be called before using other functions from Soft UART
Library.
page
218
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Soft_UART_Read
Description Function receives a byte via software UART. Parameter msg_received will be not-
zero if transfer was successful. This is a non-blocking function call, so you should test
msg_received manually (check the example below).
Required Soft UART must be initialized and communication established before using this func-
tion. See Soft_UART_Init.
do
data = Soft_UART_Read(received);
while (!received);
Soft_UART_Write
Required Soft UART must be initialized and communication established before using this func-
tion. See Soft_UART_Init.
Be aware that during transmission, software UART is incapable of receiving data – data
transfer protocol must be set in such a way to prevent loss of information.
page
219
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
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.
void main() {
recOK = &ro;
do {
do {
data = Soft_UART_Read(recOK); // Receive data
} while (!*recOK);
Soft_UART_Write(data); // Send data via UART
} while (1)
}//~!
page
220
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Sound Library
mikroC provides a Sound Library which allows you to use sound signalization in
your applications. You need a simple piezo speaker (or other hardware) on desig-
nated port.
Library Routines
Sound_Init
Sound_Play
Sound_Init
Description Prepares hardware for output at specified port and pin. Parameter pin needs to be within
range 0–7.
Sound_Play
Description Plays the sound at the specified port and pin (see Sound_Init). Parameter period_div_10
is a sound period given in MCU cycles divided by ten, and generated sound lasts for a
specified number of periods (num_of_periods).
Required To hear the sound, you need a piezo speaker (or other hardware) on designated port.
Also, you must call Sound_Init to prepare hardware for output.
Example To play sound of 1KHz: T = 1/f = 1ms = 1000 cycles @ 4MHz. This gives us our first
parameter: 1000/10 = 100. Play 150 periods like this:
Sound_Play(100, 150);
page
221
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Example
The example is a simple demonstration of how to use sound library for playing
tones on a piezo speaker. The code can be used with any MCU that has PORTB
and ADC on PORTA. Sound frequencies in this example are generated by reading
the value from ADC and using the lower byte of the result as base for T (f = 1/T).
int adcValue;
void main() {
page
222
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
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 convert-
ers, MAX7219, LTC1290, etc. You need PIC MCU with hardware integrated SPI
(for example, PIC16F877).
Note: This library supports module on PORTB or PORTC, and will not work with
modules on other ports. Examples for PICmicros with module on other ports can
be found in your mikroC installation folder, subfolder “Examples”.
Library Routines
SPI_Init
SPI_Init_Advanced
SPI_Read
SPI_Write
SPI_Init
Default settings are: Master mode, clock Fosc/4, clock idle state low, data transmitted on
low to high edge, and input data sampled at the middle of interval.
Example SPI_Init();
page
223
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
SPI_Init_Advanced
Parameter mast_slav determines the work mode for SPI; can have the values:
The data_sample determines when data is sampled; can have the values:
Parameter clock_idle determines idle state for clock; can have the following values:
Example This will set SPI to master mode, clock = Fosc/4, data sampled at the middle of interval,
clock idle state low and data transmitted at low to high edge:
SPI_Init_Advanced(MASTER_OSC_DIV4, DATA_SAMPLE_MIDDLE,
CLK_IDLE_LOW, LOW_2_HIGH)
page
224
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
SPI_Read
Description Provides clock by sending buffer and receives data at the end of period.
Required SPI must be initialized and communication established before using this function. See
SPI_Init_Advanced or SPI_Init.
SPI_Write
Description Writes byte data to SSPBUF, and immediately starts the transmission.
Required SPI must be initialized and communication established before using this function. See
SPI_Init_Advanced or SPI_Init.
Example SPI_Write(1);
page
225
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Library Example
The code demonstrates how to use SPI library procedures and functions. Assumed
HW configuration is: max7219 (chip select pin) connected to RC1, and SDO, SDI,
SCK pins are connected to corresponding pins of max7219.
char i;
void main() {
SPI_Init(); // Standard configuration
TRISC &= 0xFD;
max7219_init1(); // Initialize max7219
for (i = 1; i <= 8u; i++) {
PORTC &= 0xFD; // Select max7219
SPI_Write(i); // Send i to max7219 (digit place)
SPI_Write(8 - i); // Send i to max7219 (digit)
PORTC |= 2; // Deselect max7219
}
TRISB = 0;
PORTB = i;
}//~!
page
226
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple...
HW Connection
MAX7219
DIN DOUT
DIG0 SEGD
DIG4 SEGDP
8. 8. 8. 8. 8. 8. 8. 8.
GND SEGE
DIG6 SEGC
DIG2 V+ +5V
10K
DIG3 ISET
DIG7 SEGG
PIC16F877A
10K
GND SEGB
DIG5 SEGF
DIG1 SEGA MCLR/Vpp/THV RB7/PGD
LOAD CLK RA0/AN0 RB6/PGC
RA1/AN1 RB5
Reset
RA2/AN2/Vref- RB4
RA3/AN3/Vref+ RB3/PGM
RA4/TOCKI RB2
RA5/AN4 RB1 g f K a b
RE0/RD/AN5 RB0/INT
RC2/CCP1 RC5
RC3 RC4
RD0/PSP0 RD3/PSP3 d dp
RD1/PSP1 RD2/PSP2
e d K c dp
8
page
227
mikroC - C Compiler for Microchip PIC microcontrollers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
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.
Then, simply use the functions listed below.
Library Routines
USART_Init
USART_Data_Ready
USART_Read
USART_Write
Note: Certain PICmicros with two USART modules, such as P18F8520, require
you to specify the module you want to use. Simply append the number 1 or 2 to a
function name. For example, USART_Write2();
USART_Init
Description Initializes hardware USART module with the desired baud rate. Refer to the device data
sheet for baud rates allowed for specific Fosc. If you specify the unsupported baud rate,
compiler will report an error.
USART_Init needs to be called before using other functions from USART Library.
page
228
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
USART_Data_Ready
Required USART HW module must be initialized and communication established before using
this function. See USART_Init.
USART_Read
Description Function receives a byte via USART. Use the function USART_Data_Ready to test if
data is ready first.
Required USART HW module must be initialized and communication established before using
this function. See USART_Init.
page
229
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
USART_Write
Required USART HW module must be initialized and communication established before using
this function. See USART_Init.
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.
unsigned short i;
void main() {
do {
if (USART_Data_Ready()) { // If data is received
i = USART_Read(); // Read the received data
USART_Write(i); // Send data via USART
}
} while (1);
}//~!
page
230
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Hardware Connection
PIC16F877A
4.7uF +5V +5V
+
MCLR/Vpp/THV RB7/PGD
RA0/AN0 RB6/PGC
10K
RA1/AN1 RB5
C1+ Vcc RA2/AN2/Vref- RB4
4.7uF
+ V+ GN
D RA3/AN3/Vref+ RB3/PGM
SUB-D 9-pin connector C1- T1out
RA4/TOCKI RB2
+
4.7uF
C2+ R1in
RA5/AN4 RB1
C2- R1out
RE0/RD/AN5 RB0/INT
Reset
1
6 V- T1in
2 RE1/WR/AN6 Vdd
7
T2out T2in +5V
3 RE2/CS/AN7 Vss
R2in R2out
8 Vdd RD7/PSP7
4.7uF
4
9 + Vss RD6/PSP6
5 MAX232
OSC1 RD5/PSP5
OSC2 RD4/PSP4
RCO/T1OSO RC7/RX/DT
serial cable RC1/T1OSI RC6/TX/CK
(1 to 1) RC2/CCP1 RC5
RC3 RC4
1
6 4MHz RD0/PSP0 RD3/PSP3
Receive data (Rx)
2
7 RD1/PSP1 RD2/PSP2
3 Send data (Tx)
8
4
9
5
page
231
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Conversions Library
mikroC Conversions Library provides routines for converting numerals to strings,
and routines for BCD/decimal conversions.
Library Routines
You can get text representation of numerical value by passing it to one of the fol-
lowing routines:
ByteToStr
WordToStr
IntToStr
Following functions convert decimal values to BCD (Binary Coded Decimal) and
vice versa:
Bcd2Dec
Dec2Bcd
Bcd2Dec16
Dec2Bcd16
ByteToStr
Description Function creates string str out of parameter num. String is filled from left to right with
digits/characters, up to the number of digits in num. String will be automatically append-
ed a necessary '0'.
Example char t;
...
t = 24;
...
ByteToStr(t, text); // Create text "24"
LCD_Out_CP(text); // Print "24" on LCD
page
232
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
WordToStr
Description Function creates string str out of parameter num. String is filled from left to right with
digits/characters, up to the number of digits in num. String will be automatically append-
ed a necessary '0'.
Example unsigned j;
...
j = 7200;
...
WordToStr(j, text); // Create text "7200"
LCD_Out_CP(text); // Print "7200" on LCD
IntToStr
Description Function creates string str out of parameter num. String is filled from left to right with
digits/characters, up to the number of digits in num. String will be automatically append-
ed a necessary '0'.
Example int j;
...
j = -1022;
...
IntToStr(j, text); // Create text "-1022"
LCD_Out_CP(text); // Print "-1022" on LCD
page
233
MikroElektronika: Development tools - Books - Compilers
mikroC
mikroC - C Compiler for Microchip PIC microcontrollers making it simple...
Bcd2Dec
Dec2Bcd
Bcd2Dec16
Example unsigned a;
...
a = Bcd2Dec16(1234); // equals 4660
page
234
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
Dec2Bcd16
Example unsigned a;
...
a = Dec2Bcd16(4660); // equals 1234
page
235
MikroElektronika: Development tools - Books - Compilers
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);
Description Function eliminates the influence of contact flickering upon pressing a button (debounc-
ing).
Parameters port and pin specify location of the button; parameter time specifies the
minimum time pin has to be in active state in order to return TRUE; parameter
active_state can be either 0 or 1, and it determines if button is active upon logical
zero or logical one.
Example Example reads RB0, to which the button is connected; on transition from 1 to 0 (release
of button), PORTD is inverted:
do {
if Button(&PORTB, 0, 1, 1) oldstate = 1;
if (oldstate && Button(&PORTB, 0, 1, 0)) {
PORTD = 0;
oldstate = 0;
}
} while(1);
page
236
MikroElektronika: Development tools - Books - Compilers
mikroC
making it simple... mikroC - C Compiler for Microchip PIC microcontrollers
page
237
MikroElektronika: Development tools - Books - Compilers
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 addi-
tional information, please let us know.
If you are experiencing any trouble with mikroC, please do not hesitate to con-
tact us - it is in our mutual interest to solve these issues.
If you want to report a delay in delivery or any other problem concerning distri-
bution of our products, please use the link given below.
Other
If you have any other question, comment or a business proposal, please contact
us:
mikroElektronika
Admirala Geprata 1B
11000 Belgrade
EUROPE
page
238
MikroElektronika: Development tools - Books - Compilers