Sei sulla pagina 1di 260

www. newnespress.

co m
CHAP T E R 3
C Programming Language
There are several C compilers on the market for the PIC! series of microcontrollers.
These compilers have man" similar features# an$ the" can all %e use$ to $evelop
C&%ase$ high&level programs for PIC! microcontrollers.
'ome of the C compilers use$ most often in commercial# in$ustrial# an$ e$ucational
PIC! microcontroller applications are(

mikroC

PICC!

C!

CC'
The popular an$ powerful mikroC# $evelope$ %" )ikroElektronika *we% site(
www.microe.com+# is eas" to learn an$ comes with rich resources# such as a large
num%er of li%rar" functions an$ an integrate$ $evelopment environment with a %uilt&in
simulator an$ an in&circuit $e%ugger *e.g.# mikroIC,+. A $emo version of the compiler
with a -. program limit is availa%le from )ikroElektronika.
PICC!# another popular C compiler# was $evelope$ %" Hi&Tech 'oftware *we% site(
www.htsoft.com+ an$ is availa%le in two versions( stan$ar$ an$ professional.
A powerful simulator an$ an integrate$ $evelopment environment *Hi&Ti$e+ are
provi$e$ %" the compan". PICC! is supporte$ %" the PR/TE0' simulator
*www.la%center.co.uk+ which can %e use$ to simulate PIC microcontroller1%ase$
s"stems. A limite$&perio$ $emo version of this compiler is availa%le on the $eveloper2s
we% site.
-3 Chapter 3
ss. co m
C! is a pro$uct of )icrochip Inc. *we% site( www.microchip.com+. A limite$&perio$
$emo version# as well as a limite$ functionalit" version of C! with no time limit# are
availa%le from the )icrochip we% site. C! inclu$es a simulator an$ supports har$ware
an$ software $evelopment tools such as in&circuit emulators *e.g.# ICE-333+ an$
in&circuit $e%uggers *e.g.# IC,-+.
CC' has %een $evelope$ %" the Custom Computer '"stems Inc. *we% site( www.
ccsinfo.com+. The compan" offers a limite$&perio$ $emo version of their compiler.
CC' provi$es a large num%er of %uilt&in functions an$ supports an in&circuit $e%ugger
*e.g.# IC,&043+ which are ver" helpful in the $evelopment of PIC! microcontroller1
%ase$ s"stems.
In this %ook we are mainl" concentrating on the use of the mikroC compiler# an$ most
of the pro5ects are %ase$ on this compiler.
3. 'tructure of a mikroC Program
6igure 3. shows the simplest structure of a mikroC program. This program flashes an
LE, connecte$ to port R73 *%it 3 of P/RT7+ of a PIC microcontroller in one&secon$
/
LED FLASHING PROGRAM
*********************************
This program flashes an LED onne!e" !o por! pin R#$ of PORT# %i!h one
seon" in!er&als'
Programmer
File
Da!e
Miro
( D' I)rahim
( LED'*
( Ma+, -$$.
( PI*/0F12-
/
&oi" main34
5
for3664 // En"less loop
5
TRIS# 7 $6 // *onfig8re PORT# as o8!p8!
PORT#'$ 7 $6 // R#$ 7 $
Dela+9Ms3/$$$46 // :ai! / seon"
PORT#'$ 7 /6 // R#$ 7 /
Dela+9Ms3/$$$46 // :ai! / seon"
; // En" of loop
;
6igure 3.( 'tructure of a simple C program
intervals. ,o not worr" if "ou $on2t un$erstan$ the operation of the program at this
stage# as all will come clear as this chapter progresses. 'ome of the programming
elements in 6igure 3. are $escri%e$ in $etail here.
3.. Comments
Comments are use$ to clarif" the operation of the program or a programming
statement. Comment lines are ignore$ an$ not compile$ %" the compiler. In mikroC
programs comments can %e of two t"pes( long comments# e8ten$ing several lines# an$
short comments# occup"ing onl" a single line. Comment lines at the %eginning of a
program can $escri%e %riefl" the program2s operation an$ provi$e the author2s name#
the program filename# the $ate the program was written# an$ a list of version num%ers#
together with the mo$ifications in each version. As shown in 6igure 3.# comments can
also %e a$$e$ after statements to $escri%e the operations that the statements perform.
Clear an$ succinct comment lines are important for the maintenance an$ thus the
lifetime of a program# as a program with goo$ comments is easier to mo$if" an$9or
up$ate.
As shown in 6igure 3.# long comments start with the character :9;< an$ terminate with
the character :;9 <. 'imilarl"# short comments start with the character :99 < an$ $o not
nee$ a terminating character.
3..- 7eginning an$ En$ing of a Program
In C language# a program %egins with the ke"wor$s(
voi$ main *+
After this# a curl" opening %racket is use$ to in$icate the %eginning of the program
%o$". The program is terminate$ with a closing curl" %racket. Thus# as shown in
6igure 3.# the program has the following structure(
voi$ main*+
=
program %o$"
>
3..3 Terminating Program 'tatements
In C language# all program statements must %e terminate$ with the semicolon *:?<+
character? otherwise a compiler error will %e generate$(
5 @ A? 99 correct
5 @ A 99 error
3..4 Bhite 'paces
Bhite spaces are spaces# %lanks# ta%s# an$ newline characters. The C compiler ignores
all white spaces. Thus# the following three seCuences are i$entical(
int i? char 5?
or
int i?
char 5?
or
int i?
char 5?
'imilarl"# the following seCuences are i$entical(
i @ 5 D -?
or
i @ 5
D -?
3..A Case 'ensitivit"
In general# C language is case sensitive an$ varia%les with lowercase names are
$ifferent from those with uppercase names. Currentl"# however# mikroC varia%les are
not case sensitive *although future releases of mikroC ma" offer case sensitivit"+ so
the following varia%les are eCuivalent(
total T/TAL Total ToTal total totaL
The onl" e8ception is the i$entifiers main an$ interrupt# which must %e written in
lowercase in mikroC. In this %ook we are assuming that the varia%les are case sensitive#
for the sake of compati%ilit" with other C compilers# an$ varia%les with the same name
%ut $ifferent cases are not use$.
3..E Faria%le Games
In C language# varia%le names can %egin with an alpha%etical character or with the
un$erscore character. In essence# varia%le names can inclu$e an" of the characters a to H
an$ A to I# the $igits 3 to J# an$ the un$erscore character :K<. Each varia%le name
shoul$ %e uniCue within the first 3 characters of its name. Faria%le names can contain
uppercase an$ lowercase characters *see 'ection 3..A+# an$ numeric characters can %e
use$ insi$e a varia%le name. E8amples of vali$ varia%le names are(
'um count sum33 counter i 0serGame
Km"Game
'ome names are reserve$ for the compiler itself an$ cannot %e use$ as varia%le names
in a program. Ta%le 3. gives a list of these reserve$ names.
3..L Faria%le T"pes
The mikroC language supports the varia%le t"pes shown in Ta%le 3.-. E8amples of
varia%les are given in this section.
Ta%le 3.( mikroC reserve$ names
asm enum signe$
auto e8tern siHeof
%reak float static
case for struct
char goto switch
const if t"pe$ef
continue int union
$efault long unsigne$
$o register voi$
$ou%le return volatile
else short while
Ta%le 3.-( mikroC varia%le t"pes
T"pe 'iHe *%its+ Range
unsigne$ char ! 3 to -AA
unsigne$ short int ! 3 to -AA
unsigne$ int E 3 to EAA3A
unsigne$ long int 3- 3 to 4-J4JEL-JA
signe$ char ! -! to -L
signe$ short int ! -! to -L
signe$ int E 3-LE! to 3-LEL
signe$ long int 3- -4L4!3E4! to -4L4!3E4L
float 3- .LA4J43A3!-E&3! to E.!3AE4LL443LE3!
$ou%le 3- .LA4J43A3!-E&3! to E.!3AE4LL443LE3!
long $ou%le 3- .LA4J43A3!-E&3! to E.!3AE4LL443LE3!
*unsigne$+ char or unsigne$ short *int+
The varia%les *unsigne$+ char# or unsigne$ short *int+# are !&%it unsigne$ varia%les with
a range of 3 to -AA. In the following e8ample two !&%it varia%les name$ total an$ sum
are create$# an$ sum is assigne$ $ecimal value A3(
unsigne$ char total# sum?
sum @ A3?
or
char total# sum?
sum @ A3?
Faria%les can %e assigne$ values $uring their $eclaration. Thus# the a%ove statements
can also %e written as(
char total# sum @ A3?
signe$ char or *signe$+ short *int+
The varia%les signe$ char# or *signe$+ short *int+# are !&%it signe$ character varia%les
with a range of -! to D-L. In the following e8ample a signe$ !&%it varia%le name$
counter is create$ with a value of A3(
signe$ char counter @ A3?
or
short counter @ A3?
or
short int counter @ A3?
*signe$+ int
Faria%les calle$ *signe$+ int are E&%it varia%les with a range 3-LE! to D3-LEL. In the
following e8ample a signe$ integer name$ 7ig is create$(
int 7ig?
unsigne$ *int+
Faria%les calle$ *unsigne$+ int are E&%it unsigne$ varia%les with a range 3 to EAA3A. In
the following e8ample an unsigne$ E&%it varia%le name$ count is create$ an$ is
assigne$ value -333(
unsigne$ int count @ -333?
*signe$+ long *int+
Faria%les calle$ *signe$+ long *int+ are 3- %its long with a range -4L4!3E4! to
D-4L4!3E4L. An e8ample is(
signe$ long LargeGum%er?
unsigne$ long *int+
Faria%les calle$ *unsigne$+ long *int+ are 3-&%it unsigne$ varia%les having the
range 3 to 4-J4JEL-JA. An e8ample is(
unsigne$ long Fer"LargeGum%er?
float or $ou%le or long $ou%le
The varia%les calle$ float or $ou%le or long $ou%le# are floating point varia%les
implemente$ in mikroC using the )icrochip AGALA 3-&%it format# which is
IEEE LA4 compliant. 6loating point num%ers range from .LA4J43A3!-E&3! to
E.!3AE4LL443LE3!. In the following e8ample# a floating point varia%le name$ area is
create$ an$ assigne$ the value -.-3A(
float area?
area @ -.-3A?
To avoi$ confusion $uring program $evelopment# specif"ing the sign of the varia%le
*signe$ or unsigne$+ as well as the t"pe of varia%le is recommen$e$. 6or e8ample# use
unsigne$ char instea$ of char onl"# an$ unsigne$ int instea$ of unsigne$ onl".
In this %ook we are using the following mikroC $ata t"pes# which are eas" to remem%er
an$ also compati%le with most other C compilers(
unsigne$ char 3 to -AA
signe$ char -! to -L
unsigne$ int 3 to EAA3A
signe$ int 3-LE! to 3-LEL
unsigne$ long 3 to 4-J4JEL-JA
signe$ long -4L4!3E4! to -4L4!3E4L
float .LA4J43A3!-E&3! to E.!3AE4LL443LE3!
3..! Constants
Constants represent fi8e$ values *numeric or character+ in programs that cannot %e
change$. Constants are store$ in the flash program memor" of the PIC microcontroller#
thus not wasting valua%le an$ limite$ RA) memor". In mikroC# constants can %e
integers# floating points# characters# strings# or enumerate$ t"pes.
Integer Constants
Integer constants can %e $ecimal# he8a$ecimal# octal# or %inar". The $ata t"pe of a
constant is $erive$ %" the compiler from its value. 7ut suffi8es can %e use$ to change
the t"pe of a constant.
In Ta%le 3.- we saw that $ecimal constants can have values from -4L4!3E4!
to D4-J4JEL-JA. 6or e8ample# constant num%er -3 is store$ as an unsigne$
char *or unsigne$ short int+. 'imilarl"# constant num%er -33 is store$ as a signe$ int.
0sing the suffi8 u or 0 forces the constant to %e unsigne$. 0sing the suffi8 L or l forces
the constant to %e long. 0sing %oth 0 *or u+ an$ L *or l+ forces the constant to %e
unsigne$ long.
Constants are $eclare$ using the ke"wor$ const an$ are store$ in the flash program
memor" of the PIC microcontroller# thus not wasting valua%le RA) space. In the
following e8ample# constant )AM is $eclare$ as 33 an$ is store$ in the flash program
memor" of the PIC microcontroller(
const )AM @ 33?
He8a$ecimal constants start with characters 38 or 3M an$ ma" contain numeric $ata
3 to J an$ he8a$ecimal characters A to 6. In the following e8ample# constant T/TAL is
given the he8a$ecimal value 66(
const T/TAL @ 3866?
/ctal constants have a Hero at the %eginning of the num%er an$ ma" contain numeric
$ata 3 to L. In the following e8ample# constant CGT is given octal value L(
const CGT @ 3L?
7inar" constant num%ers start with 3% or 37 an$ ma" contain onl" 3 or . In the
following e8ample a constant name$ )in is $eclare$ as having the %inar" value
3333(
const )in @ 3%3333
6loating Point Constants
6loating point constant num%ers have integer parts# a $ot# a fractional part# an$ an
optional e or E followe$ %" a signe$ integer e8ponent. In the following e8ample# a
constant name$ TE)P is $eclare$ as having the fractional value 3L.A3(
const TE)P @ 3L.A3
or
const TE)P @ 3.LA3E
Character Constants
A character constant is a character enclose$ within single Cuote marks. In the following
e8ample# a constant name$ 6irstKAlpha is $eclare$ as having the character value :A<(
const 6irstKAlpha @ NA2?
'tring Constants
'tring constants are fi8e$ seCuences of characters store$ in the flash memor" of the
microcontroller. The string must %oth %egin an$ terminate with a $ou%le Cuote character
*:+. The compiler automaticall" inserts a null character as a terminator. An e8ample
string constant is(
:This is an e8ample string constant<
A string constant can %e e8ten$e$ across a line %oun$ar" %" using a %ackslash
character *: O<+(
:This is first part of the string O
an$ this is the continuation of the string<
This string constant $eclaration is the same as(
:This is first part of the string an$ this is the
continuation of the string<
Enumerate$ Constants
Enumerate$ constants are integer t"pe an$ are use$ to make a program easier to
follow. In the following e8ample# constant colors stores the names of colors. The
first element is given the value 3(
enum colors =%lack# %rown# re$# orange# "ellow# green# %lue#
gra"# white>?
3..J Escape 'eCuences
Escape seCuences are use$ to represent nonprinta%le A'CII characters. Ta%le 3.3
shows some commonl" use$ escape seCuences an$ their representation in C language.
6or e8ample# the character com%ination : O n< represents the newline character.
Ta%le 3.3( 'ome commonl" use$ escape seCuences
Escape seCuence He8 value Character
Oa 3 3L 7EL *%ell+
O% 3 3! 7' *%ackspace+
Ot 3 3J HT *horiHontal ta%+
On 3 3A L6 *linefee$+
Ov 3 37 FT *vertical fee$+
Of 3 3C 66 *formfee$+
Or 3 3, CR *carriage return+
O8H 'tring of he8 $igits
An A'CII character can also %e represente$ %" specif"ing its he8a$ecimal co$e after a
%ackslash. 6or e8ample# the newline character can also %e represente$ as : O83A<.
3..3 'tatic Faria%les
'tatic varia%les are local varia%les use$ in functions *see Chapter 4+ when the last value
of a varia%le %etween successive calls to the function must %e preserve$. As the
following e8ample shows# static varia%les are $eclare$ using the ke"wor$ static(
static unsigne$ int count?
3.. E8ternal Faria%les
0sing the ke"wor$ e8tern %efore a varia%le name $eclares that varia%le as e8ternal. It
tells the compiler that the varia%le is $eclare$ elsewhere in a separate source co$e
mo$ule. In the following e8ample# varia%les sum an$ sum- are $eclare$ as e8ternal
unsigne$ integers(
e8tern int sum# sum-?
3..- Folatile Faria%les
Folatile varia%les are especiall" important in interrupt&%ase$ programs an$ input&output
routines. 0sing the ke"wor$ volatile in$icates that the value of the varia%le ma" change
$uring the lifetime of the program in$epen$ent of the normal flow of the program.
Faria%les $eclare$ as volatile are not optimiHe$ %" the compiler# since their values can
change une8pecte$l". In the following e8ample# varia%le Le$ is $eclare$ as a volatile
unsigne$ char(
volatile unsigne$ char Le$?
3..3 Enumerate$ Faria%les
Enumerate$ varia%les are use$ to make a program more rea$a%le. In an enumerate$
varia%le# a list of items is specifie$ an$ the value of the first item is set to 3# the ne8t
item is set to # an$ so on. In the following e8ample# t"pe Beek is $eclare$ as an
enumerate$ list an$ )/G @ 3# T0E @ # BE, @ -# an$ so on+(
enum Beek =)/G# T0E# BE,# TH0# 6RI# 'AT# '0G>?
It is possi%le to impl" the values of the elements in an enumerate$ list. In the
following e8ample# %lack @ -# %lue @ 3# re$ @ 4# an$ so on.
enum colors =%lack @ -# %lue# re$# white# gra">?
'imilarl"# in the following e8ample# %lack @ -# %lue @ 3# re$ @ !# an$ gra" @ J(
enum colors =%lack @ -# %lue# re$ @ !# gra">?
Faria%les of t"pe enumeration can %e $eclare$ %" specif"ing them after the list of
items. 6or e8ample# to $eclare varia%le )"KBeek of enumerate$ t"pe Beek# use the
following statement(
enum Beek =)/G# T0E# BE,# TH0# 6RI# 'AT# '0G> )"KBeek?
Gow we can use varia%le )"KBeek in a program(
)"KBeek @ BE, 99 assign - to )"KBeek
or
)"KBeek @ - 99 same as a%ove
After $efining the enumerate$ t"pe Beek# we can $eclare varia%les ThisKBeek an$
Ge8tKBeek of t"pe Beek as(
enum Beek ThisKBeek# Ge8tKBeek?
3..4 Arra"s
Arra"s are use$ to store relate$ items in the same %lock of memor" an$ un$er a
specifie$ name. An arra" is $eclare$ %" specif"ing its t"pe# name# an$ the num%er of
elements it will store. 6or e8ample(
unsigne$ int TotalPAQ?
This arra" of t"pe unsigne$ int has the name Total an$ has five elements. The first
element of an arra" is in$e8e$ with 3. Thus# in this e8ample# TotalP3Q refers to the first
element of the arra" an$ TotalP4Q refers to the last element. The arra" Total is store$ in
memor" in five consecutive locations as follows(
TotalP3Q
TotalPQ
TotalP-Q
TotalP3Q
TotalP4Q
,ata can %e store$ in the arra" %" specif"ing the arra" name an$ in$e8. 6or e8ample# to
store -A in the secon$ element of the arra" we have to write(
TotalPQ @ -A?
'imilarl"# the contents of an arra" can %e rea$ %" specif"ing the arra" name an$ its
in$e8. 6or e8ample# to cop" the thir$ arra" element to a varia%le calle$ Temp we have
to write(
Temp @ TotalP-Q?
The contents of an arra" can %e initialiHe$ $uring the $eclaration of the arra" %"
assigning a seCuence of comma&$elimite$ values to the arra". An e8ample follows
where arra" months has twelve elements an$ monthsP3Q @ 3# monthsPQ @ -!# an$
so on(
unsigne$ char monthsP-Q @ =3#-!#3#33#3#33#3#3#33#3#33#3>?
The same arra" can also %e $eclare$ without specif"ing its siHe(
unsigne$ char monthsP Q @ =3#-!#3#33#3#33#3#3#33#3#33#3>?
Character arra"s can %e $eclare$ similarl". In the following e8ample# a character arra"
name$ He8KLetters is $eclare$ with E elements(
unsigne$ char He8KLettersP Q @ =NA2# N72# NC2# N,2# NE2# N62>?
'trings are character arra"s with a null terminator. 'trings can %e $eclare$ either %"
enclosing the string in $ou%le Cuotes# or %" specif"ing each character of the arra" within
single Cuotes an$ then terminating the string with a null character. The two string
$eclarations in the following e8ample are i$entical# an$ %oth occup" five locations in
memor"(
unsigne$ char )"stringP Q @ :C/)P<?
an$
unsigne$ char )"stringP Q @ =NC2# N/2# N)2# NP2# NO32>?
In C programming language# we can also $eclare arra"s with multiple $imensions.
/ne&$imensional arra"s are usuall" calle$ vectors# an$ two&$imensional arra"s are
calle$ matrices. A two&$imensional arra" is $eclare$ %" specif"ing the $ata t"pe of the
arra"# the arra" name# an$ the siHe of each $imension. In the following e8ample# a two&
$imensional arra" name$ P is create$ having three rows an$ four columns. Altogether#
the arra" has twelve elements. The first element of the arra" is PP3QP3Q# an$ the last
element is PP-QP3Q. The structure of this arra" is shown %elow(
PP3QP3Q PP3QPQ PP3QP-Q PP3QP3Q
PPQP3Q PPQPQ PPQP-Q PPQP3Q
PP-QP3Q PP-QPQ PP-QP-Q PP-QP3Q
Elements of a multi$imensional arra" can %e specifie$ $uring the $eclaration of the
arra". In the following e8ample# two&$imensional arra" R has two rows an$ two
columns# its $iagonal elements are set to # an$ its non$iagonal elements are
cleare$ to 3(
unsigne$ char RP-QP-Q @ = =#3># =3#> >?
3..A Pointers
Pointers are an important part of the C language# as the" hol$ the memor" a$$resses
of varia%les. Pointers are $eclare$ in the same wa" as other varia%les# %ut with the
character *:;<+ in front of the varia%le name. In general# pointers can %e create$ to point
to *or hol$ the a$$resses of+ character varia%les# integer varia%les# long varia%les#
floating point varia%les# or functions *although mikroC currentl" $oes not support
pointers to functions+.
In the following e8ample# an unsigne$ character pointer name$ pnt is $eclare$(
unsigne$ char ;pnt?
Bhen a new pointer is create$# its content is initiall" unspecifie$ an$ it $oes not hol$
the a$$ress of an" varia%le. Be can assign the a$$ress of a varia%le to a pointer using
the *:S<+ character(
pnt @ SCount?
Gow pnt hol$s the a$$ress of varia%le Count. Faria%le Count can %e set to a value %"
using the character *:;<+ in front of its pointer. 6or e8ample# Count can %e set to 3
using its pointer(
;pnt @ 3? 99 Count @ 3
which is the same as
Count @ 3? 99 Count @ 3
/r# the value of Count can %e copie$ to varia%le Cnt using its pointer(
Cnt @ ;pnt? 99 Cnt @ Count
Arra" Pointers
In C language the name of an arra" is also a pointer to the arra". Thus# for the arra"(
unsigne$ int TotalP3Q?
The name Total is also a pointer to this arra"# an$ it hol$s the a$$ress of the first
element of the arra". Thus the following two statements are eCual(
TotalP-Q @ 3?
an$
;*Total D -+ @ 3?
Also# the following statement is true(
STotalP5Q @ Total D 5
In C language we can perform pointer arithmetic which ma" involve(

Comparing two pointers

A$$ing or su%tracting a pointer an$ an integer value

'u%tracting two pointers

Assigning one pointer to another

Comparing a pointer to null
6or e8ample# let2s assume that pointer P is set to hol$ the a$$ress of arra"
element IP-Q(
P @
SIP-Q?
Be can now clear elements - an$ 3 of arra" I# as in the two e8amples that follow. The
two e8amples are i$entical e8cept that in the first e8ample pointer P hol$s the a$$ress
of IP3Q at the en$ of the statements# an$ it hol$s the a$$ress of IP-Q at the en$ of the
secon$ set of statements(
;P @ 3? 99 IP-Q @ 3
P @ P D ? 99 P now points to element 3 of I
;P @ 3? 99 IP3Q @ 3
or
;P @ 3? 99 IP-Q @ 3
;*P D + @ 3? 99 IP3Q @ 3
A pointer can %e assigne$ to another pointer. In the following e8ample# varia%les Cnt
an$ Tot are %oth set to 3 using two $ifferent pointers(
unsigne$ int ;i# ;5? 99 $eclare - pointers
unsigne$ int Cnt# Tot? 99 $eclare two
varia%les
i @ SCnt? 99 i points to Cnt
;i @ 3? 99 Cnt @ 3
5 @ i? 99 cop" pointer i to pointer 5
Tot @ ;5? 99 Tot @ 3
3..E 'tructures
A structure can %e use$ to collect relate$ items that are then treate$ as a single o%5ect.
0nlike an arra"# a structure can contain a mi8ture of $ata t"pes. 6or e8ample# a
structure can store the personal $etails *name# surname# age# $ate of %irth# etc.+ of a
stu$ent.
A structure is create$ %" using the ke"wor$ struct# followe$ %" a structure name an$ a
list of mem%er $eclarations. /ptionall"# varia%les of the same t"pe as the structure can
%e $eclare$ at the en$ of the structure.
The following e8ample $eclares a structure name$ Person(
struct Person
=
unsigne$ char nameP-3Q?
unsigne$ char surnameP-3Q?
unsigne$ char
nationalit"P-3Q? unsigne$
char age?
>
,eclaring a structure $oes not occup" an" space in memor"? rather# the compiler
creates a template $escri%ing the names an$ t"pes of the $ata o%5ects or mem%er
elements that will eventuall" %e store$ within such a structure varia%le. /nl"
when varia%les of the same t"pe as the structure are create$ $o these varia%les
occup" space in memor". Be can $eclare varia%les of the same t"pe as the
structure %" giving the name of the structure an$ the name of the varia%le.
6or e8ample# two varia%les )e an$ Tou of t"pe Person can %e create$ %"
the statement(
struct Person )e# Tou?
Faria%les of t"pe Person can also %e create$ $uring the $eclaration of the structure
as follows(
struct Person
=
unsigne$ char nameP-3Q?
unsigne$ char surnameP-3Q?
unsigne$ char
nationalit"P-3Q? unsigne$
char age?
> )e# Tou?
Be can assign values to mem%ers of a structure %" specif"ing the name of the structure#
followe$ %" a $ot *:.<+ an$ the name of the mem%er. In the following e8ample# the age
of structure varia%le )e is set to -A# an$ varia%le ) is assigne$ to the value of age in
structure varia%le Tou(
)e.age @ -A?
) @ Tou.age?
'tructure mem%ers can %e initialiHe$ $uring the $eclaration of the structure. In the
following e8ample# the ra$ius an$ height of structure C"lin$er are initialiHe$ to .- an$
-.A respectivel"(
struct C"lin$er
=
float ra$ius?
float height?
> )"C"lin$er @ =.-# -.A>?
Falues can also %e set to mem%ers of a structure using pointers %" $efining the varia%le
t"pes as pointers. 6or e8ample# if TheC"lin$er is $efine$ as a pointer to structure
C"lin$er# then we can write(
struct C"lin$er
=
float ra$ius?
float height?
> ;TheC"lin$er?
TheC"lin$er U ra$ius @ .-?
TheC"lin$er U height @ -.A?
The siHe of a structure is the num%er of %"tes containe$ within the structure. Be can use
the siHeof operator to get the siHe of a structure. Consi$ering the a%ove e8ample#
siHeof*)"C"lin$er+
returns !# since each float varia%le occupies 4 %"tes in memor".
7it fiel$s can %e $efine$ using structures. Bith %it fiel$s we can assign i$entifiers to
%its of a varia%le. 6or e8ample# to i$entif" %its 3# # -# an$ 3 of a varia%le as LowGi%%le
an$ to i$entif" the remaining 4 %its as HighGi%%le we can write(
struct
=
LowGi%%le ( 4?
HighGi%%le ( 4?
> )"Faria%le?
Be can then access the ni%%les of varia%le )"Faria%le as(
)"Faria%le.LowGi%%le @ -?
)"Faria%le.HighGi%%le @ !?
In C language we can use the t"pe$ef statements to create new t"pes of varia%les. 6or
e8ample# a new structure $ata t"pe name$ Reg can %e create$ as follows(
t"pe$ef struct
=
> Reg?
unsigne$ char nameP-3Q?
unsigne$ char
surnameP-3Q? unsigne$
age?
Faria%les of t"pe Reg can then %e create$ in the same wa" other t"pes of varia%les are
create$. In the following e8ample# varia%les )"Reg# Reg# an$ Reg- are create$ from
$ata t"pe Reg(
Reg )"Reg# Reg# Reg-?
The contents of one structure can %e copie$ to another structure# provi$e$ that %oth
structures are $erive$ from the same template. In the following e8ample# structure
varia%les of the same t"pe# P an$ P-# are create$# an$ P- is copie$ to P(
struct Person
=
unsigne$ char nameP-3Q?
unsigne$ char
surnameP-3Q? unsigne$
int age? unsigne$ int
height? unsigne$ weight?
>
struct Person P# P-?
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
P- @ P?
3..L 0nions
0nions are use$ to overla" varia%les. A union is similar to a structure an$ is even
$efine$ in a similar manner. 7oth are %ase$ on templates# an$ the mem%ers of %oth are
accesse$ using the :.< or :&U< operators. A union $iffers from a structure in that all
varia%les in a union occup" the same memor" area# that is# the" share the same storage.
An e8ample of a union $eclaration is(
union flags
=
> P?
unsigne$ char 8?
unsigne$ int "?
In this e8ample# varia%les 8 an$ " occup" the same memor" area# an$ the siHe of this
union is - %"tes long# which is the siHe of the %iggest mem%er of the union. Bhen
varia%le " is loa$e$ with a -&%"te value# varia%le 8 will have the same value as the low
%"te of ". In the following e8ample# " is loa$e$ with E&%it he8a$ecimal value
38AE6A# an$ 8 is loa$e$ with 386A(
P." @ 38AE6A?
The siHe of a union is the siHe *num%er of %"tes+ of its largest mem%er. Thus# the
statement(
siHeof*P+
returns -.
This union can also %e $eclare$ as(
union flags
=
unsigne$ char 8?
unsigne$ int "?
>
union flags P?
3..! /perators in C
/perators are applie$ to varia%les an$ other o%5ects in e8pressions to cause certain
con$itions or computations to occur.
mikroC language supports the following operators(

Arithmetic operators

Relational operators

Logical operators

7itwise operators

Assignment operators

Con$itional operators

Preprocessor operators
Arithmetic /perators
Arithmetic operators are use$ in arithmetic computations. Arithmetic operators
associate from left to right# an$ the" return numerical results. The mikroC arithmetic
operators are liste$ in Ta%le 3.4.
Ta%le 3.4( mikroC arithmetic operators
/perator /peration
D A$$ition
'u%traction
; )ultiplication
9 ,ivision
V Remain$er *integer $ivision+
DD Auto increment
Auto $ecrement
The following e8ample illustrates the use of arithmetic operators(
9; A$$ing two integers ;9
A D - 99 eCuals L
9; 'u%tracting two integers ;9
-3 1 A 99 eCuals A
3 1 A 99 eCuals A
9; ,ivi$ing two integers ;9
A 9 3 99 eCuals
- 9 3 99 eCuals 4
9; )ultipl"ing two integers ;9
3 ; - 99 eCuals 3E
9; A$$ing two floating point num%ers ;9
3. D -.4 99 eCuals A.A
9; )ultipl"ing two floating point num%ers ;9
-.A ; A.3 99 eCuals -.A
9; ,ivi$ing two floating point num%ers ;9
-A.3 9 4.3 99 eCuals E.-A
9; Remain$er *not for float+ ;9
L V 3 99 eCuals
9; Post&increment operator ;9
5 @ 4?
k @ 5DD? 99 k @ 4# 5 @ A
9; Pre&increment operator ;9
5 @ 4?
k @ DD5? 99 k @ A# 5 @ A
9; Post&$ecrement operator ;9
5 @ -?
k @ 5 ? 99 k @ -# 5 @
9; Pre&$ecrement operator
;9
5 @ -?
k @ 5? 99 k @ # 5 @
Relational /perators
Relational operators are use$ in comparisons. If the e8pression evaluates to TR0E# a
is returne$? otherwise a 3 is returne$.
All relational operators associate from left to right. A list of mikroC relational operators
is given in Ta%le 3.A.
The following e8ample illustrates the use of relational operators(
8 @ 3
8 U ! 99 returns
8 @ @ 3 99 returns
8 W 33 99 returns
8 U -3 99 returns
3 8 X@ 3 99 returns
3 8 U@ 3 99 returns
8 W@ 3 99 returns
Logical /perators
Logical operators are use$ in logical an$ arithmetic comparisons# an$ the" return TR0E
*i.e.# logical + if the e8pression evaluates to nonHero# an$ 6AL'E *i.e.# logical 3+ if the
Ta%le 3.A( mikroC relational operators
/perator /peration
@ @ ECual to
X@ Got eCual to
U Yreater than
W Less than
U@ Yreater than or eCual to
W@ Less than or eCual to
Ta%le 3.E( mikroC logical operators
/perator /peration
SS AG,
ZZ /R
X G/T
e8pression evaluates to Hero. If more than one logical operator is use$ in a statement#
an$ if the first con$ition evaluates to 6AL'E# the secon$ e8pression is not evaluate$.
The mikroC logical operators are liste$ in Ta%le 3.E.
The following e8ample illustrates the use of logical operators(
9; Logical AG,
;9
8 @ L?
8 U 3 SS 8 W 3 99 returns
8 U 3 ZZ 8 W 3 99 returns
8 U@3 SS 8 W@3 99 returns

8 U@3 SS 8 W A 99 returns
3
a @ 3? % @ -3? c @ 33? $ @ 43?
a U % SS c U $ 99 returns
3 % U a SS $ U c 99 returns
a U % ZZ $ U c 99 returns

7itwise /perators
7itwise operators are use$ to mo$if" the %its of a varia%le. The mikroC %itwise
operators are liste$ in Ta%le 3.L.
7itwise AG, returns if %oth %its are # otherwise it returns 3.
7itwise /R returns 3 if %oth %its are 3# otherwise it returns .
7itwise M/R returns if %oth %its are complementar"# otherwise it returns 3.
7itwise complement inverts each %it.
7itwise shift left an$ shift right move the %its to the left or right respectivel".
Ta%le 3.L( mikroC %itwise operators
/perator /peration
S 7itwise AG,
Z 7itwise /R

7itwise EM/R
7itwise complement
WW 'hift left
UU 'hift right
The following e8ample illustrates the use of %itwise operators(
i. 386A S 38EE returns 38EA
386A( 33
38EE( 3 3
& & & & & & & & & &
& &
38EA( 3 33
ii. 383 Z 386E returns
3866
383!( 3333 333
386E( 3
& & & & & & & & & &
& &
386E(
iii. 38AA

386 returns
38AA( 33 33
386( 333
& & & & & & & & & &
& &
387A( 3 33
iv. 38AA returns 38
38AA( 33 33
( 33 33
& & & & & & & & & &
& &
38AA( 33 33
v. 384 UU returns 383! *shift 384 right %" $igit+
384( 333 333
UU ( 3333 33
& & & & & & & & & & & &
383A( 3333 33
vi. 384 UU - returns 383A *shift 384 right %" - $igits+
384( 333 333
UU -( 3333 33
& & & & & & & & & & & &
383A( 3333 33
vii. 38-3AA WW returns 384E74 *shift left 38-3AA left %" $igit+
38-3AA( 333 33 33 33
WW ( 333 33 3 333
& & & & & & & & & & & & & & & & & & &
384E74 ( 333 33 3 333
viii. 38A WW 3 returns 38,3 *shift left 38A %" 3 $igits+
38A( 333 33
WW3 ( 3 3333
& & & & & & & & & & & &
38,3( 3 3333
Assignment /perators
In C language there are two t"pes of assignments( simple an$ compoun$. In simple
assignments an e8pression is simpl" assigne$ to another e8pression# or an operation is
performe$ using an e8pression an$ the result is assigne$ to another e8pression(
E8pression @ E8pression-
or
Result @ E8pression operation E8pression-
E8amples of simple assignments are(
Temp @ 3?
Cnt @ Cnt D Temp?
Compoun$ assignments have the general format(
Result operation @ E8pression

Here the specifie$ operation is performe$ on E8pression an$ the result is store$ in
Result. 6or e8ample(
5 D@ k? is same as( 5 @ 5 D k?
also
p ;@ m? is same as p @ p ; m?
The following compoun$ operators can %e use$ in mikroC programs(
D@ @ ;@ 9@ V@
S@ Z@ @ UU@ WW@
Con$itional /perators
The s"nta8 of a con$itional operator is(
Result @ E8pression [ E8pression- ( E8pression3
E8pression is evaluate$ first# an$ if its value is true# E8pression- is assigne$ to Result#
otherwise E8pression3 is assigne$ to Result. In the following e8ample# the ma8imum
of 8 an$ " is foun$ where 8 is compare$ with " an$ if 8 U " then ma8 @ 8#
otherwise ma8 @ "(
ma8 @ \8 U "] [ 8 ( "?
In the following e8ample# lowercase characters are converte$ to uppercase. If the
character is lowercase *%etween a an$ H+# then %" su%tracting 3- from the character
we o%tain the eCuivalent uppercase character(
c @ \c U @ a SS c W @ H] [ \c 3- + ( c?
Preprocessor /perators
The preprocessor allows a programmer to(

Compile a program con$itionall"# such that parts of the co$e are not compile$

Replace s"m%ols with other s"m%ols or values

Insert te8t files into a program
The preprocessor operator is the *:^<+ character# an$ an" line of co$e lea$ing with a
*:^<+ is assume$ to %e a preprocessor comman$. The semicolon character *:?<+ is not
nee$e$ to terminate a preprocessor comman$.
mikroC compiler supports the following preprocessor comman$s(
^$efine ^un$ef
^if ^elif ^en$if
^if$ef ^ifn$ef
^error
^line
^$efine# ^un$ef# ^if$ef# ^ifn$ef The ^$efine preprocessor comman$ provi$es macro
e8pansion where ever" occurrence of an i$entifier in the program is replace$ with
the value of that i$entifier. 6or e8ample# to replace ever" occurrence of )AM
with value 33 we can write(
^$efine )AM 33
An i$entifier that has alrea$" %een $efine$ cannot %e $efine$ again unless %oth
$efinitions have the same value. /ne wa" to get aroun$ this pro%lem is to remove the
macro $efinition(
^un$ef )AM
Alternativel"# the e8istence of a macro $efinition can %e checke$. In the following
e8ample# if )AM has not alrea$" %een $efine$# it is given value 33# otherwise the
^$efine line is skippe$(
^ifn$ef )AM
^$efine )AM 33
^en$if
Gote that the ^$efine preprocessor comman$ $oes not occup" an" space in memor".
Be can pass parameters to a macro $efinition %" specif"ing the parameters in a
parenthesis after the macro name. 6or e8ample# consi$er the macro $efinition(
^$efine A,,*a# %+ *a D %+
Bhen this macro is use$ in a program# *a# %+ will %e replace$ with *a D %+ as shown(
p @ A,,*8# "+ will %e transforme$ into p @ *8 D "+
'imilarl"# we can $efine a macro to calculate the sCuare of two num%ers(
^$efine 'R0ARE*a+ *a ; a+
Be can now use this macro in a program(
p @ 'R0ARE*8+ will %e transforme$ into p @ *8 ; 8+
^inclu$e The preprocessor $irective ^inclu$e is use$ to inclu$e a source file in our
program. 0suall" hea$er files with e8tension :.h< are use$ with ^inclu$e. There are two
formats for using ^inclu$e(
^inclu$e WfileU
an$
^inclu$e :file<
In first option the file is searche$ in the mikroC installation $irector" first an$ then
in user search paths. In secon$ option the specifie$ file is searche$ in the mikroC
pro5ect fol$er# then in the mikroC installation fol$er# an$ then in user search paths.
It is also possi%le to specif" a complete $irector" path as(
^inclu$e :C(OtempOlast.h<
The file is then searche$ onl" in the specifie$ $irector" path.
^if# ^elif# ^else# ^en$if The preprocessor comman$s ^if# ^elif# ^else# an$ ^en$if are
use$ for con$itional compilations# where parts of the source co$e can %e compile$ onl"
if certain con$itions are met. In the following e8ample# the co$e section where varia%les
A an$ 7 are cleare$ to Hero is compile$ if ) has a nonHero value# otherwise the
co$e section where A an$ 7 are %oth set to is compile$. Gotice that the ^if must
%e terminate$ with ^en$if(
^if )
^else
A @ 3?
7 @ 3?
A @ ?
7 @ ?
^en$if
Be can also use the ^elif con$ition# which tests for a new con$ition if the previous
con$ition was false(
^if )
A @ 3?
7 @ 3?
^elif G
A @ ?
7 @ ?
^else
A @ -?
7 @ -?
^en$if
In the a%ove e8ample# if ) has a nonHero value co$e section# A @ 3? 7 @ 3? are
compile$. /therwise# if G has a nonHero value# then co$e section A @ ? 7 @ ? is
compile$. 6inall"# if %oth ) an$ G are Hero# then co$e section A @ -? 7 @ -? is
compile$. Gotice that onl" one co$e section is compile$ %etween ^if an$ ^en$if an$
that a co$e section can contain an" num%er of statements.
3..J )o$if"ing the 6low of Control
'tatements are normall" e8ecute$ seCuentiall" from the %eginning to the en$ of
a program. Be can use control statements to mo$if" this normal seCuential flow
in a C program. The following control statements are availa%le in mikroC programs(

'election statements

0ncon$itional mo$ifications of flow

Iteration statements
'election 'tatements
There are two selection statements( if an$ switch.
if 'tatement The general format of the if statement is(
if*e8pression+
'tatement?
else
'tatement-?
or
if*e8pression+'tatement? else 'tatement-?
If the e8pression evaluates to TR0E# 'tatement is e8ecute$# otherwise 'tatement- is
e8ecute$. The else ke"wor$ is optional an$ ma" %e omitte$. In the following e8ample#
if the value of 8 is greater than )AM then varia%le P is incremente$ %" # otherwise it is
$ecremente$ %" (
if*8 U )AM+
PDD?
else
P ?
Be can have more than one statement %" enclosing the statements within curl"
%rackets. 6or e8ample(
if*8 U )AM+
=
>
else
PDD?
Cnt @ P?
'um @ 'um D Cnt?
P ?
In this e8ample# if 8 is greater than )AM then the three statements within the curl"
%rackets are e8ecute$# otherwise the statement P is e8ecute$.
Another e8ample using the if statement is(
if*8 U 3 SS 8 W 3+
=
>
else
=
>
Total D@ 'um?
'umDD?
Total @ 3?
'um @ 3?
switch 'tatement The switch statement is use$ when a num%er of con$itions an$
$ifferent operations are performe$ if a con$ition is true. The s"nta8 of the switch
statement is(
switch *con$ition+
=
case con$ition(
'tatements?
%reak?
case con$ition-(
'tatements?
%reak?
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
case con$ition(
'tatements?
%reak?
$efault(
>
'tatements?
The switch statement functions as follows( 6irst the con$ition is evaluate$. The
con$ition is then compare$ to con$ition an$ if a match is foun$# statements in that case
%lock are evaluate$ an$ control 5umps outsi$e the switch statement when the %reak
ke"wor$ is encountere$. If a match is not foun$# con$ition is compare$ to con$ition-
an$ if a match is foun$# statements in that case %lock are evaluate$ an$ control 5umps
outsi$e the switch statements# an$ so on. The $efault is optional# an$ statements
following $efault are evaluate$ if the con$ition $oes not match an" of the con$itions
specifie$ after the case ke"wor$s.
In the following e8ample# the value of varia%le Cnt is evaluate$. If Cnt @ # A is set to
. If Cnt @ 3# 7 is set to # an$ if Cnt @ 33# C is set to . If Cnt is not eCual to # 3#
or 33 then , is set to (
switch *Cnt+
=
case (
case 3(
A @ ?
%reak?
7 @ ?
%reak?
case ( A _ ? %reak?
case 3( 7 _ ? %reak?
case 33( C _ ? %reak?
$efault( , _ ?
case 33(
$efault(
>
C @ ?
%reak?
, @ ?
7ecause white spaces are ignore$ in C language we can also write the prece$ing
co$e as(
switch *Cnt+
=
>
E8ample 3.
In an e8periment the relationship %etween M an$ T values are foun$ to %e(
M T
3.-
- -.A
3 !.J
4 .-
A -.J
Brite a switch statement that will return the T value# given the M value.
'olution 3.
The reCuire$ switch statement is(
switch *M+
=
case (
case -(
T @ 3.-?
%reak?
T @ -.A?
%reak?
case 3(
case 4(
case A(
>
T @ !.J?
%reak?
T @ .-?
%reak?
T @ -.J?
Iteration 'tatements
Iteration statements ena%le us to perform loops in a program# where part of a co$e must
%e repeate$ a num%er of times. In mikroC iteration can %e performe$ in four wa"s. Be
will look at each one with e8amples(

0sing for statement

0sing while statement

0sing $o statement

0sing goto statement
for 'tatement The s"nta8 of a for statement is(
for*initial e8pression? con$ition e8pression? increment
e8pression+
=
'tatements?
>
The initial e8pression sets the starting varia%le of the loop# an$ this varia%le is
compare$ against the con$ition e8pression %efore entr" into the loop. 'tatements insi$e
the loop are e8ecute$ repeate$l"# an$ after each iteration the value of the increment
e8pression is incremente$. The iteration continues until the con$ition e8pression
%ecomes false. An en$less loop is forme$ if the con$ition e8pression is alwa"s true.
The following e8ample shows how a loop can %e set up to e8ecute 3 times. In this
e8ample# varia%le i starts from 3 an$ increments %" at the en$ of each iteration. The
loop terminates when i @3# in which case the con$ition i W 3 %ecomes false. /n e8it
from the loop# the value of i is 3(
for*i @ 3? i W 3? i DD+
=
statements?
>
This loop coul$ also %e starte$ %" an initial e8pression with a nonHero value. Here# i
starts with an$ the loop terminates when i @ . Thus# on e8it from the loop# the value
of i is (
for*i @ ? i W@ 3? iDD+
=
'tatements?
>
The parameters of a for loop are all optional an$ can %e omitte$. If the con$ition
e8pression is left out# it is assume$ to %e true. In the following e8ample# an en$less loop
is forme$ where the con$ition e8pression is alwa"s true an$ the value of i starts with
3 an$ is incremente$ after each iteration(
9; En$less loop with incrementing i ;9
for*i@3? ? iDD+
=
'tatements?
>
In the following e8ample of an en$less loop all the parameters are omitte$(
9; E8ample of en$less loop ;9
for*? ?+
=
'tatements?
>
In the following en$less loop# i starts with an$ is not incremente$ insi$e
the loop(
9; En$less loop with i @ ;9
for*i@? ?+
=
'tatements?
>
If there is onl" one statement insi$e the for loop# he curl" %rackets can %e omitte$ as
shown in the following e8ample(
for*k @ 3? k W 3? kDD+Total @ Total D 'um?
Geste$ for loops can also %e use$. In a neste$ for loop# the inner loop is e8ecute$ for
each iteration of the outer loop. In the following e8ample the inner loop is e8ecute$ five
times an$ the outer loop is e8ecute$ ten times. The total iteration count is fift"(
9; E8ample of neste$ for loops
;9
for*i @ 3? i W 3? iDD+
=
for*5 @ 3? 5 W A? 5DD+
=
'tatements?
>
>
In the following e8ample# the sum of all the elements of a 3 4 matri8 ) is calculate$
an$ store$ in a varia%le calle$ 'um(
9; A$$ all elements of a 384 matri8
;9 'um @ 3?
for*i @ 3? i W 3? iDD+
=
for*5 @ 3? 5 W 4? 5DD+
=
'um @ 'um D ) PiQP5Q?
>
>
'ince there is onl" one statement to %e e8ecute$# the prece$ing e8ample coul$ also %e
written as(
9; A$$ all elements of a 384 matri8
;9 'um @ 3?
for*i @ 3? i W 3? iDD+
=
for*5 @ 3? 5 W 4? 5DD+ 'um @ 'um D ) PiQP5Q?
>
while 'tatement The s"nta8 of a while statement is(
while *con$ition+
=
'tatements?
>
Here# the statements are e8ecute$ repeate$l" until the con$ition %ecomes false# or the
statements are e8ecute$ repeate$l" as long as the con$ition is true. If the con$ition is
false on entr" to the loop# then the loop will not %e e8ecute$ an$ the program will
continue from the en$ of the while loop. It is important that the con$ition is change$
insi$e the loop# otherwise an en$less loop will %e forme$.
The following co$e shows how to set up a loop to e8ecute 3 times# using the while
statement(
9; A loop that e8ecutes 3 times ;9
k @ 3?
while *k W 3+
=
'tatements?
kDD?
>
At the %eginning of the co$e# varia%le k is 3. 'ince k is less than 3# the while loop
starts. Insi$e the loop the value of k is incremente$ %" after each iteration. The loop
repeats as long as k W 3 an$ is terminate$ when k @ 3. At the en$ of the loop the
value of k is 3.
Gotice that an en$less loop will %e forme$ if k is not incremente$ insi$e the loop(
9; An en$less loop ;9
k @ 3?
while *k W 3+
=
'tatements?
>
An en$less loop can also %e forme$ %" setting the con$ition to %e alwa"s true(
9; An en$less loop ;9
while *k @ k+
=
'tatements?
>
Here is an e8ample of calculating the sum of num%ers from to 3 an$ storing the
result in a varia%le calle$ sum(
9; Calculate the sum of num%ers from to 3 ;9
unsigne$ int k# sum?
k @ ? sum @ 3?
while*k W@ 3+
=
sum @ sum D k?
kDD?
>
It is possi%le to have a while statement with no %o$". 'uch a statement is useful# for
e8ample# if we are waiting for an input port to change its value. An e8ample follows
where the program will wait as long as %it 3 of P/RT7 *P/RT7.3+ is at logic 3. The
program will continue when the port pin changes to logic (
while*P/RT7.3 @@ 3+? 99 Bait until P/RT7.3 %ecomes
or
while*P/RT7.3+?
It is also possi%le to have neste$ while statements.
$o 'tatement A $o statement is similar to a while statement e8cept that the loop
e8ecutes until the con$ition %ecomes false# or# the loop e8ecutes as long as the
con$ition is true. The con$ition is teste$ at the en$ of the loop. The s"nta8 of a $o
statement is(
$o
=
'tatements?
> while *con$ition+?
The first iteration is alwa"s performe$ whether the con$ition is true or false. This is the
main $ifference %etween a while statement an$ a $o statement.
The following co$e shows how to set up a loop to e8ecute 3 times using the $o
statement(
9; E8ecute 3 times ;9
k @ 3?
$o
=
'tatements?
kDD?
> while *k W 3+?
The loop starts with k @ 3# an$ the value of k is incremente$ insi$e the loop after each
iteration. At the en$ of the loop k is teste$# an$ if k is not less than 3# the loop
terminates. In this e8ample %ecause k @ 3 is at the %eginning of the loop# the value of k
is 3 at the en$ of the loop.
An en$less loop will %e forme$ if the con$ition is not mo$ifie$ insi$e the loop# as
shown in the following e8ample. Here k is alwa"s less than 3(
9; An en$less loop ;9
k @ 3?
$o
=
'tatements?
> while *k W 3+?
An en$less loop can also %e create$ if the con$ition is set to %e true all the time(
9; An en$less loop ;9
$o
=
'tatements?
> while *k @ k+?
It is also possi%le to have neste$ $o statements.
0ncon$itional )o$ifications of 6low
goto 'tatement A goto statement can %e use$ to alter the normal flow of control in a
program. It causes the program to 5ump to a specifie$ la%el. A la%el can %e an"
alphanumeric character set starting with a letter an$ terminating with the colon *:(<+
character.
Although not recommen$e$# a goto statement can %e use$ together with an if statement
to create iterations in a program. The following e8ample shows how to set up a loop to
e8ecute 3 times using goto an$ if statements(
9; E8ecute 3 times ;9
k @ 3?
Loop(
'tatements?
kDD?
if*k W 3+goto Loop?
The loop starts with la%el Loop an$ varia%le k @ 3 at the %eginning of the loop. Insi$e
the loop the statements are e8ecute$ an$ k is incremente$ %" . The value of k is then
compare$ with 3 an$ the program 5umps %ack to la%el Loop if k W 3. Thus# the loop
is e8ecute$ 3 times until the con$ition at the en$ %ecomes false. At the en$ of the loop
the value of k is 3.
continue an$ %reak 'tatements continue an$ %reak statements can %e use$ insi$e
iterations to mo$if" the flow of control. A continue statement is usuall" use$ with an if
statement an$ causes the loop to skip an iteration. An e8ample follows that calculates
the sum of num%ers from to 3 e8cept num%er A(
9; Calculate sum of num%ers #-#3#4#E#L#!#J#3
;9 'um @ 3?
i @ ?
for*i @ ? i W@ 3? iDD+
=
if*i @@ A+ continue? 99 'kip num%er A
'um @ 'um D i?
>
'imilarl"# a %reak statement can %e use$ to terminate a loop from insi$e the loop. In the
following e8ample# the sum of num%ers from to A is calculate$ even though the loop
parameters are set to iterate 3 times(
9; Calculate sum of num%ers #-#3#4#A
;9 'um @ 3?
i @ ?
for*i @ ? i W@ 3? iDD+
=
if*i U A+ %reak? 99 'top loop if i U A
'um @ 'um D i?
>
3..-3 )i8ing mikroC with Assem%l" Language 'tatements
It sometimes %ecomes necessar" to mi8 PIC microcontroller assem%l" language
statements with the mikroC language. 6or e8ample# ver" accurate program $ela"s can
%e generate$ %" using assem%l" language statements. The topic of assem%l" language
is %e"on$ the scope of this %ook# %ut techniCues for inclu$ing assem%l" language
instructions in mikroC programs are $iscusse$ in this section for rea$ers who are
familiar with the PIC microcontroller assem%l" languages.
Assem%l" language instructions can %e inclu$e$ in a mikroC program %" using the
ke"wor$ asm *or Kasm# or asm+. A group of assem%l" instructions or a single such
instruction can %e inclu$e$ within a pair of curl" %rackets. The s"nta8 is(
asm
=
assem%l" instructions
>
Assem%l" language st"le comments *a line starting with a semicolon character+ are not
allowe$# %ut mikroC $oes allow %oth t"pes of C st"le comments to %e use$ with
assem%l" language programs(
asm
=
9; This assem%l" co$e intro$uces $ela" to the
program;9 )/FLB E 99 Loa$ B with E
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
>
0ser&$eclare$ C varia%les can %e use$ in assem%l" language routines# %ut the" must %e
$eclare$ an$ initialiHe$ %efore use. 6or e8ample# C varia%le Temp can %e initialiHe$ an$
then loa$e$ to the B register as(
unsigne$ char Temp @ 3?
asm
=
)/FLB Temp 99 B @ Temp @ 3
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
>
Ylo%al s"m%ols such as pre$efine$ port names an$ register names can %e use$ in
assem%l" language routines without having to initialiHe them(
asm
=
>
)/FB6 P/RT7
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
3.- PIC )icrocontroller Input&/utput
Port Programming
,epen$ing on the t"pe of microcontroller use$# PIC microcontroller input&output ports
are name$ as P/RTA# P/RT7# P/RTC# an$ so on. Port pins can %e in analog or $igital
mo$e. In analog mo$e# ports are input onl" an$ a %uilt&in analog&to&$igital converter
an$ multiple8er circuits are use$. In $igital mo$e# a port pin can %e configure$ as either
input or output. The TRI' registers control the port $irections# an$ there are TRI'
registers for each port# name$ as TRI'A# TRI'7# TRI'C# an$ so on. Clearing a TRI'
register %it to 3 sets the correspon$ing port %it to output mo$e. 'imilarl"# setting a TRI'
register %it to sets the correspon$ing port %it to input mo$e.
Ports can %e accesse$ as a single !&%it register# or in$ivi$ual %its of a port can %e
accesse$. In the following e8ample# P/RT7 is configure$ as an output port an$ all its
%its are set to a (
TRI'7 @ 3? 99 'et P/RT7 as output
P/RT7 @ 3866? 99 'et P/RT7 %its to
'imilarl"# the following e8ample shows how the 4 upper %its of P/RTC can %e set as
input an$ the 4 lower %its of P/RTC can %e set as output(
TRI'C @ 3863?
7its of an input&output port can %e accesse$ %" specif"ing the reCuire$ %it num%er. In
the following e8ample# varia%le P- is loa$e$ with %it - of P/RT7(
P- @ P/RT7.-?
All the %its of a port can %e complemente$ %" the statement(
P/RT7 @ P/RT7?
3.3 Programming E8amples
In this section# some simple programming e8amples are given to familiariHe the rea$er
with programming in C.
E8ample 3.-
Brite a program to set all eight port pins of P/RT7 to logic .
'olution 3.-
P/RT7 is configure$ as an output port# an$ then all port pins are set to logic %"
sen$ing he8a$ecimal num%er 3866(
voi$ main*+
=
TRI'7 @ 3? 99 Configure P/RT7 as output
P/RT7 @ 3866? 99 'et all port pins to logic a
>
E8ample 3.3
Brite a program to set the o$$&num%ere$ P/RT7 pins *%its # 3# A# an$ L+ to logic .
'olution 3.3
/$$&num%ere$ port pins can %e set to logic %" sen$ing the %it pattern 3333
to the port. This %it pattern is the he8a$ecimal num%er 38AA an$ the reCuire$
program is(
voi$ main*+
=
TRI'7 @ 3? 99 Configure P/RT7 as output
P/RT7 @ 38AA? 99 Turn on o$$ num%ere$ port pins
>
E8ample 3.4
Brite a program to continuousl" count up in %inar" an$ sen$ this $ata to P/RT7. Thus
P/RT7 reCuires the %inar" $ata(
33333333
3333333
3333333
333333
. . . . . . . . . . . .
. . . . . . . . . . . .
3

33333333
. . . . . . . . . . . .
'olution 3.4
A for loop can %e use$ to create an en$less loop# an$ insi$e this loop the value of a
varia%le can %e incremente$ an$ then sent to P/RT7(
voi$ main*+
=
unsigne$ char Cnt @ 3?
for*??+ 99 En$less loop
=
P/RT7 @ Cnt? 99 'en$ Cnt to
P/RT7 CntDD? 99 Increment Cnt
>
>
E8ample 3.A
Brite a program to set all %its of P/RT7 to logic an$ then to logic 3# an$ to repeat
this process ten times.
'olution 3.A
A for statement can %e use$ to create a loop to repeat the reCuire$ operation ten times(
voi$ main*+
=
unsigne$ char 5?
for*5 @ 3? 5 W 3? 5DD+ 99 Repeat 3 times
=
P/RT7 @ 3866? 99 'et P/RT7 pins to
P/RT7 @ 3? 99 Clear P/RT7 pins
>
>
E8ample 3.E
The ra$ius an$ height of a c"lin$er are -.Acm an$ 3cm respectivel". Brite a program
to calculate the volume of this c"lin$er.
'olution 3.E
The reCuire$ program is(
voi$ main*+
=
float Ra$ius @ -.A# Height @ 3?
float Folume?
Folume @ PI ;Ra$ius;Ra$ius;Height?
>
E8ample 3.L
Brite a program to fin$ the largest element of an integer arra" having ten elements.
'olution 3.L
At the %eginning# varia%le m is set to the first element of the arra". A loop is then
forme$ an$ the largest element of the arra" is foun$(
voi$ main*+
=
unsigne$ char 5?
int m# A P3Q?
m @ A P3Q? 99 6irst element of arra"
for*5 @ ? 5 W 3? 5DD+
=
if*A P5QU m+m @ AP5Q?
>
>
E8ample 3.!
Brite a program using a while statement to clear all ten elements of an integer
arra" ).
'olution 3.!
As shown in the program that follows# G0) is $efine$ as 3 an$ varia%le 5 is use$ as
the loop counter(
^$efine G0) 3
voi$ main*+
=
int ) PG0)Q?
unsigne$ char 5 @ 3?
while *5 W G0)+
=
) P5Q @ 3?
5DD?
>
>
E8ample 3.J
Brite a program to convert the temperature from

C to

6 starting from 3

C# in steps of


C up to an$ inclu$ing 33

C# an$ store the results in an arra" calle$ 6.
'olution 3.J
Yiven the temperature in

C# the eCuivalent in

6 is calculate$ using the formula(
6 @ \C 3-(3]@(!
A for loop is use$ to calculate the temperature in

6 an$ store in arra" 6(
voi$ main*+
=
float 6P33Q?
unsigne$ char C?
for*C @ 3? C W@ 33? CDD+
=
6 PCQ @ *C 1 3-.3+ 9 .!?
>
>
3.4 'ummar"
There are man" assem%l" an$ high&level languages for the PIC! series of
microcontrollers. This %ook focuses on the mikroC compiler# since it is eas" to learn
an$ a free $emo version is availa%le that allows users to $evelop programs as large as
-. in siHe.
This chapter presente$ an intro$uction to the mikroC language. A C program ma"
contain a num%er of functions an$ varia%les plus a main program. The %eginning of the
main program is in$icate$ %" the statement voi$ main*+.
A varia%le stores a value use$ $uring the computation. All varia%les in C must %e
$eclare$ %efore the" are use$. A varia%le can %e an !&%it character# a E&%it integer# a
3-&%it long# or a floating point num%er. Constants are store$ in the flash program
memor" of PIC microcontrollers# so using them avoi$s using valua%le an$ limite$ RA)
memor".
Farious flow control an$ iteration statements such as if# switch# while# $o# %reak# an$ so
on have %een $escri%e$ in the chapter# with e8amples.
Pointers are use$ to store the a$$resses of varia%les. As we shall see in the ne8t chapter#
pointers can %e use$ to pass information %ack an$ forth %etween a function an$ its
calling point. 6or e8ample# pointers can %e use$ to pass varia%les %etween a main
program an$ a function.
3.A E8ercises
. Brite a C program to set %its 3 an$ L of P/RTC to logic .
-. Brite a C program to count $own continuousl" an$ sen$ the count to P/RT7.
3. Brite a C program to multipl" each element of a ten element arra" %" -.
4. Brite a C program to a$$ two matrices P an$ R. Assume that the $imension of
each matri8 is 3 3 an$ store the result in another matri8 calle$ B.
A. Repeat E8ercise 4 %ut this time multipl" matrices P an$ R an$ store the pro$uct in
matri8 R.
E. Bhat $o the terms varia%le an$ constant mean[
L. Bhat $oes program repetition mean[ ,escri%e the operation of while# $o&while#
an$ for loops in C.
!. Bhat is an arra"[ Brite e8ample statements to $efine the following arra"s(
a+ An arra" of ten integers
%+ An arra" of thirt" floats
c+ A two&$imensional arra" having si8 rows an$ ten columns
J. Trace the operation of the following loops. Bhat will %e the value of varia%le H at
the en$ of each loop[
a+ unsigne$ char 5 @ 3# H @ 3?
while*5 W 3+
=
HDD?
5DD?
>
%+ unsigne$ char H @ 3?
for*5 @ 3? 5 W 3? 5DD+H ?
3. Yiven the following varia%le $efinitions# list the outcome of the following
con$itional tests in terms of :true< or :false<(
unsigne$ int a @ 3# % @ -?
if*a U 3+
if*% U@ -+
if*a @@ 3+
if*a U 3+
. Brite a program to calculate whether a num%er is o$$ or even.
-. ,etermine the value of the following %itwise operations using AG,# /R# an$
EM/R operations(
/peran$ ( 333333
/peran$ -( 333
3. How man" times $oes each of the following loops iterate# an$ what is the final
value of the varia%le 5 in each case[
a+ for*5 @ 3? 5 W A? 5DD+
%+ for*5 @ ? 5 W 3? 5DD+
c+ for*5 @ 3? 5 W@ 3? 5DD+
$+ for*5 @ 3? 5 W@ 3? 5 D@ -+
e+ for*5 @ 3? 5 U 3? 5 @ -+
4. Brite a program to calculate the sum of all positive integer num%ers from to 33.
A. Brite a program to evaluate factorial n# where 3X an$ X evaluate to an$
nX @ n *n 1 +X
E. Brite a program to calculate the average value of the num%ers store$ in an arra".
Assume that the arra" is calle$ ) an$ has twent" elements.
L. )o$if" the program in E8ercise E to fin$ the smallest an$ largest values of the
arra". 'tore the smallest value in a varia%le calle$ 'ml an$ the largest value in a
varia%le calle$ Lrg.
!. ,erive eCuivalent if&else statements for the following tests(
a+ *a U %+ [ 3 (
%+ *8 W "+ [ *a U %+ ( *c U $+
J. Yiven that f an$ f- are %oth floating point varia%les# e8plain wh" the following
test e8pression controlling the while loop ma" not %e safe(
$o
=
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
> while*f X@ f-+?
Bh" woul$ the pro%lem not occur if %oth f an$ f- were integers[ How woul$ "ou
correct this while loop[
-3. Bhat can "ou sa" a%out the following while loop[
k @ 3? Total @
3? while *k W
3+
=
'umDD?
Total D@ 'um?
>
-. Bhat can "ou sa" a%out the following for loop[
Cnt @ 3?
for*??+
=
CntDD?
>
This page intentionall" left %lank
www. newnespress. co m
CHAP T E R 4
6unctions an$ Li%raries in mikroC
4. mikroC 6unctions
A function is a self&containe$ section of co$e written to perform a specificall" $efine$
action. 6unctions are usuall" create$ when a single operation must %e performe$ in
$ifferent parts of the main program. It is# moreover# goo$ programming practice to
$ivi$e a large program into a num%er of smaller# in$epen$ent functions. The statements
within a function are e8ecute$ %" calling *or invoking+ the function.
The general s"nta8 of a function $efinition is shown in 6igure 4.. The $ata t"pe
in$icates the t"pe of $ata returne$ %" the function. This is followe$ %" the name of the
function an$ then a set of parentheses# within which the arguments# separate$ %"
commas# are $eclare$. The %o$" of the function# which inclu$es the function2s
operational co$e# is written insi$e a set of curl" %rackets.
In the sample function $efinition that follows# the function# name$ )ult# receives two
integer arguments# a an$ %# an$ returns their pro$uct. Gote that using parentheses in a
return statement is optional(
int )ult*int a# int %+
=
return *a;%+?
>
Bhen a function is calle$# it generall" e8pects to %e given the num%er of arguments
e8presse$ in the function2s argument list. 6or e8ample# the prece$ing function can %e
calle$ as(
H @ )ult*8# "+?
L3 Chapter 4
ss. co m
!+pe name 3parame!er/, parame!er-,<''4
5
<<<<'
f8n!ion )o"+
<<<<'
;
6igure 4.( Yeneral s"nta8 of a function $efinition
where varia%le H has the $ata t"pe int. Gote that the arguments $eclare$ in the
function $efinition an$ the arguments passe$ when the function is calle$ are
in$epen$ent of each other# even if the" have the same name. In the prece$ing e8ample#
when the function is calle$# varia%le 8 is copie$ to a an$ varia%le " is copie$ to % on
entr" into function )ult.
'ome functions $o not return an" $ata. The $ata t"pe of such functions must %e $eclare$
as voi$. 6or e8ample(
voi$ LE,*unsigne$ char ,+
=
P/RT7 @ ,?
>
voi$ functions can %e calle$ without an" assignment statements# %ut the parentheses are
nee$e$ to tell the compiler that a function call is ma$e(
LE,* +?
Also# some functions $o not have an" arguments. In the following e8ample# the
function# name$ Compl# complements P/RTC of the microcontroller. It returns no $ata
an$ has no arguments(
voi$ Compl* +
=
P/RTC @ P/RTC?
>
This function can %e calle$ as(
Compl* +?
6unctions are normall" $efine$ %efore the start of the main program.
'ome function $efinitions an$ their use in main programs are illustrate$ in the
following e8amples(
www. newnespress. co m
6unctions an$ Li%raries in mikroC L
E8ample 4.
Brite a function calle$ CircleKArea to calculate the area of a circle where the ra$ius is
to %e use$ as an argument. 0se this function in a main program to calculate the area of a
circle whose ra$ius is -.Acm. 'tore the area in a varia%le calle$ Circ.
'olution 4.
The $ata t"pe of the function is $eclare$ as float. The area of a circle is calculate$
%" the formula(
Area @ pr
-
where r is the ra$ius of the circle. The area is calculate$ an$ store$ in a local
varia%le calle$ s# which is then returne$ from the function(
float CircleKArea*float ra$ius+
=
float s?
s @ PI ; ra$ius ; ra$ius?
return s?
>
6igure 4.- shows how the function CircleKArea can %e use$ in a main program to
calculate the area of a circle whose ra$ius is -.Acm. The function is $efine$ %efore
the main program. Insi$e the main program the function is calle$ to calculate an$
store the area in varia%le Circ.
E8ample 4.-
Brite a function calle$ Area an$ a function calle$ Folume to calculate the area an$
volume of a c"lin$er respectivel". Then write a main program to calculate the area
an$ the volume of c"lin$er whose ra$ius is -.3cm an$ height is A.3cm. 'tore the area
in varia%le c"lKarea an$ the volume in varia%le c"lKvolume.
'olution 4.-
The area of a c"lin$er is calculate$ %" the formula(
Area @ -prh
ss. co m
L- Chapter 4
/
AREA OF A *IR*LE
7777777777777777
This program alls !o f8n!ion *irle9Area !o al8la!e !he area of a irle'
Programmer( Dogan I)rahim
File( *IR*LE'*
Da!e( Ma+, -$$.

/

This f8n!ion al8la!es !he area of a irle gi&en !he ra"i8s

/
float *irle9Area3floa! ra"i8s4
5
float s6
s 7 PI

ra"i8s

ra"i8s6
re!8rn s6
;
/

S!ar! of main program' *al8la!e !he area of a irle %here ra"i8s 7 -'2

/
&oi" main34
5
float r, *ir6
r 7 -'26
*ir 7 *irle9Area3r46
;
6igure 4.-( Program to calculate the area of a circle
where r an$ h are the ra$ius an$ height of the c"lin$er. The volume of a c"lin$er is
calculate$ %" the formula(
Folume @ pr
-
h
6igure 4.3 shows the functions that calculate the area an$ volume of a c"lin$er.
The main program that calculates the area an$ volume of a c"lin$er whose ra$ius @
-.3cm an$ height @ A.3cm is shown in 6igure 4.4.
E8ample 4.3
Brite a function calle$ LowerTo0pper to convert a lowercase character to uppercase.
www. newnespress. co m
6unctions an$ Li%raries in mikroC L3
float Area3floa! ra"i8s, floa! heigh!4
5
float s6
s 7 -'$

PI

ra"i8s

heigh!6
re!8rn s6
;
float =ol8me3floa! ra"i8s, floa! heigh!4
5
float s6
s 7 PI

ra"i8s

ra"i8s

heigh!6
re!8rn s6
;
6igure 4.3( 6unctions to calculate c"lin$er area an$ volume
'olution 4.3
The A'CII value of the first uppercase character *NA2+ is 3 4. 'imilarl"# the A'CII
value of the first lowercase character *Na2+ is 3 E. An uppercase character can %e
converte$ to its eCuivalent lowercase %" su%tracting 3 -3 from the character. The
reCuire$ function listing is shown in 6igure 4.A.
E8ample 4.4
0se the function "ou create$ in E8ample 4.3 in a main program to convert letter Nr2 to
uppercase.
'olution 4.4
The reCuire$ program is shown in 6igure 4.E. 6unction LowerTo0pper is calle$ to
convert the lowercase character in varia%le Lc to uppercase an$ store in 0c.
4.. 6unction Protot"pes
If a function is not $efine$ %efore it is calle$# the compiler will generate an error
message. /ne wa" aroun$ this pro%lem is to create a function protot"pe. A function
protot"pe is easil" constructe$ %" making a cop" of the function2s hea$er an$
appen$ing a semicolon to it. If the function has parameters# giving names to these
ss. co m
L4 Chapter 4
/
AREA AND =OL>ME OF A *?LINDER
7777777777777777777777777777777
This program al8la!es !he area an" &ol8me of a +lin"er %hose ra"i8s is -'$m
an" heigh! is 2'$m'
Programmer( Dogan I)rahim
File( *?LINDER'*
Da!e( Ma+, -$$.
/
/

F8n!ion !o al8la!e !he area of a +lin"er

/
float Area3floa! ra"i8s, floa! heigh!4
5
float s6
s 7 -'$

PI

ra"i8s*heigh!6
re!8rn s6
;
/

F8n!ion !o al8la!e !he &ol8me of a +lin"er

/
float =ol8me3floa! ra"i8s, floa! heigh!4
5
float s6
s 7 PI

ra"i8s

ra"i8s

heigh!6
re!8rn s6
;
/

S!ar! of !he main program

/
void main34
5
float r 7 -'$, h 7 2'$6
float +l9area, +l9&ol8me6
+l9area 7 Area3r, h46
+l9&ol8me3r, h46
;
6igure 4.4( Program that calculates the area an$ volume of a c"lin$er
parameters is not compulsor"# %ut the $ata t"pe of the parameters must %e $efine$. An
e8ample follows in which a function protot"pe calle$ Area is $eclare$ an$ the function
is e8pecte$ to have a floating point t"pe parameter(
float Area*float
ra$ius+?
www. newnespress. co m
6unctions an$ Li%raries in mikroC LA
unsigned char Lo%erTo>pper38nsigne" har 4
5
if3 @7 AaB CC D7 AEB4
re!8rn 3 F $G-$46
else
;
re!8rn 6
6igure 4.A( 6unction to convert lowercase to uppercase
/
LO:ER*ASE TO >PPER*ASE
77777777777777777777777777
This program on&er!s !he lo%erase hara!er in &aria)le L !o 8pperase
an" s!ores in &aria)le >'
Programmer( Dogan I)rahim
File( LTO>PPER'*
Da!e( Ma+, -$$.
/
/

F8n!ion !o on&er! a lo%er ase hara!er !o 8pper ase

/
unsigned char Lo%erTo>pper38nsigne" har 4
5
if3 @7 AaB CC D7 AEB4
re!8rn 3 F $G-$46
else
;
re!8rn 6
/

S!ar! of main program

/
void main34
5
unsigned char L, >6
L 7 ArB6
> 7 Lo%erTo>pper3L46
;
6igure 4.E( Program calling function LowerTo0pper
This function protot"pe coul$ also %e $eclare$ as(
float Area*float+?
6unction protot"pes shoul$ %e $eclare$ at the %eginning of a program. 6unction
$efinitions an$ function calls can then %e ma$e at an" point in the program.
E8ample 4.A
Repeat E8ample 4.4 %ut $eclare LowerTo0pper as a function protot"pe.
'olution 4.A
6igure 4.L shows the program where function LowerTo0pper is $eclare$ as a function
protot"pe at the %eginning of the program. In this e8ample# the actual function
$efinition is written after the main program.
/ne important a$vantage of using function protot"pes is that if the function protot"pe
$oes not match the actual function $efinition# mikroC will $etect this an$ mo$if" the
/
LO:ER*ASE TO >PPER*ASE
7777777777777777777777777
This program on&er!s !he lo%erase hara!er in &aria)le L !o 8pperase
an" s!ores in &aria)le >'
Programmer( Dogan I)rahim
File( LTO>PPER-'*
Da!e( Ma+, -$$.
/
unsigned char Lo%erTo>pper38nsigne" har46
/

S!ar! of main program

/
void main34
5
unsigned char L, >6
L 7 ArB6
> 7 Lo%erTo>pper3L46
;
/

F8n!ion !o on&er! a lo%er ase hara!er !o 8pper ase

/
unsigned char Lo%erTo>pper38nsigne" har 4
5
if3 @7 AaB CC D7 AEB4
re!8rn 3 F $G-$46
else
;
re!8rn 6
6igure 4.L( Program using function protot"pe
$ata t"pes in the function call to match the $ata t"pes $eclare$ in the function protot"pe.
'uppose we have the following co$e(
unsigne$ char c @ NA2?
unsigne$ int 8 @ 33?
long Tmp?
long )"6unc*long a# long %+? 99 function protot"pe
voi$ main*+
=
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
Tmp @ )"6unc*c# 8+?
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
>
In this e8ample# %ecause the function protot"pe $eclares the two arguments as long#
varia%les c an$ 8 are converte$ to long %efore the" are use$ insi$e function )"6unc.
4..- Passing Arra"s to 6unctions
There are man" applications where we ma" want to pass arra"s to functions. Passing a
single arra" element is straightforwar$# as we simpl" specif" the in$e8 of the arra"
element to %e passe$# as in the following function call which passes the secon$ element
*in$e8 @ + of arra" A to function Calc. It is important to realiHe that an in$ivi$ual arra"
element is passe$ %" value *i.e.# a cop" of the arra" element is passe$ to the function+(
8 @ Calc*A PQ+?
In some applications we ma" want to pass complete arra"s to functions. An arra" name
can %e use$ as an argument to a function# thus permitting the entire arra" to %e passe$.
To pass a complete arra" to a function# the arra" name must appear %" itself within the
%rackets. The siHe of the arra" is not specifie$ within the formal argument $eclaration.
In the function hea$er the arra" name must %e specifie$ with a pair of empt" %rackets.
It is important to realiHe that when a complete arra" is passe$ to a function# what is
actuall" passe$ is not a cop" of the arra" %ut the a$$ress of the first element of the arra"
*i.e.# the arra" elements are passe$ %" reference# which means that the original arra"
elements can %e mo$ifie$ insi$e the function+.
'ome e8amples follow that illustrate the passing of a complete arra" to a function.
E8ample 4.E
Brite a program to store the num%ers to 3 in an arra" calle$ Gum%ers. Then call a
function name$ Average to calculate the average of these num%ers.
'olution 4.E
The reCuire$ program listing is shown in 6igure 4.!. 6unction Average receives the
elements of arra" Gum%ers an$ calculates the average of the arra" elements.
/
PASSING AN ARRA? TO A F>N*TION
7777777777777777777777777777777
This program s!ores n8m)ers / !o /$ in an arra+ alle" N8m)ers' F8n!ion
A&erage is !hen alle" !o al8la!e !he a&erage of !hese n8m)ers'
Programmer( Dogan I)rahim
File( A=ERAGE'*
Da!e( Ma+, -$$.
/
/

F8n!ion !o al8la!e !he a&erage

/
float A&erage3in! AH I4
5
float S8m 7 $'$, J6
unsigned har K6
for3K7$6 KD/$6 KLL4
5
S8m 7 S8m L AHKI6
;
J 7 S8m / /$'$6
re!8rn J6
;
/

S!ar! of !he main program

/
void main34
5
unsigned char K6
float A&rg6
int N8m)ersH/$I6
for3K7$6 KD/$6 KLL4N8m)ersHKI 7 KL/6
A&rg 7 A&erage3N8m)ers46
;
6igure 4.!( Program passing an arra" to a function
E8ample 4.L
Repeat E8ample 4.E# %ut this time $efine the arra" siHe at the %eginning of the program
an$ then pass the arra" siHe to the function.
'olution 4.L
The reCuire$ program listing is shown in 6igure 4.J.
/
PASSING AN ARRA? TO A F>N*TION
7777777777777777777777777777777
This program s!ores n8m)ers / !o N in an arra+ alle" N8m)ers %here N is
"efine" a! !he )eginning of !he program' F8n!ion A&erage is !hen alle" !o
al8la!e !he a&erage of !hese n8m)ers'
Programmer( Dogan I)rahim
File( A=ERAGE-'*
Da!e( Ma+, -$$.
/
#define Arra+9SiEe -$
/

F8n!ion !o al8la!e !he a&erage

/
float A&erage3in! AH I, in! N4
5
float S8m 7 $'$, J6
unsigned har K6
for3K7$6 KDN6 KLL4
5
S8m 7 S8m L AHKI6
;
J 7 S8m / N6
re!8rn J6
;
/

S!ar! of !he main program

/
void main34
5
unsigned char K6
float A&rg6
int N8m)ersHArra+9SiEeI6
for3K7$6 KDArra+9SiEe6 KLL4N8m)ersHKI 7 KL/6
A&rg 7 A&erage3N8m)ers, Arra+9SiEe46
;
6igure 4.J( Another program passing an arra" to a function
It is also possi%le to pass a complete arra" to a function using pointers. The a$$ress of
the first element of the arra" is passe$ to the function# an$ the function can then
manipulate the arra" as reCuire$ using pointer operations. An e8ample follows.
E8ample 4.!
Repeat E8ample 4.E# %ut this time use a pointer to pass the arra" elements to the
function.
'olution 4.!
The reCuire$ program listing is given in 6igure 4.3. An integer pointer is use$ to pass
the arra" elements to the function# an$ the function elements are manipulate$ using
pointer operations. Gotice that the a$$ress of the first element of the arra" is passe$ as
an integer with the statement( SGum%ersP3Q.
4..3 Passing Faria%les %" Reference to 6unctions
7" $efault# arguments to functions are passe$ %" value. Although this metho$ has man"
$istinct a$vantages# there are occasions when it is more appropriate an$ also more
efficient to pass the a$$ress of the arguments instea$# that is# to pass the argument %"
reference. Bhen the a$$ress of an argument is passe$# the original value of that
argument can %e mo$ifie$ %" the function? thus the function $oes not have to return an"
varia%les. An e8ample follows which illustrates how the a$$ress of arguments can %e
passe$ to a function an$ how the values of these arguments can %e mo$ifie$ insi$e the
function.
E8ample 4.J
Brite a function name$ 'wap to accept two integer arguments an$ then to swap the
values of these arguments. 0se this function in a main program to swap the values of
two varia%les.
'olution 4.J
The reCuire$ program listing is shown in 6igure 4.. 6unction 'wap is $efine$ as voi$
since it $oes not return an" value. It has two arguments# a an$ %# an$ in the function
hea$er two integer pointers are use$ to pass the a$$resses of these varia%les. Insi$e the
function %o$"# the value of an argument is accesse$ %" inserting the :;< character in
/
PASSING AN ARRA? TO A F>N*TION
7777777777777777777777777777777
This program s!ores n8m)ers / !o /$ in an arra+ alle" N8m)ers' F8n!ion
A&erage is !hen alle" !o al8la!e !he a&erage of !hese n8m)ers'
Programmer( Dogan I)rahim
File( A=ERAGEM'*
Da!e( Ma+, -$$.
/
/

F8n!ion !o al8la!e !he a&erage

/
float A&erage3in!

A4
5
float S8m 7 $'$, J6
unsigned har K6
for3K7$6 KD/$6 KLL4
5
S8m 7 S8m L

3A L K46
;
J 7 S8m / /$'$6
re!8rn J6
;
/

S!ar! of !he main program

/
void main34
5
unsigned char K6
float A&rg6
int N8m)ersH/$I6
for3K7$6 KD/$6 KLL4N8m)ersHKI 7 KL/6
A&rg 7 A&erage3CN8m)ersH$I46
;
6igure 4.3( Program passing an arra" using pointers
front of the argument. Insi$e the main program# the a$$resses of the varia%les are
passe$ to the function using the :S< character in front of the varia%le names. At the en$
of the program# varia%les p an$ C are set to -3 an$ 3 respectivel".
4..4 Faria%le Gum%er of Arguments
The ellipsis character *:. . .<+ consists of three successive perio$s with no spaces
%etween them. An ellipsis can %e use$ in the argument lists of function protot"pes to
9;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PA''IGY FARIA7LE' 7T RE6EREGCE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
This program shows how the a$$ress of varia%les can %e passe$ to functions.
The function in this program swaps the values of two integer varia%les.
Programmer( ,ogan I%rahim
6ile( 'BAP.C
,ate( )a"# -33L
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;9
9; 6unction to swap two integers ;9
void 'wap*int ;a# int ;%+
=
int temp?
temp @ ;a? 99 'tore a in temp
;a @ ;%? 99 Cop" % to a
;% @ temp? 99 Cop" temp to %
>
9; 'tart of the main program ;9
void main*+
=
int p# C?
p @ 3? 99 'et p @ 3
C @ -3? 99 'et C @ -3
swap*Sp# SC+? 99 'wap p an$ C *p@-3# C@3+
>
6igure 4.( Passing varia%les %" reference to a function
in$icate a varia%le num%er of arguments or arguments with var"ing t"pes. An e8ample
of a $eclaration of a function protot"pe with ellipsis follows. In this $eclaration# when
the function is calle$ we must suppl" at least two integer t"pe arguments# an$ we can
also suppl" an" num%er of a$$itional arguments(
unsigne$ char )"6unc*int a# int %#. . .+?
The hea$er file st$arg.h must %e inclu$e$ at the %eginning of a program that uses a
varia%le num%er of arguments. This hea$er file $efines a new $ata t"pe calle$ vaKlist#
which is essentiall" a character pointer. In a$$ition# macro vaKstart*+ initialiHes an
o%5ect of t"pe vaKlist to point to the a$$ress of the first a$$itional argument presente$ to
the function. To e8tract the arguments# successive calls to the macro vaKarg*+ must %e
ma$e# with the character pointer an$ the t"pe of the parameter as the arguments of
vaKarg*+.
An e8ample program is given in 6igure 4.-. In this program the function hea$er
$eclares onl" one parameter of t"pe int# an$ an ellipsis is use$ to $eclare a varia%le
/
PASSING =ARIA#LE N>M#ER OF ARG>MENTS
777777777777777777777777777777777777777
This program sho%s ho% &aria)le n8m)er of arg8men!s an )e passe" !o a
f8n!ion' The f8n!ion hea"er "elares one in!eger &aria)le an" an ellipsis is
8se" !o "elare &aria)le n8m)er of parame!ers' The f8n!ion a""s all !he
arg8men!s an" re!8rns !he s8m as an in!eger' The n8m)er of arg8men!s is
s8pplie" )+ !he alling program as !he firs! arg8men! !o !he f8n!ion'
Programmer( Dogan I)rahim
File( =ARIA#LE'*
Da!e( Ma+, -$$.
/
#include Ds!"arg'h@
/

F8n!ion %i!h &aria)le n8m)er of parame!ers

/
int S8m3in! n8m,<4
5
unsigned char K6
va_list ap6
int !emp 7 $6
va_start3ap, n8m46
for3K 7 $6 K D n8m6 KLL4
5
!emp 7 !emp L &a9arg3ap, in!46
;
va_end3ap46
re!8rn !emp6
;
/

S!ar! of !he main program

/
void main34
5
int p6
p 7 S8m3-, M, 246 // - arg8men!s' p7ML270
p 7 S8m3M, -, 2, N46 // M arg8men!s, p7-L2LN7/M
;
6igure 4.-( Passing varia%le num%er of arguments to a function
num%er of parameters. Faria%le num is the argument count passe$ %" the calling
program. The arguments are rea$ %" using the macro vaKarg*ap# int+ an$ then summe$
using varia%le temp an$ returne$ %" the function.
4..A 6unction Reentranc"
The mikroC compiler supports onl" a limite$ function reentranc". 6unctions that have
no arguments an$ local varia%les can %e calle$ %oth from the interrupt service routines
an$ from the main program. 6unctions that have arguments an$9or local varia%les can
onl" %e calle$ from the interrupt service routines or from the main program.
4..E 'tatic 6unction Faria%les
Gormall"# varia%les $eclare$ at the %eginning of a program# %efore the main program#
are glo%al# an$ their values can %e accesse$ an$ mo$ifie$ %" all parts of the program.
,eclaring a varia%le use$ in a function as glo%al ensures that its value is retaine$ from
one call of the function to another# %ut this also un$ermines the varia%le2s privac" an$
re$uces the porta%ilit" of the function to other applications. A %etter approach is to
$eclare such varia%les as static. 'tatic varia%les are mainl" use$ in function $efinitions.
Bhen a varia%le is $eclare$ as static# its value is retaine$ from one call of the function
to another. In the e8ample co$e that follows# varia%le k is $eclare$ as static an$
initialiHe$ to Hero. This varia%le is then incremente$ %efore e8iting from the function#
an$ the value of k remains in e8istence an$ hol$s its last value on the ne8t call to the
function *i.e.# on the secon$ call to the function the value of k will %e +(
voi$ Cnt*voi$+
=
static int k @ 3? 99 ,eclare k as static
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
kDD? 99 increment k
>
4.- mikroC 7uilt&in 6unctions
The mikroC compiler provi$es a set of %uilt&in functions which can %e calle$ from the
program. These functions are liste$ in Ta%le 4.# along with a %rief $escription of each.
)ost of these functions can %e use$ in a program without having to inclu$e hea$er files.
Ta%le 4.( mikroC %uilt&in functions
6unction ,escription
Lo Returns the lowest %"te of a num%er *%its 3 to L+
Hi Returns ne8t to the lowest %"te of a num%er *%its ! to A+
Higher Returns ne8t to the highest %"te of a num%er *%its E to -3+
Highest Returns the highest %"te of a num%er *%its -4 to 3+
,ela"Kus Creates software $ela" in microsecon$ units
,ela"Kms Creates constant software $ela" in millisecon$ units
F$ela"Kms Creates $ela" in millisecon$s using program varia%les
,ela"KC"c Creates $ela" %ase$ on microcontroller clock
ClockK.hH Returns microcontroller clock in .HH
ClockK)hH Returns microcontroller clock in )HH
The e8ceptions are functions Lo# Hi# Higher# an$ Highest# which reCuire the hea$er file
%uiltKin.h. 6urther $etails a%out using these functions are availa%le in the mikroC
manuals.
6unctions ,ela"Kus an$ ,ela"Kms are freCuentl" use$ in programs where $ela"s are
reCuire$ *e.g.# when flashing an LE,+. The following e8ample illustrates the use of the
,ela"Kms function(
E8ample 4.3
An LE, is connecte$ to %it 3 of P/RT7 *pin R73+ of a PIC!6MMM microcontroller
through a current&limiting resistor as shown in 6igure 4.3. Choose a suita%le value for
the resistor an$ write a program that will flash the LE, /G an$ /66 continuousl" at
one&secon$ intervals.
'olution 4.3
LE,s can %e connecte$ to a microcontroller in two mo$es( current sinking an$ current
sourcing. In current sinking mo$e *see 6igure 4.4+ one leg of the LE, is connecte$ to
the `AF an$ the other leg is connecte$ to the microcontroller output port pin through a
current limiting resistor R.
6igure 4.3( LE, connecte$ to port R73 of a PIC microcontroller
0n$er normal working con$itions# the voltage across an LE, is a%out -F an$ the
current through the LE, is a%out 3mA *some low&power LE,s can operate at as low
as mA current+. The ma8imum current that can %e source$ or sinke$ at the output port
of a PIC microcontroller is -AmA.
The value of the current limiting resistor R can %e calculate$ as follows. In current
sinking mo$e the LE, will %e turne$ /G when the output port of the microcontroller is
at logic 3 *i.e.# at appro8imatel" 3F+. The reCuire$ resistor is then(
AF -F
R @
3mA
@ 3(3.
The nearest resistor to choose is -J3 /hm *a slightl" higher resistor can %e chosen for a
lower current an$ slightl" less %rightness+.
6igure 4.4( Connecting the LE, in current sinking mo$e
In current sourcing mo$e *see 6igure 4.A+ one leg of the LE, is connecte$ to the
output port of the microcontroller an$ the other leg is connecte$ to the groun$ through a
current limiting resistor. The LE, will %e turne$ /G when the output port of the
microcontroller is at logic *i.e.# at appro8imatel" AF+. The same value of resistor can
%e use$ in %oth current sinking an$ current sourcing mo$es.
The reCuire$ program listing is given in 6igure 4.E *program 6LA'H.C+. At
the %eginning of the program P/RT7 is configure$ as output using the TRI'7 @ 3
statement. An en$less loop is then forme$ with the for statement# an$ insi$e this
loop the LE, is turne$ /G an$ /66 with one&secon$ $ela"s %etween outputs.
The program given in 6igure 4.E can %e ma$e more user&frien$l" an$ easier to follow
%" using $efine statements as shown in 6igure 4.L *program 6LA'H-.C+.
6igure 4.A( Connecting the LE, in current sourcing mo$e
/
FLASHING AN LED
777777777777777
This program flashes an LED onne!e" !o por! R#$ of a miroon!roller
%i!h one seon" in!er&als' miJro* )8il!Oin f8n!ion Dela+9ms is 8se" !o
rea!e a / seon" "ela+ )e!%een !he flashes'
Programmer( Dogan I)rahim
File( FLASH'*
Da!e( Ma+, -$$.
/
void main34
5
TRIS# 7 $6 // *onfig8re PORT# as o8!p8!
for36 64 // En"less loop
5
PORT# 7 /6 // T8rn ON LED
Dela+9ms3/$$$46 // / seon" "ela+
PORT# 7 $6 // T8rn OFF LED
Dela+9ms3/$$$46 // / seon" "ela+
;
;
6igure 4.E( Program to flash an LE,
4.3 mikroC Li%rar" 6unctions
A large set of li%rar" functions is availa%le with the mikroC compiler. These li%rar"
functions can %e calle$ from an"where in a program# an$ the" $o not reCuire that hea$er
files are inclu$e$ in the program. The mikroC user manual gives a $etaile$ $escription
of each li%rar" function# with e8amples. In this section# the availa%le li%rar" functions
are i$entifie$# an$ the important an$ commonl" use$ li%rar" functions are $escri%e$ in
$etail# with e8amples.
Ta%le 4.- gives a list of the mikroC li%rar" functions# organiHe$ in functional or$er.
'ome of the freCuentl" use$ li%rar" functions are(

EEPR/) li%rar"

LC, li%rar"

'oftware 0ART li%rar"

Har$ware 0'ART li%rar"
/
FLASHING AN LED
777777777777777
This program flashes an LED onne!e" !o por! R#$ of a miroon!roller
%i!h one seon" in!er&als' miJro* )8il!Oin f8n!ion Dela+9ms is 8se" !o
rea!e a / seon" "ela+ )e!%een !he flashes'
Programmer( Dogan I)rahim
File( FLASH-'*
Da!e( Ma+, -$$.
/
P"efine LED PORT#'$
P"efine ON /
P"efine OFF $
P"efine One9Seon"9Dela+ Dela+9ms3/$$$4
void main34
5
TRIS# 7 $6 // *onfig8re PORT# as o8!p8!
for36 64
5
;
;
LED 7 ON6
One9Seon"9Dela+6
LED 7 OFF6
One9Seon"9Dela+6
// En"less loop
// T8rn ON LED
// / seon" "ela+
// T8rn OFF LED
// / seon" "ela+
6igure 4.L( Another program to flash an LE,

'oun$ li%rar"

AG'I C li%rar"

)iscellaneous li%rar"
4.3. EEPR/) Li%rar"
The EEPR/) li%rar" inclu$es functions to rea$ $ata from the on&chip PIC
microcontroller nonvolatile EEPR/) memor"# or to write $ata to this memor". Two
functions are provi$e$(

EepromKRea$

EepromKBrite
Ta%le 4.-( mikroC li%rar" functions
Li%rar" ,escription
A,C Analog&to&$igital conversion functions
CAG CAG %us functions
CAG'PI 'PI&%ase$ CAG %us functions
Compact 6lash Compact flash memor" functions
EEPR/) EEPR/) memor" rea$9write functions
Ethernet Ethernet functions
'PI Ethernet 'PI&%ase$ Ethernet functions
6lash )emor" 6lash memor" functions
Yraphics LC, 'tan$ar$ graphics LC, functions
TEJE3C Yraphics LC, TEJE3&%ase$ graphics LC, functions
I
-
C I
-
C %us functions
.e"pa$ .e"pa$ functions
LC, 'tan$ar$ LC, functions
)anchester Co$e )anchester co$e functions
)ulti )e$ia )ultime$ia functions
/ne Bire /ne wire functions
P'9- P'9- functions
PB) PB) functions
R'&4!A R'&4!A communication functions
'oun$ 'oun$ functions
'PI 'PI %us functions
0'ART 0'ART serial communication functions
0til 0tilities functions
'PI Yraphics LC, 'PI&%ase$ graphics LC, functions
Port E8pan$er Port e8pan$er functions
*Continue$+
Ta%le 4.-( mikroC li%rar" functions *cont2$+
Li%rar" ,escription
'PI LC, 'PI&%ase$ LC, functions
AG'I C Ct"pe C Ct"pe functions
AG'I C )ath C )ath functions
AG'I C 't$li% C 't$li% functions
AG'I C 'tring C 'tring functions
Conversion Conversion functions
Trigonometr" Trigonometr" functions
Time Time functions
The EepromKRea$ function rea$s a %"te from a specifie$ a$$ress of the EEPR/). The
a$$ress is of t"pe integer# an$ thus the function supports PIC microcontrollers with
more than -AE %"tes. A -3ms $ela" shoul$ %e use$ %etween successive rea$s from the
EEPR/) to guarantee the return of correct $ata. In the following e8ample# the %"te at
a$$ress 386 of the EEPR/) is rea$ an$ store$ in varia%le Temp(
Temp @ EepromKRea$*386+?
The EepromKBrite function writes a %"te to a specifie$ a$$ress of the
EEPR/). The a$$ress is of t"pe integer an$ thus the function supports PIC
microcontrollers with more than -AE %"tes. A -3ms $ela" shoul$ %e use$
%etween successive
rea$s or writes to the EEPR/) to guarantee the correct transfer of $ata to the
EEPR/). In the following e8ample# num%er 383A is written to a$$ress 38-6 of the
EEPR/)(
EepromKBrite*38-6#
383A+?
E8ample 4.
Brite a program to rea$ the contents of EEPR/) from a$$ress 3 to 38-6 an$ then sen$
this $ata to P/RT7 of a PIC microcontroller.
'olution 4.
The reCuire$ program is given in 6igure 4.!. A for loop is use$ to rea$ $ata from the
EEPR/) an$ then sen$ it to P/RT 7 of the microcontroller. Gotice that a -3ms $ela"
is use$ %etween each successive rea$.
/
READING FROM THE EEPROM
7777777777777777777777777
This program rea"s "a!a from a""resses $ !o $G-F of !he EEPROM an" !hen
sen"s !his "a!a !o PORT# of !he miroon!roller'
Programmer(
File(
Da!e(
Dogan I)rahim
EEPROM'*
Ma+, -$$.
/
void main34
5
unsigned int K6
unsigned char Temp6
TRIS# 7 $6 // *onfig8re PORT# as o8!p8!
for3K7$6 K D7 $G-F6 KLL4
5
Temp 7 Eeprom9Rea"3K46
PORT# 7 Temp6
Dela+9ms3-$46
;
;
6igure 4.!( Program to rea$ from the EEPR/)
4.3.- LC, Li%rar"
/ne thing all microcontrollers lack is some kin$ of vi$eo $ispla". A vi$eo $ispla"
woul$ make a microcontroller much more user&frien$l"# ena%ling te8t messages#
graphics# an$ numeric values to %e output in a more versatile manner than with
L&segment $ispla"s# LE,s# or alphanumeric $ispla"s. 'tan$ar$ vi$eo $ispla"s reCuire
comple8 interfaces an$ their cost is relativel" high. LC,s are alphanumeric *or graphic+
$ispla"s which are freCuentl" use$ in microcontroller&%ase$ applications. These $ispla"
$evices come in $ifferent shapes an$ siHes. 'ome LC,s have fort" or more character
lengths with the capa%ilit" to $ispla" several lines. /thers can %e programme$ to
$ispla" graphic images. 'ome mo$ules offer color $ispla"s# while others incorporate
%acklighting so the" can %e viewe$ in $iml" lit con$itions.
There are %asicall" two t"pes of LC,s as far as the interfacing techniCue is concerne$(
parallel an$ serial. Parallel LC,s *e.g.# the Hitachi H,44L!3 series+ are connecte$ to
the microcontroller circuitr" such that $ata is transferre$ to the LC, using more than
one line# usuall" four or eight $ata lines. 'erial LC,s are connecte$ to a microcontroller
using one $ata line onl"# an$ $ata is transferre$ using the R'-3- as"nchronous $ata
communications protocol. 'erial LC,s are generall" much easier to work with %ut more
costl" than parallel ones. In this %ook onl" parallel LC,s are $iscusse$# as the" are use$
more often in microcontroller&%ase$ pro5ects.
Low&level programming of a parallel LC, is usuall" a comple8 task an$ reCuires
a goo$ un$erstan$ing of the internal operation of the LC,# inclu$ing the timing
$iagrams. 6ortunatel"# mikroC language provi$es functions for %oth te8t&%ase$
an$ graphic LC,s# simplif"ing the use of LC,s in PIC&microcontroller&%ase$ pro5ects.
The H,44L!3 controller is a common choice in LC,&%ase$ microcontroller
applications. A %rief $escription of this controller an$ information on some
commerciall" availa%le LC, mo$ules follows.
The H,44L!3 LC, Controller
The H,44L!3 is one of the most popular LC, controllers# %eing use$ %oth in in$ustrial
an$ commercial applications an$ also %" ho%%"ists. The mo$ule is monochrome an$
comes in $ifferent shapes an$ siHes. )o$ules with !# E# -3# -4# 3-# an$ 43 characters
are availa%le. ,epen$ing on the mo$el# the $ispla" provi$es a 4&pin or E&pin
connector for interfacing. Ta%le 4.3 shows the pin configuration an$ pin functions of
a t"pical 4&pin LC,.
F
''
is the 3F suppl" or groun$. The F
,,
pin shoul$ %e connecte$ to the positive
suppl". Although the manufacturers specif" a AF ,C suppl"# the mo$ules usuall" work
with as low as 3F or as high as EF.
Pin 3 is name$ as F
EE
an$ is the contrast control pin. It is use$ to a$5ust the contrast of
the $ispla" an$ shoul$ %e connecte$ to a ,C suppl". A potentiometer is usuall"
connecte$ to the power suppl" with its wiper arm connecte$ to this pin an$ the other leg
of the potentiometer connecte$ to the groun$. This wa" the voltage at the F
EE
pin# an$
hence the contrast of the $ispla"# can %e a$5uste$ as $esire$.
Pin 4 is the register select *R'+ an$ when this pin is L/B# $ata transferre$ to the LC,
is treate$ as comman$s. Bhen R' is HIYH# character $ata can %e transferre$ to an$
from the mo$ule.
Pin A is the rea$9write *R9B+ pin. This pin is pulle$ L/B in or$er to write comman$s
or character $ata to the LC, mo$ule. Bhen this pin is HIYH# character $ata or status
information can %e rea$ from the mo$ule.
Ta%le 4.3( Pin configuration of the
H,44L!3 LC, mo$ule
Pin no. Game 6unction
F
''
Yroun$
- F
,,
`ve suppl"
3 F
EE
Contrast
4 R' Register select
A R9B Rea$9write
E EG Ena%le
L ,3 ,ata %it 3
! , ,ata %it
J ,- ,ata %it -
3 ,3 ,ata %it 3
,4 ,ata %it 4
- ,A ,ata %it A
3 ,E ,ata %it E
4 ,L ,ata %it L
Pin E is the ena%le *EG+ pin# which is use$ to initiate the transfer of comman$s or $ata
%etween the mo$ule an$ the microcontroller. Bhen writing to the $ispla"# $ata is
transferre$ onl" on the HIYH to L/B transition of this pin. Bhen rea$ing from the
$ispla"# $ata %ecomes availa%le after the L/B to HIYH transition of the ena%le pin#
an$ this $ata remains vali$ as long as the ena%le pin is at logic HIYH.
Pins L to 4 are the eight $ata %us lines *,3 to ,L+. ,ata can %e transferre$ %etween the
microcontroller an$ the LC, mo$ule using either a single !&%it %"te or two 4&%it
ni%%les. In the latter case# onl" the upper four $ata lines *,4 to ,L+ are use$. The 4&%it
mo$e has the a$vantage of reCuiring fewer I9/ lines to communicate with the LC,.
The mikroC LC, li%rar" provi$es a large num%er of functions to control te8t&%ase$
LC,s with 4&%it an$ !&%it $ata interfaces# an$ for graphics LC,s. The most common
are the 4&%it&interface te8t&%ase$ LC,s. This section $escri%es the availa%le mikroC
functions for these LC,s. 6urther information on other te8t& or graphics&%ase$ LC,
functions are availa%le in the mikroC manual.
The following are the LC, functions availa%le for 4&%it&interface te8t&%ase$
LC,s(

Lc$KConfig

Lc$KInit

Lc$K/ut

Lc$K/utKCp

Lc$KChr

Lc$KChrKCp

Lc$KCm$
Lc$KConfig The Lc$KConfig function is use$ to configure the LC, interface. The
$efault connection %etween the LC, an$ the microcontroller is(
LC, )icrocontroller port pin
R' -
EG 3
,4 4
,A A
,E E
,L L
The R9B pin of the LC, is not use$ an$ shoul$ %e connecte$ to the groun$.
This function shoul$ %e use$ to change the $efault connection. It shoul$ %e calle$ with
the parameters in the following or$er(
port name# R' pin# EG pin# R9B pin# ,L pin# ,E pin# ,A pin# ,4
pin
The port name shoul$ %e specifie$ %" passing its a$$ress. 6or e8ample# if the R' pin is
connecte$ to R73# EG pin to R7# ,L pin to R7-# ,E pin to R73# ,A pin to R74# an$
the ,4 pin to R7A# then the function shoul$ %e calle$ as follows(
Lc$KConfig*SP/RT7# 3# # -# 3# 4#
A+?
Lc$KInit The Lc$KInit function is calle$ to configure the interface %etween the
microcontroller an$ the LC, when the $efault connections are ma$e as 5ust illustrate$.
The port name shoul$ %e specifie$ %" passing its a$$ress. 6or e8ample# assuming that
the LC, is connecte$ to P/RT7 an$ the prece$ing $efault connections are use$# the
function shoul$ %e calle$ as(
Lc$KInit*SP/RT7+?
Lc$K/ut The Lc$K/ut function $ispla"s te8t at the specifie$ row an$ column position
of the LC,. The function shoul$ %e calle$ with the parameters in the following or$er(
row# column# te8t
6or e8ample# to $ispla" te8t :Computer< at row an$ column - of the LC, we shoul$
call the function as(
Lc$K/ut*# -# :Computer<+?
Lc$K/utKCp The Lc$K/utKCp function $ispla"s te8t at the current cursor position.
6or e8ample# to $ispla" te8t :Computer< at the current cursor position the function
shoul$ %e calle$ as(
Lc$K/utKCp*:Computer<+?
Lc$KChr The Lc$KChr function $ispla"s a character at the specifie$ row an$ column
position of the cursor. The function shoul$ %e calle$ with the parameters in the
following or$er(
row# column# character
6or e8ample# to $ispla" character :.< at row - an$ column 4 of the LC, we shoul$ call
the function as(
LC,KChr*-# 4# N.2+?
Lc$KChrKCp The Lc$KChrKCp function $ispla"s a character at the current cursor
position. 6or e8ample# to $ispla" character :)< at the current cursor position the
function shoul$ %e calle$ as(
Lc$KChrKCp*N)2+?
Lc$KCm$ The Lc$KCm$ function is use$ to sen$ a comman$ to the LC,. Bith the
comman$s we can move the cursor to an" reCuire$ row# clear the LC,# %link the cursor#
Ta%le 4.4( LC, comman$s
LC, comman$ ,escription
LC,KCLEAR Clear $ispla"
LC,KRET0RGKH/)E Return cursor to home position
LC,K6IR'TKR/B )ove cursor to first row
LC,K'EC/G,KR/B )ove cursor to secon$ row
LC,KTHIR,KR/B )ove cursor to thir$ row
LC,K6/0RTHKR/B )ove cursor to fourth row
LC,K7LIG.KC0R'/RK/G 7link cursor
LC,KT0RGK/G Turn $ispla" on
LC,KT0RGK/66 Turn $ispla" off
LC,K)/FEKC0R'/RKLE6T )ove cursor left
LC,K)/FEKC0R'/RKRIYHT )ove cursor right
LC,K'HI6TKLE6T 'hift $ispla" left
LC,K'HI6TKRIYHT 'hift $ispla" right
shift $ispla"# etc. A list of the most commonl" use$ LC, comman$s is given in
Ta%le 4.4. 6or e8ample# to clear the LC, we shoul$ call the function as(
Lc$KCm$*Lc$KClear+?
An e8ample illustrates initialiHation an$ use of the LC,.
E8ample 4.-
A te8t&%ase$ LC, is connecte$ to a PIC!64A- microcontroller in the $efault mo$e as
shown in 6igure 4.J. Brite a program to sen$ the te8t :)" Computer< to row #
column 4 of the LC,.
'olution 4.-
The reCuire$ program listing is given in 6igure 4.-3 *program LC,.C+. At the
%eginning of the program P/RT7 is configure$ as output with the TRI'7 @ 3
www. newnespress. co m
6igure 4.J( Connecting an LC, to a PIC microcontroller
/
:RITING TEQT TO AN L*D
77777777777777777777777
A !eG! )ase" L*D is onne!e" !o a PI* miroon!roller in !he "efa8l! mo"e'
This program "ispla+s !he !eG! RM+ *omp8!erS on !he L*D'
Programmer(
File(
Da!e(
Dogan I)rahim
L*D'*
Ma+, -$$.
/
void main34
5
TRIS# 7 $6
L"9Ini!3CPORT#46
// *onfig8re PORT# as o8!p8!
// Ini!ialiEe !he L*D
L"9*m"3L*D9*LEAR46 // *lear !he L*D
L"9O8!3/, 1, RM+ *omp8!er46
;
// Displa+ !eG! on L*D
6igure 4.-3( LC, program listing
6unctions an$ Li%raries in mikroC JJ
statement. The LC, is then initialiHe$# the $ispla" is cleare$# an$ the te8t message :)"
Computer< is $ispla"e$ on the LC,.
4.3.3 'oftware 0ART Li%rar"
0niversal as"nchronous receiver transmitter *0ART+ software li%rar" is use$ for
R'-3-& %ase$ serial communication %etween two electronic $evices. In serial
communication# onl" two ca%les *plus a groun$ ca%le+ are reCuire$ to transfer $ata in
either $irection. ,ata is sent in serial format over the ca%le %it %" %it. Gormall"# the
receiving $evice is in i$le mo$e with its transmit *TM+ pin at logic # also known as
)AR.. ,ata transmission starts when this pin goes to logic 3# also known as 'PACE.
The first %it sent is the start %it at logic
3. 6ollowing this %it# L or ! $ata %its are sent# followe$ %" an optional parit" %it. The last
%it sent is the stop %it at logic . 'erial $ata is usuall" sent as a 3&%it frame consisting of
a start %it# ! $ata %its# an$ a stop %it# an$ no parit" %its. 6igure 4.- shows how character
:A< can %e sent using serial communication. Character :A< has the A'CII %it pattern
333333. As shown in the figure# first the start %it is sent# this is followe$ %" ! $ata
%its 333333# an$ finall" the stop %it is sent.
IDLE /
/ STOP
$ $ $ $ $ $ $
START
6igure 4.-( 'en$ing character :A< in serial communication
The %it timing is ver" important in serial communication# an$ the transmitting *TM+ an$
receiving *RM+ $evices must have the same %it timings. The %it timing is measure$ %"
the %au$ rate# which specifies the num%er of %its transmitte$ or receive$ each secon$.
T"pical %au$ rates are 4!33# JE33# J-33# 3!433# an$ so on. 6or e8ample# when
operating at JE33 %au$ rate with a frame siHe of 3 %its# JE3 characters are transmitte$
or receive$ each secon$. The timing %etween %its is then a%out 34ms.
In R'-3-&%ase$ serial communication the two $evices are connecte$ to each other *see
6igure 4.--+ using either a -A&wa" connector or a J&wa" connector. Gormall" onl" the
TM# RM# an$ YG, pins are reCuire$ for communication. The reCuire$ pins for %oth
t"pes of connectors are given in Ta%le 4.A.
The voltage levels specifie$ %" the R'-3- protocol are -F. A logic HIYH signal is
at -F an$ a logic L/B signal is at D-F. PIC microcontrollers# on the other han$#
6igure 4.--( -A&wa" an$ J&wa" R'-3- connectors
Ta%le 4.A( Pins reCuire$ for serial communication
Pin J&wa" connector -A&wa" connector
TM - -
RM 3 3
YG, A L
normall" operate at 3 to AF voltage levels# the R'-3- signals must %e converte$ to 3 to
AF when input to a microcontroller. 'imilarl"# the output of the microcontroller must %e
converte$ to -F %efore sen$ing to the receiving R'-3- $evice. The voltage
conversion is usuall" carrie$ out with R'-3- converter chips# such as the )AM-3-#
manufacture$ %" )a8im Inc.
'erial communication ma" %e implemente$ in har$ware using a specific pin of a
microcontroller# or the reCuire$ signals can %e generate$ in software from an"
reCuire$ pin of a microcontroller. Har$ware implementation reCuires either an
on&chip 0ART *or 0'ART+ circuit or an e8ternal 0ART chip that is connecte$ to
the microcontroller. 'oftware&%ase$ 0ART is more commonl" use$ an$ $oes not
reCuire an" special circuits. 'erial $ata is generate$ %" $ela" loops in software&
%ase$ 0ART applications. In this section onl" the software&%ase$ 0ART functions
are $escri%e$.
The mikroC compiler supports the following software 0ART functions(

'oftK0artKInit

'oftK0artKRea$

'oftK0artKBrite
'oftK0artKInit
The 'oftK0artKInit function specifies the serial communications parameters an$ $oes so
in the following or$er(
port# r8 pin# t8 pin# %au$ rate# mo$e
port is the port use$ as the software 0ART *e.g.# P/RT7+# r8 is the receive pin num%er#
t8 is the transmit pin num%er# %au$ rate is the chosen %au$ rate where the ma8imum
value $epen$s on the clock rate of the microcontroller# an$ mo$e specifies whether
or not the $ata shoul$ %e inverte$ at the output of the port. A 3 in$icates that it
shoul$ not %e inverte$# an$ a in$icates that it shoul$ %e inverte$. Bhen an R'-3-
voltage level converter chip is use$ *e.g.# )AM-3-+ then the mo$e must %e set to 3.
'oftK0artKInit must %e the first function calle$ %efore software&%ase$ serial
communication is esta%lishe$.
The following e8ample configures the software 0ART to use P/RT7 as the serial port#
with R73 as the RM pin an$ R7 as the TM pin. The %au$ rate is set to JE33 with the
mo$e noninverte$(
'oftK0artKInit*P/RT7# 3# # JE33# 3+?
'oftK0artKRea$
The 'oftK0artKRea$ function receives a %"te from a specifie$ serial port pin. The
function returns an error con$ition an$ the $ata is rea$ from the serial port. The function
$oes not wait for $ata to %e availa%le at the port# an$ therefore the error parameter must
%e teste$ if a %"te is e8pecte$. The error is normall" an$ %ecomes 3 when a %"te is
rea$ from the port.
The following e8ample illustrates rea$ing a %"te from the serial port configure$
%" calling the function 'oftK0artKInit. The receive$ %"te is store$ in varia%le Temp(
$o
Temp @ 'oftK0artKRea$*SR8KError+?
while *R8KError+?
'oftK0artKBrite
The 'oftK0artKBrite function transmits a %"te to a configure$ serial port pin. The $ata
to %e sent must %e specifie$ as a parameter in the call to the function.
6or e8ample# to sen$ character :A< to the serial port pin(
char )",ata @ NA2?
'oftK0artKBrite*)",ata+
?
The following e8ample illustrates the use of software 0ART functions.
E8ample 4.3
The serial port of a PC *e.g.# C/)+ is connecte$ to a PIC!64A- microcontroller# an$
terminal emulation software *e.g.# H"perTerminal+ is operate$ on the PC to use the
serial port. Pins R73 an$ R7 of the microcontroller are the RM an$ TM pins
respectivel". The reCuire$ %au$ rate is JE33.
Brite a program to rea$ $ata from the terminal# then increase this $ata %" one an$ sen$
it %ack to the terminal. 6or e8ample# if the user enters character :A#< then character :7<
shoul$ %e $ispla"e$ on the terminal. Assume that a )AM-3-&t"pe voltage level
converter chip is converting the microcontroller signals to R'-3- levels. 6igure 4.-3
shows the circuit $iagram of this e8ample.
6igure 4.-3( Circuit $iagram of E8ample 4.3
'olution 4.3
The )AM-3- chip receives the TM signal from pin R7 of the microcontroller an$
converts it to R'-3- levels. Compara%l"# the serial $ata receive$ %" the )AM-3-
chip is converte$ into microcontroller voltage levels an$ then sent to pin R73. Gote
that correct operation of the )AM-3- chip reCuires four capacitors to %e connecte$
to the chip.
The reCuire$ program listing is shown in 6igure 4.-4 *program 'ERIAL.C+. At the
%eginning of the program# function 'oftK0artKInit is calle$ to configure the serial port.
Then an en$less loop is forme$ using a for statement. The 'oftK0artKRea$ function
is calle$ to rea$ a character from the terminal. After rea$ing a character# the $ata
%"te is incremente$ %" one an$ then sent %ack to the terminal %" calling function
'oftK0artKBrite.
/
READING AND :RITING TO SERIAL PORT
77777777777777777777777777777777777
In !his program PORT# pins R#$ an" R#/ are onfig8re" as serial RQ an"
TQ pins respe!i&el+' The )a8" ra!e is se! !o TN$$' A hara!er is reei&e" from a
serial !erminal, inremen!e" )+ one an" !hen sen! )aJ !o !he !erminal' Th8s, if
hara!er RAS is en!ere" on !he Je+)oar", hara!er R#S %ill )e "ispla+e"'
Programmer( Dogan I)rahim
File( SERIAL'*
Da!e( Ma+, -$$.
/
void main34
5
unsigned char M+Error, Temp6
Sof!9>ar!9Ini!3PORT#, $, /, TN$$, $46
for36 64
5
// *onfig8re serial por!
// En"less loop
do
5
Temp 7 Sof!9>ar!9Rea"3CM+Error46
; while3M+Error46
TempLL6
// Rea" a )+!e
// Inremen! )+!e
Sof!9>ar!9:ri!e3Temp46 // Sen" !he )+!e
;
6igure 4.-4( Program listing of E8ample 4.3
4.3.4 Har$ware 0'ART Li%rar"
The universal s"nchronous as"nchronous receiver transmitter *0'ART+ har$ware
li%rar" contains a num%er of functions to transmit an$ receive serial $ata using the
0'ART circuits %uilt on the PIC microcontroller chips. 'ome PIC!6&series
microcontrollers have onl" one 0'ART *e.g.# PIC!64A-+# while others have two
0'ART circuits *e.g.# PIC!6!A-3+. Har$ware 0'ART has an a$vantage over
software&implemente$ 0'ART# in that higher %au$ rates are generall" availa%le an$
the microcontroller can perform other operations while $ata is sent to the 0'ART.
The har$ware 0'ART li%rar" provi$es the following functions(

0sartKInit

0sartK,ataKRea$"

0sartKRea$

0sartKBrite
0sartKInit
The 0sartKInit function initialiHes the har$ware 0'ART with the specifie$ %au$ rate.
This function shoul$ %e calle$ first# %efore an" other 0'ART functions. The onl"
parameter reCuire$ %" this function is the %au$ rate. The following e8ample call sets the
%au$ rate to JE33(
0sartKInit*JE33+?
0sartK,ataKRea$"
The 0sartK,ataKRea$" function can %e calle$ to check whether or not a $ata %"te has
%een receive$ %" the 0'ART. The function returns a if $ata has %een receive$ an$ a
3 if no $ata has %een receive$. The function has no parameters. The following co$e
checks if a $ata %"te has %een receive$ or not(
if*0sartK,ataKRea$"* ++
0sartKRea$
The 0sartKRea$ function is calle$ to rea$ a $ata %"te from the 0'ART. If $ata has not
%een receive$# a 3 is returne$. Gote that rea$ing $ata from the 0'ART is non%locking
*i.e.# the
function alwa"s returns whether or not the 0'ART has receive$ a $ata %"te+. The
0sartKRea$ function shoul$ %e calle$ after calling the function 0sartK,ataKRea$" to
make sure that $ata is availa%le at the 0'ART. 0sartKRea$ has no parameters. In the
following e8ample# 0'ART is checke$ an$ if a $ata %"te has %een receive$ it is copie$
to varia%le )",ata(
char )",ata?
if*0sartK,ataKRea$* ++ )",ata @ 0sartKRea$*+?
0sartKBrite
The 0sartKBrite function sen$s a $ata %"te to the 0'ART# an$ thus a serial $ata is sent
out of the 0'ART. The $ata %"te to %e sent must %e supplie$ as a parameter to the
function. In the following e8ample# character :A< is sent to the 0'ART(
char Temp @ NA2?
0sartKBrite*Temp+
?
The following e8ample illustrates how the har$ware 0'ART functions can %e use$ in a
program.
E8ample 4.4
The serial port of a PC *e.g.# C/)+ is connecte$ to a PIC!64A- microcontroller# an$
terminal emulation software *e.g.# H"perTerminal+ is operate$ on the PC to use the
serial port. The microcontroller2s har$ware 0'ART pins RCL *0'ART receive pin#
RM+
an$ RCE *0'ART transmit pin# TM+ are connecte$ to the PC via a )AM-3-&t"pe
R'-3- voltage level converter chip. The reCuire$ %au$ rate is JE33. Brite a program to
rea$ $ata from the terminal# then increase this $ata %" one an$ sen$ it %ack to the
terminal. 6or e8ample# if the user enters character :A#< then character :7< shoul$ %e
$ispla"e$ on the terminal. 6igure 4.-A shows the circuit $iagram of this e8ample.
'olution 4.4
The reCuire$ program listing is shown in 6igure 4.-E *program 'ERIAL-.C+. At the
%eginning of the program# function 0sartKInit is calle$ to set the %au$ rate to JE33.
Then an en$less loop is forme$ using a for statement. The 0sartK,ataKRea$" function
is calle$ to check whether a character is rea$"# an$ the character is rea$ %" calling
function 0sartKRea$. After rea$ing a character# the $ata %"te is incremente$ %" one an$
then sent %ack to the terminal %" calling function 0sartKBrite.
In PIC microcontrollers that have more than one 0'ART# the secon$ 0'ART is
accesse$ %" appen$ing a :-< to the en$ of the function *e.g.# 0sartKBrite-#
0sartKRea$-# etc.+.
6igure 4.-A( Circuit $iagram of E8ample 4.4
4.3.A 'oun$ Li%rar"
6unctions in the soun$ li%rar" make it possi%le to generate soun$s in our applications.
A speaker *e.g.# a pieHo speaker+ shoul$ %e connecte$ to the reCuire$ microcontroller
port. The following functions are offere$ %" the soun$ li%rar"(

'oun$KInit

'oun$KPla"
'oun$KInit
The 'oun$KInit function initialiHes the soun$ li%rar" an$ reCuires two parameters( the
name an$ the %it num%er of the port where the speaker is connecte$. The a$$ress of the
port name shoul$ %e passe$ to the function. 6or e8ample# if the speaker is connecte$ to
%it 3 of P/RT7# then the function shoul$ %e calle$ as(
'ountKInit*SP/RT7# 3+?
/
READING AND :RITING TO SERIAL PORT =IA >SART
777777777777777777777777777777777777777777777
In !his program a PI*/0F12- miroon!roller is 8se" an" >SART I/O pins are
onne!e" !o a !erminal !hro8gh a MAQ-M- &ol!age on&er!er hip' The )a8" ra!e is
se! !o TN$$' A hara!er is reei&e" from a serial !erminal, inremen!e" )+ one an"
!hen sen! )aJ !o !he !erminal' Th8s, if hara!er RAS is en!ere" on !he Je+)oar",
hara!er R#S %ill )e "ispla+e"'
Programmer( Dogan I)rahim
File( SERIAL-'*
Da!e( Ma+, -$$.
/
void main34
5
unsigned char M+Error, Temp6
>sar!9Ini!3TN$$46
for36 64
5
// Se! )a8" ra!e
// En"less loop
while 3U>ser9Da!a9Rea"+3446 // :ai! for "a!a )+!e
Temp 7 >sar!9Rea"346 // Rea" "a!a )+!e
TempLL6 // Inremen! "a!a )+!e
>sar!9:ri!e3Temp46 // Sen" !he )+!e )+!e
;
;
'oun$KPla"
6igure 4.-E( Program listing of E8ample 4.4
The 'oun$KPla" function pla"s a soun$ at a specifie$ port pin. The function receives
two arguments( the perio$ $ivi$e$ %" 3 *T,IF+ an$ the num%er of perio$s *G+. The
first parameter is the perio$ in microcontroller c"cles $ivi$e$ %" 3. The secon$
parameter specifies the $uration *num%er of clock perio$s+ of the soun$.
The following formula calculates the value use$ as the first parameter(
f
where
T,IF @
436
T,IF is the num%er to %e use$ as the first parameter
6 is the reCuire$ soun$ freCuenc" *HH+
f is the microcontroller clock freCuenc" *HH+

E8ample 4.A
Brite a program to pla" a soun$ at .HH# assuming the clock freCuenc" is 4)HH.
The reCuire$ $uration of the soun$ is -A3 perio$s.
'olution 4.A
The first parameter is calculate$ as follows(
f 4 3
E
T,IF @
436
@
43 3
3
@ 33
'ince the reCuire$ $uration is -A3 perio$s# the function is calle$ with the
parameters(
'oun$KPla"*33# -A3+?
4.3.E AG'I C Li%rar"
The AG'I C li%rar" consists of the following li%raries *further $etails on these li%raries
are availa%le in the mikroC user manual+(

Ct"pe li%rar"

)ath li%rar"

't$li% li%rar"

'tring li%rar"
Ct"pe Li%rar"
The functions in the Ct"pe li%rar" are mainl" use$ for testing or $ata conversion.
Ta%le 4.E lists the commonl" use$ functions in this li%rar".
)ath Li%rar"
The functions in the )ath li%rar" are use$ for floating point mathematical operations.
Ta%le 4.L lists the commonl" use$ functions in this li%rar".
Ta%le 4.E( Commonl" use$ Ct"pe li%rar" functions
6unction ,escription
isalnum Returns if the specifie$ character is alphanumeric *a H# A I# 3 J+
isalpha Returns if the specifie$ character is alpha%etic *a H# A I+
isntrl Returns if the specifie$ character is a control character *$ecimal 3 3 an$ -L+
is$igit Returns if the specifie$ character is a $igit *3 J+
islower Returns if the specifie$ character is lowercase
isprint Returns if the specifie$ character is printa%le *$ecimal 3- -E+
isupper Returns if the specifie$ character is uppercase
toupper Convert a character to uppercase
tolower Convert a character to lowercase
't$li% Li%rar"
The 't$li% li%rar" contains stan$ar$ li%rar" functions. Ta%le 4.! lists the commonl"
use$ functions in this li%rar".
E8ample 4.E
Brite a program to calculate the trigonometric sine of the angles from 3

to J3

in steps
of

an$ store the result in an arra" calle$ TrigK'ine.
'olution 4.E
The reCuire$ program listing is shown in 6igure 4.-L *program 'IGE.C+. A loop is
create$ using a for statement# an$ insi$e this loop the sine of the angles are calculate$
an$ store$ in arra" TrigK'ine. Gote that the angles must %e converte$ into ra$ians
%efore the" are use$ in function sin.
'tring Li%rar"
The functions in the 'tring li%rar" are use$ to perform string an$ memor" manipulation
operations. Ta%le 4.J lists the commonl" use$ functions in this li%rar".
Ta%le 4.L( Commonl" use$ )ath li%rar" functions
6unction ,escription
acos Returns in ra$ians the arc cosine of its parameter
asin Returns in ra$ians the arc sine of its parameter
atan Returns in ra$ians the arc tangent of its parameter
atan- Returns in ra$ians the arc tangent of its parameter where the signs of %oth
parameters are use$ to $etermine the Cua$rant of the result
cos Returns the cosine of its parameter in ra$ians
cosh Returns the h"per%olic cosine of its parameter
e8p Returns the e8ponential of its parameter
fa%s Returns the a%solute value of its parameter
log Returns the natural logarithm of its parameter
Log3 Returns the logarithm to %ase 3 of its parameter
pow Returns the power of a num%er
sin Returns the sine of its parameter in ra$ians
sinh Returns the h"per%olic sine of its parameter
sCrt Returns the sCuare root of its parameter
tan Returns the tangent of its parameter in ra$ians
tanh Returns the h"per%olic sine of its parameter
E8ample 4.L
Brite a program to illustrate how the two strings :)T P/BER60L< an$
:C/)P0TER< can %e 5oine$ into a new string using 'tring li%rar" functions.
'olution 4.L
The reCuire$ program listing is shown in 6igure 4.-! *program a/IG.C+. The
mikroC 'tring li%rar" function strcat is use$ to 5oin the two strings pointe$ to %"
p an$ p- into a new string store$ in a character arra" calle$ GewK'tring.
Ta%le 4.!( Commonl" use$ 't$li% li%rar" functions
6unction ,escription
a%s Returns the a%solute value
atof Converts A'CII character into floating point num%er
atoi Converts A'CII character into integer num%er
atol Converts A'CII character into long integer
ma8 Returns the greater of two integers
min Returns the lesser of two integers
ran$ Returns a ran$om num%er %etween 3 an$ 3-LEL? function sran$ must %e calle$ to
o%tain a $ifferent seCuence of num%ers
sran$ Yenerates a see$ for function ran$ so a new seCuence of num%ers is generate$
8toi Convert input string consisting of he8a$ecimal $igits into integer
/
TRIGONOMETRI* SINE OF ANGLES $ !o T$ DEGREES
7777777777777777777777777777777777777777777
This program al8la!es !he !rigonome!ri sine of angles from $ "egrees !o
T$ "egrees in s!eps of / "egree' The res8l!s are s!ore" in an arra+ alle"
Trig9Sine'
Programmer( Dogan I)rahim
File( SINE'*
Da!e( Ma+, -$$.
/
void main34
5
unsigned char K6
double PI 7 M'/1/2T, ra"s6
for3K 7 $6 K D7 T$6 KLL4
5
ra"s 7 K

PI //0$'$6
angle 7 sin3ra"46
Trig9SineHKI 7 angle6
;
;
6igure 4.-L( Calculating the sine of angles 3

to J3

Ta%le 4.J( Commonl" use$ 'tring li%rar" functions
6unction ,escription
strcat# strncat Appen$ two strings
strchr# strp%rk Locate the first occurrence of a character in a string
strcmp# strncmp Compare two strings
strcp"# strncp" Cop" one string into another one
strlen Return the length of a string
/
VOINING T:O STRINGS
7777777777777777777
This program sho%s ho% !%o s!rings an )e Koine" !o o)!ain a ne% s!ring'
miJro* li)rar+ f8n!ion s!ra! is 8se" !o Koin !he !%o s!rings poin!e" !o )+
p/ an" p- in!o a ne% s!ring s!ore" in hara!er arra+ Ne%9S!ring'
Programmer(
File(
Da!e(
Dogan I)rahim
VOIN'*
Ma+, -$$.
/
void main34
5
const char

p/ 7 RM? PO:ERF>L R6 // Firs! s!ring


const char

p- 7 R*OMP>TERS6 // Seon" s!ring


char Ne%9S!ringH0$I6
s!ra!3s!ra!3Ne%9S!ring, p/4, p-46 // Koin !he !%o s!rings
;
6igure 4.-!( aoining two strings using function strcat
4.3.L )iscellaneous Li%rar"
The functions in the )iscellaneous li%rar" inclu$e routines to convert $ata from one
t"pe to another t"pe# as well as to perform some trigonometric functions. Ta%le 4.3
lists the commonl" use$ functions in this li%rar".
The following general programs illustrate the use of various li%rar" routines availa%le
with the mikroC language.
Ta%le 4.3( Commonl" use$ )iscellaneous
li%rar" functions
6unction ,escription
7"teTo'tr Convert a %"te into string
'hortTo'tr Convert a short into string
Bor$To'tr Convert an unsigne$ wor$ into string
IntTo'tr Convert an integer into string
LongTo'tr Convert a long into string
6loatTo'tr Convert a float into string
7c$-,ec Convert a 7C, num%er into $ecimal
,ec-7c$ Convert a $ecimal num%er into 7C,
E8ample 4.!
Brite a function to convert the string pointe$ to %" p into lowercase or uppercase#
$epen$ing on the value of a mo$e parameter passe$ to the function. If the mo$e
parameter is nonHero# then convert to lowercase# otherwise convert it to uppercase. The
function shoul$ return a pointer to the converte$ string.
'olution 4.!
The reCuire$ program listing is given in 6igure 4.-J *program CA'E.C+. The program
checks the value of the mo$e parameter# an$ if this parameter is nonHero the string is
converte$ to lowercase %" calling function ToLower# otherwise the function To0pper is
calle$ to convert the string to uppercase. The program returns a pointer to the converte$
string.
E8ample 4.J
Brite a program to $efine a comple8 num%er structure# then write functions to a$$ an$
su%tract two comple8 num%ers. 'how how "ou can use these functions in a main
program.
'olution 4.J
6igure 4.33 shows the reCuire$ program listing *program C/)PLEM.C+. At the
%eginning of the program# a $ata t"pe calle$ comple8 is create$ as a structure having
a real part an$ an imaginar" part. A function calle$ A$$ is then $efine$ to a$$ two
comple8 num%ers an$ return the sum as a comple8 num%er. 'imilarl"# the function
_
t
_
h
/
*ON=ERT A STRING TO LO:ER/>PPER*ASE
77777777777777777777777777777777777777
This program reei&es a s!ring poin!er an" a mo"e parame!er' If !he mo"e is /
Then !he s!ring is on&er!e" !o lo%erase, o!her%ise !he s!ring is on&er!e" !o
8pperase'
Programmer(
File(
Da!e(
Dogan I)rahim
*ASE'*
Ma+, -$$.
/
unsigned char

S!r9*on&er!38nsigne" har

p, 8nsigne" har mo"e4


5
unsigned char

p!r 7 p6
if 3mo"e U7 $4
5
;
else
5
;
while3

p U7 AW$B4

pLL 7 ToLo%er3

p46
while3

p U7 AW$B4

pLL 7 To>pper3

p46
re!8rn p!r6
;
6igure 4.-J( Program for E8ample 4.!
'u%tract is $efine$ to su%tract two comple8 num%ers an$ return the result as a comple8
num%er. The main program uses two comple8 num%ers# a an$ %# where#
a @ -.3 3.35
% @ -.A D -.35
Two other comple8 num%ers# c an$ $# are also $eclare$# an$ the following comple8
num%er operations are performe$(
The program calculates# c @ a D % an$# $ @ a %
E8ample 4.-3
A pro5ectile is fire$ at an angle of " $egrees at an initial velocit" of v meters per
secon$. The $istance travele$ %" the pro5ectile *$+# the flight time *t+# an$ the
ma8imum height reache$ *h+ are given %" the following formulas(
v
-
sin\"]
g
-v sin\"]
$
g
@
v
-
sin\-"]
g
/
*OMPLEQ N>M#ER ADDITION AND S>#TRA*TION
7777777777777777777777777777777777777777777
This program rea!es a "a!a s!r8!8re alle" ompleG ha&ing a real par! an"
an imaginar+ par!' Then, f8n!ions are "efine" !o a"" or s8)!ra! !%o ompleG
n8m)ers an" s!ore !he res8l! in ano!her ompleG n8m)er'
The firs! ompleG n8m)er is, a 7 -'$ F -'$K
The seon" ompleG n8m)er is, ) 7 -'2 L -'$K
The program al8la!es, 7 a L )
an", " 7 a X )
Programmer( Dogan I)rahim
File( *OMPLEQ'*
Da!e( Ma+, -$$.
/
/

Define a ne% "a!a !+pe alle" ompleG

/
typedef s!r8!
5
float real6
float imag6
; ompleG6
/

Define a f8n!ion !o a"" !%o ompleG n8m)ers an" re!8rn !he res8l! as
a ompleG n8m)er

/
complex A""3ompleG i, ompleG K4
5
complex E6
E'real 7 i'real L K'real6
E'imag 7 i'imag L K'imag
re!8rn E6
;
/

Define a f8n!ion !o s8)!ra! !%o ompleG n8m)ers an" re!8rn !he res8l! as
a ompleG n8m)er

/
complex S8)!ra!3ompleG i, ompleG K4
5
complex E6
E'real 7 i'real F K'real6
E'imag 7 i'imag F K'imag6
re!8rn E6
6igure 4.33( Program for E8ample 4.J
*Continue$+
;
/

Main program

/
void main34
5
complex a,),, "6
a'real 7 -'$6 a'imag 7XM'$6 // Firs! ompleG n8m)er
)'real 7 -'26 )'imag 7 -'$6 // seon" ompleG n8m)er
7 A""3a, )46 // A"" n8m)ers
" 7 S8)!ra!3a, )46 // S8)!ra! n8m)ers
;
6igure 4.33( *Cont2$+
Brite functions to calculate the height# flight time# an$ $istance travele$. Assuming
that g @ J.!m9s
-
# v @ - m9s# an$ " @ 4A

# call the functions to calculate the three
varia%les. 6igure 4.3 shows the pro5ectile pattern.
'olution 4.-3
The reCuire$ program is given in 6igure 4.3- *program PR/aECTILE.C+.
Three functions are $efine$( Height calculates the ma8imum height of the
Height
v
h
,istance
6igure 4.3( Pro5ectile pattern
/
PROVE*TILE *AL*>LATION
777777777777777777777777
This program al8la!es !he maGim8m heigh!, "is!ane !ra&ele", an" !he fligh!
!ime of a proKe!ile' The!a is !he firing angle, an" & is !he ini!ial &eloi!+ of !he
proKe!ile respe!i&el+'
Programmer( Dogan I)rahim
File( PROVE*TILE'*
Da!e( Ma+, -$$.
/
#define gra&i!+ T'0/
/

This f8n!ion on&er!s "egrees !o ra"ians

/
float Ra"ians3floa! +4
5
float ra"6
ra" 7 +

M'/1/2T / /0$'$6
re!8rn ra"6
;
/

Fligh! !ime of !he proKe!ile

/
float Fligh!9!ime3floa! !he!a, floa! &4
5
float !, ra"6
ra" 7 Ra"ians3!he!a46
! 7 3-'$

&

sin3ra"44 / gra&i!+6
re!8rn !6
;
float Heigh!3floa! !he!a, floa! &4
5
float h, ra"6
ra" 7 Ra"ians3!he!a46
h 7 3&

&

sin3ra"44 / gra&i!+6
re!8rn h6
;
float Dis!ane3floa! !he!a, floa! &4
5
6igure 4.3-( Program for E8ample 4.-3
*Continue$+
float ", ra"6
ra" 7 ra"ians3!he!a46
" 7 3&

&

sin3-

ra"44 / gra&i!+6
re!8rn "6
;
/

Main program

/
void main34
5
float !he!a, &, h, ", !6
!he!a 7 12'$6
& 7 /-'$6
h 7 Heigh!3!he!a, &46
" 7 Dis!ane3!he!a, &46
! 7 Fligh!9!ime3!he!a, &46
;
6igure 4.3-( *Cont2$+
pro5ectile# 6lightKtime calculates the flight time# an$ ,istance calculates the
$istance travele$. In a$$ition# a function calle$ Ra$ians converts $egrees into
ra$ians to use in the trigonometric function sine. The height# $istance travele$#
an$ flight time are calculate$ an$ store$ in floating point varia%les h# $#
an$ t respectivel".
4.4 'ummar"
This chapter has $iscusse$ the important topics of functions an$ li%raries. 6unctions
are useful when part of a co$e must %e repeate$ several times from $ifferent points
of a program. The" also make programs more rea$a%le an$ easier to manage
an$ maintain. A large program can %e split into man" functions that are teste$
in$epen$entl" an$# once all of them are working# are com%ine$ to pro$uce the
final program.
The mikroC language li%rar" functions have also %een $escri%e$ %riefl"# along with
e8amples of how to use several of these functions in main programs. Li%rar" functions
simplif" programmers2 tasks %" provi$ing rea$" an$ teste$ routines that can %e calle$
an$ use$ in their programs.
4.A E8ercises
. Brite a function to calculate the circumference of a rectangle. The function shoul$
receive the two si$es of the rectangle as floating point num%ers an$ return the
circumference as a floating point num%er.
-. Brite a main program to use the function "ou $evelope$ in E8ercise . 6in$ the
circumference of a rectangle whose si$es are -.3cm an$ A.Ecm. 'tore the result in
a floating point num%er calle$ )"Result.
3. Brite a function to convert inches to centimeters. The function shoul$ receive
inches as a floating point num%er an$ then calculate the eCuivalent centimeters.
4. Brite a main program to use the function "ou $evelope$ in E8ercise 3. Convert
-.A inches into centimeters an$ store the result as a floating point num%er.
A. An LE, is connecte$ to port pin R73 of a PIC!64A-&t"pe microcontroller
through a current limiting resistor in current sinking mo$e. Brite a program to
flash the LE, in five&secon$ intervals.
E. Eight LE,s are connecte$ to P/RT7 of a PIC!64A-&t"pe microcontroller. Brite
a program so that the LE,s count up in %inar" seCuence with a one&secon$ $ela"
%etween outputs.
L. An LE, is connecte$ to port pin R7L of a PIC!64A- microcontroller. Brite a
program to flash the LE, such that the /G time is five secon$s# an$ the /66 time
is three secon$s.
!. A te8t&%ase$ LC, is connecte$ to a PIC!64A-&t"pe microcontroller in 4&%it $ata
mo$e. Brite a program that will $ispla" a count from 3 to -AA on the LC, with a
one&secon$ interval %etween counts.
J. A te8t&%ase$ LC, is connecte$ to a PIC microcontroller as in E8ercise !. Brite a
program to $ispla" the te8t :E8ercise J< on the first row of the LC,.
3. Repeat E8ercise J %ut $ispla" the message on the first row# starting from column 3
of the LC,.
. A two&row te8t&%ase$ LC, is connecte$ to a PIC!64A-&t"pe microcontroller in
4&%it&$ata mo$e. Brite a program to $ispla" the te8t :C/0GT'(< on row an$
then to count repeate$l" from to 33 on row - with two&secon$ intervals.
-. Brite a program to calculate the trigonometric cosine of angles from 3

to 4A

in
steps of

an$ store the results in a floating point arra".
3. Brite a function to calculate an$ return the length of the h"potenuse of a right&
angle triangle# given its two si$es. 'how how "ou can use the function in a main
program to calculate the h"potenuse of a right&angle triangle whose two si$es are
4.3cm an$ A.3cm.
4. Brite a program to configure port pin R7- of a PIC!64A- microcontroller as the
R'-3- serial output port. 'en$ character :M< to this port at 4!33 %au$.
A. Port R73 of a PIC!64A- microcontroller is configure$ as the R'-3- serial output
port. Brite a program to sen$ out string :'ERIAL< at JE33 %au$.
E. Repeat E8ercise A %ut use the har$ware 0'ART availa%le on the microcontroller
chip.
L. E8plain the $ifferences %etween software&implemente$ serial $ata communication
an$ 0'ART har$ware&%ase$ serial communication.
!. Brite a function to a$$ two arra"s that are passe$ to the function as arguments.
'tore the sum in one of these arra"s.
J. Brite a function to perform the following operations on two&$imensional matrices(
a+ A$$ matrices
%+ 'u%tract matrices
c+ )ultipl" matrices
-3. Brite a function to convert %etween polar an$ rectangular coor$inates.
-. Brite functions to convert temperature e8presse$ in Celsius to 6ahrenheit an$ vice
versa. 'how how these functions can %e calle$ from main programs to convert
-3

C to

6 an$ also 33

6 to

C.
--. Brite a program to store the value of function f*8+ in an arra" as 8 is varie$ from
3 to 3 in steps of 3.A. Assume that(
f\8] @ (38
3
-(A8
-
D 3(8 4(A
www. newnespress. co m
CHAP T E R A
PIC! ,evelopment Tools
The $evelopment of a microcontroller&%ase$ s"stem is a comple8 process. ,evelopment
tools are har$ware an$ software tools $esigne$ to help programmers $evelop an$ test
s"stems in a relativel" short time. There are man" such tools# an$ a $iscussion of all of
them is %e"on$ the scope of this %ook. This chapter offers a %rief review of the most
common tools.
The tools for $eveloping software an$ har$ware for microcontroller&%ase$ s"stems
inclu$e e$itors# assem%lers# compilers# $e%uggers# simulators# emulators# an$ $evice
programmers. A t"pical $evelopment c"cle starts with writing the application
program using a te8t e$itor. The program is then translate$ into an e8ecuta%le co$e
with the help of an assem%ler or compiler. If the program has several mo$ules# a
linker is use$ to com%ine them into a single application. An" s"nta8 errors are
$etecte$ %" the assem%ler or compiler an$ must %e correcte$ %efore the e8ecuta%le
co$e can %e generate$. Ge8t# a simulator is use$ to test the application program
without the target har$ware. 'imulators are helpful in checking the correctness of an
algorithm or a program with limite$ or no input&outputs# an$ most errors can %e
remove$ $uring simulation. /nce the program seems to %e working an$ the
programmer is happ" with it# the e8ecuta%le co$e is loa$e$ to the target
microcontroller chip using a $evice programmer# an$ the s"stem logic is teste$.
'oftware an$ har$ware tools such as in&circuit $e%uggers an$ in&circuit emulators can
anal"He the program2s operation an$ $ispla" the varia%les an$ registers in real time
with the help of %reakpoints set in the program.
--- Chapter A
ss. co m
A. 'oftware ,evelopment Tools
'oftware $evelopment tools are computer programs# usuall" run on personal computers#
that allow the programmer *or s"stem $eveloper+ to create# mo$if"# an$ test applications
programs. 'ome common software $evelopment tools are(

Te8t e$itors

Assem%lers9compilers

'imulators

High&level language simulators

Integrate$ $evelopment environments *I,Es+
A.. Te8t E$itors
A te8t e$itor is use$ to create or e$it programs an$ te8t files. The Bin$ows operating
s"stem comes with a te8t e$itor program calle$ Gotepa$. 0sing Gotepa$# we can create
a new program file# mo$if" an e8isting file# or $ispla" or print the contents of a file. It is
important to realiHe that programs use$ for wor$ processing# such as )icrosoft Bor$#
cannot %e use$ for this purpose# since the" em%e$ wor$ formatting characters such as
%ol$# italic# an$ un$erline within the te8t.
)ost assem%lers an$ compilers come with %uilt&in te8t e$itors# making it possi%le
to create a program an$ then assem%le or compile it without having to e8it from the
e$itor. These e$itors provi$e a$$itional features as well# such as automatic ke"wor$
highlighting# s"nta8 checking# parenthesis matching# an$ comment line i$entification.
,ifferent parts of a program can %e shown in $ifferent colors to make the program
more rea$a%le *e.g.# comments in one color an$ ke"wor$s in another+. 'uch features
help to eliminate s"nta8 errors $uring the programming stage# thus spee$ing up the
$evelopment process.
A..- Assem%lers an$ Compilers
Assem%lers generate e8ecuta%le co$e from assem%l" language programs# an$ that
generate$ co$e can then %e loa$e$ into the flash program memor" of a PIC!&%ase$
microcontroller. Compilers generate e8ecuta%le co$e from high&level language
programs. The compilers use$ most often for PIC! microcontrollers are 7A'IC# C#
an$ PA'CAL.
www. newnespress. co m
PIC! ,evelopment Tools --3
Assem%l" language is use$ in applications where processing spee$ is critical an$ the
microcontroller must respon$ to e8ternal an$ internal events in the shortest possi%le
time. However# it is $ifficult to $evelop comple8 programs using assem%l" language#
an$ assem%l" language programs are not eas" to maintain.
High&level languages# on the other han$# are easier to learn# an$ comple8 programs can
%e $evelope$ an$ teste$ in a much shorter time. High&level programs are also
maintaine$ more easil" than assem%l" language programs.
,iscussions of programming in this %ook are limite$ to the C language. )an" $ifferent
C language compilers are availa%le for $eveloping PIC! microcontroller&%ase$
programs. 'ome of the popular ones are(

CC' C *http(99www. c csinfo.com+

Hi&Tech C *http(99htsoft.co m +

C! C *http(99www.microchip.com+

mikroC C *http(99www.m ikroe.com+

BiH&C C *http(99www.fore$.co.uk+
Although most C compilers are essentiall" the same# each one has its own a$$itions or
mo$ifications to the stan$ar$ language. The C compiler use$ in this %ook is mikroC#
$evelope$ %" mikroElektronika.
A..3 'imulators
A simulator is a computer program that runs on a PC without the microcontroller
har$ware. It simulates the %ehavior of the target microcontroller %" interpreting
the user program instructions using the microcontroller instruction set. 'imulators can
$ispla" the contents of registers# memor"# an$ the status of input&output ports as
the user program is interprete$. 7reakpoints can %e set to stop the program an$
check the contents of various registers at $esire$ locations. In a$$ition# the user
program can %e e8ecute$ in a single&step mo$e# so the memor" an$ registers
can %e e8amine$ as the program e8ecutes one instruction at a time as a ke" is
presse$.
'ome assem%ler programs contain %uilt&in simulators. Three popular PIC!
microcontroller assem%lers with %uilt&in simulators are(
ss. co m
--4 Chapter A

)PLA7 I,E *http(99www.mic r ochip.com+

/shon 'oftware PIC! simulator *http(99www.oshonsoft .com+

6orest Electronics PIC! assem%ler *http(99www. f ore$.co.uk+
A..4 High&Level Language 'imulators
High&level language simulators# also known as source&level $e%uggers# are programs
that run on a PC an$ locate errors in high&level programs. The programmer can set
%reakpoints in high&level statements# e8ecute the program up to a %reakpoint# an$ then
view the values of program varia%les# the contents of registers# an$ memor" locations at
that %reakpoint.
A source&level $e%ugger can also invoke har$ware&%ase$ $e%ugging using a har$ware
$e%ugger $evice. 6or e8ample# the user program on the target microcontroller can %e
stoppe$ an$ the values of various varia%les an$ registers can %e e8amine$.
'ome high&level language compilers# inclu$ing the following three# have %uilt&in
source&level $e%uggers(

C! C

Hi&Tech PIC! C

mikroC C
A..A Integrate$ ,evelopment Environments *I,Es+
Integrate$ $evelopment environments *I,Es+ are powerful PC&%ase$ programs which
inclu$e ever"thing to e$it# assem%le# compile# link# simulate# an$ source&level $e%ug
a program# an$ then $ownloa$ the generate$ e8ecuta%le co$e to the ph"sical
microcontroller chip using a programmer $evice. These programs are in graphical user
interface *Y0I+# where the user can select various options from the program without
having to e8it it. I,Es can %e e8tremel" useful when $eveloping microcontroller&%ase$
s"stems. )ost PIC! high&level language compilers are I,Es# thus ena%ling the
programmer to $o most tasks within a single software $evelopment tool.
A.- Har$ware ,evelopment Tools
Gumerous har$ware $evelopment tools are availa%le for the PIC! microcontrollers.
'ome of these pro$ucts are manufacture$ %" )icrochip Inc.# an$ some %" thir$&part"
companies. The most ones are(
www. newnespress. co m
PIC! ,evelopment Tools --A

,evelopment %oar$s

,evice programmers

In&circuit $e%uggers

In&circuit emulators

7rea$%oar$s
A.-. ,evelopment 7oar$s
,evelopment %oar$s are invalua%le microcontroller $evelopment tools. 'imple
$evelopment %oar$s contain 5ust a microcontroller an$ the necessar" clock circuitr".
'ome sophisticate$ $evelopment %oar$s contain LE,s# LC,# push %uttons# serial
ports# 0'7 port# power suppl" circuit# $evice programming har$ware# an$ so on.
This section is a surve" of various commerciall" availa%le PIC! microcontroller
$evelopment %oar$s an$ their specifications.
LA7&M0'7 E8perimenter 7oar$
The LA7&M0'7 E8perimenter %oar$ *see 6igure A.+# manufacture$ %"
microEngineering La%s Inc.# can %e use$ in 43&pin PIC!&%ase$ pro5ect $evelopment.
The %oar$ is availa%le either assem%le$ or as a %are %oar$.
The %oar$ contains(

43&pin II6 socket for PIC microcontroller

A&volt regulator

-3)HH oscillator

Reset %utton

E&switch ke"pa$

Two potentiometers

6our LE,s

-&line %" -3&character LC, mo$ule

'peaker
ss. co m
--E Chapter A
6igure A.( LA7&M0'7 E8perimenter %oar$

RC servo connector

R'-3- interface

0'7 connector

'ocket for $igital&to&analog converter *$evice not inclu$e$+

'ocket for I-C serial EEPR/) *$evice not inclu$e$+

'ocket for ,allas ,'33L real&time clock *$evice not inclu$e$+

Pa$s for ,allas ,'!'-3 temperature sensors *$evice not inclu$e$+

In&circuit programming connector

Protot"ping area for a$$itional circuits
PIC,E) - Plus
Th PIC,E) - Plus kit *see 6igure A.-+# manufacture$ %" )icrochip Inc.# can %e use$ in
the $evelopment of PIC! microcontroller&%ase$ pro5ects.
www. newnespress. co m
PIC! ,evelopment Tools --L
6igure A.-( PIC,E) - Plus $evelopment %oar$
The %oar$ contains(

- E LC, $ispla"

PieHo soun$er $riven %" PB) signal

Active R' -3- port

/n&%oar$ temperature sensor

6our LE,s

Two push&%utton switches an$ master reset

'ample PIC!64A-3 an$ PICE6!LLA flash microcontrollers

)PLA7 REAL ICE9)PLA7 IC, - connector

'ource co$e for all programs

,emonstration program $ispla"ing a real&time clock an$ am%ient
temperature

Yenerous protot"ping area

Borks off of a JF %atter" or ,C power pack
ss. co m
--! Chapter A
PIC,E) 4
The PIC,E) 4 kit *see 6igure A.3+# manufacture$ %" )icrochip Inc.# can %e use$ in the
$evelopment of PIC! microcontroller&%ase$ pro5ects.
The %oar$ contains(

Three $ifferent sockets supporting !&# 4&# an$ !&pin ,IP $evices

/n&%oar$ DAF regulator for $irect input from JF# 33 mA AC9,C wall a$apter

Active R'&-3- port

Eight LE,s

- E LC, $ispla"

Three push&%utton switches an$ master reset

Yenerous protot"ping area

I9/ e8pan$er

'upercapacitor circuitr"

Area for an LIG transceiver
6igure A.3( PIC,E) 4 $evelopment %oar$
www. newnespress. co m
PIC! ,evelopment Tools --J

Area for a motor $river

)PLA7 IC, - connector
PIC,E) HPC E8plorer 7oar$
The PIC,E) HPC E8plorer $evelopment %oar$ *see 6igure A.4+# manufacture$ %"
)icrochip Inc.# can %e use$ in the $evelopment of high pin count PIC!&series
microcontroller&%ase$ pro5ects.
The main features of this %oar$ are(

PIC!6!L--# -!. flash# !3&pin TR6P microcontroller

'upports PIC! a&series $evices with plug&in mo$ules

3)HH cr"stal oscillator *to %e use$ with internal PLL to provi$e 43)HH
operation+

Power suppl" connector an$ programma%le voltage regulator# capa%le of
operation from -.3 to A.AF

Potentiometer *connecte$ to 3&%it A9,# analog input channel+

Temperature sensor $emo inclu$e$
6igure A.4( PIC,E) HPC E8plorer $evelopment %oar$
ss. co m
-33 Chapter A

Eight LE,s *connecte$ to P/RT, with 5umper $isa%le+

R'&-3- port *J&pin ,&t"pe connector# 0ART+

Reset %utton

3-.HH cr"stal for real&time clock $emonstration
).& 0niversal PIC ,evelopment 7oar$
The ).& 0niversal PIC $evelopment %oar$ *see 6igure A.A+# manufacture$ %" 7a5i
La%s# can %e use$ for $eveloping PIC microcontroller&%ase$ pro5ects with up to 43 pins.
The %oar$ has a ke" mechanism which allows an" peripheral $evice to %e mappe$ to
an" pin of the processor# making the %oar$ ver" fle8i%le. A small %rea$%oar$ area is
also provi$e$# ena%ling users to $esign an$ test their own circuits.
6igure A.A( ).& 0niversal PIC $evelopment %oar$
www. newnespress. co m
PIC! ,evelopment Tools -3
The %oar$ has the following features(

/n&%oar$ selecta%le 3.3F or AF

E - LC, character $ispla" *!& or 4&%it mo$e supporte$+

4&$igit multiple8e$ L&segment $ispla"

Ten LE, %ar graph *can %e use$ as in$ivi$ual LE,s+

Eight&position $ip switch

'ockete$ oscillator for eas" change of oscillators

'tepper motor $river with integrate$ $river

I
-
C real&time clock with cr"stal an$ %atter" %ackup support

I
-
C temperature sensor with 3.A $egree C precision

Three potentiometers for $irect A9, $evelopment

E&%utton telephone ke"pa$ wire$ as 4 4 matri8

R'-3- $river with stan$ar$ ,7J connector

'ockete$ 'PI an$ I
-
C EEPR/)

R6 Mmit an$ receive sockets

IR Mmit an$ receive

E8ternal $rive %uHHer

Eas" access to pull up resistors

AC a$apter inclu$e$
''E4A- ,evelopment 7oar$
The ''E4A- $evelopment %oar$ *see 6igure A.E+# manufacture$ %" 'huan 'hiHu
Electronic La%orator"# can %e use$ for $eveloping PIC!&%ase$ microcontroller
pro5ects# especiall" the PIC!6MM- series of microcontrollers# an$ also for
programming the microcontrollers.
The main features of this %oar$ are(

/ne PC7 suita%le for an" -!& or 43&pin PIC! $evices
ss. co m
-3- Chapter A

Three e8ternal interrupt pins
www. newnespress. co m
PIC! ,evelopment Tools -33
6igure A.E( ''E4A- $evelopment %oar$

Two input&capture9output&compare9pulse&wi$th mo$ulation mo$ules *CCP+

'upport 'PI# I
-
C functions

3&%it analog&to&$igital converter

R'&-3- connector

Two $e%ounce$ push&%utton switches

An !&%it ,IP&switch for $igital input

4 4 ke"pa$ connector

Rotar" enco$er with push %utton

TCLL 'PI temperature sensor

EEPR/) *-4LC347+

- -3 %us e8pansion port

IC,- connector

/n&%oar$ multiple $igital signals from HH to !)HH

/ptional $evices are - -3 character LC,# 4!9-!&pin II6 socket
ss. co m
-34 Chapter A
''E!L-3 ,evelopment 7oar$
The ''E!L-3 $evelopment %oar$ *see 6igure A.L+# manufacture$ %" 'huan 'hiHu
Electronic La%orator"# can %e use$ for the $evelopment of PIC!&%ase$ microcontroller
pro5ects. A large amount of memor" an$ I9/ interface is provi$e$# an$ the %oar$ can
also %e use$ to program microcontrollers.
The main features of this %oar$ are(

-3)HH oscillator with socket

/ne ,7J connector provi$es EIA-3- interface

In&circuit $e%ugger *IC,+ connector

6our $e%ounce$ switches# an$ one reset switch

4 4 ke"pa$ connector

/ne potentiometer for analog&to&$igital conversion

Eight re$ LE,s

!&%it ,IP switch for $igital inputs

- -3 character LC, mo$ule

Twent"&four $ifferent $igital signals# from HH to E)HH
6igure A.L( ''E!L-3 $evelopment %oar$
www. newnespress. co m
PIC! ,evelopment Tools -3A

/n&%oar$ AF regulator

/ne I
-
C EEPR/) with socket

'PI&compati%le $igital temperature sensor

'PI&compati%le real&time clock

CCP output via an GPG transistor
''E!E!3 ,evelopment 7oar$
The ''E!E!3 $evelopment %oar$ *see 6igure A.!+# manufacture$ %" 'huan 'hiHu
Electronic La%orator"# can %e use$ for $eveloping PIC!&%ase$ microcontroller
pro5ects. The %oar$ supports CAG network# an$ a large amount of memor" an$ I9/
interface is provi$e$. The %oar$ can also %e use$ to program microcontrollers.
The main features of this %oar$ are(

-3)HH oscillator with socket

/ne ,7J connector provi$es EIA-3- interface

In&circuit $e%ugger *IC,+ connector

6our $e%ounce$ switches# an$ one reset switch

4 4 ke"pa$ connector
6igure A.!( ''E!E!3 $evelopment %oar$
ss. co m
-3E Chapter A

/ne potentiometer for analog&to&$igital conversion

! re$ LE,s

!&%it ,IP switch for $igital inputs

- -3 character LC, mo$ule

Twent"&four $ifferent $igital signals# from HH to E)HH

/n&%oar$ AF regulator

/ne I
-
C EPR/) with socket

'PI&compati%le $igital temperature sensor

'PI&compati%le real&time clock

CCP output via an GPG transistor

Rotar" enco$er

CAG transceiver
PIC!64A-3 ,evelopment .it
The PIC!64A-3 $evelopment kit *see 6igure A.J+# manufacture$ %" Custom Computer
'ervices Inc.# inclu$es a C compiler *PCBH+# a protot"ping %oar$ with PIC!64A-3
microcontroller# an in&circuit $e%ugger# an$ a programmer.
6igure A.J( PIC!64A-3 $evelopment kit
www. newnespress. co m
PIC! ,evelopment Tools -3L
The main features of this $evelopment kit are(

PCBH compiler

PIC!64A-3 protot"ping %oar$

7rea$%oar$ area

J3LCAE serial EEPR/) chip

,'E3 $igital thermometer chip

Ga0E3AA real&time clock IC with attache$ 3-.LE!.HH cr"stal

Two&$igit L&segment LE, mo$ule

In&circuit $e%ugger9programmer

,C a$apter an$ ca%les
Custom Computer 'ervices manufactures a num%er of other PIC! microcontroller&
%ase$ $evelopment kits an$ protot"ping %oar$s# such as $evelopment kits for CAG#
Ethernet# Internet# 0'7# an$ serial %uses. )ore information is availa%le on the
compan"2s we% site.
7IYPIC4 ,evelopment .it
The 7IYPIC4 is a sophisticate$ $evelopment kit *6igure A.3+ that supports the
latest !3&pin PIC! microcontrollers. The kit comes alrea$" assem%le$# with a
6igure A.3( 7IYPIC4 $evelopment kit
ss. co m
-3! Chapter A
PIC!6!A-3 microcontroller installe$ an$ working at 3)HH. It inclu$es an
on&%oar$ 0'7 port# an on&%oar$ programmer# an$ an in&circuit $e%ugger. The
microcontroller on the %oar$ can %e replace$ easil".
The main features of this $evelopment kit are(

6ort"&si8 %uttons

6ort"&si8 LE,s

0'7 connector

E8ternal or 0'7 power suppl"

Two potentiometers

Yraphics LC,

- E te8t LC,

))C9', memor" car$ slot

Two serial R'-3- ports

In&circuit $e%ugger

Programmer

P'- connector

,igital thermometer chip *,'!-3+

Analog inputs

Reset %utton
The 7IYPIC4 is use$ in some of the pro5ects in this %ook.
60T0RLEC PIC!64A! Training 7oar$
The 60T0RLEC PIC!64A! training %oar$ is a ver" powerful $evelopment kit
*see 6igure A.+ %ase$ on the PIC!64A! microcontroller an$ $evelope$ %"
6uturlec *www.futurl e c.com+. The kit comes alrea$" assem%le$ an$ teste$. /ne
of its %iggest a$vantages is its low cost# at un$er b4A.
www. newnespress. co m
PIC! ,evelopment Tools -3J
6igure A.( 60T0RLEC PIC!64A! training %oar$
Its main features are(

PIC!64A! microcontroller with 3)HH cr"stal

R'-3- communication

Test LE,

/ptional real&time clock chip with %atter" %ackup

LC, connection

/ptional R'4!A9R'4-- with optional chip

CAG an$ 'PI controller

I
-
C e8pansion

In&circuit programming

Reset %utton

'peaker

Rela" socket

All port pins are availa%le at connectors
ss. co m
-43 Chapter A
A.-.- ,evice Programmers
After the program is written an$ translate$ into e8ecuta%le co$e# the resulting HEM
file is loa$e$ to the target microcontroller2s program memor" with the help of a
$evice programmer. The t"pe of $evice programmer $epen$s on the t"pe of
microcontroller to %e programme$. 6or e8ample# some $evice programmers can
onl" program PICE series# some can program %oth PICE an$ PIC! series#
while some are $esigne$ to program other microcontroller mo$els *e.g.# the Intel
!3A series+.
'ome microcontroller $evelopment kits inclu$e on&%oar$ $evice programmers# so the
microcontroller chip $oes not nee$ to %e remove$ an$ inserte$ into a separate
programming $evice. This section $escri%es some of the popular $evice programmers
use$ to program PIC! series of microcontrollers.
6orest Electronics 0'7 Programmer
The 0'7 programmer# manufacture$ %" 6orest Electronics *see 6igure A.-+# can %e
use$ to program most PIC microcontrollers with up to 43 pins# inclu$ing the PIC!
series. The $evice is connecte$ to the 0'7 port of a PC an$ takes its power from this
port.
6igure A.-( 6orest Electronics 0'7 programmer
www. newnespress. co m
PIC! ,evelopment Tools -4
)ach M Programmer
The )ach M programmer *6igure A.3+# manufacture$ %" Custom Computer 'ervices
Inc.# can program microcontrollers of the PIC-# PIC4# PICE# an$ PIC! series
ranging from ! to 43 pins. It can also rea$ the program insi$e a microcontroller an$ then
generate a HEM file. In&circuit $e%ugging is also supporte$ %" this programmer.
6igure A.3( )ach M programmer
)ela%s 0- Programmer
The )ela%s 0- $evice programmer *see 6igure A.4+# manufacture$ %"
microEngineering La%s Inc.# can %e use$ to program most PIC microcontroller
chips having from ! to 43 pins. The $evice is 0'7&%ase$ an$ receives its power
from the 0'7 port of a PC.
ss. co m
-4- Chapter A
6igure A.4( )ela%s 0- programmer
Eas"Prog PIC Programmer
The Eas"Prog PIC is a low&cost programmer *6igure A.A+ use$ with microcontrollers
of the PICE an$ PIC! series having up to 43 pins. It connects to a PC via a J&pin
serial ca%le.
6igure A.A( Eas"Prog programmer
www. newnespress. co m
PIC! ,evelopment Tools -43
PIC Prog Plus Programmer
The PIC Prog Plus is another low&cost programmer *6igure A.E+ that can %e use$ to
program most PIC microcontrollers. The $evice is powere$ from an e8ternal -F ,C
suppl".
A.-.3 In&Circuit ,e%uggers
An in&circuit $e%ugger is har$ware connecte$ %etween a PC an$ the target
microcontroller test s"stem use$ to $e%ug real&time applications Cuickl" an$ easil".
Bith in&circuit $e%ugging# a monitor program runs in the PIC microcontroller in the test
circuit. The programmer can set %reakpoints on the PIC# run co$e# single&step the
program# an$ e8amine varia%les an$ registers on the real $evice an$# if reCuire$# change
their values. An in&circuit $e%ugger uses some memor" an$ I9/ pins of the target PIC
microcontroller $uring $e%ugging operations. 'ome in&circuit $e%uggers onl" $e%ug
assem%l" language programs. /ther# more powerful $e%uggers can $e%ug high&level
language programs.
6igure A.E( PIC Prog Plus programmer
ss. co m
-44 Chapter A
This section $iscusses some of the popular in&circuit $e%uggers use$ in PIC!
microcontroller&%ase$ s"stem applications.
IC,-
The IC,-# a low&cost in&circuit $e%ugger *see 6igure A.L+ manufacture$ %" )icrochip
Inc.# can $e%ug most PIC microcontroller&%ase$ s"stems. Bith the IC,-# programs are
$ownloa$e$ to the target microcontroller chip an$ e8ecute$ in real time. This $e%ugger
supports %oth assem%l" language an$ C language programs.
6igure A.L( IC,- in&circuit $e%ugger
The IC,- connects to a PC through either a serial R'-3- or a 0'7 interface. The
$evice acts like an intelligent interface %etween the PC an$ the test s"stem# allowing
the programmer to set %reakpoints# look into the test s"stem# view registers an$
varia%les at %reakpoints# an$ single&step through the user program. It can also %e
use$ to program the target PIC microcontroller.
IC,&043
The IC,&043 is an in&circuit $e%ugger *see 6igure A.!+ manufacture$ %" Custom
Computer 'ervices Inc. to $e%ug programs $evelope$ with their CC' C compiler.
The $evice operates with a 43)HH clock freCuenc"# is connecte$ to a PC via the
0'7 interface# an$ is powere$ from the 0'7 port. The compan" also manufactures
www. newnespress. co m
PIC! ,evelopment Tools -4A
6igure A.!( IC,&043 in&circuit $e%ugger
a serial&port version of this $e%ugger calle$ IC,&'43# which is powere$ from the
target test s"stem.
PIC6lash -
The PIC6lash - in&circuit $e%ugger *see 6igure A.J+ is manufacture$ %"
mikroElektronika an$ can %e use$ to $e%ug programs $evelope$ in mikro7asic#
mikroC# or mikroPascal languages. The $evice is connecte$ to a PC through its 0'7
6igure A.J( PIC6lash - in&circuit $e%ugger
ss. co m
-4E Chapter A
interface. Power is $rawn from the 0'7 port so the $e%ugger reCuires no e8ternal
power suppl". The PIC6lash - is inclu$e$ in the 7IYPIC4 $evelopment kit. ,etails
on the use of this in&circuit $e%ugger are $iscusse$ later in this chapter.
A.-.4 In&Circuit Emulators
The in&circuit emulator *ICE+ is one of the ol$est an$ the most powerful $evices for
$e%ugging a microcontroller s"stem. It is also the onl" tool that su%stitutes its own
internal processor for the one in the target s"stem. Like all in&circuit $e%uggers# the
emulator2s primar" function is target accesscthe a%ilit" to e8amine an$ change the
contents of registers# memor"# an$ I9/. 'ince the emulator replaces the CP0# it $oes not
reCuire a working CP0 in the target s"stem. This makes the in&circuit emulator %" far
the %est tool for trou%leshooting new or $efective s"stems.
In general# each microcontroller famil" has its own set of in&circuit emulators. 6or
e8ample# an in&circuit emulator $esigne$ for the PICE microcontrollers cannot %e
use$ for PIC! microcontrollers. )oreover# the cost of in&circuit emulators is usuall"
Cuite high. To keep costs $own# emulator manufacturers provi$e a %ase %oar$ which
can %e use$ with most microcontrollers in a given famil"# for e8ample# with all PIC
microcontrollers# an$ also make availa%le pro%e car$s for in$ivi$ual microcontrollers.
To emulate a new microcontroller in the same famil"# then# onl" the specific pro%e
car$ has to %e purchase$.
'everal mo$els of in&circuit emulators are availa%le on the market. The following four
are some of the more popular ones.
)PLA7 ICE 4333
The )PLA7 ICE 4333 in&circuit emulator *6igure A.-3+# manufacture$ %" )icrochip
Inc.# can %e use$ to emulate microcontrollers in the PIC! series. It consists of
an emulator po$ connecte$ with a fle8 ca%le to $evice a$apters for the specific
microcontroller. The po$ is connecte$ to the PC via its parallel port or 0'7
port. 0sers can insert an unlimite$ num%er of %reakpoints in or$er to e8amine
register values.
RICE3333
The RICE3333 is a powerful in&circuit emulator *6igure A.-+# manufacture$ %"
'mart Communications Lt$# for the PICE an$ PIC! series of microcontrollers.
www. newnespress. co m
PIC! ,evelopment Tools -4L
6igure A.-3( )PLA7 ICE 4333
6igure A.-( RICE3333 in&circuit emulator
ss. co m
-4! Chapter A
The $evice consists of a %ase unit with $ifferent pro%e car$s for the various mem%ers
of the PIC microcontroller famil". It provi$es full&spee$ real&time emulation up to
43)HH# supports o%servation of floating point varia%les an$ comple8 varia%les such
as arra"s an$ structures# an$ provi$es source level an$ s"m%olic $e%ugging in
%oth assem%l" an$ high&level languages.
ICEPIC 3
The ICEPIC 3 is a mo$ular in&circuit emulator *see 6igure A.--+# manufacture$ %" R6
'olutions# for the PIC-9E an$ PIC! series of microcontrollers. It connects to the PC
via its 0'7 port an$ consists of a mother %oar$ with a$$itional $aughter %oar$s for each
microcontroller t"pe. The $aughter %oar$s are connecte$ to the target s"stem with
$evice a$apters. A trace %oar$ can %e a$$e$ to capture an$ anal"He e8ecution a$$resses#
opco$es# an$ e8ternal memor" rea$9writes.
6igure A.--( ICEPIC 3 in&circuit emulator
PICE&)C
The PICE&)C# a highl" sophisticate$ emulator *see 6igure A.-3+ manufacture$ %"
Ph"ton Inc.# supports most PIC microcontrollers an$ consists of a main %oar$# po$#
an$ a$apters. The main %oar$ contains the emulator logic# memor"# an$ an interface
to the PC. The po$ contains a slave processor that emulates the target microcontroller.
The a$apters are the mechanical parts that ph"sicall" connect to the microcontroller
sockets of the target s"stem. The PICE&)C provi$es source&level $e%ugging of
www. newnespress. co m
PIC! ,evelopment Tools -4J
6igure A.-3( PICE&)C in&circuit emulator
programs written in %oth assem%l" an$ high&level languages. A large memor" is
provi$e$ to capture target s"stem $ata. The user can set up a large num%er of
%reakpoints an$ can access the program an$ $ata memories to $ispla" or change
their contents.
A.-.A 7rea$%oar$s
7uil$ing an electronic circuit reCuires connecting the components as shown in
the relevant circuit $iagram# usuall" %" sol$ering the components together on
a strip %oar$ or a printe$ circuit %oar$ *PC7+. This approach is appropriate for
circuits that have %een teste$ an$ are functioning as $esire$# an$ also
when the circuit is %eing ma$e permanent. However# making a PC7 $esign for
5ust a few applicationscfor instance# while still $eveloping the circuitcis not
economical.
Instea$# while the circuit is still un$er $evelopment# the components are usuall"
assem%le$ on a sol$erless %rea$%oar$. A t"pical %rea$%oar$ *see 6igure A.-4+
consists of rows an$ columns of holes space$ so that integrate$ circuits an$ other
components can %e fitte$ insi$e them. The holes have spring actions so the
component lea$s are hel$ tightl" in place. There are various t"pes an$ siHes of
%rea$%oar$s# suita%le for circuits of $ifferent comple8ities. 7rea$%oar$s can also %e
ss. co m
-A3 Chapter A
A # * D E F
/
-
M
1
2
N
.
0
T
/$
//
/-
/M
/1
/2
/N
/.
/0
/T
-$
G H I V Y L
6igure A.-4( A t"pical %rea$%oar$ la"out
stacke$ together to make larger %oar$s for ver" comple8 circuits. 6igure A.-A shows
the internal connection la"out of the %rea$%oar$ in 6igure A.-4.
The top an$ %ottom halves of the %rea$%oar$ are entirel" separate. Columns to -3 in
rows A to 6 are connecte$ to each other on a column %asis. Rows Y to L in columns
to -3 are likewise connecte$ to each other on a column %asis. Integrate$ circuits are
place$ such that the legs on one si$e are on the top half of the %rea$%oar$# an$ the
legs on the other si$e are on the %ottom half. The two columns on the
far left of the %oar$ are usuall" reserve$ for the power an$ groun$ connections.
Connections %etween components are usuall" ma$e with stran$e$ *or soli$+ wires
plugge$ into the holes to %e connecte$.
6igure A.-E shows a %rea$%oar$ hol$ing two integrate$ circuits an$ a num%er of
resistors an$ capacitors.
www. newnespress. co m
A # * D E F G H I V Y L
/
-
M
1
2
N
.
0
T
/$
//
/-
/M
/1
/2
/N
/.
/0
/T
-$
6igure A.-A( Internal wiring of the %rea$%oar$ in 6igure A.-4
6igure A.-E( Picture of a %rea$%oar$ with some components
PIC! ,evelopment Tools -A
www. newnespress. co m
The nice thing a%out %rea$%oar$ $esign is that the circuit can %e mo$ifie$
easil" an$ Cuickl"# an$ i$eas can %e teste$ without having to sol$er the
components. /nce a circuit has %een teste$ an$ is working satisfactoril"#
the components are easil" remove$ an$ the %rea$%oar$ can %e use$ for other
pro5ects.
A.3 mikroC Integrate$ ,evelopment
Environment *I,E+
In this %ook we are using the mikroC compiler $evelope$ %" mikroElektronika.
7efore using this compiler# we nee$ to know how the mikroC integrate$
$evelopment environment *I,E+ is organiHe$ an$ how to write# compile# an$
simulate a program in the mikroC language. In this section we will look at the
operation of the mikroC I,E in $etail.
A free -. program siHe limite$ version of the mikroC I,E# availa%le on the
mikroElektronika we% site *www.mikroe.com+# is a$eCuate for most small or me$ium&
siHe$ applications. Alternativel"# "ou can purchase a license an$ turn the limite$
version into a full" working# unlimite$ I,E to use for pro5ects of an" siHe
an$ comple8it".
After installing the mikroC I,E# a new icon shoul$ appear %" $efault on "our
$esktop. ,ou%le&click this icon to start the I,E.
A.3. mikroC I,E 'creen
After the mikroC icon is $ou%le&clicke$ to start the I,E# the screen shown in
6igure A.-L is $ispla"e$ %" $efault.
The screen is $ivi$e$ into four areas( the top&left section# the %ottom&left section# the
mi$$le section# an$ the %ottom section.
Top&Left 'ection
The top left# the Co$e E8plorer section# $ispla"s ever" $eclare$ item in the source
co$e. In the e8ample in 6igure A.-!# main is liste$ un$er 6unctions an$ varia%les
'um an$ i are liste$ un$er main.
ss. co m
-A- Chapter A
*o"e EGplorer
ProKe! Se!8p
Message
:in"o%
*o"e
E"i!or
6igure A.-L( mikroC I,E screen
There are two a$$itional ta%s in the Co$e E8plorer. As shown in 6igure A.-J# the
RHelp ta% lists all the availa%le %uilt&in functions an$ li%rar" functions for a Cuick
reference.
The .e"%oar$ ta% lists all the availa%le ke"%oar$ shortcuts in mikroC I,E *see
6igure A.33+.
7ottom&Left 'ection
In the %ottom&left section# calle$ Pro5ect 'etup *see 6igure A.3+# the microcontroller
$evice t"pe# clock rate# an$ %uil$ t"pe are specifie$. The %uil$ t"pe can %e either
6igure A.-!( Co$e E8plorer form
Release# which is the normal compiler operating mo$e# or IC, $e%ug# if the program is
to %e $e%ugge$ using the in&circuit $e%ugger.
The Pro5ect 'etup section has a ta% calle$ Pro5ect 'ummar" which lists all the t"pes of
files use$ in the pro5ect# as shown in 6igure A.3-.
)i$$le 'ection
The mi$$le section is the Co$e E$itor# an a$vance$ te8t e$itor. Programs are written in
this section of the screen. The Co$e E$itor supports(

Co$e Assistant

Parameter Assistant

Co$e Template

Auto Correct

7ookmarks
6igure A.-J( RHelp form
The Co$e Assistant is useful when writing a program. T"pe the first few letters of
an i$entifier an$ then press the CTRLD'PACE ke"s to list all vali$ i$entifiers
%eginning with those letters. In 6igure A.33# for e8ample# to locate i$entifier strlen#
the letters str are t"pe$ an$ CTRLD'PACE is presse$. strlen can %e selecte$ from
the $ispla"e$ list of matching vali$ wor$s %" using ke"%oar$ arrows an$ pressing
EGTER.
6igure A.33( .e"%oar$ form
The Parameter Assistant is invoke$ when a parenthesis is opene$ after a function or a
proce$ure name. The e8pecte$ parameters are liste$ in a small win$ow 5ust a%ove the
parenthesis. In 6igure A.34# function strlen has %een entere$# an$ unsigne$ char ;s
appears in a small win$ow when a parenthesis is opene$.
Co$e Template is use$ to generate co$e in the program. 6or e8ample# as shown in
6igure A.3A# t"ping switch an$ pressing CTRLDa automaticall" generates co$e for the
6igure A.3( Pro5ect setup form
6igure A.3-( Pro5ect summar" form
switch statement. Be can a$$ our own templates %" selecting Tools &U /ptions &U Auto
Complete. 'ome of the availa%le templates are arra"# switch# for# an$ if.
Auto Correct corrects t"ping mistakes automaticall". A new list of recogniHe$ wor$s
can %e a$$e$ %" selecting Tools &U /ptions &U Auto Correct Ta%.
6igure A.33( 0sing the Co$e Assistant
6igure A.34( 0sing the Parameter Assistant
6igure A.3A( 0sing the Co$e Template
7ookmarks make the navigation easier in large co$e. Be can set %ookmarks %"
entering CTRLD'HI6TDnum%er# an$ can then 5ump to the %ookmark %" pressing
CTRLDnum%er# where num%er is the %ookmark num%er.
7ottom 'ection
The %ottom section of the screen# also calle$ the )essage Bin$ow# consists of three
ta%s( )essages# 6in$# an$ RConverter. Compilation errors an$ warnings are reporte$
un$er the )essages ta%. ,ou%le&clicking on a message line highlights the line where
the error occurre$. A HEM file can %e generate$ onl" if the source file contains
no errors. 6igure A.3E shows the results of a successful compilation liste$ in the
)essage Bin$ow. The RConverter ta% can %e use$ to convert $ecimal num%ers
into %inar" or he8a$ecimal# an$ vice versa.
6igure A.3E( ,ispla" of a successful compilation
A.3.- Creating an$ Compiling a Gew 6ile
mikroC files are organiHe$ into pro5ects# an$ all files for a single pro5ect are store$ in
the same fol$er. 7" $efault# a pro5ect file has the e8tension :.ppc<. A pro5ect file
contains the pro5ect name# the target microcontroller $evice# $evice configuration flags#
the $evice clock# an$ list of source files with their paths. C source files have the
e8tension :.c<.
The following e8ample illustrates step&%"&step how to create an$ compile a program
source file.
E8ample A.
Brite a C program to calculate the sum of the integer num%ers to 3 an$ then sen$ the
result to P/RTC of a PIC!64A-&t"pe microcontroller. Assume that eight LE,s are
connecte$ to the microcontroller2s P/RTC via current limiting resistors. ,raw the
circuit $iagram an$ show the steps involve$ in creating an$ compiling the program.
'olution A.
6igure A.3L shows the circuit $iagram of the pro5ect. The LE,s are connecte$ to
P/RTC using 3J3 ohm current limiting resistors. The microcontroller is operate$
from a 4)HH resonator.
6igure A.3L( Circuit $iagram of the pro5ect
The program is create$ an$ compile$ as follows(
'tep ,ou%le&click the mikroC icon to start the I,E.
'tep - Create a new pro5ect calle$ EMA)PLE. Click Pro5ect &U Gew Pro5ect an$
fill in the form# as shown in 6igure A.3!# %" selecting the $evice t"pe# the clock# an$
the configuration fuse.
ss. co m
6igure A.3!( Creating a new pro5ect
'tep 3 Enter the following program into the Co$e E$itor section of the I,E(
9;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EMA)PLE PR/YRA)
! LE,s are connecte$ to a PIC!64A- t"pe microcontroller.
This program calculates the sum of integer num%ers from to 3
An$ then $ispla"s the sum on P/RTC of the microcontroller.
Author( ,ogan I%rahim
6ile( EMA)PLE.C
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;9
www. newnespress. co m
voi$ main*+
=
unsigne$ int 'um#i?
TRI'C @ 3?
'um @ 3?
for*i@? iW@ 3? iDD+
=
'um @ 'um D i?
>
P/RTC @ 'um?
>
'tep 4 'ave the program with the name EMA)PLE %" clicking 6ile &U 'ave As. The
program will %e save$ with the name EMA)PLE.C.
'tep A Compile the pro5ect %" pressing CTRLD6J or %" clicking the 7uil$ Pro5ect
%utton *see 6igure A.3J+.
#8il" ProKe!
)8!!on
6igure A.3J( 7uil$ Pro5ect %utton
'tep E If the compilation is successful# a 'uccess message will appear in the )essage
Bin$ow as shown in 6igure A.3E. An" program errors will appear in the )essage
Bin$ow an$ shoul$ %e correcte$ %efore the pro5ect procee$s further.
The compiler generates a num%er of output files# which can %e selecte$ %" clicking
Tools &U /ptions &U /utput. The various output files inclu$e(
.A') file This is the assem%l" file of the program. 6igure A.43 shows the EMA)PLE.
A') file.
ss. co m
; ASM code generated by mikroVirtualMachine for PIC - V. 6.2..!
; "ate#$ime% !&#!&#2!!& 6%'6%2
; Info% htt(%##))).mikroelektronika.co.yu
; A""*+SS ,PC,"+ ASM
; ----------------------------------------------
-!!!! -+.!' .!!! /,$, 0main
-!!!1 - 0main%
;+2AMP3+.c4' %% 5oid main67
;+2AMP3+.c41 %% $*ISC 8 !;
-!!!1 -6A9' C3*. $*ISC4 !
;+2AMP3+S.c42! %% Sum 8 !;
-!!!A -6A: C3*. main0Sum03!4 !
-!!!C -6A6 C3*. main0Sum03!;4 !
;+2AMP3+.c42 %% for6i8; i<8 !; i;;7
-!!!+ -!+! M,V3=
-!!! -6+& M,V=. main0i03!4 !
-!!2 -!+!! M,V3= !
-!!' -6+1 M,V=. main0i03!;4 !
-!!6 - 30main0!%
-!!6 -!+!! M,V3= !
-!!1 -6+!! M,V=. S$AC>0!4 !
-!!A -:!1 M,V. main0i03!;4 !4 !
-!!C -:C!! S?@=. S$AC>0!4 !4 !
-!!+ -+!2 @AB 30main0C
-!!2! -:!& M,V. main0i03!4 !4 !
-!!22 -!1!A S?@3= !
-!!2' - 30main0C%
-!!2' -+C!& @AC 30main0
;+2AMP3+.c42C %% S?M 8 Sum ; i;
-!!26 -:!& M,V. main0i03!4 !4 !
-!!21 -26: A""=. main0Sum03!4 4 !
-!!2A -:!1 M,V. main0i03!;4 !4 !
-!!2C -226 A""=.C main0Sum03!;4 4 !
;+2AMP3+.c42' %% D
-!!2+ - 30main02%
;+2AMP3+.c42 %% for6i8; i<8 !; i;;7
-!!2+ -'A& IA.SAB main0i03!4 4 !
-!!C! -2A1 IAC. main0i03!;4 4 !
;+2AMP3+.c42' %% D
-!!C2 -"&. @*A 30main0!
-!!C' - 30main0%
;+2AMP3+.c426 %% P,*$C 8 Sum;
-!!C' -C!: ..12 M,V.. main0Sum03!4 P,*$C
;+2AMP3+.c42& %% D
-!!C1 -"&.. @*A -
6igure A.43( EMA)PLE.A')
.L'T file This is the listing file of the program. 6igure A.4 shows the EMA)PLE.L'T
file.
www. newnespress. co m
; ASM code generated by mikroVirtualMachine for PIC - V. 6.2..!
; "ate#$ime% !&#!&#2!!& &%!&%2
; Info% htt(%##))).mikroelektronika.co.yu
; A""*+SS ,PC,"+ ASM
; ----------------------------------------------
-!!!! -+.!' .!!! /,$, 0main
-!!!1 - 0main%
;+2AMP3+.c4' %% 5oid main67
;+2AMP3+.c41 %% $*ISC 8 !;
-!!!1 -6A9' C3*. $*ISC4 !
;+2AMP3+.c42! %% Sum 8 !;
-!!!A -6A: C3*. main0Sum03!4 !
-!!!C -6A6 C3*. main0Sum03!;4 !
;+2AMP3+.c42 %% for6i8; i<8 !; i;;7
-!!!+ -!+! M,V3=
-!!! -6+& M,V=. main0i03!4 !
-!!2 -!+!! M,V3= !
-!!' -6+1 M,V=. main0i03!;4 !
-!!6 - 30main0!%
-!!6 -!+!! M,V3= !
-!!1 -6+!! M,V=. S$AC>0!4 !
-!!A -:!1 M,V. main0i03!;4 !4 !
-!!C -:C!! S?@=. S$AC>0!4 !4 !
-!!+ -+!2 @AB 30main0C
-!!2! -:!& M,V. main0i03!4 !4 !
-!!22 -!1!A S?@3= !
-!!2' - 30main0C%
-!!2' -+C!& @AC 30main0
;+2AMP3+.c42C %% S?M 8 Sum ; i;
-!!26 -:!& M,V. main0i03!4 !4 !
-!!21 -26: A""=. main0Sum03!4 4 !
-!!2A -:!1 M,V. main0i03!;4 !4 !
-!!2C -226 A""=.C main0Sum03!;4 4 !
;+2AMP3+.c42' %% D
-!!2+ - 30main02%
;+2AMP3+.c42 %% for6i8; i<8 !; i;;7
-!!2+ -'A& IA.SAB main0i03!4 4 !
-!!C! -2A1 IAC. main0i03!;4 4 !
;+2AMP3+.c42' %% D
-!!C2 -"&. @*A 30main0!
-!!C' - 30main0%
;+2AMP3+.c426 %% P,*$C 8 Sum;
-!!C' -C!: ..12 M,V.. main0Sum03!4 P,*$C
;+2AMP3+.c42& %% D
-!!C1 -"&.. @*A -
##EE ProcedureF locationF EE
##A""*+SS P*,C+"?*+
##----------------------------------------------
-!!!1 main
##EE 3abelF locationF EE
##A""*+SS 3A@+3
##----------------------------------------------
-!!!1 0main%
-!!6 30main0!%
-!!2' 30main0C%
-!!2+ 30main02%
-!!C' 30main0%
6igure A.4( EMA)PLE.L'T
*Continue$+
##EE VariableF locationF EE
##A""*+SS VA*IA@3+
##----------------------------------------------
-!!!! S$AC>0!
-!!! S$AC>0
-!!!2 S$AC>02
-!!!C S$AC>0C
-!!!' S$AC>0'
-!!!: S$AC>0:
-!!!6 S$AC>06
-!!!& S$AC>0&
-!!!1 S$AC>01
-!!!9 S$AC>09
-!!!A S$AC>0!
-!!!@ S$AC>0
-!!!C S$AC>02
-!!!" S$AC>0C
-!!!+ S$AC>0'
-!!!. S$AC>0:
-!!! S$AC>06
-!! S$AC>0&
-!!2 S$AC>01
-!!C S$AC>09
-!!' S$AC>02!
-!!: main0Sum03!
-!!& main0i03!
-!.12 P,*$C
-!.9' $*ISC
-!."1 S$A$?S
-!."9 .S*23
-!."A .S*2G
-!."@ P3?S=2
-!."C P*+IAC2
-!."" P,S$"+C2
-!."+ P,S$IAC2
-!.". IA".2
-!.+! @S*
-!.+ .S*3
-!.+2 .S*G
-!.+C P3?S=
-!.+' P*+IAC
-!.+: P,S$"+C
-!.+6 P,S$IAC
-!.+& IA".
-!.+1 =*+/
-!.+9 .S*!3
-!.+A .S*!G
-!.+@ P3?S=!
-!.+C P*+IAC!
-!.+" P,S$"+C!
-!.++ P,S$IAC!
-!.+. IA".!
-!..C P*,"3
-!..' P*,"G
-!..: $A@3A$
-!..6 $@3P$*3
-!..& $@3P$*G
-!..1 $@3P$*?
-!..9 PC3
-!..A PC3A$G
-!..@ PC3A$?
-!.." $,S3
-!..+ $,SG
-!... $,S?
6igure A.4( *Cont2$+
PIC! ,evelopment Tools J
www. newnespress. co m
.HEM file This is the most important output file as it is the one sent to the
programming $evice to program the microcontroller. 6igure A.4- shows the
EMA)PLE.HEM file.
%!!!!!!!!'+.!!.!........9'6A:6A66A!!+!:
%!!!!!!&6+!!!+16+!!!+!!6+1:!!!:C!2+A'
%!!!2!!!&:!!A!1!&+C&:!:261:!622&'ACA
%!!!C!!!12A."&:C!12...."&............9!
%!2!!!!!'!!C!CA
%!+!!!!!!...9...+.....@..............!@
%!!!!!!!..
6igure A.4-( EMA)PLE.HEM
A.3.3 0sing the 'imulator
The program $evelope$ in 'ection A.3.- is simulate$ following the steps given
here# using the simulator in software *release mo$e+. That is# no har$ware is use$ in this
simulation.
E8ample A.-
,escri%e the steps for simulating the program $evelope$ in E8ample A.. ,ispla"
the values of various varia%les an$ P/RTC $uring the simulation while
single&stepping the program. Bhat is the final value $ispla"e$ on P/RTC[
'olution A.-
The steps are as follows(
'tep 'tart the mikroC I,E# making sure the program $evelope$ in E8ample A. is
$ispla"e$ in the Co$e E$itor win$ow.
'tep - 6rom the $rop&$own menu select ,e%ugger &U 'elect ,e%ugger &U
'oftware PIC 'imulator# as shown in 6igure A.43.
'tep 3 6rom the $rop&$own menu select Run &U 'tart ,e%ugger. The $e%ugger
form shown in 6igure A.44 will appear.
'tep 4 'elect the varia%les we want to see $uring the simulation. Assuming we
want to $ispla" the values of varia%les 'um# i# an$ P/RTC(

Click on 'elect from varia%le list an$ then fin$ an$ click on the varia%le
name 'um
ss. co m
3 Chapter A
6igure A.43( 'electing the $e%ugger

Click A$$ to a$$ this varia%le to the Batch list

Repeat these steps for varia%le i an$ P/RTC
The $e%ugger win$ow shoul$ now look like 6igure A.4A.
'tep A Be can now single&step the program an$ see the varia%les changing.
Press the 6! ke" on the ke"%oar$. Tou shoul$ see a %lue line to move $own.
This shows the line where the program is currentl" e8ecuting. .eep pressing
6! until "ou are insi$e the loop an$ "ou will see that varia%les 'um an$ i have
%ecome # as shown in 6igure A.4E. Recentl" change$ items appear in re$.
,ou%le&clicking an item in the Batch win$ow opens the E$it Falue win$ow#
where "ou can change the value of a varia%le or register# or $ispla" the value
in other %ases such as $ecimal# he8a$ecimal# %inar"# or as a floating point or
character.
'tep E .eep pressing 6! until the program comes out of the for loop an$
e8ecutes the line that sen$s $ata to P/RTC. A this point# as shown in 6igure A.4L#
i @ an$ 'um @ AA.
'tep L Press 6! again to sen$ the value of varia%le 'um to P/RTC. As shown in
6igure A.4!# in this case P/RTC will have the $ecimal value AA# which is the sum of
num%ers from to 3.
This is the en$ of the simulation. 'elect from $rop&$own menu Run &U 'top
,e%ugger.
In the a%ove simulation e8ample# we single&steppe$ through the program to the en$
an$ then we coul$ see the final value of P/RTC. The ne8t e8ample shows how to set
%reakpoints in the program an$ then e8ecute up to a %reakpoint.
www. newnespress. co m
PIC! ,evelopment Tools
6igure A.44( 'tarting the $e%ugger
ss. co m
- Chapter A
6igure A.4A( 'electing varia%les to %e $ispla"e$
www. newnespress. co m
6igure A.4E( 'ingle&stepping through the program
6igure A.4L( 'ingle&stepping through the program
4 Chapter A
ss. co m
6igure A.4!( P/RTC has the value AA
E8ample A.3
,escri%e the steps involve$ in simulating the program $evelope$ in E8ample A..
'et a %reakpoint at the en$ of the program an$ run the $e%ugger up to this
%reakpoint. ,ispla" the values of various varia%les an$ P/RTC at this point.
Bhat is the final value $ispla"e$ on P/RTC[
'olution A.3
The steps are as follows(
'tep 'tart the mikroC I,E# making sure the program $evelope$ in E8ample A. is
$ispla"e$ in the Co$e E$itor win$ow.
'tep - 6rom the $rop&$own menu select ,e%ugger &U 'elect ,e%ugger &U
'oftware PIC 'imulator.
PIC! ,evelopment Tools A
www. newnespress. co m
'tep 3 6rom the $rop&$own menu select Run &U 'tart ,e%ugger.
'tep 4 'elect varia%les 'um# i# an$ P/RTC from the Batch win$ow as $escri%e$ in
E8ample A.-.
'tep A To set a %reakpoint at the en$ of the program# click the mouse at the last
closing %racket of the program# which is at line -L# an$ press 6A. As shown in
6igure A.4J# "ou shoul$ see a re$ line at the %reakpoint an$ a little marker in the
left column of the Co$e E$itor win$ow.
'tep E Gow# start the $e%ugger# an$ press 6E ke" to run the program. The program
will stop at the %reakpoint# $ispla"ing varia%les as shown in 6igure A.4!.
This is the en$ of the simulation. 'elect from $rop&$own menu Run &U 'top
,e%ugger.
To clear a %reakpoint# move the cursor over the line where the %reakpoint is an$ then
press 6A. To clear all %reakpoints in a program# press the 'HI6TDCTRLD6A ke"s.
To $ispla" the %reakpoints in a program# press the 'HI6TD64 ke"s.
The following are some other useful $e%ugger comman$s(
'tep Into P6LQ E8ecutes the current instruction an$ then halts. If the
instruction is a call to a routine# the program enters the routine an$ halts at
the first instruction.
6igure A.4J( 'etting a %reakpoint at line -L
E Chapter A
ss. co m
'tep /ver P6!Q E8ecutes the current instruction an$ then halts. If the
instruction is a call to a routine# it skips it an$ halts at the first instruction
following the call.
'tep /ut PCTRLD6!Q E8ecutes the current instruction an$ then halts. If the
instruction is within a routine# it e8ecutes the instruction an$ halts at the first
instruction following the call.
Run to Cursor P64Q E8ecutes all instructions %etween the current instruction
an$ the cursor position.
aump to Interrupt P6-Q aumps to the interrupt service routine a$$ress *a$$ress
383! for PIC! microcontrollers+ an$ e8ecutes the proce$ure locate$ at that
a$$ress.
A.3.4 0sing the mikroIC, In&Circuit ,e%ugger
This section $iscusses how to use the mikroIC, in&circuit $e%ugger *also calle$
the PIC6lash - programmer+ to $e%ug the program $evelope$ in E8ample A..
6irst of all# we have to %uil$ the har$ware an$ then connect the in&circuit $e%ugger
$evice. In this e8ample# the har$ware is %uilt on a %rea$%oar$# an$ a PIC6lash
- mikroIC, in&circuit $e%ugger is use$ to $e%ug the s"stem. Gote that pins R7E
an$ R7L are use$ %" the mikroIC, an$ are not availa%le for I9/ while mikroIC,
is active.
The Circuit ,iagram
The pro5ect2s circuit $iagram is shown in 6igure A.A3. The mikroIC, in&circuit
$e%ugger is connecte$ to the $evelopment circuit using the following pins of the
microcontroller(

)CLR

R7E

R7L

DAF

YG,
www. newnespress. co m
PIC! ,evelopment Tools L
6igure A.A3( Circuit $iagram of the pro5ect
The mikroIC, has two mo$es of operation. In inactive mo$e all lines from the
microcontroller use$ %" the $e%ugger $evice are connecte$ to the $evelopment
s"stem. In active mo$e the )CLR# R7E# an$ R7L pins are $isconnecte$ from
the $evelopment s"stem an$ use$ to program the microcontroller. After the
programming# these lines are restore$.
The mikroIC, $e%ugger $evice has a 3&wa" I,C connector an$ can %e connecte$ to
the target s"stem with a 3&wa" I,C hea$er. /nce the $evelopment is finishe$ an$ the
mikroIC, $e%ugger is remove$# opposite pairs of the I,C hea$er can %e connecte$
with 5umpers. 6igure A.A shows the s"stem %uilt on a %rea$%oar$.
,e%ugging
After %uil$ing the har$ware we are rea$" to program the microcontroller an$ test the
s"stem2s operation with the in&circuit $e%ugger. The steps are as follows(
'tep 'tart the mikroC I,E# making sure the program $evelope$ in E8ample A. is
$ispla"e$ in the Co$e E$itor win$ow.
ss. co m
! Chapter A
6igure A.A( '"stem %uilt on a %rea$%oar$
'tep - Click the E$it Pro5ect %utton *6igure A.A-+ an$ set ,E70YK/G as shown in
6igure A.A3.
E"i! ProKe!
)8!!on
6igure A.A-( E$it Pro5ect %utton
'tep 3 'elect IC, ,e%ug in the Pro5ect 'etup win$ow as shown in 6igure A.A4.
'tep 4 Click the 7uil$ Pro5ect icon to compile the program with the $e%ugger.
After a successful compilation "ou shoul$ see the message 'uccess *IC, 7uil$+ in
the )essage Bin$ow.
www. newnespress. co m
PIC! ,evelopment Tools J
6igure A.A3( 'et the ,E70YK/G
'tep A )ake sure the mikroIC, $e%ugger $evice is connecte$ as in 6igure A.A3#
an$ select Tools &U Pic6lash Programmer from the $rop&$own menu to program
the microcontroller.
'tep E 6rom the $rop&$own menu select ,e%ugger &U 'elect ,e%ugger &U
mikroIC, ,e%ugger as shown in 6igure A.AA.
ss. co m
-3 Chapter A
6igure A.A4( 'elect the IC, ,e%ug
6igure A.AA( 'electing the mikroIC, $e%ugger
'tep L 6rom the $rop&$own menu select Run &U 'tart ,e%ugger. The $e%ugger
form will pop up an$ select varia%les 'um# i# an$ P/RTC as $escri%e$ in
E8ample A.-.
'tep ! 'ingle&step through the program %" pressing the 6! ke". Tou shoul$
see the values of varia%les changing. At the en$ of the program# $ecimal value
AA will %e sent to P/RTC# an$ LE,s 3##-#4# an$ A shoul$ %e turne$ /G# as
shown in 6igure A.AE# correspon$ing to this num%er.
6igure A.AE( ,ecimal num%er AA shown in LE,s
www. newnespress. co m
PIC! ,evelopment Tools -
'tep J 'top the $e%ugger.
In routines that contain $ela"s# the 'tep Into P6LQ an$ 'tep /ver P6!Q
comman$s can take a long time. Run to Cursor P64Q an$ %reakpoints shoul$
%e use$ instea$.
A.3.A 0sing a ,evelopment 7oar$
It is eas" to $evelop microcontroller&%ase$ applications with the help of a $evelopment
%oar$. This section e8plains how to use the $evelopment %oar$ 7IYPIC4# $escri%e$
earlier in this chapter. The program written in E8ample A. is compile$ an$ then loa$e$
to the microcontroller using the on&%oar$ mikroIC, in&circuit emulator. Then the
program runs an$ $ispla"s the sum of the num%ers to 3 on the LE,s connecte$ to
P/RTC.
However# %efore using the $evelopment %oar$ we nee$ to know how the 7IYPIC4 is
organiHe$ an$ how to use the various $evices on the %oar$.
7IYPIC4 ,evelopment 7oar$
6igure A.AL shows the 7IYPIC4 $evelopment %oar$ with the functions of various
$evices i$entifie$ with arrows. The %oar$ can %e powere$ either from an e8ternal
power suppl" *!& to E&C AC9,C+ or from the 0'7 port of a computer# using a
5umper. In this application# the %oar$ is powere$ from a 0'7 port.
A -&row %" E&column LC, can %e connecte$ in the %oar$2s upper left corner. The
contrast of the LC, can %e a$5uste$ with a small potentiometer.
The fort"&si8 LE,s on the %oar$ can %e connecte$ to the output ports of the
microcontroller# selecte$ %" switch '-. 6igure A.A! shows how to select the LE,s#
using P/RTC as an e8ample. . resistors are use$ in series with the LE,s to limit
the current. 6or e8ample# to connect eight LE,s to P/RTC we have to set the
switch arm marke$ P/RTC of switch '- to the /G position.
The fort"&si8 push&%utton switches on the %oar$ can %e use$ to program $igital
inputs to the microcontroller. There is also a push&%utton switch that acts as the
RE'ET. aumper a- $etermines whether a %utton press will %ring logical 3 or
logical to the microcontroller. Bhen the %utton is not presse$# the pin state is
$etermine$ %" 5umper aA.
ss. co m
-- Chapter A
EG!ernal
Po%er
s8ppl+
>S#
miJroI*D
RS-M-
por!s
P*
Je+)oar"
L*D
Por!
onne!ors
Proessor
LEDs
*on!ras!
Rese!
P8shO)8!!on
s%i!hes
Graphis
L*D
MM*/SD
slo!
6igure A.AL( 7IYPIC4 $evelopment %oar$
6igure A.A!( LE, an$ push&%utton switch connections
At the %ottom central position# a -! E4 pi8el graphics LC, can %e connecte$
to the %oar$. The contrast of the LC, can %e a$5uste$ %" a small potentiometer.
The ))C9', car$ slot at the %ottom right&han$ corner of the %oar$ supports
car$s up to -Y7 storage capacit".
The RE'ET %utton is locate$ 5ust a%ove the ))C9', car$ slot.
A%ove the RE'ET %utton are two potentiometers for analog&to&$igital converter
applications.
All of the microcontroller port pins are availa%le at the connectors situate$ along
the right&han$ si$e of the %oar$. In the top mi$$le portion of the %oar$ are two
R'-3- ports an$ a connection to a PC ke"%oar$.
The %oar$ supports %oth E4&pin an$ !3&pin microcontrollers. The %oar$ comes with
a PIC!6!A-3 microcontroller connecte$ to the %oar$# operating with a 3)HH cr"stal.
6urther $etails a%out the operation of the %oar$ can %e foun$ in the 7IYPIC4
user2s manual.
The steps in $eveloping an application using the 7IYPIC4 %oar$ are as follows(
'tep ,ou%le&click the mikroC icon to start the I,E.
'tep - Create a new pro5ect calle$ EMA)PLE- *see 6igure A.AJ+ an$ select the
microcontroller t"pe as PIC!6!A-3# the clock as 3)HH# an$ $evice flags as(

K/'CKH'KH

KB,TK/66K-H

KLFPK/66K4L

K,E70YK/GK4L
6igure A.AJ( Creating a new pro5ect
'tep 3 Enter the following program into the Co$e E$itor section of the I,E(
9;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EMA)PLE PR/YRA)
This program uses the PIC7IY4 ,evelopment 7oar$. ! LE,s are connecte$
To P/RTC of the microcontroller which is a PIC!6!A-3 operating at 3)HH.
This program calculates the sum of integer num%ers from to 3
An$ then $ispla"s the sum on P/RTC of the microcontroller.
Author( ,ogan I%rahim
6ile( EMA)PLE-.C
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;9
voi$ main*+
=
unsigne$ int 'um#i?
TRI'C @ 3?
'um @ 3?
for*i@? iW@ 3? iDD+
=
'um @ 'um D i?
>
P/RTC @ 'um?
>
'tep 4 'ave the program with the name EMA)PLE- %" clicking 6ile &U 'ave As.
'tep A Tick option IC, ,e%ug in the Pro5ect 'etup win$ow. Compile the pro5ect %"
pressing CTRLD6J or %" clicking the 7uil$ Pro5ect %utton.
'tep E Connect the 7IYPIC4 $evelopment %oar$ to the 0'7 port on the computer.
Configure the $evelopment %oar$ %" routing eight LE,s to P/RTC( 'et the arm
marke$ P/RTC on switch '- to the /G position.
'tep L 'elect Tools &U Pic6lash Programmer from the $rop&$own menu to
program the microcontroller.
'tep ! 'elect ,e%ugger &U 'elect ,e%ugger &U mikroIC, ,e%ugger.
'tep J 'tart the $e%ugger %" clicking Run &U 'tart ,e%ugger an$ select varia%les
'um# i# an$ P/RTC from the Batch win$ow.
'tep 3 'ingle&step through the program until the en$ %" repeate$l" pressing 6!. At
the en$ of the program# the P/RTC LE,s will turn /G to $ispla" $ecimal AA *i.e.#
LE,s 3##-#4# an$ A will turn /G+.
'tep 'top the $e%ugger.
Fiew the EEPR/) Bin$ow The mikroIC, EEPR/) win$ow is invoke$ from the
mikroC I,E $rop&$own menu when the mikroIC, $e%ug mo$e is selecte$ an$
starte$# an$ it $ispla"s contents of the PIC internal EEPR/) memor". To view the
6igure A.E3( ,ispla" of EEPR/) memor"
memor"# click Fiew &U ,e%ug Bin$ows &U Fiew EEPR/). 6igure A.E3 shows an
e8ample EEPR/) win$ow $ispla".
Fiew the RA) Bin$ow The mikroIC, RA) win$ow is invoke$ from the mikroC
I,E $rop&$own menu when the mikroIC, $e%ug mo$e is selecte$ an$ starte$# an$ it
$ispla"s contents of the PIC internal RA) memor". To view the memor"# click Fiew
&U ,e%ug Bin$ows &U Fiew RA). 6igure A.E shows an e8ample RA) win$ow
$ispla".
Fiew the Co$e Bin$ow The mikroIC, Co$e win$ow is invoke$ from the
mikroC I,E $rop&$own menu when the mikroIC, $e%ug mo$e is selecte$ an$
starte$# an$ it $ispla"s the contents of the PIC internal co$e memor". To view
6igure A.E( ,ispla" of RA) memor"
the memor"# click Fiew &U ,e%ug Bin$ows &U Fiew Co$e. 6igure A.E- shows
an e8ample Co$e win$ow $ispla".
Fiew the 'tatistics The 'tatistics win$ow is invoke$ from the mikroC I,E $rop&
$own menu an$ it $ispla"s various statistical $ata a%out our program. To view the
statistics win$ow# click Fiew &U Fiew 'tatistics. 6igure A.E3 shows an e8ample
'tatistics win$ow# which consists of several ta%s. The )emor" 0sage ta% $ispla"s
the amount of RA) *$ata memor"+ an$ R/) *co$e memor"+ use$. The Proce$ures
ta%s $ispla" information a%out the siHe an$ locations of the proce$ures. The RA)
an$ R/) ta%s $ispla" memor" usage in $etail.
ss. co m
6igure A.E-( ,ispla" of Co$e memor"
6igure A.E3( ,ispla" of 'tatistics win$ow
PIC! ,evelopment Tools -J
www. newnespress. co m
A.4 'ummar"
This chapter has $escri%e$ the PIC microcontroller software $evelopment tools *such as
te8t e$itors# assem%lers# compilers# an$ simulators+ an$ har$ware $evelopment tools
*inclu$ing $evelopment %oar$s an$ kits# programming $evices# in&circuit $e%uggers#
an$ in&circuit emulators+. The mikroC compiler was use$ in the e8amples an$ pro5ects.
The steps in $eveloping an$ testing a mikroC&%ase$ C program were presente$ %oth
with an$ without a har$ware in&circuit $e%ugger# followe$ %" an e8ample of how to
use the 7IYPIC4 $evelopment %oar$# with the on&%oar$ in&circuit $e%ugger ena%le$.
A.A E8ercises
. ,escri%e the phases of the microcontroller&%ase$ s"stem $evelopment c"cle.
-. ,escri%e %riefl" the microcontroller $evelopment tools.
3. E8plain the a$vantages an$ $isa$vantages of assem%lers an$ compilers.
4. E8plain wh" a simulator can %e a useful tool while $eveloping a microcontroller&
%ase$ pro$uct.
A. E8plain in $etail what a $evice programmer is. Yive some e8amples of $evice
programmers for the PIC! series of microcontrollers.
E. ,escri%e %riefl" the $ifferences %etween in&circuit $e%uggers an$ in&circuit
emulators. List the a$vantages an$ $isa$vantages of %oth $e%ugging tools.
L. Enter the following program into the mikroC I,E an$ compile the program#
correcting an" s"nta8 errors. Then# using the software IC,# simulate the operation
of the program %" single&stepping through the co$e# an$ o%serve the values of the
varia%les $uring the simulation.
9;@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
A 'I)PLE LE, PR/aECT
This program flashes the ! LE,s connecte$ to P/RTC of a PIC!64A-
microcontroller.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@;9
voi$ main*+
=
TRI'C @ 3? 99 P/RTC is output
ss. co m
33 Chapter A
$o
=
P/RTC @ 3866? 99 Turn /G LE,s on P/RTC
P/RTC @ 3? 99 Turn /66 LE,s on P/RTC
> while*+? 99 En$less loop
>
!. ,escri%e the steps in using the mikroIC, in&circuit $e%ugger.
J. The following C program contains some $eli%eratel" intro$uce$ errors. Compile
the program to fin$ an$ correct the errors.
voi$ main*+
=
unsigne$ char i#5#k
i @ 3?
5 @ i D ?
for*i @ 3? i W 3? iDD+
=
'um @ 'um D i?
5DD
>
>
>
3. The following C program contains some $eli%eratel" intro$uce$ errors. Compile
the program to fin$ an$ correct the errors.
int a$$*int a# int %+
=
result @ a D %
>
voi$ main*+
=
int p#C?
p @ -?
C @ 3?
H @ a$$*p# C+
HDD?
for*i @ 3? i W H? iDD+pDD
>
>
www. newnespress. co m
CHAP T E R E
'imple PIC! Pro5ects
In this chapter we will look at the $esign of simple PIC! microcontroller&%ase$
pro5ects# with the i$ea of %ecoming familiar with %asic interfacing techniCues an$
learning how to use the various microcontroller peripheral registers. Be will look
at the $esign of pro5ects using LE,s# push&%utton switches# ke"%oar$s# LE, arra"s#
soun$ $evices# an$ so on# an$ we will $evelop programs in C language using the
mikroC compiler. The har$ware is $esigne$ on a low&cost %rea$%oar$# %ut $evelopment
kits such as 7IYPIC4 can %e use$ for these pro5ects. Be will start with ver" simple
pro5ects an$ procee$ to more comple8 ones. It is recommen$e$ that the rea$er
moves through the pro5ects in their given or$er. The following are provi$e$ for
each pro5ect(

,escription of the program

,escription of the har$ware

Circuit $iagram

Algorithm $escription *in P,L+

Program listing

'uggestions for further $evelopment
The program2s algorithm can %e $escri%e$ in a variet" of graphic an$ te8t&%ase$
metho$s# some of the common ones %eing a flow $iagram# a structure chart# an$
program $escription language. In this %ook we are using program $escription
language *P,L+.
3- Chapter E
ss. co m
E. Program ,escription Language *P,L+
Program $escription language *P,L+ is free&format English&like te8t which $escri%es
the flow of control in a program. P,L is not a programming language %ut rather is
a tool which helps the programmer to think a%out the logic of the program %efore
the program has %een $evelope$. Commonl" use$ P,L ke"wor$s are $escri%e$
as follows.
E.. 'TART&EG,
Ever" P,L program $escription *or su%program+ shoul$ %egin with a 'TART
ke"wor$ an$ terminate with an EG, ke"wor$. The ke"wor$s in a P,L co$e shoul$
%e highlighte$ in %ol$ to make the co$e more clear. It is also a goo$ practice to
in$ent program statements %etween P,L ke"wor$s in or$er to enhance the
rea$a%ilit" of the co$e.
E8ample(
'TART
. . . . . .
. . . . . .
EG,
E..- 'eCuencing
6or normal seCuencing in a program# write the statements as short English te8t as if "ou
are $escri%ing the program.
E8ample(
Turn on the LE,
Bait secon$
Turn off the
LE,
E..3 I6&THEG&EL'E&EG,I6
0se I6# THEG# EL'E# an$ EG,I6 ke"wor$s to $escri%e the flow of control in a
program.
www. newnespress. co m
'imple PIC! Pro5ects 33
E8ample(
I6 switch @ THEG
Turn on LE,
EL'E
Turn on LE, -
'tart the motor
EG,I6
E..4 ,/&EG,,/
0se ,o an$ EG,,/ ke"wor$s to show iteration in the P,L co$e.
E8ample(
To create an uncon$itional loop in a program we can write(
Turn on LE,
,/ 3 times
'et clock to
Bait for 3ms
'et clock to 3
EG,,/
A variation of the ,/&EG,,/ construct is to use other ke"wor$s like ,/&6/REFER#
,/&0GTIL# etc. as shown in the following e8amples.
E8ample(
To create a con$itional loop in a program we can write(
Turn off %uHHer
I6 switch @ THEG
,/ 0GTIL Port @
Turn on LE,
Bait for 3ms
Rea$ Port
EG,,/
EG,I6
ss. co m
34 Chapter E
The following construct can %e use$ when an en$less loop is reCuire$(
,/ 6/REFER
Rea$ $ata from Port
'en$ $ata to P/RT -
Bait for secon$
EG,,/
E..A REPEAT&0GTIL
REPEAT&0GTIL is another control construct use$ in P,L co$es. In the following
e8ample the program waits until a switch value is eCual to .
E8ample(
REPEAT
Turn on %uHHer
Rea$ switch value
0GTIL switch @
Gotice that the REPEAT&0GTIL loop is alwa"s e8ecute$ at least once# an$ more than
once if the con$ition at the en$ of the loop is not met.
PR/aECT E.cChasing LE,s
Pro5ect ,escription
In this pro5ect eight LE,s are connecte$ to P/RTC of a PIC!64A-&t"pe
microcontroller# an$ the microcontroller is operate$ from a 4)HH resonator. Bhen
power is applie$ to the microcontroller *or when the microcontroller is reset+# the LE,s
turn /G alternatel" in an anticlockwise manner where onl" one LE, is /G at an" time.
There is a one&secon$ $ela" %etween outputs so the LE,s can %e seen turning /G an$
/66.
An LE, can %e connecte$ to a microcontroller output port in two $ifferent mo$es(
current sinking an$ current sourcing.
Current 'inking )o$e
As shown in 6igure E.# in current sinking mo$e the ano$e leg of the LE, is connecte$
to the DAF suppl"# an$ the catho$e leg is connecte$ to the microcontroller output port
through a current limiting resistor.
www. newnespress. co m
'imple PIC! Pro5ects 3A
6igure E.( LE, connecte$ in current sinking mo$e
The voltage $rop across an LE, varies %etween .4F an$ -.AF# with a t"pical
value of -F. The %rightness of the LE, $epen$s on the current through the LE,#
an$ this current can var" %etween ! an$ EmA# with a t"pical value of 3mA.
The LE, is turne$ /G when the output of the microcontroller is at logic 3 so the
current flows through the LE,. Assuming the microcontroller output voltage is a%out
3.4F when the output is low# we can calculate the value of the reCuire$ resistor as
follows(
R
F
'
F
LE,
F
L
@
I
LE,
\E(]
where
F
'
is the suppl" voltage *AF+
F
LE,
is the voltage $rop across the LE, *-F+
F
L
is the ma8imum output voltage when the output port is low *3.4F+
I
LE,
is the current through the LE, *3mA+
'u%stituting the values into ECuation *E.+ we get#
A - 3(4
R @
3
@ -E3 ohm
The nearest ph"sical resistor is -L3 ohms.
Current 'ourcing )o$e
As shown in 6igure E.-# in current sourcing mo$e the ano$e leg of the LE, is
connecte$ to the microcontroller output port an$ the catho$e leg is connecte$ to the
groun$ through a current limiting resistor.
6igure E.-( LE, connecte$ in current sourcing mo$e
In this mo$e the LE, is turne$ /G when the microcontroller output port is at logic
*i.e.# DAF+. In practice# the output voltage is a%out 4.!AF an$ the value of the resistor
can %e $etermine$ as(
R
F
/
F
LE,
@
I
LE,
\E(-]
where
F
/
is the output voltage of the microcontroller port when at logic *D4.!AF+.
Thus# the value of the reCuire$ resistor is(
4(!A -
R @
3
@ -!A ohm
The nearest ph"sical resistor is -J3 ohm.
Pro5ect Har$ware
The circuit $iagram of the pro5ect is shown in 6igure E.3. LE,s are connecte$ to
P/RTC in current sourcing mo$e with eight -J3&ohm resistors. A 4)HH resonator is
connecte$ %etween the /'C an$ /'C- pins. Also# an e8ternal reset push %utton is
connecte$ to the )CLR input to reset the microcontroller when reCuire$.
6igure E.3( Circuit $iagram of the pro5ect
Pro5ect P,L
The P,L of this pro5ect is ver" simple an$ is given in 6igure E.4.
START
*onfig8re PORT* pins as o8!p8!
Ini!ialise V 7 /
DO FORE=ER
Se! PORT* 7 V
Shif! lef! V )+ / "igi!
IF V 7 $ THEN
V 7 /
END
ENDDO
ENDIF
:ai! / seon"
6igure E.4( P,L of the pro5ect
Pro5ect Program
The program is name$ as LE,.C# an$ the program listing is given in 6igure E.A. At the
%eginning of the program P/RTC pins are configure$ as outputs %" setting TRI'C @ 3.
Then an en$less for loop is forme$# an$ the LE,s are turne$ /G alternatel" in an
anticlockwise manner to create a chasing effect. The program checks continuousl" so
that when LE, L is turne$ /G# the ne8t LE, to %e turne$ /G is LE, 3.
This program can %e compile$ using the mikroC compiler. Pro5ect settings shoul$
%e configure$ to 4)HH clock# MT cr"stal mo$e# an$ B,T /66. The HEM file
*LE,.HEM+ shoul$ %e loa$e$ to the PIC!64A- microcontroller using either an
in&circuit $e%ugger or a programming $evice.
/*************************************************************************************************
*HASING LEDS
777777777777
In !his proKe! 0 LEDs are onne!e" !o PORT* of a PI*/0F12- miroon!roller
an" !he miroon!roller is opera!e" from a 1MHE resona!or' The program !8rns on
!he LEDs in an an!iOloJ%ise manner %i!h one seon" "ela+ )e!%een eah o8!p8!'
The ne! res8l! is !ha! !he LEDs seem !o )e hasing eah o!her'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( LED/'*
***************************************************************************************************/
&oi" main34
5
8nsigne" har V 7 /6
TRIS* 7 $6
for3664 // En"less loop
5
PORT* 7 V6 // Sen" V !o PORT*
Dela+9ms3/$$$46 // Dela+ / seon"
V 7 V DD /6 // Shif! lef! V
if3V 77 $4 V 7 /6 // If las! LED, mo&e !o firs! LED
;
;
6igure E.A( Program listing
6urther ,evelopment
The pro5ect can %e mo$ifie$ such that the LE,s chase each other in %oth $irections. 6or
e8ample# if the LE,s are moving in an anticlockwise $irection# the $irection can %e
change$ so that when LE, R7L is /G the ne8t LE, to turn /G is R7E# when R7E is
/G the ne8t is R7A# an$ so on.
PR/aECT E.-cLE, ,ice
Pro5ect ,escription
This is a simple $ice pro5ect %ase$ on LE,s# a push&%utton switch# an$ a PIC!64A-
microcontroller operating with a 4)HH resonator. The %lock $iagram of the pro5ect is
shown in 6igure E.E.
s%i!h
PI*/0F12-
DI*E
6igure E.E( 7lock $iagram of the pro5ect
As shown in 6igure E.L# the LE,s are organiHe$ such that when the" turn /G# the"
in$icate num%ers as on a real $ice. /peration of the pro5ect is as follows( The LE,s are
all /66 to in$icate that the s"stem is rea$" to generate a new num%er. Pressing the
switch generates a ran$om num%er %etween an$ E which is $ispla"e$ on the LE,s for
3 secon$s. After 3 secon$s the LE,s turn /66 again.
/ - M 1 2 N
6igure E.L( LE, $ice
Pro5ect Har$ware
The circuit $iagram of the pro5ect is shown in 6igure E.!. 'even LE,s representing the
faces of a $ice are connecte$ to P/RTC of a PIC!64A- microcontroller in current
sourcing mo$e using -J3&ohm current limiting resistors. A push&%utton switch is
connecte$ to %it 3 of P/RT7 *R73+ using a pull&up resistor. The microcontroller is
operate$ from a 4)HH resonator connecte$ %etween pins /'C an$ /'C-. The
microcontroller is powere$ from a DJF %atter"# an$ a L!L3A&t"pe voltage regulator IC
is use$ to o%tain the DAF suppl" reCuire$ for the microcontroller.
6igure E.!( Circuit $iagram of the pro5ect
Pro5ect P,L
The operation of the pro5ect is $escri%e$ in P,L in 6igure E.J. At the %eginning of the
program P/RTC pins are configure$ as outputs an$ %it 3 of P/RT7 *R73+ is
configure$ as input. The program then e8ecutes in a loop continuousl" an$ increments a
varia%le %etween an$ E. The state of the push&%utton switch is checke$ an$ when the
switch
is presse$ *switch output at logic 3+# the current num%er is sent to the LE,s. A simple
arra" is use$ to fin$ out the LE,s to %e turne$ /G correspon$ing to the $ice num%er.
START
*rea!e DI*E !a)le
*onfig8re PORT* as o8!p8!s
*onfig8re R#$ as inp8!
Se! V 7 /
DO FORE=ER
IF )8!!on presse" THEN
Ge! LED pa!!ern from DI*E !a)le
T8rn ON reZ8ire" LEDs
:ai! M seon"s
Se! V 7 $
T8rn OFF all LEDs
ENDIF
Inremen! V
IF V 7 . THEN
Se! V 7 /
END
ENDDO
ENDIF
6igure E.J( P,L of the pro5ect
Ta%le E. gives the relationship %etween a $ice num%er an$ the correspon$ing LE,s to
%e turne$ /G to imitate the faces of a real $ice. 6or e8ample# to $ispla" num%er *i.e.#
onl" the mi$$le LE, is /G+# we have to turn on ,4. 'imilarl"# to $ispla" num%er 4# the
LE,s to turn /G are ,# ,3# ,A# an$ ,L.
Ta%le E.( ,ice num%er an$ LE,s to %e turne$ /G
ReCuire$ num%er LE,s to %e turne$ on
,4
- ,-# ,E
3 ,-# ,4# ,E
4 ,# ,3# ,A# ,L
A ,# ,3# ,4# ,A# ,L
E ,# ,-# ,3# ,A# ,E# ,L
The relationship %etween the reCuire$ num%er an$ the $ata to %e sent to P/RTC to turn
on the correct LE,s is given in Ta%le E.-. 6or e8ample# to $ispla" $ice num%er -# we
have to sen$ he8a$ecimal 3 -- to P/RTC. 'imilarl"# to $ispla" num%er A# we have to
sen$ he8a$ecimal 3 A, to P/RTC# an$ so on.
Ta%le E.-( ReCuire$ num%er an$ P/RTC $ata
ReCuire$ num%er P/RT7 $ata *He8+
3 3!
- 3 --
3 3 -A
4 3 AA
A 3 A,
E 3 LL
Pro5ect Program
The program is calle$ LE,-.C# an$ the program listing is given in 6igure E.3. At the
%eginning of the program 'witch is $efine$ as %it 3 of P/RT7# an$ Presse$ is $efine$
as 3. The relationships %etween the $ice num%ers an$ the LE,s to %e turne$ on are
store$ in an arra" calle$ ,ICE. Faria%le a is use$ as the $ice num%er. Faria%le Pattern
is the $ata sent to the LE,s. Program then enters an en$less for loop where the value of
varia%le a is incremente$ ver" fast %etween an$ E. Bhen the push&%utton switch is
presse$# the LE, pattern correspon$ing to the current value of a is rea$ from the arra"
an$ sent to the LE,s. The LE,s remain in this state for 3 secon$s *using function
,ela"Kms with the argument set to 3333ms+# after which the" all turn /66. The s"stem
is then rea$" to generate a new $ice num%er.
0sing a Pseu$oran$om Gum%er Yenerator
In the prece$ing pro5ect the value of varia%le a changes ver" fast among the num%ers
%etween an$ E# so we can sa" that the num%ers generate$ are ran$om *i.e.# new
num%ers $o not $epen$ on the previous num%ers+.
A pseu$oran$om num%er generator function can also %e use$ to generate the $ice
num%ers. The mo$ifie$ program listing is shown in 6igure E.. In this program a
function calle$ Gum%er generates the $ice num%ers. The function receives the upper
limit of the num%ers to %e generate$ *E in this e8ample+ an$ also a see$ value which
/************************************************************************************************
SIMPLE DI*E
77777777777
In !his proKe! . LEDs are onne!e" !o PORT* of a PI*/0F12- miroon!roller
an" !he miroon!roller is opera!e" from a 1MHE resona!or' The LEDs are organiEe"
as !he faes of a real "ie' :hen a p8shO)8!!on s%i!h onne!e" !o R#$ is presse"
a "ie pa!!ern is "ispla+e" on !he LEDs' The "ispla+ remains in !his s!a!e for M
seon"s an" af!er !his perio" !he LEDs all !8rn OFF !o in"ia!e !ha! !he s+s!em is
rea"+ for !he )8!!on !o )e presse" again'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( LED-'*
*************************************************************************************************/
P"efine S%i!h PORT#'F$
P"efine Presse" $
&oi" main34
5
8nsigne" har V 7 /6
8nsigne" har Pa!!ern6
8nsigne" har DI*EHI 7 5$,$G$0,$G--,$G-A,$G22,$G2D,$G..;6
TRIS* 7 $6 // PORT* o8!p8!s
TRIS# 7 /6 // R#$ inp8!
PORT* 7 $6 // T8rn OFF all LEDs
for3664 // En"less loop
5
if3S%i!h 77 Presse"4 // Is s%i!h presse" [
5
Pa!!ern 7 DI*EHVI6 // Ge! LED pa!!ern
PORT* 7 Pa!!ern6 // T8rn on LEDs
Dela+9ms3M$$$46 // Dela+ M seon"
PORT* 7 $6 // T8rn OFF all LEDs
V 7 $6 // Ini!ialise V
;
VLL6 // Inremen! V
if3V 77 .4 V 7 /6 // #aJ !o / if @ N
;
;
6igure E.3( Program listing
/******************************************************************************************
SIMPLE DI*E
77777777777
In !his proKe! . LEDs are onne!e" !o PORT* of a PI*/0F12- miroon!roller
an" !he miroon!roller is opera!e" from a 1MHE resona!or' The LEDs are organiEe"
as !he faes of a real "ie' :hen a p8shO)8!!on s%i!h onne!e" !o R#$ is presse" a
"ie pa!!ern is "ispla+e" on !he LEDs' The "ispla+ remains in !his s!a!e for M seon"s
an" af!er !his perio" !he LEDs all !8rn OFF !o in"ia!e !ha! !he s+s!em is rea"+ for !he
)8!!on !o )e presse" again'
In !his program a pse8"oran"om n8m)er genera!or f8n!ion is
8se" !o genera!e !he "ie n8m)ers )e!%een / an" N'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( LEDM'*
*******************************************************************************************/
P"efine S%i!h PORT#'F$
P"efine Presse" $
//
// This f8n!ion genera!es a pse8"o ran"om in!eger n8m)er
// )e!%een / an" Lim
//
8nsigne" har N8m)er3in! Lim, in! ?4
5
8nsigne" har Res8l!6
s!a!i 8nsigne" in! ?6
? 7 3? * M-./T L M4 \ M-.1T6
Res8l! 7 33? \ Lim4 L /46
re!8rn Res8l!6
;
//
// S!ar! of MAIN program
//
&oi" main34
5
8nsigne" har V,Pa!!ern,See" 7 /6
8nsigne" har DI*EHI 7 5$,$G$0,$G--,$G-A,$G22,$G2D,$G..;6
TRIS* 7 $6 // PORT* o8!p8!s
TRIS# 7 /6 // R#$ inp8!
PORT* 7 $6 // T8rn OFF all LEDs
for3664 // En"less loop
6igure E.( ,ice program using a pseu$oran$om num%er generator
5
if3S%i!h 77 Presse"4 // Is s%i!h presse" [
5
V 7 N8m)er3N,see"46 // Genera!e a n8m)er )e!%een / an" N
Pa!!ern 7 DI*EHVI6 // Ge! LED pa!!ern
PORT* 7 Pa!!ern6 // T8rn on LEDs
Dela+9ms3M$$$46 // Dela+ M seon"
PORT* 7 $6 // T8rn OFF all LEDs
;
;
;
6igure E.( *Cont2$+
$efines the num%er set to %e generate$. In this e8ample# the see$ is set to . Ever" time
the function is calle$# a num%er %etween an$ E is generate$.
The operation of the program is %asicall" same as in 6igure E.3. Bhen the push&%utton
switch is presse$# function Gum%er is calle$ to generate a new $ice num%er %etween
an$ E# an$ this num%er is use$ as an in$e8 in arra" ,ICE in or$er to fin$ the %it
pattern to %e sent to the LE,s.
PR/aECT E.3cTwo&,ice Pro5ect
Pro5ect ,escription
This pro5ect is similar to Pro5ect -# %ut here a pair of $ice are use$cas in man" $ice
games such as %ackgammonc instea$ of a single $ice.
The circuit shown in 6igure E.! can %e mo$ifie$ %" a$$ing another set of seven LE,s
for the secon$ $ice. 6or e8ample# the first set of LE,s can %e $riven from P/RTC# the
secon$ set from P/RT,# an$ the push&%utton switch can %e connecte$ to R73 as
%efore. 'uch a $esign reCuires fourteen output ports 5ust for the LE,s. Later on we will
see how the LE,s can %e com%ine$ in or$er to re$uce the input9output reCuirements.
6igure E.- shows the %lock $iagram of the pro5ect.
Pro5ect Har$ware
The circuit $iagram of the pro5ect is shown in 6igure E.3. The circuit is %asicall"
same as in 6igure E.!# with the a$$ition of another set of LE,s connecte$
to P/RT,.
s%i!h
PI*/0F12-
DI*E
6igure E.-( 7lock $iagram of the pro5ect
Pro5ect P,L
6igure E.3( Circuit $iagram of the pro5ect
The operation of the pro5ect is ver" similar to that for Pro5ect -. 6igure E.4 shows the
P,L for this pro5ect. At the %eginning of the program the P/RTC an$ P/RT, pins
are configure$ as outputs# an$ %it 3 of P/RT7 *R73+ is configure$ as input. The
program then e8ecutes in a loop continuousl" an$ checks the state of the push&%utton
switch. Bhen the switch is presse$# two pseu$oran$om num%ers %etween an$ E are
START
*rea!e DI*E !a)le
*onfig8re PORT* as o8!p8!s
*onfig8re PORTD as o8!p8!s
*onfig8re R#$ as inp8!
DO FORE=ER
IF )8!!on presse" THEN
Ge! a ran"om n8m)er )e!%een / an" N
Fin" )i! pa!!ern
T8rn ON LEDs on PORT*
Ge! seon" ran"om n8m)er )e!%een / an" N
Fin" )i! pa!!ern
T8rn on LEDs on PORTD
:ai! M seon"s
T8rn OFF all LEDs
END
ENDDO
ENDIF
6igure E.4( P,L of the pro5ect
generate$# an$ these num%ers are sent to P/RTC an$ P/RT,. The LE,s remain at
this state for 3 secon$s# after which all the LE,s are turne$ /66 to in$icate that the
push&%utton switch can %e presse$ again for the ne8t pair of num%ers.
Pro5ect Program
The program is calle$ LE,4.C# an$ the program listing is given in 6igure E.A. At the
%eginning of the program 'witch is $efine$ as %it 3 of P/RT7# an$ Presse$ is $efine$
as 3. The relationships %etween the $ice num%ers an$ the LE,s to %e turne$ on are
store$ in an arra" calle$ ,ICE# as in Pro5ect -. Faria%le Pattern is the $ata sent to the
LE,s. Program enters an en$less for loop where the state of the push&%utton switch is
checke$ continuousl". Bhen the switch is presse$# two ran$om num%ers
are generate$ %" calling function Gum%er. The %it patterns to %e sent to the LE,s
are then $etermine$ an$ sent to P/RTC an$ P/RT,. The program then repeats
insi$e the en$less loop# checking the state of the push&%utton switch.
PR/aECT E.4cTwo&,ice Pro5ect 0sing 6ewer I9/ Pins
Pro5ect ,escription
This pro5ect is similar to Pro5ect 3# %ut here LE,s are share$# which uses fewer input9
output pins.
/
T:O DI*E
77777777
In !his proKe! . LEDs are onne!e" !o PORT* of a PI*/0F12- miroon!roller an"
. LEDs !o PORTD' The miroon!roller is opera!e" from a 1MHE resona!or'
The LEDs are organiEe" as !he faes of a real "ie' :hen a p8shO)8!!on s%i!h
onne!e" !o R#$ is presse" a "ie pa!!ern is "ispla+e" on !he LEDs' The
"ispla+ remains in !his s!a!e for M seon"s an" af!er !his perio" !he LEDs all !8rn
OFF !o in"ia!e !ha! !he s+s!em is rea"+ for !he )8!!on !o )e presse" again'
In !his program a pse8"oran"om n8m)er genera!or f8n!ion is
8se" !o genera!e !he "ie n8m)ers )e!%een / an" N'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( LED1'*
/
P"efine S%i!h PORT#'F$
P"efine Presse" $
//
// This f8n!ion genera!es a pse8"o ran"om in!eger n8m)er
// )e!%een / an" Lim
//
8nsigne" har N8m)er3in! Lim, in! ?4
5
8nsigne" har Res8l!6
s!a!i 8nsigne" in! ?6
? 7 3? * M-./T L M4 \ M-.1T6
Res8l! 7 33? \ Lim4 L /46
re!8rn Res8l!6
;
//
// S!ar! of MAIN program
//
&oi" main34
5
8nsigne" har V,Pa!!ern,See" 7 /6
8nsigne" har DI*EHI 7 5$,$G$0,$G--,$G-A,$G22,$G2D,$G..;6
TRIS* 7 $6 // PORT* are o8!p8!s
TRISD 7 $6 // PORTD are o8!p8!s
TRIS# 7 /6 // R#$ inp8!
PORT* 7 $6 // T8rn OFF all LEDs
PORTD 7 $6 // T8rn OFF all LEDs
6igure E.A( Program listing
for3664 // En"less loop
5
if3S%i!h 77 Presse"4 // Is s%i!h presse" [
5
V 7 N8m)er3N,see"46 // Genera!e firs! "ie n8m)er
Pa!!ern 7 DI*EHVI6 // Ge! LED pa!!ern
PORT* 7 Pa!!ern6 // T8rn on LEDs for firs! "ie
V 7 N8m)er3N,see"46 // Genera!e seon" "ie n8m)er
Pa!!ern 7 DI*EHVI6 // Ge! LED pa!!ern
PORTD 7 Pa!!ern6 // T8rn on LEDs for seon" "ie
Dela+9ms3M$$$46 // Dela+ M seon"s
PORT* 7 $6 // T8rn OFF all LEDs
PORTD 7 $6 // T8rn OFF all LEDS
;
;
;
6igure E.A( *Cont2$+
The LE,s in Ta%le E. can %e groupe$ as shown in Ta%le E.3. Looking at this ta%le we
can sa" that(

,4 can appear on its own

,- an$ ,E are alwa"s together

, an$ ,3 are alwa"s together

,A an$ ,L are alwa"s together
Thus# we can $rive ,4 on its own an$ then $rive the ,-#,E pair together in series# the
,#,3 pair together in series# an$ also the ,A#,L pair together in series. *Actuall"# we
Ta%le E.3( Yrouping the LE,s
ReCuire$ num%er LE,s to %e turne$ on
,4
- ,- ,E
3 ,- ,E ,4
4 , ,3 ,A ,L
A , ,3 ,A ,L ,4
E ,- ,E , ,3 ,A ,L
coul$ share ,#,3#,A#,L %ut this woul$ reCuire ! volts to $rive if the LE,s are
connecte$ in series. Connecting them in parallel woul$ call for even more current# an$ a
$river IC woul$ %e reCuire$.+ Altogether# four lines are nee$e$ to $rive the seven LE,s
of each $ice. Thus# a pair of $ice can easil" %e $riven from an !&%it output port.
Pro5ect Har$ware
The circuit $iagram of the pro5ect is shown in 6igure E.E. P/RTC of a PIC!64A-
microcontroller is use$ to $rive the LE,s as follows(

RC3 $rives ,-#,E of the first $ice

RC $rives ,#,3 of the first $ice

RC- $rives ,A#,L of the first $ice

RC3 $rives ,4 of the first $ice

RC4 $rives ,-#,E of the secon$ $ice
6igure E.E( Circuit $iagram of the pro5ect

RCA $rives ,#,3 of the secon$ $ice

RCE $rives ,A#,L of the secon$ $ice

RCL $rives ,4 of the secon$ $ice
'ince two LE,s are %eing $riven on some outputs# we can calculate the reCuire$ value
of the current limiting resistors. Assuming that the voltage $rop across each LE,
is -F# the current through the LE, is 3mA# an$ the output high voltage of the
microcontroller is 4.!AF# the reCuire$ resistors are(
4(!A - -
R @
3
@ !A ohms
Be will choose 33&ohm resistors.
Be now nee$ to fin$ the relationship %etween the $ice num%ers an$ the %it pattern to %e
sent to the LE,s for each $ice. Ta%le E.4 shows the relationship %etween the first
$ice num%ers an$ the %it pattern to %e sent to port pins RC3&RC3. 'imilarl"# Ta%le E.A
shows the relationship %etween the secon$ $ice num%ers an$ the %it pattern to %e
sent to port pins RC4&RCL.
Ta%le E.4( 6irst $ice %it patterns
,ice num%er RC3 RC- RC RC3 He8 value
3 3 3 !
- 3 3 3
3 3 3 J
4 3 3 E
A 3 E
E 3 L
Be can now fin$ the !&%it num%er to %e sent to P/RTC to $ispla" %oth $ice num%ers as
follows(

Yet the first num%er from the num%er generator# call this P

In$e8 the ,ICE ta%le to fin$ the %it pattern for low ni%%le *i.e.# L @ ,ICEPPQ+

Yet the secon$ num%er from the num%er generator# call this P
Ta%le E.A( 'econ$ $ice %it patterns
,ice num%er RCL RCE RCA RC4 He8 value
3 3 3 !
- 3 3 3
3 3 3 J
4 3 3 E
A 3 E
E 3 L

In$e8 the ,ICE ta%le to fin$ the %it pattern for high ni%%le *i.e.# 0 @ ,ICEPPQ+

)ultipl" high ni%%le %" E an$ a$$ low ni%%le to fin$ the num%er to %e sent
to P/RTC *i.e.# R @ E;0 D L+# where R is the !&%it num%er to %e sent to
P/RTC to $ispla" %oth $ice values.
Pro5ect P,L
The operation of this pro5ect is ver" similar to that of Pro5ect -. 6igure E.L shows
the P,L of the pro5ect. At the %eginning of the program the P/RTC pins are
START
*rea!e DI*E !a)le
*onfig8re PORT* as o8!p8!s
*onfig8re R#$ as inp8!
DO FORE=ER
IF )8!!on presse" THEN
Ge! a ran"om n8m)er )e!%een / an" N
Fin" lo% ni))le )i! pa!!ern
Ge! seon" ran"om n8m)er )e!%een / an" N
High high ni))le )i! pa!!ern
*al8la!e "a!a !o )e sen! !o PORT*
:ai! M seon"s
T8rn OFF all LEDs
END
ENDIF
ENDDO
6igure E.L( P,L of the pro5ect
configure$ as outputs# an$ %it 3 of P/RT7 *R73+ is configure$ as input. The program
then e8ecutes in a loop continuousl" an$ checks the state of the push&%utton switch.
Bhen the switch is presse$# two pseu$oran$om num%ers %etween an$ E are generate$#
an$ the %it pattern to %e sent to P/RTC is foun$ %" the metho$ 5ust $escri%e$. This %it
pattern is then sent to P/RTC to $ispla" %oth $ice num%ers at the same time. The
$ispla" shows the $ice num%ers for 3 secon$s# an$ then all the LE,s turn /66 to
in$icate that the s"stem is waiting for the push&%utton to %e presse$ again to $ispla"
the ne8t set of num%ers.
Pro5ect Program
The program is calle$ LE,A.C# an$ the program listing is given in 6igure E.!.
At the %eginning of the program 'witch is $efine$ as %it 3 of P/RT7# an$ Presse$
is $efine$ as 3. The relationships %etween the $ice num%ers an$ the LE,s to %e
turne$ on are store$ in an arra" calle$ ,ICE as in Pro5ect -. Faria%le Pattern is the
$ata sent to the LE,s. The program enters an en$less for loop where the state of
the push&%utton switch is checke$ continuousl". Bhen the switch is presse$# two
ran$om num%ers are generate$ %" calling function Gum%er. Faria%les L an$ 0 store
the lower an$ higher ni%%les of the %it pattern to %e sent to P/RTC. The %it pattern
to %e sent to P/RTC is then $etermine$ using the metho$ $escri%e$ in the
Pro5ect Har$ware section an$ store$ in varia%le R. This %it pattern is then sent to
P/RTC to $ispla" %oth $ice num%ers at the same time. The $ice num%ers are
$ispla"e$ for 3 secon$s# after which the LE,s are turne$ /66 to in$icate that the
s"stem is rea$".
)o$if"ing the Program
The program given in 6igure E.! can ma$e more efficient %" com%ining the two $ice
ni%%les into a single ta%le value as $escri%e$ here.
There are thirt"&si8 possi%le com%inations of the two $ice values. Referring to
Ta%le E.4# Ta%le E.A# an$ 6igure E.E# we can create Ta%le E.E to show all the possi%le
two&$ice values an$ the correspon$ing num%ers to %e sent to P/RTC.
The mo$ifie$ program *program name LE,E.C+ is given in 6igure E.J. In this program
arra" ,ICE contains the thirt"&si8 possi%le $ice values. The program enters an en$less
/
T:O DI*E O >SING FE:ER I/O PINS
777777777777777777777777777777
In !his proKe! LEDs are onne!e" !o PORT* of a PI*/0F12- miroon!roller
an" !he miroon!roller is opera!e" from a 1MHE resona!or' The LEDs are
organiEe" as !he faes of a real "ie' :hen a p8shO)8!!on s%i!h onne!e"
!o R#$ is presse" a "ie pa!!ern is "ispla+e" on !he LEDs' The "ispla+
remains
in !his s!a!e for M seon"s an" af!er !his perio" !he LEDs all !8rn OFF !o in"ia!e
!ha! !he s+s!em is rea"+ for !he )8!!on !o )e presse" again'
In !his program a pse8"oran"om n8m)er genera!or f8n!ion is
8se" !o genera!e !he "ie n8m)ers )e!%een / an" N'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( LED2'*
/
P"efine S%i!h PORT#'F$
P"efine Presse" $
//
// This f8n!ion genera!es a pse8"o ran"om in!eger n8m)er
// )e!%een / an" Lim
//
8nsigne" har N8m)er3in! Lim, in! ?4
5
8nsigne" har Res8l!6
s!a!i 8nsigne" in! ?6
? 7 3? * M-./T L M4 \ M-.1T6
Res8l! 7 33? \ Lim4 L /46
re!8rn Res8l!6
;
//
// S!ar! of MAIN program
//
&oi" main34
5
8nsigne" har V,L,>,R,See" 7 /6
8nsigne" har DI*EHI 7 5$,$G$0,$G$/,$G$T,$G$N,$G$E,$G$.;6
TRIS* 7 $6 // PORT* are o8!p8!s
TRIS# 7 /6 // R#$ inp8!
PORT* 7 $6 // T8rn OFF all LEDs
for3664 // En"less loop
6igure E.!( Program listing
ss. co m
5
if3S%i!h 77 Presse"4 // Is s%i!h presse" [
5
V 7 N8m)er3N,see"46 // Genera!e firs! "ie n8m)er
L 7 DI*EHVI6 // Ge! LED pa!!ern
V 7 N8m)er3N,see"46 // Genera!e seon" "ie n8m)er
> 7 DI*EHVI6 // Ge! LED pa!!ern
R 7 /N*> L L6 // #i! pa!!ern !o sen" !o PORT*
PORT* 7 R6 // T8rn on LEDs for )o!h "ie
Dela+9ms3M$$$46 // Dela+ M seon"s
PORT* 7 $6 // T8rn OFF all LEDs
;
;
;
6igure E.!( *Cont2$+
Ta%le E.E( Two&$ice com%inations an$ the num%er to %e sent to P/RTC
,ice num%ers P/RTC value ,ice num%ers P/RTC value
# 3 !! 4# 3 !E
#- 3 ! 4#- 3 E
#3 3 J! 4#3 3 JE
#4 3 E! 4#4 3 EE
#A 3 E! 4#A 3 EE
#E 3 L! 4#E 3 LE
-# 3 ! A# 3 !E
-#- 3 A#- 3 E
-#3 3 J A#3 3 JE
-#4 3 E A#4 3 EE
-#A 3 E A#A 3 EE
-#E 3 L A#E 3 LE
3# 3 !J E# 3 !L
3#- 3 J E#- 3 L
3#3 3 JJ E#3 3 JL
3#4 3 EJ E#4 3 EL
3#A 3 EJ E#A 3 EL
3#E 3 LJ E#E 3 LL
AE Chapter E
ss. co m
/*****************************************************************************************
T:O DI*E O >SING FE:ER I/O PINS
77777777777777777777777777777
In !his proKe! LEDs are onne!e" !o PORT* of a PI*/0F12- miroon!roller
an" !he miroon!roller is opera!e" from a 1MHE resona!or' The LEDs are
organiEe" as !he faes of a real "ie' :hen a p8shO)8!!on s%i!h onne!e" !o
R#$ is presse" a "ie pa!!ern is "ispla+e" on !he LEDs' The "ispla+ remains
in !his s!a!e for M seon"s an" af!er !his perio" !he LEDs all !8rn OFF !o
in"ia!e !ha! !he s+s!em is rea"+ for !he )8!!on !o )e presse" again'
In !his program a pse8"oran"om n8m)er genera!or f8n!ion is
8se" !o genera!e !he "ie n8m)ers )e!%een / an" N'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( LEDN'*
******************************************************************************************/
P"efine S%i!h PORT#'F$
P"efine Presse" $
//
// S!ar! of MAIN program
//
&oi" main34
5
8nsigne" har Pa!!ern, V 7 /6
8nsigne" har DI*EHI 7 5$,$G00,$G/0,$GT0,$GN0,$GE0,$G.0,
$G0/,$G//,$GT/,$GN/,$GE/,$G./,
$G0T,$G/T,$GTT,$GNT,$GET,$G.T,
$G0N,$G/N,$GTN,$GNN,$GEN,$G.N,
$G0E,$G/E,$GTE,$GNE,$GEE,$G.E,
$G0.,$G/.,$GT.,$GN.,$GE.,$G..;6
TRIS* 7 $6 // PORT* are o8!p8!s
TRIS# 7 /6 // R#$ inp8!
PORT* 7 $6 // T8rn OFF all LEDs
for3664 // En"less loop
5
if3S%i!h 77 Presse"4 // Is s%i!h presse" [
5
Pa!!ern 7 DI*EHVI6 // N8m)er !o sen" !o PORT*
PORT* 7 Pa!!ern6 // sen" !o PORT*
Dela+9ms3M$$$46 // M seon"s "ela+
PORT* 7 $6 // *lear PORT*
;
VLL6 // Inremen! V
if3V 77 M.4 V 7 /6 // If V 7 M., rese! !o /
;
;
6igure E.J( )o$ifie$ program
www. newnespress. co m
'imple PIC! Pro5ects AL
for loop# an$ insi$e this loop the state of the push&%utton switch is checke$. Also# a
varia%le is incremente$ from to 3E. Bhen the %utton is presse$# the value of this
varia%le is use$ as an in$e8 to arra" ,ICE to $etermine the %it pattern to %e sent to
P/RTC. As %efore# the program $ispla"s the $ice num%ers for 3 secon$s an$ then turns
/66 all LE,s to in$icate that it is rea$".
PR/aECT E.AcL&'egment LE, Counter
Pro5ect ,escription
This pro5ect $escri%es the $esign of a L&segment LE,&%ase$ counter which counts
from 3 to J continuousl" with a one&secon$ $ela" %etween counts. The pro5ect
shows how a L&segment LE, can %e interface$ an$ use$ in a PIC microcontroller
pro5ect.
L&segment $ispla"s are use$ freCuentl" in electronic circuits to show numeric or
alphanumeric values. As shown in 6igure E.-3# a L&segment $ispla" consists %asicall" of
L LE,s connecte$ such that the num%ers from 3 to J an$ some letters can %e $ispla"e$.
'egments are i$entifie$ %" the letters from a to g# an$ 6igure E.- shows the segment
names of a t"pical L&segment $ispla".
6igure E.-3( 'ome L&segment $ispla"s
ss. co m
A! Chapter E
a
f )
g
e
"
6igure E.-( 'egment names of a L&segment $ispla"
6igure E.-- shows how the num%ers from 3 to J are o%taine$ %" turning /G $ifferent
segments of the $ispla".
6igure E.--( ,ispla"ing num%ers 3 to J
L&segment $ispla"s are availa%le in two $ifferent configurations( common catho$e an$
common ano$e. As shown in 6igure E.-3# in common catho$e configuration# all the
catho$es of all segment LE,s are connecte$ together to the groun$. The segments are
turne$ /G %" appl"ing a logic to the reCuire$ segment LE, via current limiting
resistors. In common catho$e configuration the L&segment LE, is connecte$ to the
microcontroller in current sourcing mo$e.
In common ano$e configuration# the ano$e terminals of all the LE,s are connecte$
together as shown in 6igure E.-4. This common point is then normall" connecte$ to the
www. newnespress. co m
'imple PIC! Pro5ects AJ
6igure E.-3( Common catho$e configuration
6igure E.-4( Common ano$e configuration
suppl" voltage. A segment is turne$ /G %" connecting its catho$e terminal to logic
3 via a current limiting resistor. In common ano$e configuration the L&segment LE, is
connecte$ to the microcontroller in current sinking mo$e.
In this pro5ect# a .ing%right 'AA-& re$ common ano$e L&segment $ispla" is use$.
This is a 3mm *3.A- inch+ $ispla" with ten pins that inclu$es a segment LE, for the
$ecimal point. Ta%le E.L shows the pin configuration of this $ispla".
Pro5ect Har$ware
The circuit $iagram of the pro5ect is shown in 6igure E.-A. A PIC!64A- t"pe
microcontroller is use$ with a 4)HH resonator. 'egments a to g of the $ispla" are
connecte$ to P/RTC of the microcontroller through -J3&ohm current limiting resistors.
7efore $riving the $ispla"# we have to know the relationship %etween the num%ers to %e
$ispla"e$ an$ the correspon$ing segments to %e turne$ /G# an$ this is shown in
Ta%le E.!. 6or e8ample# to $ispla" num%er 3 we have to sen$ the he8a$ecimal num%er
3 46 to P/RTC# which turns /G segments a#%#c#$# an$ g. 'imilarl"# to $ispla"
num%er J we have to sen$ the he8a$ecimal num%er 3 E6 to P/RTC which turns /G
segments a#%#c#$#f# an$ g.
ss. co m
E3 Chapter E
Ta%le E.L( 'AA-& pin configuration
Pin num%er 'egment
e
- $
3 common ano$e
4 c
A $ecimal point
E %
L a
! common ano$e
J f
3 g
6igure E.-A( Circuit $iagram of the pro5ect
www. newnespress. co m
'imple PIC! Pro5ects E
Ta%le E.!( ,ispla"e$ num%er an$ $ata sent to P/RTC
Gum%er 8 g f e $ c % a P/RTC ,ata
3 3 3 3 36
3 3 3 3 3 3 3 3E
- 3 3 3 3 A7
3 3 3 3 3 46
4 3 3 3 3 3 EE
A 3 3 3 3 E,
E 3 3 3 L,
L 3 3 3 3 3 3 3L
! 3 3 L6
J 3 3 3 E6
8 is not use$# taken as 3.
Pro5ect P,L
The operation of the pro5ect is shown in 6igure E.-E with a P,L. At the %eginning of
the program an arra" calle$ 'EY)EGT is $eclare$ an$ fille$ with the relationships
%etween the num%ers 3 an$ J an$ the $ata to %e sent to P/RTC. The P/RTC pins are
then configure$ as outputs# an$ a varia%le is initialiHe$ to 3. The program then enters an
START
*rea!e SEGMENT !a)le
*onfig8re PORT* as o8!p8!s
Ini!ialiEe *NT !o $
DO FORE=ER
Ge! )i! pa!!ern from SEGMENT orrespon"ing !o *NT
Sen" !his )i! pa!!ern !o PORT*
Inremen! *NT )e!%een $ an" T
:ai! / seon"
ENDDO
END
6igure E.-E( P,L of the pro5ect
ss. co m
E- Chapter E
en$less loop where the varia%le is incremente$ %etween 3 an$ J an$ the correspon$ing
%it pattern to turn /G the appropriate segments is sent to P/RTC continuousl" with
a one&secon$ $ela" %etween outputs.
Pro5ect Program
The program is calle$ 'EFEG.C an$ the listing is given in 6igure E.-L. At the
%eginning of the program character varia%les Pattern an$ Cnt are $eclare$# an$ Cnt
is cleare$ to 3. Then Ta%le E.! is implemente$ using arra" 'EY)EGT. After
configuring the P/RTC pins as outputs# the program enters an en$less loop using
a for statement. Insi$e the loop the %it pattern correspon$ing to the contents of Cnt is
/*************************************************************************************
.OSEGMENT DISPLA?
77777777777777777
In !his proKe! a ommon ano"e .Osegmen! LED "ispla+ is onne!e" !o PORT*
of a PI*/0F12- miroon!roller an" !he miroon!roller is opera!e" from a 1MHE
resona!or' The program "ispla+s n8m)ers $ !o T on !he "ispla+ %i!h a one
seon" "ela+ )e!%een eah o8!p8!'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SE=EN/'*
**************************************************************************************/
&oi" main34
5
8nsigne" har Pa!!ern, *n! 7 $6
8nsigne" har SEGMENTHI 7 5$GMF,$G$N,$G2#,$G1F,$GNN,$GND,
$G.D,$G$.,$G.F,$GNF;6
TRIS* 7 $6 // PORT* are o8!p8!s
for3664 // En"less loop
5
Pa!!ern 7 SEGMENTH*n!I6 // N8m)er !o sen" !o PORT*
Pa!!ern 7 ]Pa!!ern6 // In&er! )i! pa!!ern
PORT* 7 Pa!!ern6 // Sen" !o PORT*
*n!LL6
if3*n! 77 /$4 *n! 7 $6 // *n! is )e!%een $ an" T
Dela+9ms3/$$$46 // / seon" "ela+
;
;
6igure E.-L( Program listing
www. newnespress. co m
'imple PIC! Pro5ects E3
foun$ an$ store$ in varia%le Pattern. 7ecause we are using a common ano$e $ispla"#
a segment is turne$ /G when it is at logic 3 an$ thus the %it pattern is inverte$ %efore
it is sent to P/RTC. The value of Cnt is then incremente$ %etween 3 an$ J# after
which the program waits for a secon$ %efore repeating the a%ove seCuence.
)o$ifie$ Program
Gote that the program can %e ma$e more rea$a%le if we create a function to $ispla" the
reCuire$ num%er an$ then call this function from the main program. 6igure E.-! shows
the mo$ifie$ program *calle$ 'EFEG-.C+. A function calle$ ,ispla" is create$ with an
argument calle$ no. The function gets the %it pattern from local arra" 'EY)EGT
in$e8e$ %" no# inverts it# an$ then returns the resulting %it pattern to the calling
program.
PR/aECT E.EcTwo&,igit )ultiple8e$ L&'egment LE,
Pro5ect ,escription
This pro5ect is similar to Pro5ect E.A# %ut here multiple8e$ two $igits are use$ instea$ of
5ust one $igit an$ a fi8e$ num%er. In this pro5ect the num%er -A is $ispla"e$. In
multiple8e$ LE, applications *see 6igure E.-J+ the LE, segments of all the $igits are
tie$ together an$ the common pins of each $igit are turne$ /G separatel" %" the
microcontroller. Bhen each $igit is $ispla"e$ onl" for several millisecon$s# the e"e
cannot tell that the $igits are not /G all the time. This wa" we can multiple8 an"
num%er of L&segment $ispla"s together. 6or e8ample# to $ispla" the num%er A3# we have
to sen$ A to the first $igit an$ ena%le its common pin. After a few millisecon$s# num%er
3 is sent to the secon$ $igit an$ the common point of the secon$ $igit is ena%le$. Bhen
this process is repeate$ continuousl"# it appears to the user that %oth $ispla"s are /G
continuousl".
'ome manufacturers provi$e multiple8e$ multi$igit $ispla"s# such as -&# 4&# or !&$igit
multiple8e$ $ispla"s# in single packages. The $ispla" use$ in this pro5ect is the ,CAE&
EBA# which is a re$ 3.AE&inch common&catho$e two&$igit $ispla" having ! pins
an$ the pin configuration as shown in Ta%le E.J. This $ispla" can %e controlle$ from the
microcontroller as follows(

'en$ the segment %it pattern for $igit to segments a to g

Ena%le $igit
ss. co m
E4 Chapter E
/***************************************************************************************
.OSEGMENT DISPLA?
777777777777777777
In !his proKe! a ommon ano"e .Osegmen! LED "ispla+ is onne!e" !o
PORT* of a PI*/0F12- miroon!roller an" !he miroon!roller is
opera!e" from a 1MHE resona!or' The program "ispla+s n8m)ers $ !o T
on !he "ispla+ %i!h a one seon" "ela+ )e!%een eah o8!p8!'
In !his &ersion of !he program a f8n!ion alle" ^Displa+^ is 8se" !o "ispla+ !he
n8m)er'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SE=EN-'*
*****************************************************************************************/
//
// This f8n!ion "ispla+s a n8m)er on !he .Osegmen! LED'
// The n8m)er is passe" in !he arg8men! lis! of !he f8n!ion'
//
8nsigne" har Displa+38nsigne" har no4
5
8nsigne" har Pa!!ern6
8nsigne" har SEGMENTHI 7 5$GMF,$G$N,$G2#,$G1F,$GNN,$GND,
$G.D,$G$.,$G.F,$GNF;6
Pa!!ern 7 SEGMENTHnoI6
Pa!!ern 7 ] Pa!!ern6 // Pa!!ern !o re!8rn
re!8rn 3Pa!!ern46
;
//
// S!ar! of MAIN Program
//
&oi" main34
5
8nsigne" har *n! 7 $6
TRIS* 7 $6 // PORT* are o8!p8!s
for3664 // En"less loop
5
PORT* 7 Displa+3*n!46 // Sen" !o PORT*
*n!LL6
if3*n! 77 /$4 *n! 7 $6 // *n! is )e!%een $ an" T
Dela+9ms3/$$$46 // / seon" "ela+
;
;
6igure E.-!( )o$ifie$ program listing
www. newnespress. co m
'imple PIC! Pro5ects EA
6igure E.-J( Two multiple8e$ L&segment $ispla"s
Ta%le E.J( Pin configuration of ,CAE&EBA $ual $ispla"
Pin no. 'egment
#A E
-#E ,
3#! C
4 ,igit ena%le
L#L Y
A#3 7
E# A
!#- 6
3 ,igit - ena%le
4 ,ecimal point
J ,ecimal point -
ss. co m
EE Chapter E

Bait for a few millisecon$s

,isa%le $igit

'en$ the segment %it pattern for $igit - to segments a to g

Ena%le $igit -

Bait for a few millisecon$s

,isa%le $igit -

Repeat these steps continuousl"
The segment configuration of the ,CAE&EBA $ispla" is shown in 6igure E.33.
In a multiple8e$ $ispla" application the segment pins of correspon$ing segments
are connecte$ together. 6or e8ample# pins an$ E are connecte$ as the
common a segment# pins A an$ 3 are connecte$ as the common % segment#
an$ so on.
6igure E.33( ,CAE&EBA $ispla" segment configuration
Pro5ect Har$ware
The %lock $iagram of this pro5ect is shown in 6igure E.3. The circuit $iagram is given
in 6igure E.3-. The segments of the $ispla" are connecte$ to P/RTC of a PIC!64A-&
t"pe microcontroller# operate$ with a 4)HH resonator. Current limiting resistors are
use$ on each segment of the $ispla". Each $igit is ena%le$ using a 7C3!&t"pe
transistor switch connecte$ to port pins R73 an$ R7 of the microcontroller. A segment
is turne$ on when a logic is applie$ to the %ase of the correspon$ing segment
transistor.
www. newnespress. co m
'imple PIC! Pro5ects EL
-O"igi! "ispla+
PI*/0F12-
PORT*
PORT#
Ena)le /
Ena)le -
6igure E.3( 7lock $iagram of the pro5ect
6igure E.3-( Circuit $iagram of the pro5ect
Pro5ect P,L
At the %eginning of the program P/RT7 an$ P/RTC pins are configure$ as outputs.
The program then enters an en$less loop where first of all the )ost 'ignificant ,igit
*)',+ of the num%er is calculate$# function ,ispla" is calle$ to fin$ the %it pattern an$
then sent to the $ispla"# an$ $igit is ena%le$. Then# after a small $ela"# $igit is
$isa%le$# the Least 'ignificant ,igit *L',+ of the num%er is calculate$# function
,ispla" is calle$ to fin$ the %it pattern an$ then sent to the $ispla"# an$ $igit - is
ena%le$. Then again after a small $ela"# $igit - is $isa%le$# an$ this process repeats
in$efinitel". 6igure E.33 shows the P,L of the pro5ect.
START
END
*rea!e SEGMENT !a)le
*onfig8re PORT# as o8!p8!s
*onfig8re PORT* as o8!p8!s
Ini!ialiEe *NT !o -2
DO FORE=ER
Fin" MSD "igi!
Ge! )i! pa!!ern from SEGMENT
Ena)le "igi! /
:ai! for a %hile
Disa)le "igi! /
Fin" LSD "igi!
Ge! )i! pa!!ern from SEGMENT
Ena)le "igi! -
:ai! for a %hile
Disa)le "igi! -
ENDDO
Pro5ect Program
6igure E.33( P,L of the pro5ect
The program is name$ 'EFEG3.C# an$ the listing is shown in 6igure E.34. ,IYIT an$
,IYIT- are $efine$ as eCual to %it 3 an$ %it of P/RT7 respectivel". The value to %e
$ispla"e$ *the num%er -A+ is store$ in varia%le Cnt. An en$less loop is forme$ using a
for statement. Insi$e the loop# the )', of the num%er is calculate$ %" $ivi$ing the
num%er %" 3. 6unction ,ispla" is then calle$ to fin$ the %it pattern to sen$ to P/RTC.
Then $igit is ena%le$ %" setting ,IYIT @ an$ the program waits for 3ms. After
this# $igit is $isa%le$ an$ the L', of the num%er is calculate$ using the mo$ operator
*:V<+ an$ sent to P/RTC. At the same time# $igit - is ena%le$ %" setting ,IYIT- @
an$ the program waits for 3ms. After this time $igit - is $isa%le$# an$ the program
repeats forever.
/
D8al .OSEGMENT DISPLA?
7777777777777777777777
In !his proKe! !%o ommon a!ho"e .Osegmen! LED "ispla+s are onne!e" !o
PORT* of a PI*/0F12- miroon!roller an" !he miroon!roller is opera!e"
from a 1MHE resona!or' Digi! / 3lef! "igi!4 ena)le pin is onne!e" !o por! pin
R#$ an" "igi! - 3righ! "igi!4 ena)le pin is onne!e" !o por! pin R#/ of !he
miroon!roller' The program "ispla+s n8m)er -2 on !he "ispla+s'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SE=ENM'*
/
P"efine DIGIT/ PORT#'F$
P"efine DIGIT- PORT#'F/
//
// This f8n!ion fin"s !he )i! pa!!ern !o )e sen! !o !he por! !o "ispla+ a n8m)er
// on !he .Osegmen! LED' The n8m)er is passe" in !he arg8men! lis! of !he f8n!ion'
//
8nsigne" har Displa+38nsigne" har no4
5
8nsigne" har Pa!!ern6
8nsigne" har SEGMENTHI 7 5$GMF,$G$N,$G2#,$G1F,$GNN,$GND,
$G.D,$G$.,$G.F,$GNF;6
Pa!!ern 7 SEGMENTHnoI6 // Pa!!ern !o re!8rn
re!8rn 3Pa!!ern46
;
//
// S!ar! of MAIN Program
//
&oi" main34
5
8nsigne" har Ms", Ls", *n! 7 -26
TRIS* 7 $6 // PORT* are o8!p8!s
TRIS# 7 $6 // R#$, R#/ are o8!p8!s
DIGIT/ 7 $6 // Disa)le "igi! /
DIGIT- 7 $6 // Disa)le "igi! -
for3664 // En"less loop
5
6igure E.34( Program listing
*Continue$+
Ms" 7 *n! / /$6 // MSD "igi!
PORT* 7 Displa+3Ms"46 // Sen" !o PORT*
DIGIT/ 7 /6 // Ena)le "igi! /
Dela+9Ms3/$46 // :ai! a %hile
DIGIT/ 7 $6 // Disa)le "igi! /
Ls" 7 *n! \ /$6 // LSD "igi!
PORT* 7 Displa+3Ls"46 // Sen" !o PORT*
DIGIT- 7 /6 // Ena)le "igi! -
Dela+9Ms3/$46 // :ai! a %hile
DIGIT- 7 $6 // Disa)le "igi! -
;
;
6igure E.34( *Cont2$+
PR/aECT E.LcTwo&,igit )ultiple8e$ L&'egment
LE, Counter with Timer Interrupt
Pro5ect ,escription
This pro5ect is similar to Pro5ect E %ut here the microcontroller2s timer interrupt is use$
to refresh the $ispla"s. In Pro5ect E the microcontroller was %us" up$ating the $ispla"s
ever" 3ms an$ coul$ not perform an" other tasks. 6or e8ample# the program given
in Pro5ect E cannot %e use$ to make a counter with a one&secon$ $ela" %etween
counts# as the $ispla"s cannot %e up$ate$ while the program waits for one secon$.
In this pro5ect a counter is $esigne$ to count from 3 to JJ# an$ the $ispla" is refreshe$
ever" Ams insi$e the timer interrupt service routine. The main program can then
perform other tasks# in this e8ample incrementing the count an$ waiting for one secon$
%etween counts.
In this pro5ect Timer 3 is operate$ in !&%it mo$e. The time for an interrupt is given %"(
Time @ \4 clock perio$] Prescaler \-AE T)R3L]
where Prescaler is the selecte$ prescaler value# an$ T)R3L is the value loa$e$ into
timer register T)R3L to generate timer interrupts ever" Time perio$.
In our application the clock freCuenc" is 4)HH# that is# clock perio$ @ 3.-Ams# an$
Time @ Ams. 'electing a prescaler value of 3-# the num%er to %e loa$e$ into T)R3L
can %e calculate$ as follows(
T)R3L @ -AE
4
Time
clockperio$ prescaler
or
T)R3L @ -AE
4
A333
3(-A
3-
@ 33
Thus# T)R3L shoul$ %e loa$e$ with 33. The value to %e loa$e$ into T)R3 control
register T3C/G can then %e foun$ as(
T$*ON
/ / $ $ $ / $ $
Ena)le
TMR$
0O)i!
mo"e
In!ernal
loJ
Lo%Ohigh
!ransi!ion
>se
presaler
/(M-
presaler
Thus# T3C/G register shoul$ %e loa$e$ with he8a$ecimal 3 C4. The ne8t register
to %e configure$ is the interrupt control register IGTC/G# where we will $isa%le
priorit" %ase$ interrupts an$ ena%le the glo%al interrupts an$ T)R3 interrupts(
INT*ON
/ Q / $ $ $ Q Q
Ena)le
glo)al
in!err8p!s
Ena)le
TMR$
in!'
Disa)le
INT$
in!'
Disa)le
R# hange
in!'
*lear
TMR$IF
Taking the $on2t&care entries *M+ as 3# the he8a$ecimal value to %e loa$e$ into
register IGTC/G is 3 A3.
Bhen an interrupt occurs# the program automaticall" 5umps to the interrupt
service routine. Insi$e this routine we have to reloa$ register T)R3L# reena%le
the T)R3 interrupts# an$ clear the T)R3 interrupt flag %it. 'etting IGTC/G
register to 3 -3 reena%les the T)R3 interrupts an$ at the same time clears the
T)R3 interrupt flag.
The operations to %e performe$ can thus %e summariHe$ as follows(
In the main program(

Loa$ T)R3L with 33

'et T3C/G to 3 C4

'et IGTC/G to 3 A3

Increment the counter with &secon$ $ela"s
In the interrupt service routine(

Re&loa$ T)R3L to 33

Refresh $ispla"s

'et IGTC/G to 3 -3 *reena%le T)R3 interrupts an$ clear timer interrupt
flag+
Pro5ect Har$ware
The circuit $iagram of this pro5ect is same as in 6igure E.3- where a $ual L&segment
$ispla" is connecte$ to P/RT7 an$ P/RTC of a PIC!64A- microcontroller.
Pro5ect P,L
The P,L of the pro5ect is shown in 6igure E.3A. The program is in two sections( the
main program an$ the interrupt service routine. Insi$e the main program# T)R3 is
configure$ to generate interrupts ever" Ams an$ the counter is incremente$ with a one&
secon$ $ela". Insi$e the interrupt service routine# the timer interrupt is reena%le$ an$
the $ispla" $igits are refreshe$ alternatel" ever" Ams.
MAIN PROGRAM(
START
*onfig8re PORT# as o8!p8!s
*onfig8re PORT* as o8!p8!s
*lear &aria)le *n! !o $
*onfig8re TMR$ !o genera!e in!err8p!s e&er+ 2ms
DO FORE=ER
Inremen! *n! )e!%een $ an" TT
Dela+ / seon"
END
ENDO
INTERR>PT SER=I*E RO>TINE(
START
ReOonfig8re TMR$
IF Digi! / 8p"a!e" THEN
>p"a!e "igi! -
END
ELSE
END
>p"a!e "igi! /
6igure E.3A( P,L of the pro5ect
Pro5ect Program
The program is calle$ 'EFEG4.C# an$ the program listing is given in 6igure E.3E.
At the %eginning of the main program P/RT7 an$ P/RTC are configure$ as
outputs. Then register T3C/G is loa$e$ with 3 C4 to ena%le the T)R3 an$ set the
prescaler to 3-. T)R3L register is loa$e$ with 33 so that an interrupt is generate$
after Ams. The program then enters an en$less loop where the value of Cnt is
incremente$ ever" secon$.
Insi$e the interrupt service routine# register T)R3L is reloa$e$# T)R3 interrupts are
reena%le$# an$ the timer interrupt flag is cleare$ so that further timer interrupts can %e
generate$. The $ispla" $igits are then up$ate$ alternatel". A varia%le calle$ 6lag is use$
to $etermine which $igit to up$ate. 6unction ,ispla" is calle$# as in Pro5ect E# to fin$
the %it pattern to %e sent to P/RTC.
)o$if"ing the Program
In 6igure E.3E the $ispla" counts as 33 3. . .3J 3 . . .JJ 33 3. . . *i.e.# the first $igit
is shown as 3 for num%ers less than 3+. The program coul$ %e mo$ifie$ so the first
/
D8al .OSEGMENT DISPLA? *O>NTER
777777777777777777777777777777
In !his proKe! !%o ommon a!ho"e .Osegmen! LED "ispla+s are onne!e" !o
PORT* of a PI*/0F12- miroon!roller an" !he miroon!roller is opera!e"
from a 1MHE resona!or' Digi! / 3lef! "igi!4 ena)le pin is onne!e" !o por! pin R#$
an" "igi! - 3righ! "igi!4 ena)le pin is onne!e" !o por! pin R#/ of !he miroon!roller'
The program o8n!s 8p from $ !o TT %i!h one seon" "ela+ )e!%een eah o8n!'
The "ispla+ is 8p"a!e" in a !imer in!err8p! ser&ie ro8!ine a!
e&er+ 2ms'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SE=EN1'*
/
P"efine DIGIT/ PORT#'F$
P"efine DIGIT- PORT#'F/
8nsigne" har *n! 7 $6
8nsigne" har Flag 7 $6
//
// This f8n!ion fin"s !he )i! pa!!ern !o )e sen! !o !he por! !o "ispla+ a n8m)er
// on !he .Osegmen! LED' The n8m)er is passe" in !he arg8men! lis! of !he f8n!ion'
//
8nsigne" har Displa+38nsigne" har no4
5
8nsigne" har Pa!!ern6
8nsigne" har SEGMENTHI 7 5$GMF,$G$N,$G2#,$G1F,$GNN,$GND,
$G.D,$G$.,$G.F,$GNF;6
Pa!!ern 7 SEGMENTHnoI6 // Pa!!ern !o re!8rn
re!8rn 3Pa!!ern46
;
//
// TMR$ !imer in!err8p! ser&ie ro8!ine' The program K8mps !o !he ISR a!
// e&er+ 2ms'
//
&oi" in!err8p! 34
5
8nsigne" har Ms", Ls"6
TMR$L 7 /$$6 // ReOloa" TMR$
INT*ON 7 $G-$6 // Se! T$IE an" lear T$IF
Flag 7 ] Flag6 // Toggle Flag
if3Flag 77 $4 // Do "igi! /
5
6igure E.3E( Program of the pro5ect
DIGIT- 7 $6
Ms" 7 *n! / /$6 // MSD "igi!
PORT* 7 Displa+3Ms"46 // Sen" !o PORT*
DIGIT/ 7 /6 // Ena)le "igi! /
;
else
5 // Do "igi! -
DIGIT/ 7 $6 // Disa)le "igi! /
Ls" 7 *n! \ /$6 // LSD "igi!
PORT* 7 Displa+3Ls"46 // Sen" !o PORT*
DIGIT- 7 /6 // Ena)le "igi! -
;
;
//
// S!ar! of MAIN Program' onfig8re PORT# an" PORT* as o8!p8!s'
// In a""i!ion, onfig8re TMR$ !o in!err8p! a! e&er+ /$ms
//
&oi" main34
5
TRIS* 7 $6 // PORT* are o8!p8!s
TRIS# 7 $6 // R#$, R#/ are o8!p8!s
DIGIT/ 7 $6 // Disa)le "igi! /
DIGIT- 7 $6 // Disa)le "igi! -
//
// *onfig8re TMR$ !imer in!err8p!
//
T$*ON 7 $G*16 // Presaler 7 M-
TMR$L 7 /$$6 // Loa" TMR$L %i!h /$$
INT*ON 7 $GA$6 // Ena)le TMR$ in!err8p!
Dela+9ms3/$$$46
for3664 // En"less loop
5
*n!LL6 // Inremen! *n!
if3*n! 77 /$$4 *n! 7 $6 // *o8n! )e!%een $ an" TT
Dela+9ms3/$$$46 // :ai! / seon"
;
;
6igure E.3E( *Cont2$+
$igit is %lanke$ if the num%er to %e $ispla"e$ is less than 3. The mo$ifie$ program
*calle$ 'EFEGA.C+ is shown in 6igure E.3L. Here# the first $igit *)',+ is not ena%le$
if the num%er to %e $ispla"e$ is 3.
/
D8al .OSEGMENT DISPLA? *O>NTER
777777777777777777777777777777
In !his proKe! !%o ommon a!ho"e .Osegmen! LED "ispla+s are
onne!e" !o PORT* of a PI*/0F12- miroon!roller an" !he
miroon!roller is opera!e" from a 1MHE resona!or' Digi! / 3lef!
"igi!4 ena)le pin is onne!e" !o por! pin R#$ an" "igi! -
3righ! "igi!4 ena)le pin is onne!e" !o por! pin R#/ of !he
miroon!roller' The program o8n!s 8p from $ !o TT %i!h
one seon" "ela+ )e!%een eah o8n!'
The "ispla+ is 8p"a!e" in a !imer in!err8p! ser&ie ro8!ine a!
e&er+ 2ms'
In !his &ersion of !he program !he firs! "igi! is )lanJe" if !he
n8m)er is $'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SE=EN2'*
/
P"efine DIGIT/ PORT#'F$
P"efine DIGIT- PORT#'F/
8nsigne" har *n! 7 $6
8nsigne" har Flag 7 $6
//
// This f8n!ion fin"s !he )i! pa!!ern !o )e sen! !o !he por! !o "ispla+ a n8m)er
// on !he .Osegmen! LED' The n8m)er is passe" in !he arg8men! lis! of !he f8n!ion'
//
8nsigne" har Displa+38nsigne" har no4
5
8nsigne" har Pa!!ern6
8nsigne" har SEGMENTHI 7 5$GMF,$G$N,$G2#,$G1F,$GNN,$GND,
$G.D,$G$.,$G.F,$GNF;6
Pa!!ern 7 SEGMENTHnoI6 // Pa!!ern !o re!8rn
re!8rn 3Pa!!ern46
;
//
// TMR$ !imer in!err8p! ser&ie ro8!ine' The program K8mps !o !he
// ISR a! e&er+ 2ms'
//
&oi" in!err8p! 34
5
8nsigne" har Ms", Ls"6
6igure E.3L( )o$ifie$ program
TMR$L 7 /$$6 // ReOloa" TMR$
INT*ON 7 $G-$6 // Se! T$IE an" lear T$IF
Flag 7 ] Flag6 // Toggle Flag
if3Flag 77 $4 // Do "igi! /
5
DIGIT- 7 $6
Ms" 7 *n! / /$6 // MSD "igi!
if3Ms" U7 $4
5
PORT* 7 Displa+3Ms"46 // Sen" !o PORT*
DIGIT/ 7 /6 // Ena)le "igi! /
;
;
else
5 // Do "igi! -
DIGIT/ 7 $6 // Disa)le "igi! /
Ls" 7 *n! \ /$6 // LSD "igi!
PORT* 7 Displa+3Ls"46 // Sen" !o PORT*
DIGIT- 7 /6 // Ena)le "igi! -
;
;
//
// S!ar! of MAIN Program' onfig8re PORT# an" PORT* as o8!p8!s'
// In a""i!ion, onfig8re TMR$ !o in!err8p! a! e&er+ /$ms
//
&oi" main34
5
TRIS* 7 $6 // PORT* are o8!p8!s
TRIS# 7 $6 // R#$, R#/ are o8!p8!s
DIGIT/ 7 $6 // Disa)le "igi! /
DIGIT- 7 $6 // Disa)le "igi! -
//
// *onfig8re TMR$ !imer in!err8p!
//
T$*ON 7 $G*16 // Presaler 7 M-
TMR$L 7 /$$6 // Loa" TMR$ %i!h /$$
INT*ON 7 $GA$6 // Ena)le TMR$ in!err8p!
Dela+9ms3/$$$46
for3664 // En"less loop
5
*n!LL6 // Inremen! *n!
if3*n! 77 /$$4 *n! 7 $6 // *o8n! )e!%een $ an" TT
Dela+9ms3/$$$46 // :ai! / seon"
;
;
6igure E.3L( *Cont2$+
PR/aECT E.!cFoltmeter with LC, ,ispla"
Pro5ect ,escription
In this pro5ect a voltmeter with LC, $ispla" is $esigne$. The voltmeter
can %e use$ to measure voltages 31AF. The voltage to %e measure$ is applie$
to one of the analog inputs of a PIC!64A-&t"pe microcontroller. The
microcontroller rea$s the analog voltage# converts it into $igital# an$ then
$ispla"s it on an LC,.
In microcontroller s"stems the output of a measure$ varia%le is usuall"
$ispla"e$ using LE,s# L&segment $ispla"s# or LC, $ispla"s. LC,s make it
possi%le to $ispla" alphanumeric or graphical $ata. 'ome LC,s have fort" or
more character lengths with the capa%ilit" to $ispla" several lines. /ther LC,
$ispla"s can %e use$ to $ispla" graphics images. 'ome mo$ules offer color
$ispla"s# while others incorporate %acklighting so the" can %e viewe$ in $iml"
lit con$itions.
There are %asicall" two t"pes of LC,s as far as the interface techniCue is
concerne$( parallel an$ serial. Parallel LC,s *e.g.# Hitachi H,44L!3+ are
connecte$ to a microcontroller %" more than one $ata line an$ the $ata is transferre$
in parallel form. 7oth four an$ eight $ata lines are commonl" use$. A four&wire
connection saves I9/ pins %ut is slower since the $ata is transferre$ in two stages.
'erial LC,s are connecte$ to the microcontroller %" onl" one $ata line# an$
$ata is usuall" sent to the LC, using the stan$ar$ R'&-3- as"nchronous $ata
communication protocol. 'erial LC,s are much easier to use# %ut the" cost more
than the parallel ones.
The programming of a parallel LC, is a comple8 task an$ reCuires a goo$
un$erstan$ing of the internal operation of the LC, controllers# inclu$ing the timing
$iagrams. 6ortunatel"# the mikroC language provi$es special li%rar" comman$s for
$ispla"ing $ata on alphanumeric as well as graphic LC,s. All the user has to $o is
connect the LC, to the microcontroller# $efine the LC, connection in the software# an$
then sen$ special comman$s to $ispla" $ata on the LC,.
H,44L!3 LC, )o$ule
The H,44L!3 is one of the most popular alphanumeric LC, mo$ules an$ is use$ %oth
in in$ustr" an$ %" ho%%"ists. This mo$ule is monochrome an$ comes in $ifferent siHes.
)o$ules with !# E# -3# -4# 3-# an$ 43 columns are availa%le. ,epen$ing on the
mo$el chosen# the num%er of rows ma" %e # -# or 4. The $ispla" provi$es a 4&pin
*or E&pin+ connector to a microcontroller. Ta%le E.3 gives the pin configuration an$
pin functions of a 4&pin LC, mo$ule. The following is a summar" of the pin
functions(
F
''
is the 3F suppl" or groun$. The F
,,
pin shoul$ %e connecte$ to the positive
suppl". Although the manufacturers specif" a AF ,C suppl"# the mo$ules will usuall"
work with as low as 3F or as high as EF.
Pin 3# name$ F
EE
# is the contrast control pin. This pin is use$ to a$5ust the contrast of
the $ispla" an$ shoul$ %e connecte$ to a varia%le voltage suppl". A potentiometer is
normall" connecte$ %etween the power suppl" lines with its wiper arm connecte$ to this
pin so that the contrast can %e a$5uste$.
Ta%le E.3( Pin configuration of H,44L!3 LC, mo$ule
Pin no. Game 6unction
F
''
Yroun$
- F
,,
D ve suppl"
3 F
EE
Contrast
4 R' Register select
A R9B Rea$9write
E E Ena%le
L ,3 ,ata %it 3
! , ,ata %it
J ,- ,ata %it -
3 ,3 ,ata %it 3
,4 ,ata %it 4
- ,A ,ata %it A
3 ,E ,ata %it E
4 ,L ,ata %it L
Pin 4 is the register select *R'+# an$ when this pin is L/B# $ata transferre$ to the
$ispla" is treate$ as comman$s. Bhen R' is HIYH# character $ata can %e transferre$ to
an$ from the mo$ule.
Pin A is the rea$9write *R9B+ line. This pin is pulle$ L/B in or$er to write comman$s
or character $ata to the LC, mo$ule. Bhen this pin is HIYH# character $ata or status
information can %e rea$ from the mo$ule.
Pin E is the ena%le *E+ pin# which is use$ to initiate the transfer of comman$s or $ata
%etween the mo$ule an$ the microcontroller. Bhen writing to the $ispla"# $ata is
transferre$ onl" on the HIYH&to&L/B transition of this line. Bhen rea$ing from the
$ispla"# $ata %ecomes availa%le after the L/B&to&HIYH transition of the ena%le pin#
an$ this $ata remains vali$ as long as the ena%le pin is at logic HIYH.
Pins L to 4 are the eight $ata %us lines *,3 to ,L+. ,ata can %e transferre$
%etween the microcontroller an$ the LC, mo$ule using either a single !&%it %"te or
as two
4&%it ni%%les. In the latter case# onl" the upper four $ata lines *,4 to ,L+ are use$.
The 4&%it mo$e means that four fewer I9/ lines are use$ to communicate with the
LC,. In this %ook we are using onl" an alphanumeric&%ase$ LC, an$ onl" the 4&
%it interface.
Connecting the LC,
The mikroC compiler assumes %" $efault that the LC, is connecte$ to the
microcontroller as follows(
LC, )icrocontroller port
,L 7it L of the port
,E 7it E of the port
,A 7it A of the port
,4 7it 4 of the port
E 7it 3 of the port
R' 7it - of the port
where port is the port name specifie$ using the Lc$KInit statement.
6or e8ample# we can use the statement Lc$KInit*SP/RT7+ if the LC, is connecte$ to
P/RT7 with the $efault connection.
It is also possi%le to connect the LC, $ifferentl"# using the comman$ Lc$KConfig to
$efine the connection.
Pro5ect Har$ware
6igure E.3! shows the %lock $iagram of the pro5ect. The microcontroller rea$s the
analog voltage# converts it to $igital# formats it# an$ then $ispla"s it on the LC,.
Inp8!
&ol!age
PI*/0F12-
L*D
6igure E.3!( 7lock $iagram of the pro5ect
The circuit $iagram of the pro5ect is shown in 6igure E.3J. The voltage to %e measure$
*%etween 3 an$ AF+ is applie$ to port AG3 where this port is configure$ as an analog
6igure E.3J( Circuit $iagram of the pro5ect
input in software. The LC, is connecte$ to P/RTC of the microcontroller as in the
$efault four&wire connection. A potentiometer is use$ to a$5ust the contrast of the
LC, $ispla".
Pro5ect P,L
The P,L of the pro5ect is shown in 6igure E.43. At the %eginning of the program
P/RTC is configure$ as output an$ P/RTA is configure$ as input. Then the LC, an$
the A9, converter are configure$. The program then enters an en$less loop where
analog input voltage is converte$ to $igital an$ $ispla"e$ on the LC,. The process is
repeate$ ever" secon$.
START
*onfig8re PORT* as o8!p8!s
*onfig8re PORTA as inp8!
*onfig8re !he L*D
*onfig8re !he A/D on&er!er
DO FORE=ER
Rea" analog "a!a 3&ol!age4 from hannel $
Forma! !he "a!a
Displa+ !he "a!a 3&ol!age4
:ai! one seon"
END
ENDO
6igure E.43( P,L of the pro5ect
Pro5ect Program
The program is calle$ 'EFEGE.C# an$ the program listing is given in 6igure E.4. At
the %eginning of the program P/RTC is $efine$ as output an$ P/RTA as input. Then
the LC, is configure$ an$ the te8t :F/LT)ETER< is $ispla"e$ on the LC, for two
secon$s. The A9, is then configure$ %" setting register A,C/G to 3 !3 so the A9,
result is right&5ustifie$# Fref voltage is set to F,, *DAF+# an$ all P/RTA pins are
configure$ as analog inputs.
The main program loop starts with a for statement. Insi$e this loop the LC, is
cleare$# an$ analog $ata is rea$ from channel 3 *pin AG3+ using the statement
A$cKRea$*3+. The converte$ $igital $ata is store$ in varia%le Fin which is $eclare$
as an unsigne$ long. The A9, converter is 3&%its wi$e an$ thus there are 3-4 steps
/
=OLTMETER :ITH L*D DISPLA?
7777777777777777777777777777
In !his proKe! an L*D is onne!e" !o PORT*' Also, inp8! por! AN$ is 8se"
as analog inp8!' =ol!age !o )e meas8re" is applie" !o AN$' The
miroon!roller rea"s !he analog &ol!age, on&er!s in!o "igi!al, an" !hen
"ispla+s on !he L*D'
Analog inp8! range is $ !o 2=' A PI*/0F12- !+pe miroon!roller is 8se" in
!his proKe!, opera!e" %i!h a 1MHE resona!or'
Analog "a!a is rea" 8sing !he A"9Rea" )8il!Oin f8n!ion' This f8n!ion 8ses !he
in!ernal R* loJ for A/D !iming'
The L*D is onne!e" !o !he miroon!roller as follo%s(
Miroon!roller L*D
R*. D.
R*N DN
R*2 D2
R*1 D1
R*M Ena)le
R*- RS
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SE=ENN'*
/
//
// S!ar! of MAIN Program' *onfig8re L*D an" A/D on&er!er
//
&oi" main34
5
8nsigne" long =in, m=6
8nsigne" har opH/-I6
8nsigne" har i,K,l"H2I6
TRIS* 7 $6 // PORT* are o8!p8!s 3L*D4
TRISA 7 $GFF6 // PORTA is inp8!
//
// *onfig8re L*D
//
L"9Ini!3CPORT*46 // L*D is onne!e" !o PORT*
L"9*m"3L*D9*LEAR46
L"9O8!3/,/,^=OLTMETER^46
Dela+9ms3-$$$46
//
6igure E.4( Program listing
*Continue$+
// *onfig8re A/D on&er!er' AN$ is 8se" in !his proKe!
//
AD*ON/ 7 $G0$6 // >se AN$ an" =ref7L2=
//
// Program loop
//
for3664 // En"less loop
5
L"9*m"3L*D9*LEAR46
=in 7 A"9Rea"3$46 // Rea" from hannel $ 3AN$4
L"9O8!3/,/,^m= 7 ^46 // Displa+ ^m= 7 ^
m= 7 3=in * 2$$$4 @@ /$6 // m& 7 =in G 2$$$ / /$-1
LongToS!r3m=,op46 // *on&er! !o s!ring in ^op^
//
// Remo&e lea"ing )lanJs
//
K7$6
for3i7$6iD7//6iLL4
5
if3opHiI U7 _ _4 // If a )lanJ
5
l"HKI7opHiI6
KLL6
;
;
//
// Displa+ res8l! on L*D
//
L"9O8!3/,N,l"46 // O8!p8! !o L*D
Dela+9ms3/$$$46 // :ai! / seon"
;
;
6igure E.4( *Cont2$+
*3 to 3-3+ correspon$ing to the reference voltage of A333mF. Each step correspon$s to
A333mF93-4 @ 4.!!mF. Insi$e the loop# varia%le Fin is converte$ into millivolts %"
multipl"ing %" A333 an$ $ivi$ing into 3-4. The $ivision is $one %" shifting right %" 3
$igits. At this point varia%le mF contains the converte$ $ata in millivolts.
6unction LongTo'tr is calle$ to convert mF into a string in character arra" op.
LongTo'tr converts a long varia%le into a string having a fi8e$ wi$th of eleven
characters. If the resulting string is fewer than eleven characters# the left column of
the $ata is fille$ with space characters.
The lea$ing %lanks are then remove$ an$ the $ata is store$ in a varia%le calle$ lc$.
6unction Lc$K/ut is calle$ to $ispla" the $ata on the LC, starting from column A of
row . 6or e8ample# if the measure$ voltage is -ELmF# it is $ispla"e$ on the LC, as(
mF @ -EL
A )ore Accurate ,ispla"
The voltage $ispla"e$ in 6igure E.4 is not ver" accurate# since integer arithmetic
has %een performe$ in the calculation an$ the voltage is calculate$ %" multipl"ing
the A9, output %" A333 an$ then $ivi$ing the result %" 3-4 using integer $ivision.
Although the multiplication is accurate# the accurac" of the measurement is lost when
the num%er is $ivi$e$ %" 3-4. A more accurate result can %e o%taine$ %" scaling the
num%er %efore it is $ispla"e$# as follows.
6irst# multipl" the num%er Fin %" a factor to remove the integer $ivision. 6or e8ample#
since A33393-4 @ 4.!!# we can multipl" Fin %" 4!!. 6or the $ispla"# we can calculate
the integer part of the result %" $ivi$ing the num%er into 33# an$ then the fractional
part can %e calculate$ as the remain$er. The integer part an$ the fractional part can %e
$ispla"e$ with a $ecimal point in %etween. This techniCue has %een implemente$ in
program 'EFEGL.C as shown in 6igure E.4-. In this program varia%les F$ec an$ Ffrac
store the integer an$ the fractional parts of the num%er respectivel". The $ecimal part is
then converte$ into a string using function LongTo'tr an$ lea$ing %lanks are remove$.
The parts of the fractional num%er are calle$ ch an$ ch-. These are converte$ into
characters %" a$$ing 4! *i.e.# character :3<+ an$ then $ispla"e$ at the ne8t cursor
positions using the LC, comman$ Lc$KChrKCp.
Be coul$ also calculate an$ $ispla" more accurate results %" using floating point
arithmetic# %ut since this uses huge amounts of memor" it shoul$ %e avoi$e$ if possi%le.
PR/aECT E.JcCalculator with .e"pa$ an$ LC,
Pro5ect ,escription
.e"pa$s are small ke"%oar$s use$ to enter numeric or alphanumeric $ata into
microcontroller s"stems. .e"pa$s are availa%le in a variet" of siHes an$ st"les# from
- - to 4 4 or even %igger.
This pro5ect uses a 4 4 ke"pa$ *shown in 6igure E.43+ an$ an LC, to $esign a simple
calculator.
/**************************************************************
=OLTMETER :ITH L*D DISPLA?
7777777777777777777777777777
In !his proKe! an L*D is onne!e" !o PORT*' Also, inp8! por!
AN$ is 8se" as analog inp8!' =ol!age !o )e meas8re" is
applie" !o AN$' The miroon!roller rea"s !he analog &ol!age,
on&er!s in!o "igi!al, an" !hen "ispla+s on !he L*D'
Analog inp8! range is $ !o 2=' A PI*/0F12- !+pe
miroon!roller is 8se" in !his proKe!, opera!e" %i!h a 1MHE
resona!or'
Analog "a!a is rea" 8sing !he A"9Rea" )8il!Oin f8n!ion' This
f8n!ion 8ses !he in!ernal R* loJ for A/D !iming'
The L*D is onne!e" !o !he miroon!roller as follo%s(
Miroon!roller L*D
R*. D.
R*N DN
R*2 D2
R*1 D1
R*M Ena)le
R*- RS
This program "ispla+s more a8ra!e res8l!s !han program SE=ENN'*'
The &ol!age is "ispla+e" as follo%s(
m= 7 nnnn'mm
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SE=EN.'*
**************************************************************/
//
// S!ar! of MAIN Program' *onfig8re L*D an" A/D on&er!er
//
&oi" main34
5
8nsigne" long =in, m=,="e,=fra6
8nsigne" har opH/-I6
8nsigne" har i,K,l"H2I,h/,h-6
TRIS* 7 $6 // PORT* are o8!p8!s 3L*D4
TRISA 7 $GFF6 // PORTA is inp8!
//
// *onfig8re L*D
6igure E.4-( A more accurate program
//
L"9Ini!3CPORT*46 // L*D is onne!e" !o PORT*
L"9*m"3L*D9*LEAR46
L"9O8!3/,/,^=OLTMETER^46
Dela+9ms3-$$$46
//
// *onfig8re A/D on&er!er' AN$ is 8se" in !his proKe!
//
AD*ON/ 7 $G0$6 // >se AN$ an" =ref7L2=
//
// Program loop
//
for3664 // En"less loop
5
L"9*m"3L*D9*LEAR46
=in 7 A"9Rea"3$46 // Rea" from hannel $ 3AN$4
L"9O8!3/,/,^m= 7 ^46 // Displa+ ^m= 7 ^
=in 7 100*=in6 // Sale 8p !he res8l!
="e 7 =in / /$$6 // Deimal par! =fra 7 =in \
/$$6 // Fra!ional par!
LongToS!r3="e,op46 // *on&er! ="e !o s!ring in ^op^
//
// Remo&e lea"ing )lanJs
//
K7$6
for3i7$6iD7//6iLL4
5
if3opHiI U7 _ _4 // If a )lanJ
5
l"HKI7opHiI6
KLL6
;
;
//
// Displa+ res8l! on L*D
//
L"9O8!3/,N,l"46 // O8!p8! !o L*D
L"9O8!9*p3^'^46 // Displa+ ^'^
h/ 7 =fra / /$6 // *al8la!e fra!ional par!
h- 7 =fra \ /$6 // *al8la!e fra!ional par!
L"9*hr9*p310Lh/46 // Displa+ fra!ional par!
L"9*hr9*p310Lh-46 // Displa+ fra!ional par!
Dela+9ms3/$$$46 // :ai! / seon"
;
;
6igure E.4-( *Cont2$+
6igure E.43( 4 4 ke"pa$
6igure E.44 shows the structure of the ke"pa$ use$ in this pro5ect which consists of
si8teen switches forme$ in a 4 4 arra" an$ name$ numerals 31J# Enter# :D<# :.<# :&<#
:;<# an$ :9<. Rows an$ columns of the ke"pa$ are connecte$ to P/RT7 of a
microcontroller which scans the ke"pa$ to $etect when a switch is presse$. The
operation of the ke"pa$ is as follows(

A logic is applie$ to the first column via R73.

Port pins R74 to R7L are rea$. If the $ata is nonHero# a switch is presse$. If
R74 is # ke" is presse$# if R7A is # ke" 4 is presse$# if R7E is # ke" J is
presse$# an$ so on.

A logic is applie$ to the secon$ column via R7.

Again# port pins R74 to R7L are rea$. If the $ata is nonHero# a switch is presse$.
If R74 is # ke" - is presse$# if R7A is # ke" E is presse$# if R7E is # ke" 3 is
presse$# an$ so on.

This process is repeate$ for all four columns continuousl".
In this pro5ect a simple integer calculator is $esigne$. The calculator can a$$# su%tract#
multipl"# an$ $ivi$e integer num%ers an$ show the result on the LC,. The operation of
the calculator is as follows( Bhen power is applie$ to the s"stem# the LC, $ispla"s te8t
6igure E.44( 4 4 ke"pa$ structure
:CALC0LAT/R< for - secon$s. Then te8t :Go(< is $ispla"e$ in the first row of the
LC, an$ the user is e8pecte$ to t"pe the first num%er an$ then press the EGTER ke".
Then te8t :Go-(< is $ispla"e$ in the secon$ row of the LC,# where the user enters the
secon$ num%er an$ presses the EGTER ke". After this# the appropriate operation ke"
shoul$ %e presse$. The result is $ispla"e$ on the LC, for five secon$s an$ then the
LC, is cleare$# rea$" for the ne8t calculation. The e8ample that follows shows how
num%ers - an$ -3 can %e a$$e$(
Go( - EGTER
Go-( -3 EGTER
/p( D
Res @ 3-
In this pro5ect the ke"%oar$ is la%ele$ as follows(
- 3 4
A E L !
J 3 EGTER
D M 9
/ne of the ke"s# %etween 3 an$ EGTER# is not use$ in this pro5ect.
Pro5ect Har$ware
The %lock $iagram of the pro5ect is shown in 6igure E.4A. The circuit $iagram is given
in 6igure E.4E. A PIC!64A- microcontroller with a 4)HH resonator is use$ in the
pro5ect. Columns of the ke"pa$ are connecte$ to port pins R731R73 an$ rows are
connecte$ to port pins R741R7L via pull&$own resistors. The LC, is connecte$ to
P/RTC in $efault mo$e# as in 6igure E.3J. An e8ternal reset %utton is also provi$e$ to
reset the microcontroller shoul$ it %e necessar".
PI*
/0F12-
L*D
YE?#OARD
6igure E.4A( 7lock $iagram of the pro5ect
Pro5ect P,L
The pro5ect P,L is shown in 6igure E.4L. The program consist of two parts( function
getke"pa$ an$ the main program. 6unction getke"pa$ receives a ke" from the ke"pa$.
Insi$e the main program the two num%ers an$ the reCuire$ operation are receive$
from the ke"pa$. The microcontroller performs the reCuire$ operation an$ $ispla"s
the result on the LC,.
Pro5ect Program
The program listing for the program .ETPA,.C is given in 6igure E.4!. Each ke" is
given a numeric value as follows(
3 - 3
4 A E L
! J 3
- 3 4 A
6igure E.4E( Circuit $iagram of the pro5ect
The program consists of a function calle$ getke"pa$# which rea$s the presse$ ke"s# an$
the main program. Faria%le )".e" stores the ke" value *3 to A+ presse$# varia%les /p
an$ /p- store respectivel" the first an$ secon$ num%ers entere$ %" the user. All these
varia%les are cleare$ to Hero at the %eginning of the program. A while loop is then
forme$ to rea$ the first num%er an$ store in varia%le /p. This loop e8its when the user
presses the EGTER ke". 'imilarl"# the secon$ num%er is rea$ from the ke"%oar$ in a
secon$ while loop. Then the operation to %e performe$ is rea$ an$ store$ in varia%le
)".e"# an$ a switch statement is use$ to perform the reCuire$ operation an$ store the
result in varia%le Calc. The result is converte$ into a string arra" using function
LongTo'tr. The lea$ing %lank characters are then remove$ as in Pro5ect !. The program
F8n!ion ge!Je+pa"(
START
IF a Je+ is presse"
Ge! !he Je+ o"e 3$ !o /24
Re!8rn !he Je+ o"e
END
Main program(
ENDIF
START
*onfig8re L*D
:ai! - seon"s
DO FORE=ER
Displa+ No/(
Rea" firs! n8m)er
Displa+ No-(
Rea" seon" n8m)er
Displa+ Op( Rea"
opera!ion Perform
opera!ion Displa+
res8l!
:ai! 2 seon"s
ENDDO
END
6igure E.4L( Pro5ect P,L
$ispla"s the result on the LC,# waits for five secon$s# an$ then clears the screen an$ is
rea$" for the ne8t calculation. This process is repeate$ forever.
6unction getke"pa$ receives a ke" from the ke"pa$. Be start %" sen$ing a to
column # an$ then we check all the rows. Bhen a ke" is presse$# a logic is $etecte$
in the correspon$ing row an$ the program 5umps out of the while loop. Then a for loop
is use$ to fin$ the actual ke" presse$ %" the user as a num%er from 3 to A.
It is important to realiHe that when a ke" is presse$ or release$# we get what is known as
contact noise# where the ke" output pulses up an$ $own momentaril"# pro$ucing a
num%er of logic 3 an$ pulses at the output. 'witch contact noise is usuall" remove$
either in har$ware or %" programming in a process calle$ contact $e%ouncing. In
software the simplest wa" to remove the contact noise is to wait for a%out -3ms after a
switch ke" is presse$ or switch ke" is release$. In 6igure E.4E# contact $e%ouncing is
accomplishe$ in function getke"pa$.
/
*AL*>LATOR :ITH YE?PAD AND L*D
7777777777777777777777777777777
In !his proKe! a 1 G 1 Je+pa" is onne!e" !o PORT# of a PI*/0F12-
miroon!roller' Also an L*D is onne!e" !o PORT*' The proKe! is
a simple al8la!or %hih an perform in!eger ari!hme!i'
The Je+s are organiEe" as follo%s(
$ / - M
1 2 N .
0 T /$ //
/- /M /1 /2
The Je+s are la)ele" as follo%s(
/ - M 1
2 N . 0
T $ En!er
L X * /
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( YE?PAD'*
/
P"efine MASY $GF$
P"efine En!er //
P"efine Pl8s /-
P"efine Min8s /M
P"efine M8l!ipl+ /1
P"efine Di&i"e /2
//
// This f8n!ion ge!s a Je+ from !he Je+pa"
//
8nsigne" har ge!Je+pa"34
5
8nsigne" har i, Ye+ 7 $6
PORT# 7 $G$/6 // S!ar! %i!h ol8mn /
%hile33PORT# C MASY4 77 $4 // :hile no Je+ presse"
5
PORT# 7 3PORT# DD /46 // neG! ol8mn
Ye+LL6 // ol8mn n8m)er
if3Ye+ 77 14
5
PORT# 7 $G$/6 // #aJ !o ol8mn /
Ye+ 7 $6
6igure E.4!( Program listing
*Continue$+
;
;
Dela+9Ms3-$46 // S%i!h "e)o8ne
for3i 7 $G/$6 i U7$6 i DD7/4 // Fin" !he Je+ presse"
5
if33PORT# C i4 U7 $4)reaJ6
Ye+ 7 Ye+ L 16
;
PORT#7$G$F6
%hile33PORT# C MASY4 U7 $46 // :ai! 8n!il Je+ release"
Dela+9Ms3-$46 // S%i!h "e)o8ne
re!8rn 3Ye+46 // Re!8rn Je+ n8m)er
;
//
// S!ar! of MAIN program
//
&oi" main34
5
8nsigne" har M+Ye+, i,K,l"H2I,opH/-I6
8nsigne" long *al, Op/, Op-6
TRIS* 7 $6 // PORT* are o8!p8!s 3L*D4
TRIS# 7 $GF$6 // R#1OR#. are inp8!s
//
// *onfig8re L*D
//
L"9Ini!3CPORT*46 // L*D is onne!e" !o PORT*
L"9*m"3L*D9*LEAR46
L"9O8!3/,/,^*AL*>LATOR^46 // Displa+ *AL*>LATOR
Dela+9ms3-$$$46 // :ai! - seon"s
L"9*m"3L*D9*LEAR46 // *lear "ispla+
//
// Program loop
//
for3664 // En"less loop
5
M+Ye+ 7 $6
Op/ 7 $6
Op- 7 $6
L"9O8!3/,/,^No/( ^46 // Displa+ No/(
%hile3/4 // Ge! firs! no
5
6igure E.4!( *Cont2$+
M+Ye+ 7 ge!Je+pa"346
if3M+Ye+ 77 En!er4)reaJ6 // If ENTER presse"
M+Ye+LL6
if3M+Ye+ 77 /$4M+Ye+ 7 $6 // If $ Je+ presse"
L"9*hr9*p3M+Ye+ L _$_46
Op/ 7 /$*Op/ L M+Ye+6 // Firs! n8m)er in Op/
;
L"9O8!3-,/,^No-( ^46 // Displa+ No-(
%hile3/4 // Ge! seon" no
5
M+Ye+ 7 ge!Je+pa"346
if3M+Ye+ 77 En!er4)reaJ6 // If ENTER presse"
M+Ye+LL6
if3M+Ye+ 77 /$4M+Ye+ 7 $6 // If $ Je+ presse"
L"9*hr9*p3M+Ye+ L _$_46
Op- 7 /$*Op- L M+Ye+6 // Seon" n8m)er in Op-
;
L"9*m"3L*D9*LEAR46 // *lear L*D
L"9O8!3/,/,^Op( ^46 // Displa+ Op(
M+Ye+ 7 ge!Je+pa"346 // Ge! opera!ion
L"9*m"3L*D9*LEAR46
L"9O8!3/,/,^Res7^46 // Displa+ Res7
s%i!h3M+Ye+4 // Perform !he opera!ion
5
ase Pl8s(
*al 7 Op/ L Op-6 // If ADD
)reaJ6
ase Min8s(
*al 7 Op/ O Op-6 // If S8)!ra!
)reaJ6
ase M8l!ipl+(
*al 7 Op/ * Op-6 // If M8l!ipl+
)reaJ6
ase Di&i"e(
*al 7 Op/ / Op-6 // If Di&i"e
)reaJ6
;
LongToS!r3*al, op46 // *on&er! !o s!ring in op
//
// Remo&e lea"ing )lanJs
//
K7$6
for3i7$6iD7//6iLL4
5
if3opHiI U7 _ _4 // If a )lanJ
5
6igure E.4!( *Cont2$+
*Continue$+
l"HKI7opHiI6
KLL6
;
;
L"9O8!9*p3l"46 // Displa+ res8l!
Dela+9ms32$$$46 // :ai! 2 seon"s
L"9*m"3L*D9*LEAR46
;
;
6igure E.4!( *Cont2$+
Program 0sing a 7uilt&in .e"pa$ 6unction
In the program listing in 6igure E.4!# a function calle$ getke"pa$ has %een $evelope$ to
rea$ a ke" from the ke"%oar$. The mikroC language has %uilt&in functions calle$
.e"pa$KRea$ an$ .e"pa$KRelease$ to rea$ a ke" from a ke"pa$ when a ke" is presse$
an$ when a ke" is release$ respectivel". 6igure E.4J shows a mo$ifie$ program
*.ETPA,-.C+ listing using the .e"pa$KRelease$ function to implement the prece$ing
calculator pro5ect. The circuit $iagram is the same as in 6igure E.4E.
7efore using the .e"pa$KRelease$ function we have to call the .e"pa$KInit function to
tell the microcontroller what the ke"pa$ is connecte$ to. .e"pa$KRelease$ $etects
when a ke" is presse$ an$ then release$. Bhen release$# the function returns a num%er
%etween an$ E correspon$ing to the ke" presse$. The remaining parts of the program
are the same as in 6igure E.4!.
PR/aECT E.3c'erial Communication17ase$ Calculator
Pro5ect ,escription
'erial communication is a simple means of sen$ing $ata long $istances Cuickl" an$
relia%l". The most common serial communication metho$ is %ase$ on the R'-3-
stan$ar$# in which stan$ar$ $ata is sent over a single line from a transmitting $evice to a
receiving $evice in %it serial format at a prespecifie$ spee$# also known as the %au$
rate# or the num%er of %its sent each secon$. T"pical %au$ rates are 4!33# JE33# J-33#
3!433# etc.
R'-3- serial communication is a form of as"nchronous $ata transmission where $ata is
sent character %" character. Each character is prece$e$ with a start %it# seven or eight
/
*AL*>LATOR :ITH YE?PAD AND L*D
7777777777777777777777777777777
In !his proKe! a 1 G 1 Je+pa" is onne!e" !o PORT# of a PI*/0F12-
miroon!roller' Also an L*D is onne!e" !o PORT*' The proKe! is a
simple al8la!or %hih an perform in!eger ari!hme!i'
The Je+s are la)ele" as follo%s(
/ - M 1
2 N . 0
T $ En!er
L X

/
In !his program miJro* )8il!Oin f8n!ions are 8se"'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( YE?PAD-'*
/
P"efine En!er /-
P"efine Pl8s /M
P"efine Min8s /1
P"efine M8l!ipl+ /2
P"efine Di&i"e /N
//
// S!ar! of MAIN program
//
&oi" main34
5
8nsigne" har M+Ye+, i,K,l"H2I,opH/-I6
8nsigne" long *al, Op/, Op-6
TRIS* 7 $6 // PORT* are o8!p8!s 3L*D4
//
// *onfig8re L*D
//
L"9Ini!3CPORT*46 // L*D is onne!e" !o PORT*
L"9*m"3L*D9*LEAR46
L"9O8!3/,/,^*AL*>LATOR^46 // Displa+ *AL*>LATOR
Dela+9ms3-$$$46
L"9*m"3L*D9*LEAR46
//
// *onfig8re YE?PAD
//
Ye+pa"9Ini!3CPORT#46 // Ye+pa" on PORT#
6igure E.4J( )o$ifie$ program listing
*Continue$+
//
// Program loop
//
for3664 // En"less loop
5
M+Ye+ 7 $6
Op/ 7 $6
Op- 7 $6
L"9O8!3/,/,^No/( ^46 // Displa+ No/(
%hile3/4
5
"o // Ge! firs! n8m)er
M+Ye+ 7 Ye+pa"9Release"346
%hile3UM+Ye+46
if3M+Ye+ 77 En!er4)reaJ6 // If ENTER presse"
if3M+Ye+ 77 /$4M+Ye+ 7 $6 // If $ Je+ presse"
L"9*hr9*p3M+Ye+ L _$_46
Op/ 7 /$*Op/ L M+Ye+6
;
L"9O8!3-,/,^No-( ^46 // Displa+ No-(
%hile3/4 // Ge! seon" no
5
"o
M+Ye+ 7 Ye+pa"9Release"346 // Ge! seon" n8m)er
%hile3UM+Ye+46
if3M+Ye+ 77 En!er4)reaJ6 // If ENTER presse"
if3M+Ye+ 77 /$4M+Ye+ 7 $6 // If $ Je+ presse"
L"9*hr9*p3M+Ye+ L _$_46
Op- 7 /$*Op- L M+Ye+6
;
L"9*m"3L*D9*LEAR46
L"9O8!3/,/,^Op( ^46 // Displa+ Op(
"o
M+Ye+ 7 Ye+pa"9Release"346 // Ge! opera!ion
%hile3UM+Ye+46
L"9*m"3L*D9*LEAR46
L"9O8!3/,/,^Res7^46 // Displa+ Res7
s%i!h3M+Ye+4 // Perform !he opera!ion
5
ase Pl8s(
*al 7 Op/ L Op-6 // If ADD
)reaJ6
ase Min8s(
*al 7 Op/ O Op-6 // If S8)!ra!
)reaJ6
ase M8l!ipl+(
6igure E.4J( *Cont2$+
*al 7 Op/ * Op-6 // If M8l!ipl+
)reaJ6
ase Di&i"e(
*al 7 Op/ / Op-6 // If Di&i"e
)reaJ6
;
LongToS!r3*al, op46 // *on&er! !o s!ring
//
// Remo&e lea"ing )lanJs
//
K7$6
for3i7$6iD7//6iLL4
5
if3opHiI U7 _ _4 // If a )lanJ
5
l"HKI7opHiI6
KLL6
;
;
L"9O8!9*p3l"46 // Displa+ res8l!
Dela+9ms32$$$46 // :ai! 2 seon"s
L"9*m"3L*D9*LEAR46
;
;
6igure E.4J( *Cont2$+
$ata %its# an optional parit" %it# an$ one or more stop %its. The most common format is
eight $ata %its# no parit" %it# an$ one stop %it. The least significant $ata %it is transmitte$
first# an$ the most significant %it is transmitte$ last.
A logic high is $efine$ at -F# an$ a logic 3 is at D-F. 6igure E.A3 shows how
character :A< *A'CII %inar" pattern 333 333+ is transmitte$ over a serial line. The
line is normall" i$le at -F. The start %it is first sent %" the line going from high to
low. Then eight $ata %its are sent# starting from the least significant %it. 6inall"# the stop
%it is sent %" raising the line from low to high.
IDLE
START /
$ $ $ $ $ / $ STOP
6igure E.A3( 'en$ing character :A< in serial format
In a serial connection# a minimum of three lines is use$ for communication( transmit
*TM+# receive *RM+# an$ groun$ *YG,+. 'erial $evices are connecte$ to each other
using two t"pes of connectors( J&wa" an$ -A&wa". Ta%le E. shows the TM# RM#
an$ YG, pins of each t"pe of connectors. The connectors use$ in R'-3- serial
communication are shown in 6igure E.A.
Ta%le E.( )inimum reCuire$ pins for serial communication
J&pin connector
Pin 6unction
- Transmit *TM+
3 Receive *RM+
A Yroun$ *YG,+
-A&pin connector
Pin 6unction
- Transmit *TM+
3 Receive *RM+
L Yroun$ *YG,+
As 5ust $escri%e$# R'-3- voltage levels are at -F. However# microcontroller input&
output ports operate at 3 to DAF voltage levels# so the voltage levels must %e translate$
%efore a microcontroller can %e connecte$ to a R'-3- compati%le $evice. Thus the
output signal from the microcontroller has to %e converte$ to -F# an$ the input from
an R'-3- $evice must %e converte$ into 3 to DAF %efore it can %e connecte$ to a
microcontroller. This voltage translation is normall" $one with special R'-3- voltage
6igure E.A( R'-3- connectors
converter chips. /ne such popular chip is the )AM-3-# a $ual converter chip having
the pin configuration shown in 6igure E.A-. The $evice reCuires four e8ternal m6
capacitors for its operation.
6igure E.A-( )AM-3- pin configuration
In the PIC! series of microcontrollers# serial communication can %e han$le$ either in
har$ware or in software. The har$ware option is eas". PIC! microcontrollers have
%uilt&in 0'ART *universal s"nchronous as"nchronous receiver transmitter+ circuits
provi$ing special input&output pins for serial communication. 6or serial communication
all the $ata transmission is han$le$ %" the 0'ART# %ut the 0'ART has to %e
configure$ %efore receiving an$ transmitting $ata. Bith the software option# all the
serial %it timing is han$le$ in software# an$ an" input&output pin can %e programme$
an$ use$ for serial communication.
In this pro5ect a PC is connecte$ to the microcontroller using an R'-3- ca%le. The
pro5ect operates as a simple integer calculator where $ata is sent to the microcontroller
using the PC ke"%oar$ an$ $ispla"e$ on the PC monitor.
A sample calculation is as follows(
CALC0LAT/R PR/YRA)
Enter 6irst Gum%er( -
Enter 'econ$ Gum%er( -
Enter /peration( D
Result @ 4
Pro5ect Har$ware
6igure E.A3 shows the %lock $iagram of the pro5ect. The circuit $iagram is given in
6igure E.A4. This pro5ect uses a PIC!64A- microcontroller with a 4)HH resonator#
an$ the %uilt&in 0'ART is use$ for serial communication. The serial communication
lines of the microcontroller *RCE an$ RCL+ are connecte$ to a )AM-3- voltage
translator chip an$ then to the serial input port *C/)+ of a PC using a J&pin
connector.
PI*
/0F12-
RS-M- a)le
P*
6igure E.A3( 7lock $iagram of the pro5ect
Pro5ect P,L
The P,L of the pro5ect is shown in 6igure E.AA. The pro5ect consists of a main program
an$ two functions calle$ Gewline an$ Te8tKToK0ser. 6unction Gewline sen$s a
carriage&return an$ line&fee$ to the serial port. 6unction Te8tKToK0ser sen$s a te8t
message to 0'ART. The main program receives two num%ers an$ the operation to %e
performe$ from the PC ke"%oar$. The num%ers are echoe$ on the PC monitor. The
result of the operation is also $ispla"e$ on the monitor.
6igure E.A4( Circuit $iagram of the pro5ect
Pro5ect Program
The program listing of the pro5ect is shown in 6igure E.AE. The program consists of a
main program an$ two functions calle$ Gewline an$ Te8tKToK0sart. 6unction Gewline
sen$s a carriage return an$ line fee$ to the 0'ART to move the cursor to the ne8t line.
6unction Te8tKToK0sart sen$s a te8t message to the 0'ART.
At the %eginning of the program various messages use$ in the program are $efine$ as
msg to msgA. The 0'ART is then initialiHe$ to JE33 %au$ using the mikroC li%rar"
routine 0sartKInit. Then the hea$ing :CALC0LAT/R PR/YRA)< is $ispla"e$ on
the PC monitor. The program rea$s the first num%er from the ke"%oar$ using the li%rar"
function 0sartKRea$. 6unction 0sartK,ataKRea$" checks when a new $ata %"te is
rea$" %efore rea$ing it. Faria%le /p stores the first num%er. 'imilarl"# another loop is
forme$ an$ the secon$ num%er is rea$ into varia%le /p-. The program then rea$s the
operation to %e performe$ *D ; 9 +. The reCuire$ operation is performe$ insi$e a
switch statement an$ the result is store$ in varia%le Calc. The program then converts the
result into string format %" calling li%rar" function LongTo'tr. Lea$ing %lanks are
F8n!ion Ne%line(
START
Sen" arriageOre!8rn !o >SART
Sen" lineOfee" !o >SART
END
F8n!ion TeG!9To9>sar!
START
Ge! !eG! from !he arg8men!
Sen" !eG! !o >SART
END
Main program(
START
*onfig8re >SART !o TN$$ #a8"
DO FORE=ER
Displa+ R*AL*>LATOR PROGRAMS
Displa+ REn!er Firs! N8m)er( S
Rea" firs! n8m)er
Displa+ REn!er Seon" N8m)er( S
Rea" seon" n8m)er
Displa+ ROpera!ion( S
Rea" opera!ion
Perform opera!ion
Displa+ RRes8l!7 S
Displa+ !he res8l!
ENDDO
END
6igure E.AA( Pro5ect P,L
remove$ from this string# an$ the final result is store$ in character arra" k%$ an$ sent to
the 0'ART to $ispla" on the PC ke"%oar$.
Testing the Program
The program can %e teste$ using a terminal emulator software such as H"perTerminal#
which is $istri%ute$ free of charge with Bin$ows operating s"stems. The steps to test
the program follow *these steps assume serial port C/)- is use$+(

Connect the R'-3- output from the microcontroller to the serial input port of a
PC *e.g.# C/)-+
/
*AL*>LATOR :ITH P* INTERFA*E
777777777777777777777777777777
In !his proKe! a P* is onne!e" !o a PI*/0F12- miroon!roller' The proKe! is a
simple in!eger al8la!or' >ser en!ers !he n8m)ers 8sing !he P* Je+)oar"' Res8l!s are
"ispla+e" on !he P* moni!or'
The follo%ing opera!ions an )e performe"(
L X

/
This program 8ses !he )8il! in >SART of !he miroon!roller' The >SART is
onfig8re" !o opera!e %i!h TN$$ #a8" ra!e'
The serial TQ pin is R*N an" !he serial RQ pin is R*.'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SERIAL/'*
/
P"efine En!er /M
P"efine Pl8s _L_
P"efine Min8s _X_
P"efine M8l!ipl+ _

_
P"efine Di&i"e _/_
//
// This f8n!ion sen"s arriageOre!8rn an" lineOfee" !o >SART
//
&oi" Ne%line34
5
>sar!9:ri!e3$G$D46 // Sen" arriageOre!8rn
>sar!9:ri!e3$G$A46 // Sen" lineOfee"
;
//
// This f8n!ion sen"s a !eG! !o >SART
//
&oi" TeG!9To9>sar!38nsigne" har

m4
5
8nsigne" har i6
i 7 $6
%hile3mHiI U7 $4
5 // Sen" TEQT !o >SART
>sar!9:ri!e3mHiI46
iLL6
6igure E.AE( Program listing
*Continue$+
;
;
//
// S!ar! of MAIN program
//
&oi" main34
5
8nsigne" har M+Ye+, i,K,J)"H2I,opH/-I6
8nsigne" long *al, Op/, Op-,Ye+6
8nsigne" har msg/HI 7 ^ *AL*>LATOR PROGRAM^6
8nsigne" har msg-HI 7 ^ En!er Firs! N8m)er( ^6
8nsigne" har msgMHI7 ^En!er Seon" N8mm)er( ^6
8nsigne" har msg1HI 7 ^ En!er Opera!ion( ^6
8nsigne" har msg2HI 7 ^ Res8l! 7 ^6
//
// *onfig8re !he >SART
//
>sar!9Ini!3TN$$46 // #a8"7TN$$
//
// Program loop
//
for3664 // En"less loop
5
M+Ye+ 7 $6
Op/ 7 $6
Op- 7 $6
Ne%line346 // Sen" ne%line
Ne%line346 // Sen" ne%line
TeG!9To9>sar!3msg/46 // Sen" TEQT
Ne%line346 // Sen" ne%line
Ne%line346 // Sen" ne%line
//
// Ge! !he firs! n8m)er
//
TeG!9To9>sar!3msg-46 // Sen" TEQT !o >SART
"o // Ge! firs! n8m)er
5
if3>sar!9Da!a9Rea"+344 // If a hara!er rea"+
5
M+Ye+ 7 >sar!9Rea"346 // Ge! a hara!er
if3M+Ye+ 77 En!er4)reaJ6 // If ENTER Je+
>sar!9:ri!e3M+Ye+46 // Eho !he hara!er
Ye+ 7 M+Ye+ O _$_6
Op/ 7 /$

Op/ L Ye+6 // Firs! n8m)er in Op/


;
;%hile3/46
6igure E.AE( *Cont2$+
Ne%line346
//
// Ge! !he seon" hara!er
//
TeG!9To9>sar!3msgM46 // Sen" TEQT !o >SART
"o // Ge! seon" n8m)er
5
if3>sar!9Da!a9Rea"+344
5
M+Ye+ 7 >sar!9Rea"346 // Ge! a hara!er
if3M+Je+ 77 En!er4)reaJ6 // If ENTER Je+
>sar!9:ri!e3M+Ye+46 // Eho !he hara!er
Ye+ 7 M+Ye+ O _$_6
Op- 7 /$

Op- L Ye+6 // Seon" n8m)er in Op-


;
;%hile3/46
Ne%line346
//
// Ge! !he opera!ion
//
TeG!9To9>sar!3msg146
"o
5
if3>sar!9Da!a9Rea"+344
5
M+Ye+ 7 >sar!9Rea"346 // Ge! a hara!er
if3M+Ye+ 77 En!er4)reaJ6 // If ENTER Je+
>sar!9:ri!e3M+Ye+46 // Eho !he hara!er
Ye+ 7 M+Ye+6
;
;%hile3/46
//
// Perform !he opera!ion
//
Ne%line346
s%i!h3Ye+4 // *al8la!e
5
ase Pl8s(
*al 7 Op/ L Op-6 // If ADD
)reaJ6
ase Min8s(
*al 7 Op/ O Op-6 // If S8)!ra!
)reaJ6
ase M8l!ipl+(
*al 7 Op/

Op-6 // If M8l!ipl+
)reaJ6
6igure E.AE( *Cont2$+
*Continue$+
ase Di&i"e(
*al 7 Op/ / Op-6 // If Di&i"e
)reaJ6
;
LongToS!r3*al, op46 // *on&er! !o s!ring
//
// Remo&e lea"ing )lanJs
//
K7$6
for3i7$6iD7//6iLL4
5
if3opHiI U7 _ _4 // If a )lanJ
5
J)"HKI7opHiI6
KLL6
;
;
TeG!9To9>sar!3msg246
for3i7$6 iDK6iLL4>sar!9:ri!e3J)"HiI46 // Displa+ res8l!
;
;
6igure E.AE( *Cont2$+

'tart H"perTerminal terminal emulation software an$ give a name to
the session

'elect 6ile &U Gew connection &U Connect using an$ select C/)-

'elect the %au$ rate as JE33# $ata %its as !# no parit" %its# an$ stop %it

Reset the microcontroller
An e8ample output from the H"perTerminal screen is shown in 6igure E.AL.
0sing 'oftware&7ase$ 'erial Communication
The prece$ing e8ample ma$e use of the microcontroller2s 0'ART an$ thus its special
serial I9/ pins. 'erial communication can also %e han$le$ entirel" in software# without
using the 0'ART. In this metho$# an" pin of the microcontroller can %e use$ for serial
communication.
6igure E.AL( H"perTerminal screen
The calculator program given in Pro5ect 3 can %e reprogramme$ using the
mikroC software serial communications li%rar" functions known as the 'oftware
0art Li%rar".
The mo$ifie$ program listing is given in 6igure E.A!. The circuit $iagram of the pro5ect
is same as in 6igure E.A4 *i.e.# RCE an$ RCL are use$ for serial TM an$ RM
respectivel"+# although an" other port pins can also %e use$. At the %eginning of the
program the serial I9/ port is configure$ %" calling function 'oftK0artKInit. The serial
port name# the pins use$ for TM an$ RM# the %au$ rate# an$ the mo$e are specifie$. The
mo$e tells the microcontroller whether or not the $ata is inverte$. 'etting mo$e to
inverts the $ata. Bhen a )AM-3- chip is use$# the $ata shoul$ %e noninverte$ *i.e.#
mo$e @ 3+.
'erial $ata is then output using function 'oftK0artKBrite. 'erial $ata is input using
function 'oftK0artKRea$. As the rea$ing is a non%locking function# it is necessar" to
check whether or not a $ata %"te is availa%le %efore attempting to rea$. This is $one
using the error argument of the function. The remaining parts of the program are
the same.
/
*AL*>LATOR :ITH P* INTERFA*E
777777777777777777777777777777
In !his proKe! a P* is onne!e" !o a PI*/0F12- miroon!roller' The proKe! is a
simple in!eger al8la!or' >ser en!ers !he n8m)ers 8sing !he P* Je+)oar"' Res8l!s are
"ispla+e" on !he P* moni!or'
The follo%ing opera!ions an )e performe"(
L X

/
In !his program !he serial omm8nia!ion is han"le" in sof!%are
an" !he serial por! is onfig8re" !o opera!e %i!h TN$$ #a8" ra!e'
Por! pins R*N an" R*. are 8se" for serial TQ an" RQ respe!i&el+'
A8!hor( Dogan I)rahim
Da!e( V8l+ -$$.
File( SERIAL-'*
/
P"efine En!er /M
P"efine Pl8s _L_
P"efine Min8s _X_
P"efine M8l!ipl+ _

_
P"efine Di&i"e _/_
//
// This f8n!ion sen"s arriageOre!8rn an" lineOfee" !o >SART
//
&oi" Ne%line34
5
Sof!9>ar!9:ri!e3$G$D46 // Sen" arriageOre!8rn
Sof!9>ar!9:ri!e3$G$A46 // Sen" lineOfee"
;
//
// This f8n!ion sen"s a !eG! !o serial por!
//
&oi" TeG!9To9>sar!38nsigne" har

m4
5
8nsigne" har i6
i 7 $6
%hile3mHiI U7 $4
5 // Sen" TEQT !o serial por!
Sof!9>ar!9:ri!e3mHiI46
6igure E.A!( )o$ifie$ program
iLL6
;
;
//
// S!ar! of MAIN program
//
&oi" main34
5
8nsigne" har M+Ye+, i,K,error,J)"H2I,opH/-I6
8nsigne" long *al, Op/, Op-,Ye+6
8nsigne" har msg/HI 7 ^ *AL*>LATOR PROGRAM^6
8nsigne" har msg-HI 7 ^ En!er Firs! N8m)er( ^6
8nsigne" har msgMHI7 ^En!er Seon" N8mm)er( ^6
8nsigne" har msg1HI 7 ^ En!er Opera!ion( ^6
8nsigne" har msg2HI 7 ^ Res8l! 7 ^6
//
// *onfig8re !he serial por!
//
Sof!9>ar!9Ini!3PORT*,.,N,-1$$,$46 // TQ7R*N, RQ7R*., #a8"7TN$$
//
// Program loop
//
for3664 // En"less loop
5
M+Ye+ 7 $6
Op/ 7 $6
Op- 7 $6
Ne%line346 // Sen" ne%line
Ne%line346 // Sen" ne%line
TeG!9To9>sar!3msg/46 // Sen" TEQT
Ne%line346 // Sen" ne%line
Ne%line346 // Sen" ne%line
//
// Ge! !he firs! n8m)er
//
TeG!9To9>sar!3msg-46 // Sen" TEQT
"o // Ge! firs! n8m)er
5
"o // If a hara!er rea"+
M+Ye+ 7 Sof!9>ar!9Rea"3Cerror46 // Ge! a hara!er
%hile 3error46
if3M+Ye+ 77 En!er4)reaJ6 // If ENTER Je+
Sof!9>ar!9:ri!e3M+Ye+46 // Eho !he hara!er
Ye+ 7 M+Ye+ O _$_6
Op/ 7 /$*Op/ L Ye+6 // Firs! n8m)er in Op/
6igure E.A!( *Cont2$+
*Continue$+
;%hile3/46
Ne%line346
//
// Ge! !he seon" hara!er
//
TeG!9To9>sar!3msgM46 // Sen" TEQT
"o // Ge! seon" n8m)er
5
"o
M+Ye+ 7 Sof!9>ar!9Rea"3Cerror46 // Ge! a hara!er
%hile3error46
if3M+Je+ 77 En!er4)reaJ6 // If ENTER Je+
Sof!9>ar!9:ri!e3M+Ye+46 // Eho !he hara!er
Ye+ 7 M+Ye+ O _$_6
Op- 7 /$

Op- L Ye+6 // Seon" n8m)er in Op-


;%hile3/46
Ne%line346
//
// Ge! !he opera!ion
//
TeG!9To9>sar!3msg146
"o
5
"o
M+Ye+ 7 Sof!9>ar!9Rea"3Cerror46 // Ge! a hara!er
%hile3error46
if3M+Ye+ 77 En!er4)reaJ6 // If ENTER Je+
Sof!9>ar!9:ri!e3M+Ye+46 // Eho !he hara!er
Ye+ 7 M+Ye+6
;%hile3/46
//
// Perform !he opera!ion
//
Ne%line346
s%i!h3Ye+4 // *al8la!e
5
ase Pl8s(
*al 7 Op/ L Op-6 // If ADD
)reaJ6
ase Min8s(
*al 7 Op/ X Op-6 // If S8)!ra!
)reaJ6
ase M8l!ipl+(
*al 7 Op/

Op-6 // If M8l!ipl+
6igure E.A!( *Cont2$+
)reaJ6
ase Di&i"e(
*al 7 Op/ / Op-6 // If Di&i"e
)reaJ6
;
LongToS!r3*al, op46 // *on&er! !o s!ring
//
// Remo&e lea"ing )lanJs
//
K7$6
for3i7$6iD7//6iLL4
5
if3opHiI U7 _ _4 // If a )lanJ
5
J)"HKI7opHiI6
KLL6
;
;
TeG!9To9>sar!3msg246
for3i7$6 iDK6iLL4Sof!9>ar!9:ri!e3J)"HiI46 // Displa+ res8l!
;
;
6igure E.A!( *Cont2$+
This page intentionall" left %lank
www. newnespress. co m
CHAP T E R L
A$vance$ PIC! Pro5ectsc',
Car$ Pro5ects
In this an$ the remaining chapters we will look at the $esign of more comple8
PIC! microcontroller1%ase$ pro5ects. This chapter $iscusses the $esign of 'ecure
,igital *',+ memor" car$1%ase$ pro5ects. The remaining chapters of the %ook
$escri%e the %asic theor" an$ $esign of pro5ects %ase$ on the popular 0'7 %us an$
CAG %us protocols.
L. The ', Car$
7efore going into the $esign $etails of ', car$1%ase$ pro5ects# we shoul$ take a look
at the %asic principles an$ operation of ', car$ memor" $evices. 6igure L. shows
a t"pical ', car$.
The ', car$ is a flash memor" storage $evice $esigne$ to provi$e high&capacit"#
nonvolatile# an$ rewrita%le storage in a small siHe. These $evices are freCuentl" use$
in man" electronic consumer goo$s# such as cameras# computers# YP' s"stems#
mo%ile phones# an$ P,As. The memor" capacit" of the ', car$s is increasing all
the time. Currentl" the" are availa%le at capacities from -AE)7 to !Y7. The ',
car$s come in three siHes( stan$ar$# mini# an$ micro. Ta%le L. lists the main
specifications of the most common stan$ar$ ', an$ mini', car$s.
', car$ specifications are maintaine$ %" the ', Car$ Association# which has over
si8 hun$re$ mem%ers. )ini', an$ micro', car$s are electricall" compati%le with
the stan$ar$ ', car$s an$ can %e inserte$ in special a$apters an$ use$ as stan$ar$
', car$s in stan$ar$ car$ slots.

Potrebbero piacerti anche