You are on page 1of 52

2011

Microcontroller
Course
By Eng

Ahmed Sheimy
Microcontroller Course Interfacing Hardware and Software

Table Of Contents
2.1- INTRODUCTION ............................................................................................................................. 8

2.2- ARCHITECTURE OF 8-BIT PIC MICROCONTROLLER ......................................................... 9

2.2.1- CPU ............................................................................................................................................................ 11

2.2.2- REGISTER ................................................................................................................................................... 11

2.2.3- Special Function REGISTERS ....................................................................................................................... 11

2.2.4- INPUT / OUTPUT PORTS ............................................................................................................................. 12

2.2.5- MEMORY UNIT ........................................................................................................................................... 12

2.2.6- INTERRUPT ................................................................................................................................................. 13

2.2.7-SERIAL COMMUNICATION .......................................................................................................................... 13

2.2.8- I2C (INTER INTEGRATED CIRCUIT) ............................................................................................................... 14

2.2.9- SPI (SERIAL PERIPHERAL INTERFACE BUS) .................................................................................................. 14

2.2.10- UART (UNIVERSAL ASYNCHRONOUS RECEIVER/TRANSMITTER) ............................................................... 15

2.2.11-OSCILLATOR .............................................................................................................................................. 15

2.2.12- POWER SUPPLY CIRCUIT .......................................................................................................................... 15

2.2.13- TIMERS..................................................................................................................................................... 16

2.2.14- COUNTERS ............................................................................................................................................... 16

2.2.15- WATCHDOG TIMER .................................................................................................................................. 16

2.2.16- A/D CONVERTER ...................................................................................................................................... 17

2.3-SUMMARY ....................................................................................................................................... 18

3.1-HOW THE PROGRAMMING IS DONE ...................................................................................... 19

3.2-YOUR FIRST MIKROC PROJECT ............................................................................................... 20

Eng Ahmed Sheimy Tel:+201114110781 1


Microcontroller Course Interfacing Hardware and Software

3.2.1-Create new Project ..................................................................................................................................... 20

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

..................................................................................................... ERROR! BOOKMARK NOT DEFINED.

3.3-C PROGRAMMING ESSENTIAL .................................................................................................. 22

3.3.1-Keywords .................................................................................................................................................... 22

3.3.2-Types in C language .................................................................................................................................... 22


3.3.2.1-Arithmetic Types .........................................................................................................................................22

3.3.3-Variables ..................................................................................................................................................... 23

3.3.4-Constant ..................................................................................................................................................... 24

3.3.5- Different between Variable and Const ....................................................................................................... 24

3.3.6-Number Representation ............................................................................................................................. 25


3.3.6.1-Decimal .......................................................................................................................................................25
3.3.6.2-Binary ..........................................................................................................................................................26
3.3.6.3-HexDecimal .................................................................................................................................................26
3.3.6.4-Conversion Code – Chart ............................................................................................................................27

3.3.7- Special Char Format ................................................................................................................................... 27

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.11- Arithmetic Operators ............................................................................................................................... 31

3.3.12- Relational Operators ................................................................................................................................ 32

3.3.13- Bitwise Operators .................................................................................................................................... 32


3.3.13.1-Bitwise AND (&) truth table ......................................................................................................................33
3.3.13.2- Bitwise OR (|) truth table .........................................................................................................................33
3.3.13.3- Bitwise exclusive OR (XOR ^) truth table .................................................................................................33

Eng Ahmed Sheimy Tel:+201114110781 2


Microcontroller Course Interfacing Hardware and Software

3.3.13.3- Bitwise complement (~) truth table .........................................................................................................33


3.3.13.4- Bitwise Shift left (<<) ................................................................................................................................33
3.3.13.5- Bitwise Shift Right (>>) .............................................................................................................................33

3.3.14-Logical Operators ...................................................................................................................................... 33


3.3.14.1- logical AND ...............................................................................................................................................34
3.3.14.1- logical OR .................................................................................................................................................34
3.3.14.1- logical negation ........................................................................................................................................35

3.3.15- Different between Bitwise Operators and Logical Operators ................................................................... 36

3.3.16- Conditional Operator ? : ........................................................................................................................... 36

3.3.17- Assignment Operators (=) ........................................................................................................................ 36

3.3.18-the different between (=) and (==) ............................................................................................................ 37

3.3.19 - Sizeof Operator ....................................................................................................................................... 37

3.3.20 – Good Expression for working with variable and operator ....................................................................... 37

3.3.21- Statements .............................................................................................................................................. 38


3.3.21.1 -Labeled Statements .................................................................................................................................38
3.3.21.2- Selection Statements ...............................................................................................................................38
3.3.21.3-Iteration Statements (Loops) ....................................................................................................................41
3.3.21.4- Jump Statements .....................................................................................................................................44

3.3.22-Preprocessor ............................................................................................................................................. 47
3.3.22.1-File Inclusion .............................................................................................................................................47
3.3.22.2-Preprocessor Operators ............................................................................................................................48

3.4- SUMMARY ...................................................................................................................................... 50

Eng Ahmed Sheimy Tel:+201114110781 3


Microcontroller Course Interfacing Hardware and Software

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

Eng Ahmed Sheimy Tel:+201114110781 4


Microcontroller Course Interfacing Hardware and Software

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

Eng Ahmed Sheimy Tel:+201114110781 5


Microcontroller Course Interfacing Hardware and Software

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

Eng Ahmed Sheimy Tel:+201114110781 6


Microcontroller Course Interfacing Hardware and Software

CODE 43 : DO-WHILE STATEMENT ......................................................................................................................................42


CODE 44 : DO-WHILE STATEMENT EXAMPLE.........................................................................................................................42
CODE 45 : FOR STATEMENT ...............................................................................................................................................43
CODE 46 : ENDLESS LOOP USING FOR ...................................................................................................................................43
CODE 47 : FOR LOOP EXAMPLE ...........................................................................................................................................44
CODE 48 : TWO INITIAL CONDITIONS WITH FOR .....................................................................................................................44
CODE 49 : BREAK STATEMENT EXAMPLE .............................................................................................................................45
CODE 50 : CONTINUE STATEMENT EXAMPLE .........................................................................................................................45
CODE 51 : CONTINUE WITH WHILE .....................................................................................................................................45
CODE 52 : CONTINUE WITH DO-WHILE ................................................................................................................................46
CODE 53 : CONTINUE WITH FOR .........................................................................................................................................46
CODE 54 : GOTO STATEMENT EXAMPLE ...............................................................................................................................46
CODE 55 :RETURN STATEMENT ..........................................................................................................................................47
CODE 56 : FILE INCLUSION.................................................................................................................................................47
CODE 57 : FILE INCLUSION EXAMPLE ...................................................................................................................................47
CODE 58 : DEFINE EXAMPLE ..............................................................................................................................................48
CODE 59 : OPERATOR ## ..................................................................................................................................................48
CODE 60 :DIRECTIVES #IF..................................................................................................................................................48
CODE 61 : USING DIRECTIVE CODE .....................................................................................................................................50

Eng Ahmed Sheimy Tel:+201114110781 7


Microcontroller Course Interfacing Hardware and Software

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

Eng Ahmed Sheimy Tel:+201114110781 8


Microcontroller Course Interfacing Hardware and Software

comparable.

2.2- Architecture of 8-bit PIC microcontroller


The following is the architecture of 8-bit PIC microcontroller

Eng Ahmed Sheimy Tel:+201114110781 9


Microcontroller Course Interfacing Hardware and Software

Figure 2 architecture of 8-bit PIC microcontroller

From the above Figure we see that the microcontroller has large number of register that used to

Eng Ahmed Sheimy Tel:+201114110781 10


Microcontroller Course Interfacing Hardware and Software

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

2.2.3- Special Function REGISTERS


The Register can be used by any part to save and get data from it ,but the special function register is
used for Special operation like this which used to Configure the state of the pins (in or out).

Eng Ahmed Sheimy Tel:+201114110781 11


Microcontroller Course Interfacing Hardware and Software

Figure 5 Special Function REGISTERS

From the above Figure we see that the special function register is used to control in other parts inside
the microcontroller.

2.2.4- INPUT / OUTPUT PORTS


The microcontroller has a number of ports that is used to connect with the external world, these Port
can be used as an input and also as an output to control in Devices connected to it, also some of these
ports can be used as an analog input to capture analog signals like voltage and Temperature. It is like
that shown in the following Figure

Figure 6 INPUT / OUTPUT PORTS

2.2.5- MEMORY UNIT


Memory is part of the microcontroller used for data storage, it is a collection of Register from wich we
can read and write data to it, it is shown below.

Eng Ahmed Sheimy Tel:+201114110781 12


Microcontroller Course Interfacing Hardware and Software

Figure 7 MEMORY UNIT

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.

Figure 8 SERIAL COMMUNICATION

Eng Ahmed Sheimy Tel:+201114110781 13


Microcontroller Course Interfacing Hardware and Software

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.

2.2.8- I2C (INTER INTEGRATED CIRCUIT)


Inter-integrated circuit is a system for serial data exchange between the microcontrollers and
specialized integrated circuits of a new generation. It is used when the distance between them is short
(receiver and transmitter are usually on the same printed board). Connection is established via two
conductors. One is used for data transfer, the other is used for synchronization (clock signal). As seen in
figure below, one device is always a master. It performs addressing of one slave chip before
communication starts. In this way one microcontroller can communicate with 112 different devices.
Baud rate is usually 100 Kb/sec (standard mode) or 10 Kb/sec (slow baud rate mode). Systems with the
baud rate of 3.4 Mb/sec have recently appeared. The distance between devices which communicate
over an I2C bus is limited to several meters.

Figure 9 I2C

2.2.9- SPI (SERIAL PERIPHERAL INTERFACE BUS)


A serial peripheral interface (SPI) bus is a system for serial communication which uses up to four
conductors, commonly three. One conductor is used for data receiving, one for data sending, one for
synchronization and one alternatively for selecting a device to communicate with. It is a full duplex
connection, which means that data is sent and received simultaneously. The maximum baud rate is
higher than that in the I2C communication system.

Figure 10 SPI

Eng Ahmed Sheimy Tel:+201114110781 14


Microcontroller Course Interfacing Hardware and Software

2.2.10- UART (UNIVERSAL ASYNCHRONOUS RECEIVER/TRANSMITTER)


This sort of communication is asynchronous, which means that a special line for transferring clock signal
is not used. In some applications, such as radio connection or infrared waves remote control, this
feature is crucial. Since only one communication line is used, both receiver and transmitter operate at
the same predefined rate in order to maintain necessary synchronization. This is a very simple way of
transferring data since it basically represents the conversion of 8-bit data from parallel to serial format.
Baud rate is not high, up to 1 Mbit/sec.

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

2.2.12- POWER SUPPLY CIRCUIT


There are two things worth attention concerning the microcontroller power supply circuit:

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.

Eng Ahmed Sheimy Tel:+201114110781 15


Microcontroller Course Interfacing Hardware and Software

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.2.15- WATCHDOG TIMER


the whole idea is based on the fact that every program is executed in several longer or shorter loops. If
instructions which reset the watchdog timer are set at the appropriate program locations, besides
commands being regularly executed, then the operation of the watchdog timer will not affect the
program execution. If for any reason, usually electrical noise in industry, the program counter ‘gets
stuck’ at some memory location from which there is no return, the watchdog timer will not be cleared,
so the register’s value being constantly incremented will reach the maximum et voila! Reset occurs!

Eng Ahmed Sheimy Tel:+201114110781 16


Microcontroller Course Interfacing Hardware and Software

Figure 13 WATCHDOG TIMER

2.2.16- A/D CONVERTER


External signals are usually fundamentally different from those the microcontroller understands (ones
and zeros) and have to be converted therefore into values understandable for the microcontroller. An
analogue to digital converter is an electronic circuit which converts continuous signals to discrete digital
numbers. In other words, this circuit converts an analogue value into a binary number and passes it to
the CPU for further processing. This module is therefore used for input pin voltage measurement
(analogue value).

Figure 14 A/D CONVERTER

Eng Ahmed Sheimy Tel:+201114110781 17


Microcontroller Course Interfacing Hardware and Software

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.

Eng Ahmed Sheimy Tel:+201114110781 18


Microcontroller Course Interfacing Hardware and Software

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.1-how the Programming is done


We need a .hex file to burn it in our microcontroller chip, the used compiler give us this file and the
programming operation will be in sequence like the following Figure

Eng Ahmed Sheimy Tel:+201114110781 19


Microcontroller Course Interfacing Hardware and Software

3.2-Your First MikroC Project


In this Project we will show how the code is written using MikroC compiler, how to compile it, how to
debug it to see if it is work good before burning it or not, how to simulate it using Proteus ISIS and
finally what is the output file that we will burn to our Microcontroller.

3.2.1-Create new Project


To see how to create a new Project and how to debug it see Appendix 1(Working with 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.1-ISIS Simulation Circuit

Figure 15 ISIS Simulation Circuit

Eng Ahmed Sheimy Tel:+201114110781 20


Microcontroller Course Interfacing Hardware and Software

3.2.2.2-Practical Circuit

Figure 16 Practical Circuit + Powe 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
}
}

Code 1 :First Project

As we see from the previous code that the state of the PORTB (ON/OFF) is change every one second.it is

Eng Ahmed Sheimy Tel:+201114110781 21


Microcontroller Course Interfacing Hardware and Software

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.

3.3-C Programming Essential


3.3.1-Keywords
Keywords is the words reserved in the compiler and we can’t use it in our definition of the variable as an
example, but it used for special purpose operations

absolute do namespace template


asm double operator this
at else org throw
auto enum pascal true
bit explicit private try
bool extern protected typedef
break false public typeid
case float register typename
catch for return union
char friend rx unsigned
class goto sfr using
code if short virtual
const inline signed void
continue int sizeof volatile
data io static while
default long struct
delete mutable switch

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

Eng Ahmed Sheimy Tel:+201114110781 22


Microcontroller Course Interfacing Hardware and Software

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.

3.3.2.1.2- Floating-point Types


The types float and double, together with the long double variant, are considered to be floating-point
types. The mikroC PRO for PIC’s implementation of an ANSI Standard considers all three to be the same
type.
Floating point in the mikroC PRO for PIC is implemented using the Microchip AN575 32-bit format (IEEE
754 compliant). The following is a Table of those types.

Type Size in bytes Range


float 4 -1.5 * 1045 .. +3.4 * 1038
double 4 -1.5 * 1045 .. +3.4 * 1038
long double 4 -1.5 * 1045 .. +3.4 * 1038
Table 3 Floating-point Types

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;

Code 2: Defining variable

And so on with all types, also we can initialize them and they will be like the following.

Eng Ahmed Sheimy Tel:+201114110781 23


Microcontroller Course Interfacing Hardware and Software

Int i=5;

float l=10.0;

Code 3: initialize Variable

3.3.4-Constant
The constant from its name its value can’t be changed inside the program, it is defined as the following

const Int i=5;

const float l=10.0;

Code 4: Constant

Common Programming Error 1:

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.

const unsigned i=0;

void main() {

i=10; // the value of I can’t change

Code 5: Common Programming Error 1

3.3.5- Different between Variable and Const


Variable Const
Value change Yes No
Memory Location RAM(Data Memory) ROM(Program Memory)
Table 4 Difrrent between Variable and Const

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

Eng Ahmed Sheimy Tel:+201114110781 24


Microcontroller Course Interfacing Hardware and Software

also required a large space for the Array.

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

Figure 17 Decimal Number

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.

Figure 18 Decimal Conversion

So if we want to get the value of 125 it will be:

Eng Ahmed Sheimy Tel:+201114110781 25


Microcontroller Course Interfacing Hardware and Software

5*(1) +2*(10) +1*(100) =5+20+100=125

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.

Figure 19 Binary Conversion

So if we want to get the value of 255 it will be:

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.

Eng Ahmed Sheimy Tel:+201114110781 26


Microcontroller Course Interfacing Hardware and Software

Figure 20 Hex Conversion

So if we want to get the value of 255 it will be:

F*1+F*16= 15*1+15*16=255

3.3.6.4-Conversion Code – Chart

Figure 21 Conversion Code – Chart

3.3.7- Special Char Format


The char is a type that enable us to work with variable as string , it is important for the Parts that
required this like writing in LCD, the char is written as the following.

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

Sequence Value Char What it does


\a 0x07 BEL Audible bell
\b 0x08 BS Backspace
\f 0x0C FF Form feed
\n 0x0A LF Newline (Linefeed)
\r 0x0D CR Carriage Return
\t 0x09 HT Tab (horizontal)
\v 0x0B VT Vertical Tab
\\ 0x5C \ Backslash

Eng Ahmed Sheimy Tel:+201114110781 27


Microcontroller Course Interfacing Hardware and Software

\' 0x27 ' Single quote


(Apostrophe)
\" 0x22 " Double quote
\? 0x3F ? Question mark
\O any O = string of up to 3
octal digits
\xH any H = string of hex
digits
\XH any H = string of hex
digits
Table 5 Spechial Char Format

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

Code 10: /n Code

When this data received on the PC there is nothing to display but the received data after this will be
displayed on new line

Common Programming Error 2:

Lcd_Out_Cp("\x091.0 Intro");

Code 11 : Common Programming Error 2

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:

Lcd_Out_Cp("\x09" "1.0 Intro");

Code 12: solution of Common Programming Error 2


2-\r\n
It is important and used when we interface the Mobile with the microcontroller using “AT Commands”,
if we use the Heber Terminal to send AT Commands to Mobile phone after each command we have to
press ENTER, but how to do this using the microcontroller? It is by using /n/r and the following is an
example to show you how.

Eng Ahmed Sheimy Tel:+201114110781 28


Microcontroller Course Interfacing Hardware and Software

UART1_Write('A’);

UART1_Write('T');

UART1_Write('\r');

UART1_Write('\n');

Code 13 : AT Command Exampe


3.3.8-Strings
Strings is an array of char, it is represented by chars and numbers inside the double quotes (“”).in c
langue there is no string type but we can do this as the following.

char *S1=”Hello Sheimy”;

Code 14 : String

Some important information about string.

"This is " "just"


" an example."

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."

Code 15 : String Format

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

enum Devices {Lamp, Refrigerator }; // Declare constant Devices

PORTB.Lamp=1; //this equal to PORTB.B0=1;

Code 16 : Enumeration

3.3.10-Arrays
arrays are probably the most commonly used composite data type, we can define array as the following.

Eng Ahmed Sheimy Tel:+201114110781 29


Microcontroller Course Interfacing Hardware and Software

3.3.10.1-One-Dimensional ARRAY
component_type array_name [number_of_components];

Code 17 : define array


And the following is an example of defining a char array its name is A and its elements is 4 elements

char A[4];

Code 18: array Example


But what is meaning of this? The following figure will show you what you want.

data data data data

A[0] A[1] A[2] A[3]

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.

A[3]=’S’; //put 5 in last element

Code 19 : initialize element

char c=A[3]; //get the data stored in last element

Code 20 : get data from address

3.3.10.2- Two-Dimensional ARRAY


The two dimensional array is like a table of row and columns, we define it as the following.

component_type array_name [number_of_rows] [number_of_columns];

Code 21 : define Two-Dimensional ARRAY

And the following is an example

char Tb [3][2]; // Tb is defined to have 3 rows and 2 columns

Code 22 : two dimension array example

And as a graph it is like the following

Eng Ahmed Sheimy Tel:+201114110781 30


Microcontroller Course Interfacing Hardware and Software

Tb[0][0] Tb[0][1]
Tb[1][0] Tb[1][1]
Tb[2][0] Tb[2][1]

3.3.11- Arithmetic Operators


Operator Operation
+ addition
- subtraction
* multiplication
/ division
% modulus operator returns the remainder of integer division (cannot be used
with floating points)
+ unary plus does not affect the operand
- unary minus changes the sign of the operand
++ increment adds one to the value of the operand. Postincrement adds one to the
value of the operand after it evaluates; while preincrement adds one before it
evaluates
-- decrement subtracts one from the value of the operand. Postdecrement
subtracts one from the value of the operand after it evaluates; while
predecrement subtracts one before it evaluates
Table 6 Arithmetic Operators

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

a++ equal to a=a+1 (Postincrement) use a then increment 1

++a equal to a=a+1 (Predecrement) increment 1 then use a

a- - equal to a=a-1 (Postincrement) use a then decrement 1

- -a equal to a=a-1 (Predecrement) decrement 1 then use a

Eng Ahmed Sheimy Tel:+201114110781 31


Microcontroller Course Interfacing Hardware and Software

3.3.12- Relational Operators


Operator Operation
== equal
!= not equal
> greater than
< less than
>= greater than or equal
<= less than or equal
Table 7 Relational Operators

The following is some examples that show you how to use them.

Assume a=5 and b=8

Operation Meaning Result


a==b Check if the value of a equal to the value of b false
a != b Check if the value of a not equal to the value of b true
a>b Check if the value of a large than the value of b false
a<b Check if the value of a less than the value of b true
a >= b Check if the value of a large than or equal the value of b false
a <= b Check if the value of a less than or equal the value of b true
Table 8 Relational Operators Examples

3.3.13- Bitwise Operators


The Bitwise Operators is used if we want to modify a specific bit in the variable, like if we want to get the
first 4 bits from the number .the following table is illustrate 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

The following is the truth table of each operator

Eng Ahmed Sheimy Tel:+201114110781 32


Microcontroller Course Interfacing Hardware and Software

3.3.13.1-Bitwise AND (&) truth table


& 0 1
0 0 0
1 0 1
Table 10 Bitwise AND truth table

3.3.13.2- Bitwise OR (|) truth table


| 0 1
0 0 1
1 1 1
Table 11 Bitwise OR (&) truth table

3.3.13.3- Bitwise exclusive OR (XOR ^) truth table


^ 0 1
0 0 1
1 1 0
Table 12 Bitwise exclusive OR (XOR ^) truth table

3.3.13.3- Bitwise complement (~) truth table


~ 0 1
1 0
Table 13 Bitwise complement (~) truth table

3.3.13.4- Bitwise Shift left (<<)


Assume we have a=0b01010101 and we apply the shift left operator like that a << 3 this means we shift
it to the left by 3,but how the shift is done? It is by shifting all bits three steps to the left and filling the
empty three bits in the right by zero so the result will be:

0b10101000

3.3.13.5- Bitwise Shift Right (>>)


The bitwise shift right is like the bitwise shift left but it shifts the bits to the right instead of to left, as an
example if we have a=0b01010101 and we apply a >> 3 the result will be.

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

Eng Ahmed Sheimy Tel:+201114110781 33


Microcontroller Course Interfacing Hardware and Software

Table 14 Logical Operators

3.3.14.1- logical AND


logical AND is used to check if two or more conditions satisfy in the same time or not, the truth table of
logical AND is below.

&& 0 x
0 0 0
x 0 1
Table 15 logical AND truth table

And as an example of using it. Assume a=1 and b=0 and c =2

Operation Result
a && b 0
a && c 1
Table 16 ogical AND Example

And as a code example

If(a==4 && b==9)

// write what you want to do here if the two conditions are true

Code 23 :logical AND Code Example

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

x is any number greater than zero

And as an example of using it. Assume a=1 and b=0 and c =2

Operation Result
a || b 1
a || c 1

Eng Ahmed Sheimy Tel:+201114110781 34


Microcontroller Course Interfacing Hardware and Software

Table 18 logical OR Example

And as a code example

If(a==4 || b==9)

// write what you want to do here if one of the two conditions are true

Code 24 : logical OR Code Example

3.3.14.1- logical negation


logical negation is used to check if condition not satisfy or not, the truth table of logical negation is
below.

! 0 x
1 0
Table 19 logical negation truth table

And as an example of using it. Assume a=1 and b=0 and c =2

Operation Result
!a 0
!b 1
Table 20 ogical negation Example

And as a code example

If(! a)

// write what you want to do here if a=0

Code 25 : Logical negation Code Example

Eng Ahmed Sheimy Tel:+201114110781 35


Microcontroller Course Interfacing Hardware and Software

3.3.15- Different between Bitwise Operators and Logical Operators


The logical operator check for the variables to be true(>0) or false (<0),but the bitwise operator make a
logic operation between them bit by bit. To see how lets look to the following example

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

3.3.16- Conditional Operator ? :


The conditional Operator is defined as the following

expression1 ? expression2 : expression3

Code 26 :Conditional Operator ? :

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.

C = a > b? a : b; //if a > b then C=a, else C=b

Code 27 :Conditional Operator ? : Example

3.3.17- Assignment Operators (=)


It is defined as the following
expression1 = expression2

Code 28 :Assignment Operator

Eng Ahmed Sheimy Tel:+201114110781 36


Microcontroller Course Interfacing Hardware and Software

The above code means that save the value of expression2 in expression1

3.3.18-the different between (=) and (==)


We will show the difference by an Example as the following

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 (==)

3.3.19 - Sizeof Operator


sizeof returns the size of the specified type in bytes, to show how look for the following examples and
give a look for the size of this types in Ttable2 and Table3

sizeof(char) /* returns 1 */
sizeof(int) /* returns 2 */
sizeof(unsigned long) /* returns 4 */
sizeof(float) /* returns 4 */

Code 29: Sizeof Operator Examples

3.3.20 – Good Expression for working with variable and operator


1-if we want to define two variable of type char we can do the following.

char a;

char b;

But the good is to do this as the following

char a,b;

Also if we want to initialize them it maybe

char a=5;

char b=6;

Or for good programming

Eng Ahmed Sheimy Tel:+201114110781 37


Microcontroller Course Interfacing Hardware and Software

char a=5,b=6;

Code 30 : more one way to define variable


3.3.21- Statements
Statement is the parts that the program code consists of, in this section will go through several of these
statements, we start with labeled statements and got to selection statements and finally we will show
the iterations statements and Jump statements.

3.3.21.1 -Labeled Statements


Each statement in a program can be labeled. A label is an identifier added before the statement like this:

label_identifier: statement;

Code 31 : Labeled Statements identifire

And as an Example:

ahmed: a=10;

Code 32 :Labeled Statements Example

Why we add a label to statements?

1-it is important to use the jump statement like goto as we will see in the following subsections

2-and also to be used with the selection statement like Switch.

3.3.21.2- Selection Statements


Selection or flow-control statements select one of alternative courses of action by testing certain values.
There are two types of selection statements:

3.3.21.2.1-IF Statement
It is used to test a condition it is defined as the following condition
if (expression) statement1;

Code 33 : IF statement identifire

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;

Code 34 : IF statement Example

Eng Ahmed Sheimy Tel:+201114110781 38


Microcontroller Course Interfacing Hardware and Software

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){

statement1; // what will execute if expression is true

else {

// what will execute if expression is false

Code 35 :IF-else statement identifier

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++;

Code 36 :IF-else statement Example

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

else statement3 /* this belongs to: if (expression3) */

else statement4 /* this belongs to: if (expression2) */

Code 37 : Nested If statements

Eng Ahmed Sheimy Tel:+201114110781 39


Microcontroller Course Interfacing Hardware and Software

3.3.21.2.4- Switch Statement


The Switch Statement is a good selection statement, it is used if we want to select more than two
actions according the condition, for example if we have a variable i and its value change from 0 to 100
and we want to do some actions for each value of i(e.g if i=0 flash led and so on), we can make it using if
else but it will be very large , so let’s know how to define Switch statement.

switch (expression) {

case constant-expression_1 : statement_1;

case constant-expression_n : statement_n;

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;

Code 39 :Switch Statement Example

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.

Eng Ahmed Sheimy Tel:+201114110781 40


Microcontroller Course Interfacing Hardware and Software

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;

Code 40 :Switch Statement Good Example

3.3.21.3-Iteration Statements (Loops)


Iteration statements allow looping a set of statements. There are three forms of iteration statements in
the mikroC PRO for PIC:

3.3.21.3.1-While Statement
While Statement is a loop statement it is defined as the following.

while (expression)

Statement;

Code 41 :While Statement

As the expression is true the statement is evaluated.

Eng Ahmed Sheimy Tel:+201114110781 41


Microcontroller Course Interfacing Hardware and Software

And as an example .

while (i < 100) {

PORTB=I;

i++;

Code 42 : While Statement Example

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);

Code 43 : do-While Statement

The statement will evaluate as long as the expression is true. And the following is an Example for it.

do

PORTB=I;

i++;

} while (i < 100);

Code 44 : do-While Statement Example

Eng Ahmed Sheimy Tel:+201114110781 42


Microcontroller Course Interfacing Hardware and Software

3.3.21.3.3-for Statement
The for statement implements an iterative loop.it is defined as the following

for ([init-expression]; [condition-expression]; [increment-expression])

statement

Code 45 : for 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

Code 46 : endless loop using for

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.

Eng Ahmed Sheimy Tel:+201114110781 43


Microcontroller Course Interfacing Hardware and Software

And as an example

Int i;

for (i=0 ; i<100 ; i++ )

PORTB=i;

Code 47 : for loop Example

We can use to initial conditions as the following:

int i,k;

void main() {

TRISB=0x00;

for (i=0,k=0 ; i<100,k<100 ; i++,k++ )

PORTB=i+k;

Code 48 : two initial conditions with for


}

3.3.21.4- Jump Statements


Jump Statements is good for controlling our code and for jumping from any position to another, the only
condition is that this position must be labeled as we show in the previous section. The Jump Statements
is four statements and it is :

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.

Eng Ahmed Sheimy Tel:+201114110781 44


Microcontroller Course Interfacing Hardware and Software

switch (state) {

case 0: Lo(); break;

case 1: Mid(); break;

case 2: Hi(); break;

default: Message("Invalid state!");

Code 49 : Break Statement Example

As shown in the above example the break statement is used to stop its execution upon the first positive
match.

3.3.21.4.2- Continue Statement


The continue statement is used to skip doing something within the loop if condition occurs and continue
evaluating the loop. As an example if we loop from i=0 to i=100 doing some actions and we don’t want
this actions to be evaluated if i=50. We will use continue statement and it will be as the following:

for (i=0;i<100;i++) {

if (i==50) continue;

//write actions her

// continue jumps here

Code 50 : Continue Statement Example

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

Eng Ahmed Sheimy Tel:+201114110781 45


Microcontroller Course Interfacing Hardware and Software

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

3.3.21.4.3- Goto Statement


The goto statement is used for unconditional jump to a local labeled statement (see section 3.3.21.1).to
show you how see the following example.

for (...) {
for (...) {
...
if (disaster) goto Error;
...
}
}
.
.
.
Error : /* error handling code her */

Code 54 : Goto Statement Example

Eng Ahmed Sheimy Tel:+201114110781 46


Microcontroller Course Interfacing Hardware and Software

3.3.21.4.4- Return Statement


The return statement is used to exit from the current function back to the calling routine, optionally
returning a value. It is defined as the following.

return [expression];

Code 55 :Return Statement

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"

Code 56 : File Inclusion

And as an example of how to use it.

#include "C:\my_files\test.h"

Code 57 : File Inclusion Example

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.

Eng Ahmed Sheimy Tel:+201114110781 47


Microcontroller Course Interfacing Hardware and Software

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.

#define led1 PORTB.B0


void main() {
TRISB=0x00;
led1=1;
}

Code 58 : define Example

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 ##

Now, the call MERG(cnt, 2) will expand to the identifier cnt_2.

3.3.22.2.3- Directives #if, #elif, #else, and #endif


The conditional directives #if, #elif, #else, and #endif work very similar to the common C conditional
statements. If the expression you write after #if has a nonzero value, the line group immediately
following the #if directive is retained in the translation unit and is added to the compiled HEX file.it
defined as the following.

#if constant_expression_1
<section_1> ...
[#elif constant_expression_n
<section_n>]
[#else
<final_section>]
#endif

Code 60 :Directives #if

Eng Ahmed Sheimy Tel:+201114110781 48


Microcontroller Course Interfacing Hardware and Software

3.3.22.2.4-Directives #ifdef and #ifndef


The #ifdef and #ifndef directives can be used anywhere #if can be used and they can 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 #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

Figure 22 Using Directive Circuit

Eng Ahmed Sheimy Tel:+201114110781 49


Microcontroller Course Interfacing Hardware and Software

And the code is:

#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);
}
}

Code 61 : Using Directive Code

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.

Eng Ahmed Sheimy Tel:+201114110781 50


Microcontroller Course Interfacing Hardware and Software

Eng Ahmed Sheimy Tel:+201114110781 51

You might also like