You are on page 1of 58

14,'tu"

200s
Part One
Eigthth Edition, May 2005

Compiledby
U Maung Maung Hyat
ntemvnic Tldning Ccntrc
Romt N o. 44, B$frng N o. 7417a,
Connr { enrwrrfttt met ntd 54n sttltct
Ynngon, Mymnu

fi
PIC ${ierocontroller Course 2OG4 Eleetranics Trairting Centre Fage I

GhapterGne
Things to Rememher
1"f Logic l-evels e.g-
Digital Eleekonics is concerned wiih hvo-skte switch- BitT BitO BitS Bit4 Bir3 Slt2 Bitl BitO
ing iype ciicuits in which the signals are in the form af eiecirical 11010101
pulses shoi.;n in Fig 1. Their ougub and inpuis involve only
f"ve leveis of vcltage, referred tc as'HlGl*i' ancj 'LOW. 't{lGH'is The binary vaiue atposition Bit4 = f
near the suppiy voitage, e.g. +5V and'LOW Is near 0V. 'HlGtl'
is referred to as logic level 'l ( or just 1| and 'LgW' as logic
level 0 {or just 0}. t.3 Decirnal vs Binary
The .rabie shows how the decimai number from 0 to 15
are coded in the 4 bit hinary systern

Decifiaal binary

n 00m
1 0001
Fig.l-l logfc f evefs
2 ffi10
0011
HIGFi =logie f =1=$uFplyvoltage
LQW
4 01ffi
=LegicS=0=0\f 5 0101
o 0110
1.2 Bib
- lt is necessary tc uriderstand the concept of a bii i shctt 011r
form cf binary digit i. A bii is e singie part of an eiectronic inemory I lGOC
,'rrhich can be set io one of two states either to logic 1 or logic 0. o 1001
4,menrory iC can have any number ol bits contained '10
within ii.
1010
11 101"1
'1 nibbie=4bib 12 11m
2nibbles=8bib= I byte IJ 1101
14 1110
210=1024=1k 4fi 1111
fi24k= fi24xfi24 = 220 =
jM

e.g. l kbit = 1024 biF 1.4 Einary te Becimal Conversion


1k byte = 1024 bytes = 10?4 x B blts t4$Bbhb
Each digit posltion has a vaiue or'weight'.
The status sf the bits i ilicH or LOW i wittrin a binary Slnce oniy tvra digits are used in binary system, *"he weights are
urord is expressed as a binary number reading frem leftto right, pawer of 2 insiead of 1 0. Thus r.ieigh& are 2n , 2\ ,22 ,2:'. and so
in order +f the bit representlng the highest value fiist i Mcst
Signiflcant tsii - MSE i down to the lovrest value i Least Ife d+cirnaf eq#ivalenf of * &inary n umber eguals
$lgni,"icant Bit - l-SB )- lfie sos? of all &rlrary digr'fs ,naltiplied by ffief wefgFfs"

e.g. Tc cor:vert a binary to its decirnal equivalent:


MSE LSB 1. W'rite ihe binary number=
11000111 2. tr*riie the vaeighG 1,2,4,$,16 under the binary digit.
3. Grass cut any weight under 0
4. Add the ren:aining weight.
The bits of a blnary word are referred to by the position
within a word, position 0 at the right, ascending as high as
ExaruEIe,1
necessary depending on the word lengi.h.
Thus one byte word has its bits num'oered as 7, 6, 5, 4,
3, 2, 't . and 0. A I 4 -bit wcrd n'ouid be numbei'ed from 1 3 ia S.
11'r 010
The use of 0 {zero} as a bit nunrber is essential to remenrber
643?16S42
when prograrnming PlCs
=64+ 32+ 16+ 0+ 4+ 0+
= 117
P3fl hdics'ocontro!len ecurse 2004. ffimrmpfrfled by [J Man"lng ft4aunE Myat Fage 2

., '1.5 Decinnalto Binary Converslon 1"7 Hexadecimal to Decimal Conversion


There are two ways to convert a decimal number A hexadecimal number can be converted to its declmal
equivalent by using the fact that each hex digit position has a
1. Repeated Division weight that is a power of l6 The LSD (Least Significant Digit)
It requires repeatedly dividing the decimal number by 2 has a weight of 16r =1, the next higher digit has a weight of
and writing down the remainders after each division until a quo- '161
= 16, 162=256. and so on
tient of 0 is obtained
-- Convert 2AFH to decimal

hex2AF
+1 weight rc2 161 160
+0 = 2x256 + 10x16 +15x1 =687

+0
1.8 Decimal to Hexadecimal Conversion
+1 Decimal io hexadecimal conversion can be done using
+1 repeated divisior by 16

25,r= 11OA1, - Convert decimal number 423 to hexadecimal equiva-


lent

2. Quickerway
The decimal number is sirnpiy expressed as a sum of
powers of 2 (weights) and then 1s and 0s are written in the
api:i-opriate bit positions +7
+10 =A
25,0= 16 I 4 2 1
+1
= I 1 0 O 1,
423 ,o = 1A7H
1.6 Hexadecimal Nurnber System
The hexadecimal system uses base 16 lt uses the dig-
rts C through 9 plus the letiers, A, B, C, D, E, F asthe 16 digit 't .$ hlexadecimal to Binary Conversion
symlrols lt is important to renrember that hex digits A through F To convert a hexadecimal number to a binary, convert
are equivaient to the decimal values 10 through 15
each hexadecimal digit to its 4-bit equivalent

Hexadecimal Binary Decimal ExaEpie


: Convert 9F2 to binary
n 0000 0
o F 2
1 0001 1
a 1 001 1111 0010
2 001 0 z
4
3 0011 J
9F2H = 1001 1111 0010
'4 0x00 4
f,
0101 5
6 0110 6
a 1.10 Binary to Hexadecimal Conversion
7 0111
The binary number is grouped into groups of four bits.
1 000 I and each group rs convefted to its equivalent hexadecimal digit.
q '100'l 0
A 1010 fn
Example
B 1411 11
- Convert 101110100'110 to hexadeclnial number
1100 12
D 1101 13 1011 1010 0110
E 1110 14 BA6
F 1111 15
1.11 BeD Nun-rbers
Binary-Coded-Decimal (BCD) num bers express each
decimal digits as a nibble For instance, decimal 2,945
convefts to a BCD numtrer as follows

2945
0010 1001 0100 0101
uovf, ,rr, = gbt+
rfne.rnorS cz)L
{lt'p {Lg -s -. I bt{ shtc , Bf r$, ,A {o, qbt+
-t woY{ = btma15 (2,, tr + ,,^to,L
Re-Xtetev s -+ 1Y'+ 4 ft+ fl"p " rc!.f {Pfr tqbit oo-oottt +,*orl.
an*a* of I J.t
) Bbi+ reJt t rcbLl -> ,;

PEC Micrsc$ntroller Course 2O04 Eleetrenics Trainins Centre Fage 3 \


-rJ 5 s;r1H:

'!.12 Memory Word size = 14 bits


Number of rruords = 1S24
The men:ory is a device foi'storing binary data on a long-
Addsess:
sands of each A binary numberthat identifies ihe iocalion of a ward in menicr.ot,
types Each rvord stored in rnemory has a specific
binary address.
large amounb of binary data Address are aiurays expressed as binary numbers, but
tftey are freguently repi'esented in hexaciecirnal in PICs,

eterrnines which bii(s) binary F{ev Bit position


store data in, or output eiaia trom.
'"ve '+sant to addres$ address 7 p E
The sto*ng and oirtor-ttting of data from menrot-ies is
ccnventionally referred to as WRITING anc READING respec-
tivety.
8000 0000 00h { n l
0000 00s1 CIth '! 1
Terminology
$HT : Folce to make a bit positicn to HiGH ( 1 )-
CLEAR ; Fcrce to make a bit pcsition ro LO\& i 0 ) 0000 001 s uln 4
I t
ln PIC orogramming a slngie command v;ill cietermine
the s*.afus o{ any individual bit. Each bit can be set to HiGH ar 000$ c01 I s3h I 1

LOW by a single commanci.


: A devrbe or eiecfnca,f circuit capable of sfonng 0000 0108 04h U u
a sr,'gle binary digit; 0 or 1.
A fiio-flop is a i bit memory cel!. 0000 0101 05h 1 {

l
0CI00 0110 06h t 1
tI
lf rnemcry ce!!s are organized in groups they can be
used tc store a number of bib. For insiance, a registerccnsisting
00c0 0111 07h U U 0
of eight flip-ilops can be conside!'ed to be a memcry that is
storing an I bit word { a byte ) ln this case the mercory ".vord
size is 8-bit. Pcpulalriord sizes for tabi* illustrates a small 6 v*'ci-d memory. Each of these
This
rnicrocomputers are 8, 16, and 32 bits.
ward has a specific address.
!n a microconrputer tite addresses are issued by ihe
Word size = number cf bits per word
mrc!'oprcc6ssor.

fily{e.' A ssecial term used fof sn 8-bit wo.rd- A byte or S bit is


Nurnber of memory locations = Number of ivords = I
Wordsize =8bit=1b]4e
the most common word size in mi Casaciiy * I byie

:
Vclatile Mernory:
A way of specitying how many bib can be stare in a Any fgpe of memory ihai requires the aopiication of elec-
partlcrrlar memary device of ccmpiete n1emcry +*ical povrer rn crder to stoi-e inforrnatton. if the electrical power
sYstem' rrto, o[ Rego no' o[ ,ttorL is removed, ali infcrmati+n stsreci in the memory lvili be iast.
Many senriconductor rnemones are volatile.
Cepacify = Nr;nrber af words x word size

Fol exannple, in the PiCi6FB4A, GPR iGeneral l\lon-\folatile M*mory: retains its dab even though he powe;"
Furpose Register) extends ftom address *Ch ta 4Fh. Total is removed fiom the lC,
memcry positions are 68, i.e., number of rvoreis are 68. A 6 bit
binary wcrd can stcre in each positicn. i e., vrord size is I bit
rmer youp rEietnr
Then the capacity of the GFR is
aFtJ
"t
6Sxibyte=68byte
l!, +Y Ypt

Exampte : Suppcse that a memory can store i k of 14-bit wards


!1ftratis fte capaciiy of the n:emory? l4ftat is the vrord
size? Hcw many vrords can be stored?
tnamDvtJ Relo ip, vp 16 |oa>:
Capscity = Nurnber qf wcrcis x word size Rc4t
= 1kx i4 bits 9L
= 1424 x i4 bits 1
I
= 14,330 bits er'L W r;+o
6

oonltoL 1o <o>i\c
tD 9cL ellreqs ta'z3islrr c') sl -P/W to I 1o
:le913zt
lo E4ov i.t Pqt, s+b eAL -- ott i/s pt* ; rp
o

a
c2) 1cl AaLq. to 1'1s PLtt-
tO lo 11s6
PIC Microcontroller Course 2004 Compiled by U Maung Maung Myat Page 4

1.1 3 Semiconductor Memories into an EPROM by applying high voltage signals. Data is erased
There are two main types - Read Only Memories, i.e by shining ultraviolet light onto a transparent window that covers
ROMs, and Read and Write Memories called Random the lC. This process takes about 20 to 30 minutes. EPROMS
Access Memory i e. RAMs ( because they allow random have two rn-ajor disadvantages. First, they have to be removed
access) from their sockets in order to be erased and reprogrammed,
Fufthermore, erasure removes the complete memory contents;
this necessitates complete reprogramming even when only one
RAM (Random Access Memory)
memory word has changed
RAM srmpiy stands for Random Access Memory, and
rreans thai ii takes the same time to access any
ocation (i e all are equally accessible) EEPROM
Mosi semiconductor memories are RAMs A RAM nor- The EEPROM was developed as an improvementto the
mally loses the stored data as soon as the power to it is switched EPROM EEPROM can be programmed and erased in circuit
off i.e RAM is a volatile memory. by the application of suitable electrical pulses. Unlike the
.:. EPROM it may be selectively reprogrammed
RAMs are of two types - Static RAM (SRAM) and
Dyramic RAM (DRAM). ln a SRAM each memory cell consists No matter which non -volatile memory you are using in
basrcally of a bistable (flip-flop) whose contents are fixed ( i,e, your system application, the operating characterlstics are all
.i very similar.
a or 0) until the cell is written into or the power is switched off

The memory cells in a DRAM are tiny capacitors which FlashMemory


become charged but due to leakage currents the charged cells EEPROM had three major problems that did not go away;
have to be'refreshed' (rechargbd) regularly. Refreshing is done high cost, low density, and unsatisfactory reliability. Forthese
automatically by sbme microprocessors about every 2 to 5 ms reasons. INTEL exited EEPROM market and introduced its
A charged capacitor represents a 1 and an uncharged one a 0 replacement - Flash Memory.
Norr-volatile DRAM lCs are now available with inbuilt low-voltage
backup batteries ln the prog d read modes, Flash memory look like
EPROMs in the e ode they look like EEPROMs ln other
ROM (Read Only Memory words, Flash memory adds electrically erasability to EPROM
)
without adding the EEPROM's poor reliability and high cost To
ROMs are semiconductor memories used to provide a
achieve these features, flash memory had to give up the ability
rnrcroprocessor system with non-volatile internal memory
to erase individual locations; instead all locations are erased at
Information in ROM can be read out but not
once in a flash
aLtefed There are several types of non-volatile memory that
car be used in microcomputer systems These are:

Read Only Memory: ROM


Programnrable Read Only Memory PROM
Erasable Programmable ROM EPROM
Electrically Erasable Programmable ROM EEPROM
lrrespective of the type of ROM used, data can only ever be
read out from the device

ROM
fne iOttl is programmed by the manufacturer Once
clata has been entered into the device it cannot be altered
subsequently ROMs are used to store programs and data that
are not to change during the operation of a system. A major use
for ROMs is the storage of programs in microcomputers Since
all ROMs are non-volatile, these programs are not lost when
the microcomputer is turned otf At switch on the microcom-
euter can immeciiately begin executing the program stored in
ROM

PROM
A PROM may be programmed by the manufacturer or
the user. Once programmed the contents of the PROM cannot
be altered

EPROM
The main disadvantage of the PROM device is the fact
that it cannot be reprogrammed An EPROM ma5r be pro-
grammed by the manufacturer or:the user. Dbta is programmed
FIC {vli*rocontreller esurse ?SS4 eompiled by S $fiaung Maung Myat Fage 5

PIC f4 TCROCCITTTTRG LL ERS


Chapter Two
FEardqnrare of FECL6FE4/ PECX6F
Z1 lt$rat is PIC OSCI/CLKIN : Osciilatarcrystalinput
PIS { Peripheral Interface Controller j is a special fype Exiemal cicck source input
of mici'oprocessor calied micrcccnt oiier, which is manufacfured OSC?CLKOUT Csciiiaicrcrystaloi.rtpui
by Ai'rzona lr.tlicrochip- A, rnicrccontroiler is sirnila!' io a MCLR {inv) : Master"Clear (RESET) input
microprocessor but it aciditionaliy ccntains ib olvn prograi'r1 (A.ctir,e LOW)
command code memory, data siorage mennory, bi-directional ir' Programmin g Voitage input
O ( input - cutput i ports and a clock osciliator. [4any RAO-RA3 : Bi-directionai lJO Pott { PORTA }
micrcprocesscrs reguire the use cf additional chips to prcvide RA4.ffOCKt : Bi-directionai ilO Pcrt { POR-IA)
these reqr"ri remenb: PlCs are seif-contained, Cicck input to ihe TtulR0 tinrer/counter
RBOJiNT : Bi-directional l/Q Port ( PORTB )
Externai interrupt pln
The genei'al advantage of FlCs is thai they can
programn'red to oer-form many functions {cr which *iany other
RBi -RB7 : Bi-directional IJO Port { PCRTB i
chips v*oiild normatiy be requireci This not oniy makes for VSS : Graund { 0V j
simplicity in eiecironic designs, bui als+ allov'rs some fun+tions v*_
ui : Positive supply ( +2 0V tc +5 5V )
to be pefcrmed whictr cpuid noi be done using nornui digital
logic chips - i e. circuits for rnrhich. previously, a rnicrcprocessor PlC16F84F. uses CIdOS technology. lt consumes very
v'rouid have been required, little current and is fully static, means thet the ciock can be
sioppeci and all register contenb ''vill be retained
The PlCl6F84A is the device which we shail use
throughouiihis iraining courss. The PtC1SF84 which Micrcchip The rnaximum sink or source current foi' a port at any
describes as their'flash'equivaient i+ ihe PlC16C84. As far as given tirnr is as foilows:
corning tutorlals are concerned, Se two devices can be regarded PORTA PORTB
as being lnt+rchangeabie. You ilay use 'FB4' in place of ihe Sink Current 80r,"4 150m4
'CB4'if you wisn. Source Cui:'ent 50mA 1 00nrA

ly{uch olthe informadan aboi-rtthe ccrnmends which we Suopiy cui'rent is primarily a function of operaiing votfage,
present hei'e is, in niost instances, acpiicable to other members frequency and ilO pin loading and is iypicelly 2 rnA for a 4Mi-{z
of the PIC iamiiy. Once you r:nderstanC a PIC16F84 yor.r shouid clock osciilator. This drops to apprcximateiy 4CpA in the $I-EEF
have no difficulty applying your i<nowledge to cther FlCs. rncde.
Because the cjevice is CMQS, ail inputs must go
There are twc versions of these chips having the suffix - so!-rlewlrere- All unused inpub should be puiled up tc the supply
04 and -10 respecrJveiy. The suffix indicetes ihe rnaximum clock valtage i usually +5V i or connected tc grcund (OVi.
frequenc.v at ychich the chip can be used.: -04 means.4MHz, -
10 means i0MHz You nray use eitherspeed raiing. 23.2 Clock Oscillator
The following four differeni types of cicck osciilators
may be used.
2.2. Hardu*are of PIC!.6F844
RC - ResistorlCapacitor i less ihan l MHz )
The a,.chitecture cf the PiCs are based upon the RISC
iReeiuced' lnstruction Set Computer ) method. \tiith this, the
LD - Lovr Poviercrystal

niirnber of the instructions of the PIC is anly 35 krnds. i 32kHz - ?S0kHz )


!f;- - Crystal or ceramic resonator
( 100kHz - 4MHz )
?" 2. f Fins and Functions HS - High $peed crystal or ceraniic tescnator
{4MHz-20LfHz)
The frecuency sf asciiia$on can be changeci by
changlng R andlci C values Approximate frequency of
oscliiation is shalvn beicw
RA2 RA1

RA3 RAO E u irequenry of


RA4/TOCKI ll OSCI/CLKIN oscilletion

MCLR
o
J OSC2yCLKOUT
o) 1Ck 20pF 625kHz
V"s -Tl Voo '!0k 220pF 80kHz
@
RBUINT A R87 10i( 0.1 pF 85Hz
RB1 R86
Recornended values for R and C : 5k < R (to$k, C>
R82 R85 ZCIpF
R83 R84
PIC Microcontroller Course 2OO4 Electronics Training Centre Page 6

2.2.3 RESET teseL "


The plc 16FB4 has built-in power-on-Reset l0toev 2,Q,
A''Lb R€9eT otfl
"
i POR ) which works when the power is turned-on Manual
Reseting can make as shown in the figure

RA2 RA1

RA3 RAO
!
- RA4/TOCKI !
o 3:fill
osc2/
XTA

OSC2/CLKOUT
'100 \/
v^^
O)
Vrs ,,22oF
ohm
-T'1
vte vDD
@
RBO/INT s RB7 RBOiINT R87
RB1 R86 RB1 RB6
R82 RB5 R82 RB5
RB3 R84 R83 R84

BASTC PIGI6184 SPEGTHGlfl 0lts

35 single-word commands Watchdog timer ( WDT ) with own on-chip RC oscillator


cu,4 ^tK x 14 bit EEPROM program memory ,o;',i tmsl'"Lc Power saving SLEEP functron
'38 x 8-bit generai purpose SRAM registers Code protection
I n-Circuit Serial Programming (ICSP)
i 5 specialfunction hardware registers GPAW)
64 x 8-bit EEPROM data memory Selectable oscillator options
1000 program memory erase/write cycles (typical ) lnterrupts:
1- million data memory erase/write cycles ( typicai ) External, RB0/lNT pin
Data retention > 40 years TMR0 timer overflow
5 ddta input/output pins, PortA Port B RB4 to RB7 interrupt on change
8 data input/output pins, Port B Data EEPROM write complete
25 mAcurrent sink maximum per prn
20 mA current source maximum per pin Operating voltage:
8O mA maximum current sunk by PortA 2.0V to 6V ( to 5.5V for F84A ) 81 rrnax' e t
50 mA maximum current source by PotlA Power consumption: A
<2mA@ 5V,4MHz ',5
150 mA maximum current sunk by Port B
'1
00 mA maximum current sourced by Port B 15 pA typical@ 2V 32kHz
Total power dissipation 800 mW , SW <1pA typica V
8-bit timer/counterwith 8-bit prescalar CiytQ o)
Power-On Reset (POR )
Power-up timer ( PWRT )
Cscillator start-up timer ( OST )

There are two timers that offer necessary delays on power One is the Oscillator Start-up Timer (OST), intended to keep
:he chip in RESET ,lntii the crystai oscillator is stable The cther is the Power-up Timer (PWRT), which provides a flxed delay of 72

osT gout' 6t ( "@ , tfii 'J nor{- ., tescL 4E o*


I'LPPV "Lg @e'mE ecr,E co.
pwtuT
Izrms r'rn|. t Poe'

ProgYat",t B?o , po*orgol PoP,) osf Pl,dP,i


aftv 4S ct6gcf.oo:

o cyXt,
' hro'i 5
cmE
'.,'L'
Tzne

L.. L

h"o
PIC llicrocontroller Course 2OO4 Compiled by U tlaung Eaung tlyat Page t
2.3 Configuretion p'jc
Pnl.(I duta,or aiJ tltLt.
The lirst thing io underciand is that all PlCs must be corfigured for the applicatcn they are inl€nd€d to control The
CONFIG statement can be used to cantrol ihe connguration tuses of the PIC Such mniguraiion include th6 s6l€ction of

aied at sddrges 2007h of the program memory Address 2OO7h is


beyond the user program memory space snd ftis space can on ly be accessed duiing progEmming Ono ol h6 best ways of
ensLringltl€ PIC can be pmgrrmmed propeny is to incllde ths conliglretion bits inthe sou ecode.
04 P'"itam d9 ati al:
PlCl 6F84A Conliguration litbrd
p.o1'"- ".ni, qS 1e
CP CP CP CP :P ]P ;p wr-rs- l/DTE FOSCI :osco
*. t,\
Lit, " b6,t
tft13 o r bito .ge t
'u,,,
bit 13 -4 bit
on protecton disabled, 0 = All pro
1 = Code
bn3 plimerEnabb bn'1 = disabled,o = enabled
b[2 WDTE Waichdog Timer Enabred bii - 1 = WDT enabted,0 = WDI drsabled
bn1{ toscl:fosco: Oscrlator setecton bilE 1
,2 ' wollll 11

1 e'4 j"( cn ,;. { , f v"n5c $f,o,s1f


nBf ,,'$ ,
,"-o.,trtnt 19
1 F :an{z i,i "r rrr ""ys,f t''$) "-$
Satting ofths conngurdtion data into the PIC istreated as one programming operaiion Sendingthe program is the
another. ltis Elso possible with some progranmers io'eflbed'he configuraiion code inio tr\e program ibof.l^/hen be
program is s€nttotle PlC, he connguraton isthen automatically set as requi.ed.
lfyour PIC has been used berore in some other applicaton, you should cjear its exisling program and dah EEPROM
contents by usinq ERASE'prosram-
o,itb't Vsqt, orc t.stl ,yS
Exampl* of confi guralion :

1 - enable, WDT - disable, cP - OFF, Osc-LP _CONFIG


F /VRTE H 3FF0'
zoot
2 PWRTE - enable, WDT- disable. CP -OFE osc-XT _CONFIG H'3FFI i
3 PWRTE - €nablo, WDT - disable, CP - OFF, Osc-HS _CONFIG H'3FF2 1
.i,
4. PWRTE - €nable, WOT - disable, cP.oFi
O€C-RC _CONFIG H'3FF3'
5- P\4RTE -enable, WDT-eneble, cP - disable
psc- LP =:3FF4, osc- XT == 3FF5, osc - HS == 3FF5, osc - RC == 3FF7 \,
Attemate way to lmte confguraton

1 _CONFIG _CP-OFF E _WDT-OFF A -RC-OSC & -PWRTE_ON


2 _CP-OFF &, T_OFF E _PWRTE-ON &-XT.OSC
-CONFIG
qrtc.nD
ry
o'otl ai,Lz
' t4 bit
Lo -,ns 7,o, o! .lrorL E tl.
) - @4 ( tmr+raLb:o,tL 6,rt:)
PIC Microcontroller Course 2OOrt Electronics Training Centre Page 8
24 tvtE|VIORY ORGANIZAT|C|TI
FIGURE2li PROGRAM &IEMORY I'iAP
{r/,el,trm0.1rhe'ea.:vonremorvblcci:r.h.PLC16F84AThese
has lsownbls so ihai ac.ess toeach b ock can o
thesameoscl ato cycle D a . tr4+L
p rn.
2.4.1, ",AA,cct
Program Memory Organizati

The Flash menrory is lsed ior the menoryw


tlre prog ar
lhe P C16FXX has a 13 brt progra
capab e of ad.ress ng an 8k x 1.1 progmrn memo
For lhe P|CT6F84A the first 1k x 14 I 0000
are physca y mpemented ( See Fg 2 1)

i lkwords r are rnslalled


Even l swtcres off ihe power sLrppy th
,' .r s st.fed Prcqrarr jrenrot' do notdrsa
n the
..r )leois.iiie Prograrn menory can bewrtter is I
jill the rewrhen number s h red t rs ah.Ln rco
2.4.2 Reset Vector ( 0000h )
t\heothe RESEI sexec!tedbytheturn ng
. lhe other la
pr i!.!r sErts ate. ihe reset t om lh s addess
2.4,3 Per:pheral Interrupt Vedor ( OOO4
Wiren there is the trme-out rnleruplLor of t
TMR0), iire interupton lrorn outslde and so on, th
ihis address
).^? +n Detai explanalions will be given Laler
244 Data Meliory The ptcToFE4ahave 64 b!199lj1r_!_!rE_i-9r_@la
Tre Data Uemory s padnoned lnto two areas The EEPR TheFFpR()r\ri
''si s ihe SpecarFlncto. Reg,s.('. i StF )are: phlethe tt+
:..ona s the Geferal Plrpose Regrsrers ,.a -mJlmohr.3Fh
n and wrrres rhe new.lara ( erase
PIC l,licrocontroller Course 2OO4 Compiled by U fiaung Maung Myat Page 9

2.5.2 PORTA and TRISA r€gisters


FIG{ RE 2'2: REGBTERFILE tlAP.
PORTA is a s-bitwide bFdrrectonal portwth prns RAo
PICI6FB4A
to RA4 Podpins RAoto RA3 ar€ bi-dir€ciional, wher&s RA4
4 eg'+'\t has an open collecior ouhu t PORTA is a fila register at 6ddress
eclioo control r€giste. TRISA is
"i**"] ^* mapped in bankl of a file rcgit'€t at address €5h TR|SAisa
'+r\qPtl
8' 5-bit wicje resisier with bit o to 4 Li,+B)6)+ .or66.o:
TRISA blr = 1 wlll rnate the corEspondhg PORTA as
lnput
TRISA hit= 0 wlllmakethe correspondlng PORTAaS
output r
Sumrnary of Po(A Register

Regisle, name I addess I Power-On-Re€etvalue

PortAloshl---XXXXX
TRt I 85h I -,- 11'-111

X= unknown ;- = unimplemented, read as zero

pottA p,:' ",6 Jlfl 69r 'ilE'ip$.1 .---"'tr)

tr r.nFere. 6 nn-t cla 6. 5 c


,J,l. i tor. ri$-rr c!s:r

25 l/O Porls
-Ihe
PiCl6F€4 has 13 uO pihs organized astwo dis.rete
l/O p.rts PortA ( 5 bit wide ) aod PortB ( 8 bit wide )

2,tl PorlA Functions


)t[".]\-'!P+?i4

Bt

UO, TTL lnpui levels

l/O, TTL lnpdlevels

RA2 l/O, TTL lnput levels

l/O, TTL lnput l€vels

orTMolime countet
lnputisSchmitt
PIC Micrscontroller Course 2004 Compiled by U Maung Maung Myat Page 1O

2.5 3 PottB Functions SummaryofPo Reqistet

Regrstername Power-On-Resel vahre

PotB 06h XXXX X

f.d lli,f tiB0 c l/O pod p n TTL inpLrt levels end


TRISB 86h 11111111
inLernal

, rdmlc rtlt OPTION REG alrt 11111111

?"1 {oa,t O^1ftt 4.14 in oL


l/O poi( pif TTL lnput evels and floaiing np
Pl internal soflware prograrnmable
=. weakpLrll-up
qsl" tn.q i say ]0k!r 10 100ko) or set as oltplts in a o9c 0 (LOW)
2 l/O poJt pin, TTL input leve s and
pdf
"f interna soflwarc programmab e
The Speca Funcion Reg sters are used by the CPU
8+L f.rB3 l l/O porL p.T'lL inplt levels and
and Perpheacalfunctons io controlihe devce
operauon These regsters are statc RAI\1 The SFR canspecry
'teY nternal software programmab e 10 k nds of registers by bank changrng
m'q, ^ Each SFR iras tlre lollowing r!i.Uon

sll "p$b l/O pcrt pin TTL input evels and INDF: Dala memory contents by ndirect
rn iernai sofiwa re programmable
addressng
weak pu lup. Exiernal ntel(rpl TMRo Timercclr'rier
rnput
PCL Low croe. t bns ofthe proqr;m counter
STATUS: Flagolthe.alculanonres!i
rSR ndr r'l . a a IA rof cacre:, po ']le'
5 /O podpin, TTL nputleves and PORTA PORTA dAtA VO
lnternal software p rog €mrnable PORTB PORTB d€la l/O

'
reak pull-.rp :{erta rnterr!pl EED Dala foTEEPRON'I
input EEADR Address olEEPROirl
PCLATH Wlte bLrfier ior upper 5 b is oi the program
R86 6 l/O porl prn ITL rnput levels and
nterna software prog€mmab e
INTCON lnterruptconlro
OPTION REG l,rlode set
weak pul-up Exiern al lnteffLrpt TRISA [,1bde set for PORTA
nput TRISB lr]ode seifor PORTB
EECoNI Conro r€g st€r ior EEPRON]
R87 l/O poi( p n TTLrnput evelsand EECON2 Wnte proteclron reg sterior EEPROT'l
internal software programmable
weak pu I up, Externalinterrupt

2 5 4 PORTa a.d TRISB registers


POR;3 s an 8-b twde bi dreclrona partwtirprns
iigo ic 116i PORTB f e reg ster at address 06lr The
rs a
..rrespond ig dala d rect on reg:ster s TRISB wh ch rs
r.aoped rn bankl ola file regrster at address 86h TR SB ls a
il rrwrde reg sterwth bt0 ro 7

IR]SB b'i = l wrllmakethe conesponding PORTB as


TRISB bit = 0 will make the conespondinq PORTB as
PIC Microcontroller CoBrs€ 2004 Compiled by U MaunE lr4aung Myat Page 11

2.6.1 STATUS REGISTER ( RAM memory add.ess 03h, 83h )


0t)

0 RWO l_ 1
o
IRP RP1 RPO Z DC G

7 6 5 3 2 1 0 Bit.umber

f,

R= Readable biti W= tablebh; -n = value at PORresei;x = unknown

bitT :lRP -NotusedbythePlcl6FE4A,s\ouldbemaintainedcl€ar


bii 6 RP1 -Noi used by the PlCl 6F e4A, sho'rld be mainiained clear
bn5 RPo -Regisier ban k selecl bits (used ior di.ect addresing )
bitS=0meanss€lectBank0,bit5=i means select Ban k 1

Each bankB 126 byres (128x 8 brb )


bit4 :iC - TimeoLdbit
bit4 = 1rAfter pov/er-up, CLRWDT instruclion, SLEEP insirucnon,bit 4 = 0 A hme oiJt
bit 3 :PD 'Pdwe.'down bit
bit3 = l After poweFup or by ttre CLBWOT insirucion, bit3 = 0:tsyexecut,on oflheSLEEP
bit2 Z Z€rcbit
bii 2 = 'l : The r€sulr of an arithme'ic or lag|c operataorl is zerc, bit 2 = 0: The resuli € not zer!
btl DC : DigiicaEy/borrcwbii ( ior boroy/ t'e pclaniy lS reversed )
,

bt1=1:Aca cutfrom the 4tl low orderbnof1he result occu.reci.


brtl = 0 Norcaffy-outfrom 4th low order bit ofthe result
blto C Carry / boror!, bit, (forbofiowlhe polariry is revelsed )
bii e = 1 :A carry-lut lron the most €igniiicant bit of the r€sult occureci
bit 1 = 0 r Nor carry-oi* Fom 1,'r e most signifcant bit oi fte iesult occused

25.2 Vltorking Regi iand File Register

ItJorldng Register ( Vlbrkihg rnernory - SRAM 1 b)'te )


Th€ working register is used to keep fie cal6ulzfion resLli ai iire ALU re mporaily The coitents ol this .egjster are store
in ilre vanous rcgisier and rt is used for the ou! t c.ntrcl oi the inputoutpu porG, too. ( h otler processoc the Workng
regis te. n ay be calied ine Acc! muiaior )

destination Forthe $lorking Register, fie destinaiion is kncv?r as WDRing deginalion


The progrFm comfiands renect the file ancj wo.king desarinations by $e use of F aad W respechvelX in ihe code rtsef
c
tlovF Po?lb , tls
tov| P'RIA;w ---t ," Wy.
a/'e.nblr' - u+nPll''r

PIC Microcontroller Course 20O4 Electronics Training Centre Page 12

at"o,",ln.."
F|ow to Program the PIC

LlSTCommand'rhe list slatementarowsyoutousethe nrlLal


i.i i s coL,rse, we \ir I use Mrcrochrp's I!4PASlvl operanng condilions for the assember ln thaltql siatement
'
assemblerio develop source codefor PIC The prLmary
reason for thrs is ihe fact ihe Microch pAssembier uses
tl.e nsVLctonsilo.Lrmert€d n the l,4icroch p delabooks
.c.rn oown,caa l€e from wlvw mlcroch p com) Radir i:v n9 specifred ihe radrx as deomal, any Lrn'prefxed
va ue e.cclntered by N4PASIVI dur ng assembly w be taken
C.eating Your Code
Atooioiten overooked by beg nners is the edrtor
JSed to develop the source code Yo! can use
Regisier declarations: Use standard regisier declarauons by
NOTE wrndows or [ilS-DOS ED]TOR the l\4rcrcch p nam ng convenions

Laquages:
_CONFIG statemert The CONFIG statementcan be used
Tie lafg!age that you choose should produce to conko the con ngu ratron tuses of the P C These config uratio l
:,,:1.1i rl irc le,'rces r th. P C lne-up Mrc ochrp bts te the P C how to behave on power-Lrp n terrns of whal
. oe |\4PASIM'o .i .5ese)dLtl/whatvoJreqJtre type ofoscrllator s lo be used, whether or
I r,a nrost ;mportanr ad\lce s that oon't p ck one that nottlrewatchdog t mer s go ng to execuie etc
h des the features ofthe PIC microcontroller On top of
understandingthe PIC you also haveto learn the Labels Names when g ven to proqram llstrng addresses are
commonly known as LABELS One thing to note is that the
anguage
Tlrsi column is eserued lo. abels tite commands canrot siai
nrnearslcoLumnoltheirne Plt ng lhe commands on the frrsl
Sample ofthe body of the source file ..unnwrllconiuse IVIPASNI and probably wrll prcd uce errcrs

lMtutT as:r nftra con]ments prograr"n ORG 0 rs kiown as lbe Reset Vector adCress ll s to !h s ?dare.s
.a nes auihors faTne dates and descrplon rrratthe P C tLrmps,,!hen lt:s nlst run orslbsequ€nly RESET
LIST P=16FE4A, R=DEC
CONF]G H 3FFB' ORG 4 s known as ihe lnleirupt Vector add.ess li ls lo tl s
A rylh ng EQU 12 tPLrtrntneregster adoress that PIC turnps rf an nl€nlpl occurs The sublectot
ntetr!plwrllbe deaitw tlr aterlutorlals lgnore the concept,'.r
CPC C Reset;ectoraddress
GOTO 5 :Goto prograrn memory ORG 5 is the stad of the proglam rnemory, e tsihefrsi
..auori (address)5n ava lable pos lion w thin the PlC atwhch the actua: progranr
ORG 4 lntefiupt vector ad d ress
GOTO 5
ORG 5 tstart ofthe program memory GOTO command srmply ie s the PIC io go to the address sht€d
Ihe address c€n be any chosen by the program wnler
-CLRFAnylhng Clearihecontentscl Yo! will notrce lhal the addrcss th. 2h and 3h ate rcl
i:r. AnJ,lhing reg ster netcned These are rcserved by the Plc and are nol ava ab e
tcrnoma program lse

END On@ yo!r so;rrce prcgram s complete tle ast line rs an-
EllD'staiement Thlsstatementtells l,4PASl/lthatiireprcgram
END

Keep this fohat whenever you write a program.


Numerical Prefixes and radix
There ere fo!r fonnats thatcan be lsed toexpress
^Lirr .al!a1,.res i a p'o_olam

comments C.mre.ls i:!sr avrays be preleeded by a Decrnal DC,D12 D55


ri i.ao.ir,, so rf at ine assen[' er ooes not fy ro t.€ar them
;lexadecrnrel ll'00 H0.4 H05 HFF
as program cornmands comments may appear anywlrere
or0100.0x04 0x05.orFF
vritrn the program and rn anyposrtron where they do not
Binary 8'00000000, 8 00000T00 8 00000101 .

:_ierlerew(h a prooram command 811111111


ASC C 5
Page 19

Chapter Fo$r
Tutorials
m Commands
ma TUTORIALl
,I€LRF Charf
i3l{TUil ASu
:Selting Pod Bio ouiput mcd€ and turn on an LED

6F84A R=OEC
fis the address ofFile rcgister rctF 3F;3
( 00h to 7Fh ) iCP-OFF WDT'DlSAtsLE, PWRTE-ENABLE. OSC-RC
,-/(,rdd i r,lti ryolT
ORG0
OperaSon This command cfears the contents
rcgister and it sets Zflag
offle
uc I
n''
FIAg !tsetstheZiag,l.e-Z= 1
'h- \'' tl-cl U"
dt '(^"-
\' 'l
cvde @m.Z.ar4 tl e,xrqb.
lnstruclion !
' ^16 $ cLRFoa- drRf 5
b'ff, c5cto faof-o$ BSF 3,5 ;Sei bit 5 of STATU S regjster, io

2€CF gitClearf

lLabellBCFf,b
label is omitable.
fis the address ofFile register
( 00hto 7Fh ). b = bitposiiion 0to ?

Operaton Thls command clearsthe specified bit El.D ;end oiihe prosram
(make LOW) offle register.

Flag Nochanqe

lnskucton

3€SF BitSetf
o
llabel) ESF lb -n
labelis omitable
fis lhe address ofFile register
( 00h to 7Fh ), b = bitposition 0 io 7

Operation This comfilandsets the specified bit


(make HIGH) brf !e reilister.

FIag No change

fnst-uclion

Test Ciroit for 3MTUT1


PIC M icrocontroller Course 2{)()4 Elec*onics Training Centre ?age L4
Nnll1L,s in Dlace of n!mbors
, i rie p.--!:D!s i.ltor i., we we€ !s ng nLrmbe s 1o PORTB EOU6
progr.m ocaton 6as PORTB
1. care rhrch Fi e Regrsler was be n9 reffered ro As we naJne
pro!ress w th eiair n f9 ihe PlCl6FSr nsLrlctons anc
LOOP]T BSF PORTB O

Lets exam ne how names ca. be:ppried to the


numbeied F e reg sters n Tu(onal 'l Cornpare Tliofal 1 ! lh
,!.oraL2 - GOTO LOOP I
Any flnroerwr llen rnto a sirng can be represented go to address that LOOPITpo ntA

n tne PIC data books s!ch name as STATUS and PORTB ihat addrcsses number has been noled and each tme the
assern bler encounieE a conrmand refercnce to the addrcss
named LOOPIT tSlbstitLtes the number oflhat address
3'g"aa(&u{
4DEFINE
Define a te* sirbsttutng abelorcommand
Syniax
8SF35 BSF STATT]S 5
#DEFlll€ < name > <va:ue>
RSF DoFlB0 * hot"!,
One concept thai ycu are likeiy 10 see n P C son\rae
Eeo + Case Sensitivity
The nar.es are case sensrtve n otherwords on.e
s li.Fl oide1 n n9 a frcqlerly ! sed conrnaid Jorma( as a
s ng e name Each trme lhe assembler encouniers thar name
etojraaf,?*.. lave eq!at€{r a name wlh a Nlirnber i!nher !se oithis d!fng assembly. tl-re denned command will be substiuted rl

.::i:p e. PCRrB end portb canior ae,ised rite.cia.ge.by Ev€mpLe


#DEF NE BANKOBCF STATUS 5
Directiv Lanouaoe #DEFLNE BANKT BSF STATUS,S
cd* sanattt'.
" 15-s-,^;".
+. r s:!ra.
neEe,nsrr-cuon>are
\jFA.r/rrcrhi TUTOR{AL2
c."4 'i^...,,.1:-r.
.,:].t v.!'.. ror!.i iire .f 3IM TL]T2 ASM
--,ai o. ni u e ass-pmb er
e^'ri".' Sei*rg Port B to outp!r flode and tLrm on an LED
^'1,
EQu clirective LISIF-16F84A R=DEC
aircd|tc Ec o coNFto ir 3TF3
CP CFF WDT.D SAEIF PWRTE-ENABLE, OSC,RC
1."& Defrne aLr assem b ler con slaNr

A +znbw STATUS EQU 3


1.fu. Syntax < lab€l> EQll <exprcss ons> EOU lJ

lJS EOll l;:tdl.bi Lb.lL


Fxar; -- S IAi- 3 IORTB EOU O ^;hbL
TFSB EQU 6

Tc arlocate a nurnerals !r' th a name EQU drrcctve s used as ORGO


above STATUS s a abei name GOTO5
ORG4
STATUS EQU 3 GOTO 5
Ti,s statement simpry te s MPASI,/] when (assembtes the ORG5
sl.-o nto code, thal ea.h t me t €]les across the rr4re
SI,ATUS \ rs io rep ace t rrto rie .ode by the v:rle !r CLRFPORTB
BSF STATI-;S 5
CLRFTR SB
'\/JIr LrlPASi\4 ail ranes,locatrons i D rectrve CLRFTRlSA
uorf rra rJs I niusL appea, ar ihe head of Lfe program
BCF STATUS] 5
st ng ln the initra izal or b ock
8SF PORTB O

LABELS
END
i\a r cs p.Dlrair strnq addresses
wtr. g !e r to as
r/ !i LOOPIT a,. conimon y kro(n as t.ABEI.S
PIC Microcontroller Course 2OO4 Electmnics Training Centre Page 15
Program Commands ORG O
GOTO 5
4{)ECFSZ ORG 4
DECrease File Skipif Zero GOTO 5
ORG 5
Fo.mat {abe$DECFSZf, d CIRF STORE1
f- address offle registeri CLRF PORTB
d = 0 - store result in Wreg, .tQF PoPl A
d = 1, store resultin File reg BANIfi
CLRF TRISB
Op€ration: This command SUBSTRACTS 1 b CLRF TRISA
lhe contenb ofthe Fileregister, ifthe result is do
EANKO
^5
zero skip lhe next instuction.
BSF PORTB. O -'s"{ -, Vult"'\
Flag: No c+lange
DELAY NOP
)
bECFSZ STORE1. F
lnshuctbn 1 cycle;when skipping, itis 2 cycles @TO DELAY
MF i PoRTB,c

5-GOTO Goio a , gfoc j,5, oet ffry'F nh'+ov{got'


Golo specifi€d addrcss locations
CALL subroutin€ and RETURN
Fornat GOTO k Subroutine
k= literalneH 000h to TFFh Programscao be wfitlen as a series ofsubrcutines\i/hich
can be reac$ed in one ol lhree ways,
GOTO 6n1maDd. or by a CALL command S.'broutnes are a:
Operation: Jumps uncfidilionally tolhe add.ess
imporlEnt pari of any prog.amming, aid * is qlite n6rmal for a
which the literalfeld show program io consisb of a main loop lyhiCt calls up nunerous

FbO: No change \ ihen do['r€ the same p


essing at more than once, ri
makes the processing in h€ io
ofsrb-.ouline Subiouir€s
lnstruction l cyde are very easy to use, and il isjlst a matier oi using the CALL
insi-uction to erterthe subroutne, and some fdrnr of RETURN
inslruction back into the main proqranr 6nce the rou'tine has
6-NOP - No Operaljon -- trad one cycle
Exdnple
Tutorial 3 : },AIN: CALL SU81
gSF PORTE.l
i3MTUT3 asm GOTO l/tAtN
Setijng PodB to outrd mode and tum on an LED ior about sUEr: BCFPORTA,O
RETURN
Crrc-Jtdiagram as shoen rr i-ro4a, 1
;Usin g assembler dlreclives and #DEFINE You simply apply a labei to a subrodin8 and the as-
LISTP=16F84A R=DEC less j/or,j

-CONFIGH'3FF3
:CP-OFF, WDT-DISABLE, PWnTE-ENABLE, OSC RC
#DEFINE EANKO BCF STATUS. 5 The sbrooline must always .ettm ttre processng io the
#DEFINEBANK1 BSFSTATUS, 5
RETLW Do n.t return by lhe instru.tion ofJUMP
STATUS EOU 3
PORTA EOU 5 sEck
TRISA ECIU 5 The slack is lhe memorylvhich stores tjre relrn address
PORTB EQU 6 of the prodram In the progran v/hlch use!; the subrouline, ii
TRISB EQU O jlmps io rhe slbrouline using the instsuclton of CALL At this
EOU 1 time, the return address rs stored in the stack When the
procesjng by the subroutne ends ard bre inslruciion of R5-
TURN is ex€qned, itjumps to the rctum address whrch is Mitten
STOREl EQUHOC-
inthe srack The stack allows acomDination or up to I program
PIC Microcootroller Co{rrse 2OO4 Electronics'taaining Centre Page 16
-m-+ the
']'e , er ite
rne th€ n ne
'er!.. Tuiorial 4
3lvlrUl4asrn
Settrng Pod B to outpLrt mode and ilash AN LED
C rcutdiagram as shown in turona l

TCALL
CALLS'rbrouiine
CP OiF WDT DISABLE FWRTE.ENABLE OSC RC
#DEF]NE BANKO BCF S'AIUS 5
laire ) CALL k
#DEF]NE BANK,] BSF STATUS 5

EQU 3
tioni ltlrfrps tothe subroLlrne EOU 5
,,i/h cr, ir: iere lleld s.afrl EAU 5
EQU 6
Fiag: No.|ang-- EQU O

lnstrLrction 2 ct.l,.s !;i!iqE:------€o!L-!ron'


onai 0
GCTO

6,fiETUIiN GCTO
RETURN fronr subroLrrlne

Formar: liabeilRETURN
€tR-{€RE?
Operation: ,i reiurns unconcii oraly Jror. tfe PORTB
subroutrne tolhe callng point,po fled by the address .IAF PoQ.t A
SETIJP BANKl
CLRF msB
TR SA
Flag: Nochanle BANKI
Go-ic IVIAIN

NOP

NOP
NOP
RETURN u,iih tera lnW NOP
RETURN

i abel) RETLW k, k = Lrerarfie d


\1AIN BSF
CALL IJEIAY
Op€rationr t relurns irom ine s!brourinb to the BCF PORTB O
.al rng po nL, pointed by the acldress n the stack and CALL DELAY
siore literaldata ntothe W register GOTO l!'lAlN

Flaq: Nochange

lnstructron 2 cyc es

cAlL R(itoqN z uylcs


PIC Microcofltmller Course 2OO4 Electronics Training Centre Page 17
TUTORIALs
;Setiing PortB to orltputmode andtum on each LED
:Controltfie runningspeed by VRI

!a
5

Test Circuit for Tutorials 5

LIST P=16F84A,R=DEC
CONFIG H'3FF3' ;CP OFF WDT DISABLE, PWRTE.ENABLE, OSC-RC
#DEFINE BANKO BCF STATUS,5
#DEFINE BANK1 BSF STATUS,5
STATUS EOU 3
PO EQU 5
TRISA EGU 5
PORTB EQU 6
TRISB EOU 6
ORG O

GOTO 5
- ORG 4
GOTO 5
ORG 5
SETUP K1
CLRFTRISA ->
CLRFTRISE _,
KO
CLRFPORTB
LOOPIT BSF PORTB, O<
BSFPORTB,1
BSF PORTB,2
BSF PORTB,3
BSF PORTB,4
BSF PORTB,5
BSF PORTB,6
BSF PORTB. T
CLRF PORTB
GOTO LOOPIT
END
PIC Microcontroller Course 2OO4 Electronrcs Training Centre Fage 18

1o-MOVF Movef
Mo-veeontents ofW register to
For,nat: lt4OVF f.d Fil€ register
f s ihe addrcss of F le regrsier
(00hto7Fh ) tormatr UO\,,\I/F f
o s destrnahon seieci(0 or T ) '=IIe eg \ie. dLoress 00- ,r r,
C;rcrrt;.i: Th:s co,r'fr:i.lfrove (copy )ihe Operaii.nr Th s ccmmand copy the contenls o,
.cnlefrs .j ine F: e eg stei io (he Wregrsier Lo lhe Fi:e reg ster at
selected desl nator sPecried address
d = 0 9orethe resu t rn W
Flag: Nochange
Sto e trre resu i rn F reg'ster
lnstruction r.yce
lfsir!.tion Cycle: I cyc e cycle

!'iieni e.ts,,:L s tJ:zero Z !


14-BTFSS
BitTest f, Skip ji Set
lllore L:rllrar value
to W register Format BTFSSf,b
f= Fie reglsteraddress (00h 7Fh
Fo.mat: I1OVLW k b = bit number
)

k= ltera fre d (00h io FFh)


ope'at,on: rrsc. , .r e.'lrie-pp- el
rc'rd
rlr s command inove the lrte.aidata
bft of the r.egrsier and lfiiequals i
sk p rh€ fexl fstructron

Flagr Nocharge
lnstuuction T cycle lns{ruction 1cl..
Cycle

1z-BTFSC
ilrt lesl i Skrp ifClear
Rotate Left File reg'sterthrough Carry

Formatr FOfMAT: KLF I.O


Bl FSCf,b
' . e;" doorbc' 001-L' l. Fie regrsteraddress
d = desirnahon se ect ( 0 or 1 )
b = bit number

Operaiion: This command command checks the vPE'4(u .


of lhe File regrsterto '1
specifled b 1oi the I r.9 sler. and f 1
brt
nc ud ng
egrr s ! r(rPr
the Carry bi
Fla{lr N..h?nqe d=o Slcre the resu a rn W
C=1 Sloretheresult n F
Irstruction l cyc e
Flag: ll setthe most significant b t ofthe
reoisterio C

anstruction l ayce
PIC Microcontroller Cours€ 2004 Electronlcs Trainlng Centrc Page 19

16{RF TI,TORIAL 7
Rotate RbhtFile rcgbterthrough Cany I3MTUTT ASM
iSsmeprooram asTutons 6, butusins Z naq and RRF
tonnaE KKF r,c icircuit diagran as shown inTubnal5. Speed conEolwith
f = File register address
d = destination select ( 0 o.1 ) LIST P=16F84A, R:DEC
_CONFTG H'3FF3 iCP-oFF, PWRTE-
uPerauoni ENABLE,WDT-OFF, RC OSC
of the File registerto 1 bit
dgltt induding
theCarrybit
d = o : Store the result in lfJ
EOU 3
d= 1 : Store the resuhin F
STATUS
POR'A EOU 5
TRIS,q EQU 5
Fbg: lt set the leastsignifcant bitofthe PORTB EOU 6
reqisterto C TRISB EQU 6
EQU O
EQU 1
TUTORIAL 6
c EQU O
z EOU 2
:3MTUT6 ASM
;-,o pedorm LEDS on FG'IB to light ono at a tm€ and shift
'rp ORG O
Ieft
GOTO 5
:Ci.cuitdiagram as shown rn Tutorial5, Speed codroiwifr
ORG 4
VR1
GOTOS
ORG5
LIST P=16F844, R=OEC
CONFIG H'3FF3'
SETUP BANKl
;cp-oFF, Pll/RTE-ENABLE. IADT-OFF, RC OSC CLRFTRISA
CI,RFTRISB
#DEFINE BANKO ACF STATUS, 5
#DEFINE BANKI BSF STATUS,5
t
BANKO
CLRF PORTB
STATUS EQU 3
EQU 5
TRISA EOU 5
LOOPJ l\,tov 8 10000000'
PORIB
.iRISB
mu6 MOVIF PORTB
ECFSTATUS, C
EOU 6
ECIU O LOOP2
c
EQU 1
EOU O
MovF il;i;;" ? z.o;?"tsl.o
BTFSSSTATUS, Z
GOTO LOO72
ORG O
GOTO LOOP1
GOTO 5
END
ORG 4
GOTO 5
ORG 5
e'-
.i
SETUP BANKl
CLRF
CLRF

BANKO
CLRF
lL
LOOP1 t
2< M{.,F
BCF STATUS, C
LOOP2 RL-F PORTB, F
BTFSS STATUS,C
GOTO LOO72
GOTO LOOPl
END
PIC Microcontroller Course 2004 €lectronics Training Centre Page 20

TIJTORIAL 8
'17-INCF
3L1IUT8 AS[i
Fo.warc/Rc'reise runn nS qht NCrease Frle regrster
C,c.1t Cia:;,, iL as sfosi n-r,rto:ial 5 Set Vil i!
Format: {label} INCF f d
f - address offLle reg ster
LSIP=r6F84A R=DEC d=0 store resuLt nWreS
CONFIG FI'3FF3 d = T store result n File reg
CP OFF PWRTE ENABLE \,!DT OFF I]C OSC
#DEFINE BANKO BCF STATUS 5
Operation: Thrs conmand add 1 to the contents
#DFF!N[ BANKl ASF STATI.IS 5
ollhe i re reJ,:l.rr
sthirls ;ilu : Flag: When esu i:s zerc Z=l.wher
res,,rlt is n3l z€rc Z=0

iatsB fOU T lrlstiuction 1 cycle

EOU 1

c
1 EQU 2 18-INCFSZ
lNCrease File Skip lf Zero
ORG !.
GO|C 5
Format: {labe} INCFSZf d
GOTO 5 f-address of file reglster
ORG 5 d = 0 -store resrlt rn Wreg
d= 1 siore resuli in File reg
SETUP AANK]
_r:itsA
Operationi ThrscoinandADD 1 to
IE Sts the contefls ofihe Fi ,. regrsterfthe resu I s zero
sk o th-a nerl ns(Lr.r .n

;!"- 0
Flagr Nocnange
.
t,r \ Jtr]OVLW
MOWlF PORIR lnstruction 1 cycle whe. sklpping i ls 2 cyc es
BCF STATITS C

MAIN2 POli ll' I

.;FSC STATUS C
co'io IAIN3 1g.DECF
GOTO MAiN2 DECrease F'le "g ster

IrAtNil PORTB F Formatr {label} DECFJ, d


tsTFSC STATUS C f address off! e reg ster
GCTO [44 N2 d=0-siore resultinWreg
GCTO N3
JVIA
d = 1 st.re:esult rn Fre reg

TN!
Operation: Thrs command SUBSTRACTS I l.
the contenis ofihe Fre reg ster

Flag: ll/hef resu t:s zero Z=1,whef


esul rs rclze o Z=0

lnst.ucilon l iy.iE
PIC Microcontroller Cou.se 2004 Electrcnics Training Centre Page 21

SWAPF TUTORIAL 1O

3NITUTT O ASM
Format {abell SWAPFf, d t:nc.ement ofco!nts by pressing a sw tch
f - address offile registeri .Circu tdragram as shown in page 23 brir SA2 not used
i Control the speed by VRT
d= 0
store resutl in W reg,
d = 1 siore resu t tn Fte reg L ST P=16F8.1A, R=DEC
CONFIG H 3FF3'
OpeEtion: This command swaps lower nibbles ;CP.OFF PWRTE ENABLE WDT-OFE RC OSC
wlihtheuppernlbbles #DEFINE BANKO BCF STATUS 5
#DEFINE BANK1 BSF STATUS 5

Flag: Nochange STATUS EQU 3


EQU 5
lnstruction l cyce TRLSA EQU 5
PORTB EOU 6
TRLSB EQU 6
EQU O
i F,OLI 1
TUTORIAL 9 C EQU O
3'\'lT1lT9 ASI\,1 z EOU 2
.B nary !p and down counterc COUNT EQU H'OC'
C rc! tdlagram as shown n Tltaflal 5, Controlihe speed by
ORG O
L STP=16F84A R=DEC GOTO 5
CONF]G H 3FF-3' ORG 4
CP OFI PWRTE,ENABLE WDT CFF RC OSC GOTO5
#DEFINE BANKO BCF STATUS, 5 ORG 5
#DEFINE BANKl BSF STATUS, 5
SETUP BANKl
STATUS EQU 3 IV]OVLW 1
EAU 5 T4OVWF -TRISA
TRISA EOU 5 CLRF TR SB
EQU 6
TRISB EOU 6 BANKO
EQU O
CLRF PORTB
F EQU 1
CLRF COUNT
c EQU O
ETFSS PORTA O
z EQU 2 GOTO LOOP
COUNT EOU HoC INCF COUNT, F
IIOVF COUNT W
ORG O IIOVWF PORTB
_ GOTO 5 GOTO LOOP
ORG 4
GOTO 5 END
ORG 5
BANKl
TR!SA
TRISB
BANKO
PORTB
COUNT
LOOPl I\,1OVF COUNT,W
N]O\1AF PORTB
INCFSZ COUNT F
GOTO LOOPl
LOOP2 t\ltovF COUNT,W
[40\1Af PORTB
DECFSZ COUNT F
GOTO LOOP2
GOTO

END
PIc Microcontroller course 2004 Electronics Training Centre Page 22

clRcL.rlI DlAGR4l\,4 FOti


Trl,,fr;i 1l; xnr 11

6Ao

9Az r /'trDw
'DtLrLL

ITTORIAL,Il
:itTL fl i ASr\,r
Lrsrng trc s$iches cn Poi* .i,. io rrcrease PodB LEO I\4A N BANKO
_of its ( SAC:PA!) ..d'.h..ih. .nc to decrease PodB I ED
colni (SA2/RA2) SA0 takes prior iy +)
; c! Ld agram as s rowr ripage?3 COUNT
c.nlrcl lhe speed ry vR1 SWTCH

LISTP=16F84A R=DEC TESTZERO BTFSC


.oNFl:r | ?fF? GOTO TEST B
\ TJFI PWli :ENABLE. lVDT.OFi- RCOSC BCF SWTCH O
#DFF!NF BANKO BCF STATUS 5 GOTO TEST TWO
#CErl {t BANK' BsF S rAl US,5
TEST D BiFSC swraH.0
s rAruS - EQ! 3 GOTO TISI TWO
irO,tTA rCU 5
-R,SA EOU 5 NC COUNT BSF SWTCH, O
I::iTB EQU O INCF COUNT F
iisB Eo! 6 GOTO a!,'PUT
!\ FO! 0
t:Qtl iE.lJ i 1\.|,IO BTFSC
C FOU O GOIO TEST 28
: !:r'! t BCF SW!I,CH 2
:: if,tl r1.r' I ia GOIO IESIZER3
::f!TarF ao i Fa!) .LS' 2B BTFSC SWTCH 2
CCTl) TESTZERO
JRG !
GCTO 5
.RG 4
DEC COUNT BSF SWTCH,2
GOIO 5
DECF COUNI F
cR(. t CUTPL]T NI]OVF COUNIW
JAN(' l\,1o',l/'rF PCRTB
MOVLW B',0C000T01
GOTO TESTZERO
ivlu/.lri IRiSA
c,ll: TRISB ENI)
PIC Microcontrollol Conrse lrooa Etectronics'fraining Centrc Page 99

Chapter five
REGISTER FILE MPC
List File and PCL
q'r et r
The sr f e forrnal by |,4PAS[,] ,s straqhl

The produciname and velsioi. the assembly


date and lme, and the page number appearat the

Ihe lrst colurnn ol .!mre s conla:ns the


base ad.lress ln memory where the code w be
p:,.ed fhe second co umn dsp ays the 32 b tvalu€

code that wll be executed by the PlCrnrcrc MCU


The fourth column sts the assocrated source f e
lrne nwber lor th s ne The rernalnderof the ne
ls reserved for ihe soLrrce code nethatgenerated

e'rrbeded between the se!rce res, and pedarn to

Thesymbo lable l:sts all symbols def ned in


the program The memo y usage map gives a
graphical represen taUon ofmemory usage X ma s
a lhat s not

; "",llJ1l*r,r6
Thenrstco umn offoL.rrdrg ts s the address
luf
oi program memory wih n the P C atwnrclr the l
sirlcbon \ir' be p aced Note that it starts at 0000
and lhen Jumps ska ght to 0004 the eddress to
whch ORG 4 staler.ent rele6 Code ORG 5states E !rnFrere.!:rs h*
thatLheprooram tselfis to start at iocation 5 (0005).
l'G 1: ,di::h{#]r:i.er
bL:columnhlo wh chhoid the 2-byte code are nor
Ls.d !n1 acommand seicoLrntered lnihs.ese PCL { Prosram counter Lit€ral )
.crmand CLRF PORTA generales the code
The prograrn counier (PC ) specrfres the address of lhe nstruci on to
0r 85
felch forexeclion The PC is 13 btwde The LOW byte ( b i 0 ta bft 7) s
MALN s the nane il ven lo the address at caled the PCL register This rcg ster rs readable and w tabLe The H GH
whrch the comnrand CLRF COUNT has been byte { bitOio blt 12 ) rs ca ed the PCH regsterand s nold rect y readabe
pla@d Durng assembled by l'/IPAS[4, thaiaddress or witabe All lpdates to the PCH reg ster so rhrcuEh the PCLATII regrs-
nlmber has been noted and each trne the
assernblerencc!nters a command L.le.ence to the
address named [,1ALN itslbsnlliesihe number for
12 11 10 6 2 llo
Refeffrng to Lst ng TUT13 the ine reads PCH regisler PCL reo sier
ON18 OIAO CO64 fulAN CLRF COUNT
Nore ihai0C18 in co !mr 1
There s af other sb ternen l:
000c 2818 00038 Gofo MAN
,vo Jno --.t
""L PJ l.&
Now nolethe 18ln colurnn 2 The twovalles
( co lmn In line 64 and co lmn 2 in line 38 ) are
dentcal and ntentonal The address ior whrch
l.4A N stlre relerence name at ocaton(ADDRESS)

(COTO = 28) p!s the address number (=18) lo

The name tllAlN Ls replaced by an acldress value


PIC Microcontroller Coursc 2oo4 Centrc

List File - 3MTUTl2.LST


I!1PASl\4 t3 2C Released 3l!lTUI12 ASM 23-Jan-2004 6 05:21 PAGF 1

eol+ 4wcvaBiai o4 $k mnnm


lrl lCC OBJECTCODE LINE SOURCETEXT
'
.a!, r J|:uE c,!,r cotr4

00001 .TU roRtAL 12 - 3t\,1-iuT12 ASI\,1


00002 Co!ntrng or: a 7-segmen td rsplay
00003

2!07 3FF0 I 00004 L sTP=15F84A R=DEC


00005 _OONFIG H'5F[0' ;CP-OFFPWRTE"ON WDT,OFFCrysra XT,
,OSC, f= 3 2768[It-l2
0006
MOOT +I]E;INE BANKO BCF STATUS 5
OOOOs #OFFINE BANK1 BSF STATUS 5
00009

oooo2
00003
ffill *t
00012 STATUS
EQU
EQU
2
3
00005 00013 TRISA EOL] 5
00005 0!014 PORrA EQU 5
0c006 0c015 TRlsa EQU 6
00006 mfis PoRTB EQU 6
00000 00017 w EQU O
!0001 00018 F EQU 1
00000 00019 c EOIJ O
00002 cw20 z EQU 2
00001 0C02i 61, EQU 1
00020 00022 couNr
bao21 00023 3! .;v'
ce" 00024
aoi, ,' egog' H
otfr2s
2d05 0002ri GOTO 5 o\4* ,4nlnh' '.oAL
aaa27 ORG 4
28tr 00028 coTo
oR5,
5
. nao)o

cic5 tu?" fi65


uco:o
0U031
-r st$'& CLRF ?ORTA
n'un odt
0006 0185 00032 CLRF PORTB
00u7 1683 00033 BANKl ;select bank 1
0008 0186 00031 CLRF TRISB make allPodB pins as o!tputs
ocm 3C01 0ffA5 t\,rovlw 8',00000001
0c0A 0c85 00036 MOWXF TRISA
,-08 1283 00037 BANKO ;selecl bank 0
0ij0c 2A1A 0C038 GOTO NIAIN
00039
moD a7a2 00010 coMAlicDE 3odv,{PCL F ; add Wvalue to PCL
lrdnE U1i 00041 reirw B '11000000' ; 0 common anode codes
000F :}106 a0042 r€Llw B'11111001 ;1
0010 ?/58 00043 reu\i., B 10T 00100 2
cc11 y,4F O0tA4 relNv S 10110000' i3
a,,iz 31'cf,, 03045 B-1C011001
r-4d.1/ ',4
aa 13 3.t5D 00046 retw B 1CC1C010 5
a! 14 3+7C aAuAT rei w B '10000011' ;6
0015 ua7 00048 retiw B'1T111000' t7
0nr6 utF 00M9 retlw 8 i0000000' i8
CL':7 367 00050 €tlw 8 10011000
PIC Microcoxtrolle: Course 2oo4 Electronics Training Centre p.rge 9s
OOTS O1AO OO I\IAIN CLRF COUNT
0019 01A1 00065 CLRF SWTCH
001A 1805 00066 GETKF/ B]FSC PORTA O
OOTB 281E 00067 GOTO TSTPRV
001c 1021 00068 BCF SWTCH, O
001D 2826 00069 GOTO OUTPUT
00070
m1E 1821 OOO71 TSTPRV BTFSC SWTCH, O
001F 2814. AAA12 GOTO GETKEY
0020 u21 44073 BSF SWTCH O
c021 0AA0 00074 INCF COUNI F
at2 0820 00075 MOVF COUNT W
0023 3E06 00076 ADDLW 6
4024 1883 0007 BTFSC STATUS DC
0025 0140 00078 CLRF COUNT
0026 0820 00079 oUTPUT MOVF COUNI W
ac27 3S0F 00080 ANDLW 8'0000111,1'
ao28 200D 00087 CALL COL]ANODE
aa29
latt
0086
;i' ooo
000 I4OVWF PORTB
002A 2814 00084 GOTO GETKEY
' 'u4 000 END
'1M PASNI 03 20 Released 3]\,1TUT12 AStul 23-Jan-2004 6:0521 PAGE 3

SYI!,IBOLTABLE
LABEL VALUE
BANKO
BANKl
c
COIMANODE
COUNT 00000020
TC 00000001
00000001
GETKEY 0000001A
IVIAIN 00000018
OUTPUT 00000026
PCL 00000002
PORTA 00000005
PORTB 00000006
STATUS 00000003
S\4,/ITCH 00000021
TRLSA 00000005
TR]SB 00000006
ISTPRV 0000001E
00000000
z 00000002
16F84A 00000001

t.#f$" Afi.!tAi#'=used,' =unused)

\
Program MemoryWords Used 40 ( X co ,D5

N4essagesr 0 repoded 0suppressed


PIC Micioconirollcr Course 9oo4 Electronics'I'Iainine CeDtr'€ Page ro

VVe nave seen lhatp.os€ns are slorcd as


_-irucli..s rn @nsecltive bytes rr has been shown that
Look-upTables
Ti . ook-up tabre conta ns tabulaled cor-a r.ts or
,.. se byles are rLrmbrirco rr. n zero upwards {see .ra ues \dn.h are derern ned by a vatue set ersewtleie n a

c!,renly belfq proiess€.land therc LSa coLrnterwhr.h had i" pCLrcorsrer


ih,siniormanon the ProqLam Counler- PCI Tab;s deo€nd uoon the use orpcLand the commands
lJnless tol.i orherwise whel' one nslructDn h;s be€n CALL_ R=TLW a;dGOiO lMen a |Ebre is accesseo rhevatue
t:dorm€d, the prog;i,i. :cJn€- is sr.np,y rn.rem:r,led I a atraaoy neto nW6adoer:cpCLa.dcauseslhep.:!anro
;- re of'1 adce.l ro i!\,n.1 'hp n.a:r eo,,sedn'rF instruciion i\ lumpf;6ardbythesax€.umberprograncommanrsasare
[riiormei ,fi W The comn]ano at the rlnp address s then p€.folre/l

changeofaddr€ssofPCL Sildy lhe following progrsm (on y padofthe progra'r s


The p.ogran aclliress niixber hel.l by rh€ PCL can be shourn)
changed, eitherwhen the inslruction ls one such as GOTO or
CALL. ff oy tre user lell,ng it to add anolher literaivalle10 J3]B GOTO IOOP
ilseli The nextrnsuuctioa periormed is th.l a(the add.ess OOOC TABLE ANDLW 15

irr :led to byihe newvalue 000D ADDWF PCL F


r,rilbe see| U/€n thet fihe value 0 saddedictrePCL 000E RETLW O

L lxt lnstrLctial rs sinrpry:he nerton€ on f ho$ever, i re LUoF RETLW 1

;r0 t0 RETLW 5
^sft.tian N bypas..rC (sk,poed)and ihe one bcyonC,r s
gJlF LOOP MOIF PORTA W
c020 CALL TABLE
fcre,.ample: aJ21 fuIO\,1\F PORTB
ItiePCL sstlu,rhenfamE yrtw aJtomat.€ ! Qa22 ooTo LooP
rr.l lne io and rhs rexi rsttu!tonwillbethat:tl3.ard
'lself
i ' .ne after at w b. at ir .ic lr somehow w. rlqve"o
,'1 add i to rhe PCI- wi)le,t rs stili 12 tne liCL !r'ill irlccmts !O2r- END
' .),Jtwlistr aod its c,M.,rarle of i :c rtsell m.irng'14
Tl ,n th,. orcgraniwll :!rnpsr:qirt f:cm 1: (a 1.l,.rnitnqg h ihe aooveerample afler inrtrallsatlon. and before a.y
rsr !p.rs) th€ rnslfl,!tron at 13 ',?l e "L... ur,rl_ca r" .TdGOTOIOOP , .--
Stuoy ! re fo owl.g t:rogrrm i only part ortfe prcqrarn ri)e tablecommands AL lhe irs! comrnand of oop sw tch Caia
ftor PORTA s bro!ght nto W Ihe CALLI€ble command tlrsr
roLrtesihe progmm to the f6Lcommand within the tab e ANDIW
08 tocP I ,vl,.lvLl/v 1 15 Ailhe commandADDu/F PCI Fth€ANDecvalre.er3i r!
OJ i4CVWF PORTB in !ry s a.lded to the PCL and the cornmand wthn ihe i?ble
10 BCF STATUS.C whrch corresponds to lhe newaddress rs pedormed
10
11 LOOP2 RLF PORIS F
12 BTFSS STATIJS.C ,Assu.ne Po.tc contents rs C000001(0lh)
13 GOTO LOOP2
GOTO LOOPl i]J LOOP MOVF PORTA W

l-:isi3r tha r:En: J SrF-as^ ?e !i.. v hat -e tihe.o,rte.6 . W is 00000001( decimal 1)

''' ls i 2! C;_,-- iASLE


ll:.:S co":rn3.- ti,a a.swi, is auromtrtrcally added to I €
ri.r ihc.efcre ,qt lss.r :gaiCLs€dngvarcoi '2 f ger iahe laiue io/ thar setnrg va !e
ihe a,rssre,,s I ue ( i ), L p lrCL has 1 adceo to,t the ? jL
-|ABLE
berone 13 butw I stil aou rs owf va !e of ! to tse i maki.g O-- ANDI,W ]5
'ANDiog ihe cont€nF orw 00ca0cc1) w lh the
r
PCL=,2 lltetul.,arL=
_ia0l)1111r!:...,3:l r:lo00: a c
STFSS STATUS.C
I s comnrard's cJ'eJlii, g ii b,( C ol STATUS is set I lrle = thisv3,ue s -estored rn fV
',f rt ls :Je iher' lhe bli,s sE: aiC hre I ot I're L.utn aLlsller
OD ADIJWF PCL F
-har?C!:12r1 i: I
The comrLara al aodress 13 is sK pped snd the com nan! at tAdo the conte 1is of Wwlh lhe con(enis n PCL and rlsLoreih-"
address 14 ( GOIO LOOPIr pef.ornred
rs
Itbit C of STATUS is noi sei ( la se = 0 ) t\e.
P.L= 12+C+ 1= 13
alzro j3 I
The comman, e3s i GOTO LOOir: rs
PIC Microcoltlolter Course 9oo4 Elecrronics'I-raining Ccntre P agc q.1

,The orig nalcontenls rn PCL is 0D thenihenew!a!ernPCL


PCL=oDh+.lh+ 1 = 13+ 1 + 1 = 15=oFh
Srnceihe PCLlnclemented 1 rn tsef.ihenilre programtumps
ircm ocaton 0D io 0F and the nstrLrclon at ocauon oFh s

RETLW1 W.0000 0001


21 novwJportb,PortB=00000001 22

Tutoriall2 22
Up Counter using 7 segment display
R86

Th s program usesthepush bLrtion(SA0)to ncremenl


theco!nton a7-segment display Theco!ntvaluestore rn a f e
reqster (e g COUNT ) and |r s va !e s incremented bythe
program each Umelhe push button rs pressed The co!ntvalle
rs lsed io ook up a labe to p.k Lip the d sF ay va ue for the 7 Circuit diagram for 3MTUTl2.asm

PodAls used lorsensrng switclr statls PodB ls used


as outpuis io drve 7 segrnent display The requfed c rcLr t s
shown rn PAGE27

;TUTORIAL 12 . 3MlUT12.AS[l
llp Couni ng on a 7'segrnent display CON]CATHODE ADD!\F PCL,F
RETLW 9'00111111 i0
st P=T6F84A, r=dec
RETLW 800000110 1
RETL\'! 8'01011011' 2
CONFIG H'3FFT
CP OFF PWRTE-ON,WDT-OFF CrystalXT OSC
RETLW B'O1OOT111' 3
f= 3 2768lvlHz RETLW B'O]1OO1TO' 4
RETLW 8 01101101 5
#DEFINE BANKO BCF STATUS 5 RETLW B'O1T111OT' 6
4DEFINE BANKl BSF STATUS 5 RETLW B 00000111 7
RETLW B'0T11,11T1' 8
PCL EQU 2 RETLW 8',01101111' 9
STATUS EQU 3
TRISA EOU 5 I\,!AIN CLRF COUNT
PORTA EOU 5
TRISB EOI-] 6 GETKEY
PORTB EQU 6 GOTO TSTPRV
WEQUO BCF SWTCH O
FEQU1 GOTO O]-]TPUT
C EOU O TSTPRV BTFSC SW]TCH, O
ZEQU2 GOTO GETKE'/
DC EQU 1
BSF SW TCH, O
COUNT EQU H 20' INCF CCUNT F
SWTCH EOU fi'21' I\,IOVF COI]NT W
ADDLW 6
ORG O
BTFSC STATUS DC
GOTO 5 CLRF OOUNT
ORG 4 OUTPUT rv . odt
GOTO 5 A 1 l'tr6+)<
ORG 5 CALL COIVICATHODE
I\,1O PORTB
CLRF PORTA GOTO GETKEY
CLRF PORTB
BANK,]
END
CLRF TRISB
[40vLW 800000007

BANKO
GOTO N4A N
l'lal Nl:frocontrotlcr Couse 2oo1 Lle(tlonirs Tr.rining ('crrtrc Page 9s

Tutoriall3 - Up-clown counter us:ng 7-segment TSTPRV BTFSC SWTCH O

display GOTC KE\2


BSF SWTCH. O
NCF COIJNT F
TUTORIAL 13- 3MTUTl3.ASM l\rlovF COUNT W
Countng !p.nd down on a 7-segment dispay ADDLW 6
BTFSC STATUS OC
lrst p=16F84A, Fdec CLITF COUNT
CONFIG H'3FF1' GOTO OUTPUT
lD OrFPWRTE-IN\ /DTaFFCrysta XT Csa
i:3 2768t4H2 KEY2 CTFSC POFTA ,1

COIC TSTPR2
#DEF]NE BANKO ECF STATUS 5 3CF SWTCH 1
#D!F NE BANK' BSi STA]TUS 5 GO-,C OUTPUT
TSTPR2 BTF-SC SWTCH T

a_i !s E-OU
GOTQ GETKEY

EQU
3
5
BSF SWTCH 1

MovLw 1
EOU 5 SUB!,F COUNT. F
IRISB EOU 6 STFSS STATUS C
PORTB r-Qt 6 iO
GO SUBSFT
EOU O GOTO OUTPUT
EOU 1

fQU ! SUBSET INOVLW 9


z EOU 2 MOW\F COUNT
rl] EQU 1
COUNT EOU H2C OUTPUT COUNT,W
Sr/rltTCH FOU ft2r ANDLW 8 0000111r
CALL COIVICATHODE
t\rtoll/\F PORTB
GOTO 5 coto GETKEY
otic 4
GITO 5
END
ORG 5

QLi]i
BANKI
TR]SB 20,AND AND:iteralwith W
[4ov]_w 800000011
TRISA lLabellAN0LWk
BANKO label is onrliable
GOTO k iilera iie d 00h io FFh

Operation Thrs command executes the log c


/lItwl AND operatron ofthe iteral
RETLW B !011T111
B'00000110
data and lhe contents of the W
RETLW
RETLW 8 01011011 rcgisterand the resu tis reialned .
RETLW B 0100T111
RETLW a 01100110
RETLW I01101107 Fag When Lhe result rs zerc Z = 1 (SET )
RETLW B 0111110',1 When the result is notzero, Z = 0
RETLW B 00000111
R!ILW B',atllTl tl
itEILIA B 0'1101111

JI\ aLrll. c0uNl


SWICI'i
I ilarY EII-SC
j clTo
BCF SWLTCI] O
ooTo
PIC i\{icru(Dtrollo Coulsc 2(X}t Elecnoric-s'1-mhilg Cente I'agc 20

21.ANDWF AND Wwith F 24-XOR Exclusive OR literalwith W

lLabellANDWF f,d lLabeli XORLW k


labelisomnable label is omitable.
f= file reg€ter address k:literalfield 00h to FFh
d = 0 for W and d = 1 for File destr
Opetauon This command execrites the exclu
sive OR (XOR) operat on ofthe Lteral
Operation This command executesthe logrc data and the contents ofthe W
AND operation ofthe File reglster
contents and the contents ofthe W
regisier Flag When the resulL rs zero, Z = 1 ( SET)
When the result rs not zero, Z = 0 (
Flag When the result szero, Z= 1(SET) CLEAR)
\Ahen ihe result s notzero Z = 0
lnstirc on cycle
lnstruction 1 cycle .1

2s-XORWF Exclusive OR Wwith f


22-ADDLW ADD literaland W
lLabell XoRwFf,d
lLabel)ADDLWk
labelis omitab e f:file register address 00h to 7Fh
k lilera field 00h io FFh d =destination WorF

OpeEtion Th s command execltes the add t on Operation Th s command executes lhe exclu
ofihe literaldata and the contents of sive OR (XOR) operal on oflhe
I the Wregrsterand the result is le contents of the fregrster and the !V
tained inWreg register

Fag Whenihe byte ovedlows, it seis C Fag When the result szero,Z=T (SET)
(C=1), when lhe 4 b ts of Lower part When Lhe resu t ls not zero Z = 0
ovedows. t sets DC When the resllt
rs zero, itsets z (z='1) lnstructon l cyc e

1 cycle
26-tORLW InclusiveOR literal with W
23-ADDWF ADDF and W
llabel|ORLW k
abe is om table
lLabellADDwFt,d k: iteralfie d 00h io FFh
labells omitab e
f= flle.eg ster address Operaton This command execules the inclu
d = 0 forWand d = 1 for Frle destr sive OR operation of the literaldala
and the contenls oftheW register

Operaton This command executes the addition Flag :


When ihe result rs zero, Z 1 ( SET l
ofthe contents of the W register and Whenthe result is notzero, Z = 0
File register
lnstruction 1 cycle
Fag When the byte overflows, itsets C
(C=1) when the 4 brtsoflowerpari
overflows il sels DC When the result
rs ze.o, it sets Z (Z=1)

lnstrucllon
PIC Mirrccantroller Course 2004 Electronics Training Centre Page 30

29€UAWF SubtractWfromf

flabel]sUBWff,d
labelis omitable- I
l:file registe. address 00h to 7Fh;
l: destjnation select( 0 = W or 1 = F ,t
)

Operdtjcn Ihis colhmand executes the subtJaction


)f the contents o i the W register from
:lre f register

Fiag lvhen the result is posiiive C = 1. Z = 0


Wiren the resull is ?ero. C=1.2=1
When the result is negative C =0, Z = 0

lnsaudion
2E'sUSLW subt'acrWfmm Literal

[LabeI}SUBLW fr
3060lrlF - coMplemenlthe contents ofthe File
k liieraltuid 00h to FFh register

This cDrrmand erecuiesth€ subiraciion ol


the conienjs cf the W reqister ircnl

v,.ften ihe resirlt is posliva C = 1, Z = 0


When tlre resurt is zeto, c=1,Z-1
U/hen the resunisnegative C.C, Z = 0 iI
{

L
n
:

2005
Part Two
Iriqthrh lldrtion. \'1i! 2005

{
i,

€o bl
U Maung Maung Myat
Etectfo , cs I raln tfig Lefltrt

Yangon, Mganmar
7

Programminq PICs in CCSC com 6q u Mau

60
IJIC Microcorltroll cr Couse2ool flcctruricr 1-ra g Centre Pag€ 31

Chapter Six
Timer_Zero and applications

T:mer O (TMRo) - address Olh When used wlih T]\,1R0 the prescaler
The PlC16F84 has ore specla reg ster reserued lor use as an drvision ratios are 1r2 to 1 256 as shown above
IbitTmer,TMR0 li divides its input freq uency by 256 and can ae both iable The prescalercan aternatr\rely be
watlen io and read ftom Note thai f Tl,,lRo rs wrtten to the tirner is alocated for usewlth the Watchdog Trner
nh,b ted kom @!nting for t.!o clock cycles N,{ore lselulthan wring to (WDT), rn n,h ch mode each ofthese rattos s
IMRO s to use lts oliplt as a d vde by 256 counter and then use the
prescaLerto sub-.lLvde ihat rate as required The p.escaer drlrdes its PLC effective y runs at one quairer of the
nD'ri pulses by p.eseitab e powe6 oi i!/c Therc are e g h I possrble lnput clock irequency at prn 16 (OSC1/CLK N)
d v,sion rairos wh ch are set via bits 0 I and 2 (PSO, PSl and PS2) oi lllhen TMRo:s used as an interna Umer, the pu se
il counts also occur at one qlarter of the clock
frequency So lf the clock freq Liency (set by a crysia
OPTION REG
oscllator) s runn ng at 3 2768 N/Hz, TIT4RC wrl
coirnt 819200 Hz and rts 1 256 roll over ratewil be
lBPU INTEDG IOCS TOSE PSA PS2 PS1 PSO 3200 Hz This rate s then d vrded by the rat o sei
into the presca er lf we d ivided by 32, for exarnpie,
BTl 6 5 43 210 we oblarn raie of 100 Hz

bl7 FEE: PORTB pul-up enab e brt In Tl\4R0 mode when the prcscaler roils ove r
1= PORTB pullups are d sabled tozero, a fag is s-at in the INTCON regrster ai Dir2
{-0lE\ -le Fte_Lpl ca l oe nc-^Fo ov c ear ng
blt T0:E {INTCON bil 5) B t T0lF rnusi be cleared
= lnterrLpi on ris nS edge of RBO/ NT prn
1
0 = lnterupt on tal ing edge of RBO/|NT p n
bi5 ToCS TMRo C ock Solrce se ect b t
.,j,ar,tor or cAa-0ck p.
INTCON ( lnrerrupt control ) Register
lnle..upls
0 = lnternel irstruction cyc e clock
An nteffupl may be generated wh ch wilLc.lse
ihe PIC io dro! what t s do ng, take care of lhe rrme,
b14 diaie iask that it reeds to perform n response to the
rnterupland ihen reiurn to wlralltwas doing
M4/ToCK pin INTCCN reglster is used lo goba y enable n-
0 = lncrement on Low{o-High transltlon on ierr!pts and conlrol ihe response to dfferenl nterrrpl
M4/T0CKlprn
bi3 PSA Presca erAssrgnment bit INTCON brt narnes tlratends n E'are nterrl,pl
1 = Prescaier asslgned to ihe WDT -ndb e orls ,|/lp dnr n. ol g
Inieffupt requests wLLl set the coffespondrng rnterrupt
0 = prescala I ass igned io Tl\rlR0
request actve flags, wh ch has a bt name lharenlls rn
'F The requestactve fag musi be reset rn hardvr'are
brt2 -0 PS2- PSo P rescaler mte seleci blt and is not reset aLrlomalce y by the operat on ol the

Biivalue WDT €te GIE TO]F R3IF


BITT
PS2 PS1 PSO

0 0 0 1:2 11 GE Global lNterrupt Enab e b i


0 0 1 1:4 1:2
1= Enabea un masked nterupts
0=Dlsablesalinterupts
0 1 0 18 14 bit6 EEE EE wrlt€ Complele lnierlpi Enabe
0 1 1 1:16 T8
0 0 1:32 T 16 1 = :rabes the EEwf te cornplete
0 1 1:64 132
1 0 1:128 161 0 = Dsabesthe EE wrie complere
1 1 1:256 1:12a
b:is TOIE: TMR0 Overfow lnteft!pt Enable bit
I = Enabes the T[,1R0 interupt
tr' Drsabes ihe Tl"'lR0 nteffLrpt
PIC Microcontroller Course 2004 E:ectronics Training Centre page 32

Registers associated with Timer Zero (TMR0)

bit0

01h

0Bh/8Bh RB]F

81h PSO

8sh PoiA daia direction regrster

b L.! INTE RBO/ NT nteffuptEnabebt DC EOU 1


1 = Enabes the R€0/lNT nieflupi CLKCNT EOtJ H 20'
0 = D sabes tlre RBo/lNT interupt CLKSEC EOU H'2T'
brt3 RB E: RB pon( PortB ) change lnterrlpi
Enabebii ORGO
1 = Enabtes the FB podchanse GOTO 5
nierrupt ORG4
0 = Disables ine Rts lortcha rSe GOTO5
nteffupl ORG5
:rj: T0F TMRCOveil.vlnte Lrp!aaglrt CLRF PORTB
1 . TMRO nas cver owec ( nuslbe BANKl
cLear€d in soflwa'e ) CLRF TRISA
0= T[,,lRod d not oveflow CLRF TRISB
blir iNTF: R80/lNT lnteffuptFlag b t NloVLW B 100001T0'
1 = The RBo/lNT lnteffLrpt occuffed IIOW!f OPTION REG
0 = The RBo/tNT nterupr did rlot BANKO
occurred lrlOVLW 25
!: ir Rll l: RB portcharge lnterrlpt Fag art |\4O\,M/F CLKCNT
'r = when ai reast one of rhe Rts7 15 CLRF CLKSEC
RB.l p ns change state ( m!st be BCF NTCON 2
cleared n software ) GOTO \4A N
0 = None of the RBTto RB4 p:.s
CC]\4CATHODE ADDWF
have clranged stale
REfLW B CC'l]t111 0
rrteruptvecto buili ftothe PlC10F84 is ai
The
RETLW B 0000c1'tc 1

ac,.ress04h t\rhen rnleff!ploccLrs the inre ilptvectof


RETLW B 1110.'10:1 l
RETLW B 0100r11i 3
pc iis io prolrar. rnemory add€ss 04h wlrere tlre f]'st
rsir!clicf cithe rnterrupl serv ce rout ne musl be sto€d RETLW B 01100T10 4
B 0110'1101 5
i3l\1TUT14.ASM RETLW B 011,11101 6
Use ofllrnerw th BCD countinE cn 7-segmeni (singe). I RETLW At000011]' 7
RETLW S t1.11111 3
RETLW B 01101111 :9
lstp=16FE,l4 Fdec
CONFIG H'3FF1 tltAtN BTFSS NTCON 2
Crysta 3 2768MHz XTosc GOTO MAN
BCF INTCON 2
#DEF]NE BANKO BCF STATUS,S DECFSZ CLKCNTF
#DEF]NE BANKl BSF STATUS,5 GO|O l\lAtN
OPTON REG EQU 1 i\tovlw 25
PCL EQU2 I\,1OWVF CLKCNT
S,ATUS EQU 3 LNCF CLKSEC,F
TR]SA EQU5 I,1O!f CLKSEC W
PORTA FOL]5 ADDLW 6
IRiSB EOU6 ETFSC STATUS DC
FORTB EOU6 CLRF CLKSEC
NTCON EOU h'OB I\,lO\f CLKSEC,W
W EQUO ANDLW B OOOO1 ] 11'
F EAUT CALL CO]\T]CAT]']ODE
C EOUO
Z EQU2 GOTO I/IAN
END
PIC Microcontroller Course 2004 Electronics Training Centre page 33

Tab e ADDWF PCL,F


RETLWI..]'77'
RETLWH'7C' tb
RETLWH'58' ,C
RETLWH'5E
RETLWH'79
RETLWH'8E'
RB2 RETLW H 6F' g
RB3 RETLWH 76' iH
RETLWH'06' I

RETLWH'OE' '
RETLWH'38' L
RETLWH'54' n
RETLWH'3F' o
RETLWFl'73'
RETLWH'67' ,q
Tdtorial 15 RETLWH'50' I
RETLWH'6D ,S
3t/tTUT15 ASN4 RETLWH'78'
P'ocl!c nS:etters o.lre 7 seS d spLay
RETLWH'3E' ;U

stp=16F84A, r=dec RETLW H 66 y


coNFtG lr 3FF1'
DETAY NOP
#DEFINE BANKO BCF STATUS 5 DECFSZ STOREI,F
#DEFINE BANKl BSF STATUS 5 GOTO DELAY
DECFSZ STORE2 F
PCL Prcgram co!nler register GOTO DELAY
S-rATL.lS EQU3 STATUS regrster
RETURN
TR]SA EQU5 PodAdlreclron regrsier
EQU5 PoirAdata f,.grster
EOU6 Poir B d reci on reg ster
N1AIN CLRFSTORE3
PORTB EOU6 :Port B data €g ster IMainl I\IOVF STORE3 W
FQUO CALLTABLE
EOIJ 1 MOV!\,F PORTB
c EQUO Caryflaq CALL Delay
z EQU2 Z€ro ia9 CALL DELAY
EOU 1 D gitCarryJaq CALL DETAY
N1OVLW H'FF
STOREl EOU H'20'
STORE2 EQU H 21'
I!1O\,\ryF PORTB
STORE3 EOU U',22 CALL DELAY
INCF STORE3 F
ORGO lovlw H14'
GOfO 5 XORWF STORE3,W
ORG4 BTFSS STATUS Z
GOfO 5 GOTO I!1A N1

ORG5 GOTO l\la n


END
Setup BANK1
CLRF TRISB
EANKO
GOTO Marn

h v+
'
1b 1
FIC icrocontroller Course 2004 Electronics Training Centre Page 34
,17
TUTORIAL

F-r i"J :;
COMCATI,]ODF
RFTLW B 00111111
RETIW 8',00
,B ITL'] LW 8 0101,'1011
RETLW B 0'1 00,'1 1 1 1

IiETLW B 01r g011o


69 RETLW
to RETLI^/ e or rlror
o7 RETLW e ooo{cr r
RETLW B rl 6rr\r
I 6F RE]LW 8 0110;f i

DGSEI Mrr- Dcll.\i: j.y''


.A\DL\^/ 1

t!1o\ A,F oGT


r\)D\,^!r- PC_ F
SF.CTBN
CiCTO L
@TO SECOIiE ,'l
a 1 , tt( 25th I i. o,t
CALL DGSEL
'(Iit liq:rftr lbt Tidorill 17 BTFSS INTCON 2

BCF INTCON,2
l:r4a!lT1 7 A St!]
!!.lliin.r !i i scl rale wtr BcD 10 59 co!rtro of 2 LED 7- GOTO IIIAN
-irqre ri.,sp ayr plrs lr25 Fc cou.ler MOVLW 25
fuLO\'\]\F CLKCNi
NcF clrisEc l:
rstp=16F44A. r=dec [401,F CLKSEC f,,

GOTO ENCT ftI


*l)L:FtN: BAN(oercF StAl US 5 MOI, /"F CLKIjEC j

rmo n$5 '<,


l,O! l2A

tiKsEc .clockseconds FND utvt GOTO MAN


|,l,lf' tQL 1i22 ,7 seiFerldi( ls.lect
",sL1rQor sEciLN
GOTO OL]IPUT
S=COi\li

coTo 5 CALL COI.'ANCI)E

CLRF POR'IA LNCF D]G IW


CLRIJ POR1 E

CLRF TR SA
CLRF TRSB
I
l\rovLvl/ B 1n000 10 o I o ENL)

"'oo I t|t'
lrlOVL\/11 25

clti c.KsEc
CLRF D]GIT

NTC(JN 2
GOTOtrtAtN

Gst$pdad - l{dn
v'

pIC Microcontroller Course 2004 Electronics Training Centre page 35

TUTORIAI, 1R

-{l-=

RB2
:: RB3

22 il RB!
pF !L nes
RB6

<- qAq ol9


ilN to flrl I
gec t

luz 'ecp
8C547 8C547
LA)

PA. 1Mt, QAa, Ua ,ol


r
: 3MTUT18.ASM ,10:04 AM2l1512OO4
Use ol Tr ner with set rate, w*n BCD to 59 colnt ng PcL r,G COX,ICATHODE ?tL '61o'5
rn4 LED 7 seg d sp ays 1111 t0
RETLW B'OOOOOIIIb' ;1
RETLW B'O1O1IO11 2
RETLW BolobTTll 3
lstP=16F84A r=de. RETLW B'O11OO11O
CONF G H'3FF,]'
PWRTE. ENABLE. WDT. D SABLE XTOSC RETLW BO1TO11O1 i5
NCLUDE <P16F84A. NC> 6
#DEFINE BANKO BCF S-.ATUS.5
4DEFINE BANK1 BSFSTATUS 5 RETL0u B'01'r11r1 8
n 1b66 REf6A/ B olr oi l r'j 9
CLKCNT EOU aza e 62s ? 6?C
CLKSEC N21 D Crlw
cLKt/[N EOU d2 ANDLW B'ooodooll'
EOLJ MOW1F DIGII
OIG]T ,ro n- rSt t1 on
ADDLW 2

GOTO 5 GOTO I.]RSTEN


GOTO HRSONE
GOTO 5 60Tc| MINTEN
ORG 5 GOTO NIINONE ,
GOTO SECTEN
CLRF PORTA GOTO SECONE l
CLRF PORTS
&^Nr ' Pt,r t DL5l w M(!F DICTW
uovrw aoonrnnnn e-
idgitl
*Jot" -,., 6G;, r'tt q ' tt- idigil2
" S100001T0-
MOVLW "t
t'' -v' ttut. qit3
";^'^;. :,:' lil .:'"
d
t 't
l'?d^a"rn lJ" id gil.+

P"ANKO
[4ovLw
I.iOW\F CLKCNT
CLRF CLKSEC BCF iNTcoN2 yes
CLRF CLKi/]IN CALL CLXADD
CLRF CLKHRS

(tr)IO MAJN

* 14tU m,;1. AatN a",.5p9 fr1,,5" p.y b"^),1


9dj
PIc Microcontroller Course 2004 Electronics Training Centre Page 36
REruRN

CLKADD DECFSZ CLKCNIF HRSIEN


SVL/,qPF CLKHRS W
t!4OVL\r/ 25 coto ontufT
HRSONE I
MOVF CLKI]RS,W
SECCLK INCF CLKSEC F GOTO OUTPUT
NrcVLW 6
S\\'\PF CLKMINW
BTFSS STATUS DC GOTO OUTPUT
MINONE
MOW\]F CLKSEC MOVF CLK[1]N,W
xoRLW 80n00000 GOTOOUTFUT
BTFSS STATUS Z
SECTEN
SV]IAPF CLiSEC,W
I,IINCLK GOTO OUT PUT
SECONE
'r ADDIM:, CLKMINW IVOr'F CLKSEC W
BTFSS STATUS DC

ANDLW B'OOOO1111
XORLW 96 qA[ COMtrA]I]ODE
BTFSS STATIS Z CLRF FIORTA
t"to\l/!f PoRTB-
CALL DIGS'[A/
IIO\^/\F PORTA
IRSCLK D]G]T,W
'TNOVF
XORLW 1
BTFSC STATUS Z
BTFSC STATI]S,DC BSF PORTB,T
MO!\ lF CLKHRS tyes RE'IURN
, END
BTFSC STATUS Z
CIRF CLKT]RS
7'
, y* ," 11"'ttt1* hq+ ' turw qo.l.t.det fi *nf 4 'l*"' Pen

PIc Microcgntroller Course 2004 Electronics Training centre 37

Chapter 7 4a'f -s,c/".+


How to use Liquid Crystal Display ( LCD ) o) Grofl',r: LD toL rL"

.!menddotrnat r q!.d cDstaldrsp ay (LCDs)

l'a!e buili in controlrers drve6 character seneralor RAl,,l/

LCDs are us!a lycoitro


ed by m crocoitro ers
LCDscome many shapes and sizes buitt'e most
rn
conrmon slhe 16 character x 2 nedlspLay
The LCD dol rnatrx dlsplay module cons sis ol an
LC! pane and controLletc ver circuits t s capable of drs
p,ay ng two nes oi lA characters rt rncorporates
cfcLr ts daia RAl,{ characler generator RAM and characier
geneEtor Rolrl required fordrsp ay This module provdes bolh
€ b t and 4 b t paralle nbrraces and allows ihe coniro ng
m croprocessor to read andwrlte data direcily
Differenitypes of LCDs
Ge eral S pecifications
n
Thefuncuon ofeach ofthe connectlons is
1 Drve nrethod 1/16drty 1/5bias
2 Drsplay sze l6 characters x 2lrnes
3 Character str!.hr re 5r7 dols +.lrsor i Table'1 PinoutFunctions ofan LCD
4 Dlspaydata RAM 80 characte.s (80 x 8 bts)
PnNo

6 Character ge nerator RAI\,'l: 8 characierc ( I x I bds) cA Brt1 1 Ground


7 .slrl.ton fLncn.n seeTabLe 2
2
N/lost LCD modules conform to a standard nlerfac.
3 66p11ss1 <- ad'1.!fa3f
soecrfrcaron A14 pinaccess sprovrded havrngerghLdal:
nes. three corko lines and thrce power lrnes Tie connec- RS Reg sier se ecis
t ons are larJ cr tin one of tvro conmon con[guratLons, 5
,?
e: rer twc rows oiseven prns ora s ng e row ol14 pins The 6
i\'vo lavorta iernanles are d splayed rn Fis 1 7 DO ,L
I D1
I m aiabt2
10 DZ t.t4' ata bt ?lc Portl8i8s
3
11 u Databit4 8 ldil &r wt""o
12 D5 Daiabit 5
',n1,4, 13 a6 data brl6
14 til DaiabtT

The f!nct on oJthe connectrons s shown in Tabe


uz,. ) u5tt
rt9t9 ti lil!!99
g' 5vioov ( l9P 5v )
? pi,. or 4

b€a t{ht v..orv.-- usedlo arerthe contrasiofthe d splay deaily

s]]ltabe in manycases bLribe awarethatsome modLr e nray


requires a negatve voliage, as ow as 7V ln sorne cases

Frg 1 Prnouis of the tr,/o bas c 16 char2 ines LCD


formals

lastUpdated 18 SEP 2005


PIc a L.t P:C F4icrocontroller Course 2004 Electronics Training Centre 3B
Ba
ea+" are rreared as co,nmands, a rd rre d:ia.yrcs ieac r w Lhe ,"- ?:l!,,-::
,._-,_lTbLltalso
thedrspiav :1la c!
determi.ls
so'i mmmand r"ms m
the cLlrsorslvle ar tlre sar.e
p9
i); dspLay ndcates{sstat(s lrme
when Rs ., uiGH character data can be I TosetBlrnkrn! CLrBorwith Underlne
re,red to snd rronr the LCD odrte Set data swfc ].s S1 io SB ro 000011'1'1
Rs =Lr comman.t nrode set RS = 0 (comm.Nil:roie)
RS= I . Cal:entry mode
setE HIGH to LOWand then HIGH
Arasf rgclrsorwth rnder new appear rthetopleft

q
e. ll ea''

nS=0
Se!E- HlGfi toLOWand trren llcl
Ths cor.manddetermrnes 8-brda: 2 ies afd
lic ease conlrastlrtueto vsb e 2lines

3- To enter a character
RS = T (data enty mode )
Set data = 01000001 (4rh ) ihrs s the cod: ior a

Set E--lllGH toLOWarc tre| I Gl

n,,lr|' ry
. rn,l .(5

.J2 Cr .'r.drJcn;o d LC)epF <.


PIC Microcontroller Course 2004 Electronics Trairing Centre 39

Tab:e 2 Tne command control codes

4_(,)
&) R.5'o
o) L'>v*

Experiment2. Setting the cursor addr€ss Experiment 3. Shifting the display


1 Clear D,splay Command RAfi .Va.f 1. Clear Disp:ay Command
C.de =000000C1 Code=Oam aaaT
RS =0 RS=O
Set E H GH 1o LOW and then H GH Sei E - H Gl to.Lo\l/and lhei H GH

2 To set LCD to 2 l:nes, 8-bit data and 5x7 format 2. To set LCDio 2 lines, 8-bit data ancl 5x7 format
using Function Set Command using Function Sei Command
Code = 0011 1010 Code = 0011 T 010
RS=0
SetE -- HIGH to LOWandther flch Set E - HIGH lo LOW and then HlGil

3 llsing Display on/offCJ rsor command set 3. Using Display on/off Cursor co'nmand set
d'splay to ON, with undeni,re and Blinking crrsor display to ON, wiih underline and B:'nking cursor
Code = 0000 1111 Co.le=000! I l1
RS =0
SeiE H GH 1i LOW and then H GF Sei E - H Gl'l to LOWand the n I'lGH
rt. Enter all 26 cnaracters as fo:lows:
4 DisplayAddress Command code=0'i000001 (ior'A)
cursoraiaddress 0000 r000 (0Blr)
To set the RS ='1 (dala entry mode)
!si.g SetDspayAddresscommand.thec!rsorvr' lumpto Set E -- HIGH to LOW and ihen HlGn
Then enters clher.haracles sequentrally
address command = cursor OnJrAi.FrrLb3vsrae
-q!!play
address + 80h The Cusor/Drsplay Siifr command caf .oq De useC tr
scrol a tlre dls! ay lccaions to the eit sotratthelei€rsQ
code = l ooo looc .- '"'t' 9tD'ie
RS=0
Sei E - HICH to LOWancltrren f lcl_l
command code = 000r 1000 (18h)
Display edd resses 2Eh tc 3Fir ard 68h tc 7Fh Sei E -. HIGH 1o LOW afd then HICH
cannotbe !sa. Tne re:tonsh p bet.reer addresses and
Eaclr tme the cornrnaid rs entered and usinlt tlre E sw icl.
d splay ocrtsn vafles depend n! on the type of LCD
r.a! e be r! rsed Atypca l6character2lne sslrown the character c!n De sirltone place to tle Laft

00 01 a2 03 04 05 06 07 08 09 OA OB OC OD OE ol + u+tiov t9l

4F
PIC M icrocontroller Cout se 2OO4 E:ectronics Traininq Centre

Table 3. Standard LCD charactertable

t!. 0
::::\ )co;
l 2
0or I
4 5 6 7 8 9 B c D E F

l I

2 t-
3

I
5
l: i.i
:t ::q

B i

F
!itr

FS=0 E = H.L-H
Tir s sets Lh,p e rlry mocie to a!to- ncr3nrerU
.onr'ri )r ccd!, = 0001 1l0011c il
Set E - l_llcH 10 LOWafd ihe r H Gii
4. Enter a few number from 0 to 9
Erperiment4i Characterentry nrode re 30h to 39h
- S3.i s!riabe iuncno. sei Drspi.y cinrcli.riiiarx RS=- E = H-L-H
ch:.:cte.€pprars c!.lne flght-hanc afd sc.o"s as
clrrra.:r.s a . enl3r!o l!s: like : ncrma calcJlltDr

rls.0 E=ht-H
3 s.il characler enirv nrode corn! d
PIC Microcontroller Course 20O4 Electronics Train:ng Centre 4t
;3lvITUTl9 Using LCDwittr PIC iRS=o
;D splayrng a message BCF

N1OVLW H'OF'
ist p=16F84A R=DEC
r!lo!l^F PORfB
*h\cCONFIG H'3FF3'
CALL PULSE E
LUDE .P16Fe4A 'br) CALL SHORTDEL
#DEFINE BANKO BCF STATUS 5
CLRF CNTl
#DEFINE BANKl BSF STATUS.5
lnz/.ra
CBLOCK HOC cNtl CNT1 W
CNTl
,ELAll PORTA 2
DELAYT
DELAY2 )eAlz
ENDC ts o$q9 A,+a,)"$. ,uto, *,
I,IOVWF PORTB
ORG O
CALL PULSE E
GOTO 5
ORG 4
CALL SHORTDEL
GOTO 5
NCF CNT],W
XORLW 14
ORG 5
BTFSC STATUS,Z
INIT CNTl
GOTO STOP
n) DELAYl INCF CNTI,F
DELAY2 GOTO ]\,IESSAGE
STOP: GOTO STOP
oLD PORTB
SHORTDEL DECFSZ DELAY1 F
SETPORTS: BANKl GOTO SHORTDEL
TRISA RFTLW O

CLRF TRISB PULSE E BSF PORTAO


E=HLGH
BANKO
LONGDEL NOP
CALL SHORTDEL
DECFSZ DELAY2 F BCF PORTA O

GOTO LONGDEL iF.LOW


FUNCTSET BCF PORTA,2 RETLW O
RS=0 T ADDV\F PCLF
scF RETLW W
RETLW E'
N]OVLW H'38' RETLW I
RETLW C'
CqLL PULSE E RETLW 'O'
GALL SHORTDEL RETLW 'ful'
RETLW 'E
RETLW '-rpar
DISPLAYON BCF PORTA2
RETLW T 'll.'

Circuitdiagrarn
-forLCDl asm
P lC Mic.ocontro ller Course E lectron ic Tra in in g Centre

;llLustating use olTimer 0 and LCO set up

LISTP=16F84A R-DEC LCDSET


CONF G I] 3FII . PWRTE ENAtsLE IADT
RSL:NE
DISABLE CP OFF XI OSC
LCDST2 MOVF
INcLUDE<P16F34AllC>
TABLCD
#DEFINE BAN KO BCF STATUS,5
LCDO!T
+DEFlNE BANKl BSF STATUS.s

CBLOCK rl OC
'!oO tr/ L,oro nsT,
usr l@ ,zl c,n, ?1,J:
CLKCNT
LCDMSE
STCRE
RSLNE
BsF RSLINE4
LCDMS2 I/iOVF
ENoc
CALL MESSAG
CAIL LCDOUT -)
ORG 0
GOTO 5
BTFSS LOOP3
ORG
GOTO 5
€OTO LCDMS2
ORG 5
NOMOte cOrO NOMORE
- -' - abt ort6
CLRi LCDOUT MOW'/F 5TC F i 5io*t -
CLRF
BANKl
( MOVLW 50
1 Nlo"v"F LooPA
CLRF DELAY 1oFc;s7 Io raF
CLRF
tull]v1\i/
TRSB a,b5 ]. eoro o'-rr'
N4(]!1,\F
CALL SENDT
BANKO
SEND]T SVLA:: STORE.F e qbu $q7* auEfl
GOTO
TABLCD ADDII]F
rvtovF sioRE.wi
AND-r]t 15
RETLW
RETLW
RET -V/
RETLW
RETLW
lttTLW
rtlTL!1r
RETLW
4f
PAi]S I t\rlovLw 5
[10!x1/F CLKCNT
,/i.::EssAG ADDWF pcL.F
RETLV/ 'R pause
CLRF NICON
RETLW E'
BTFSS INTCON,2
RETLVL]
RETLW
RETLV' :? BCF INTCON.2

RETLW
- ILTLV\]
itf rlw 'c
ENO

LCD IMODULE

RB3 RB2RB1 RBORB4 RBs

Fig 1. Circuit diagram forTUT20

Last Updaled 18 sEP 2005


PIC Microcontrollercourse Electronic Training Centre 44
:3II,!TUT21,ASM ccLl Lcooul
0q lal24 hou C ock !s ng LCD dispay wrh swirch sen.g of
BTFSS LOOP,3
Cryslal3 2768MHz GOTO LCDST2

LIST P= 16F84A R " DEC


LCDMSG

"_ )",
lNcLuDE<P]6F84AlNC> epeo e t r n t BSF RSLINE.4
#DEFINE BANKN BCFSTAT S 4 - LCDMS2
+DEFINE BANKT BSF STATUS,s CPf,L MESSAG
CAL LCDOUT
CBLOCK H20 INCF
BTFSS
CLKCNT itll coTo LCDM52
CLKSEC llll CLRF CLKSEC
CLKMIN 211'l h, rntr, (c I' CLRF CLKMIN
CLKHRS L CLRI CLKNRS
STOREl MOVLW
STORE2 MO/\ /F CLKCNT
RSLNE
hLFSEC ITAN BTFSS )NttoN2 , t.l44o o,'.' laqJ
EVENT GOTO
BCF ]NTCON2
ENDC CALL CLKADD
GOTO MAIN
ORG 0
GOTO CLKADD DECFSZ CLKCNTF
ORG
GOTO 5 25'
ORG 5 CLKCNT
GEIKEY
HLFSEC F
BIFSC HLFSEC O
BANKl
800011111 RETURN

TRISB CLKSEC
810000101 FS
OPTION REG 3
BANKO
GOTO SETUP STOREl

TABLCD AOOCLK NCF


RETLW 800'1100'i1 MOVLW 6
RETLW 800110011 ADD\]!F
RETLW 800110010' BTFSC STATUS,DC
B'00101100 L/lo\ AF
RETLW 800000110
RE]LW 8',00001100 ADDCL2 MOVF
8',00000001 cctL CHKVAL
800000010 MOWIF STORE2
MOVF
II4ESSAG ADDWF PCLF SUBIA]F STORE2,F
RETLW T BTFSC STATIJS,C
RETLW 1 @TO CLKSHW
REILW CLRF
RETLW ,r; 8 -r" INCF STOREl.F
RETLW
,N 2,"1 . - |" ."E<ttdt INCF
RETLW 61op" oEcFsz
RETLW 'o' GOIO ADOCLK
RETLW
cLKSn!! BIISC
CI.]KVAL ADOL\F CLRF CLKSEC
RETLW B 0'r 0r't 001' MOVLW B11000000
RETLW 801011001' CALL LCDLIN
RETLW B 0010001't MOVF
CALL
SETIjP CALI MOVLW
CALL LCDOUT
LCDSET MOlf CLKI\4 N.W

LCDSt2 MOVIW
CATL TABLCD CAI LCDOUT
PIC Microcontroller course Electronic Training Centre 45

T IMSEI

Mo\'ll,t]- STORE2 @TO SUBT]IT]]

ANDLY/ 15
oRLW 800110000

MOVLW 6
ANDLW 15
BTFS' S'IAiUS,DC

LCDOI,]T :NCF EVENTW


t\rovLw 50

DELAY
GOTO DELAY SUB\ATF STORE2.F
CALL SEND T BTFSS STA1 L]S C

ANDL\^] 15 SUBT]N4 Niov:,,! l

GOTC SUBSET
BTFSC STATUS.DC
GOTO ENDSUB

ANDLW B ]]1]OOOO
: Lr\ tsCF RSLINE4 ORLW 9
CALL LCDOUT
60T0 ENDSUts
sL_rBsE t NCF E\EN]-!!

G'TIIY
GOTO CHKS!\2 ENDSUB GOtr) CtKSltv
BSF EVENT,O
rvlovLr4r cL-KuFs \95q
C')TO TIIISET
aiKSL!2
BTFSS INTCON 2
GOTO
INTCCN 2
DEC:SZ
GOTO

ENO

LCD IMODULE

D7 D6 n5 n4 n3 D2 nl

RB3 RB2RB] RBORB4

16
3 2764

22p 22p

\u4 sod,E
SA0 ' minus, SA1'plus, SA2 - Minute,
SA3 - Hour, SA4- Clear sec
Fis 2. 24 hour Prc d_siraL"l9+ !,il.jj,
PIC Mic.ocontroller Course Electronic Training Centre 46

Chapter I
Programming Data EEPROM memory p-e,86 Lt" $
0 = The wrile operat on ls not comp ete or has not
DATA EEPROM MEMORY
?tostdrtu 4 dotg
bt3 I/VRERR: EEPROIV] EffoI F ag b|t
1 =Awnieoperaton rsprenraiureLyierrn nated
(any [4CLR Resei or any WDT Resetdurlng noma
nol drrecty mapped in the reg ster fle space lnsiead I s

o =Thewrite operaton comp eted


These reg siers are
bt2 WRENI EEPROIITIWl te Enable b i
1 =AlLowsw.iie cycles
o = lnlribitswr te to the EEPROM

tt ?norF,f te

The device prcgrammer can no longer access this memory


Additona nlormaiion on tlre Daia EEPROI,'lrs avalable
rn the PlCm crorM l,lrd Rar]ge Reference Man!a (DS33023)

EECONl REGISTER (ADDRESS 88h)

bt7 5 Unimplemented:

bt4 EEIF: EEPRONI Wrlte Operation


lnterrupt Flag bit
1 =Thewrlte operatron cornpleted
(musl be cLeared n software)

TABLE 3-1r REGISTERS/BITS ASSOCI.ATED WITH DATA EEPRoM

Bi! 2 Eir l Bii 0

0lh :EP:Cll [i;5 R:q sier


0:ih E:ADF :rFfDv !.c r5. r€-tEtir
.fiR:ti
E:!Ot,: :EFA0hl ll0rtr.l Fs!L:::. l
L:!r::.:.=rr1r.rr'r,11=Lrnrh:fi!c, =-:rr'!errenter.rE.rrl.rsl;t-rnL:::J:!?fn:u!!ir:.cr::-l
:iril.r re r-: rre :.: Lr!€d :,i lilr :iFf(jl,l
P lC Mic roco ntrolle. Cou rse E lectron ic Train lng Centre 47

Tu Lorial 22 - Writihs and reading EEPROIM file data

The EEPRO'I| dala memory caf be w.itten to and read


fi.m whefeve.we want and whcli wLl not ose thedalavhen the Nowlheroutne speclied ir the plcsdatasheelis sbned
p.t/er s svrlched oil Thrslutonal demonstfales a smple prograrn al abelMANIAL The 12 rnes oithjs routineibm EANK1 down lo
to-ead/lvfltelheEEPRONIhenoryNolethatlhrsprogranrcannot BCF iNTCON 5 shouLd be tot owed in any other EEpROtrt w tinO
o- Lr ds.r4_draror ro.pd c,Loo.1'e,.r'i,d'noiloro oogdm
gra n Arsc.ole lnal lhe program s specrnc tolhe P C16F84 and fiat
tr.therP C famlles may reqLre slghily defferent codrng MANUALT BANKI

EEDATA ( eqlivalent to INDF ) o. ret evrnq data fiom theEEPROtvt mowtEECONl


.e! ste.E;ADR ls loaded with lhe add€ss irom whrch ihedala s Lo bstEECONt WR
co,ae 3nd rhen rhe Plc copies rhe dara l.cf Lh21 posrrrof nro cFK\r\fit brfssEEcoNl4
EE DATA Prior to v/rting dala to ttre EEPRoi\4 a whte enab e uag ( goto CBKWRT
!!iENEECONI2)hastobeseLnregElerEECONIAnother(ag bcfEECONIWREN
BsetrnEEcONl(RDEECON10)whendzlarstobe.eadlronrthe bciEECONl.4
e.irrcrn To lra rs fer data fr.m EEDATA to Lhe EEPROM lle poLrled MNKo
10 !y EEADR. a routne as sp.cilied ln the PlCs datasheet has to be bo|NTCON 6
perrcmed Thls rouline in tarses oper.l ons blrll nLo lhe P C and
whchlastiorapredeterni.edlrme Aflag(EECONI,4)issetbythe Thelna €lLm comnand coud be repaced by aGOTO
Pl'l when these operations have occurred and it seunls lras to be o by the proqEm rmmedaletv totowrno on into anolher roulrne
a dd o, bF'|of i .r i -i I o! c .om d - tu' 06 pbdo fe1
Red4r'g dala Ir'm the eep om sverysimpLe aslistrna
'
A.exampeorh.wtrewrlngolrreNsed6;h;/,rn sh.6
Aher the hrlra lsation .f var ib es tiy FFPRoM F3.rl'nre .perat'on" p*iUcrt
mow{ EEADR
t SETPRI/I mowf€EADR BANKI
ESF EECONl,RD
bsrl' oN WP I t" b6J\10
-.'lt'i# ni / r
^ ^\r
o.*qc t)d'$ a'"b' r" r'3l.J"$' relLm
on entry lo sETPRtr the ca.len{s o1 \,r' are copied inro
Th. mLline E entered al PRNTGET wirh the EEPRoM I le
EEADR and lhe. v. EAN(] the command BSF EECONI. WREN accressared nW lhis is coored rnLo EEADR tn.n MaBANKI lhe

After tlral aa@ ls copred lroh STOREI nlo W and then c.rnrand tvtOVF eEOATA W

PIC TUTOR
C]RCU T DIAGRAI\T] FOR 3IT,ITUT33
Binary to Hex converter

D7
D6
D5

tc1
PIC M icrocontroller Cou rse Electronic Training Centre 48

3MTUT23.ASM Ys,
Binaryto Hexadecimal converte. using Data EEPROM
LCDSET
llLstrating lse of€EPROrl rcad/M Le clri RSLINE
Convers on oiblnary to hexadecrma LCDST2

LISIP=16F34A, R=DEC €l LCDOUT


coNFrG F 3FFl
:PV.]RTE.ENABLE. WDT DISABLE CP OFF XTOSC
LNCLUDE<P16F84A INC> goi, LcDsT2
#DEFINE BAN KO BCF STATUS 5
+DEFINE BANKI BSF S IATUS 5
ETVALUES (-
CBLOCK N 20' L 6a M*6 rrPnoli.l,lo
VALIJEO

VALUE2
RSLINE
CLKCNT
STOREl

ORG 0
GOTO 5
INCVALl
5
5 INCVAI2
,,'4" qs J ."J-? :
STOREIT
goto MAN

B,ANK] NCVALO
800001111

INCVAL1
8100001r0 sHorwaLs
OPTiO].] REG
BANKO INCVAL2
SBO!\'VALS
MAIN
TABLCD
relN 8001100'11' STOREIT vlrueo,w
€dw 8001100'11'
EUw 8'00110010 EE

Edw 800000110
mo!4
retlw 800001100
mor {,1
VALUEI W
retM 8 0000000'j' STOREI
retlw 800000010
c SETPRM
B0000111't movf VALUE2 W
movuf STOREI
'0 molhv 2
'l *T SETFRJ]
'2
3 B 11001000 ) .B
As,r @L l€L'
5'
6
,q"43.Lff
rnovw
"4< 4 "[t
S
a SloAt call LCDOUT
9
'B
€ll LCDOUT
c
rnovw O
'D cal LCDOUT
E
ca LCDO]_IT
movlw E'
€L LCDOUT
PIC Mic rocontroller Course Electron ic Tralning Cenk€ 49

LCDOUT ho!'l VALUE2 W


CA] HFJ(TABLE
wr.rrsw: g.f,s 666 LCDOUI

8110!1000
DLIN
<> LCOLIN: RSLINE.4
q,f,
.-- ' fl41 LCDOUT
oour 5e, Q, RSLINE4

rcDOUT
LCOOUT STORE
].cDour
$
LCDOUT DELAY
DELAY
LCDOUI SENDIT

LCDOUT SENDT

SHOV\VALS RSLINE,!1]
#$oao , V., ,,,a., vo
LCDOUI

LCOOUT
'f 5
LCDOUT CLKCNT
'0 INTCON

:cDoLn INTCON.2
LCDOUT
}NTCON 2
HEXTABLE
LC'OUT

HEXTABLE
LCDOUT ili]RITE DATATO EEPROM ROUTINE
B 1mfi000'
LCDLIN SETPRM:
BANKl
LCDOU-T EECONl,WREN
aANKO
LCDOUT STORE1 W
'f EEDATA
LCDOUT
''I BANK]
LCOOUT ll55
EECON2
LCOOUT
EECON2
HE(TPALE to'-l.i!l,L EECONl,I&R
LCTOUI
VALUEl,W EECON1 4
HEXTABLE
LCDO{JT EECONI. EN
811000000 EECON1.4
LCDL N BANi<O
rNrcoN6 ) Lirt ltrl .re-'
LCDOUT

LCDOIJT :READ DATA FROM FFPROM ROIJTINF


'L
LCDOIJf GETPRM:
2 &qN(i
LC@UI EECONl,RD

LCDOUT EEDATA,W

HEXTABLE
PIC lllicroco ntroller Co u rse 2004 Electronics Training Cenlre Page 50

Chapter Nine
Projects on Sound Effects

C RCUII O'A€RAIII FEIt


SoLrnd Effect Proiects

$Y It tLY
A,algf" 9 t,,,i '2'
+5v b +ft,'l

o 8" s4,'.'e ,;1


I.
Jf)
,? +L

L-,. .1. I qS

CLRF POR]B

sroRE4 SETLJP1 MOVLW


STOREs i,!O\\\F STORE1
1

STORE6 GOTO r/AlN


STORET
FNDC _ TABL€ ADDWF PcL F
RErLW P {s t6sroops
ORG 0 RETLW Hsts, c 392ltz
GoTo s RETLW FOFA 2sotoops
oRG 4 RETLW H6B, iE 33OHz
rr)To 5 RErLW F,46, Totoops
ORG 5 RETLW 868 E 330H2
PIC Mlcrocontroller Cours6 2004 Electronics Training Cenke Page 5'l

RETLW H'54' ;3MTUT25.ASM


RETLW HsB ,G 392H2 isound Ettoct 2: creallng atune
RETLW HsE :94 r@ps |CREATING A TONE when SA0 rs pressd @nbeusedasa
RETLW H 51' :A-,t4ollz, d@rbe1
RETLW H'OFC
REILW I]'7A tD 292H2
RETLW H'OFF'
INCLUDE <P16F84A1NC>
DELAY NOP +DEFINEBANKO BCFSTATUS.5
+DEFINEBANK1 BSF STATUS 5

CBLOCK H OC'
STOREl
STORE2
STORE3
DELAY2 OE SIORE4
DECFSZ SIORE2, F STORE5
coTo DELAY2 STORE6
RETURN STORET
ENDC
DECFsz STORE2 F
GOTO DELAY3
DECFSZ ORG O
c,oTo DELAY3 GOTO 5
ORG 4
DECf GOTO 5
sToREl, W ORG 5
TABLE
STORE6 SETIJP BANKI
CLFF TRISS
STOREl, W Fonb as ouiplr, PonA s rpulas a delault
-TABLE
BANKO

STORE5
PORTB,T CLRF STORE2
MAIN2 OELAY CLRF STORE3
DECFSZ CLRF STORE4
@TO CLRF STORES
BCF CLRF STORE6
MAN3 DELAY CLRF STORET
DECFSZ STOREs, F
GO tO SETUPl MOVLW 1

DECFSZ STORE6,F STOREl


GOTO MAINl GOTO GETKEY
BCF
cp,r r DELAY2
P1n.. h.L ut.a c^r OELAY2 RETLW HOI€'
oEr.\Y2
Loma, NcF STORE1, F RETLW H'54' G- 392 rlz
tr4Olf
cAl-L TABLE RFTIW H'6S
l\rc\ SioRE7
^,F
MOVLW RETLW H46 Toloops
XORL1tr !151.ffir1,i,1.], RETLW l_16B E-330 Hz.
ETISC srArus.z t rtvu L RETLV{ H'54'
GOTO RETLW H'54 :G.392H2
ll.cF REILW H5a ig4l@ps
@TO RETLW H'5I :A-44OHZ
DELAY3 RETLW HoFc i252r@ps
OELAY3 RETLW H7A A-292P,2
DELAY3 RETLW H'OFF ENd OfT'bIE

i ' $i r,.r" SETUPl OELAY NOP

NOP
NOP
NOP

RETURN
C"q[ DELAY
DECFSZ STORE2, F
GOTO OELAY2
PIC Microcontroller Course 2004 Page 52

DECFSZ SIORE2, F
GOTO DELAY3 SETUP BANKI
DECFSZ STORE3 F TRSB
GOTO OEIAY3 &ANKO

GETKEY
GOTO GETKEY STORE2
DECF STOREI, F STORE3
sToRe.l
STORE5
CALL TABLE
S REN MOVLW H'30
INCF STOREI, F MO\'\\F STOREI
MOVF STORE1,W N10W1rF STORE2
CALL TABLE MOVLW H'50
MO\,l/\F STORE4 lvr STORE3

BSF PORTB 7 MOIMF STORE4


i,AIN2 CALL DEIAY
DECFSZ STORE4,F
GOTO lr4AlN2
Ei]F PO€TB 7 ESF PORTB 7
CALL DELAY
cr\ ( DECFSZ sroRE5 F*J r- .-2-l
GOTO MAIN3
DECFSZ STORE6, F
ht,L { coro ' 'y'
@TO 6t4.[c I iro\A4F STORES
BCF
MAIN1

DELAY2
t:r8[ '*o
CALL DELAY2 COTO OFF
DEIAY2 DECFSZ STORE2, F
GOTO REPEAT
DECF STORE4. F
TABLE NCF STORE],F
STORET MO\f STORE,] W
MOVLW
STORET W DECFSZ STORE3, F
STATUS.Z GOTO REPEAT
GOIO GOTO SIREN

GOTO MAN
END
DELAY3

DELAY3 ;3MTUT27.ASM
GOTO ;Sound E fect 4: Creating a S:ren sound
iSIREN SOUND s geneGledwhen SA0 is pressed. Conlinue
END
;Press RESET butlon lo siop

;3MTU-T26.ASM LST P=P C16F3,IA R-DEC


Sound Effect 3i Creating a Siren
NCLIJDE <P 16F34A INC>
sound #DEFINEBANKO BCF STAIUS 5
+DEFINEBANK1 BSF STATI]S 5
LST P=P|C16F84A R=DEC
coNFGH3FFI' CBLOCK t-t 0C
LNCLUDE<P16F84A NC> STOREl
+DEFINEBANKO BCFSTATUS5 STORE2
+DEFINEBANK1 BSFSTATUS5 STORE3

CBLOCK H'OC' STORES


STOREl ENDC
stoRE2
STORE3
STORE4 ORG O
STORE5 GOIO 5
ENDC
GOTO 5
0
GOTO

5
PIC lllicrocontroll€. Coutse 2004 Electronics Traininq Centre Page 53

.N DECFSZ STOREs F
GOTO ON
MOW\F STORES
CLRF STOREI BCF PORTB.T

OFF DECFV STOREs.F


GOTO OFF
DECFSZ STORE2 F
GOTO REPEAT
OSTKEY
GOTOGETKEY
DECF STORE4 F
INCF STORE1 F
MOVLW H 80'
I\4OVF STOREI W
MOW\F STORE]
llo!4v\F sToRE2
inovLw F50
MOW\F STORE3

IiCVF STORE4 W
MCII\F STOREs
BSF PORTB 7

Chapter Ten
Using Interrupts

1rcly, though. and can bedangerous to the correctopera


1o. ofihe marn program
Allowance has io be made io r a pad cular opera
lon io be cornp:eted befo.e the inierupt roLnne is peF

The use of a holdLng rounne thereforc, seerns


preferabe tca r be as s rnpy as

STARI NOP
GOTO STARf

The o ogrd- ,ro- d oe _o 1 r .y oe ro sb_l / oot 'J


throughlhe ty/ocornrnands NOP and GOTO START. wa t-
ng ior ai ntenpt to occlr When rnterupt occlrs, the
oop s erited and alurnp made to the rounne at INTRPT
At the enC oilhe routine cals€d bylhe ifl€rrupt.
r re, ,, ro fe p- 9 on po . - r rq-ra lle r'-rr p .np
!!as made must be specf€d rhere s a commard wh:ch
s used fo.th s pLrpose RETFIE

RETFIE - RET!ir Fr.n lnlenlpt Events

Tl-re OPTION reg ster and INTCON reg stercon


trols the rnteff upt fu..Uo.s
PIC Microcontroller Course 2004 Eleckonics Train:ng Centre Page 54

p luT2a.AsM
;TMROINTERRUPT

Ti.lRo@unlslrom and gen-


eEles an nterupt when overn@s from 255 (FFh) to 0 This 100n
overflow sets lhe TolF bit 'l( bir 2 of lNTcoN regisle0 Ihe nlets
rlpl can be nasked by cearlng TolE bil ( b { 5 oi NTCON regE-
ie4 The TolF bit ( int@. 2) mlst be ceaEd in sotware by lhe
TMRo module inlenuDl seMce roume beloe e+nablhq lhis rn-

INTTIVROASM
iProesslng lnieiilpl caused by OVERFLOWon TMRo
iThls program illoskales how inlerupt on TMRo ;ove.now can
lcl

LISTP=16i_34A, R=DEC
_coNFrcH3pFl
INCLUDE <P16F84A INC>
ERRORLEVEL -302

GOTO MAIN
ORG 4
GOTO INTRPT
ORGsj

CLRF PORTA
CLRF PORTB
BSF STATIJS 5
CLRF TRISA
CLRF TRISB
MO\tW 810000100'
I/IO!\AF OPTON REG
;3MTUT29,Aslrl
MOVLW B 10100000
;R3O/INYTNTERRUPT.
INTRBO-ASM
tProcessing ntenlpl elsed by changing onpin RBo/ NT This
NOP program demonstretes use ot:interupl on RBo/ NT UPon
GOTO LOOP
iaitJ6li.gedg€of lhe pusecomingtoRBo/|NTpr,prog.am
tunp6 lo:slbroulrne for processrng rnlerupl
BSF PORTB,T
,rhsrou ne lhen perfoms a @nain operation lhat
'blinks ihe LED of R87
NOP
r126AM9/1/2004
C
lnlo NOP LISTP=l5F34A R=DEC
itoP coNFlG H 3E4S 3!r I
tBor.", BCF PORTB,T !NCLUDE <PI€F84A INC>
scF tNTcoN.2 ERRORLEVEL .302
RETFIE ORG O
GOTO IVIAIN
END ORG
GOTO INTRPT

ORG 5

CLRF FIRTA
CLRF PORTB
BSF STATUS 5
MOVLW ]
MOVLW 811000111'
rvlo!1^,F OPTION_REG
ECF STATUS,g :
PIC Microcontroll€r Course 2004 Elect.onics Training Centre Page 55

MO\!\F rlrcoN ,66'.:' CLRF PORTA


CLRF PORTB
GOTO LOOP
BSF STATUS 5
CLRF TRISA
llovLw B'1fi10000

GOTO LED2

GOTO LEO3
GOTO INTEND
BCF NTCON i LEDO
RETFE
GOTO INTEND
END
LEDl BCF PORTB 1
GOTO IN'IEND
teD2
GOTO INTEND
;3MTUT3O.ASM LED3
INTRB4T.AST]I
Pio€ssrng .lerupl caused by PORTCI.TAT\IGE ON R81 INTEi..]D BCF N-TCON O
i87 howr.teFupl car be empoyed for
ThLs DrograJn Llust ales RETFIE
fdr.atrng cha rles o pns RB4- Ra7 upof plshng a.y ollhe
swilches of PORTB. program enlers the interuptroutine and END
detem nes whrch pn.alses rnt€rupl

L ST P= 16F34A, RiDEC

INCLUDE <P,]6F84A ]NC>

GOTO N,I,A N

I
tF--
ca_

c1

E3

You might also like