Professional Documents
Culture Documents
Microcontroller
Course
By Eng
Ahmed Sheimy
Microcontroller Course Interfacing Hardware and Software
Table Of Contents
2.1- INTRODUCTION ............................................................................................................................. 8
2.2.11-OSCILLATOR .............................................................................................................................................. 15
2.2.13- TIMERS..................................................................................................................................................... 16
2.3-SUMMARY ....................................................................................................................................... 18
3.2.2-Cuircuit ....................................................................................................................................................... 20
3.2.2.1-ISIS Simulation Circuit .................................................................................................................................20
3.2.2.2-Practical Circuit ..........................................................................................................................................20
3.2.2.3-MikroC code ................................................................................................................................................21
3.3.1-Keywords .................................................................................................................................................... 22
3.3.3-Variables ..................................................................................................................................................... 23
3.3.4-Constant ..................................................................................................................................................... 24
3.3.8-Strings......................................................................................................................................................... 29
3.3.9-Enumeration ............................................................................................................................................... 29
3.3.10-Arrays ....................................................................................................................................................... 29
3.3.10.1-One-Dimensional ARRAY ...........................................................................................................................30
3.3.10.2- Two-Dimensional ARRAY..........................................................................................................................30
3.3.20 – Good Expression for working with variable and operator ....................................................................... 37
3.3.22-Preprocessor ............................................................................................................................................. 47
3.3.22.1-File Inclusion .............................................................................................................................................47
3.3.22.2-Preprocessor Operators ............................................................................................................................48
Table of Figures
FIGURE 1 MICROCONTROLLER ...............................................................................................................................8
FIGURE 2 ARCHITECTURE OF 8-BIT PIC MICROCONTROLLER .........................................................................10
FIGURE 3 CPU .........................................................................................................................................................11
FIGURE 4 REGISTER .............................................................................................................................................11
FIGURE 5 SPECIAL FUNCTION REGISTERS ......................................................................................................12
FIGURE 6 INPUT / OUTPUT PORTS .............................................................................................................12
FIGURE 7 MEMORY UNIT.................................................................................................................................13
FIGURE 8 SERIAL COMMUNICATION ........................................................................................................13
FIGURE 9 I2C ...........................................................................................................................................................14
FIGURE 10 SPI .........................................................................................................................................................14
FIGURE 11 OSCILLATOR ....................................................................................................................................15
FIGURE 12 TIMERS ..............................................................................................................................................16
FIGURE 13 WATCHDOG TIMER ....................................................................................................................17
FIGURE 14 A/D CONVERTER ..........................................................................................................................17
FIGURE 1 ISIS SIMULATION CIRCUIT ..................................................................................................................20
FIGURE 2 PRACTICAL CIRCUIT + POWE CIRCUIT ..............................................................................................21
FIGURE 3 DECIMAL NUMBER ...............................................................................................................................25
FIGURE 4 DECIMAL CONVERSION ........................................................................................................................25
FIGURE 5 BINARY CONVERSION ...........................................................................................................................26
FIGURE 6 HEX CONVERSION .................................................................................................................................27
FIGURE 7 CONVERSION CODE – CHART .............................................................................................................27
FIGURE 8 USING DIRECTIVE CIRCUIT ..................................................................................................................49
Table OF Tables
TABLE 1 C KEYWORDS................................................................................................ 22
TABLE 2 INTEGRAL TYPES ............................................................................................ 23
TABLE 3 FLOATING-POINT TYPES .................................................................................. 23
TABLE 4 DIFRRENT BETWEEN VARIABLE AND CONST .......................................................... 24
TABLE 5 SPECHIAL CHAR FORMAT ................................................................................. 28
TABLE 6 ARITHMETIC OPERATORS................................................................................. 31
TABLE 7 RELATIONAL OPERATORS ................................................................................. 32
TABLE 8 RELATIONAL OPERATORS EXAMPLES .................................................................. 32
TABLE 9 BITWISE OPERATORS ...................................................................................... 32
TABLE 10 BITWISE AND TRUTH TABLE ........................................................................... 33
TABLE 11 BITWISE OR (&) TRUTH TABLE........................................................................ 33
TABLE 12 BITWISE EXCLUSIVE OR (XOR ^) TRUTH TABLE ................................................... 33
TABLE 13 BITWISE COMPLEMENT (~) TRUTH TABLE ........................................................... 33
TABLE 14 LOGICAL OPERATORS .................................................................................... 34
TABLE 15 LOGICAL AND TRUTH TABLE ........................................................................... 34
TABLE 16 OGICAL AND EXAMPLE ................................................................................. 34
TABLE 17 OGICAL OR TRUTH TABLE ............................................................................... 34
TABLE 18 LOGICAL OR EXAMPLE ................................................................................. 35
TABLE 19 LOGICAL NEGATION TRUTH TABLE ..................................................................... 35
TABLE 20 OGICAL NEGATION EXAMPLE ........................................................................... 35
TABLE 21 DIFFERENT BETWEEN (=) AND (==) .................................................................. 37
Table Of Codes
CODE 1 :FIRST PROJECT ....................................................................................................................................................21
CODE 2: DEFINING VARIABLE..............................................................................................................................................23
CODE 3: INITIALIZE VARIABLE .............................................................................................................................................24
CODE 4: CONSTANT .........................................................................................................................................................24
CODE 5: COMMON PROGRAMMING ERROR 1 .......................................................................................................................24
CODE 6: DECIMAL............................................................................................................................................................25
CODE 7: BINARY ..............................................................................................................................................................26
CODE 8: HEX..................................................................................................................................................................26
CODE 9: CHAR ................................................................................................................................................................27
CODE 10: /N CODE .........................................................................................................................................................28
CODE 11 : COMMON PROGRAMMING ERROR 2 ....................................................................................................................28
CODE 12: SOLUTION OF COMMON PROGRAMMING ERROR 2 ...................................................................................................28
CODE 13 : AT COMMAND EXAMPE .....................................................................................................................................29
CODE 14 : STRING ...........................................................................................................................................................29
CODE 15 : STRING FORMAT ...............................................................................................................................................29
CODE 16 : ENUMERATION .................................................................................................................................................29
CODE 17 : DEFINE ARRAY...................................................................................................................................................30
CODE 18: ARRAY EXAMPLE ................................................................................................................................................30
CODE 19 : INITIALIZE ELEMENT ...........................................................................................................................................30
CODE 20 : GET DATA FROM ADDRESS ...................................................................................................................................30
CODE 21 : DEFINE TWO-DIMENSIONAL ARRAY ....................................................................................................................30
CODE 22 : TWO DIMENSION ARRAY EXAMPLE ........................................................................................................................30
CODE 23 :LOGICAL AND CODE EXAMPLE ............................................................................................................................34
CODE 24 : LOGICAL OR CODE EXAMPLE ..............................................................................................................................35
CODE 25 : LOGICAL NEGATION CODE EXAMPLE .....................................................................................................................35
CODE 26 :CONDITIONAL OPERATOR ? :................................................................................................................................36
CODE 27 :CONDITIONAL OPERATOR ? : EXAMPLE ..................................................................................................................36
CODE 28 :ASSIGNMENT OPERATOR.....................................................................................................................................36
CODE 29: SIZEOF OPERATOR EXAMPLES ..............................................................................................................................37
CODE 30 : MORE ONE WAY TO DEFINE VARIABLE ....................................................................................................................38
CODE 31 : LABELED STATEMENTS IDENTIFIRE ........................................................................................................................38
CODE 32 :LABELED STATEMENTS EXAMPLE ...........................................................................................................................38
CODE 33 : IF STATEMENT IDENTIFIRE ...................................................................................................................................38
CODE 34 : IF STATEMENT EXAMPLE ....................................................................................................................................38
CODE 35 :IF-ELSE STATEMENT IDENTIFIER.............................................................................................................................39
CODE 36 :IF-ELSE STATEMENT EXAMPLE .............................................................................................................................39
CODE 37 : NESTED IF STATEMENTS .....................................................................................................................................39
CODE 38 : SWITCH STATEMENT IDENTIFIER ..........................................................................................................................40
CODE 39 :SWITCH STATEMENT EXAMPLE ............................................................................................................................40
CODE 40 :SWITCH STATEMENT GOOD EXAMPLE ...................................................................................................................41
CODE 41 :WHILE STATEMENT ............................................................................................................................................41
CODE 42 : WHILE STATEMENT EXAMPLE ..............................................................................................................................42
Lect 2
PIC Microcontroller
2.1- Introduction
The pic microcontroller is a chip that has an Input and an Output pins, we can used it in very large
number of Projects Specially Smart Projects, and to know how to use this chip we must know what is
inside it and how to use what is inside it .the following Figure will show you what is inside but not in
Details
Figure 1 Microcontroller
As shown in the above Figure the Microcontroller is look like a microcomputer, but with limited Features
like the RAM, ROM and Microprocessor but it is very small compared with that of the Computer, also it
has a features that is not available in the Computer like Analog to Digitals Converter and the interfacing
with Devices to control in it, also to get data from Devices Connected to it, and finally the prices is not
comparable.
From the above Figure we see that the microcontroller has large number of register that used to
perform the various operations and the following is some important of them.
2.2.1- CPU
The CUP is the Manger that control all operation inside the Microcontroller, it contain the ALU unite that
perform all arithmetic and logic operation, also it contain the Accumulator register which also called the
‘W’ register that is used to save the result of operation like (Add, Sub, mov),the CPU inside the
microcontroller is like the following
Figure 3 CPU
2.2.2- REGISTER
Registers is a 8 bit memory that can be used so that the CPU can save data in it also we can get it back
again, it is like the following Figure
Figure 4 REGISTER
From the above Figure we see that the special function register is used to control in other parts inside
the microcontroller.
2.2.6- INTERRUPT
If the microcontroller was doing something, and we want it when an important thing occur to stop
executing the current event and to do another important, this operation is called the interrupt, as an
example if we have a ROBOT that search for Landmines and we want it to stop its motion when it is
detect a mines it is important to use the interrupt because if we don’t stop the motion in this time the
ROBOT maybe Destroyed.
2.2.7-SERIAL COMMUNICATION
Parallel connection between the microcontroller and peripherals via input/output ports is the ideal
solution on shorter distances up to several meters. However, in other cases when it is necessary to
establish communication between two devices on longer distances it is not possible to use parallel
connection. Instead, serial communication is used.
One of the most important things concerning serial communication is the Protocol which should be
strictly observed. It is a set of rules which must be applied in order that devices can correctly interpret
data they mutually exchange.
Figure 9 I2C
Figure 10 SPI
2.2.11-OSCILLATOR
Even pulses generated by the oscillator enable harmonic and synchronous operation of all circuits within
the microcontroller. The oscillator is usually configured so as to use quartz crystal or ceramic resonator
for frequency stability, but it can also operate as a stand-alone circuit (like RC oscillator).
Figure 11 OSCILLATOR
1. Brown out is a potentially dangerous condition which occurs at the moment the microcontroller
is being turned off or when the power supply voltage drops to a minimum due to electric noise.
As the microcontroller consists of several circuits with different operating voltage levels, this
state can cause its out-of-control performance. In order to prevent it, the microcontroller
usually has a built-in circuit for brown out reset which resets the whole electronics as soon as
the microcontroller incurs a state of emergency.
2. Reset pin is usually marked as MCLR (Master Clear Reset). It is used for external reset of the
microcontroller by applying a logic zero (0) or one (1) to it, which depends on the type of the
microcontroller. In case the brown out circuit is not built in, a simple external circuit for brown
out reset can be connected to the MCLR pin.
2.2.13- TIMERS
The microcontroller oscillator uses quartz crystal for its operation. Even though it is not the simplest
solution, there are many reasons to use it. The frequency of such oscillator is precisely defined and very
stable, so that pulses it generates are always of the same width, which makes them ideal for time
measurement. Such oscillators are also used in quartz watches. If it is necessary to measure time
between two events, it is sufficient to count up pulses generated by this oscillator. This is exactly what
the timer does.
Figure 12 TIMERS
2.2.14- COUNTERS
If the timer receives pulses from the microcontroller input pin, then it turns into a counter. Obviously, it
is the same electronic circuit able to operate in two different modes. The only difference is that in this
case pulses to be counted come over the microcontroller input pin and their duration (width) is mostly
undefined. This is why they cannot be used for time measurement, but for other purposes such as
counting products on an assembly line, number of axis rotation, passengers etc. (depending on sensor in
use).
2.3-Summary
In this lecture we go inside the microcontroller to show what is the features that it is have and we can
use to perform our tasks we start by the CPU after that we introduce the registers, timers, counters,
memories, and we go to the various type of serial connection and finally we show the analog to digital
features.
Lect 3
Programming the Microcontroller Using
MikroC PRO
In this section we will go to programming the microcontroller using the C language and with MikroC Pro
3.5 Compiler, using previous version of the compiler the codes maybe not successfully compiled, MikroC
Pro compiler is free to try with small Projects but it is limited to 2 Kbyte, we also will show you some of
the very important library that the compiler have and we will need it in interfacing operations, like the
UART library, USB library, RS485 library and ADC library. We will start with the language essential and
the examples for each part using MiKroC Pro.
3.2.2-Cuircuit
In this Project we are going to make a Flasher on PORTB that flashes every one second. The circuit is
shown below.
3.2.2.2-Practical Circuit
3.2.2.3-MikroC code
void main() {
TRISB=0x00; //All PORTB pins as O/P
PORTB=0x00; //Make all PORTB off
while(1){ //infinite LOOP
PORTB=~PORTB; //Complement PORTB
Delay_ms(1000); // Make Delay 1 Sec
}
}
As we see from the previous code that the state of the PORTB (ON/OFF) is change every one second.it is
so easy to be read and understand because it is written by C language .MikroC Pro Enable you to see the
Assembly Code of that Code.
Now and after making the First Project we will have to know the C language essentials to be able to
write a professional project, also to know how to do what we want.
Table 1 C Keywords
Not only the above keywords is reserved but also all relevant SFR are defined as global variables and
represent reserved words that cannot be redefined (for example: TMR0, PCL, etc).
3.3.2-Types in C language
C language have more type of variables we will explore them here, and also we will see an example for
every type and how to use it, all of this using MikroC Pro Compiler.
3.3.2.1-Arithmetic Types
Arithmetic Types is the types that deals with numbers ,but we can use it to create char or string
3.3.2.1.1-Integral Types
Type Size in bytes Range
bit 1–bit 0 or 1
sbit 1–bit 0 or 1
char 1 0 .. 255
signed char 1 - 128 .. 127
short 1 - 128 .. 127
unsigned short 1 0 .. 255
int 2 -32768 .. 32767
unsigned 2 0 .. 65535
long 4 -2147483648 .. 2147483647
unsigned long 4 0 .. 4294967295
Table 2 Integral Types
From the above table we know the type of the integral and the size of them and finally the range for
each type .the size of each type is very important because the memory of the microcontroller is small
and we have a professional code to take small memory.
After explaining the Athematic types we must Explain the variable and the Constant and different
between them.
3.3.3-Variables
Suppose that we have a variable I and we want it to be of type int and another variable l of type float
how we will do this ,it will be like the following
Int i;
float l;
And so on with all types, also we can initialize them and they will be like the following.
Int i=5;
float l=10.0;
3.3.4-Constant
The constant from its name its value can’t be changed inside the program, it is defined as the following
Code 4: Constant
If the variable is defined as a const its value can’t change inside the program, the following code will not
compiled for this reason.
void main() {
The important different is the memory Location ,for example if we want to display image on GLCD this
image will be an Array of numbers represent the image ,this number will not change and will take a large
space in the RAM , so we define it as const to store it in the ROM .another Example is the Led Matrix ,it
3.3.6-Number Representation
We can represent the number in more than one format, like Decimal, Hex and binary ,the previous three
types is the most common ,in the following we will show each type and how to convert between them,
the used compiler in this book (MikroC Pro) have its own converter that enable us converting between
them Quickly.
Suppose that we have a variable i and its value is 255(i=255) we will know how to present it in the
previous format.
3.3.6.1-Decimal
The Decimal format of 255 will be as it is 255,and it is written like the following in the used compiler
i=255;
Code 6: Decimal
Each number systems has a base which used to obtain the value of the number, the base of the Decimal
number is (10),but how to obtain the value? It is like the following.
3.3.6.2-Binary
The binary format of 255 is 11111111, and it is written as the following in MikroC Pro
i=0b11111111;
Code 7: Binary
To know how the conversion is done, we should know the base of the binary number which is (2), and to
obtain the value it is like the following.
1*1+1*2+1*4+1*8+1*16+1*32+1*64+1*128=255
3.3.6.3-HexDecimal
The most preferred number format, the Hex format of 255 decimal number is FF, and it is written as the
following:
i=0xFF;
Code 8: Hex
To know how the conversion is done, we should know the base of the binary number which is (16) it
takes the value from 0 to 9 plus A,B,C,D,E and F. and to obtain the value it is like the following.
F*1+F*16= 15*1+15*16=255
char i=’A’;
Code 9: Char
A backslash character (\) is used to introduce an escape sequence, this escape sequence is shown in the
following table
And the following is some examples of how to use them in our codes.
1-\n
It is very important, the meaning of it is that the next writing operation will be in new line , as an
example.
UART1_Write('\n'); //Send this via Serial PORT
When this data received on the PC there is nothing to display but the received data after this will be
displayed on new line
Lcd_Out_Cp("\x091.0 Intro");
This is intended to be interpreted as \x09 and "1.0 Intro". However, the mikroC PRO for PIC compiles it
as the hexadecimal number \x091 and literal string ".0 Intro". To avoid such problems, we could rewrite
the code in the following way:
UART1_Write('A’);
UART1_Write('T');
UART1_Write('\r');
UART1_Write('\n');
Code 14 : String
is equivalent to
"This is just an example."
And we can divide string between two line using \ like the following.
"This is really \
a one-line string."
3.3.9-Enumeration
Enumeration is a good to be used to manage our and make it very simple to understand .to show this
look at the following Example
Code 16 : Enumeration
3.3.10-Arrays
arrays are probably the most commonly used composite data type, we can define array as the following.
3.3.10.1-One-Dimensional ARRAY
component_type array_name [number_of_components];
char A[4];
As shown the array is store more than one element of the same type and to access them easily using
their Address, but how to put data in element and how to get it again? The following is two examples to
show this.
Tb[0][0] Tb[0][1]
Tb[1][0] Tb[1][1]
Tb[2][0] Tb[2][1]
If we have a=5 and b=8 the following is how this operator effect.
a+b=5+8=13
b-a=8-5=3
a*b=5*8=40
b/a=8/5=1
b%a=8%5=3
+a=+5=5
-a= -5
The following is some examples that show you how to use them.
Operator Operation
& bitwise AND; compares pairs of bits and returns 1 if both bits are 1, otherwise returns 0
| bitwise (inclusive) OR; compares pairs of bits and returns 1 if either or both bits are 1,
otherwise returns 0
^ bitwise exclusive OR (XOR); compares pairs of bits and returns 1 if the bits are
complementary, otherwise returns 0
~ bitwise complement (unary); inverts each bit
<< Bitwise shift left; moves the bits to the left, discards the far left bit and assigns 0 to the far
right bit.
>> bitwise shift right; moves the bits to the right, discards the far right bit and if unsigned
assigns 0 to the far left bit, otherwise sign extends
Table 9 Bitwise Operators
0b10101000
0b00001010
3.3.14-Logical Operators
The logical operators is used to check for two or more conditions to be satisfied in the time or one of
them satisfied , this will be shown below.
Operator Operation
&& logical AND
|| logical OR
! logical negation
&& 0 x
0 0 0
x 0 1
Table 15 logical AND truth table
Operation Result
a && b 0
a && c 1
Table 16 ogical AND Example
// write what you want to do here if the two conditions are true
3.3.14.1- logical OR
logical OR is used to check if one of two or more conditions satisfy in the same time or not, the truth
table of logical OR is below.
|| 0 x
0 0 1
x 1 1
Table 17 ogical OR truth table
Operation Result
a || b 1
a || c 1
If(a==4 || b==9)
// write what you want to do here if one of the two conditions are true
! 0 x
1 0
Table 19 logical negation truth table
Operation Result
!a 0
!b 1
Table 20 ogical negation Example
If(! a)
Assume a =5 and b =6
a && b = 1 //both variables are true (>1)
a & b= ???
To do this operation we convert both of a and b to the binary format
0000 0101
&
0000 0110
---------------
0000 0100
So a & b =4
The expression1 is evaluated first. If its value is true, then expression2 evaluates and expression3 is
ignored. If expression1 evaluates to false, then expression3 evaluates and expression2 is ignored. The
result will be a value of either expression2 or expression3 depending upon which of them evaluates.
s an example if we want to get the maximum value from two values using the conditional operator ? : It
will be like the following.
The above code means that save the value of expression2 in expression1
Example Meaning
a=b Get the value of b and save it to a
a == b Check the value of a and b if they are equal or not
Table 21 different between (=) and (==)
sizeof(char) /* returns 1 */
sizeof(int) /* returns 2 */
sizeof(unsigned long) /* returns 4 */
sizeof(float) /* returns 4 */
char a;
char b;
char a,b;
char a=5;
char b=6;
char a=5,b=6;
label_identifier: statement;
And as an Example:
ahmed: a=10;
1-it is important to use the jump statement like goto as we will see in the following subsections
3.3.21.2.1-IF Statement
It is used to test a condition it is defined as the following condition
if (expression) statement1;
If expression is true statement1 will be executed by the code else the next code statements will be
executed. And as an example
if (a == 5)a=0;
3.3.21.2.2-IF-else statement
It is used to test a condition and if it is not true the statements inside else will execute.it is defined as
the following
if (expression){
else {
f expression is true statement1 will be executed by the code else the code statements inside else will be
executed. And as an example:
if (a == 5)a=0;
else a++;
3.3.21.2.3-Nested If statements
In Nested if statements we can use more than one if and more than one else so it required special
attention, for more details look at the following Example:
if (expression1) statement1
else if (expression2)
if (expression3) statement2
switch (expression) {
default : statement;
}
Code 38 : Switch Statement Identifier
First expression is evaluated the corresponding case will be evaluated; the following is an example that
show you how.
switch (i) {
case 1: i+=1;
case 2: i+=2;
case 3: i+=3;
default : i=0;
In the previous example if the value of i was 1 statement after case 1 will evaluated and so on. And if
there is no case corresponding to the value of I the statement after the default will be evaluated.
To avoid evaluating any other cases and to get out from switch statement after the case that is
corresponding to the condition is evaluated each case must end by break statement, without break
statement the code is correct but not good as we have to evaluate all remaining cases before getting out
from the switch statement. It will be like the following.
switch (i) {
case 1: i+=1;
break;
case 2: i+=2;
break;
case 3: i+=3;
break;
default : i=0;
3.3.21.3.1-While Statement
While Statement is a loop statement it is defined as the following.
while (expression)
Statement;
And as an example .
PORTB=I;
i++;
In the previous example what is inside the while loop will evaluated 100 times tell the value of I will be
large than 100.
3.3.21.3.2-do-While Statement
Do-while statement is like while but it is defined as the following.
do
statement
} while (expression);
The statement will evaluate as long as the expression is true. And the following is an Example for it.
do
PORTB=I;
i++;
3.3.21.3.3-for Statement
The for statement implements an iterative loop.it is defined as the following
statement
Before the first iteration of the loop, init-expression sets the starting variables for the loop. You cannot
pass declarations in init-expression.
condition-expression is checked before the first entry into the block; statement is executed repeatedly
until the value of condition-expression is false. After each iteration of the loop, increment-expression
increments a loop counter. Consequently, i++ is functionally the same as ++i.
All expressions are optional. If condition-expression is left out, it is assumed to be always true. Thus,
“empty” for statement is commonly used to create an endless loop in C as the following:
for ( ; ; )
statement
The only way to break out of this loop is by means of the break statement as we will see in the Jump
statements in the following section.
And as an example
Int i;
PORTB=i;
int i,k;
void main() {
TRISB=0x00;
PORTB=i+k;
3.3.21.4.1-Break Statement
The break statement is important if we want to stop the loop if some condition occurs. The break
statement is commonly used with the selection statements as we will see in the following example.
switch (state) {
As shown in the above example the break statement is used to stop its execution upon the first positive
match.
for (i=0;i<100;i++) {
if (i==50) continue;
continue statement can be used with while and do-while and as we show with for statements. The
following will show how to use it with this statements.
while (..) {
...
if (val>0) continue;
...
// continue jumps here
}
Code 51 : Continue with while
do {
...
if (val>0) continue;
...
// continue jumps here
}
while (..);
Code 52 : Continue with do-while
for (..;..;..) {
...
if (val>0) continue;
...
// continue jumps here
}
Code 53 : Continue with for
for (...) {
for (...) {
...
if (disaster) goto Error;
...
}
}
.
.
.
Error : /* error handling code her */
return [expression];
This will evaluate expression and return the result. Returned value will be automatically converted to
the expected function type, if needed. The expression is optional; if omitted, the function will return a
random value from memory.
3.3.22-Preprocessor
Preprocessor is an integrated text processor which prepares the source code for compiling. Preprocessor
allows:
1. inserting text from a specifed file to a certain point in the code (see File Inclusion).
2. replacing specific lexical symbols with other symbols (see Macros).
3. conditional compiling which conditionally includes or omits parts of the code (see Conditional
Compilation).
3.3.22.1-File Inclusion
The file inclusion directive enable us to divide our code two more than one file and to include them all in
the main file to compile them to one hex file .it is defined as the following .
#include <header_name>
#include "header_name"
#include "C:\my_files\test.h"
File Inclusion is vey important when we work with ledmatrix and also GLCD, it is enable us to creat the
images and text we want to display in dindividual file and include it to the main project to display it.
3.3.22.2-Preprocessor Operators
3.3.22.2.1-Operator #
The # operator is very important it is used with define to name our microcontroller pins as an example,
we used it as the following.
3.3.22.2.2- Operator ##
Operator ## is used for token pasting. Two tokens can be pasted(merged) together by placing ## in
between them (plus optional whitespace on either side). The preprocessor removes whitespace and ##,
combining the separate tokens into one new token. This is commonly used for constructing identifiers.
And as an example:
#define MERG(x,y) x ## _ ## y
Code 59 : Operator ##
#if constant_expression_1
<section_1> ...
[#elif constant_expression_n
<section_n>]
[#else
<final_section>]
#endif
#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 #if, #elif, #else, and #endif.
An identifier defined as NULL is considered to be defined.
It is used if we want to compile something if we define a specific identifier and to compile another if we
define another identifier.
The following is an example that show you how to use it(you can fined it in the CD at
Projects/UsingDirective).
The circuit is like the following
#define ledB
void main() {
#ifdef ledB
TRISB=0x00;
PORTB=0x00;
#define led1 PORTB.B0
#endif
#ifdef ledD
TRISD=0x00;
PORTD=0x00;
#define led1 PORTD.B0
#endif
led1=0;
while(1)
{
led1=~ led1;
Delay_ms(500);
}
}
All what you need to change the led that is flashing is to change the first line of the code which define
the led you want to flash it and the code is compiled to that PORT only. You can change #define ledB To
#define led D and what is change.
3.4- Summary
In this chapter we show what is the programming and how the code is compiled and also we show the
most important essential of the C programming language that we need it in the programming of the
hardware specially in programming the pic microcontroller. All what you need to program the PIC
Microcontroller is to read the data sheet of the microcontroller you want to work with it and you will
find it is very easy to program it using c language with MikroC Pro compiler.