Vous êtes sur la page 1sur 188

EXPERIMENTING

withthe
PICBASICPRO
Y
ByLesJohnson
ACOLLECTIONOFBWLINGBLOCKS
ANDWORKINGAPPLICATIONS
USINGMELABS
SIMPLETOUSE
YETPOWERFULCOMPILER
IfRosettaTechnologies
ACROWNHILLPUBLICATION

~a
c2
~~~~~~~~~~~~~
~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~

~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~

~
- - - - - -
- - - - - -
- - - - -
--
- - ~ - -- -
- - - - - - - - - - - -
- -
- - - -- - -
- - - - -
~ - - - - -
- ~
- - ~ ---- - - -

~ -
-- -
- -- - - -- - - - -- -
-
- -
~ - - - - - - -
~ - -
- -~- ~- -- - - - -~-
-~ ~- -- - - -
- - - -
-~- ~ - - -
-
-- - -
-- - -- -~~~~--- - - -
- - -- - ----
ExperimentingwiththePicBasicProCompiler
Introduction
The BASIC
languagehasbeenpopular
since it' s conception
in the
1970' s
.Oneofthemainreasonsforthisisitseaseofuseandabilityto
makeaprojectworkwithinamatterofhours,insteadofdaysorweeks
.
ButtohavetheabilitytoprogramamicrocontrollerinBASIC,isadream
cometrue
.Moreover,whentheBASIClanguageisintheformofa
compiler
;itcombinesbothspeedandeaseofuse
.MicroEngineering,
LabsInchavecomeupwiththeperfectmediumforprogrammingthe
PlCmicrorangeofmicrocontrollers
.ThePicBasicProCompilerallows
totalcontroloverthefullrangeof14-bitand16-bitcorePIC' savailable
.
Thisbooktakesoverfromwherethecompiler' susermanualleftoff,and
isintendedforusebythemoreadventurousprogrammer
.Itillustrates
howtocontrolreadilyavailabledevicessuchasAnaloguetoDigital
Converters,DigitaltoAnalogueConverters,Temperaturesensorsetc,
thatmaybeincorporatedintoyourownprojects,aswellassome
completeprojects
.Inaddition,tipsandtechniquesarediscussedwhich
allowevenmorecontroloverthePIC
.Eachexperimentinthebookhas
anaccompanyingprogramthatshowsexactlywhatishappening,or
supposedtohappen
.Mostareintheformofsubroutines,readytodrop
intoyourownprogram .
Themajorityoftheprojectswillworkonanyofthe14-bitcoredevices,
however,unlessotherwisestated,thePICusedistheeverpopular
PIC16F84usinga4mHzcrystal .
TheaccompanyingCDROMhasallthesourcelistingsforthe
experiments,aswellasthemanufacturersdatasheetsandapplication
notesforthesemiconductordevicesused
.
MythanksgotoJeffShmoyer,notonlyforco-writingthecompilers,but
alsoforhisadviceintheconstructionofthisbook
.Iwouldalsoliketo
thankyouforpurchasingthisbookandIwishyoueverysuccessinyour
futureprojects
.
LesJohnson
.
ExperimentingwiththePicBasicProCompiler
Contents.
Section1.
DisplayControllerExperiments.
Page
SimpleSerialLCDcontroller. 1-1
MultiplebaudSerialLCDcontroller. 1-3
ContrastcontrolforanLCDmodule
. 1-6
Drivingmultiplexed7-segmentLEDdisplays. 1-7
SubstitutingcommonAnodeLEDdisplays 1 . 11
InterfacingtotheMAX7219LEDcontroller. 1-14
Section2.
InterfacingwithKeypads.
Keypadinterfacingprincipals 2-1
12-buttonKeypadinterface. 2-2
16-buttonKeypadinterface.
2-4
SerialKeypadcontroller.
2-6
ReceivingdatafromtheSerialKeypadcontroller. 2-9
AssemblercodedKeypaddecoder. 2-10
Section3 .
ExperimentingwithSerialEeproms.
GivingthePICamemory. 3-1
MicrowireInterfaceprincipals. 3-3
SPIInterfaceprincipals.
3-4
12CInterfaceprincipals. 3-6
12CserialeepromInterfaceprincipals. 3-8
Interfacingtothe24C32,
12C
serialeeprom.
3-10
Interfacingtothe24C32usingtheMSSPmodule
. 3-13
Interfacingtothe93C66,Microwireserialeeprom. 3-18
Interfacingtothe25LC640,SPIserialeeprom. 3-20
ExperimentingwiththePicBasicProCompiler
Contents. (continued)
Section4.
ExperimentingwithAnaloguetoDigitalConverters. Page
InterfacingwiththeMAX186AnaloguetoDigitalConverter . 4-1
Usinga3-wireinterfacetotheMAX186 . 4-4
UsinganexternalreferencevoltagefortheMAX186
.
4-5
Quantasizingtheresult.
4-6
UsingtheMAX187AnaloguetoDigitalConverter . 4-8
InterfacingtotheMAX127AnaloguetoDigitalConverter. 4-9
Usingtheon-boardAnaloguetoDigitalConverter . 4-12
AchievinggreateraccuracythroughSLEEP
.
4-15
UsingtheADCINcommand . 4-16
Analternativequantasizingformula. 4-18
Ironingoutnoisyresults . 4-19
Section5 .
ExperimentingwithDigitaltoAnalogueConverters.
UsingthePWMcommandasaDigitaltoAnalogueConverter . 5-1
ControllingthehardwarePWMmodules .
5-5
BuildinganR-2RDigitaltoAnalogueConverter. 5-9
InterfacingtotheMAX5352DigitaltoAnalogueConverter . 5-11
InterfacingtotheAD8402digitalpotentiometer. 5-14
Section6 .
ExperimentingwithRemoteControl .
SonyinfraredremotecontrolReceiver. 6-1
AssemblercodedSonyinfraredReceiver 6-3
SonyinfraredremotecontrolTransmitter .
6-4
AssemblercodedSonyinfraredTransmitter 6-7
InfraredTransmitter/Receiver . 6-8
TransmittingandReceivingserialinfrared .
6-10
418mHz,A . M . radioTransmitter
. 6-13
418mHz,A. M . radioReceiver. 6-16
ExperimentingwiththePicBasicProCompiler
Contents. (continued)
Section7.
TemperatureMeasurementExperiments .
Page
Dallas1-wireinterfaceprincipals
. 7-1
InterfacingwiththeDS1820,1-wiretemperaturesensor. 7-5
InterfacingwiththeLM35temperaturesensor .
7-8
Section8 .
ExperimentingwithRobotics .
Proximitydetectionprincipals
. 8-1
Singledirectioninfraredproximitydetector.
8-2
Infraredproximitydetectorwithdistancegauge .
8-4
Directionalinfraredproximitydetector.
8-5
Ultrasonicproximitydetector .
8-7
DrivingaDCmotorusinganH-Bridge.
8-10
DrivingaDCmotorusingtheL293D .
8-12
Section9 .
ExperimentingwithAudioControlDevices
.
AddingavoicetothePICwiththeISD1416chipcorder. 9-1
Recordingandplayingbackmultiplemessages.
9-2
AllowingthePICtoaudiblycount .
9-5
DigitalVolumecontrolusingtheAD840X
. 9-7
Controllingthegainofanop-amp
. 9-9
DigitalactiveBassandTreblecontrols .
9-10
Section10 .
Programmingtechniques
IntegratingAssemblylanguageintoyourprograms.
10-1
Declaringvariablesforusewithassembler .
10-2
PassingparametersusingtheDEFINEcommand
. 10-3
UsingINCLUDEfilestotidyupyourcode
. 10-5
WakingthePICfromSLEEP.
10-7
AbriefintroductiontoHardwareinterrupts .
10-9
UsingtheONINTERRUPTcommand
. 10-17
ExperimentingwiththePicBasicProCompiler
Contents. (continued)
Section11.
PoweringupthePIC
.
Gettingthemostoutofbatteries.
Page
11-1
TheperfectPower-up. 11-4
Appendix.
Componentsources.
Devicepinouts.
CDROMContents.
ExperimentingwiththePicBasicProCompiler
ExperimentingwiththePicBasicProCompiler
Section-1
Display
Controller
Experiments
SimpleserialLCDcontroller .
MultiplebaudserialLCDcontroller.
Drivingmultiplexed7-segmentdisplays
.
SubstitutingcommonAnodeLEDdisplays.
InterfacingtotheMAX7219LEDdisplaydriver
.
ExperimentingwiththePicBasicProCompiler
Program - SERLCD
.BAS
SimpleserialLCDcontroller
IntelligentLCDmodulesacceptdataandcommandinstructionsovera
fouroreightbitparallelinterface
.Commandinstructionsinclude :cursor
control,clearing,scrolling,etc
.Thesecommandsaredescribedinthe
LCDmoduledatasheetandinthecompiler'smanual
.Thankstothe
LCDOUTcommand,thesedisplaysarenotdifficulttouse,butstill
requireatleastsixpreciouspinsfromthePICtobeused
.TheserialLCD
controllerdescribedhere,simplifiestheuseofthesedisplaysevenmore,
byenablingcontroloftheLCDwithasinglewire
.Thisisinvaluablein
debuggingyourlatestmasterpiece,asitopensupawindowintoyour
code
.ByconnectingittoanunusedpinandusingtheDEBUGcommand
atspecificareaswithintheprogram,variablesandregisterscanbe
viewed.
Theprogram SER_LCD.BAS
implementsasimpleserialLCDcontroller
forusewiththePIC16F84 .
WhenthePICispoweredup,thefirstthingItdoesisturnontheLCD
andwaittheappropriatetimeforthedisplaytobefullyinitialised,this
usuallytakesapproximately100ms
.Itthenlooksatthepolarityswitch,
andjumpstotheappropriatesectionofcodeanddisplays :-
"T9600BaudOK!"

fortrueinput
or
"N9600BaudOK!"

forinvertedinput
Itthenwaitsfora9600-baudserialcharacterofwhicheverpolaritywas
chosen
.Ifthecharacterisaspecialescapecharacter
(254), thenext
characterisassumedtobeacommand
.ThePICwillthereforepassthe
followingbytetotheLCDasacommand
.Otherwise,thedatawillpass
directlytotheLCD.Thisallowsthedisplaytobeclearedscrolled,etc
.
simplybysendingdatawithanescapecharacterinfrontofthecontrol
byte: -
SeroutPortB.0,N9600,[254,11
Pause30
ThiswillcleartheLCD
.NotethePAUSEcommand,thisgivestheLCD
moduletimetorecoverfromtheCLScommandbeforesendinganother
character.
Section-1 -1
ExperimentingwiththePicBasicProCompiler
9Volts
0
V
78L05
IN OUT
GND
Regulated5Volts
RESET
RI
10k
4nHo
Crystal
C3
22pf 22pf ass

ass
V

R07
MCLR RBB
RB5
RB4
RB3
OSC1 R82
RBI
RBO
PIC18F84
RA4
0502 RA3
RA2
RA1
VSSRAO
R4
220k
Section-1 -2
INTELLIGENTLCD
MODULE
R11A91So51ai >
RS
1k
SWI
R3
7
Figures . 1 . SimpleserialLCDcontroller.
SimpleserialLCDcontroller
Ifadisplaywithmoreorlessthan2linesisusedthenalterthelastlineof
theLCDdefines: -
DefineLCD_LINES 2

'SetnumberoflinesonDisplay
Figurel . 1showsthecircuitoftheSimpleserialLCDcontroller. Serial
dataentersthroughR5,thisgivessomeprotectiontothe PICinthe
eventofashortcircuit,itisalsoconnectedtooneterminalofthe DIL
switch(SW1) .
TheDILswitchservestwopurposes,firstitconfigurestheserialpolarity
mode (invertedortrue) bypullingPortB. 4togroundthroughR3,just
enoughtoregisterasalowreading (0),
butnotenoughtointerferewith
theoutputtotheLCD. Sharingapinlikethisisacommonpracticewhen
sparepinsarenotavailable.
Secondly,itstopstheinputfromfloating,
(floatingmeansthatthepinis
neithersethighorlow) . ThisisachievedbyresistorsR2andR4. When
thepolarityisconfiguredforinvertedmode,theleftswitch intheDIL
packageisclosed,whichmeansthattherightswitch isopen,thus
allowingonlyR4tobeconnectedtotheinput,thispullstheserialinput
pinslightlytowardsground . Andwhentruepolarityisselected,the left
switchintheDILpackageisopenandtherightswitchisclosed,bringing
R2intocircuit,butasR2hasalowerresistancethanR4theserialinput
pinispulledmoretothesupplyline . Withouttheseresistors,random
characterswouldbedisplayedwhentheinputwasnotconnected to
anything.
+5v
R2
look
0
Seri5I
Date
In
O
ExperimentingwiththePicBasicProCompiler
Programs -MULTILCD2.BAS&MULTILCD4.BAS
MultipleBaudSerialLCDcontroller
If,likeme,youarefascinatedbyserial (RS232)communication,thenthis
projectisamust
.Thebaudratesareselectablefrom300to19200and
bothinvertedandnon-invertedserialdataisaccepted
.Thecircuitis,in
essencethesameastheSimplecontroller,butwiththeexceptionofa
cleverlittleswitchcalleda DecimalRotaryDIL, figurel .2showsthe
pinoutofoneofthesedevices
.Ithastenrotarypositions,numbered0to
9,andthesenumbersarerepresentedasBCD

1 ,9o
y8
outputsonpins,1,2,4and8.

Cco

Nc
41

C.
2
Section-1 -3
9
9
V
Figure1.2.
TheoutputsoftheswitchareconnectedtoRBO
- RB4,
andbylookingattheseinputs,theprogramisableto
determinewhichbaudrateisrequiredi .e.
3for300baud,9for9600,8for19200 (position1isalreadyused) etc.
Figurel .3showsthecircuitforthemulti-baudcontroller
.Becauseofthe
higherbaudratesinvolved,a16F873runningat12mHzisused .
YoumayhavenoticedthattheVddpinoftheLCDisconnectedto
PortB.5insteadofthesupplyline,thisissothatwhenthePICisreset,all
portsareinitialisedasinputsbydefault,thus,alsoturningofftheLCD,
andeffectivelyresettingit.Therefore,thefirstthingtheprogramdoesis
makePortB.5anoutput,andturntheLCDon
.
Inordertoreadtherotarydilswitch,theinternalpullupresistorsare
enabledonPortB,andthelower4-bitsaremadeinputs,weareonly
interestedinthepinsthattheswitchisconnectedto,sothe
port isread
andtheupper4-bitsaremaskedoutbyANDingtheresultwith
%00001111,thevalueheldin B-TESTnowholdstheBCDoutputofthe
switch
.AlookuptableissetupbyusingtheLOOKUPcommandwhich
holdsallthebaudratesthatwillbeselected (0-9),
theyhavealready
beendividedby100 (12insteadof1200,96insteadof9600), thisis
becausethecalculationtosetthebaudrateforSERIN2is, (1000000/
baud )- 20,
however,thisistoolargeanumberforthecompilerto
handle,therefore,ithastobescaleddown,thisisachievedbydividing
by100i
.e. (10000/(baud/ 100))-20. AftertheLOOKUPcommand,the
variable
BAUD holdstheselectedbaudrate/100,thentheabove
calculationiscarriedout,and BAUD
nowholdsthevaluetobeplacedin
theSERIN2command.
ExperimentingwiththePicBasicProCompiler
TrisB.4=1
IfPTest=1then
Baud.14=0
Mode="T"
Else
Baud.14=1
Mode="N"
Endif
TrisB.4=0
Section-1 -4
MultiplebaudserialLCDcontroller
Toreadthepolarityswitch,PortB
.4ismadeaninputandbit-14of BAUD
issetorclearedaccordingtotheresult
.Bit-14isthemodesetting,(1=
inverted,0=noninverted) : -
'SetPortB.4toInput
'IfP_TestishighthenSetforTruePolarity
'Resetbit-14(Modebit,clearforTrue)
'Variableusedforthedisplay
'ElseSetforInvertedPolarity
'Setbit-14(Modebit,setforInverted)
'Variableusedforthedisplay
'TurnPortB.4backtoanoutput
TheincomingserialdataisthenreadinusingtheSERIN2command,as
thiscanachievehigherbaudratesthanSERIN
.Theprogramnowsitsin
aloop,receivingdataandoutputtingittotheLCD
.Ifthecontrolbyteis
detected (254) theprogramisre-directedtoaroutinethatinput'sanother
serialcharacter,thiswillbethebytethatinformstheLCDastowhat
actionshouldbetaken,scroll,clearscreenetc
: -
Loop:
Serin2SI,Baud,(RcvByte]

'Receivetheserialbyte
IfRcvByte=254thenControl

' Trapthecontrolbyte
LcdoutRcvByte

'
ElsedisplayitontheLCD
GotoLoop

' Keeponlooking
Control:
Serin2Sl,Baud,[RcvByte2]

'Receivethesecondserialbyte
IfRcvByte2=253thengotoBar ' TraptheBargraphbyte
LcdoutRcvByte,Rcvbyte2

'Orsendoutthetwobytes
GotoLoop

'Lookagain
Bar:
'ReceivetheThirdandfourthserialbyte
Serin2SI,Baud,[BarPos,Bar_Val]
Lcdout

l,BarPos

'Positionofbargraph
GosubBargraph

'Displaythebargraph
GotoLoop

'Lookagain
Y
ExperimentingwiththePIcBasicProCompiler
5Volts
Cl
C2

0 .1u1
1Ou1
b~
assass
RESET
R1
10k
i
12mHz
Crystal
s
10
C3

C4
15101

151311
sa
VDD
RC7
RC6
RC5
RC4
MCLR RC3
RC2
RC1
RCO
RB7
RBA
RB5
RB4
RB3
RB2
OSC1

RB1
RBO
PIC15F873
RA5
RA4
OSC2 RA3
RA2
RA1
VSSVSS
RAO
ie
17
8
e
e
5
a
i
INTELLIGENTLCD
MODULE
0 0000o
S w 3> >
R3
1k
SWI
Figurel .3
.Multi-baudserialcontroller .
Bargraphoption
TheBargraphdisplayisinitiatedbysendingthecontrolbyte253along
withthepositiontostartdisplayingfrom,andthenthelengthofthebar
: -
Section-1 - 5
MultiplebaudserialLCDcontroller
x
e
0
e
SW2
+SV
VR1
50k
R2
100k
0
Debugl ,
Bar,Line1,Lengthof_Bar : Pause1
`LengthofBar'maybeavalueof0to59ifa4x20displayisused,ora
valueof0to47fora2x16display .ThePAUSEcommandallowsthe
serialcontrollertimetodothebargraphsubroutine
.
TheBargraphsubroutineisintheformofanincludefile,whichisloaded
inaftertheLCDhasinitialised .Theincludefile BARGRAF2
.INC isfor
usewitha2x16LCD,and
BARGRAF4.INC isfora4x20LCD.Thecode
isfullycommented
.Theserialcontrollerprogram MULTILCD2.BAS is
forusewith2x16LCDmodules,andprogram
MULTILCD4.BAS isfor
usewith 4x20
LCD modules .Theprogram SERTEST
.BAS
demonstratestheuseofthebargraphoption
.
I Con
254 `ControlByte
Bar Con 253
`Bardisplayinitiate 3.6Volts
Line1 Con 128 `Displayline1 IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
ExperimentingwiththePicBasicProCompiler
ContrastcontrolforanLCDmodule
Ifacontrastcontrolisneeded,itissimpleenoughtoaddasmallpreset
potentiometerconnectedtothe Vo
pinoftheLCD,asinfigurel . 4 .
Contrastincreasesasthepotisturnedtowardsgroundandthevoltage
onPin Vo decreases. Alternately,afixedresistorwithavalueofafew
hundredohmscanbeconnectedfrom Vo toground.
+5V
VRII
50k
INTELLIGENTLCD
MODULE
mmmm m 2yo
00

aaaa W
jr
>>>
11111111111
GND Figurel
. 4
. LCDContrastcontrol
.
Extended-temperatureLCDmodulesontheotherhand,requirea
negativevoltageappliedtopinVo,thiscanbeachievedwithaswitch-
modenegativevoltageconverter,suchastheMAXIM1CL7660. As
showninfigurel . 5.
+5VIN
VDD
ICL7660
CAP-
VOUT
CAP+
GND
C2
10uf
Section-1 - 6
MultiplebaudserialLCDcontroller
Figurel . 5. Switch-modenegativevoltagegenerator .
ExperimentingwiththePicBasicProComp
il er
Programs - 5CC_DISP.BAS
Drivingmul tipl exed7-segmentLEDdispl ays
ThemainconsiderationwhendesigninganinterfacetoanLEDdispl ayis
thenumberofpinsavail abl eonthePIC.Todriveafivedigitnon-
mul tipl exeddispl aywoul drequireaPICwith45I/Opins,oneforeach
segment
.Thisisofcourseimpractical therefore,mul tipl exingisal most
universal l yadopted.Whichwil l stil l take13pins,butonthel argerPICs
with33I/Osthisisnotusual l yaprobl em
.
Asmostofyouwil l al readyknow,mul tipl exingisaccompl ishedbydriving
eachdispl ayinsequence.Aseachdispl ayisturnedon,thesegment
datafromthePICissettothecorrectpatternforthatdigit.Thepatterns
foreachdigitareshownintabl e1
.1 .
Tabl e1
.1 .Binarypatternfor7-segmentdigits.
Toil l ustratehowasingl edigitisdispl ayed,wewil l l ookatdigits4and5
.
Thebinarypatternfordigit4is%01100110,andfordigit5itis
%01101101 .Figurel
.6showshowthesebinarypatternsrel atetothe
segmentstoil l uminate.
OFF0
ON1 ON,
OFF0
OFF0
ON1
ON1
A
D
0

EC
7)
ON1
OFF0
ON1
OFF0
ON1
ON1
ON1
A
0
G
es>
IF

e
E

C I
Figurel
.6
.Binaryrel ationshiptoil l uminatedsegments.
Remember,thatthe'A'segmentisattachedtotheLSBofthebinary
number
.
Section-1
- 7
DigitDispl ayed
Binaryval ueon A-Gsegments Decimal
F E C B
A
0 0
1 1 1 1 1 1 63
1 0 0 0 0
1 1 0 6
2
1 0 1 1 0 1 1 91
3 1 0 0
1 1 1 1 79
4 1 1 0 0 1 1 0 102
5 1 1 0
1 1 0 1 109
6 1 1 1 1 1 0 0 124
7 0 0
0 1 1 1 7
8 1 1 1 1
1 1 1 127
9
1 1 0 0 1 1 1 103
ExperimentingwiththePicBasicProCompiler
Common
Figurel . 7 . IndividualLEDswithinacommoncathodedisplay .
Byexaminingfigurel
. 7 wecanseethatapplyingapprox2Vtotheanode
ofaparticularsegmentLED,whilethecommonlineisconnected to
groundanindividualsegmentmaybeilluminated .
Tomultiplexmorethanonedisplay,requiresustotakecontroloftheir
individualcathodes. Thisisachievedbyatransistoractingasaswitch,
asshowninfigurel . 8 .
A

DP
Figurel . 8 . Transistorswitch.
Alogichighonthebaseofthetransistorwillswitchiton,thuspullingthe
commoncathodestoground . R2limitsthecurrentthatcanflowbetween
theindividualsegmentLEDs . R1limitsthevoltagesuppliedtothebase
ofthetransistor.
Wenowhavethemeanstoswitcheachdisplayoninturn,aswellasthe
informationrequiredtoilluminateaspecificdigit
. What'srequirednowis
ameansofturningonadisplay,illuminatethecorrectdigitanddothe
samethingforthenextones,quicklyenoughtofooltheeyeintothinking
itisseeingallthedisplaysilluminatedatonce .
Drivingmultiplexed7 -segmentdisplays
ConnectingthedisplaytothePICisuncomplicated . TheA-segment
connectstoPortCbit-0,andtheG-segmentconnectstoPortC bit-6 .
SegmentsB. . Fconnecttothepinsinbetween . Thedecimal pointis
connectedtobit-7 ofthesameport .
Inthisdemonstration,weshallbeusingcommoncathodedisplays . As
thenamesuggests,allthecathodesfortheindividualsegmentLEDsare
connectedtogetherinternally,asshownbelowinfigurel . 7 .
A

DP
Section-1-
8
ExperimentingwiththePicBasicProCompiler
Drivingmultiplexed7-segmentdisplays
Andallwithinthebackground,toallowtheprogramtoprocesstheactual
informationtobedisplayed
.ThisisaperfectapplicationforaTMRO
interruptusingthecompiler'sONINTERRUPTcommand
.
Program 5CC_DISP.BAS
showsawayofdisplayingafive-digitnumber
onfive,7-segmentdisplays
.Becausethefivedisplaysrequire13I/O
pins,theprogramisintendedtobeusedononeofthenewer16F87X
rangeofPICs,andalsoassumesa20mHzoscillatorisbeingused.
Figurel
.10showsthecircuitlayoutforthedemonstration .
ThefirstthingtheprogramdoesisinitiateaTMROinterrupt(as
shownin
theprogrammingtechniquessection) togenerateaninterruptevery
1 .6384ms,bysettingtheprescalerto1
:32.Tocalculatetherepetitive
rateoftheinterruptusethefollowingformula
: -
Interruptrate(inus)=((OSC/4)*256)*prescalerratio
Withintheinterrupthandlerroutine,thedigitofinterestspatternis
extractedbyusingtheLOOKUPcommand,whereaspecificpattern
correspondstoacertainnumberheldinthearray NUM[O_C]. The
patternextractedfromthelookuptableisplacedintothevariable
DISPPATT. Thevariable0_Chasadualpurpose
;itsmainpurposeis
toformasortof
time-share fortheindividualdisplays
.Oneachinterrupt,
thevariableOCisincremented,andeachdisplaywaitsforitsparticular
time-slotbeforeitisturnedon
.Thiswayeachdisplayisturnedonfor
approx1 .6msspreadoverfiveinterrupts,causinganoverallscanrateof
about125Hz
.
Withineachdisplay'stime-slot,thepreviousdisplayisturnedoffandthe
valueheldin DISPPATT isplacedontoPortC
.Acheckisthenmadeof
thevariable
DP whichholdsthedecimalpointplacement.If DP
holdsthe
valueofthedisplaywearecurrentlyusing,thedecimalpointisturnedon
bysettingbit-7ofPortC
.Thedisplayitselfisthenturnedonbysetting
theparticularbitofPortBhigh .Note. DP
mayholdavaluebetween0. .5
where1isthefarthestrightdisplay,andzerodisablesthedecimalpoint
.
Whiletheinterruptgivesusameansofdisplayingfivedigits,the
subroutine DISPLAY doestheprocessingoftheactualnumberto
display
.Thesubroutinefirstdisablestheinterrupttoeliminateany
glitchesthatmaybevisiblewhileprocessingthenumbers,thenitsplits
Section-1-
9
ExperimentingwiththePicBasicProCompiler
Programs-5,4,3,2CC_DISP.INC,MULTTST.BAS

Drivingmultiplexed7-segmentdisplays
theindividualdigitsfromthe16-bitnumberheldin D_NUMBERusingthe
DIGoperand.Eachdigitisplacedintothefiveelementarray
NUM, anda
seriesof if-then's zerosuppresstheunuseddigits .Afterallthedigits
havebeenprocessed,theinterruptisre-enabledandthesubroutineis
exited.
Toaidintheuseofmultiplexingthedisplays,severalincludefileshave
beendevelopedforusewith2to5displays .Theincludefileofchoice
shouldbeplacedatthetopoftheprogramafterthe MODEDEFS.BAS
filehasbeenincluded.
Theincludefile 5CC_DISP.INC isforusewhen5displaysarerequired
TheTMROinterruptwillautomaticallybeenabledupontheprogram's
start .Italsocontainsthesubroutine DISPLAY whichexpectstwo
variablestobepre-loadedbeforeitiscalled.Thefirstvariable,
D-NUMBERholdsthe16-bitvaluetobedisplayed .Thesecondvariable,
DP holdsthepositionofthedecimalpoint (0. .5) : -
D_NUMBER=12345

`Displaythenumber12345
DP=0

'Donotplacethedecimalpoint
GosubDisplay

`Displaythenumber
Theincludefile 4CC_DISP.INC isforusewhen4displaysarerequired .
Again,theTMROinterruptisenabledontheprogram'sstart .Thesame
twovariablesneedtobepre-loadedbeforethe DISPLAYsubroutineis
called
.However,
DP
nowhastherange0
..4
.
Theincludefiles 3CC_DISP.INC and 2CC_DISP.INC areforusewith3
and2displaysrespectively.
Thevariables, DNUMBERandDParealreadypre-declaredwithinthe
includefile,therefore,thereisnoneedtodeclaretheminyourprogram .
Theprogram DISPTST.BASdemonstratestheuseof2to5multiplexed
displays,byuncommentingtherequiredincludefile .Theprogram
incrementsa16-bitvariable,whichisdisplayedonthe7-segmentLEDs.
However,thisloopcouldeasilybereplacedbytheADCINcommandfor
displayingthevoltageconverted.Oratemperaturereadingroutine .
Section-l- 1
0
ExperimentingwiththePicBasicProCompiler
Programs-5,4,3,2CA_DISP .INC,MULTTST.BAS

Driving multiplexed7-segment displays


SubstitutingCommonAnodedisplays
Ifcommonanodedisplaysaresubstitutedforthecommoncathodetypes
thenaslightre-arrangementoftheswitchingtransistorsisrequired,as
showninfigurel .9 .
To PortB
ToPortC
+5V
A
-I
0
D
E

C
D
-DP,
B
C
D
E
F
a
DP
Common
noao
Figurel
.9
.CommonAnodedisplay.
Aslightdifferenceinthecodeisalsorequired.Themaindifferenceisthe
patternsthatmakeupthedigits.Whencommoncathodeswereused,a
highonthesegmentsilluminatedthem,butforcommonanodes,alow
onthesegmentsisrequired
.Therefore,thepatternsshownintable1 .1
needtobeinvertedi .e .%11111100becomes%00000011
.Thiscan
easilybeachievedbyplacingnewvaluesintotheLOOKUPcommand
withintheinterrupthandler.Thenewpatternsareshownbelow: -
[192,249,164,176,153,146,131,248,128,152,255]
Oneotherthingthatrequiresalteringisthedecimalpointplacement .
PreviouslyPortC.7wassethightoturnonthepoint,butnowitneedsto
bepulledlow.Thisagainiseasilyremediedsimplybychangingthelines
correspondingtoPortC.7intheinterrupthandler .
Allthepreviousprogramsandincludefilesdiscussedhavealreadybeen
alteredforusewithcommonanodedisplaysandmaybefoundinthe
COMANODfolder.
Section-l- 1 1
ExperimentingwiththePicBasicProCompiler
Section-l- 1 2
Drivingmultiplexed7-segmentdisplays
Figurel.10. 5-digitmultiplexed
commoncathodedisplay.
ExperimentingwiththePicBasicProCompiler
PSO=0
PS1 =1
PS2=0
Drivingmultiplexed7-segmentdisplays
Whenusingthemultiplexerinyourownprogram,youmustremember
thatitisusingthecompiler'sONINTERRUPTcommand
.Andassuch
theprecautionsandwork-arounds
explainedinthe programming
techniquessection shouldbeobserved.
Ifanoscillatoroflessthan20mHzisrequired,thentheprescalevalueof
theinterruptshouldbedecreased
.Especiallyifmorethanfourdigitsare
beingutilized,otherwiseaslightflickeringofthedisplaywillbenoticed
.
Thisiseasilyaccomplishedbychangingthethreelinesinthe
include
filesthatcontrolthePSO,PS1,andPS2bitsofOPTION-REG . For
example,tousea4mHzoscillatorwithafivedigitdisplay,thefollowing
changesshouldbemade : -
`Assigna1
: 8prescalertoTMRO
Byexaminingtheincludefilesforthedifferentamountofmultiplexed
displays,youwillnoticethatastheamountofdisplaysisreducedthen
theinterruptrateisalsodecreased.Themainreasonforthisisthat,as
theinterrupthandlerisprocessingitsmultiplexingcode,themain
programishalteduntiltheinterruptisover,thusultimatelyslowing it
down
.Thelesstimesaninterrupthandlerneedstobecalledthequicker
themainprogrambecomes .
Afinalnoteonmultiplexing
: Whenreducingtheamountofdisplaysused,
alwaysremovethemostsignificantdigits
.Forexample,if4displaysare
usedinsteadof5thenremovedisplaynumber4,whichistheleftmost
digit.
Section-l- 1 3
ExperimentingwiththePicBasicProCompiler
Program- MAX_CNT.BAS
InterfacingtotheMAX7219
TheMAX7219iscapableofdrivinguptoeightcommon-cathodeseven-
segmentLEDdisplaysusingathreewire
(synchronousserialinterface)
.
Itcanalsoconvertbinary-coded
decimal (BCD) valuesintotheir
appropriate patterns ofsegments
.And hasbuilt-in pulse-width
modulationandcurrent-limitingcircuitstocontrolthebrightness
ofthe
displayswithonlyasingleexternalresistor .
WitheightLEDdisplaysattached,theMAX7219isabletoscanthemat
over1200Hz,thuspreventinganydisplayflicker
.Ifadisplayoflessthan
eightLEDsisused,thechipmaybeconfiguredtoscanonlytheone's
connected,increasingthebrightnessandscanningfrequency
ofthe
display .WithallofitscomplexityonewouldexpecttheMAX7219tobe
difficulttocontrol,butquitetheoppositeistrue
.Withjustafewlinesof
codeaversatileLEDdisplaycanberealizedandwithonlythreepins
(datain,clock,andload)
requiredonthePIC,eventhe8-pindevices
maybeused .
ConnectiontotheLEDdisplaysisstraightforward,pinsSEG-Athrough
SEG-GandSEGDP-connecttosegmentsAthroughGandthedecimal
pointofallofthecommon-cathodedisplays
. PinsDIGIT-0through
DIGIT-7connecttothecathodesofeachofthedisplays
. Figurel .10
showsatypicalsetupusingfourLEDdisplays,interfacedinthis
case
withaPIC16F84 .
ResistorR2setsthecurrentthrougheachLEDdisplay
.Thesmallerthis
resistoris,thegreaterthecurrentthrougheachsegment (minimumvalue
=9.53ko),avalueof10kosetsthecurrentto40mAperdisplay
.R3isa
pulldownresistorontheinterfacebetweenthePICandtheMAX7219
LOADpin,thisisrequiredbecausewhenaPICresets, itsportsare
initialisedasinputs
.Theyareeffectivelydisconnected, therefore,
anythingconnectedtothemisalsodisconnected,andarefloating
.Such
inputsfrequentlyfloathigh,however,electricalnoisecancausethemto
changestatesatrandom,thiswillnormallycausetheMAX7219togo
intotestmodewithallsegmentslit
.Therefore, R3preventsthisby
pullingtheloadpinmoretogroundwhennotinuse.
Section-1- 1 4
ExperimentingwiththePicBasicProCompiler
-AN
O
0
f O/
9

$
N

r
O!

p
$

00
I>
0 ;
7Zv
4
V
N
i
O

f 0
00000000
i7c~ i7c~c~c~ G
O+N(JAUI6J
~ul e lulm
11
11
11
A
m lII-INI
0
O
e
mmmmmmmm
60000000
00000000
0
0
1910101III
I' 3 1 .
id
.T m
mo
Figure1 .10.MAX7219LEDdisplaycontroller.
Section-1-1 5
a
n
O
N
x
D
D
D
Interf acingtotheMAX7219
ExperimentingwiththePicBasicProCompiler
Table2. 1
. RegisterswithintheMAX721 9
Digit-0 -
Digit-7 pointtotherelevantdisplaysattached,digit-0isthefar-
rightdisplay .
Decode
enablesordisablesBCDdecodingforeachindividualdisplay
(%1 0000001 wouldenableBCDondisplays0and7)
.
Intensity
setstheoverallbrightnessofthedisplays (0to1 5).
ScanLimit
informstheMAX721 9astohowmanydisplaysareattached
(0-7).
Shutdown, placestheMAX721 9instandbymodewhencleared
.
Test,placestheMAX721 9intestmodewhensetto1
(maximum
brightnessandallsegmentson)
.
WhensendingdatatotheMAX721 9itexpectsapacketconsistingofa
1 6-bitwordcontainingtheregisternumberandthenthevaluetobe
placedwithintheregister : -
Firstbyte1 1

pointstothescanlimitregister
Secondbyte3

informstheMAXthat4LEDsarebeingused
The1 6-bitsareclockedintotheMAX721 9,regardlessofthestateonthe
LOADpin
. However,theyareonlyacteduponwhentheLOADpinis
clockedhightolow,whichhasthesecondaryeffectofdisablingthe
deviceafterthedataissent .
InterfacingtotheMAX721 9
Thereare1 4addressableregisterswithintheMAX721 9,table1
. 1 shows
alistofthem
.
Section-l- 1 6
Register Address
Description
NOP 0 NoOperation
Digit0 1 ThefirstLEDDisplay
Digit1 2 ThesecondLEDDisplay
Digit2 3 ThethirdLEDDisplay
Digit3 4 ThefourthLEDDisplay
Digit4
5 ThefifthLEDDisplay
Digit5
6 ThesixthLEDDisplay
Digit6
7 TheseventhLEDDisplay
Digit7 8
TheeighthLEDDisplay
DecodeMode 9
BCDdecodingOn/Off
Intensity 1 0
BrightnessofDisplays
ScanLimit 1 1
AmountofDisplaysattached
Shutdown 1 2 PlacechipintoStandby
Test 1 5 TestmodeOn/Off
ExperimentingwiththePicBasicProCompiler
InterfacingtotheMAX7219
Program MAX-CNT.BAS
showsasimpleapplicationoftheMAX7219 .In
theprogram,a16-bitintegerheld
inthevariable COUNTER is
incrementedandthendecremented,thisisdisplayedonthefour7-
segmentLEDs.FirsttheMAX7219isinitialisedbyloadingthe Scan
registerwith 3 (4displays
attached), theLuminanceregisterwith3,
Decoderegisterwith%00001111,thiswillconfigurethefirst4displaysto
BCDdecoding,thentheSwitchregisterissettoone,whichwillwakeup
theMAX7219andfinallytheTestregisteriscleared .
Thecountup-downroutinethenplacesthepositionofthedecimalpoint
in MAX_DP, (MAX DPmaycontainavaluebetween0 . .
.7,zerobeing
theright-mostdisplay), andthevalueof COUNTERinto MAX_DISP. The
subroutine DISPLAY
isthencalled,thisextractstheseparatedigitsfrom
thevariable MAX_DISP, usingtheDIGoperand,anddisplaysthemon
theappropriateLEDs.Notethezerosuppression,thisissimplyaseries
ofifthen' s
thatblankthedigitsbysendingthevalue15whenthedisplay
isnotbeingused
.Thissubroutineitselfcalls anothernamed
TRANSFER,
whichshiftsoutthetwobytesthenstrobestheLOADpin
lowthenhigh,thistransfersthedataintotheinternalregisters
ofthe
MAX7219 .
Ifmoreorlessdisplaysare
used,changethevalueplaced in
SCAN_REG (thisislocatedintheinitialisationsectionofcode),
tothe
appropriateamountofLEDsattached (0-7) .
AlsowithinthesubroutineDISPLAY,changethelines
:
ForPosition= 4 to1step-1
into
ForPosition=nto1step-1
Where nis thenumberofLEDsattached
(1-8)
IfDigit>=3thenDigit=0
Into
IfDigit>=nthenDigit=0
Where nis thenumberofdigitsinthevariable MAX_DISP(0-4),
in
PicBasicProthemaximumamountofdigitsisfive (0to65535)
Section-l- 1 7
ExperimentingwiththePicBasicProCompiler
Section-2
Interfacing
with
Keypads
Keypadinterfacingprincipals.
Interfacingwitha12-buttonkeypad
.
Interfacingwitha16-buttonkeypad.
Serialkeypadcontroller.
Receivingdatafromthekeypadcontroller.
Assemblercoded,keypaddecoder.
Usingthepseudocommand,INKEYS.
ExperimentingwiththePicBasicProCompiler
Programs -KEYPAD12
.BAS,KEYTST12.BASandINKEYS12.INC
Programs
-KEYPAD16.BAS,KEYTST16.BASandINKEYSI6.INC
Keypadinterfacingprincipals
Interfacingtoafewbuttonsissimple,butwhenmorearerequired,a
keypadisalmostessential .Inthisexperiment,weshalllookatthe
principalsofhowakeypadworksandwriteasubroutinetoaccessit
.
Figure2
.1showsthearrangementofa12-buttonand16-buttonkeypad .
Ascanbeseentheyarearrangedasamatrix,thisminimizestheamount
ofI/Olinesneeded,otherwise12or16inputswouldhavetobeusedto
interfacetothesameamountofkeys
.ByarrangingthekeysintoRows
andColumnsweonlyrequire7or8inputstooperateit,however,the
pricetopayisthatakeypadscanningroutinemustbeemployed
.
12-Buttonkeypadmatrix
Columns
5

7
Figure2.1.
Thekeypadscanningroutinesystematicallysearchesforakeypress
.It
startsbysettingtheconnectionstothecolumnpinsasinputsandthe
connectionstotherowpinsasoutputs
.Theinputsareheldhighbythe
internalpullupresistors.Theobjectofthesearchistofindoutwhether
oneoftherowsofthekeypadisconnectedtooneofthecolumns,andif
sowhichone
.Thescanroutinepullsoneoftherowlineslow,thenlooks
atthecolumnsinputtoseewhethera0isdetected
.Ifnot,itthentries
thenextrow;thisiscontinueduntilalltherowlineshavebeenscanned .
Thereareasmanykeypadscanningroutinesasthereareprogrammers.
Eachprogrammerhashis/herwayofdoingthings
.However,whichever
waygetsthejobdoneeffectivelyisOK.
Section-2 -1
16-Buttonkeypadmatrix
Columns
6

7
5 8
ExperimentingwiththePIcBasicProCompiler
Interfacingwitha12-buttonkeypad
Theprogram KEYPAD12.BAS, andthecircuitshowninfigure2
.2
demonstratetheuseofa12-buttonkeypad .Theprogramscansthe
keypadanddisplaysthevalueofthekeypressesonaserialLCD
moduleconnectedtoPortB .7
.Itisbasedaroundthekeypadscanning
subroutineINKEYS.Whenthissubroutineiscalled,twovariablesare
returned.ThefirstvariableisKEY,whichholdsthevalueofthekey
pressed
(128ifnokeypressed), thesecondvariablereturnedis
DEBOUNCE, which (asyoumighthaveguessed)is
adebounceflag.
Thisreturnsholdingazeroifakeyhasbeenpressed,however,when
theINKEYSsubroutineiscalledasecondtimeandakeyisstillinuse,a
valueofoneisreturned
.Onepossibleuseofthisfeaturecouldbe : -
Main:
GosubInkeys

'Goscanthekeypad
ifDebounce=1thengotoMain

'Gobackifbuttonisstillheld
WithintheINKEYSsubroutinethevariable DEBOUNCE isinitiallysetto
1,thenthefirstfourbitsofPortAareconfiguredasoutputs (rows), and
thefirstthreebitsofPortBaresetupasinputs
(columns). Carehasbeen
takentoconfigureonlytherelevantbitsthatthekeypadisattachedto
.
Theinternalweakpullupresistorsareenabledandthefirstrowispulled
low (PortA.3), thesubroutineSCANCOListhencalled,thisexaminesthe
columnlinesinturnandincrementsthevariableKEYwhenakeypress
hasnotbeendetected,thiswillbuildup13numberscorrespondingthea
certainkeypressornokeypress (albeitinthewrongorder). Onreturning,
thevariableK_FLAGwillhold1ifakeypresswasdetectedotherwiseit
holds0
.ThevariableK_FLAGisexaminedafteritsreturn,toascertain
whethertoscanthenextrowortoprocessthevalueheldinKEY
.If
KFLAGreturned0,thenthesameprocedureiscarriedoutforallfour
rows
.However,ifKFLAGreturneda1thenthedebounceflagsareset
orclearedaccordinglytothevalueheldin D-FLAG.
ThevariableKEYis
re-arrangedtocorrespondtothekeypadlegends,byusingtheLOOKUP
command
: -
Mapofthekeypadlegendsfornumericoutput
LookupKey,[1,2,3,4,5,6,7,8,9,10,0,11,128J,Key
Section-2 -2
Interfacingwithakeypad
5Volts
ExperimentingwiththePicBasicProCompiler
Interfacingwithakeypad
Forexample,initsrawstate,KEYwillholdthevalue0iftheonekeyhas
beenpressed,10ifthezerokeyhasbeenpressed,and12ifno
keypresshasbeendetected,therefore,thethirteenvalueswithinthe
bracesoftheLOOKUPcommandcorrespondtotherawKEYvaluesand
theexpectedkeypadlegendvalues
.
Theprogram KEYTST12. BASdoesthesameas
KEYPAD12. BAS, but
the INKEYS
subroutineisloadedinasanincludefile : -
Include"INKEYS12. INC"
`Placethisatthebeginningoftheprogram
.
VDDRB7
MCLRRB6
RB5
RB4
RB3
0SC1RB2
RB1
RBO
PIC16F84
RA4
OSC2RA3
RA2
RA1
vss
RAO
To
SerialLCD
N9600baud
Figure2
. 2. 12- buttonKeypadCircuit.
Section- 2 - 3
ExperimentingwiththePicBasicProCompiler
Interfacingwitha16-buttonkeypad
Usinga16-buttonkeypadisessentiallythesameasusingthe12-button
version,however,minordifferencesintheINKEYSsubroutinehaveto
bemade.Figure2.3showstheslightlydifferentcircuitlayoutand
program KEYPAD16.BAS demonstratesitsuse.Thekeypadisagain
arrangedasamatrix,butthistimeitis4x4, (fourcolumnsandfourrows).
Withinthe INKEYS subroutinemostofthecodestaysthesame,itstill
scansthefourrows,butthistimetherearefourcolumnsinsteadofthree .
Therefore,oneextrainputisrequiredwhichmeanstheTRISvaluehas
totakethisintoaccount .Aswiththe12-buttonprogram,thevalue
returnedinKEYfromthesubroutineSCANCOLdoesnotmatchupwith
thelegendsprintedonthekeypad'sbuttons.Therefore,theLOOKUP
commandisusedagaintochangethevaluereturnedinKEYtothe
correctnumber.However,thistimethereare17differentcombinations.
'Mapofthekeypadlegendsfornumericoutput
LookupKey,[15,7,4,1,0,8,5,2,14,9,6,3,13,12,11,10,128],Key
Theprogram KEYTST16.BAS doesthesameas KEYPAD16.BAS, but
theINKEYSsubroutineisloadedinasanincludefile : -
Include"INKEYS16.INC" 'Placethisatthebeginningoftheprogram .
To
SerialLCD
N9600baud
RB7
RB6
RB5
RB4
RB3
RB2
RB1
RBO
RA4
RA3
RA2
RA1
RAO
B
Figure2.3.16-buttonKeypadCircuit .
Section-2 -4
a
Interfacingwithakeypad
5Volts
R1
4.7k
VDD
MCLR
4mHz
Crystal
1 16
OSC1
PIC18F84
C1
L' 10uf OSC2
C3 C4
C2 ses M
22p1 22pt
Slut
VSS
Dv
I
I
ExperimentingwiththePicBasicProCompiler
Interfacingwithakeypad
Inboththe12and16buttondemonstrationprograms,thevaluereturned
inthevariableKEYisanumericrepresentationofthekeypressed
( i.e.
keyonereturnsthevalue
1) . However,iftheACSIIrepresentationis
desired ( i.e .
keyonereturnsthevalue49) , thecommentedLOOKUP
commandneedstobeuncommentedandtheinitialLOOKUPcommand
needstobecommented .
'Mapofthe12-buttonkeypadlegendsforASCII
output
LookupKey,j"11, 2",113 11,"4", 115" 11611,"7 ", "8 ",

"0 ",11#11,3 21,Key


'Mapofthe16-buttonkeypadlegendsforASCII output
LookupKey,["F'"7 1,114
",'l"0 "8 '5","2",
En
11911,116"1"3 ",
p C, .8 ,.
A''

Key
Ifyourparticularkeypaddoesnotmatchupwiththevaluesdisplayed,
simplyre-arrangethevalueswithinthebracesoftheLOOKUP
command .
Todeterminewhichkeysarewhich,commenttheLOOKUPcommand
andplaceaSEROUTorDEBUGcommandjustafterit
.Thiswilldisplay
thevalueheldinthevariableKEY
.Whichevervalueisreturnedforthe0
buttonwillbethefirstvaluewithinthebracesoftheLOOKUPcommand
.
Section-2 -5
ExperimentingwiththePicBasicProCompiler
Program - SERKEY.BAS
Serialkeypadcontroller
Theuseofakeypadisoftenessentialbutitstilltakesuppreciouspins
onthemicrocontrollerthatcouldhaveotherfunctions,
therefore,the
logicalsolutionistosendoutthedatafromthekeypadserially .
This
meansthatonlyoneortwopinsareuseduponthePIC
. Figure2 .4
showsthecircuitforsuchacontroller
.Thekeypadcontrollersendsout
asyncserialdataateitherT1200baudorT9600baud .
ThethreeLINKSconnectedtoPortAand
PortB;configureseveral
differentpropertieswithinthecontrollercode .
LINK1configurestheserialoutputbaudrate
.Whenconnected,9600is
transmitted,andwhenleftunconnected,1200baudistransmitted
. The
lowerbaudhasbeenchosensothataserialIRtransmitteroraradio
transmittermaybeconnected
.
LINK2selectstheoutputtype.Whenconnected,
ASCIIvaluesare
transmitted,wherethevaluesentreflectstheASCIIvalueofthe
key
(buttonAwillsendthevalue
65) . Whenunconnected,numericvalues
aretransmitted,wheretheactualkeyvaluesaresent
(button3willsend
thevalue3) .
LINK3selectsthenumberofbuttonsontheparticularkeypad used .
Connectedwillinterfacetoa16- buttonkeypad,andunconnected
will
interfacewitha12- buttontype.
The STROBE pin(PortB
.6),willbehigh50msbeforetheserialdatais
transmitted,andlowjustaftertheendoftransmission
. Thismaybe
usedasanindicatororasadatavalidationlinetothereceivingPICthat
akeyhasbeenpressedandserialdataisonitsway
.ByusingtheNAP
commandwithinthewaitingloopofthemainprogram,thecontrollers
currentconsumptionisonly0 .4 mA.
Section- 2 - 6
ExperimentingwiththePicBasicProCompiler
Serialkeypadcontroller
Theprogram,
SERKEY.BAS isbasedaroundthekeypadscanning
subroutine INKEYS,
thisisamodifiedversion ofthestandard
subroutinesexplainedinthepreviousexperiments
.Themainloopofthe
programexaminesthepinswherethelinksareattached,
andplaces
theirvalueintothreeflags,
BUTTONS,NUMERIC,
and BAUDRATE,
thesenowcontain1or0accordingtowhetherthepinsareconnectedor
not
.TheinternalpullupsandR2ensurethatwhenalinkisnotconnected
thepinwillalwaysremainhigh .
Thelinkkflagsareusedtoconstructthedifferentconfigurationsbysimple
if- then
commandslocatedatplaceswithinthecodethatrequirea
differentproductforthespecifiedlinkconnectionordisconnection
.
Theformatfortheserialdatatransmittedis : -
Syncbyte " l7 " , KeyValue,Debounceflag
ThisissentasTruepolarity9600or1200baud .
Lowcurrentconsumptionisachievedbycontinuouslyusing
theNAP
commandwhennokeyispressed .ThismeansthatthePICisoffmore
thanitison
.TheNAPcommandplacesthePICintolowpowermodefor
18ms,whichmeansthereisan18msdelaybeforethekeypress
is
respondedto,however,thisisnotnoticedasthekeypadisnotatime
criticalcomponent.
Again:
GosubInkeys

'Goandscanthekeypad
IfKey=128orKey=32then'Ifnokeypresseddothefollowing
: -
Nap0

'Gointolowpowermodefor18ms
GotoAgain

'Andlookagainwhenwokenup.
Endif
Thecircuitshowsa16- buttonkeypadconnected,however,ifa12- button
typeisusedinstead,connectionsareasfigure2
.2 .
Section- 2 - 7
L
d
E
0
U
+5Volts
Link1
Connected. . . 9600baud
Open1200baud
Link2
Connected. . . ASCIIoutput
OpenNumericoutput
JJJ
Link3
Connected. . . 16-button
keypad
Open12-buttonkeypad
0
C:
0
U
a
a)
Q
a
Y
a)
u)
N
a))
0)
LL
0
a
R1
4. 7k 14
V
as
a
a)
L
a+
. C
VDD
RB7
RB6
RB5
RB4
RB3
RB2
RB1
RBO
MCLR
OSC1
P1C16F84
4mHz
Crystal
3
RA4
0)
C 00
bC1
10uf C3
4
OSC2

RA3
RA2
C4
C2
-
r22pf 22pf
C
RA1
a)
E
VSS
RAO
0
"
u" TT T
s
a)
ay
W
- V
ExperimentingwiththePicBasicProCompiler
Program - KEYIN.BAS
Receivingdatafromtheserialkeypadcontroller
Theprogram KEYIN.BAS
demonstrateshowtoreceivetheserialdata
fromtheserialkeypadcontrolleranddisplaytheresultsonaserialLCD
display,connected
toPortA
.1,configuredforN9600baud .The
subroutine KEVIN
continuallylooksforthesyncbyte"@"andwhen
found,readsinthenexttwobyteswhichcontainthevalueofthekey
pressed,andthedebounceflag
.Itthenreturnswiththesevaluesinthe
variables
KEYandDEBOUNCE: -
Key

Var

Byte

`Buttonpressedvariable
DebounceVar

Byte

'DebounceFlag
Keyin:
SerinPortA
.0,T9600,Key

`Lookforthesyncbyte
IfKey<>"@ "
thengotoKeyin

`Lookagainifnotfound
SerinPortA
.0,T9600,Key,Debounce
Return
Alternatively,theSERIN2orDEBUGINcommandsmaybeused
.These
havetheabilitytowaitforaspecificsequenceofcharacters
before
receivingtheKeyandDebouncedata,andnotsurprisingly,thisoperand
iscalledWAIT
.Thesubroutineabovecanbechangedto
: -
Key

Var

Byte

`Buttonpressedvariable
DebounceVar

Byte

'DebounceFlag
B9600

Con 84

79600baud
Keyin:
Serin2PortA.0,B9600, [
wait ("@") , Key,Debounce]
Return
Timeoutvaluesmaybeadded,sothatifakeyisnotpressedwithina
certaintimeframethesubroutineisexited
.Theflexibilityofthe
compiler'sserialdatacommandsaretoonumeroustoexplain,thePBP
manualshouldneverbefaraway .
AlternativelytheSTROBEpin
maybeconnectedandperiodically
examined,ifitishighthenthekeypadistransmitting,andlowmeansthe
keypadisuntouched .
Section- 2
- 9
ExperimentingwiththePIcBasicProCompiler
Programs -ASM_KEY
.BAS&ASMKEY.INC
Assemblercoded,Keypaddecoder
Theassemblercoded,keypaddecoderisintheformofanincludefile
ASMKEY.INC, itsuseisessentiallythesameastheBASICcoded
versions,exceptthereisnodebounceflagreturnedi .e. DEBOUNCE.
Therearehowever,twonewDefinesaddedforthekeypad,thefirst,
informsthesubroutinewhethera12or16-buttonkeypadisbeingused,
theseare: -
Define KEYPAD_BUTTONS12

`Usea12-buttonkeypad
or
Define KEYPADBUTTONS16

`Usea16-buttonkeypad
Thewiringofthekeypadsare*showninfigures4
.2and4 .3 .
ThesecondDefineinformsthesubroutine,whethertoreturnthevariable
KEYwiththeASCIIvalueofthekeypressedorthenumericvalue : -
Define KEYPADRETURN 0

`Returnthenumericvalue
or
Define
KEYPADRETURN 1

`ReturntheASCIIvalue
IftheNUMERICvalueischosen,thevariable,KEYwillbereturnedfrom
thesubroutineholdingthenumericequivalentofthelegendsprintedon
thekeypadbuttons (0will returnavalueof0,Awillreturnavalueof10
etc.) , and128ifnobuttonpressed
.IftheASCIIvalueischosen,KEYwill
returnholdingtheASCIIequivalentofthelegendsprintedonthekeypad
buttons (0will returnavalueof48,Awillreturnavalueof65etc.) , and
3 2 (space)
ifnobuttonpressed .
IfnoDefinesareaddedtoyourprogram,thedefaultsettingsare,
12-
buttonkeypad,returningtheNUMERICvalues .
Theportsonwhichthe
keypadisconnected,areautomatically
configuredforthecorrectinput/outputconfigurationeachtime acallis
madetothesubroutine INKEYS. Andthevariable,KEYisalreadypre-
declaredwithintheincludefile.Makesurethattheincludefileisplaced
atthebeginningofyourprogram,inordertominimizetheriskofpage
boundaryconflicts.Theprogram ASM_KEY.BAS
isademonstrationfor
usingtheassemblercodedkeypaddecoder .
Section-2- 1 0
ExperimentingwiththePicBasicProCompiler
INKEYS,pseudocommand
Withintheincludefiles
INKEYS12.INC andINKEYS16.INC,
amacrohas
beendefinedwhichallowstheuseofapseudocommandcalled
INKEYS
.InsteadofcallingthesubroutineINKEYSandhavingthevalue
ofthekeypressedreturnedinKEY,andthedebounceflagin
DEBOUNCE,
wecanplacethesevaluesintoanyvariablewechoose
.
Theuseofthe INKEYS
commandis: -
Variablel

Var Byte BANKO SYSTEM


Variable2

Var Byte BANKO SYSTEM


@

INKEYSVariablel,Variable2
Variable1will
holdthekeypressedand Variable2will holdthedebounce
flag
.Therearethreethingstorememberwhenusingthepseudo
command
.Alwaysplacethe@symbolatthebeginningoftheline,also
anyvariablesusedwithinthecommandshouldbedeclaredasBANKO
variables.
Also,don'tforgettodeclarethevariablesasSYSTEMtypes,oran
underscoremustprecedethem .
Bothvariablesareoptional,if
Variable2is notusedthedebounceflag
willbeplacedinto DEBOUNCE.
Andif Variablelis notusedthekey
valuewillbeplacedintoKEY.
Section- 2-
11
ExperimentingwiththePicBasicProCompiler
Section-3
Experimenting
with
SerialEeproms
GivingthePICamemory.
MicrowireInterfaceprincipals
.
SPIInterfaceprincipals.
1 2 CInterfaceprincipals.
1 2Ceeprominterfacingprincipals
Interfacingtothe24C32,1 2 Cserialeeprom.
Interfacingtothe24C32usingtheMSSPmodule.
Interfacingtothe93C66,Microwireserialeeprom .
Interfacingtothe25LC640,SPIserialeeprom .
ExperimentingwiththePicBasicProCompiler
GivingthePICamemory.
Ifyouhaveaprojectthatrequireslong-termmemorystorage (upto200
years) thatwillnotfitintothePIC'sinternaleeprom,anexternalserial
eeprom (SEEPROM)
maybetheanswer. Thesesmallandinexpensive
devicesareeasilyinterfacedtoanyofthePICrange . Thissection isa
guidetochoosingandusingseeproms. Wewillcomparethethreemajor
interfacetypes:Microwire,SPI, and12C,alsotheadvantagesand
disadvantagesofusingeachtype .
Allserialeepromsuseasynchronousserialinterface (SSI), thismeans
thatboththeeepromandthemicrocontrolleruseacommonclockanda
clocktransitionsignaltoindicatewhentosendorreadeachbit . Some
synchronousserialdevicesrequireminimumclockfrequencies,theclock
forseepromscanbeasslowasrequired,orasfastasafewmHz's . The
microcontrollercanstrobetheclockat itsconvenience,uptothe
maximumspeedofthedevice.
Serialeepromsnormallyhavejusteightpins,power,ground,oneortwo
data/addresslines,andaclockinput,plusuptothreeothercontrol
signals
. However,unlikeparalleleeproms,whichrequireextrapinstobe
addedasthenumberofaddressanddatalinesgrow, aseeprom's
physicalsizedoesnothavetoincreasewithitsmemorycapacity .
EepromsuseCMOStechnology; therefore,theyconsume minute
amountsofpower,withcurrentsaslowasafew uA instandbymodeand
amA orsowhenactive.
Dependingonthedevice,themaximumclockspeedforaccessingserial
eepromsmaybeover2mHz. However,becauseittakeseight clock
cyclestotransferabyte,andthemasteralsoneedstosendinstructions
andaddresses,themaximumrateofdatatransferisusuallynomore
than4msperbyte. Writeoperationsactuallytakemuchlonger,because
theeepromneedsseveralmillisecondsto programabyteintoits
memoryarray. Duringthistime,thePICcannotreadorwriteto
the
eeprom
.
Withcontinueduse,eepromseventuallylosetheirabilitytostoredata,so
theyarenotsuitedforapplicationswherethedatachangesconstantly
.
Section-3 - 1
ExperimentingwiththePicBasicProCompiler
GivingthePICamemory
Mostareratedforbetween1millionand10millionerase/writes,whichis
OKfordatathatchangesoccasionally,oreveneveryfewminutes
.
It'snotonlyeepromsthatuseaserialinterface,otherdeviceswith
synchronousserialinterfacesinclude,AID,D/Aconverters,clocks,
and
displayinterfacesetc,allofthesedevicesareusedextensivelyinthis
book
. Therefore,thissectionwillgiveaninsightonhowotherdevices
usingaserialinterfacecommunicatewiththePIC
. Multipledevicescan
connecttoonesetofdatalines,witheachchiphavingitsownChip-
Selectline(CS)orfirmwareaddress,thiseffectivelymeansthatiftwo
devicesareconnectedthentheseconddevicemayonlyrequire one
extrapin.
Afteryouhavedecidedtouseaserialeeprom,thenextstepistoselect
one of
thethreeserialprotocols. In conventionalassembler
programming,the3-wiredeviceswoneasilybecauseofthesimplicityof
theirinterface . However,withthecompiler's1
2 CandShiftcommands,
interfacingtoanyofthedevicesisgreatlysimplified .
Toseehowthedifferentinterfacescompare,wewilllookataneeprom
ofeachtype
.
Table3
. 1summarizesthemajorfeaturesofeachtypeused .
Table3
. 1 . ComparisonofSPI,Microwire,andICeeproms .
Section-3 -2
InterfaceType
Microwire SPI I`C
Device
93C66 2 5LC640 2 4C32
Memorycapacity
4Kbits 64Kbits 32 Kbits
Numberof Interfacepins
4or3 4or3 2
Datewidth(bits) 8or16 8
8or16
Maximumclock speed 2 mHz
2 mHz 400kHz
Write(busy)time 10ms 5ms 10ms
MaxNo. of
bytesprogrammedInoneoperation 2 32 16
Writesbiton(clockstate) Risingedge Risingedge Lowlevel
Readsbit on(clockstate)
Risingedge Failingedge Lowlevel
Chipselectmethod
Hardware Hardware Software
ExperimentingwiththePicBasicProCompiler
Microwireinterfaceprincipals
Atmel's93C66isan8-pin,4Kbitserial
eepromwithaMicrowire
interface.Ithastwodatapins,datain
(DJ) anddataout (DO), aclock
input
(SK),andachip-select(CS)
.Additionalinputsareformemory
configuration, (ORG),
whichdetermineswhetherdataformatis8or16-
bits,andprogramenable
(PE), whichmustbehightoprogramthechip
.
Thememoryisorganisedas256wordsof16-bitseachwhentheORG
pinisattachedtoVcc,and512wordsof8-bitseachwhen
ORGis
connectedtoground
.
Althoughitissometimescalleda3-wireinterface,acompleteconnection
actuallyrequiresfoursignallines
.However,useofthePIC'sabilityto
rapidlyswitchstatesfrominputtooutputmeansthatthe
datain and data
outpinsmaybeconnectedtothesamepinonthePIC
.
Theeepromunderstandsseveninstructions,theseare,ERASE/WRITE
ENABLEandDISABLE,WRITE,READ,ERASE,ERASEALL
(setsall
bitsto1), andWRITEALL
(writesonebytevaluetoalllocations)
. Each
instructionmustbeginwithaStartcondition,whichoccurswhenCSand
DIarebothhighontheclocksrisingedge
.DIisbroughthighnaturally
whenaninstructioniswritten,becausealloftheinstructionsbeginwith
one
.ThePICmustbringCSlowaftereachinstruction,
exceptfora
sequentialread
.WhenCSisbroughthigh,theeepromisplacedinto
standby,ignoringallinstructionsuntilitdetectsanewstartcondition
.
Towritetotheeeprom,thePICmustfirstsendan
ERASE/WRITE
ENABLEinstructiontoDI,followedbyaWRITEinstruction,thewritebits
arewrittenontheclocksfallingedge,andtheeepromlatcheseachbiton
thenextrisingedge
.Aftersendingthefinaldatabitinaprogramming
sequence,thePICmustbringCSlowbeforethenextrisingedgeofthe
clock (SK)
.Thiscausestheeepromtobeginitsinternalprogramming
cycle
.Theprogrammingisself-timedwhichmeansthatitrequires
no
clockcycles
.IfCSreturnshigh
beforetheprogrammingcycleis
complete,DOwillindicateReady/Busystatus
.CSmustthen
golow
againtocompletethewriteoperation .
ThePICneedstosendtheErase/WriteEnableinstructionjustonceper
programmingsession
.Thedeviceremainswrite-enableduntilitreceives
anErase/WriteDisableinstructionorpowerisremoved
.
GivingthePICamemory
Section-3 -3
ExperimentingwiththePicBasicProCompiler
GivingthePICamemory
Toreadfromtheeeprom,thePICsendsaREADinstructionto
DI,
followedbytheaddresstoread
.Whentheeepromreceivesthefinal
addressbit,itwritesa
dummyzero toDO,thenwritestherequesteddata
ontheclocksrisingedges.
IfCSremainshighafterareadoperation,additionalclocktransitionswill
causethechiptocontinuetooutputdataatsequentialaddresses
.IfCS
goeslow,thenextreadoperationmustbeginwiththereadinstruction
andanaddress
.
SPIInterfaceprincipals
SPIisverysimilartoMicrowire,althoughpolaritiesand
otherdetails
vary
.AswithMicrowire,SPIeepromswritebitsontheclock's
rising
edge,however,unlikeMicrowire,theylatchinputbitsonthefallingedge
.
ThepolarityofCS (activelow)
isalsooppositefromtheMicrowire
convention
Microchip's25LC640isa64KbiteepromwithanSPIinterface,organised
as8192wordsx8-bits
.Inadditiontothefourinterfacelines,thechiphas
twootherinputs.WP
(writeprotect),
whichmustbehightoprogramthe
device
.Moreover,forinterfaceswithmultipleslaves,
theHOLDinput
enablesthePICtopauseinthemiddleofatransferinorderto
do
somethingmoreurgentontheSPIbus
.Theeepromignoresallactivity
ontheSPIbusuntilHOLDreturnshigh,thenbothdevicescarry
on
wheretheyleftoff
.
Theeepromunderstandssixinstructions,theseare,SETANDRESET
THEWRITEENABLELATCH,READANDWRITETOTHESTATUS
REGISTER,andREADANDWRITETOTHEMEMORYARRAY
.The
eepromhasseverallevelsofwriteprotection,which
maybeusedto
virtuallyguaranteethattherewillbenounintentionalwritestothedevice
.
IfWPislow,nochangestothedataareallowed
.IfWPishigh,twonon-
volatilebitsinthechip's
statusregister canblockwritestoall,ora
portionofthedevice
.Finally,ifWPishigh,beforeyoucanwritetothe
statusregisterortheportionofmemoryenabledinthestatusregister,
theeeprommustreceiveaSetWriteEnableLatchinstruction
.
Section-3- 4
ExperimentingwiththePicBasicProCompiler
GivingthePICamemory
Towritetotheeeprom,thePICsendsaSETWRITEENABLELATCH
instructiontoSI,followedbyaWRITEinstruction,thenthehighbyteand
lowbyteoftheaddressaresent,thenthedatatowrite
.ThePICmay
senduptofourdatabytesforsequentialaddressesinoneoperation
.
AfterclockingthefinaldatabitwithSCKlow,CSmustgohightobegin
programmingthebyteintotheeeprom .
Whiletheeepromisprogrammingthedata,thePICcanreadthe
eeprom'sstatusregister
.Whenbit-0ofthestatusregisteris0,the
eepromhasfinishedprogramming,andthenextwriteoperationmay
begin
.Thechipiswrite-protectedaftereachprogrammingoperation
;
therefore,eachwritemustbeginwithaSETWRITEENABLELATCH
instruction
.
Toreadtheeeprom,thePICsendsaREADinstructionfollowedbythe
highbyteandthelowbyteoftheaddress
.Theeepromrespondswiththe
databitsinsequenceonSO
.AswithMicrowire,additionalclockswill
causetheeepromtosendadditionaldatabytesinsequence
.
Section-3 -5
ExperimentingwiththePicBasicProCompiler
SCL
e a
SDA
(start condition) .(up

h
i
oi
~rme

a
SDA
(stop condition)
Figure3.1 .1 2 CSTART/STOPconditions
.
setup
time
Section-3 -6
GivingthePICamemory
1 2 CInterfaceprincipals
1 2 Cisasynchronousserialbus,developedbyPhilipstoallow
communicationbetweendifferentperipherals.Manydevicessuchas
eeproms,ADCs,LCDdrivers,DACs,etcsupportthe1 2 Cbusprotocol.
Thesedevicescommunicatethrougha2 -wirebus,withdatatransfer
ratesof1 00Kbit/s,400Kbit/s,andeven1 Mbit/s .Thenumberofdevices
onthebusislimitedbythemaximumbuscapacitanceof400pF .
Mostdevicesareusedasslaveswhilemicrocontrollersaretypically
masters.1 2 Calsosupportsmulti-mastering,whichmeansmorethanone
deviceisallowedtocontrolthebus .1 2 Chascollisiondetectionand
arbitrationtomaintaindataintegrity .Thetwolinesusedfor1 2 C
interfacingare,SerialDataAddressLine
(SDA) andSerialClockLine
(SCL).Bothofthesearebi-directional .
1 2 C:Protocol
1 2 Cisamulti-master/slaveprotocol .Alldevicesconnectedtothebus
musthaveanopen-collectororopen-drainoutput .Atransactionbegins
whenthebusisfree (i.e. bothSCLandSDAarehigh), amastermay
initiateatransferbygeneratingaSTARTcondition .Thenthemaster
sendsanaddressbytethatcontainstheslaveaddressandtransfer
direction.Theaddressedslavedevicemustthenacknowledgethe
master.Ifthetransferdirectionisfrommastertoslave,themaster
becomesthetransmitterandwritestothebus .Whiletheslavebecomes
thereceiverandreadsthedataandacknowledgesthetransmitter,and
vice-versa.Whenthetransferiscomplete,themastersendsaSTOP
conditionandthebusbecomesfree .Inbothtransferdirections;the
mastergeneratestheclockSCLandtheSTART/STOPconditions .
i-sa-
ExperimentingwiththePicBasicProCompiler
GivingthePICamemory
TheSTARTconditionisgeneratedbyahightolowtransitionontheSDA
lineduringtheHighperiodoftheSCLline,asshowninfigure3 . 1 .
AstopconditionisgeneratedbyalowtohightransitionontheSDAline
duringtheHighperiodoftheSCLline,alsoshowninfigure3 . 1
.
ThenumberofbytestransferredperSTART/STOPframeisunrestricted .
Databytesmustbe8-bitslongwiththemostsignificantbit
(MSB) first.
EachvaliddatabitsenttotheSDAlinemustremainhighfor'1 'orlowfor
'0'duringthehighperiodoftheSCL,otherwiseanytransitionintheSDA
linewhileSCLishighwillbereadasaSTART/STOPcondition
. Thus,
transitionscanonlybemadeduringthelowperiodofSCL
. An
acknowledgebitmustfolloweachbyte. Afterthelastbitofthebyte is
sent,anACKclock (acknowledgementclock) isgeneratedbythemaster
(9t` ' clock). AnACK
(acknowledgebit,low) mustbesentbythereceiver
andremainlowduringthehighperiodoftheACKclock .
Iftheslave (receiver)
doesn'treturnanACK (e. g. anerror,orisunableto
receivethedata),
thentheslavedevicemustleavetheSDAlinehigh
(NACK). Themasterwillabortthetransferbygenerating aSTOP
condition. IftheslavedoesreturnanACK,butsometimelateritisunable
toreceiveanymoredata. ThentheslavemustgenerateaNACK (not
acknowledge,high) onthefirstbytetofollow
. Theslavewillthenneedto
keeptheSDAlinehighforthemastertogenerateastopcondition . Ifthe
receiveristhemasterandthetransferisending . Thenthemasterneeds
tosendaNACKafterthelastbyteissent
. Theslave (nowatransmitter)
mustreleasetheSDAlinetohigh,thisallowthemastertogeneratea
START/STOPcondition .
Atthebeginningofeachtransfer,themastergeneratestheSTART
conditionthensendsaslaveaddress. Thestandardslaveaddressis7-
bits (sometimes1 0-bits) followedbyadirectionorR/Wbit (8"t bit) as
showninfigures4
. 2and4
. 3
. WhenthedirectionbitisaWRITE (z ero),
theaddressedslavedevicebecomesthe
receiverandthemaster
becomesthetransmitter. WhenthedirectionbitisaREAD (one), the
addressedslavedevicebecomes thetransmitterandthemaster
becomesthereceiver
.
Section-3- 7
ExperimentingwiththePicBasicProCompiler
GivingthePICamemory
12CSerialeeprominterfaceprincipals
Microchip's24C32isa32Kbitserialeepromusingan1
2Cinterface,the
memoryorganisationis4096wordsx8-bits,or2048wordsx16-bits
.
Theslaveaddressassignedtothisdevicebythe
manufactureris
101OXXX,whereX=Don'tCare
. Theeepromsupportsseveraltransfer
modessuchas,BYTEWRITE,PAGEWRITE,CURRENTADDRESS
READ,RANDOMREAD,andSEQUENTIALREAD .
ToperformaByteWrite,themastergeneratesaSTARTconditionand
sendstheslaveaddresswiththedirectionbitsettoWRITE
(zero) asin
figure3 . 2
. Whentheslavedevicematchestheaddress,itsendsanACK
tothemasterduringtheninthclockcycle
. Thenextbytesenttothe
eepromwillbethewordaddressthatmovesitsinternaladdresspointer
.
Thenthedatasentbythemasterwillbewrittentothememorylocation
pointedtobythisaddress
. Finally,themaster
generatesaSTOP
condition,whichwillsignaltheeepromtoinitiatetheinternalwritecycle.
Atthistimetheeepromwillnotgenerateanyacknowledgesignalsuntil
thetransactioniscomplete
.
APageWriteissimilartoaByteWrite,exceptthemastermaytransmit
uptoeightbytesbeforegeneratingastopcondition
. Eachbytesentto
thedevicewillincrementthe addresspointerforthe
nextbyte
transaction
. Theeepromstoresthedatainaneight-bytebuffer,whichis
thenwrittentomemoryafterthedevicehasreceivedastopcondition
fromthemaster,asinfigure3 . 2 .
ControlByte
Word Address
I
A
Section-3 -8
ByteWrite
_- i,oiByte
I I 0 I 1 I 0 I X I X

W dAddress(n]IA`Date(n) I A(Data
(n+11
A I
D t(n+7
A I P i
Figure3 . 2
. Writetransfers .
Page Write
S
:STARTcondition P:STOPcondition El
FromMastertoSlave
W:Writebit(low) R:Readbit(high)
A:ACKbit N:NACKbit
FromSlavetoMaster
ExperimentingwiththePicBasicProCompiler
0
UUBU
Data
an
C d
WordAddressIn) I A A I Data [n]
IN;
P-J
RandomRead
~ bo0~

Data In] J,A jData [n+1]lkr Data [n+2] A I


arls
SequentialRead
S:STARTconditionP:STOPcondition
W :Writebit(low)

R:Readbit(high)
A:ACKbit

N:NACKbit

D
FromSlavetoMaster
Data(n ]
Do
FromMastertoSlave
FigureP.3 .Readtransfers.
Section- 3 -9
GivingthePICamemory
Readoperationsareinitiatedthesamewayasawriteoperationexcept
thedirectionbitissettoREAD(one) .Theeepromkeepstheaddress
pointerfromthelastbyteaccessedincrementedbyone.InaCurrent
AddressReadtransaction,theeepromacknowledgesthemasterafter
receivingtheslaveaddressandtransmitsthedatabytepointedbyits
internaladdresspointer,seefigure3 .3 .Thepointerisincrementedby
oneforthenexttransaction
.SequentialReadsbehavethesamewayas
aCurrentAddressReadtransactionexceptdataiscontinually
transmittedbytheslavedeviceuntilthemastergeneratesaSTOP
conditionseefigure3.3 .
ForRandomRead,themastergeneratesaSTARTconditionthensends
theslaveaddresswiththedirectionbitsettoWRITE (zero). Thenthe
nextbytesentisthewordaddresstobeaccessed.Thisoperationwill
changetheeeprom'sinternaladdresspointer
.Thenwithoutgeneratinga
STOPcondition,aCurrentAddressReadorSequentialReadtransaction
willfollow.
NoticethattheCurrentAddressReadandSequentialReadtransaction
generateanotherSTARTcondition,asshowninfigure3 .3 .
ExperimentingwiththePicBasicProCompiler
Programs -24C32.BAS,24X_TST.BASand24XXX.INC
Interfacingtothe24C321 2Ceeprom
Nowthatweknowtheprincipalsbehindserialeeprominterfacing, we
candevelopapairofsubroutinesthatwillautomatereadingandwriting
tothem
.TheMicrochip24C32isan1 2Cdevicethatcanstore4096bytes
ofdata.Figure3.4showstheeepromsconnectionstothePIC
.
+5Volts
SSA
SCL
VCc
24C32
WP
AO
A1
A2
i
v
Figure3.4.24C32eepromconnections.
Writingtotheeeprom
Thesubroutine EWRITE
isusedforthispurpose. Itexpectstwo
variablestobepre-loadedbeforeitsuse
.Thefirstistheaddresswithin
theeepromwherethedataistobestored,thisisheldinthe
16-bit
variable ADDR,
thesecondisthedatatowritetotheeeprom,thisisheld
inthevariable EBYTEOUT.
Withinthe
EWRITE subroutine,theI2CWRITEcommandsendsthree
lotsofdatatothe12Cbus; firstlythe
slave addressissent, (thismust
alwaysstartwith%1010,whichistheserialeepromdeviceidentifier)
. If
thereismorethanoneeepromonthe1
2Cbusthenthenextthreebitswill
reflectthepatternontheA2,Al andAOpins
.However,forthis
demonstrationweareonlyusingonedevice,therefore,theyarecleared.
Sotheslaveaddressis%10100000,theI2CWRITEcommandwill
automaticallysettheread/writebit
.Thenextlotofdatasentisthe16-bit
memoryaddress,andfinallytheBYTEorWORDsizedvalueto
be
placedattheaddresslocationissent
.Adelayof10msisrequiredafter
thewriteisperformed
; thisallowstheeepromtimetoallocatethedata
intoitsmemoryarray
: -
EWrite:
12CWRITESDA,SCL,%10100000,Addr,[E_ByteOut]'Writethebyte
Pause10

'Delay10msaftereachwrite
Return
Interfacingtothe24C32eeprom
Section-3-
1 0
ExperimentingwiththePicBasicProCompiler
Interfacingtothe24C32eeprom
IfthevariableE_BYTEOUT
isdeclaredasaBYTE,then8-bitswillbe
written
.IfthevariableisdeclaredasaWORDthen16-bitswillbewritten
Readingfromtheeeprom
Thesubroutine EREAD
isusedforthispurpose
.Itreads8or16-bits
fromtheeeprom
.Beforethesubroutineiscalled,theaddressofinterest
mustbeloadedintothevariable ADDR .
Uponreturningfromthe
subroutine,thedatafromthespecifiedaddresslocationisheld
inthe
variable EBYTEIN.
The EREAD
subroutineusestheI2CREADcommand
.Theslave
address
(asinEWRITE)
andthe16-bitmemoryaddressaresent.Then
thedataisreadintotheassignedvariable
.Itsuseis: -
ADDR=1024
`Pointtolocation1024withintheeeprom
GosubEread
'Readthedatafromthespecifiedlocation
ThevariableE_BYTEINnowholdsthebyteofdata
ERead:
12CREADSDA,SCL,%10100000,Addr,jEBytelnJ
'Readthebyte
Return
Unfortunately,thecompiler's12CREADandI2CWRITEcommands
do
notusetheacknowledgereturnsfromthebus
.Therefore,thismethod
cannotbeusedtoverifywhetherasuccessfulwritehasbeenperformed
.
Onewaytogetroundthis,istoreadthedatabackfromthesame
addressthatithasjustbeenwrittento,andcomparetheresult
.
Forexample.
Write:
ADDR=1024

`Pointtolocation1024withintheeeprom
EBYTEOUT=128

'Placethevalue128intheaddress
GosubEWrite

`
Writethebytetothespecifiedaddress
GosubEread

`Readthedatafromthesameaddress
IfEBytein<>EByteoutthengotoWRITE

`Comparethem
Thiscomparesthevariable
E_BYTEIN
withthevariable EBYTEOUT,
andiftheyarenotthesamethentheWRITEprocessiscarried
out
again
.Thiswillslowdownthewritingprocessslightly,butasuccessful
writeisguaranteed
.Unlesstheeepromhascometotheendofitslife
.
Section-3 -
1 1
ExperimentingwiththePicBasicProCompiler
Interfacingtothe24C32eeprom
Theincludefile 24XXX.INC, containsthetwosubroutines,
EREAD, and
EWRITE.
Thisshouldbeloadednearthebeginningofthemainprogram,
justafterdeclaringtheSCLandSDApinassignments
: -
SCL
VAR PortB.0 `AssignPortB.0 toSCL
SDAVAR PortB.1
`AssignPortB.1 toSDA
Include"24XXX.INC"

`Loadtheread/writesubroutines
Thevariable, ADDR isalreadypre- declaredwithintheincludefile
.The
variables
E_BYTEIN and EBYTEOUT needtobedeclaredwithinthe
mainprogram
.Dependingonhowthesevariablesaredeclareddictates
ifan8or1 6- bitread/writeisperformed .Forexample.
Declaring EBYTEIN
asaWORDtypewillenable1 6- bitreads,and
declaringitasaBYTEtypewillenable8- bitreads
.Thesameappliesfor
EBYTEOUT .
Thisispossibleduetothe1 2Ccommand'sabilityto automatically
detectingifavariableisabyteoraword,thustransferring8or1 6- bits
.
NOTE.Thesubroutinesmaybeusedforthe24C1 6,24C32,24C64,and
24C65eeproms.Theymayworkonother24xxxserieseeproms,
but
havenotbeentested .
Section- 3- 1 2
ExperimentingwiththePicBasicPro
Compiler
Programs-SSP_24XX
.BAS,SSP_TST,andSSP24XX.INC
Interfacingtothe24C32eeprom,usingtheMSSPmodule
Thenewmid-rangePICs,16F872,873,874,876,and877allhavea
mastersynchronous serialportmodule
(MSSP), whichmaybe
configuredasanSPImaster/slaveor1 2
Cmaster/slave.Weareintending
toreadandwritetoa24C32eeprom,therefore,wewilldiscusshowto
configure,andusetheMSSPasan1
2Cmasterdevice .Thereareseveral
registersandbitsthatneedtobemanipulatedformastermodetobe
configured
.Wewilllookateachregisterinturn
.
Firstly,theSDA (PORTC.4) andSCL
(PORTC.3) pinsneedtobemade
inputs.
TheCKEbit (SSPSTAT
.6) needstobecleared
.Thiswillconfigurethe
MSSPmoduletocomplywithnormal1
2Cspecifications.
TheSMPbit (SSPSTAT
.7) needstobeset
.Thisdisablestheslewrate
control,
(whichisnotneededfora100kHzbusspeed) .
ThefirstfourbitsofSSPCONaregiventhevaluesof%1000
.
This
configurestheMSSPasan1
2Cmaster.
Thebaudrategeneratorregister
(SSPADD) isnextloadedwiththebus
speedrequired.Theformulaforthisis: -
SSPADDvalue=(OSC/(BUSSPEED*4))-1
Inthisexperiment,wearegoingtouseabusspeedof100kHz,andan
oscillatorof20mHz
.Therefore,thevalueplacedinSPPADDis49
.This
isautomaticallycalculatedforusintheprograms
.
Lastly,theMSSPmodulehastobeenabled
.Thisisaccomplishedby
settingtheSSPENbit (SSPCON
.5).
NowthatwehavetheMSSPconfigured,thenextthingtodoiswritea
pairofsubroutinesthatmanipulatethe1 2
Cbusforreadingandwritingto
theeeprom.
Section-3- 1 3
ExperimentingwiththePicBasicProCompiler
Interfacingtothe24C32eepromusingtheMSSPmodule
AtypicalsequenceforWRITINGtoaserialeepromis : -
SendSTART : Thestartconditionenablebit,SEN (SSPCON2. 0 ) must
beset. Afterthestartcommandhasbeensent,theSEN
bitwillbe
cleared . Ifabuscollisionoccurred,theinterruptflagBCLIF (PIR2. 3) will
beset.
Sendslaveaddress: TheslaveaddressisloadedintotheSSPBUF
registerwiththeR/Wbit(DO) cleared . ThecodemustchecktheRWflag
(SSPSTAT. 2 toseewhetherthePIChasfinishedtransmittingits8- bits.
Uponcompletingthetransmission,thebufferfullflag,BF (SSPSTAT. O)
willbecleared
. Theeepromnowacknowledgesthebyte,andthis is
placedintheacknowledgestatusflagACKSTAT (SSPCON2. 6 ) . Ifan
acknowledgewasreceived,thisflagwillbecleared,ifnotthentheflag
willbeset.
Sendhighbyte(MSB) ofmemoryaddress: Thesamesequenceas
above,butthehighbyteofthememoryaddressissentinsteadofthe
slaveaddress.
Sendlowbyte(LSB) ofmemoryaddress: Thesamesequenceas
sendslaveaddress,butthelowbyteofthememoryaddress issent
insteadoftheslaveaddress
.
Sendthebytetoplaceintotheeeprom : Thesamesequenceassend
slaveaddress,butwiththebytetoplaceintotheeepromsentinsteadof
theslaveaddress.
SendSTOP: Thestopsequenceenablebit,PEN (SSPCON2. 2) mustbe
set
. Afterthestopcommandhasbeensent,thePENbitwillbecleared,
andtheinterruptflag,SSPIF (PIR1. 3) is set.
Section- 3 - 1 4
ExperimentingwiththePicBasicProCompiler
Interfacingtothe24C32eepromusingtheMSSPmodule
AtypicalsequenceforREADINGfromaserialeepromis : -
Send
START: Thestartconditionenablebit,SEN (SSPCON2.0) must
beset.Afterthestartcommandhasbeensent,theSEN bitwillbe
cleared.Ifabuscollisionoccurred,theinterruptflagBCLIF
(PIR2.3)will
beset.
Sendslaveaddressforwrite : Theslaveaddressisloadedintothe
SSPBUFregisterwiththeR/Wbit (DO) cleared.Thecodemustcheck
theRWflag (SSPSTAT.2) toseewhetherthePIChasfinished
transmittingits8- bits .Uponcompletingthetransmission,thebufferfull
flag,BF (SSPSTAT.O) willbecleared .Theeepromnowacknowledges
thebyte,andthisisplacedintheacknowledgestatusflagACKSTAT
(SSPCON2.6) . Ifanacknowledgewasreceived,thisflagwillbecleared,
ifnotthentheflagwillbeset.
Sendhighbyte(MSB)ofmemoryaddress: Thesamesequenceas
above,butthehighbyteofthememoryaddressissentinsteadofthe
slaveaddress.
Sendlowbyte (LSB) ofmemoryaddress: Thesamesequenceas
sendslaveaddressforwrite,butthelowbyteofthememoryaddressis
sentinsteadoftheslaveaddress .
Send RESTART: Therepeatedstartcondition enablebit,RSEN
(SSPCON2.1 ) mustbeset.Aftertherestartcondition hasbeen
transmitted,theRSENbitiscleared,andtheSSPIFflagisset.
Sendslaveaddressforread : Theslaveaddressisloadedintothe
SSPBUFregisterwiththeR/Wbit (DO) set.Andthesamesequenceof
eventsoccurasforthefirstslaveaddresstransmission
.
Send ENABLERECEIVE: Thereceiveenablebit,RCEN (SSPCON2.3
mustbeset.Thishastheeffectofmakingtheslave (eeprom) a
temporarymaster.Afterreceivingthe8- bitsfromtheeeprom,theRCEN
bitisclearedandthebuffer- fullflag (BF) isset.Thecontentsofthebuffer
(SSPBUF) isthenread,thisautomaticallyclearsthebuffer- fullflag(BF) .
Section- 3- 1 5
ExperimentingwiththePicBasicProCompiler
Interfacingtothe24C32eeprom
SendNACK: Theslave (eeprom)is
stillatemporarymaster,therefore,
tonotifyittobeaslaveagainitmustbesentaNACK
(notacknowledge)
command (thisreleasestheSDAline). Firstly,theacknowledgedatabit,
ACKDT
(SSPCON2. 5 ) andtheacknowledgesequenceenable bit,
ACKEN (SSPCON2. 4)
mustbeset. TheACKENbitisautomatically
clearedwhentheNACKcommandisover.
SendSTOP:
Finally,thestopsequenceenablebit,PEN (SSPCON2. 2)
mustbeset
. Afterthestopcommandhasbeensent,thePENbitwillbe
cleared,andtheinterruptflag,SSPIF
(PIR1
. 3)
isset.
Theprogram
SSP24XX. BAS, readsandwritestoa24C32eeprom.
Thefirstelevenbytesoftheeepromarewrittento,andthenreadback,
thisisdisplayedonaserialLCDconnectedtoPortA. O
. Theprogram
breaksuptheaboveproceduresintoasetofsubroutines,send_start,
sendstop,sendnacketc,andthenusestwomainsubroutines for
writingandreadingtoandfromtheeeprom
.
Thewritingsubroutine, EWRITE, expectstwovariablestobepre-loaded
beforeitiscalled
. Thevariable ADDR, holdsthememoryaddresswithin
theeeprom,and EBYTEOUT,
holdthebytetoplaceintotheeeprom .
Thereadingsubroutine, EREAD, musthavethe ADDR variableloaded
beforeitiscalled
. Uponreturning,thebytereadfromtheeepromisheld
inthevariable EBYTEIN.
Onethingthatyoumusthavenoticed (I knowIdid)is thatforahardware
solutiontheresureisalotofcodeneeded
. Tominimize thecode
overhead,assemblersubroutinesmustbeused
. Thatisthepurposeof
theincludefile
SSP24XX. INC, thishasexactlythesamelayoutasthe
BASICprogram,exceptitisalotsmaller
. Thetwosubroutines, EREAD
and EWRITE areagainused,withoneexception
. Theslaveaddress
mustbepre-loadedbeforethesubroutinesarecalled,thisisheldinthe
variable,
SLAVEADDR . Asthe12 Cbuscansupportuptoeightserial
eeproms,thevalueplacedwithinthisvariablemaybebetween 0. . 7 .
TheMSSPmoduleisautomaticallyconfiguredwhentheincludefile
is
loaded,alsothevariables, ADDR,EBYTEIN,E_BYTEOUT, and
SLAVEADDR arepre-declared.
Section-3 - 1 6
ExperimentingwiththePicBasicProCompiler
Interfacingtothe24C32eeprom
UsingthepseudocommandsEREADandEWRITE
Analternativemethodforreadingandwritingtotheeepromistheuseof
twonew
pseudocommands. Thesearealsonamed EREAD and
EWRITE,
andarereadyforusewhentheincludefile SSP24XX. INC is
loaded. Theirsyntaxanduseareexplainedbelow.
Theeepromwritingcommandiscalled
EWRITE, itssyntaxis: -
EWRITEslaveaddress,memoryaddress,bytewrittentotheeeprom
Theslaveaddressmustbeaconstantbetween0- 7 . Thememory
addressmaybeanyWORDvariable
. ThebytewrittenmaybeanyBYTE
variable. Itsuseis : -
Address VarWORD

SYSTEM 'Eeprommemoryaddress
Byte- SentVarBYTE

SYSTEM
`Byteplacedintoeeprom
Address=1000

`Pointtoaddress1000
Byte_Sent=128

`Write128intotheeeprom
@ EWRITE0,Address,ByteSent`Writethebyte
Theeepromreadingcommandiscalled EREAD, itssyntaxis : -
EREADslaveaddress,memoryaddress,bytereadfromtheeeprom
Theslaveaddressmustbeaconstantbetween0- 7 . Thememory
addressmaybeanyWORDvariable
. ThebytereadmaybeanyBYTE
variable. Itsuseis : -
Address VarWORD

SYSTEM 'Eeprommemoryaddress
Byte_RecVarBYTE

SYSTEM `Bytereadfromeeprom
Address=1000

`Pointtoaddress1000
Cam? EREAD0,Address,Byte_rec
`Readthebyte
`ThevariableByteRecnowholdsthevaluereadfromtheeeprom
The@symbolmustalwaysprecedethepseudocommand,asitis
essentiallyanassemblermacro .
Section- 3 - 17
ExperimentingwiththePicBasicProCompiler
Programs - 93C66
.BAS
Interfacingtothe93C66Microwireeeprom
ReadingandwritingtotheAtmel93C66eepromisslightlymoreinvolved
thanits1 2 Ccounterpart,becauseitusesinstructionsintheformof
op-
codes
toinformtheeepromastowhatfunctionitshouldperform
.Also,
theexactamountofbitsperinstructionmustbesent, otherwisethe
eepromwillignoretheinstructionandreturntostandby
.
Abriefdescriptionoftheseveninstructionsisshownintable3
.2 .
Table3.2
.Instructionsetfor93C66:ORG=0(x8organization)
.
Theprogram 93C66.BAS,
writesthestringofcharacters"HELLO
WORLD"tothefirstelevenlocationswithintheeeprom,thenreadsthem
backanddisplaysthemonaserialLCDconnectedtoPortA.0 .Figure3.5
showstheeeprom'sconnectionstothePIC
.
Foursubroutinesareusedwithinthemainprogram,theseare
: -
EWRITEEN,
enablestheeepromforwritingbyshiftingouttheop-code
%1 001 1 ,followedbyseven dummybits.No
variablesneedbeset .
EWRITEDS,
disablestheeepromforwritingbyshiftingouttheop-code
%1 0000,followedbyseven dummybits.No
variablesneedbeset .
EWRITE,
bringstheCSlinehigh (enablingtheeeprom),
thenwritesa
bytetotheeeprombyfirstshiftingouttheop-code%1 01 0,followedby
thememoryaddress,heldinthevariable
ADDR, thenthebytetosendto
theeepromisshiftedout,whichisheldinthevariable
EBYTEOUT. The
CSlineisthenpulledbacklow
(disablingtheeeprom), andadelayof
1 0msisexecuted,thisallowsthebytewrittentotheeeprom
tobe
allocatedwithinitsmemoryarray : -
Section-3- 1 8
Instruction Start-bit Opcode Address DataIn
DataOut ReqClkcycles
READ
1 1 0 A8- AO --- D7-DO
2 0
EWEN 1
00 1 1 XXXXXXX --- High -Z
1 2
ERASE
1 1 1 A8-AO --- (RDY/BSY)
1 2
ERAL 1 00
1 oxxxxxxX --- (RDY/BSY) 1 2
WRITE 1 01
A8 - AO D7- DO (RDY/BSY) 2 0
WRAL 1 00
O1 XXXXXXX D7- DO (RDY/BSY) 2 0
EWDS 1 00
OOXXXXXXX --- Hiqh -Z 1 2
ExperimentingwiththePicBasicProCompiler
Figure3 . 5 . 93C66eepromconnections.
R1allowsthedata-inandthedata-outlinestosharethesamePICpin .
R2isprecautionaryonly,itensuresthatwhenthecircuitisfirstpowered
upthechipisdisabled . Thismaybeomittedifrequired .
Section-3 - 1 9
Interfacingtothe93C66eeprom
Ewrite:
HighCS

'Enabletheeeprom
SendWRITEcommand,ADDRESSandDATA
ShiftoutDI,SK,MSBFIRST,[EWRI4,Addr,EByteout]
LowCS

'Disabletheeeprom
Pause10

'Allowtheeepromtoallocatethebyte
Return
EREAD, bringstheCSlinehigh (enablingtheeeprom), thenreadsa
bytefromtheeeprombyfirstshiftingouttheop-code%1100,followedby
thememoryaddress,heldinthevariableADDR,itthenshiftsinthebyte
fromtheeepromtothevariable E_BYTEIN. TheCSlineisthenpulled
backlow (disablingtheeeprom) : -
Eread:
HighCS

'Enabletheeeprom
'SendREADcommandandADDRESS
ShiftoutDl,SK,MSBFIRST,[ERDI4,Addr]
'ReadthedataintoE_BYTEIN
ShiftinDO,SK,MSBPOST,(EByteinJ
LowCS

'Disabletheeeprom
Return
CaremustbetakenwhenchoosingaMicrowiredevice. Forexample,
Microchiphastwoversionsofthe93C66,onehasthedenomination'A'
afterthename,theotherhasa 'B' . TheAtypeispermanentlyconfigured
as5 12wordsx8-bits,whiletheBtypeisconfiguredas25 6wordsx16-
bits. Inbothtypes,theORGpinisnotimplemented . Thesameapplies
fortheir93LC66versions.

+5 v
ToRBO
ToRB1
ToRB2
ExperimentingwiththePicBasicProCompiler
Programs -25LC640.8AS
Interfacingtothe25LC640SPIeeprom
Microchip's25LC640isa64Kbitserialeeprom,whichisorganisedas
8192wordsx8-bits,andusesanSPIinterface .Readingandwritingto
the25LC640hassimilaritiestoMicrowireinterfacing,althoughitis
somewhateasiertoimplement
(thiscouldbeonepossiblereasonwhy
theMicrowireinterfaceisbecomingunpopularwithdesigners) .SPI
eepromsarecertainlyeasiertoimplementwithlowlevelprogramming
(assembler), thantheir12Ccounterparts .
SPIeepromsstilluseinstructionstoperformspecificfunctions (read,
writeetc), however,itisnotasstringentwithitsprotocolasMicrowire
.A
briefdescriptionofthesixinstructionsisshownintable3
.3.
Table3
.3.Instructionsetfor25LC640.
Theprogram 25LC640.BASwritesthestring,"HELLOWORLD"tothe
first11locationswithintheeeprom
.Thenreadsthembackanddisplays
thecharactersonaserialLCDconnectedtoPortA.O.Figure3.6shows
theeeprom'sconnectionstothePIC .
Theprogramisbasedaroundtwosubroutines,
EREAD, and EWRITE,
theseperformthereadingandwritingtotheeeprom.
Thesubroutine EWRITE, enablestheeeprombypullingtheCSlinelow,
thenshiftsouttheWRITEENABLEop-code
(6). TheCSlineisthen
broughthightolatchtheinstructionintotheeeprom,andimmediately
pulledlowagain.TheWRITEop-code(2)isthenshiftedout,alongwith
thehighbyteandlowbyteoftheaddressvariable, ADDR.
Thebytetobe
placedintotheeepromisthensent,thisisheldinthevariable
EBYTEOUT. TheCSpinisreturnedtoitshighposition (disablingthe
eeprom), andadelayof5msisexecuted,allowingthebytetobewritten
totheeepromsmemoryarray.
Section-3 - 20
Instruction Op-code InstructionDescription
READ 00000011
Readmemoryfrommemoryarray,beginningatselectedaddress
WRITE 00000010
Writedatatomemoryarray,beginningatselectedaddress
WREN
00000110 Setthewriteenablelatch(enablewriteoperations)
WRDI
00000100 Resetthewriteenablelatch(disablewriteoperations)
RDSR 00000101 ReadtheStatusregister
WRSR 00000001 WritetotheStatusregister
ExperimentingwiththePicBasicProCompiler
To RBO
ToRBI
ToRB2
VSS
R2
10K
R1
1K
0V
Figure3.6 .25LC640eepromconnections .
Resistor,R1allowsthedata-inandthedata-outlinestosharethesame
PICpin.Resistor,R2isprecautionaryonly,itensuresthatwhen the
circuitisfirstpoweredupthechipisdisabled .Thismaybeomitted if
required .
Asiscommonpracticenow,anincludefilehasbeenaddedtoallowthe
readingandwritingofSPIeeproms.Thisiscalled 25XXXX.INC, and
containsthetwosubroutines, EREAD, and EWRITE. Thisshouldbe
loadednearthebeginningofthemainprogram,justafterdeclaringthe
CS,SCK,andSIpinassignments: -
CS
Var PortB.0
'AssigntheCSlinetoPortB.0
SCK VarPortB.1 'AssigntheSCKlinetoPortB .1
SI

VarPortB.2 'AssigntheSIlinetoPortB.2
Include"25XXXX
.INC"

'Loadintheeepromsubroutines
TheSOlineisautomaticallyassignedtothesamepinastheSIline,and
thevariables, ADDR,E_BYTEIN, and E_BYTEOUT
arealreadypre-
declaredwithintheincludefile.
NOTE.OtherSPIeepromsinthesamedevicefamilyasthe25LC640,
suchasthe25LC040orthe25LC080,mayalsobeusedwiththese
subroutines
.
Interfacingtothe25LC640eeprom
Thesubroutine, EREAD, bringstheCSlinelow,enablingtheeeprom,
andshiftsouttheREADop-code ( 3) .
Thehighbyteandlowbyteofthe
.addressvariable,ADDRarethensent,andthebytefromtheeeproms
memoryarrayisshiftedintothevariable E_BYTEIN . Theeepromisthen
disabledbyreturningtheCSlinetoitshighstate
.
Section-3 - 21
ExperimentingwiththePicBasicProCompiler
Section-4
Experimenting
with
AnaloguetoDigital
Converters
InterfacingwiththeMAX186ADC
.
Usinga3-wireinterfacewiththeMAX186.
UsinganexternalreferencevoltagefortheMAX186
.
Quantasizingtheresult.
UsingtheMAX187ADC
.
InterfacingtotheMAX127ADC .
UsingtheonboardADC
.
AchievinggreateraccuracythroughSLEEP.
UsingtheADCINcommand
.
Analternativequantasizingformula.
Ironingoutnoisyresults
.
ExperimentingwiththePicBasicPro
Compiler
Program -MAX1861.BAS
InterfacingwiththeMAX186AIDConverter
Mostrealworldapplicationsworkwithanaloguelevels
: -temperature,
light,etc
.Thisanaloguedataneedstobechangedintoaformatthata
PICcanunderstand,anduse
.Thisisnormallyachievedwithan
AnaloguetoDigitalConverter (ADC).
SomeofthePICseriesof
microcontrollershavebuiltinAIDConverters,butarelimitedto8-bitor
10-bitresolution,inmostcasesthisisenough,butforapplicationsthat
requireahigherresolution,anexternalAIDConverterisnecessary
.
TheMAX186isaneightchannel,12-bit,successiveapproximationAID
Converter,utilizinga3,4or5-wireinterface
(clock,cs,dataout,datain
andoptionalstrobe).
Itmaybeconfiguredtouseitsowninternal
referencevoltageoranexternalsource,andiscapableofperforminga
conversionin6 - 10us .
Figure4
.1showsademonstrationalcircuittointerfacewiththeMAX186.
BeforeasamplecanbereadfromtheMAX186acontrol-bytehastobe
sent,thiscontrol-byte,
(whichisthepurposeofpinDIN), informsthechip
as'towhichinputtosamplefrom,aswellaswhatformofsamplingto
take
(bipolaroruni-polar) etc .Thereisnotenoughroomtogothroughall
thefeaturesoftheMAX186,ThedatasheetfortheMAX186maybe
foundontheaccompanyingCDROM
.However,table4.1,showsa
summaryofeachbitwithinthecontrol-byte .
Table4.1 .MAX186controlbyte
.
Section-4-1
Bit Name
Description
7(MSB)
START Thismustalwaysbeone,definesthebeginningofthecontrol
byte
6
5
4
SEL2
SEL1
SELO
Thesethreebitsselectwhichoftheeightchannelsareusedforthe
conversion
3
UNI/BIP
1=unipolar,O=bipolar.Selectsunipolarorbipolarconversion
mode.
Inunipolarmode,aninputsignalfromOVtoVREFcanbeconverted
.
Inbipolarmode,thesignalcanrangefrom-VREF/2to+VREF/2
.
2
SGUDIF
1=singleended,O=differential.Selectssingle-endedordifferential
conversions .
Insingle-endedmode,inputsignalvoltagesarereferredtoAGND.
Indifferentialmode,thevoltagedifferencebetweentwochannels is
measured.
1,0(LSB) PD1
PDO
Selectsclockandpower-downmodes
.
PD1PDOMode
0

Fullpower-down
0

Fastpower-down
1

Internalclockmode
1

Externalclockmode
ExperimentingwiththePicBasicProCompiler
Table4 . 2
. MAX186channelselectbits.
TheMAX186hasaninternalreferenceof4 . 096V,whichmeansthata
voltageofupto4
. 095Vonanyoftheinputchannelswillresultinthe
samevaluebeingsentseriallytothePIC
. Theprogram MAX186I. BAS
demonstratesthis
. ThepotentiometerVR1,actsasavariablepotential
dividerconnectedtochannel0oftheMAX186,thusvaryingthevoltage
appliedtotheinput,from0to5V
. Thisvoltageisdisplayedonaserial
LCDsetupforInverted9600baud,andconnectedtoPortA
. 0 .
ThecodeforreadingtheMAX186isinthesubroutine MAX186IN, but
beforethissubroutineiscalled,thechannelofinterestisloadedintothe
variable MAXCH.
ThesubroutineusestheLOOKUPcommand,which
holdsall8combinationsofthe3-bitchanneladdresses
(asintable3) .
Thecontrol-byte variable CNTRLis pre-loaded withthevalue
%10001110,(start,unipolar,single-endedandinternalclock), andthe3-
bitaddressnowheldin MAX-CH
isORedwithit,thissuperimposesthe
channelbitsintothecontrol-byte .
LookupMaxCh,j0,64,16,80,32 ,96,48,112 1,MaxCh
Cntr1=%10001110/MaxCh

'"OR" intheChannelbits
TheMAX186isthenactivatedbypullingtheCSpinlow,andthecontrol-
byteisshiftedout
. Immediatelyafterthis,the12 -bitvoltageconversion is
shiftedin,andtheMAX186isde-activatedbybringingtheCSpinhigh
.
Thevariable MAX_VAL
nowholdsthe12 -bitvoltagereading (0-4095) .
Section-4 -2
InterfacingtotheMAX186NDConverter
Inthisseriesofexperiments,wewillbeusingsingle-ended unipolar
inputs (0toVret) andaninternalclock
. Therefore,theonlypartofthe
control-bytethatneedstobechangedarethechannelselection
bits
(SEL
0-2 ), Thesebitsareshownbelowintable4 . 2 .
SEL2 SEL1 SELO Channel
0 0 0 CHO
1 0 0 CH1
0 0 1 CH2
1 0
1 CH3
0
1 0 CH4
1 1 0
CH5
0 1 1 CH6
1 1 1 CH7
ExperimentingwiththePicBasicProCompiler
Ih
n
e
2
>Y
O
~II-I~Iml~lml
Section-4-3
InterfacingtotheMAX186AIDConverter
LowCS

`ActivatetheMAX186
ShiftoutDin,Sclk,Msbfirst,[Cntrll8]

`ShiftouttheControlbyte
ShiftinDout,Sclk,Msbpost,[MaxVall12]`Shiftin12bits
HighCS

`DeactivatetheMAX186
TheSSTRBpinmaybeusedtomakesurethattheMAX186hasfinished
aconversionbeforethe12-bitvalueisshiftedin
.Thispingoeshigh
whenaconversioniscomplete,howeverthePICisfastenoughinmost
casestojustignorethispin : -
WhileSSTRB=O: Wend

`Waitforendofconversion
Figure4 .1
.MAX186demonstration .
n
o
m
7
R
9
N
Vo
.-
U
o
1II--
1 IF-
N
n
e
e,
V
$
av
~ , ~a ~~
I

0 CD
U.
m
t0
0
O

a.
-
z> a >

N!
0 .
ff
F
yJ
m om '
f~ O
G
at
0 !
oMI-J-,Wi
Im
a
o
0

>N~
ow
m
$>
o
ON0 7 f u7< Of~

^
52222=22

Z
110 0 0 0 0 0 0 0
ExperimentingwiththePicBasicProCompiler
Program -3_WIRE.BAS

InterfacingtotheMAX186A/DConverter
UsingathreewireinterfacewiththeMAX186
Usinga5-wireinterfacetodemonstratetheuseoftheMAX186is
acceptable,butinnormaluseweonlyrequire3wires .Thisispossible
duetothePIC'sabilitytochangeitspinstatefrominputtooutputalmost
instantaneously,whichmeansweareabletoconnecttheMAX186'sDIN
andDOUTpinstogether,R1isinplacetolimitthecurrentflowbetween
thePICI/OpinandtheMAX186'sdataoutput,incaseaprogramming
errorcausesabusconflict,thishappenswhenbothpinsareinoutput
modeandinoppositestates(1vs0)
.WithoutR1,largecurrentswould
flowbetweenthepins,possiblycausingdamagetooneifnotbothofthe
devices.WealreadyknowthattheSSTRBpinmaybeomitted
.This
leavesjust3pinsusedbythePIC,andasmallchangeofcode.
Theprogram 3-WIRE.BAS
showshowthe3-wireinterfaceisused,and
figure4 .2showsthenewlayoutfortheMAX186 .
MAX186
VREF
AGNDVSSDGND
13
i
74 C5

C6
4 .7uf
T
T0.01ut
Figure4 .2 .MAX1863-wireinterface.
Section-4 -4
Regulated 5volts
VR1
10klinear
20
IC1
CHOVDD
a
CH1

SHDN
-
R2
i
CH2
13
s
CH3

SSTRB 1 5
ik
s
CH4

DOUT 17
CH5

DIN 1B
O RB2
B
CH6

IN
1 9OTo RB1
CH7

SCLK
0 RBO
12
REFADJ
ExperimentingwiththePleBasicProCompiler
Program -
MAX186E.BAS
UsinganexternalVREFfortheMAX186
Asmentionedearlier,becauseofitsinternalvoltagereferencethe
MAX186givesafull-scalereadingof4
.095V.However,anyvoltage
abovethisisnotconverted
.Ifthefull-scalereadingneedstobelesseror
greaterthanthisvoltage,anexternalvoltagereferenceisrequired
.This
cantaketheformofasimplepotentiometer,actingasavariable
potentialdivider,connectedtotheVrefpin
(crude,buteffective), asin
figure4
.3 .OrtheVrefpincanbeconnectedtoVdd,
(whereVddis
regulated5Vj,
asinfigure4 .4 .
Connect
toVdd
REFADJ
VR2
VREF

47k
DGND

linear
VREF
AGND VSS DGND
Regulated5volts
s

C5
0 .01of
Figure4 .4
.MAX186externalVrefconnections .
Section-4 -5
InterfacingtotheMAX186AIDConverter
Figure4 .3 VariableVref
.
VR1
10klinear
20
Ic1
CHO
VDD
10 2
3
CH1
SHDN
a
CH2
15
R2
1k
5
s
i
CH3
CH4
CH5
SSTRB
DOUT
DIN
15
O RB2
1
8 oTo RB1
8
CH6
CH7 SCLK
lam`
1
9 O
RBO
REFADJ
12
MAX186
11
ExperimentingwiththePicBasicProCompiler
InterfacingtotheMAXI86AIDConverter
Quantasizingtheresult
WhentheVrefpinisconnectedtoVdd,thefull-scalereadingof4095
nowrepresents5V,sotheoutputfromtheAID,nolongerrepresentsthe
inputi.e
.2000isnolonger2.OOV.Thisisbecauseouranalogueinput
containsanalmostinfinitenumberofpossiblevaluesbetween0to5V
.
However,theresolutionoftheMAX186is12-bits
(4096), whichforces
theAIDtouseeachofitspossiblecombinationstorepresentasegment
oftheanalogueinput.
Forexample,ifwewereconvertinga0to5Vanalogueinputusinga4-bit
AID .The4-bitbinarynumberwouldrepresentarangeof0-15
.Dividing
the5Vanaloguerangeinto15equalsegmentswouldresultin
approximately
.33Vpersegment.Thesesegmentsarecalled
quanta
levels.To calculatethe quantalevel
fortheMAX186weneedtodivide
theVrefvoltage (+5Vinthiscase)
withtheresolutionused,whichis
4096 : -
quantalevel=VREF/A/Dresolution
Therefore: -
quantalevel=5/
4096
Thisgivesusa
quanta level of
.0012207V,however,becausethe
compileronlyworkswithrealnumbers
(integers), thisistoosmallavalue
forittohandle,therefore,wewillroundituptoamoremanageablevalue
of123,onehasbeenaddedtothefinalquantaleveltotakeintoaccount
thatthecompilertruncates
(roundsdown) anyresultofadivision
.We
nowhaveour quantalevel
.Tocalculatetheactualvoltageontheinputof
theAIDweuse: -
Actualvoltage=Resultofconversion*quantalevel
Letssupposeaconversionhastakenplaceandtheresultreturnedis
2382,ourcalculationwillnowbe: -
Actualvoltage=2382*123
Thiswouldgivearesultof292986,butthisvalueistoolargeforthe
compilertohandle,soonepartofthecalculationneedstobereduced
.
Section-4-6
ExperimentingwiththePicBasicProCompiler
Section-4 -7
InterfacingtotheMAX186AIDConverter
Toacheivemoreaccurateresultsitwouldbebettertoreducethelarger
ofthetwonumbers
.Thereforeourcalculationnowlookslikethis : -
Actualvoltage=(2382/10)*123
Theactualvoltageisnow29298
.6,butbecausethecompilerhandles
arithmeticwithintegervaluesonlyandalsotruncates,theactual
result
placedinthevariable
MAX_VALis2927 4.
Thevalue2927 4isanicerealnumbertoworkwithinsidethecodeitself,
butfordisplaypurposesitismoremeaningfultoviewitas2
.927 4Volts.
Thereforewemustsplitoffthenumberstotherightofthedecimalpoint,
luckily,butnotsurprisinglythecompilerhasacommandtocalculatethe
integerremainderofadivision
.Theoperatorfordivision is/andthe
operatorforcalculatingtheremainderis//.
Forexample: -
Theintegercalculation, VOLTS=2927 4/10000
wouldresultinVOLTS
holdingthevalue2 .
Andtheintegercalculation,
MILLIVOLTS=2927 4//10000 wouldresult
in MILLIVOLTS
holdingtheremainderofthecalculation,whichis927 4 .
Inthedemonstrationprogramstheactualcodelookslikethis
: -
VOLTS=MAXVAL/10000
MILLIVOLTS=MAXVAL//10000
Sonowwehavetwonewvariables,VOLTSand MILLIVOLTS andwe
candisplaythemwithadecimalpointplacedin-between
: -
DEBUGdeciVOLTS,
".", dec4MILLIVOLTS,"Volts"
WhichwilldisplayontheLCD
2.927 4Volts
Theprogram, MAX186E.BAS demonstratesthesecalculations
.
ThisformulaisnotonlyusefulfortheMAX186demonstration,itworks
forallA/DConverters,whether8,10,12or16-bit
.
Experimenting with the PicBasic Pro Compiler
Programs- MAX187I . BA &MAX187E
. BA
I nterfacing with the MAX187 AI D Converter
The MAX187 is the little brother of the MAX186
. I t only has one input but
still has a resolution of 12 -bits and can use its internal 4
. 0 9 6 V reference
voltage, or and external source
. The wonderful thing about this chip is its
ease of use, as it has no control byte, it may be accessed with only three
lines of code
. F igure 4 . 5 illustrates its use with an internal Vref and figure
4 . 6 shows its external Vref counterpart
. Note that the HDN pin must be
connected to Vdd to use the internal reference, and left unconnected to
use an external source
. The pins CL K, C , and DOUT connect to the
PI C' s PortB as in the previous section on the MAX186
.
VR1
10 k
linear
DD
DOUT
HDN

Z3
CL K
MAX187
AI N

VREF
~
F igure 4
. 5 . MAX187 internal Vref .
ection-4 - 8
VDD
DOUT
HDN

C' 9
CL K
MAX187
AI N

VREF
V
F igure 4 . 6 . MAX187 external Vref
.
Program,
MAX1871. BA demonstrates how easy it is to use this device
.
I t uses the internal Vref, therefore the voltage that can be read is 0 to
4 . 0 9 5 V .
Program, MAX187E
. BA is based on an external Vref connected to
VDD, this will give a range of 0 to 5 V full-scale
.
The subroutine
MAX187_I N,
enables the MAX187, by bringing the C
line low, then shifts in the 12 -bit result, it then de-activates the chip
by
setting the C line high
. I n the external Vref program the same formula
for calculating the quanta levels are used as in the MAX186 code
. The
voltage reading is returned in the variable
MAX-VAL .
L ow C

`Activate the MAX187


hiftin Dout, clk, Msbpost, ( Max_Val112 1 ` hift in 12 bits
High C

`Deactivate the MAX187


Ma) _Val=( Max Vat/ 10 ) * Quanta

' Quantasize the result


ExperimentingwiththePicBasicProCompiler
Program -MAXI27_5.BAS
InterfacingwiththeMAX127AIDConverter
TheMAX127isalsoaneightchannel,12-bitAIDConverter,butusesa
2-wire1 2Cinterface
(SCL,SDA). WhatmakesthisAIDConverterdifferent
isitsabilitytoconvertavoltagegreaterthanitssupplyline,withoutthe
useofanexternalVref
.ThisisduetothefactthattheinternalVrefis
softwarecontrolled .Bit-3ofthecontrolbyte (RNG) configurestheVrefto
5Vor10Vfull-scale .
BeforeaconversioncanbereadfromtheMAX127acontrol-bytehasto
besent,thisinformsthechipastowhichinputtosamplefrometc .Table
4
.3showsasummaryofthebitswithinthecontrolbyte,andtheir
purpose.
Table4.3
.MAX127controlbyte.
Inthisexperiment,wewillbeusingtheunipolarinputs (0toVreO, and
the5Vfull-scaleconversion,therefore,theonlypartofthecontrol-byte
thatneedstobechangedarethechannelselectionbits
(SEL 0-2),
Thesebitsareshownbelowintable4 .4 .
Table4 .4
.MAX127channelselectbits .
Section-4 -9
SEL2 SEL1 SELO Channel
0
0 0 CHO
0 0 1 CH1
0 1 0
CH2
0
1 1 CH3
1 0 0
CH4
1 0 1 CH5
1 1 0 CH6
1 1 1 CH7
Bit Name
Description
7(MSB) START Thismustalwaysbeone,definesthebeginningofthecontrolbyte
.
6
5
4
SEI2
SEL1
SELO
Thesethreebitsselectwhichoftheeightchannelsareusedforthe
conversion
.
3 RNG
Selectsthefull-scaleinputvoltage.0= (0-5v), 1=(0-10v)
2 BIP Selectsunipolarorbipolarconversion
.0=unipolar, 1=bipolar
1,0(LSB)
PD1
PDO
Selectspower-downmodes.
PD1PDOMode
0

Normaloperation
1

Standbypower-downmode
1

Fullpower-downmode
ExperimentingwiththePIcBasicProCompiler
MAX127fiveVoltfull-scalereading
Figure4 .7showsthecircuitfortheMAX127,usingthe5Vinternal
reference
.ThepotentiometerVR1,actsasavariablepotential divider
connectedtochannel0oftheMAX127,thusvaryingthevoltageapplied
totheinput,from0to5V
.SCLandSDAconnecttoRBOandRB1ofthe
PIC,asintheMAX186demonstration .R1isapullupresistorrequiredby
the1
2
Cbusprotocol
.
Regulated5volts
Figure4
.7 .MAX1275Voltreference .
Theprogram MAX127S.BAS, demonstratestheuseoftheabove
circuit
.Theinputchannelofinterestisloadedintothevariable MAX-CH
andthesubroutine MAX127_IN iscalled
.Thissubroutineshiftsthe
channelbitsintotheircorrectplacewithinthecontrolbyte,andsetsbit-7,
whichmustbea1
(seetables5.3& 5.4) .
Theslaveaddressofthedeviceisthensent,tomakesurethatweare
talkingtothecorrectdeviceonthe1 2Cbus,andthenthecontrolbyteis
sent
.Thesameslaveaddressissent,beforethe12-bitresult ofthe
conversionisreadin.The12CREADcommandreadsinafull
16-bit
word,sotheresulthastobeshifted4placestotherighttocorrectthis .
Thequantalevelcalculationisthencarriedout,andtheresultisplaced
in MAXVAL.
Section-4-10
InterfacingtotheMAX127AIDConverter
ExperimentingwiththePicBasicProCompiler
Program -MAX127_9.BAS
MAX127tenVoltfull-scalereading
Asmentionedatthestartofthisexperiment,theMAX127iscapableof
convertingavoltagethatisgreaterthanitspowersupply,upto10Vin
fact
.Thisisachievedbysettingbit-3ofthecontrolbyteto1,figure4 .8
showsademonstrationcircuitforthis
.
Figure4 .8 .MAX12710Voltreference .
Theprogram MAX1279.BAS,
demonstratestheuseoftheabove
circuit.Theprogramisbasicallythesameas MAX1275.BAS,
except
thatwithinthesubroutine
MAX127IN, bit-3ofthecontrolbyteissetto
1
.Andbecauseweareconvertingavoltageofupto10V,thequanta
levelisalsochangedfrom123to245
(101//4096).
InterfacingtotheMAX127AIDConverter
Section-4-11
ExperimentingwiththePicBasicProCompiler
Program - 1OBITADC .BAS
Usingtheon-boardAnaloguetoDigitalConverter
TheADCINcommandtakesalotoftheworkawayfromaccessingthe
on-boardAnaloguetoDigitalConverter,howevertomakeefficientuseof
thiscommandtheprincipalsbehindusingtheADCneedtobe
understood.Weshalltakealookattheprocedureforreadingan
analoguevoltage,the old fashioned way.Thenweshalllookatthe
ADCINcommanditself.
ThePICsweshallbeusingarethenew16F87Xrange,thesehavean
on-board10-bitsuccessiveapproximationADC,whichusesabankof
internalcapacitorsthatbecomechargedbythevoltagebeingsampled .
The28pindeviceshavefivechannelsofADC,whilethe40pindevices
haveeightchannels .
ThePICpowersupwithalltheADCpinsconfiguredasanalogueinputs .
Thismaybeacceptableifallthechannelsarebeingusedforanalogue
purposes.However,ifonlyafewofthemareforanalogueandtherest
aretobeusedasdigitallinesthenthefirst4-bits (PCFG) ofthe
ADCON1registerneedtobemanipulated
.Thereseemstobenopattern
involvedwiththesebits,thereforetable4
.6mustbeusedtodetermine
whichbitstosetorclearedforaspecificinputconfiguration .
A=Analogueinput

D=Digitalinput
Table4.6
.PCFGOtoPCFG3configuration .
Theportpinsthataredesiredasanalogueinputsmustalsohavetheir
TRISvaluesetasinput(1) .
Section-4-12
PCFG AN7 AN6 AN5 AN4 AN3 AN2 AN1 ANO VREF+
VREF-
0000 A A A A A A A A AVdd AVss
0001 A
A A A Vref+ A A A AN3 AVss
0010
D D D A A A A A AVdd AVss
0011 D D D A
Vref+ A A A AN3 AVss
0100 D D
D D A D A A AVdd AVss
0101 D D D D Vref+ D A
A AN3 AVss
011X D D D D D
D D D --- ---
1000 A A A A Vref+ Vref- A A AN3
AN2
1001 D D A A A A A
A AVdd AVss
1010
D D A A Vref+ A A A AN3 AVss
1011 D D A A Vref+ Vref- A A AN3 AN2
1100 D
D D A Vref+ Vref- A A AN3 AN2
1101 D
D D D Vref+ Vref- A A AN3 AN2
1110 0 D D D D
D D A AVdd AVss
1111 D D D
D Vref+ Vref- D A AN3 AN2
Experimenting with the PicBasic
ProCompiler
Usingtheon-boardADC
Thechannelofinterestischosenbybits3to5ofthe
ADCONOregister
(CHS2: CHSO).
Table4. 7showstheirarrangementforaspecific
channel.
Table4. 7
. Channelselectionbits .
The10-bitresultisheldintheregisters ADRESH and ADRESL
. Bit
ADFM(ADCON1 . 7),
dictateswhethertheresultswillbeleftjustified
(ADRESHholdinglsb) orrightjustified
(ADRESLholdingIsb). Setting
ADFMwill
enablerightjustification (normal),
whileclearing ADFMwill
enableleftjustification
.
The ADC'sclock
sourcemustnowbechosen, thisisselectedbybits6
and7ofthe
ADCONOregister (ADS1 : ADSO).
Thefourchoicesare
shownbelowintable4 . 8 .
Bits7 . . 6
00
01
10
11
Clocktypeselected
2/Fosc
8/Fosc
32/Fosc
FRC(InternalRCoscillator)
Table4
. 8 . Clockselectionbits.
The ADC's conversiontimeperbitisdefinedasT
AD. For correct
operation, the ADC
requiresaminimumTAD of1 . 6us. Whichmeanswe
mustbeverycarefulwhenchoosingthe
clock source, awrongly
configured clockwill resultinreduced ADC
resolutionornon-atall .
TocalculatetheT AD
foraspecificoscillatorwecanusethefollowing
formula: -
TAD=x/Fosc
Wherex=2, 8, or32, andFoscisinmHz
Section-4-13
Bits5
. . 3
Channelselected Pinname
000 Channel0
RAO/ANO
001 Channelt
RA1/AN1
010
Channelt RA2/AN2
011 Channel3
RA3/AN3
100 Channel4
RA5/AN4
101 Channel5
REO/AN5(onlyon40pin)
110 Channel6
RE1/AN6(onlyon40pin)
111 Channel7 RE2/AN7(onlyon40pin)
ExperimentingwiththePicBasicProCompiler
Usingtheon-boardADC
Forexample,usinga20mHzcrystal,wecanchoosewhichclocksource
issuitablebychangingthevalueofxuntiltheresultis1 .6usorover : -
TAD =32/20==1.6us
TAD =8120==0.4us
Wecanseefromtheresultsthataclocksourceof8/Foscwillbetoofast
fortheADCtofullymakeaconversion
.However,aclocksourceof
32/Foscisperfect.
WhenFRCisselectedastheclocksource,theTAD timeisapproximately
2- 6us.
TheADCmoduleisnowreadytobeenabled,thisisdonebysettingthe
ADONbit (ADCONO.0)
Toallowtheinternal sampleandhold capacitorstimetocharge,wemust
waitaspecifictimebeforeactuallymakingaconversion
.Thistimeperiod
dependsontheimpedanceofthesourcebeingsampled,aswellasthe
temperatureofthePICitself,however,adelayofbetween2to20uswill
sufficeinmostcases .
Wearenowreadytotakeasample,thisisaccomplishedbysettingthe
GO-DONEbit
(ADCONO.2)
Theconversionmustbegiventimetocomplete,thismaytaketheform
ofadelayaftertheGO_DONEbitisset,ortheGO_DONEbitmaybe
polledtoseeifitisclear
.Thelatteristhebestandmostaccurate
methodastheGODONEbitisclearedbyhardwareaftercompletionof
aconversion .
Toreducecurrentconsumption,wecannowdisabletheADCbyclearing
theADONbit (ADCONO.0) The10-bitanaloguetodigitalconversion
resultisnowheldintheregisters,ADRESHandADRESL.
Program 10BITADC.BAS, illustratestheuseoftheabovetechnique
.
Andfigure4.9showsthecircuitlayoutforaPIC16F876 .Asthe
potentiometer (VR1) isturnedtowardsthe+5VorOVlinetheresultwill
increaseordecrease
.ThiswillbedisplayedonaserialLCD,configured
forN9600baud,connectedtoPortC .7.
Section-4-14
ExperimentingwiththePicBasicProCompiler
Program- ADC_SLP.BAS

Usingtheon-boardADC
AchievinggreateraccuracythroughSLEEP
AccordingtothePICdatasheets,amoreaccuratesampleisobtained
whenthePICisplacedinsleepmodebecausetheswitching noise
causedbythePIC'sinternalregistersisminimized .PlacingthePICinto
lowpowermodeisdiscussedwithmoredetailinsection-10,andthishas
manysimilarities.
ThreenewcontrolbitsareusedforwakingthePICwhentheADChas
takenasample.Theseare : -
PEIE (INTCON.6) . Peripheralinterruptsareenabledwhenset,suchas
theADC,MSSPetc
.Whenclearedtheinterruptsaredisabled.
ADIE (PIE1 .6) . Whenset,theADCinterruptisenabled,anddisabled
whencleared.
ADIF (PIR1 .6) . ThisflaggetssetwhenanADCinterrupthasoccurred,in
otherwordswhentheADChasfinishedtakingasample.Thisflag is
mainlyofusewhenaninterrupthandlerisimplemented .
Figure4.9andprogram ADC_SLP.BAS demonstratetheSLEEP
process.Thefirstthingthecodedoesisdisableglobal interruptsby
clearingtheGIEbitofINTCON (INTCON.7) .
WhenthePICisplacedintolow-powermodethe externalcrystal
oscillatorishalted ;therefore,thecodeattachestheADCclocksourceto
theinternalRCoscillatorbysettingbits6and7oftheADCONOregister
(ADS1
: ADSO) . Peripheralinterruptsarethenenabledbysettingthe
PETEbit.ThentheADIEbitissetwhichenablestheADCtoactually
wakethePIC.
WhentheRCclocksourceisselectedfortheADC,thePICwaitsone
instructioncycleaftertheGODONEbit (ADCONO.2 isset.Thisallows
theSLEEPinstructiontobeexecutedbeforeasampleisstarted .
TheSLEEPinstructionthenplacesthePICintolowpowermodeuntilthe
ADChasfinishedasample,thisisthendisplayedontheserialLCDand
thewholeprocessisrepeated .
Section-4-15
ExperimentingwiththePicBasicProCompiler
Program- ADCIN
.BAS
UsingtheADCINcommand
Nowwthatwehaveabetter
insightintotheon-board ADC,wecanusethe
ADCINcommandwith moreconfidenceand efficiency .
Therearethreedefines
usedbytheADCINcommand, theseare: -
Define ADC_BITS
Define ADCCLOCK
DefineADCSAMPLEUS
Thefirstdefine (ADCBITS),is usedtoinformthecompilerastowhat
resolutionthe
on-boardADCis.SomePIC'shave an8-bitADC,while
thenewertypes havea10-bit
ADC,or12-bits forthePIC16C77X
devices.
Thesecond define (ADC_CLOCK), selectsthe ADC'sclock source
(2/Fosc,8/Fosc,32/Fosc,or
FRC). Thiswasdiscussed earlier.
Thethirddefine (ADCSAMPLEUS), informsthecompiler howlongto
wait
(inmicroseconds)toallowtheinternal sampleandhold capacitors
tochargebeforeasampleistaken
.Thisisthedelayafterthe ADONbit
isset,butbeforethe GO-DONEbitisset.
BeforetheADCIN commandmaybeused, thepinofinterest mustbe
configuredasaninput,bysettingitsTRISvaluetoone .
Thenthefourinputconfigurationbits (PCFG) ofADCON1mustbeset or
cleared (seetable
4
.6) .
Thiswillconfiguretheappropriatepins todigital
oranalogue.
Thejustification
bit(ADFM)ofADCON1 mustalsobesetorcleared. In
normaloperation,
theADFMisset,which enablesrightjustification.
Finally,theADCINcommanditselfis used,thiswill
makeaconversion
fromthechosenchannel andplacetheresult intothevariable assigned.
TheADCIN command
usesapolling technique todetermine ifa
conversionhasbeen completed,therefore,nodelayisrequired
afterits
use.
Section-4-16
Usingtheon-boardADC
ProgramADCIN.BAS,
illustrateshowtousetheADCINcommand
.The
mainpartoftheprogramisshownbelow
: -
PCFGO=O
PCFG1=1
PCFG2=1
PCFG3=1
ADFM=1
ExperimentingwiththePicBasicProCompiler
Usingtheon- boardADC
Ink
ADCIN0,AD_Result

'Placetheconversionofchannel- 0
'intoADRESULT
Debugl,Line1,#AD_Result,"
"'Displaytheresult
Pause200

'
Asmalldelay
GotoInf

'Doitforever
Thecircuitinfigure4
.9isalsousedforthedemonstration .
C
To17
Serial
s
LCD
L'
13
n
0
RC7
VDD
RC6
RC5
RC4
RC3

MCLR
RC2
RC1
RCO
'ConfigureforANOasanalogueinput
`RightjustifiedresultinADRESLand
' ADRESH
Section- 4- 17
Regulated5Volts
23
RB7

a
C1
v

10uf
2RB5

C2
23
RB4

O.tuf
2'
RB3

20mHz
23
RB2

Crystal
22
RB1

0SC1 3
21
RBO
PIC16FO76
- ' RA5
- RA4
e
RA3

OSC2
C4

C3
VR1

RA1

15pf 15pf_
look *RAO
VSSVSS
linear
19
31 1
Figure4 .9
.On- board10- bitADC.
ExperimentingwiththePicBasicProCompiler
Program - Q_ADCIN.BAS
Analternativequantasizingformula
Inthepreviousdemonstrations,wehaveonlylookedattherawdata
presentedfromtheADC,whereaconversionof5Vwillproducearesult
of1023
.Quantasizingtheresultwasdiscussedearlierinthissection
(under,interfacingtheMAX186)
. However,adifferenttechniquewillbe
discussedforthequantasizingofthe10-bitADC
.Thismakesuseofthe
' */ ' operator,whichreturnsthemiddle16-bitsofa32-bitmultiplication
.
Thiswillallowthecompiler' sintegermathstomultiplyafractional
constant.
Anyquantasizedresultdependsontheaccuracyofthequantalevel,
whichinthiscaseis,
(5/1024). Thisgivestheresult, .0048828125,
clearlythisistoosmallforthecompiler' sintegermathstouse,therefore,
wewillmovethedecimalpointrightafewtimes,thiswillleaveuswitha
quantalevelof4.8828125.Tomakethequantalevelarealnumberwe
multiplyitby256: -
4.8828125*256=1250
Wenowhaveanicerealnumberforourquantalevel .Theformulafor
calculatingtheactualvoltageis : -
Actualvoltage=Resultofconversion*/quantalevel
Forexample,supposewehavetakenasamplefromtheADCandithas
returnedtheresultof512,thecalculationnowlookslikethis : -
Actualvoltage=512*/1250
Thiswillproducearesultof2500,or2.5V.Toachieveaslightlymore
accurateresult,theresultoftheconversionneedstobeincreasedby
multiplyingitby10: -
Actualvoltage=(512*10)*/1250
Whichwillproducearesultof25000,again2
.5Volts.
Program
QADCIN.BAS, illustratestheabovemethod,usingthecircuit
infigure4.9.
Usingtheon-boardADC
Section-4-18
ExperimentingwiththePicBasicProCompiler
Program
- SAMPLING.BAS
Ironingoutnoisyresults
Sometimesaccuracyisofapremium,therefore,certainprecautions
havetobetakenwhenusingAIDConverters,especiallyiftheyare10-bit
ormoretypes.Anyinaccuracywillmanifestitselfasnoise,thisiswhen
theLSBofthereadingchangescontinuouslyfromonevaluetoanother.
Theintegermathusedbythecompilerironsoutmostofthe noise,
however,ifyouareusingtherawdatapresentedbytheADCthenyou
mustfirstfindoutwherethenoiseiscomingfrom .
Amajorcauseofnoiseisinadequatedecouplingofthepowersupply .
Thismaybealleviatedbytheuseofcapacitorsprolificallyplacedaround
thecircuit,andlocatedasphysicallyclosetotheADCaspossible .
IftheinputtotheADCisnotarapidlymovingsignalthenacapacitor
shouldbeplacedfromitsinputtoground,thevaluedepends onthe
frequencyofthesignalbeingsampled,therefore,atrialanderrormethod
shouldbeadopted (afewthousandpFisnormallysufficient) .
Also,whendesigningthePCBorstripboardforfinalconstruction,alarge
groundplaneshouldbeemployed .
Alwaysensurethatthesupplylineiswell regulatedandthatifan
externalreferencevoltageisused itisprecise.Whenprototypingyour
circuitonabreadboard,noisewillbemoreapparent,therefore, ifthe
decouplingandregulationofthepowersupplyworkwellonthismedium
itwillbeminimizedinthefinalproduct .
Anothermethodforreducingthenoiseisasoftwareone .Several
samplesaretakenfromtheADC,thenaveragedout.Forinstance,ifwe
weretakingsamplesfromthebuiltin10-bitADC,whichhasarangeof
0 . .1023,wewouldsampletheADC10times,addthemtogetherand
placetheminaWORDvariable,thiswillgiveusamaximumvalueof
10230,whichiswellwithinthe16-bitcapabilitiesofthecompiler
.
Whenallthesampleshavebeenaquired,thevariablecan thenbe
dividedbythenumberofsamplestaken,whichis10inourcase.This
willgiveustheaveragevaluethatwassampled
.Thismethod
isnot
100%accurate,however,theresultsobtainedareadequatefor most
practicalpurposes.Theprogram SAMPLING.BAS, demonstratesthe
usefulnessofthismethod .
Ironingoutnoisyresults
Section-4-19
ExperimentingwiththePicBasicProCompiler
Section-5
Experimenting
with
DigitaltoAnalogue
Converters
UsingthePWMcommandasaD/AConverter .
ControllingthehardwarePWMmodules.
BuildinganR-2RD-AConverter.
InterfacingtotheMAX5352D/AConverter
.
InterfacingtotheAD8402digitalpotentiometer.
ExperimentingwiththePicBasicProCompiler
Program -8BIT_PWM.BAS
Asyouwouldexpect,aDigitaltoAnalogueconverter
istheexact
oppositeofanAnaloguetoDigitalconverter
.Ittakesabinaryvalueand
convertsittoavoltage
.Thereareseveralwaystoachievethis,
pulse
widthmodulationisthesimplestmethod,aresistorladderisaslightly
morerefinedway,andaseparateICisthemostaccuratetype
.Inthis
sectionwewillexploreallthreemethods,includingthePWMmodules,
incorporatedinthenew16F87Xrangeofmicrocontrollers .
UsingthePWMcommandasaDigitaltoAnalogueConverter
BecausePulsewidthmodulationisrelativelyeasytoimplementwiththe
compiler,it'softenoverlookedasaviable8-bit
digitaltoanalogue
converter,yettheresultsachievedaresurprisinglyaccurate
.
Pulse-widthmodulation
(PWM) allowsadigitaldevicetogeneratean
analogvoltage
.Theideais,thatifyoumakeapin'soutputhigh,
the
voltageonthatpinwillbe5V
.OutputlowwillbeOV . Howeverifyou
switchthepinrapidlybetweenhighandlowsothatitwashighforhalf
thetimeandlowforhalfthetime,theaveragevoltageovertimewould
behalfwaybetweenOVand5V (2
.5Volts) . Theratioofhighstolowsin
PWMiscalledthedutycycle
.Thedutycyclecontrolsthe analogue
voltage,thehigherthedutycyclethehigherthevoltage
.SincethePWM
commandusesabyte
(8-bits) tocontrolthedutycycle,wecanresolve
thevoltagedowntoavalue,definedbythefunction
: -
RangeofOutput/Rangeofinput
Whereoutputisthe0 . .5Vswing,andinputisthe8-bit
(0-255) valueof
duty,so
5V/256= .0195
whichmeans,foreach1-bitchangeintheduty,
theoutputvoltagewillchangeby
.0195V,thisiscalledthequantalevel
.
Therefore,basedonagiveninputwecancalculatetheoutputvoltage
withthefollowingformula: -
Vout=duty*quantalevel
Forexample,adutyof150wouldresultinanoutputvoltageof2
.925V
Vout= 150* .0195,
Voutnowequals 2.925
Section-5-1
ExperimentingwiththePicBasicProCompiler
UsingthePWMcommandasadigitaltoanalogconverter
Thisisimportanttoknowbutnotterriblyusefulwithinourcode,weneed
toknowthevaluetoplaceintodutythatrepresentsthevoltagerequired
ontheoutput.Theformulawewilluseis
: -
duty=Vout/quantalevel
Ourquantalevelworkedoutas
.0195,howeverthisnumberistoosmall
forthecompiler'sintegercalculationstohandle,thereforewewillscaleit
uptoamoremanageable195 .WewillalsoscaleupVoutforamore
accurateresult.Soourformulanowlookslikethis ; -
duty=(Vout*100)/195
InordertoconvertthechoppedPWMintoasmoothanalogvoltagewe
needtofilteroutthepulsesandstoretheaveragevoltage.R2andC3in
figure5
.1formanR/Cnetwork .Thecapacitorholdsthevoltagesetby
PWMevenaftertheinstructionhasfinished .Thelengthoftimeitwill
holdthevoltagedependsonhowmuchcurrentisdrawnbyanyexternal
circuitryconnectedtoit
.Inordertoholdthevoltagereasonablysteady,
wemustperiodicallyrepeatthePWMcommandtogivethecapacitora
re- charge.Justasittakestimetodischargethecapacitor,italsotakes
timetochargeitinthefirstplace
.ThePWMcommandletsyouspecify
thechargingtimeintermsofcycles
.Todeterminehowlongtocharge
thecapacitor,usethisformula: -
Chargetime=4*R(in
kQ) *C (inuF) .
Forinstance,figure5
.1usesa10kOresistoranda1pFcapacitor : -
Chargetime=4*10*1=40,
whichis40ms.
Whichmeansitwilltake40cyclestochargethecapacitor,
however,
sincethecompiler'sPWMcommandcycletimeisdependanton
the
crystalfrequency,
(a4mHzcrystalwillgiveasinglecycletimeof 5ms,a
20mHzcrystalwillgiveasinglecycletimeofimsetc) .To
giveacycle
timeof40msusinga4mHzcrystalweusethisformula
: - .
Cycle=chargetime/(20/OSC)
Thiswillgiveusacycletimeof8toplacewithinthePWMcommand
.
Section- 5 - 2
ExperimentingwiththePicBasicPro
Compiler
UsingthePWMcommandasadigitaltoanalogconverter
IfwewantedtoproduceavoltageonPortB
.Oof2.5Vwitha4mHz
crystal,usinga1OkQresistoranda1uFcapacitor,wewoulduse
: -
AfteroutputtingthePWMpulses,thecompilerleavesthepinasaninput
.
Whichmeansthepin'soutputdriveriseffectivelydisconnected
.Ifitwere
not,thesteadyoutputofthepinwoulddischargethevoltageonthe
capacitorandundothevoltagesettingestablishedbyPWM
.ThePWM
chargesthecapacitor,andtheloadconnectedtoyourcircuitdischarges
it.Howlongthechargelasts
(andthereforehowoftenyourcodeshould
repeatthePWMcommandtorefreshthecharge) dependsonhowmuch
currentthetargetcircuitdraws,andhowstablethevoltagemustbe
.If
yourloadorstabilityrequirementsaremorethanthepassivecircuitof
figure5
.1canhandle,anOp- ampfollowermaybeaddedtotheoutputof
theR/Cnetwork
.Thisisillustratedinfigure5.2.
Theop- ampchosenmusthaverail- to- railcharacteristicssuchasthe
NationalSemiconductorLMC662ortheAnalogueDevicesOP296
;
otherwisethemaximumvoltageswingisapprox1Vto3.9V
.Theuseof
9Vfortheop- amp'ssupplyallowsthemaximumoutputof5Vtobe
achieved
; iftheop- amp'ssupplywas5V,themaximumoutputwouldbe
approx4.8V.
Theprogram 8BIT_PWM.BAS,
simplyoutputsavoltageof3.5V,and
thenpausesfor100ms,withouttheop- ampconnectedtheLEDflashes,
asthePWMcommandisnotbeingcalledintimetostopthecapacitor
fromdischargingduetotheloadtakenbytheled
.Withtheop- amp
followertheLEDremainsstable,astheop- ampnowcarriestheload
.
Section- 5- 3
Vout
Var Word
`Outputvoltagerequired
Duty
Var Byte `DutyvariableforPWMcommand
Quanta Con 195
`Ourquantalevelbasedon5V
Vout=250 'Werequire2
.5V
Duty=(Vout*100)/quanta
`Calculatetheduty
PwmPortB.0,Duty,8
`Outputthevoltagefor40ms
9Volts
In
ExperimentingwiththePicBasicProCompiler
MC6
MAW
781.05
IN OUT
GND
IC1
Figure5.1 .UnbufferedR/Cnetwork.
Regulated5Volta
R1
4.7k
C1

C2
1Ou1

0.lut
0
C3

C4
6pf

56pt
T
UsingthePWMcommandasadigitaltoanalogconverter
PWMdemonstrationcircuits
a
4mHz
Crystal
IC2
OSC2
VSS
14
PIC16F84
5
Section-5-4
VDDRB7
MCLR RB6
RB5
RB4
RB3
OSCI RB2
RBI
R80
RA4
RA3
RA2
RA1
RAO
Figure5.2.Bufferedoutput.
Regulated5Volts
R1
4.7k
14
VDD
3
RB7
MCLR

RB6
2
11
RB5
10
4mHz R84
Crystal
16
RB3
OSCI

RB2
RB1
9
e R2

Voltage
- 10k

Out
I
C1 C2
RBO
6
1001-1:1 of
PIC16F84
RA4
LED
a
OSC2

RA3
z
C5
WMISS
C3 C4
RA2 1of
6pf 56pt
RA1
VSSRAO
8
R3
470
Ov.
Ti
IS
ExperimentingwiththePicBasicProCompiler
Programs-1OBITPWM
.BAS,HPWMTST.BASandHPWM.INC
Controllingthe10-bitHardwarePWM
AlthoughhardwarePWMisn'tuncommonon somePICs,thenew
PIC16F87Xrangehavemadethisfeatureviabletoexperiment with
becauseoftheirflasheepromcapabilities.Inthisexperiment,wewillbe
usingthePIC16F876,butanyofthe87Xrangemaybesubstituted .The
16F876hastwohardwarePWMmodules ;thesearelocatedonpins12
and13andarenamedCCP1&CCP2 .UsingthesePWMmodulesisn't
aseasytoimplementasthecompiler'sPWMcommand,several
hardwareregistersneedtobemanipulated,andareasonableamountof
mathsisrequiredtorealizethefinalPWMperiodanddutycycle .Wewill
focusonjustoneofthetwoPWMmodules,namelyCCP1 .
InordertogenerateaPWMsignalfromCCP1acertainsequenceof
registershastobesetorcleared,thereforewewilllookatthissequence
asaprocessofstepstocarryout .
Step1.
TheCCP1pinalsoaliasesasPortC .2,thereforethefirstthingwehave
todoisconfigureitasanoutput, (TR/SC.2=0) .
Step2 .
BothPWMmodulesareattachedtoTMR2,whichmeansthat both
moduleswillsharethesamefrequency .SoTMR2hastobeinitialised
FirstlyTMR2's prescalerratio hastobeestablished. This is
accomplishedbysettingorclearingbits-0&1oftheT2CONregister:
-
0-0willsettheprescalerratioto1
: 1(TMR2willtickoneveryinstruction
cycle) .
0-1 willsettheprescalerratioto1: 4(TMR2willtickoneveryfourth
instructioncycle) .
1-Xwillsettheprescalerratioto1
: 16(TMR2willtickoneverysixteenth
instructioncycle) .
TMR2nowhastobeturnedon ;thisisdonebysettingbit-3ofT2CON,
clearingthisbitwillturnTMR2off .
Section-5-5
ExperimentingwiththePicBasicProCompiler
Section-5 -6
Controllingthe10-bithardwarePWM
Step3
Theperiod (or
frequency) ofTMR2nowhastobeestablished .Thisis
placedinthePR2register
.Theformulatoaccomplishthisis : -
Period=(PR2+1)*4*(1/Fosc)*(TMR2prescalervalue)
The '(1/Fosc)'
partoftheformulawillalwaysyieldafractionalresulti .e .
(0 .25).
Therefore,inrealitywearedividingeachtimewemultiplybythat
numberi
.e . (100*0 .25=25), whichisthesameas100/4.Thismeans
that, '* (1/Fosc)'
maybereplacedwith ' /Fosc ' . Ourformulanowlooks
likethis : -
Period=((PR2+1)*4/Fosc)*(TMR2prescalervalue)
So,fora4mHzoscillator,prescalersetto1
: 1,andPR2=255
((256 *4)
14)*
1=256
TheperiodofthePWMwillbe256 us
.Inrealitythisisonlyasaccurate
asthecrystalorresonatorused .
Tocalculatethefrequencythatthisrepresentsweusetheformula, (1000
/Period). Thismeansourfrequency
(inkHz)will be (1000/256 ) which
equals3
.906 25kHz.
Itwouldbebeneficialtoincreasethefrequencytoashighasitwouldgo,
however,asthefrequencyincreasessotheresolutiondecreases
.To
calculatetheresolutionofagivenfrequencyweusetheformula : -
(log(
Fosc/Fpwm))/log(2)
WhereFoscisthecrystalfrequencyandFpwmisthefrequencyofthe
PWMsignal,ascalculatedabove
.Thisformulacanbebrokendown
furtherbythefactthatthelogof2isaconstantvalueof
.301,therefore
ourformulanowlookslike
: -
(log(Fosc/Fpwm )) / .301
ExperimentingwiththePicBasicProCompiler
Controllingthe10-bithardwarePWM
So,forafrequencyof3
.9kHz,usinga4mHzcrystal,ourformulaisnow.
(log(4000000/3900))1 .301=10 .003
Whichmeansthatwehavearesolutionof10-bits
.Thatwasn'ttoobad,
wasit?
Step4
The10-bitdutycyclevaluehastobeloadedintotwoseparateregisters
inaratherpeculiarway .Themostsignificant8-bitsofthedutyhaveto
beplacedintheCCPRL1register,andthefirsttwobitsofthedutyhave
tobeplacedinbits-4&5oftheCCP1CONregister.Therefore,wehave
toplacebit-0ofthe10-bitdutyintotheCCP1CONregisterbit-4and
placebit-1ofthe10-bitdutyintotheCCP1CON registerbit-5
.This
soundsmoredifficultthanitactuallyis, asisdemonstratedinthe
program
10BITPWM .BAS . Wenowneedtocalculatethevaluetoplace
intothedutyregisterstoproducearequiredPWMvoltage .Firstly,we
needtocalculateourquantalevelfora10-bitresolution(0-
1023).This
ismorefullyexplainedintheAIDsection .However,thecalculation is
(5/1024)whichequals
.00488,wewillmovethedecimalpointrightafew
timesandrounduptocompensateforthecompiler'struncation
ofa
division,whichmakesourquantalevel49 .Theformulaforcalculating
thedutycycleforagivenvoltageis : -
duty=Vout/quantalevel
WhereVoutisanumberfrom1to500,wemustincreasethevalueof
Vout,soastoincreasetheaccuracyofourresult,thiswillbedoneby
multiplyingitby100 .Soourcalculationwithintheprogramnowlookslike
this: -
duty=(Vout*100)/quanta
Steps
AllthatneedstobedonenowistoturnthePWMon,thisisachievedby
settingbits-2&3oftheCCP1CONregister
.Clearingthesebitswillturn
offtheCCP1PWMmodule .
Section-5-7
ExperimentingwiththePicBasicProCompiler
Figure5 . 3
. HardwarePWMcircuit .
Section-5-8
Controllingthe10-bithardwarePWM
IfCCP2moduleisbeingusedthenregisterCCP2CONshouldbe
exchangedforCCP1CON
. AndCCPRL1shouldbechangedto
CCPRL2.
Byplacingdifferentdutycyclevaluesintothetwo10-bitCCPregisters,a
differentvoltagewillbeproducedfromeachCCPmodule
. However,they
willbothsharethesamefrequencyastheyarebothattachedtoTMR2
.
ThereisanIncludefile
HPWM. INC onthediskthatsimplifiestheuseof
thePWMmodules
. Theincludefilehastobeplacedatthebeginningof
yourprogram. Thenpriortocallingthe HPWM
subroutine,twovariables
havetobeloaded . ThevariableVOUTholdsthevoltageoutputrequired,
andthevariableCCPholdsthePWMmoduleofinterest : -
CCP=0willturnOFFbothPWMmodules.
CCP=1willoutputthevoltageheldinVOUTtoPWMmodule1
.
CCP=2willturnPWMmodule1
OFF
CCP=3 willoutputthevoltageheldinVOUTtoPWMmodule2
.
CCP=4willturnPWMmodule2 OFF
CCP=5willoutputthevoltageheldinVOUTtobothPWMmodules
Theprogram HPWMTST. BAS,
demonstratestheuseoftheincludefile.
Regulated5Volts
120
R1
VDDRC7
17
RC6
e
4 . 7k
RC5
RC4
Ls-

R2
MCLR

RC3 ' -

10k
RC2/CCP1
RC1 12 Voltage
RCO ' -' Out
RB7
xe
27
RB6
ss o
C5
RB5
RB4
2a

MMM
24
luf
4mHz
RB3
C2 C7

Crystal RB2
!-I
IOuf . I Sluf
0SC1

RB1
22
RBO
s,

i PIC16FB76
RA5
C3
RA4
OSC2

RA3
e
s
C4
se
,56p1 56pf
RAI
VSSVSSRAO
2 -oTo
SerialLCD
. T T
1
.

ExperimentingwiththePicBasicProCompiler
Program
-R2R.BAS
BuildinganR-2RDigitaltoAnalogueConverter
TheR-2RDigitaltoAnalogconverterissurprisinglysimpletoimplement,
withonly16externalresistorsconnectedintheladderformation,an
extremelyfastandreasonablyaccurate8-bitD/Aconvertercanbe
realized .
TheR-2Rarrangementofresistorsworksbydividingeachvoltage
presentatitsinputsbyincreasingpowersoftwo,andpresentsthetotal
ofallthesedividedvoltagesatitsoutput
.SincethePICiscapableof
drivingitsoutputsfrom0to5V,theR-2Rladderconvertsthebinary
numberonPortBintoaproportionalvoltagefrom0to5Vinstepsof
approximately20mV
.
AgreatmanycommercialDigitaltoAnalogconvertersworkonthissame
principle,butalsohaveinternalvoltageregulatorsandlatches .Our
demonstrationdoesn'trequireanyofthosethings ;thereforewecanuse
theresistorarrayalone .Figure5
.4showsthecircuitfortheR-2RDigital
toAnalogconverter.
Section-5 -9
Figure5 .4 .R-2RD/Aconverter .
R2

Voltage
2k

Out
AN
R3

R10
2k

1k
R4

R11
2k

1k
Regulated5Volts
R5

R12
2k

1k
R1
4 .7k
VDDRB7
17
R6

R13
12
2k

1k
MCLR

RB6
11 a C5
4mHz
RB5
RB4
10
R7

R14M0
.1uf
9
Crystal RB3
2k

1k
0SC1

RB2
RB1
e
R8

R15
C1 C2
RBO
6
2k

1k
10uf 1uf
PICi6F84
E-] : -
RA4
z
R9

R16
MEN MEN
C3 C4 a
OSC2

RA3
RA2
i
2k

1k
6pf 56pf
RA1
1e
R17
T T11
s

1k
ExperimentingwiththePicBasicProCompiler
BuildinganR-2Rdigitaltoanalogconverter
TheR-2RdesignhastheadvantageoverPWMinthat,asPWMisa
trainofpulsesthatrequirefilteringtheR-2Rdoesnot
.Also, withthe
softwareimplementationofPWM,thishastoberefreshedperiodically
;
theR-2Rdesignwillholdtheoutputvoltageuntilthevalueplaced on
PortBischanged
.Theaccuracyofthisdesignreliesonthetoleranceof
theresistorsused,butevenwithstandard10%resistorstheresultsare
acceptable
.Ifdifficultyinobtaining2ksaresistorsisencountered, they
maybesubstitutedfor2.2kQtypes,withaverymarginaldecreasein
accuracy .
ThesoftwaretocontroltheR-2RD/Aconverterisextremelyeasyto
write,theformulatoconvertthebinaryrepresentation presentedon
PortBintoavoltageisbasicallythesameasforthePWMcommand
: -
Bval=Vout/quantalevel
WhereBvalisthe8-bitbinarynumberthatisplacedontoPortB,
we
alreadyknowthequantalevelfor5Vand8-bit (195).
Wewillagainscale
upVoutforamoreaccurateresult
.Sothecalculationnowlookslikethis:
Bval=(Vout* 100)/195
Program R-2R.BAS,
demonstratestheuseoftheR-2Rdigitaltoanalog
converter.TheoutputvoltagerequiredisloadedintothevariableVOUT,
andthenacallismadetothesubroutine R2R. Thiswillcalculatethe
valueofBVAL,asintheabovecalculation,andoutputitsresulttoPortB .
Section-5-10
Experimentingwiththe PicBasic ProCompiler
Program - MAX5352R
.BAS
InterfacingtotheMAX5352D/AConverter
TheMAX5352isa12-bitdigitaltoanalogconverter,whichusesa3-wire
serialinterface (SCLK, DIN,CS).
Ithasabuiltinop-ampfollowerthatwill
allowafull-scaleoutputof0to5V
.Howeveritdoesnothaveaninternal
Vref,thereforeanexternalsourcehastobeapplied .Also,theexternal
Vrefmustbe1 .4VbelowtheVddrail
.Whichmeansthemaximumoutput
voltage,usingthistechnique,is3.6V,figure5
.5,showsthecircuit for
this
.Butallisnotlostbecause,byaddingtworesistors,andmakingthe
Vref2
.5V,wecanobtainthefull-scaleoutputof0to5V,figure5
.6shows
therelevantcircuit .
AlthoughtheMAX5352onlyuses12-bitstooutputavoltage,itrequires
all16-bitstobesent,thisisbecause,withinthe16-bits,thethreemost
significantbits,andtheleastsignificantbitarecontrolflags
. Table5.1
showsthecommandbitswithinthisword .
(X=don't care)

Table5.1
.Bitswithinthecommandbyte.
Thefirstdemonstration usesanexternal Vrefof3.6V,this
is
accomplished,asshowninfigure5
.5,byusingatrimpotpotentiometerto
actasavariablevoltagedivider,whichenablestheVrefto
beany
voltagebetween0and5V .Forthisdemonstration,adjustthetrimmer
until3
.6Visobtainedonpin6oftheMAX5352.
Program MAX5352R.BAS,
isforusewiththiscircuit .Themainprogram
revolvesaroundthesubroutine MAX-OUT, butbeforethissubroutineis
called,thevariableVOUThastobeloadedwiththerequired output
voltage,thiscanbeanyvaluebetween0and360,where360isequalto
3.6V
.Thesubroutine,multipliesVOUTby10,whichwillgiveusour12-
bitvalue
.ItthenshiftsVOUT,oneplacetotheleft ;thismovesthe12-bits
ofvoltagedataintotheircorrectplacewithinthe16-bitwordandensures
bit-0isclear.Itthenclearsbits-13..15
(seetable5.1), beforeshiftingout
the16-bits.
Section-51 1
16-BITSERIALINPUT
FUNCTION

I
C2
C1 CO D11DO SO
X 0 0
12bitsofdata 0
Loadinputregister;TheDACregisterisimmediately
updated(alsoexitshutdown)
X 0 1 12bitsofdata 0
Loadinputregister;TheDACregisterisunchanged
X 1 0 XXXXXXXXXX X
UpdatetheDACregisterfromtheinputregister
(alsoexitshutdown;recallpreviousstate)
1 1 1 XXXXXXXXXX X Shutdown
0
1 1 XXXXXXXXXX X NoOperation(NOP)
ExperimentingwiththePicBasicProCompiler
Program - MAX5352.BAS

InterfacingwiththeMAX5352D/Aconverter
TheseconddemonstrationoftheMAX5352usesa2
.5VVref,butthis
timeitisgeneratedbyaTexasinstrumentsTLE2425,precisionvirtual
groundIC
.ThisIC,outputsaregulated2
.5Vfroma5Vinput
.Therefore,
weareguaranteedasteadyVref,whichwillgiveusgreateroverall
accuracy
.InorderfortheMAX5352toproduceamaximumvoltage
swingof0to5V,theinternalop-ampisconfiguredwithaclosedloop
gainoftwo
;thisisaccomplishedbyR2andR3
.Figure5.6showsthe
circuitforthistechnique
.
Nowthatweareoutputtingavoltagegreaterthan3
.6V,weneedtouse
theformulasforquantasizingtheresult
.Firstly,weneedtocalculatethe
quantalevel
(seepreviousexperiments), whichis
(5/4096), thiswillgive
usaquantalevelof122
.Wenowneedtocalculatethevaluetosendto
theMAX5352whichwillrepresenttheoutputvoltagerequired,justto
remindyou,theformulaforthisis : -
Bval=Vout/quantalevel
Where, Bvalis
the12-bitbinarywordthatwillbesenttotheD/A,and
Voutis therequiredoutputvoltage
.Inordertoobtainamoreaccurate
outputvoltage,weshallbeusingaslightlydifferentapproachtothe
calculationsusedwithinthecompilercode
.Wewillbeusingthe
divisionalremainderoperator,whichis(//) .
Ourformulafromabovecan
bebrokendownintothreeparts,thefirstwillcalculatethemainbodyof
theresult,thesecondpartwillcalculatetheremainder,andthethirdpart,
addsthesevariablestogether,whichwillgiveusthefinalresult
.
Forexample,Let'ssaythatwewishtoproduceanoutputvoltageof3
.8V
,
thecalculationswithinthecompilercodewilllooklikethis
: -
Vout=380
Result=((Vout*100)lquantalevel)*10
Remainder=((Vout*100)//quantalevel)/10
Vout=Result+Remainder
Youwillnoticethatthevalueshavebeenscaledupbyafactorof10or
100
;thisensuresthatwewillachieveamoreaccurateresultfromthe
divisions
.Thistechniquecanbeusedfor8,10,or12-bitDigitalto
Analogueconverters,ifaccuracyisofapremium
.
Section-5-
12
ExperimentingwiththePicBasicPro Compiler
InterfacingwiththeMAX5352D/Aconverter
MAX535212-bitD/Aconvertercircuits
AdjustableVref
Regulated5Volts
RB2
To RBI
RBO
IC1
TLE2425
TLE2425
(Bottomview)
GND
D
OUT
D IN
Figure5.5.
2
.5VoltVrefwithop-ampgainofx2
Regulated5Volts
Figure5.6 .
IC2
VDD
SCLK
~~DIN
IN1

MAX5352
OUT

REF

FB
GND
GND
OUT
Section-5- 1 3
Voltage
Out
R1
10k
R2
10k
ExperimentingwiththePicBasicProCompiler
Program -AD840X.BAS
InterfacingtotheAD8402digitalpotentiometer
Thedigitalpotentiometer (DP)
allowsmanyoftheapplicationsof
mechanicaltrimmingpotentiometerstobe
replacedbyasolid-state
device
.Thedigitalpotentiometer hasseveral
benefitsover its
mechanicalcounterpart,includingcompactsize,freedomfromshockor
vibration,andtheabilitytowithstandoil,dust,temperatureextremes,
andmoisture
.TheserialinterfaceofaDPallowsittobeelectronically
controlledbyamicrocontrollersothattheusercanadjustsystem
parametersquicklyandprecisely
.SomeDPapplicationsinclude
: -
Powersupplyadjustment
Automaticgaincontrol
Volumecontrolandpanning
LCDcontrastcontrol
Programmablefilters,delays,andtimeconstants
ThetwomajorconfigurationsoftheDPincludethe
RHEOSTAT(2-
terminalconfiguration) andthePOTENTIAL
DIVIDER (3-terminal
configuration).
Andalthoughthedigitalpotentiometerisnotspecifically
designedforuseasaD/Aconverter,itisjustoneofseveraljobsthat
theseremarkabledevicesarecapableofachieving
.
TheAnalogDevice'sAD8402isamemberof
aseriesofdigital
potentiometers
.Thisfamilyconsistsofone,two,orfourpotentiometer
devices
.ThesearetheAD8400,AD8402,andAD8403
.Eachofthese
devicescomeinarangeofresistancevalues,1kQ,10kQ,50kQ,
and
100kQ
.Wewilllookatonlyoneofthesedevices,namelytheAD8402
witha1OkQfixedresistanceperpotentiometer
.
TheAD840Xseriesprovides256-positiondigitallycontrolled
variable
resistors (RDAC).
TheRDACisdesignedwithafixedresistorvaluethat
hasawipercontactthattapstheresistoratapointthatisdeterminedby
an8-bitdigitalcode
.Theresistancebetween
thewiperandeither
endpointofthefixedresistorvarieslinearlywithrespecttothe
digital
codelatchedintotheRDAC
.Each
RDACoffersaprogrammable
resistancebetweentheAterminalandthewiper(W)andtheBterminal
andthewiper (W)
.Auniqueswitchingcircuitminimizestheinherent
glitchfoundintraditionalswitchedresistordesigns
byavoidingany
make-before-breakorbreak-before-makeoperation .
Section-5
1 4
ExperimentingwiththePicBasicProC
ompiler
InterfacingtotheAD84OXdigitalpotentiometers
EachRDAChasitsownlatchtoholdthe8-bitdigitalvaluedefiningthe
wiperposition
.Theselatchesareupdatedfroma3-wire SPI (serial
peripheralinterface) . Tenbitsmakeupthedatawordneededforthe
serialinputregister.ThefirsttwoaddressbitsselectanRDACtomodify
andarethenfollowedbyeightdatabitsfortheRDAClatch .Thebitsare
clockedontherisingedgeoftheserialclockMSB
(mostsignificantbit)
first.TheCSpinstartsaserialtransactionbygoinglowandthenlatches
the10-bitsofdataclockedbygoingbackhigh .
TheAD8402providesenhancementsovertheAD8400,suchasreset
andshutdown .WhentheRSpinispulledlow,thevaluesoftheRDAC
latchesresettoamidscalevalueof$80 (128). WhentheSHDNpinis
pulledlow,thepartforcestheresistortoanend-to-endopencircuiton
theAterminalandshortstheBterminaltothewiper
(W) . Whilein
shutdownmode,theRDAClatchescanbeupdatedtonewvalues
.
ThesechangeswillbeactivewhentheSHDNpinisbroughtbackhigh
.
Figure5
.6showstheinternalsoftheAD8402 .
VDD--op.
DGND-11o-
AGND-10-
ADDRESS
DECODER
1SBIT
SERIAL
LATCH
-t VR1
0-8IT LATCH
VR2
8-BIT
LATCH
Section-5-15
VR1
R2
Al
W1
B1
A2
W2
B2
Figure5 .6 .BlockdiagramoftheAD8402digitalpotentiometer .
ExperimentingwiththePicBasicProCompiler
Table5
. 2 . Dataformat
Table5 . 3. Addressbitformat.
ProgrammingtheVariableResistor
Thenominalresistance,R
AB, betweenterminalsAandBoftheAD8402
usedinthisdiscussionis1Oku . TheR
AB oftheRDAChas2 56resistive
contactpointsthatcanbeaccessedbythewiperterminalplusthe
B
terminalcontact.
Foran8-bitvalueof$00,thewiperstartsattheBterminal
. TheB
terminalhasaninherentresistanceof50Q
. Thenextresistiveconnection
hasadigitalvalueof$01
. Ithasavalueequaltothe
Bterminal
resistanceplusanLSBresistorvalue
. Forthe10kQpartused,thisLSB
amountisequalto1OkoJ2 56or39
. 062 5Q
. Therefore,theresistivevalue
at$01is89 . 062 5Q
(50sa+39. 062 5Q).
EachLSBincreasemovesthe
wiperuptheresistorladderuntilthelasttappointishit
.
Section-5 . 16
InterfacingtotheAD84OXdigitalpotentiometers
Theserialinterfacerequiresdatatobeintheformatshownintable5
. 2 .
First,theaddressbitsofA1andAOmustbesent,table5
. 3showsthe
formatforthetwoaddressbits
. Thenexteightbitsarethedatavalueto
belatchedintotheselectedRDAC
.
Figure5 . 7
. Variableresistoror(RHEOSTAT)configuration .
ADDR
DATA
B9 B8
B7 B6 B5 B4 B3B2 B1 BO
Al AO D7
D6D5D4 D3 D2 D1 DO
MSB LSB MSB
LSB
2 " 2 " 2 '
2
Al AO ROACdecoded
0 0
RDAC#1
0
1 RDAC#2
1 0
RDAC#3AD8403only
1 1
RDAC#4AD8403only
ExperimentingwiththePicBasicProCompiler
InterfacingtotheAD840Xdigitalpotentiometers
TheresistancebetweenterminalBandthewiperWcanbedescribed
usingtheformula: -
RWB=D*(R
ae/256)+RB
where
RWB
=theresistancebetweenthewiperW,andterminalB
D=digitalvalueoftheRDAClatch
RAB
=thenominalresistancebetweenterminalAand
B(10ks4
RB
=theresistanceofterminal
B(50x4
Table5.4.RWB
ResistancevalueswithR
AB=1
Q
Notethatthezero- scalevalueproducesaresistanceof50Q
.Care
shouldalsobetakentolimitthecurrentflowbetweenthewiperand
terminalBtoamaximumof5mA
.
TheRDACisfullysymmetrical
.TheresistancebetweenthewiperWand
terminalAalsoproducesaresistancevalueofR
WA. Whensettingthe
resistanceforRWA,
thedigitalvalueof$00startstheresistancesettingat
itsmaximumvalue
.Asthedigitalvalueisincreased,theR WA
resistance
decreases
.Thiscanbedescribedusingtheformula
: -
RWA =(256- D)*(R
AB/256)+RB
where
RWA
=theresistancebetweenthewiperW,andterminalA
D=digitalvalueoftheRDAClatch
RAB
=thenominalresistancebetweenterminalAand
B(10ks4
RB
=theresistanceofterminal
B(50Q)
Table5.5.RWA ResistancevalueswithR
AB=10Q
Section- 5- 17
D RWB(9)
OutputState
255 10010.9375
Fullscale
128 5050
Midscale
1 89.0625
1 81 Leastsignificantbit(LSB)
1 50
Zero- Scale
D
RWB(Q)
OutputState
255
89.0625
Fullscale
128
5050
Midscale
1
10010.9375 181
Leastsignificantbit(LSB)
1 50
.050 Zero- Scale
ExperimentingwiththePicBasicProCompiler
InterfacingtotheAD840Xdigitalpotentiometers
Inthisexperiment,weareonlyinterestedinusingtheAD8402asa
digitaltoanalogueconvertertherefore
;weshalllookatameansof
providingavariablevoltageoutput
.Thisisaccomplishedbytheuseof
thepotentialdividerconfiguration,illustratedinfigure5
.8.TheDPcan
easilybeusedtogenerateanoutputvoltageproportionaltothevoltage
appliedbetweenterminalsA'andB
.IfterminalAisconnectedtothe+5V
supply,andterminalBisconnectedtoground,thewipervoltagehasa
rangeofOVupto1LSBlessthan+5V
.EachLSBisequaltothevoltage
acrossterminalsAandBdividedby256
.Thewiper'soutputvoltagecan
thereforebecalculatedbyusingthefollowingformula : -
Vw =( D/256)*V
AB
+ VB
where
Vw
=voltageonwiper
D=digitalvalueoftheRDAClatch
VAB
=voltageacrossterminalAandB
VB =voltageatterminalB
Figure5.8
.Potentialdividerconfiguration,
Forexampleifweareusingthe10kopartwith+5Vconnectedto
terminalA,andamidscalevalueof$80 ( 128)
isplacedintotheRDAC's
latch
.Thevoltageonthewiperterminal( Vw)wouldbe: -
Vw =( 128/256)*5=2
.5Volts
Intheaboveexample,the
( VAB +VB) partofthecalculationmaybe
replacedwith5and0respectively,asthesupplyvoltage
( VAB)
will
invariablyalwaysbe+5VandthevoltageontheBterminal
( VB) will
usuallybeOV
.
However,weneedtoknowwhatvaluetoplaceinto
D ( RDAClatch) to
outputaspecificvoltage
.
Section- 5- 1 8
ExperimentingwiththePicBasicProCompiler
Section-5-1 9
InterfacingtotheAD840Xdigitalpotentiometers
ThecalculationweshalluseisbasicallythesameforthepreviousDAC
experiments.Wecalculatethequantalevelfor8-bitsofdatausinga5V
supply (5/256).
Thisgivesusourusualquantalevelof .01953,rounding
thisupandmovingthedecimalpointtotherightafewtimes,givesus
ourfinalquantalevelof196
.Therefore,thecalculationplacedinthe
programwilllooklikethis : -
D=(Vw*100)/quantalevel
ThevalueofV W
hasbeenincreasedbyafactorof100,toenableamore
accurateresult.
Program AD840X
.BASandthecircuitinfigure5.9demonstratetheuse
ofanAD8402tooutputavoltagefrom0to4
.99V .Itiscentredaround
thesubroutine RDACOUT, thissubroutineoutputsthe10-bitwordtoan
AD8400,AD8402,orAD8403digitalpot .TheinternalRDACofchoice
(1.
.4)isloadedintothevariable RDAC, andthevoltagetooutputis
placedintoVOUT .Thesubroutinecalculatesthevaluewhichisto
be
placedintothespecificRDAClatchandchecksthevariable RDAC.
A
seriesof if-thens
determinetheaddressbitstosetorclear .Thenthechip
isenabledbypullingtheCSpinlowandthe10-bitsofdataareshifted
out
.ThechipisdisabledbybringingtheCSpinbackhigh, andthe
subroutineisexited.
Themainbodyoftheprogramlooksattheswitchesconnected to
PortB.3(SW1)andPortB.4(SW2)
.Dependingonwhich oftheseis
pressedtheprogramwillincreaseordecreasetheoutputvoltage.
Regulated5Volts
Figure5.9.D/Aconverterusingadigitalpotentiometer .
R1
To
SerialLCD
4.7k
VDDRB7
MCLR

RB6
L- VDD
Voltage
RB5 SHDN

Al
4mHz RB4
iB
R-9

W1
, 2

Out
Crystal
RB3
B
81
14
0SC1

RB2
RB1
e
B
SDI
A08402/10
RBO
PIC16F84
8
CLK
A2
swi
L=
C1
RA4
OSC2

RA3 O
W2
B2
T
lout
C3 C4
RA2
AGNDDGND
C2 W M
22pf 22pf
RAI
a
Ov
vss RAO
r
1sw2
e0
.
1afI T T
ExperimentingwiththePicBasicProCompiler
Section-6
Experimenting
with
RemoteControl
SonyinfraredremotecontrolReceiver.
Assemblercoded,SonyremotecontrolReceiver.
SonyinfraredremotecontrolTransmitter
.
Assemblercoded,SonyremotecontrolTransmitter .
InfraredTransmitter.
InfraredReceiver.
TransmittingandReceivingserialinfrared .
418mHz,A. M. radioTransmitter.
418mHz,A. M
. radioReceiver.
ExperimentingwiththePicBasicProCompiler
Programs- SONY_REC.BAS & SONY_RX.INC
Sony,infraredremotecontrolReceiver
Therearethreemainprotocolsusedforthetransmissionandreception
ofinfraredsignals.RC5,whichisusedbyPhilips,Rec-80,whichisused
byPanasonic,andtheSonyformat (SIRCS), whichwillbedescribed
here.Eachformofinfraredsignallinghasonethingincommon,thatis
theuseofmodulatedinfraredlight.Modulation isusedtoenablea
certainamountofimmunityfromambient lightsources,especially
fluorescentlighting.Thefrequencyofmodulationvariesfrom36kHzto
40kHz,dependingonthemanufacturer .Aninfrareddetectorisrequired
toconvertthismodulatedlightintoadigitalsignal
.Theseare readily
availableinjustabouteveryTV,VCR,andsatellitereceivermadewithin
thepast20years.Thetypeusedfortheseseriesofexperimentsisthe
SiemensSFH506-38, (unfortunatelyit'snowoutofproduction,butthe
alternativesaretheSFH5110ortheLT-1059) . Thesearesmallthree
terminaldevicesthathaveacentrefrequencyofaround38kHz .
However,justaboutanytypemaybesubstituted,theonlydifferencethat
willbeapparentwillbeaslightlackofrange .
FortheSonyprotocol,theremotesendsastartbit,sometimescalledan
AGCpulse,thatis2 .4msin length.Thisallowsthereceiverto
synchronize,andadjustitsautomaticgaincontrol,thisoccursinsidethe
infrareddetectormodule.Afterthestartbit,theremotesendsaseriesof
pulses.A600uspulserepresentsazero,anda1200uspulserepresents
aone,thereisa600usgapbetweeneachpulse.Notallmanufacturers
stickstringentlytothesetimings,sowewill
considerthemas
approximates.Allofthesepulsesbuildupa12-bitserialsignalcalleda
packet.Thiscomprisesofa7-bitbuttonvalue (theremotebutton
pressed), anda5-bitdevicevalue (TV, VCR,etc)
.
Theserialsignalis
transmittedwiththeleastsignificantbitsentfirst.
Figure6.1,showsthereceivercircuit.PortA.0isanoutputtoaserial
LCDmodule,setforinverted9600baud
.ThegreenLEDflasheswhena
valid12-bitpacketisreceived .
Theprogram SONY_REC.BAS, usesanincludefile, SONY_RX.INC to
loadinthereceiversubroutine .Whenthesubroutine SONYINiscalled,
itreturnsthreevalues.Thebuttonpressedontheremote isheldin
IRDATA, thedevicecodeisheldin IRDEV, andthebitflag, IRVALID
issetifavalidsignalwasdetected,andclearifnot
.
Section-
6 -1
ExperimentingwiththePicBasicProCompiler
Therefore,ourcodewilllooklikethis : -
Again:
GosubSony_In

`Receivethe12- bitpacket
IfIRValid=0thengotoAgain

`Testifavalidpacketreceived
Thethreevariables, IR_DATA,IR_DEV, and IRVALID arealreadypre-
declaredwithintheincludefile .However,thePortandpinonwhichthe
infrareddetectorisconnectedmustbechangedwithintheIncludefile, if
PortA.4isnotused .
Thecodewithinthesubroutine SONY- IN workslikethis,First,ittests
theinputonwhichtheinfrareddetectorisconnected,thiswillbelowif
wearealreadyinthemiddleofapacket, (note: thedetectorpullsits
outputlowwhenasignalisdetected) . Ifwearenotalreadyinthemiddle
ofadatapacket,theheaderpulseislookedforusingthePULSIN
command ;theresultisplacedinthevariable,ST .Notallremotessend
anexact2 .4msheaderpulse;thereforewetestforapulsewithinthe
limitsof2msto2 .7ms.ThePULSINcommand,usedwitha4mHzcrystal
hasaresolutionof10us;thereforeapulseof2.4ms (2400us) willbe
returnedas240 .Ifaheaderisnotdetectedtheflag IRVALID iscleared,
andthesubroutineisexited .However,ifavalidheaderisdetected, a
loopof12issetup,withinthislooptheindividualdatabitsareinputted,
againusingthePULSINcommand .Weknowthata1 bithasapulse
durationof1200us,andthata0bithasadurationof600us,thereforewe
cansplitthedifferenceandsaythatapulsedurationofover900usmust
bea1bit,andanyvalueunderthis,mustbea0bit.Theloopcounter
doesthis12timestobuildupthe12- bitpacket .Eachtimeapulseof
over90isreceivedtheappropriatebitofthevariable
IRWORD isset,
elseitiscleared .
Afterthe12- bitshavebeenreceived,the7- bitbuttoncodeandthe5- bit
devicecodemustbeseparatedintotheirappropriate variables.To
separatethebuttoncode,thevariable IRWORD isANDedwith
%01111111,thishastheeffectofmaskingallbutthefirst7- bits, the
resultisthenplacedintothevariable IRDATA. Toseparatethedevice
code,thevariable IR_WORD isshiftedrightseventimes,the5- bitcode
nowstartsatbit- 0of IRWORD, againitisANDed,thistimewith
%00011111,theresultisthenplacedintothevariable IR_DEV . Theflag,
IR_VALID isset,whichindicatesavalidpackethasbeenreceived,then
thesubroutineisexited .
Section- 6-
2
Sony,infraredremotecontrolReceiver
ExperimentingwiththePicBasicProCompiler
Programs-SONY_ASM.BAS&ASM_RX.INC
Section-6
- 3
Sony,infraredremotecontrolReceiver
Assemblercoded,SonyremotecontrolReceiver
.
Theincludefile
ASM_RX.INC, achievesthesameresultsasthe
previous,BASICcodedversion,exceptthatit-isalotsmaller,only77
bytes,andisalsoonlyexecutableusinga4mHzcrystal
.Exactlythe
samevariablesare returned,
namely, IRDATA, IRDEV, and
IRVALID.
Inaddition,twonewdefineshavebeenadded,toinformthe
subroutineastowhichpintheinfrareddetectoristobeplaced,these
are: -
Define IRINPORT

Port

`Port forthe IRdetector


Define IRIN_BIT

Bit

`Bit forthe IRdetector


Iftheseareomittedfromtheprogram,thedefaultisPortA.4 .Asalways,
theincludefilemustbeplacedatthebeginningofyourprogramtoavoid
anypageboundaryconflicts .
+5Volts
SFH506
H
211
1
.VOUl
2.Vcc
3.Gnd
vcc -
voul
Gnd
To
SerialLCD
N9600baud
Figure6
.1.Sony,InfraredremotecontrolReceiver .
Rl
4 .7k
VDD
RB7
L3_
MCLR

RB6
2
4mHz
RB5
0
Crystal
RB4
RB3
s
SFH506-38
1s
0SC1

RB2
e
IRdetector
7
RB1
6
C1 C2
RBO
lOuf
PIC16F84
3
~O.iuf
0 la
RA4
C3 C4
OSC2

RA3
t
"'
2pf 22pf
RA2
RA1
e
R2
470
RAO
T
S
V~5
s

Green
ti
LED
ExperimentingwiththePicBasicPro
Compiler
Programs -BAS_TX.BAS,SNY_SEND &SONYTRUNC
Sony,infraredremotecontrolTransmitter
The transmitterdescribedherecomplementsthepreviousreceiver
experiments
.Thetransmittersendsouta2.4msheaderpulse,thena12-
bitwordconsistingofa7-bitbuttoncode,anda5-bitdevicecode .Unlike
otherprogramsthatrequireagatedoscillatortogeneratethe38kHz
modulation,thisisachievedwithinthecodeitself.38kHzhasatime
durationof26us
;therefore,byturningtheinfraredLEDonfor13usand
offfor13us,apulseof38kHzistransmitted, (Time(inus)=1000/
Frequency(inkHz)) .
Thisisaccomplishedbythesubroutine, IR_MOD,
thisturnstheinfraredLEDon,waits8us,thenturnstheinfraredLEDoff,
andwaitsafurther7us .Assuminga4mHzcrystal,thecommandsLOW
andHIGHeachtake4ustocomplete,theNOP'stake1useach,andthe
GOSUBandRETURNcommandstakeafurther3us
.Soaltogether,we
haveamodulationtimeof (2+4+8+4+7+1=26us).
IfaPICisusedwith
morethan2kofROM,thenthecompilerwillplaceextracodeto
manipulatethePCLATHregisterfortheGOSUBcommand .Thiswill
needtobecompensatedfor,byreducingtheamountofNOP's .The
PAUSEUScommandcouldnotbeused,asitsminimumdelayis24us
witha4mHzcrystal,hencetheuseoftheNOP's .The IR_MOD
Section-6 -
4
subroutineisshownbelow: -
IR_Mod.-
HighIRLED 'TurnontheIRLED.(4cycles)
Nop
Q Nop
'EachNOPtakes1instructioncycle
@ Nop ' assuminga4mHzcrystal
Nop
Nop
'RemoveforPICswithmorethan2KROM
Nop
Nop
Nop
'Donothingfor8cycles
LowIRLED
'TurnofftheIRLED.(4cycles)
Nop
Q Nop
Q Nop
Q Nop 'RemoveforPICswithmorethan2KROM
C'
Nop
Q Nop
C! Nop
'Donothingforafurther7cycles
Return 'Returnfromthesubroutine,(1cycle)
ExperimentingwiththePicBasicProCompiler
Sony,infraredremotecontrolledTransmitter
Transmittingthepulsedurations,600us,1200us,and2400us,is
performedbythesubroutine,
BURST, thiscreatesaloopofdifferent
lengthsforeachduration
.Thetimingsofthisloopwereaccomplishedby
trialanderror,asit'snotaseasytocount
.thecyclesusedinthis
subroutineasitwasin
IRMOD. Withintheloop,theinfraredLED
modulationsubroutineiscalled,thustransmittingamodulatedsignalfor
agiventime
.Thevariouspulsedurationsareplacedinthevariable,
B-TIME.
Burst:
ForB_Loop=itoBTime
'Loopforthepulsedurationrequired
GosubIRMod

'ModulatetheIRLED,(2cycles)
NextB-Loop

'Closethepulsedurationloop
Pauseus600

'Pausefor600usaftereverypulse
Return

'Exitthesubroutine
Nowthatwehavethemeanstosendtheinfraredsignal,weneedto
buildupthe12-bitword
(knownasapacket), whichcontainsthebutton
anddevicecodes
.Firstly,weneedtoplacethetwocodesintheircorrect
positionswithinthepacket,
(thebuttoncodeinthefirst7-bitsandthe
devicecodeinthenext5-bits)
. Thevariable IR_WORD
holdsthepacket
thatwillbesent .Thedevicecode,heldin
IRCMD isfirstplacedintothe
highbyteof IR_WORD,
thenshiftedrightonebit
.Thiswillplaceit
startingatthebit-8
.Bit-7ofthebuttoncode, IRBYTE
isclearedasa
precautionagainstavaluegreaterthan127beingentered
.Thenitis
ORedinto
IRWORD,
thishastheeffectofsuperimposingonevalueinto
another
.Wenowhaveourtwocodesintheircorrectpositionswithin
IR_WORDreadytosend
.Afor-nextloopissetuptoexaminethefirst12-
bitsof
IRWORD, ifthebitisa1then
B-TIME isloadedwiththevalue
forapulselengthof1200us,elseitmustbeazero,andapulselengthof
600usisplacedinto B-TIME.
Afterall12-bitshavebeensent,adelayof35msisimplemented
; thiswill
bringthetotaldelaytimeofthepacketsent,toapprox45ms
.
Tousetheinfraredtransmitter,placethebuttonvaluewithinthevariable
IRBYTE, andthedevicecodewithinthevariable
IRCMD.
IR
_
CMD=1

'Setdevicecodeto1(television)
IR_BYTE=18

'Sendvolumeupcommand
GosubSony_Out

'Sendthe12-bitpacket
Section-6 - 5
ExperimentingwiththePicBasicProCompiler
Sony,infraredremotecontrolledTransmitter
Program, BASTX.BAS,
demonstrates the use ofthe infrared
transmitter,witha12-buttonkeypad,asinfigure6 .2 .Thekeypadisused
tosendthechannelbuttonsandvolumeupanddown, " * " isusedfor
volumedown,and" #" isusedforvolumeup .Thelookuptableconverts
thevaluesreturnedfromthe INKEYS
subroutine,intothevalueexpected
bytheSonydeviceyouwishtocontrol,atelevisioninthisinstance .
Program, SNYSEND.BAS,
doesexactlythesameastheabove
program,butusingtheincludefile
SONYTRX.INC
.
Figure6 .2,showstheconnectionstothepic .Transistor,Q1amplifiesthe
outputoftheinfraredLED,youwillhavenoticedthatthereisnoseries
resistorwiththeinfraredLED,thisisbecausetheLEDisneverfullyon,it
isalwaysmodulatedwitha38kHzsignal .ThisactsasaformofPWM
.If
Q1isomitted,theinfraredLEDmaybeconnecteddirectlytothepinof
thePIC,however,thiswillresultinadrasticlackofrange .Thegreen
LEDisilluminatedwheneverasignalistransmitted
.
+5Volts
C1

T
1Out

C3

C4
C2 -
_22pf22pf
I O.1ul
TTT
O
v
9
4mHz
Crystal
VDDRB7
MCLR RB6
RB5
RB4
RB3
0SC1 RB2
RB1
RBO
PIC16F84
RA4
0SC2 RA3
RA2
RA1
VSSRAO
Figure6 .2 .Sony,infraredremotecontrolTransmitter.
Section- 6 -6
ExperimentingwiththePicBasicProCompiler
Programs-SONY_TX
.BAS&SONYTX.INC
Sony,IRremotecontrolledTransmitter
Assemblercoded,SonyInfraredremotecontrolTransmitter
Thisassemblercodedtransmitterusesthesameprincipalsasdescribed
fortheBASICcodedversion,butusesalotlessmemorywithinthePIC
.
TheassemblersubroutineistransparenttoyourBASICprogramasitis
intheformofanincludefile, SONYTX
.INC, andacalltoasubroutine,
SONYOUT.
Aswiththereceiversubroutineitisonlycompatiblewitha
4mHzcrystal
.Theassembycodewillnotbeexplained,howeveritisfully
commentedifyouwishtoexamineitmoreclosely
.
Tousetheinfraredtransmitter,placethebuttonvaluewithinthevariable
1R_BYTE,
andthedevicecodewithinthevariable IR_CMD
. Thevariable
nameshavebeenchangedfromthereceiverroutine
toavoidany
duplicatevariableerrorsoccurringifbothareused
withinthesame
program
.Again,therearetwonewdefinesadded,these
informthe
subroutinewhichportandbittoplacetheinfraredLED
.Theseare: -
Define
IROUTPORT Port

`PortfortheIRLED
Define IROUT_BIT

Bit

`BitfortheIRLED
Ifthesedefinesareomittedfromyourprogramthedefaultsare,PortA
.O.
Program SONYTX
.BAS, demonstrates
theuseofthe infrared
transmitter,witha12-buttonkeypad,asinfigure6
.2
.Thekeypadisused
tosendthechannelbuttonsandvolumeupanddown,
" * "
isusedfor
volumedown,and" #" isusedforvolumeup
.TheLOOKUPcommand
convertsthevaluesreturnedfromthe
INKEYS
subroutine,intothevalue
expectedbytheSonydeviceyouwishtocontrol,atelevision
inthis
instance.
Section-6 -
7
ExperimentingwiththePicBasicProCompiler
Programs -IRTRANS.BAS &
IR_RX_TX.INC
InfraredTransmitter
Theprevioustwoprojectsareidealifaremotecontrolhandsetisallthat
isbeingimplemented .However,ifafull8-bitbyte
istobesentor
receivedthentheprojectpresentedherecanbeused .WithintheInclude
file, IR_RX_TX.INC,
therearetwosubroutines, IROUT, whichwill
transmitan8-bitbyte,alongwithauniquetransmitternumber,and
IRIN,
whichwillreceivetheIRsignalfromitscomplementarytransmitter
. Both
subroutinesarewritteninassembler,andareforuse witha4mHz
crystal
.However,thisistransparenttoyourBASICprogram,andallthat
isrequiredarethatafewvariablesbeloaded,andacallmadetothe
relevantsubroutine .Theaddedadvantageisthat,boththe
IROUT and
IRIN
subroutinescombined,onlyuse112 bytesofROM.The
transmissionandreceptionmethodused,isbasedontheSonyprotocol,
however,insteadofsending12-bits,16-bitsaresent
.Thismeansthata
full8-bitscanbesentforthedatabyte,andanother8-bitscansignifya
uniquenumberforeachtransmitterused .Fournewdefineshavebeen
added,toinformthesubroutinesoftheportandpintoconnect the
infrareddetectorandtheinfraredLED
.Twoofthesedefinesareforthe
transmittersubroutine, IROUT andtheseare : -
Define IROUT_PORT Port

`Port fortheIRLED
Define IROUTBIT

Bit

`BitfortheIRLED
IfthedefinesarenotusedinyourprogramthedefaultisPortA.O
Tousethetransmittersubroutine,loadthebytetosendintothevariable
IRBYTE, andthetransmitteridinto IRID, thenmakeacallto
IROUT.
Forexample: -
IR_
ID=2

`Thisistransmitter2
IR_BYTE=254

`Let'ssendthevalue254
GosubIROUT

`Transmitthetwobytes
Thetwovariables, IRBYTE and IRID arepre-declaredwithinthe
includefile,
IRRXTX.INC, therefore,theydonotneedtobedeclared
withinyourprogram .
Thecircuitforthe IROUT
subroutineisthesameastheSonyremote
controltransmitter,figure6 .2
.Butthekeypadmaybediscarded .
Section-6 -8
ExperimentingwiththePicBasic
Pro Compiler
Programs-IR_REC.BAS & IR_RX_TX.INC
InfraredReceiver
Thereceiverdefines,againinformthe IRIN
subroutineastowhichport
andpintoplacetheIRdetector,theseare : -
Define
IRINPORT

Port

`Port fortheIRdetector
Define IR/NBIT

Bit

`BitfortheIRdetector
Ifthe MIN definesarenotused,thedefaultisPortA
.4 .
Tousethereceiversubroutine,makeacallto
IRIN, andtherearethree
variablesreturned,theseare
IR_BYTE,IRID, and IR_VALID
. Asyou
willhaveguessed, IR_BYTE
containsthebytetransmitted,and IRID
containsthetransmitterid value. I R
VALID isabitvariable,which
returnsthevalues1or0
.Ifavalid16-bitpackethasbeenreceived
correctly,thenthisflagisset,howeverifavalidpacketwasreceived
incorrectlyitisclear .Forexample
: -
Again:
GosubIR/N
`Receivea16-bitpacket
IfIRVALID=0thengotoAgain
`Checkifpacketisvalid
If IR_
ID=2then
`ChecktheTXIDcode
DothecodewithintheIFstatement 'Dothiscodeifcorrect
Endif
Thecircuitforthe IRIN
subroutineisthesameastheSonyremote
controlreceiver,figure6
.1 .
Section-6 -9
ExperimentingwiththePicBasicProCompiler
Programs-
IRSEROUT.INC,IRSERIN.BAS&SER_IR
.BAS
TransmittingSerialinfrared
Thefinalmethodweshalllookatfortransmittingandreceivinginfrared
signals,isthatofnormalRS232serialprotocol
( i .e. inverted2400baud
etc) .
Thiswillallowustosendmorethanonebyteatatime
.However,
wecannotsimplyconnectaninfraredLEDtothePICandinvokethe
SEROUTcommand,theLEDmustbemodulatedat38kHz
.Therefore,
thetransmittersubroutinehashadtobewritteninassembler,
butis
compatiblewith4,8,10,and12mHzcrystals
.Asalways,theincludefile,
IRSEROUT
.INC mustbeplacedatthebeginningofyourprogram
.In
addition,FIVEnewdefines
havebeenadded,whichenablethe
IRSEROUTsubroutinetobecustomized
.Thefirsttwodefines,configure
theportandpinonwhichtoconnecttheIRdetector,theseare
: -
Define IRSEROUT_PORT
Port

`PortfortheIRLED
Define IRSEROUTBIT

Bit

`BitfortheIRLED
Ifthesedefinesarenotusedinyourprogram,thedefaultsarePortA
.0
Thethirddefine,configuresthedesiredtransmissionbaudrate
.
There
arefourbaudratestochoosefrom,namely,300,600,1200,and2400
.
Define IRSEROUTBAUD
Baud

`Desiredbaudrate
Ifthisdefineisomittedfromyourprogramthedefaultis1200baud
Themaximumbaudrateachievablewithanyaccuracyis2400
; thisis
becausethecomponentswithintheinfrareddetectormodulecause
a
finitedelaybetweenreceivingtheinfraredsignalandoutputtingthelogic
level
.Thebaudmodeis,inverted,1start-bit,8data-bits,and1stop-bit
.
Thefourthdefine,setsthedelaybetweenbytestransmitted
.Sometimes
thetransmissionratesof
IRSEROUT
maypresentcharacterstooquickly
tothereceiver
.Therefore,adelayof1to255milliseconds( ms) ,
maybe
implemented .
Define IRSEROUTPACING
1 . . . 255
`delaybetweenchrs( ms)
Ifthisdefineisnotused,thedefaultis1ms
Section-6-1 0
ExperimentingwiththePIcBasicPro
Compiler
TransmittingSerialinfrared
Thefifthdefine,switchesonoroffa3-byteheaderthatprecedesevery
databytetransmitted
.
Define
IRSEROUTHEADER1or0

Turnon/offheader
The3-byteheader,consistingof"#0K",allowsthereceivertoadjustits
internalAGC,andsynchronizewiththestartofatransmission
. Unlike
asynccommunicationsoverwires,thereareplentyof38kHzmodulated
signalsaround,namelytheTVremote
. Thesecanbepickedupbyour
receiverandinterpretedasvalidsignals,withdisastrousresults
. Thus,
weplaceauniquesequenceofcharactersthatsignifythatasignalfrom
ourtransmitterhasbeensent
. Thelikelihoodofthesamethree
charactersbeingrandomlyproducedisvirtuallynon-existent
. The
internallyproducedheaderisusefulifonlyonebyteofdataisbeing
transmitted,otherwise,everybytesentwillhavea3-byteheader
precedingit
. Toillustratetheuseoftheheadercharacters,andtoshow
howeasyitistotransmitseveralbytes,yourcodecouldlooksomething
likethis: -
IRByte='W" : GosubIRSerout
`Sendathreebyteheader
IR_Byte=
"0" : GosubIRSerout
'tosynchronisethereceiver
IRByte=W"
: GosubIRSerout `withtheactualbytessent
IR_Byte=127
: GosubIRSerout`Sendabytewithvalue127
IRByte=254
: GosubIRSerout`Sendabytewithvalue254
IRByte=2
: GosubIRSerout

`Sendabytewithvalue2
Thevariable, IR_BYTE
hastobepre-loadedwiththebytetobe
transmitted,andthenacallismadeto
IRSEROUT. Iftheheaderdefine
isnotused,thedefaultisNOheader
. Thereisnoneedtodeclarethe
variable, IR_BYTE
inyourprogram,asitisalreadypre-declaredwithin
theincludefile. Theprogram
SER_IR. BAS, illustratestheuseofthe
IRSEROUT subroutine.
Section-6- 1 1
Experimentingwith theP ic Basic ProCompiler
Rec eivingserialinfrared
Rec eivingSerialInfrared
Torec eivetheserialinfraredsignal,wesimplyusethec ompiler's
SERIN2orDEBUGINc ommands
.Thesearemoredesirablethanthe
normalSERINc ommand,sinc etheyc anautomatic allywaituntilthe3-
byteheaderisfound,usingtheWAIToperand : -
Serin2PortA.4,BAUD, [ wait (" #OK"), IR_Rc v
]
Thiswillwaitforthec harac ters,"#OK"toberec eivedbeforeitrec eives
theac tualbyte,whic hitplac esintothevariable IRRCV. Thishelpsto
sync hronizethestartoftheac tualtransmission,andalsopreventsfalse
c harac tersbeinginterpretedasvaliddata .
Toc alc ulatethebaudrateusedintheSERIN2c ommand,theformulais
(1000000/baud) -20, alsothebaudmodemustalwaysbesettoTrue,
thisistheoppositeofthetransmitter'smode,bec ausetheinfrared
detec torpullsitsoutputlowwhenitrec eivesasignal,therefore,itinverts
theinc omingsignal
.Thetablebelowshowsthevaluetoplac eintothe
Constant BAUD,forthedesiredbaudrate .
T2400baud396
T1200baud813
T600baud1646
T300baud
3313
Theprogram, IRSERIN.BAS
illustratesonetec hniqueforrec eiving
severalbytes.Thec irc uitfortherec eiveristhesameasthatfortheSony
remotec ontrolrec eiver,figure6.1 .
Sec tion-6- 1 2
ExperimentingwiththePicBasicProCompiler
Program -AMTX.BAS
Markdenotes
positiveside
I I
AM-TX1-418Pinouts.
Signalin
Figure6 .3
.Basiccircuitarrangement.
418mHz,AMRadioTransmitter
Remotecontrolsystemsarebecomingincreasinglypopular,andthe
introductionofpre-tunedradiomodulesandtheireverdecreasingprices
hasmaderadioapracticalalternativetoinfrared
.Theadvantageofradio
istheabilityofthesignaltopassthroughobjectsandwalls.I tsrangeis
alsoimpressive,100metresormore
( in freespace) beingnormal.No
licenceisrequiredintheUK,providingtheradiomodulesoperateonthe
418mHzor43 3 mHzwavebands.Theradiomodulesmaybeusedina
similarwaytothoseintheinfraredremotecontrolsections.
Althoughthemodulesdescribedinthissectionarethea
.m.type,thef .m.
typesmaybedirectlysubstituted .
I nordertocarryinformationtherequiredsignalmustbesuperimposed
ontheradiowave ( knownasthecarrierwave)
. WithAmplitude
Modulationtransmissions,itisthe amplitude ofthecarrierwavethatis
madetochangeinaccordancewith
therequiredsignal .Thisis
reasonablyeasytogenerate,butcansufferfromexternalinterference
.
AM-TX1-418Transmitter
TheRFSolutionsa.m
.transmittermodule,typeAM-TX1-418,isa2-pin
devicethatissimilarinappearancetoacapacitor.I t'sincrediblysimple
touse,thestandardcircuitarrangementisshowninfigure6
.3 .
AM-7X1 .418
Section-6- 1 3
E xpe rime nting wit t e P ic Ba sic P ro Compile r
4 1 8 mHz, AM Ra d io T ra nsmitte r
Only a f e w a d d itiona l c ompone nts a re re quire d , a c a pa c itor w ic c a n be
a ny va lue f rom 200pF to 0 . 1 uF, a nd Rx
. T e va lue of Rx is c ose n
a c c ord ing to t e supply volta g e use d in t e c irc uit,
( be twe e n 3 a nd 1 2V) .
T e list be low s ows t e va lue s f or e a c volta g e use d , a s we ll a s ot e r
spe c if ic a tions: -
Supply volta g e

Re sistor va lue
1 2V

2. 2kQ
9V

1 . 8 kc 2
6V

1 kQ
4 . 5V or 5V

4 709
3V

1 005
Curre nt c onsumption
: 2 . 5mA ( typic a l)
CMOS/ T T L c ompa tible input
Da ta t roug put
: 1 200 ba ud ( 24 00 ba ud ma x)
T e AM- T X1 - 4 1 8 mod ule re quire s a n a e ria l w ic is slig tly more d if f ic ult
to se t up t a n t e AM- RT 4 - 4 1 8
. T wo a rra ng e me nts a re illustra te d in
f ig ure 6. 4
. A sma ll va ria ble c a pa c itor a ving a 2pF to 5pF ra ng e is a lso
re quire d , a nd must be a d juste d to provid e t e strong e st sig na l
. I f no
a e ria l or c a pa c itor is use d , a typic a l ra ng e is a pprox 5 me tre s
.
f
RF Ground

2 - 5pf
S ort W ip Ae ria l
Fig ure 6. 4
. Ae ria l a rra ng e me nts f or t e AM- T X1 - 4 1 8 T ra nsmitte r
.
Se c tion- 6- 1 4
ExperimentingwiththePicBasicProCompiler
1
AM-RT4-418
,
TopView
4
2

3
1 . . . VCC
2
. . . GND
3DATAIN
4AERIAL
Figure6 . 5
. AM-RT4-418PinoutsandBasiccircuitarrangement .
Theoperatingvoltageforthismodulemaybeanythingbetween
2to
14V,itdraws4mAwhenasignalisbeingtransmitted, andhasa
maximumdatarateof4kHz
(4800 baudmax). Theaerialforusewiththis
modulemaybeawhiptypeorahelicalcoil
. Thehelicalcoilconsistsof
34turnsof0 . 5 mmenamelledcopperwire,closewoundona2
. 5 mm
diameterformer
. Thisusesalotlessspace thanthewhipaerial,
however,itsperformanceisalittleinferior,andsmalladjustmentstoits
lengthmayberequired . Awhipaerialisthesimplesttype
forthis
transmitter. Itcanbeassimpleasapieceofwire (or pcbtrack) 17cm
long
. Thewireshouldbeasstraightaspossible. Thereisnoneedfora
variablecapacitorwiththistransmittermodule
. Again,ifanaerial isnot
used,theusefulrangeisreducedtoapprox10metres .
InterfacingatransmittermoduletothePICisaseasyasattaching its
inputtooneofthePIC'soutputs
. Thereisnoneedtomodulatethesignal
with38kHz,thereforeanyoftheSERIALcommandsmaybeused,orthe
PULSOUTcommand,andwiththeaddedluxuryofanydesiredoscillator
frequency
. Theuseofasynchronisingheaderisalwaysrecommended
whensendingserialdata,thiscanbeassimpleasthe3-byteheader
used
intheserial infraredtransmitterexperiment. Withoutthe
synchronisingheader,randominputscouldbeinterpretedasvaliddata .
Otherthanthat,thesemodulesmaybetreatedasifawireinterfacewas
beingused .
Signalin
Section-6-1 5
418mHz,AMRadioTransmitter
AM-RT4-418Transmitter
Analternative418mHza. m . transmittermoduleistheRFSolutions,AM-
RT4-418. ThisishousedinaD
. I . L. packageanditsbasiccircuit
arrangementandpinoutsareshowninfigure6
. 5
ExperimentingwiththePicBasicProCompiler
Program-AM_RX.BAS
AM- RX-
TTT

T
123

7
1 .. .RFVCC
2.. .RFGND
i3.. .AERIAL
7. . .RFGND
10 . .AFVCC
1 . .AFGND
12. .AFVCC
13. .TESTPOINT
14 . .OUTPUT
15 . .AFVCC
TTTTTT
10

1s
418mHz,AMRadioReceiver
Therearethreetypesofa .m
.receiveravailable .Theyallhavethesame
pinlayoutsandareinterchangeablewitheachother
.Thethreeversions
are: -
AM-HRR1-418: Thisistheleastexpensive,andalthoughitwas
supersededbytheHRR3type,itsperformanceissurprisinglygood
.
AM-HRR3-418:
Asabove,butislasertrimmedforgreateraccuracyand
lessfrequencydrift.
AM-HRR5-418:
Thesamelasertrimmeddesignasabove,butwitha
lowercurrentconsumption(0
.5mA).
Thethreereceivershavethefollowingspecifications : -
Supplyvoltage: 4.5Vto5 .5V
Supplycurrent: 2.5mA(HRR5version : 0
.5mA)
CMOS/TTLcompatibleoutput
Maximumdatarate2kHz
(inpractice4800baudhasbeenachieved)
Thepinlayoutandbasiccircuitarrangementforallthreereceiversis
showninfigure6.6
.Theaerialforthesereceiversisthesameasforthe
AM-RT4-418transmitter
.
+5Volts
RFVCC
RFGND
AERIAL
AM
HRRX-418
RFGND
AFVCC
AFGND
AFVCC
TESTPT
OUTPUT
AFVCC
Eq
i
M

V
Aerial
0 .1of
Data
Out
Figure6.6.AM-HRRX-418pinoutsandbasiccircuitarrangement
.
Section-6-16
ExperimentingwiththePicBasicProCompiler
418mHz,AMRadioReceiver
Aswiththetransmittermodules,interfacingthereceivertothePICisa
simplecaseofconnectingitsdataoutpintooneofthePIC'spins
.Then
byusingoneofthecompiler'smanyserial-incommands
(DEBUGIN,
SERINetc),
thedatafromthetransmitterisreceived.
Thereceiversdiscussedmayreceivedatauptoalimitof4800baud
;
however,therearereceiversavailablethatarecapableofreceivingdata
manytimesfasterthanthis,alongwiththeircorrespondingtransmitter .
But,asthetransmissionrategoesupsodoestheprice
.Withgoodaerial
design,thesimpleandinexpensive418mHzmodulesarecapableof
remarkabledistanceswithahighdegreeofaccuracy .
TheaccompanyingCDROMhasacomprehensivesetofdatasheetsand
applicationnotesformostofthemorecommontransmitter/receiver
modulesavailable.
Section-6- 1 7
ExperimentingwiththePicBasicProCompiler
Section-7
Temperature
Measurement
Experiments
InterfacingwiththeDS1820.
Dallas1-wireinterfaceprincipals.
InterfacingwiththeLM35temperaturesensor
.
ExperimentingwiththePicBasicProCompiler
Program -DS1820.BAS
InterfacingwiththeDS1820,1-wiretemperaturesensor
TheDallasDS1820isacompletedigitalthermometeronachip .Itcan
measuretemperaturesfrom-55Cto+125Cin0
.5Cincrements.
TheDS1820communicateswiththePICthrougha1-wireconnection .
Thishasamaster,whichisthePIC,andoneormoreslaves
.The
DS1820actsasaslave,receivingcommandsthentransmittingitsdata
backtothemaster.The1-wiresystemrequiresstrictprototocolsfor
transmissionandreceptionofdata,thesearecalled time-slots.
1-wireinterfaceprincipals .
Alltransactionsonthe1-wirebusmustbeginwiththemastersendingan
initialisationsequence .
TheINITIALIZATIONSEQUENCEconsistsofthemasterpullingtheDO
linelowforaminimumof480us .ThemasterthenreleasestheDOline
(whichisheldhigh viaapullupresistor)
andgoesintoreceivemode .
AfterdetectingtherisingedgeontheDOline,theDS1820waits
15.
.60us,thentransmitsitspresencepulse .Thisisalowsignal,which
lastsfor60. .120us
.IfforanyreasontheDS1820didnot,orisnot
capableofsendingapresencepulsetheDOlinewillremainhighandan
errorflagmaybeset : -
DS-
Init .-Low DQ
Pauseus500
DQDIR=1
Pauseus100
IfDQ=1then
DS_
Valid=0
Return
Endif
Pauseus 400
DS Valid=1
Return
'Setthedata
pinlow toinitialize
'Waitformore than 480us
'Releasethe data pin(settoinputfor high)
'Waitformore
than 60us
'Istherea DS1820detected?
'Ifnot, then clear DS_VALIDflag
'Return with DSVALIDholding0(error)
'Else
' Waitfor endofpresencepulse
'Set DS_VALIDflag
'Return with DS_VALIDholding1(no error)
Section-7 -1
ExperimentingwiththePicBasicProCompiler
InterfacingtotheDS1820,1-wiretemperaturesensor
TheDS1820aswithallthe1-wiredevicesoperatewith instructions,
thesearetransmittedbythemasterimmediatelyafterthebusis
initialised
.TheDS1820understandseleveninstructions (op-codes), the
mostcommonoftheseareexplainedbelow.
SKIPROM[CCh]
Thiscommandallowsthemastertoaccessthememoryfunctions
withoutprovidingthe64-bitromcode.Ifmorethanoneslaveispresent
andareadcommandissentaftertheSkipromcommand,datacollision
willoccuronthebusasmultipleslavestransmitsimultaneously
.
READROM[33h]
ThiscommandallowsthemastertoreadtheDS1820's8-bitfamilycode,
(aunique48-bitserialnumber),
and8-bitCRC.Thiscommandcanonly
beusedifthereisasingleDS1820onthebus .Ifmorethanoneslaveis
present,adatacollisionwilloccurwhenallslavestrytotransmitatthe
sametime.
READSCRATCHPAD[BEh]
Thiscommandreadsthecontentsofthescratchpad .Readingwillbegin
atbyte0,andwillcontinuethroughthescratchpaduntiltheninth
(byte-8,
CRC)
byteisread
.Ifnotalllocationsaretoberead,themastermay
issuearesettoterminatethereadingatanytime .
COPYSCRATCHPAD[48h]
ThiscommandcopiesthescratchpadintotheeepromoftheDS1820,
storingthetemperaturetriggerbytesin non-volatilememory.Ifthe
masterissuesreadtimeslotsfollowingthiscommand,theDS1820will
outputazeroonthebusaslongasitisbusycopyingthescratchpadto
eeprom,itwillreturnaonewhenthecopyprocessiscomplete. Ifthe
DS1820isparasitepowered,themasterhastoenableastrongpullup
foratleast1 Oms immediatelyaftersendingthiscommand
.
CONVERT[44h]
Thiscommandbeginsatemperatureconversion . Nofurtherdatais
required .Thetemperatureconversion willbeperformed,thenthe
DS1820willremainidle
.Ifthemasterissuesreadtimeslotsfollowing
thiscommand,theDS1820willoutputazeroonthebusaslongasitis
busymakingatemperatureconversion,itwillreturnaonewhen
the
temperatureconversioniscomplete.
Section-7 - 2
ExperimentingwiththePicBasicProCompiler
DS_Write:
For Bit_Cnt=1to8
IfCmd.0=0then
LowDQ
Pauseus60
DQ_DIR=1
Else
LowDQ
Nop
DQDIR=1
Pauseus60
Endif
Cmd=Cmd>>1
Next
Return
InterfacingtotheDS1820,1-wiretemperaturesensor
WRITESCRATCHPAD[4Eh]
ThiscommandwritestothescratchpadoftheDS1820,startingat
address2
.Thenexttwobyteswrittenwillbesavedinscratchpad
memory,ataddresslocations2and3
.Writingmaybeterminatedatany
pointbyissuingareset .
Toreadavaluefromthe1-wireslave,ortotransmitaninstruction,the
master/slavemanipulatestheDQlineforspecificlengthsoftime,which
willtransmit/receiveaoneorazero
.
Alloftheinstructionsaremadeupof8-bits
.ToTransmitaninstruction
acrossthe1-wirebus,themastermustscanthe8-bits
(leastsignificant
bitfirst)
thatmakeuptheinstructionthensendeitheraoneorazero
accordingly.
AONEistransmittedbypullingtheDQlinelowforlessthan15us,then
released (settoinput)
. Asthewritetime-slotmustbeaminimumof60us
inlength,therestofthetime-slotispaddedoutwitha60usdelay
.
AZEROistransmittedbypullingtheDQlinelowfor60us,thenreleased
byconfiguringthepinasaninput .
Allwritetime-slotsmusthaveatleast1usbetweenbittransmissions
.
Thesubroutinebelow,writesaninstructionacrossthe1-wireinterface
: -
'Createaloopof8-bits(BYTE)
'Checkbit-0ofCMD
'Writea0-bit
'Sendalow for morethan60us
for a0-bit
'Releasedatapin(settoinput for high)
'Else
'Sendalow
for lessthan15us for a1-bit
'Delaylusat4mHz
'Releasethedatapin(settoinput for high)
'Useuptheremainingtimeslot
'Shifttothenextbit
'Closetheloop
Section-7 - 3
ExperimentingwiththePicBasicProCompiler
InterfacingtotheDS1820,1-wiretemperaturesensor
AlthoughthedatafromtheDS1820isintheformofa9-bitword,the
actualdatalengthsentis16-bits .Therefore,themastermustread 16-
bitsfromtheslave
(mostsignificantbitfirst) andconstructtheword
accordingtowhetheraoneorazerowasreceived .
ToReceiveabitfromtheslave,themastermustpulltheDQlinelowfor
aminimumof1us,thenreleasetheDQline,whichenables
receive
mode.TheDS1820 (whichisnowthetransmitter)pulls
theDQlinelow
forZERO,orhighforONEwithinatime-slotof15us
.Asthereadtime-
slotmustbeaminimumof60usinlength,therestofthetime-slotis
paddedoutwitha60usdelay .
Allreadtime-slotsmusthaveatleast1usbetweenbitreceptions .
DS_Read:
ForBitCnt=1to16 'Createaloopof16-bits(WORD)
Temp=Temp >>1

'Shiftdownbits
Temp.15=1

'Presetreadbitto1
LowDO

'Startthetimeslot
@
nop

'Delay1usat4mHz
DQDIR=1

'Releasedatapin(settoinputforhigh)
IfDQ=OThen

'Else
Temp.15=0

'Setthebitto0
Endif
Pauseus60

'Useuptheremainingtimeslot
Next

'Closetheloop
Return
TheaboveexplanationandcodeisbynomeansonlyfortheDS1820
device
.All1-wiredevicesoperateon asimilarprotocol.Onlythe
instructionsforthespecificdeviceusedwillbedifferent
.
Section-7 - 4
ExperimentingwiththePicBasicProCo
mpiler
MSB
0
=+24.5C
2"complimentformatfornegativetemperatures
MSB
1
=-24.5C
Figure7.1 .9-bitdataformat.
InterfacingtotheDS1820,1-wiretemperaturesensor
Measuringthetemperature.
ToreadthetemperaturefromasingleDS1820connectedtothebuswe
candispensewiththe64-bitromcode
.
Firstly,the1-wirebusisinitialised,thenaskiprominstruction
(CCh) is
transmitted,followedbyaconvertinstruction(44h) .
TheDS1820isagaininitialisedandanotherskiprominstructionissent,
followedbyareadscratchpadinstruction
(BEh). The16-bitsofdatamay
thenbereceivedfromtheDS1820
.
Weareonlyconcernedwiththefirst9-bitsofthe16-bitsreceivedfrom
theDS1820,therefore,thelast7-bitsmaybedisregarded
.
TheDS1820hasaresolutionof0
.5C;thisisrepresentedbytheLSB
(bit-0)
ofthe9-bits.A1signifiesa0
.5increment,whilea0signifiesan
integervalue.
Bits1to7arethetemperaturereading,bit-1canbenowthoughtofas
theLSBofthetemperaturevalue.
Bit-8isthesignbit,whenthisis1theresultisanegativetemperature
andthefirst8-bitsaretwo'scompliment
(1 becomesa0andvice-versa)
.
Figure7
.1,illustratestherelationshipofthe9-bitsofdataforbotha
positiveandnegativetemperature
.
Normalformatforpositivetemperatures
0 0 1 1 0 0 0
LSB
1
1
1 1 1
Section-7 - 5
LSB
1
0
ExperimentingwiththePicBasicProCompiler
InterfacingtotheDS1820,1-wiretemperaturesensor
Program DS1820 .BAS, displays,thetemperatureofasingleDS1820
connectedtoPortB .O .Figure7 .2showtheconnectionstothePIC .
Theprogramiscentredaroundthreesubroutines
;theseare DS_INIT,
DS-READ, andDS-WRITE.
Thefirsttobecalledis DS_INIT, thissubroutineinitialisesthe1-wirebus
andchecksforapresencefromtheDS1820
.Ifnodevicewasdetected
thentheflag, DS_VALID willreturnholding0,elseitwillreturnholding1
ifalliswell .
Fourinstructionsarethentransmittedbyusingthe DS-WRITE
subroutine .Theinstructiontosendisfirstloadedintothevariable
CMD.
Thesubroutinescansthe CMD variablebyexaminingbit-0,ifitisclear
thena0istransmittedonthebus,andifitissetthena1istransmitted .
CMDisthenshiftedrightoneplace,andthesameprocessiscarriedout
eighttimestotransmitthe8-bitbyte (leastsignificantbitfirst)
. Afterthe
fourinstructionshavebeentransmitted,thesubroutine DS-READ is
called
.Thisreadstheincomingbitstream (mostsignificantbitfirst) and
placesthemintothe16-bitvariable
TEMP. Thisisaccomplishedby
readingabitfromtheDS1820andplacingitintobit-15of
TEMP, the
variableTEMPisthenshiftedright1place.Ifthebitreadisa0thenbit-
15willbecleared,andifthebitreadisa1thenbit-15willbeset .Thisis
carriedout16timestobuildupthe16-bitresult
.
Wenowhaveour16-bitresultfromtheDS1820,however,weareonly
interestedinthefirst9-bits
.Firstly,bit-8isexamined,ifitisset(1)thena
negativetemperaturehasbeenmeasuredandtheflag
NEGATIVE isset
toindicatethisfact .Thisalsoindicatesthatthefirst8-bitsaretwo's
compliment.Therefore,thelowbyteofthevariable TEMP mustbe
XORedwith255,toconvertitbacktonormalformat (xoringwitha1has
theeffectofreversingthebit,1becomes0andvice-versa) .
Regardlesswhetherapositiveornegativeresultwasreceived,the
variable TEMP nowholdsthe7-bitsoftemperatureandthe0
.5C
increment (bit-0) .To convertthisintoaformatwecanuse,thelowbyteof
TEMPisshiftedright1placeandtheresultisplacedintothevariable
DEG,
thisnowholdsthecorrect7-bittemperaturereading (0-127) . In
ordertoplacethe0 .5increment,theresultheldin
DEGhastobescaled
upbyafactorof10 .Thiswillnowgiveusatemperaturevalueof
between0and1270.
Section-7- 6
ExperimentingwiththePicBasicProCompiler
InterfacingtotheDS1820,1-wiretemperaturesensor
Toincludethe0
.5incrementvalueinourfinalresult,weexaminebit-0of
TEMP
(theoriginalvaluewasnotalteredbyshiftingitright)
. Andmultiply
itsresultby5,ifbit-0wasclearthentheproductwillbe0(0*5),however,
ifthebitwassetthentheproductwillbe5
(1' ' 5) . Thisproductisthen
addedtothevalueheldinDEG
.
Uponthesubroutinesreturn,onevariableandaflaghavebeenloaded,
DEG, and
NEGATIVE.
Thiswillallowustodisplayaminussignifthe
temperatureisnegative,aswellasinformtheprogramastotheactual
temperature.
Todisplaytheminussign,theflag,
NEGATIVE isexamined,and
dependingonitsvalue,thevariable NEG_POS
isloadedwiththe
character, ` -` orspace.
Thefinaldisplayissplitintofourpartswithinthesamedebugcommand
.
Firstly,thevariableNEGPOSisdisplayed,thisholdaminussignora
space,dependingonthevalueof
NEGATIVE. Thenthevalueleftofthe
decimalpointisdisplayed,bydividingthevariable
DEG by10.Thevalue
totherightofthedecimalpointisdisplayedbycalculatingtheremainder
of DEG dividedby10
(/ / ) . Andfinallythedegreessignisdisplayed,this
wassetupatthebeginningoftheprogram
.
ToRBO
+5Volts
VDD
DDDS1820
GND
0
DS1820
iii
123
1. .GND
2. .VQ
3. .VDD
Figure7
.2.DS1820configuration .
Section-7 -7
ExperimentingwiththePicBasicProCompiler
Program -LM35.BAS
InterfacingwiththeLM35temperaturesensor
InterfacingtotheNationalSemiconductorsLM35istotallydifferentfrom
theDS1820,andissimplertouseinmanyrespects
.TheLM35was
designedwithanalogueinterfacinginmind,thereforeitoutputsavoltage
thatisproportionaltothetemperature (inC) in 10mVsteps
.For
example,iftheLM35'soutputvoltageis0
.22V,thenthetemperatureis
22C.ThemaximumtemperaturethattheLM35willmeasuresafelyis
125Cwhichwillproduceavoltageof1 .25V.
Program LM3587X.BAS
usesa16F876 (oranyotherpicwithanon-
boardADC)
todisplayatemperaturebetween0and125Cand its
correspondingvoltage,onaserialLCDconnectedtoPortC
.6.
TheADCINcommandissetup
(asdescribedintheanaloguetodigital
section) toconvertavoltagepresentedtoitsANOinput
(PortA.0) . The
temperatureisthendisplayedbymovingthedecimalpointoneplaceto
theright.
ADCON1=%10001110

'ConfigureforANOasanalogue
'inputwithrightjustifiedresult
Again:
ADCIN0,ADRes

'DotheADCconversion
Debugl,Line1,#(AD_Res/100)," . ,#(A5Result//100),4,"C"
'Displaythetemperature
Debugl,Line2,#(AD_Res/1000),
".", #(ADResult//lOOO), " Volts "
'Displaythevoltage
Pause200

' Asmalldelay
GotoAgain

'Doitforever
Figure7.3showstheconnectionstothePIC .
Figure7.3.LM35configuration.
Section-7-8
LM35
n
+5Volts
13
2
ToRAO
VDD
Vout
LM35
III
321
(ANO)
Ov
GND
1 . .GND
2 . .VOUT
3. .+VS
I
ExperimentingwiththePicBasicProCompiler
Program -MAX_TEMP.BAS
IfaPICisusedthatdoesnothaveanon-boardADC,suchasthe
PIC16F84,thenanexternaldevicemustbeemployed
.Thisisaperfect
applicationfortheextrasimpleMAX18712-bitADC
.Figure7 .4shows
thecircuitforsuchahook-up
.
LM35
RB2
To RB1
RBO
VDD
DOUT
C$

SHDN
SCLK
MAX187
VREF

AIN
VSS
VDD
VolLM35
GND
Figure7 .4
.LM35connectionstotheMAX187ADC.
Theprogram MAX
_TEMP.BAS isusedforthisdemonstration
.The
programsimplycallsthe
MAXINsubroutinetoacquireavoltagesample
fromtheMAX187 .
MAXIn:
Max_VaI=O
LowCs

'ActivatetheMAX187
ShiftinDout,Sclk,Msbpost,[MaxVall12]'Clockin12-bits
HighCs

'DeactivatetheMAX187
Return

'Exitthesubroutine
Theresultheldinthevariable MAX_VAL
isdividedby10toproducethe
degreesandtheremainderisalsodividedby10toproducethe
decigrees.
Debugl,Line2,dec2(MaxVal/i0), " ." , dec1(Ma)Val//10),4," C"
ThereisnoneedtoquantasizetheresultfromtheMAX187,asthe
voltagefromtheLM35willnotexceed1 .25V
.Whichistheequivalentto
125C.
Section-
7
-9
InterfacingwiththeLM35Temperaturesensor
ExperimentingwiththePicBasicProCompiler
Section-8
Experimenting
with
Robotics
Proximitydetectionprincipals .
Singledirectioninfraredproximitydetector
.
Infraredproximitydetectorwithdistancegauge
.
Directionalinfraredproximitydetector.
Ultrasonicproximitydetector
.
DrivingaDCmotorusinganH-Bridge .
DrivingaDCmotorusingtheL293D
.
ExperimentingwiththePicBasicProCompiler
Proximitydetectionprincipals
Detectingacollisiononarobotisnormallyaccomplishedbysensing
whenaswitchhasbeentriggeredbybumpingintosomething,however,
avoidingthecollisionaltogetherisamuchmoredesirablegoal .There
aretwomainwaysofprovidingproximitydetectionforthepurposeof
avoidingcollisions,thesearelightandsound
.Infraredlightand
ultrasonicsoundtobeexact
.
First,weshalllookattwopossiblewaysofusinginfraredlightasa
proximitydetector
.Thefirstisasingledirectiondevice,whilethesecond
isadirectionaldevice (left,right,andcentre) .
Proximitydetectionusinginfraredlightispossibleduetothefactthat
lightalwaystravelsinastraightline,andbouncesofjustabout
everything
(toagreaterorlesserextent) . Wecanusethisfacttoour
advantagebytransmittingapulseoflightthenlookingforitsreflection
.If
thereisnoreflectionthennothingmustbeinfrontofthedetector.
Weshallbeusingthesameinfrareddetectorthatwasusedinthe
remotecontrolsection,namelyanSFH506-38.Thisissensitiveto
infraredlightmodulatedat38kHz
.Aswiththeinfraredremotecontrol
experiments,modulatedlightisusedtoeliminateunwantedambient
light,causedbythesun,ormanmadesourcessuchasfluorescent
lighting
.Theinfraredsourcefortheseexperimentsisa5mminfrared
LED,againthesametypeusedintheinfraredremotecontrol
experiments.
Weshallalsolookatdetectionusingultrasonicsound .Aswithinfrared
light,ultrasoundisalsomodulatedbutthistimeat40kHzinanattemptto
eliminatebackgroundnoises .Butunlikelight,soundtravelsmuch
slower,therefore,wearealsoabletosensethedistancetotheobject
thathasbeendetected.
Section-8 -1
ExperimentingwiththePicBasicProCompiler
Program -IR_PROX.BAS
Singledirectioninfraredproximitydetector .
Figure8 .1showsthecircuitfortheinfraredproximitydetector (IRPD).
AlthoughthePICiscapableofsourcingcurrentsofupto20mA,asingle
transistorbufferwillincreasetherangeoftheIRPDtwo-fold .
Section-8 - 2
Green
LED
Figure8 .1 .Infraredproximitydetector .
ArequirementinthefinalproductisthattheLEDmustnotleakanylight
fromitssides,whichwouldtriggerthedetectorconstantly .Tohelp
alleviatethis,heatshrinksleevingisplacedovertheLEDwithonlythe
lensatthefrontleftclear,showninfigure8
.2
.
Figure8 .2 .HeatshrinksleevingovertheinfraredLED.
Anotherconsiderationwhenbuildingthefinalprojectisthepositioningof
thedetectorandLED.Theyshouldobviouslybepointinginthesame
direction,however,theLEDmustbeslightlyforwardofthedetectoror
thelightwillpenetratethroughthebackofit .Intheprototype, theIR
detectorwaspaintedblackonallsides,leaving onlythefrontlens
exposed .Figure8 .3showsthearrangementused .
+5Volts
R1
Infra-red
4.7k
14
LED
VDDRB7
Is
01
MCLR

RB6
RB5
BC549
4mHz RB4
Lo.
Infra-red
Crystal1e RB3
0SC1

RB2
_L
e
Vcc
sensor
I
0
RB1
RBO
Vout
e
Gnd
id1
PIC16F84
SFH506
RA4
z
10uf C3 C4
OSC2

RA3
i
C2
_
22pf 22pf
RA2
RAI
I,
VSSRAO
L7_
R2
1312
1
1
Ov
1 0 .1 afT T T
1 1
470
1VOlt
2.000
3 .Gnd
ExperimentingwiththePicBasicProCompiler
Singledirectioninfraredproximitydetector
Figure8 .3 .ArrangementofdetectorandLED
.
Program IR_PROX.BAS
usesthecircuitinfigure8 .1todetectanobject
upto24inchesinfront
.Ittransmitsapulseofmodulatedlightfor400us
thenwaitsforareflection .Inordertoeliminatefalse reflectionsthe
processiscarriedouttentimesandonlywhenten reflectionsare
receivedisthegreenLEDlit,whichindicatesthatanobjecthasbeen
positivelydetected .Theprogramisbasedaroundthe
PING subroutine,
thissendsoutthe38kHzmodulatedinfrared
light.Themethodfor
modulatingtheLEDisexplainedintheremotecontrolsection .
Afor-nextloopof10issetupandthe PING subroutineiscalled
.PortB.1
isthenexamined (lR detectoO, ifit'slowthenareflectionhasbeen
detectedandthevariableHITSisincremented .IfPortB.1 ishighthen
therehasbeennoreflectionandHITSisleftalone.
Afterthetentransmissionshavefinished,thevalueofHITSisexamined
.
IftenreflectionsweredetectedthevariableHITSwillholdthevalue10,
andthegreenLEDisilluminatedtosignifyapositivecontactinfront .
IfyoufindthattheIRPDisoversensitiveandisdetectingdistantobjects
ortheLEDisconstantlyilluminated,thefrequencyofthemodulationmay
beincreasedordecreased
.Thisisaccomplished byincreasingor
decreasingthenumberofNOP'sinthe PING subroutine.Removing
NOP'swillincreasethefrequencyofthemodulation,andaddingNOP's
willdecreasethefrequency .Thiswillhavetheeffectof loweringthe
sensitivityofthedetector .
Alternatively,theinfraredLEDmaybeattacheddirectlytothePIC, and
Q1maybediscarded .
Section-8 - 3
ExperimentingwiththePlcBasicProCompiler
Program -DIS_PROX.BAS
Infraredproximitydetectorwithdistancegauge
.
IfyoubuiltthesingledirectionIRPDyouwillhavenoticedthatatthe
peripheryofitsdetectionrangetheLEDflashes
.Thisisbecause the
furtherawaytheobjectisfromtheIRdetectorthelesslikelythat
10
reflectionswillbecounted .Wecanputthisobservationtogooduse.
Bycountinghowmanyreflectionshavebeenreceivedwecangetan
approximationofdistance
.Forexample,ifall10reflectionswere
receivedthentheobjectmustbeclosetothedetector,however,ifonly5
reflectionsofthepossible10weredetected,theobjectmustbealittle
furtheraway
.Forpracticaluse10samplesisnotenough,therefore,the
program DIS_PROX.BAS takes30samplesandincrementsthevariable
HITSwhenareflectionisdetected .
IfHITShasthevalueof10,thenonly10reflectionsweredetectedfrom
30samplestaken,whichisjustontheperipheryoftheIRPD'slimit
.The
greenLEDisilluminatedtoindicateadistantobjectwasdetected .
If HITS hasthevalueof20fromapossible30samplestaken,thenthe
objectmustbealittlecloserandtheyellowLEDisilluminated .
IfHITShasthevalueof30fromapossible30samples,thentheobject
mustbeclosetothedetector,andtheredLEDisilluminated
.
Figure8 .4showsthecircuitlayoutforthismethod .
+5Volts
Ov
R1
4 .7k
a
VDDRB7
MCLRRB6
RB5
RB4
RB3
OSC1 RB2
11131
RBO
n
13
i
9
e
e
Section-8 - 4
Infra-red
LED
G1
BC549
PIC16F84
RA4 -
OSC2

RA3
-
C3

C4
22pf 22pf

RA1 '-
VSS
RAO
'-'
R2

R3

R4
i6
470

470

470
1
GreenYellow Red
LED

LED

LED
Figure8 .4 .IRPDwithdistancegauge .
Infre-red
sensor
vcc
Vout
2nd'
SFH5O6
1 31
2
h
x .266
3 .2nd
ExperimentingwiththePicBasicProCompiler
Program - LR_PROX.BAS
Directionalinfraredproximitydetector
.
TheDirectionalIRPDusesthesamemethodastheprevious
experiments,transmittingapulseoflightanddetectingareflection
.
However,itiscapableofdeterminingwhetheranobjectistotheleft,
right,orcentre .
TwoinfraredLEDsareplacedeithersideoftheinfrareddetector,
pointingawayfromitatanangleofapprox30to45degrees
.Figure8.4
showsthearrangement
.
R1
4.7k
e
4mHz
Crystal
IB
C7
u
10u1 C3 C4
C2
.

2pf 22pf
0.1ufT TT
OV
Figure8.4.LEDanddetectorarrangementfordirectionalIRPD
.
EachinfraredLEDispulsedinturnandareflectionisdetected
.Ifa
reflectionisdetectedwhentheleftLEDwaspulsedthenanobjectisto
theleft
.IfareflectionisdetectedwhentherightLEDwaspulsedthenan
objectistotheright
.However,ifareflectionwasdetectedforbothleft
andrightthentheobjectmustbeinfront
.Figure8
.5showsthecircuitfor
thedirectionalIRPD .
r5Volts
I
BC540
,oBC549
9
B
t
8
R3
470
Ill
Z
/44
R4
470
2
i
3
LeftCentreRight
Figure8.5
.DirectionalIRPD.
LEDLED LED
Section-8 - 5
Right
infrared
LED
Infra-red
aensor
SFH506
n
1.Vnu1
2.VCc
3 .Ond
ExperimentingwiththePicBasicProCompiler
Directionalinfraredproximitydetector
Theprogram LR_PROX.BAS
usesthesamemethodasthelasttwo
experiments
.However,therearenowtwoinfraredpulsingsubroutines,
onefortheleftLED,
PINGLEFT, andonefortheright, PING-RIGHT
.
EachLEDispulsedtentimesbycallingeach
PING subroutineinturn
andtheamountofreflectionsfromeachareplacedinthevariables
HITSLEFT, and HITS-RIGHT
.
Thetwovariablesarethenexamined,iftheyarebothgreaterthanseven
thenbothLEDsproducedareflection7ormoretimes,which
means
theremustbeanobjectinfrontofbothofthem
.Sotheleftandright
LEDsareextinguishedandthecentreledisilluminated .
Next,thevariable HITSLEFT isexamined
;ifthisholdsavalueoften
thentheleftLEDproducedareflection10timesoutof10
.Whichmeans
theremustbeanobjecttotheleftofthedetector
.Sotherightandcentre
LEDsareextinguishedandtheleftledisilluminated
.
Finallythevariable HITS-RIGHT
isexamined,ifthisholdsavalueoften
thentherightLEDproducedareflection10timesoutof
10 .Which
meanstheremustbeanobjecttotherightofthedetector
.Sotheleft
andcentreLEDsareextinguishedandtherightledisilluminated
.
TheplacementoftheLEDsisevenmorecriticalinthisapplication
as
therearenowtwoinfraredlightsources
.Caremustbetakentoensure
thatnolightleaksfromeitherLED,allthelightshould
bedirected
forwards.
IfyoufindtheLEDisconstantlyilluminated,
thefrequencyofthe
modulationmaybeincreasedordecreased
.Thisisaccomplished by
increasingordecreasingthenumberofNOP'sinthePINGsubroutines
.
RemovingNOP'swillincreasethefrequencyofthemodulation,
and
addingNOP'swilldecreasethefrequency
.Thiswillhavetheeffect of
loweringthesensitivityofthedetector.
Alternatively,theinfraredLEDmaybeattacheddirectlytothePIC,
and
Q1andQ2maybediscarded .
Section-8- 6
ExperimentingwiththePIcBasicProCompiler
Program
-SONPROX.BAS
Ultrasonicproximitydetector.
Usingultrasonicsoundinsteadofinfraredlightforproximitydetection
is
thesameinmanyrespects
.However,assoundtravelsmuch slower
thanlight (approximately0 .3m/msor1ft/ms,and0
.3m/nsorift/ns
respectively),
wecanusamethodcalled timeof
flight(TOF) tojudgethe
distanceofanobjectaswellasdetectitspresence .Timeofflightisthe
timetakenfromthetransmittersendingitspingtothereceiverdetecting
theecho.
Tosendandreceivetheultrasonicsignalsweusetwotransducers,the
transmittransducer (TX)
isaformofspeakerwhoseresonantfrequency
is40kHz .Thereceivingtransducer (RX)
isaformofmicrophonewiththe
sameresonantfrequency .Modulatingthefrequencyofthe
soundat
40kHzhasthesameeffectasmodulatingtheinfraredsignals,
thatof
ambientnoiseelimination (almost)
.
Figure8 .7showsthecircuitfortheultrasonicproximitydetector
. Unlike
theinfraredexperiments,thereisnoready-madedetectorforsoundthat
willconvertitssignalintoaTTLvoltage
.Thishastobeaccomplishedby
anamplifier,anop-ampinthiscase .
TheTXtransducerisconnectedtoPortA.0andPortA.1ofthePIC,This
actsasaformofpush-pulldrive,onepinalternatesfromhightolow,
whiletheotherpinalternatesfromlowtohigh
.Thismethodachieves
greaterdrivetothetransducer.Anyobjectinthepathofthesignalwill
causeareflection
.Thereflected signalisatasignificantlylower
amplitudecomparedtotheoriginaltransmittedsignal,thereforeweneed
toamplifyitbyapproximately100times,thisissetbyR4andR5ofthe
op-ampIC1
.CapacitorR7feedsatransistor (Q1), whosepurposeisto
provideTTLlevelpulsestothePIC
.VR1andR6adjustthebiasonthe
baseofQ1,whichdeterminestheoverallsensitivityofthecircuit
. The
transistor'snormalstateishigh(5V)butispulledlowwhenasuitably
strongechohasbeendetected
.
Initially,thebiaslevelonthebaseofQ1shouldbeadjustedto0
.4V .This
willgiveusasensitivityofapproximatelytwofeet .Anymoresensitive
andwewillincreasethechanceofdetectingstrayreflections .
Reducingthebiaslevelwilldecreasethesensitivityofthecircuit
.
Section-8 - 7
ExperimentingwiththePicBasicProCompiler
Ultrasonicproximitydetector
Theprogram SON_PROX
.BAStransmitsapulseof40kHzmodulated
soundforadurationof600ususingthePING
subroutine.Asthe
transducerhastobeswitchedfromhightolowextremelyrapidlyforthe
push-pulleffecttowork,assemblycodehas
hadtobeused .The
principalsofthissubroutineareverysimilartotheinfraredremotecontrol
experiments.
Afterthe
PING subroutinehassentoutitspulse,wemustlookforan
echoonPortA.2
.IfweweretoexaminePortA.2 andcontinuewiththe
code,wewouldmissthesignal,asitwouldn'thavereachedthereceiver
yet
.Remember,soundtravelsalotslowerthanlight
.Wemusttherefore
givethereceivertimetodetecttheecho .
Thisisaccomplishedbycreatingaloopcountingupto2 55
; withinthis
loopwecontinuallyexaminePortA
.2 foralow,whichwillsignifythatan
echohasbeenheard .Ifanechohasbeenheardtheloopisexited,and
thevalueoftheloopvariable
(E TIME) nowcontainsanumber
representingadistance,thefurtherawaytheobject,thecloseritwillbe
to2 55
.Ifanechowasnotheardthentheloopexitsnormallyandthe
E-TIME
variableiscleared .
Thishasgivenusameansofdetectingandgaugingthedistanceofan
object,however,totryandeliminatefalsereflectionsweusethesame
principalthatwasusedintheinfraredproximitydetectors .
Wesample
theincomingechotentimesandeachtimeanechoisheardthevariable
HITSisincremented
.If,attheendoftensamplesHITScontainsthe
value10,therehasbeenapositivecontactwithanobject,andthegreen
LEDisilluminated
.AserialLCDconnectedtoPortB.0displaysthe
variableETIME,
whichisarepresentationofthedistance .
Eachtimethetransmittersendsoutaping,
thereceiverphysically
vibrates (rings)
insympathy .Thisringingcancausethe receiving
softwaretoseeafalsereflectionimmediatelyaftertheping
.Inorderto
combatthisproblemthereceivertransducermustbepadded
.Thiswas
accomplishedintheprototypebyplacingastripoffeltaroundthebody
ofthetransducer,andalsoonthebottomwheretheconnectingwires
protrude.Figure8 .6illustratesthis .
Section- 8 -8
ExperimentingwiththePicBasicProCompiler
3
7
Q
Figure8.6.Positioningandcushioningofthetransducers .
U
o
V
o~,
in
J I M
7 Va
I ~

N~y
CJ

b0
O

y
s>

>

Section-8 -9
101
xY
Figure8.7.Ultrasonicproximitydetector.
M !g
Ultrasonicproximitydetector
ExperimentingwiththePicBasicProCompile r
Program -
H_BRIDGE.BAS
DrivingaDCmotorusinganH-Bridge .
Forthisexperiment,themotorusedwastheDCtypesuppliedwiththe
LEGOROBOTICSSYSTEM.Theseare9Vtypes,whichdrawafew
hundredmilliAmps.However,anytypeofmotormaybeusedaslongas
thevoltageandcurrenthandlinglimitsofthecircuitsormotorsarenot
exceeded.
Tocontrolthedirectionofamotorwithlogiclevelspresentedfromthe
PIC,weuseanH-bridgecircuit
.Figure8 .8showsatypicallayout . It' s
calledanH-bridge,becauseitresemblestheletterHinitsconfiguration
.
+9volts
03

04
R3TIP32

TIP32
R4
27

27
R1

R2
1K

1K
D1
..41N4001
Figure8 .8
.DiscreteH-Bridge .
Thecircuitisconfiguredinsuchawaythatonlytwotransistors
are
conductingatanyonetime
.WhentransistorsQ3andQ6areon,the
motorspinsinonedirection
.WhentransistorsQ4andQ5areon,the
motorspinsintheoppositedirection
.Whenallthetransistorsareoffthen
themotorremainsmotionless .TransistorsQ1andQ2actasbuffersto
thePIC,thereforeallowingasmallcurrenttocontrolfourlargercurrent
transistors.D1toD4are
flyback suppression diodesandareinplaceto
protectthetransistorsfromanyhighvoltagespikes
createdbythe
motor' swindings.
Q3toQ6shouldbechosentosuitthemotorused,inthiscaseTIPSare
morethanadequate.Ifalargermotorisusedthentransistorswith
a
largercurrentcapabilitymustbeused .
TocontrolthedirectionofthemotortwopinsarerequiredfromthePIC
.
TheseconnecttoAandBoftheH-bridge .Wheneitheroneofthese
linesisbroughthighwhiletheotherispulled lowthenadifferent
directionischosen
.Ifbotharepulledlowthenthemotorremainsstill .
Section-8 -10
ExperimentingwiththePicBasicProCompiler
DrivingaDCmotorusinganH-Bridge
Thedirectionofthemotordependsonwhichwayitisinsertedintothe
circuit.ConnectingitspositiveterminaltoQ4andQ6willhaveadifferent
directionthanconnectingittoQ3andQ5 .
Note
.LinesAandBshouldneverbebothbroughthighforanylengthof
time,asthiswillturnonallfourtransistors,resultinginanearshort
circuit.However,wecanusethistoouradvantage,whena
motor's
terminalsareshortedtogetherthemotor'sshaftishardtoturnbyhand .
UsingthisprincipalwecansetLinesAandBoftheH-bridgehighfora
fewmilliseconds(ms)toactlikeabrakeandstopthemotorinitstracks,
insteadofjustslowingtoastop .
Program
H_BRIDGE.BAS demonstratesthesimplicityofcontrollingthe
H-bridgecircuitoffigure8 .8
.Line-AoftheH-bridge isconnectedto
PortB.OofthePIC,andLine-BisconnectedtoPortB
.1 .Theprogram
cyclesthrough,turningthemotorfirstonewayandstoppingthenturning
itintheoppositedirection .Thedirectionitshouldbeturningisdisplayed
onaserialLCDconnectedtoPortA .O .
Todemonstratethebrakingmethod,subroutine BRAKE iscalledjust
beforeastop
.ThisbringsbothLineAandBhighfor1 00ms,justenough
timeforthebrakingeffecttoworkbutnotenoughtimeforanydamageto
becausedtothetransistors.
Whencontrollingmotors,orindeedanyheavyload .Alargecapacitor
shouldbeplacedacrossthePIC'ssupplylines
.A3300uFisnormally
sufficient.Thishelpsmoothoutanyspikescausedbythemotorbeing
initiallyactivated.
Section-8 -1 1
ExperimentingwiththePicBasicProCompiler
Program -
L293D.BAS
DrivingaDCmotorusingtheL293D
.
TheSGS-ThompsonL293Distherobotenthusiastsfavouritemotor
driver
.Thedevicecontainsfourpushpulldriversaswellastheirflyback
protectiondiodes
.Eachdriveriscapableofproducing600mAcontinuous
outputcurrent
.
Figure8
.9showstheinternalconfigurationofoneofthesedevices .
INI
EN1
VS
OUT, OUTS
h Mh,
W

1-1 9
IN2
iGu

IN4
OUT!
Figure8
.9.L293Dinternals.
ThemostcommonconfigurationfortheL293DisastwoseparateH-
bridges
.ThisallowsthedevicetosupplyuptolAmptothemotor
.If
suchhighcurrentsarebeingimplementedaheatsinkmustbeused
.
Figure8 .10showsanL293DbeingusedintheH-bridgeconfiguration
.
TheIN1andIN2pinsactliketheAandBlinesofthediscreteH-bridge
.
TheEN1pinisanenableline,whenthisispulledlowtheoutputvoltage
tothemotorisdisengaged .
Toallowthedevicetobecontrolledbylowvoltage
(TTL) levels,a
separatelogicvoltagemaybeappliedtotheVSSpin
.Whilethemotor's
supplyvoltage,whichisusuallyalothigher,isconnectedtotheVSpin
.
Section-8-1 2
INS
EN2
IN1
IN2 MotorDirection
1
0 Forward
0
1 Reverse
0 0
Stopped (Brakeappliedtomotor)
1 1
Stopped(shouldbeavoided)
ExperimentingwiththePicBasicProCompiler
DrivingaDCmotorusingtheL293D
Figure8 .10 .L293DH-Bridgemotorcontrol
.
Program L293D
.BAS demonstratescontroloftheL293D.Theprogram
cyclesthrough,turningthemotorfirstonewayandstoppingthenturning
itintheoppositedirection .Thedirectionitshouldbeturningisdisplayed
onaserialLCDconnectedtoPortA
.0 .
Thedatasheetsforallthepartsusedinthissectioncanbefoundonthe
accompanyingCDROM.
Section-8- 1 3
+5Volts
R1
4.7k
1
VDD
RB7
13 +9Volts
MCLR

RB6
L2.
RB5
I
10
4mHz
Crystal
16
RB4
RB3
B
e
z
vS

VSS
0SC1

RB2
I NI

OUT1
1
RB1
HBO
B

i
EN1
I N2

OUT2
Motor
C1 0
PI C16F84
2200uf
RA4 L293D
0
OSC2

RA3
z
OUT3
C3 C4
RA2
0
I N3
C2 -
22pf 22pf
RA1
vss RAO
13
n 1s
EN2
I N4 OUT4
14
Ov
.
uT
j01t
T T
GND
i4 .8 .12.1
ExperimentingwiththePicBasicProCompiler
Section-9
Experimenting
with
AudioControl
Devices
AddingavoicetothePICwiththeISD1416 .
Recordingandplayingbackmultiplemessages.
AllowingthePICtoaudiblycount.
DigitalvolumecontrolusingtheAD840X.
Controllingthegainofanop-amp.
Digitalactivebassandtreblecontrols .
ExperimentingwiththePicBasicProCompiler
AddingavoicetothePICwiththeISD1416
.
Imaginehavingyourlatestdigitalthermometertellyouthetemperature,
ortherobotyouhavejustbuiltactuallytellyouthatitneedsitsbattery
recharged . Andwhat'smore,itcantelltoyouinyourownvoice!
ThisisallpossiblethankstoanewseriesofdevicesfromISD ;called
Chipcorders. A
rangeofdevicesareavailablethatallowmorethan20
secondsofspeechtoberecordedontothechip,andplayedback
complete,orseveralsmallermessagesmayberecordedandselectively
playedback
. ThedeviceweshallbeusingistheISD1416,whichwill
allowacompletemessageof16secondsorseveralsmallermessages .
TheISD1416mayalsobeusedasastand-aloneprojectforuseasa
memopad
. Figure9 . 1showsthecircuitforjustthistypeofoperation .
. 5volts
II
f
AOVCCDVCCARECANAANA
A1
A2
A3
A4
A5
A6
. .
A7
ISD1416
LEDINOUT
SPKR+
SPKR-
MICREF
PLAYL
PLAYE
RECAGC
VSSDVSSAXCLK
MIC

S2
z o
A5
4 . 7k
n
SPKR
16ohmS
e
C4
. 1of
R6
10k
0v
PlaybackPlaybackRecord
part

lull
messagemessage
Figure9 . 1 . ISD1416memopad.
Inthecircuitabove,arecordingismadebypressingS3
. TheLEDwill
illuminatetoindicaterecordmodeisoperational . Whenthemessageis
complete
;releasingS1willdisengagerecordmode . Tolistentothe
messageS1orS2maybeused
. S1willplaythemessageaslongasit
remainspressed . S3willplaythemessagetoitscompletionwitha
momentarypressandpulsetheLEDwhenitisfinished .
Section- 9 -1
ExperimentingwiththePicBasicProCompiler
/
/I
s
e
B
10
i
AddingavoicetothePICwiththeISD1416
Oncethemessageisrecodedontothechipitwillremain,evenwhenthe
powerisremoved
.Accordingtothedatasheetitwillstayrecordedfor
100years. (howdotheyknow?) .
Wecanuseasinglemessageasan
audioindicatororwarningbyapplyingapulsetothePLAYEpininstead
ofusingapushswitch
.Thepulsemusthaveahightolowtransitionfor
theISDtodetectit
.Thisiseasilyaccomplishedbythelinesofcode
below: -
PLAYSPIN

VarPortA .0
HighPLAYSPIN

` Setthelineinitiallytohigh
Nop

` A1usdelay
LowPLAYE_PIN

` Bringthelinelow
Recordingandplayingbackmultiplemessages
.
Torecordandplaybackmultiplemessages
;theaddresslinesoftheISD
mustbeused
(A0 . .A7) . Figure9
.2showstheconnectionofaDILswitch,
whichwillallowdifferentportionsoftheISD'snon- volatileRAMtobe
accessed
.Therestofthecircuitisidenticaltofigure9 .1 .
+5volts
All
47k
AO
A1
A2
A3
A4
A5
A6
A7
Section- 9 -
2
ISD1416
Ov
6way
DIL
switch
Figure9 .2
.DILswitchconnection.
TheRAMwithintheISDdevicemaybethoughtofasapieceof
audiotape,changingthevalueappliedtotheaddresslinesA0 .
.A7is
likenedtoplacingtheaudioheadanywhereonthetape
.Placingthe
binaryvalue%0ontheaddresslinesmaybethoughtofasplacingthe
audioheadatthebeginningofthetape
.The16secondsofrecording
timemaybesplitinto160segments
;eachsegmentis100msinlength
.
Thisislikemovingtheheadeveryfewinchesalongthetape
.This
meansthatthevalueplacedontheaddresslineshasarangeof0to
160 .
ExperimentingwiththePicBasicProCompiler
Address
00000000
Address
00101000
On Of t
IERZ-3
CzM
Elm
Address
01010000
Section-9 - 3
AddingavoicetothePICwiththeISD1416
AddresslinesA6andA7haveadualpurpose .Whentheyare
both
broughthighthenasystemnamed
operationalmode isenabled,which
allowsloopingof themessageaswellasseveral
otherf unctions.
Operationalmodehasnorelevancetoourdesign,theref ore,wewillnot
discussit
.If youwishtof indmoreaboutoperationalmode,thereare
verycomprehensivedatasheetsontheaccompanyingCDROMf ormost
of theISDrangeof devices .
Aslongasanaddressabove160isnotchosen,operationalmodewill
notbeenabled.
Wewillnowlookatamethodof recordingandplaying
backf our
separatemessages
.Eachmessagewillhaveamaximumlengthof f our
seconds
.Thisdoesn'tseemalot,butyouwillbesurprisedathowmuch
canbesaidinsuchasmallamountof time
.
Torecordthef irstmessage,avalueof 0mustbeplacedontheaddress
lines.TheDILswitchshouldbesetupasinf igure9
.3a.Nowpressthe
recordbutton(S1)untilthemessageisspoken
.Pressingtheplaybutton
willplaybackthef reshlyrecitedmessage
.Eachconsecutivemessage
musthavetheDILswitchpositionedaccordingtotheremainingthree
settingsof f igure9 .3
.Toplaybackeachmessagethesamevaluemust
beplacedontheaddresslines .
Address
01111000
AO
A7
Message1

Message2

Message3

Message4
a

d
Figure9.3
.DILswitchconf igurationf ormessages .
Nowthatwehaveourf ourdistinctmessagesrecorded
ataddresss
%00000000 (0), %00101000
(40),%01010000(80),and%01111000
(120) theISDchipmaybehookeduptothePIC
.Thisisasimplerlayout
thantherecordingversionasthemicrophonesectionisnotrequired
.
Figure9
.4showsthecircuitf orthis .
ExperimentingwiththePicBasicPro Compiler
Program -4_MESGE.BAS
+5Volts
R2&3
47k
u
VDD
RB7 e
4 MCLR

RB6
2
RB5
Hz

R84
tai

RB3
OSCI

RB2
RBI
RBo
PIC16F84
RA4
C4
OSC2

RA3
RA2
22p1

RA1
vss RAO
e
z
IB
n
2
2
2e
lie
a 16ohm
VCCA

VCCD

Speaker
R1
4.7k
4m
Crys
C2 -
'T T T
To
p

SerialLCD
Section-9 -4
Addingavoicetothe PICwiththeISD1416
26
SPKR+
A7
AS

SPKR-
A5
A4
A3

ANAIN
A2
A1

ANAOUT
A
ISD1416
RZ.~

MICREF
PLAYL
PLAYS

MIC
RECLED
XCLK

AGC
VSSD

VSSA
pI
a
e
9
Figure9.4.ISD1416connectionstothePIC
.
Program 4_MESGE.BAS
demonstratesplayingbackthefourmessages
thathavebeenrecorded
.ThePLAYS lineisnotusedinthis
demonstrationtherefore
;itisdisconnectedbymakingPortA
.2an input
allowingR3tokeepsitpulledhigh
.Theprogramitselfisveryprimitive,
allitdoesisloadthecorrespondingmessageaddress'sontoPortBand
calltheSAYITsubroutine .
TheSAYITsubroutinewaits50msbeforeenablingtheISDchip
.This
givesittimetoprocessthecontentsontheaddressline
.ThePLAYLline
isthenheldhighandadelayof1usisimplementedbeforethelineis
pulledlow
.ThiswilltriggertheISDintoplaying
thecorresponding
message
.Toestablishwhenthemessagehasfinished,theREC_LED
lineispolled
.Thispulseslowwhenthemessagehasended.
ThedelayswerefoundnecessaryinorderfortheISDchiptoplaythe
propermessageandwerefoundbytrialanderror,smallerdelaysmay
workjustaswell.
Ifmoremessagesarerequiredthenthesamemethodapplies
.However,
themessagelengthswillneedtobesmaller .
ExperimentingwiththePicBasicProCompiler
Program -
SAYCOUNT.BAS

AddingavoicetothePICwiththeISD1416
AllowingthePICtoaudiblycount
WecangoonefurtherandmaketheISDchipspeaknumbersoreven
count.First,wemustrecordmultipleseparatemessages
.Thesewillbe
thedigits0to9andalsotheword'point'
.Ifthisprogramistobeusedfor
adigitalthermometerthentheword`degrees'mustbealsoberecorded
.
Asanexamplewewillassumeatalkingdigitalthermometeris
being
implemented .Therefore,12messagesneedtoberecorded
.Firstwe
mustcalculatethelengthofeachmessage
.Thisisaccomplished by
dividingthemaximumlength (inseconds)
thatthechipwillallow (16 in
ourcase) bythenumberofmessagesrequired : -
16112=1.3
Thisgivesusalengthof1 .3secondspermessage
.Toconfigurethisas
anaddresstopresenttotheISDchip,simplymultiplythelengthofthe
messagebyten,whichwillgiveus13
.Theneachmessage'saddressis
amultipleofthisnumberplus1 . i.e.
Messageoneaddress=0
Messagetwoaddress=
14 (whichisequalto(0+ 13)+1
Messagethreeaddress= 28
(whichisequalto (14+13)+1
Messagefouraddress= 42

(whichisequalto
(28+13)+1
Thevalueoneneedstobeaddedtothemessageaddresstoavoidthe
endofmessagemarkerthattheISDchipplaces
(notsurprisingly) atthe
endofeachmessage
.Whentheendofmessagemarkerisreached,the
RECLEDlineispulsedlow
.Withoutthispulse,thePICwillkeepon
pollingforitandbecomestuckinanendlessloop
.
Table9
.1showsthevaluestoplaceontheaddresslinesforeachofthe
twelvemessagesrequiredforadigitalthermometerexample . Orany
programthatrequires12messagestobespoken
.
Section-9 - 5
ExperimentingwiththePicBasicProCompiler
AddingavoicetothePICwiththeISD1416
Table9 . 1
. Addressvaluesforthedemonstrationprogram
.
Usingthe12messagesthathavebeenpreviouslyrecorded
;theISDchip
isnowabletospeakanydigitfrom0to9
. Withtheabilitytospeakthe
digits
;thenextstepwastobuildupthedigitsintoacountingprogram
.
Program ISD
CNT. BAS doesjustthat.
Itiscentredaroundthe
subroutineSAYIT,whichtakesthe16-bitvalueheldin
S_NUMand
speakstheindividualdigitsofthatvalue
.
The SAYIT
subroutineworkslikethis
. Aloopiscreatedtoextractthe
individualdigitsfromthe16-bitvalue
;usingtheDIGoperand . The
variable
SNnowholdstheindividualdigit
. Wedonotwishtohearthe
leadingzeroesofeachnumberbeingspoken,thereforeleading
zero
suppressionisaccomplishedbyagroupof
if-then. Alookuptableis
thenusedtoextracttheaddressforthespecificnumbertobespoken
.
AndthisvalueisplacedontoPortB
. The PLAY subroutineisthancalled
whichtriggerstheISD1416
.
Asademonstrationofthecapabilitiesofthisprogramthewords'POINT'
and`DEGREES'arealsospoken
. Theword'POINT' isspokenby
placingtheaddressforthe11
th
messageontoPortBandcallingthe
PLAY subroutine
. Theword`DEGREES'isspokeninasimilarmanner,
excepttheaddressforthe12 th
messageisplacedontoPortBbeforethe
PLAY
subroutineiscalled.
Section-9- 6
MessageNo#
MessageSpoken
Addressofmessage Dec
1
ZERO 00000000
0
2
ONE 00001110
14
3
TWO 00011100
28
4 THREE
00101010
42
5 FOUR
00111000 56
6 FIVE
01000110 70
7 SIX
01010100 84
8 SEVEN
01100010 98
9
EIGHT
01110000 112
10
NINE
01111110 126
11
POINT
10001100 140
12
DEGREES 10011010
154
ExperimentingwiththePicBasicProCompiler
Program - DIGVOL.BAS
0
C1
lout
DigitalVolumecontrolusingtheAD840X
Digitalvariableresistorswerecoveredindetailinthedigitaltoanalogue
section.However,theyaresoversatileandcapableofextremely low
noiseoperationthatitwasinevitablethattheywouldbeused inaudio
equipment.Figure9 .5showsoneoftheobviousapplicationsforadigital
resistor,thatofavolumecontrol .
Regulated5Volts
R1
4 .7k
0
0
C3

C4
C2
.
_56pf 56pf
Va"u"TTT
VDD
RB7
MCLR RB6
RB5
R84
RB3
OSC1 RB2
RB1
RBO
PIC16F84
RA4
OSC2 RA3
RA2
RAI
VSS
RAO
To
SerialLCDo
z
i
9
e
6
0
z
2-
Section-9 - 7
DigitalvolumecontrolusingtheAD84OX
R2
10k
s
5
C9
SDI
CLK
Figure9.5 .Digitalvolumecontrol .
Program AD8400.BASusesthecircuitinfigure9 .5 .TheAlpinofan
AD8400maybeconnectedtotheinputofanamplifierandtheW1
pin
maybeconnecteddirectlytoamicrophoneortheoutputfromapre-amp .
SW1controlsVolumeup,andSW2controlsVolumedown,SW3stores
thecurrentvolumelevelinthePIC'sinternaleeprom.The programs
mainsubroutinecalled
POTOUT, controlstheAD8400viaits3-wire
interface.Insteadofselecting aspecificresistancetooutput, the
subroutinecalculatesthepercentageoftheresistance .Thisisnecessary
becauseofthedifferentresistancetypesavailable ( i.e. Jka2,
10k2,
50ksa
and100kb . Thereisnorealneedtoknowthespecificresistance,aswe
knowthat%90ofa50kQresistanceis45kQ,and%90ofa 1Oks2
resistanceis9kQ.
VDD
W1
131
AD8400
GND
z
iAt 80Output
-0Input
ExperimentingwiththePicBasicProCompiler
Program -AD8400.8AS

UsingtheAD8400digitalpotentiometer
Weknowthatthedigitalpotshavearesolutionof256
(0-255) .
Soto
calculatethepercentagewejustdivideby100
.Howeverwiththe
limitationsofthemathroutinesinthecompiler,thevalueshadtobe
scaledupandthendownagain
.L ikethis: -
POutput=(Percent*255)/100
Thevariable PERCENT
holdsavalue (notsurprisingly)
between0to
100
.Thevariable POUTPUT
holdsthedatabytetobesenttotheDCP
.
WhenusingtheAD8400,theaddressbits
(bit-8andbit-9)
mustboth
containzeroes
.Thisisachievedbysimplyclearingbothbits
: -
P_Output.8=0
POutput.9=0
TheAD8400isenabledbybringingtheCSlinelowandthe10-bitword
isshiftedout,withtheMostSignificantBitsentfirst
: -
SHIFTOUTSDI,CL K,Msbfirst,[POutput110]
TheCSlineisbroughthightodisablethechip,andthesubroutineis
exited.
Section-9 -
8
ExperimentingwiththePicBasicProCompiler
Program -AD8400.BAS
TheseconddemonstrationusingtheAD8400,showninfigure9 .6 .Uses
thetwoterminalorREOSTATmode,thegainofaninvertedop-amp
amplifieriscontrolledbytheDCP.Thedigitalpotisconnectedbetween
theinvertinginputandtheoutputoftheop-amp
.A1OkQpartwasusedin
thisdemonstrationbuthighergainscouldbeachievedbyusinga100kQ
part.WhentheDCPisat%0(50Q)thereislessthanunitygain,when
theDCPisat%10(1kQ)thereisunitygainandwhentheDCPisat
%100(10k52)thereisagainof10.The3-wireinterfaceconnectstothe
PICasinfigure9 .5 .SwitchesSW1andSW2controlthegain, SW3
storesthecurrentgainlevelinthePIC'sinternaleeprom .
TheProgramforthisdemonstrationis AD8400.BAS.
+5Volts
Figure9 .6
.Op-ampgaincontrol .
Theversatilityofthesedevicesisneverending,virtuallyanything that
usesamechanicalpotentiometercanbecontrolledwithoneofthese
remarkableIC's.
Section-9 -9
UsingtheAD8400digitalpotentiometer
Controllingthegainofanop-amp
ExperimentingwiththePicBasicProCompiler
Program -AD8402.BAS UsingtheAD8402dualdigitalpotentiometer
Digitalactivebassandtreblecontrols
Figure9 .8illustratestheuseofthedualdigitalpot(AD8402)asamono
bassandtreblecontroller
.Thecircuitlooksmorecomplicated thanit
actually is, figure9 .7showsasimplifiedlay outofthesamecircuit
.
Treble
Figure9 .7 .Simplifiedbassandtreble.
It'saconventionaltonecontrolfoundinmostaudioamplifiers, only one
channelisshown.IfstereooperationisrequiredanAD8403willhaveto
beusedasitcontainsfourRDAC's .
Thebassisadjustedby RDAC1 (Al, Bi, and W1), whilethetrebleis
adjustedby RDAC2(A2, 82, and W2) . Thefourswitches (SW1 . .4)
attachedtothelower4-bitsofPortBcontrolbassupordown, andtreble
upordown, andaredisplay edonaserialLCDattachedtoPortB .7 .
Switches1and2controlBasswhileSwitches3and4controlTreble
.
Program AD8402
.BAS isforusewithfigure9.8.Itiscentredaroundthe
subroutine POTOUT, thissubroutineoutputsthe10-bitwordtoan
AD8400, AD8402, orAD8403digitalpot .TheinternalRDACofchoice
(i..4) isloadedintothevariableRDAC, andthepercentage ofthe
resistanceisloadedintothevariable
PERCENT. Forexample, ifthe
bass, whichiscontrolledby RDAC1istobeincreasedto%90, variable
RDACisloadedwith1, and PERCENT isloadedwith90thenthe
POTOUT
subroutineiscalled: -
RDAC=1

`PointtoRDAC1
PERCENT=90

'%90oftheRDAC'sresistance
GosubPOTOUT

'ShiftoutPERCENTtoRDAC1
Section-9- 1 0
ExperimentingwiththePicBasicProCompiler
0
3
0

0I

0
-n

<
D
S~D7J31~~7J]7~7]D mD
oAw
D
w
D
a O-Nw~CD~~
I ziI I -I NI -
--00
T
y
^ ^ O
f T
T
w^ ^ O
aT'm I 'oL

r-oNI
AM
Z

x-

>Z
w
f
f
w
v
win
-
an
Section- 9 -11
UsingtheADS402dualdigitalpotentiometer
Therestoftheprogramisessentiallyaseriesof
if-then's
thatscanthe
lower4-bitsofPortBtoseewhichswitchhasbeenpressed
.Andthenact
uponwhicheverswitchisoperated .
g
1D~
O2 en
11
11
A
s
N

()
NN
O
A

TC)
0

C
Figure9 .8
.ActivedigitalBassandTreblecontrol
.
ExperimentingwiththePicBasicProCompiler
Section-10
Programming
Techniques
IntegratingAssemblylanguageintoyourprograms
.
DeclaringVariablesforusewithAssembler.
PassingparametersusingtheDEFINEstatement
.
UsingINCLUDEfilestotidyupyourcode.
WakingthePICfromSLEEP.
AbriefintroductiontoHardwareINTERRUPTS
.
UsingtheONINTERRUPTcommand.
ExperimentingwiththePicBasicProCompiler
IntegratingAssemblylanguageintoyourprograms
Thismaycomeasablowtoanydie-hardBASICprogrammersoutthere,
butassemblylanguagesubroutinesareoccasionallyunavoidable.
Especiallywhentime-criticalorultraefficientcodeisrequired . Not
everyoneagreesonthis,andIwouldbemorethanhappytobeproved
wrong. However,untilsuchtime,Ifeeldutyboundtotryandshowyou
howtoincorporateassemblerroutinesseamlesslyandpainlesslyinto
yourBASICcode .
Ifyoudonotuseassemblylanguageatall,thenyoumaywishtoskipthe
nextfewpages. However,Iurgeyoutogainevenarudimentary
understandingofassembler. Youwillachieveagreaterinsightintohow
thePICfunctionsatitsbaselevel,anditwillalsoallowinformationtobe
gleanedfromMicrochip'smanydatasheetsandapp-notes(sometimes!).
Thiswillultimatelyleadtobettercompilerprogramsbeingwritten .
Theabilitytoplacein-lineassemblerintoyourcodecanbeapowerful
toolifusedappropriately,however,itcanalsobeyourworstnightmareif
abugorglitchshouldarise . Therefore,itisalwaysadvisabletoseeka
standardBASICapproachtosolvingaparticularcodingproblem,ifatall
possible. Someoftheexperimentsinthisbookuseassembler
subroutinesoutofnecessitytoachieveacertaingoal . Primeexamplesof
thisaretheMSSP,eepromsubroutines, EREAD and EWRITE,
discussedinsection-3. TheBASICcodedversionis204Bytesinlength,
whiletheassemblercodedversion,whichhasexactlythesamefunction
and
is transparenttotheprogrammer,isonly116Bytes . Surely,the
savingof88BytesofpreciousROMisworththeuseofassembler .
Amajorconsiderationwhenusingassemblersubroutinesarebank
boundaryconflicts . Allthe14-bitcoredevicesuseROMboundariesof2k
(0-2048). Theproblemwithcrossingtheseboundariesisthat,the
assembler'sGOTOandCALLinstructionsonlysupply11-bitsofthe13-
bitsrequiredbythe program
counter
toaccessROMpast2k. The
remaining2-bitsaresuppliedbybits-3:4ofthePCLATHregister. These
mustbesetorclearedbeforeanassemblerGOTOorCALLinstructionis
implementedwithinyourcode . Forexample,ifaportionofyour
assemblercodecrossesaboundary,thenacallorjumptoaroutine
withinthatbankwillnotactuallygetthere. If,however,theeverpopular
16F84isused,thentheseissuesdonotarise . However,ifthemid-range
PIC'sareused,thenALLassemblersubroutinesshouldbeplacedatthe
startofyourprogram,thusensuringtheywillbelocatedwithinbank-0.
Section-1 0 -1
ExperimentingwiththePicBasicProCompiler
IntegratingAssemblylanguageintoyourprograms
InordertoaccessyourassemblersubroutinefromBASIC,thecompiler's
CALLcommandshouldalwaysbeused
.ThismanipulatesthePCLATH
registertoconstructthefull13-bitsrequiredtoaccessROManywherein
thePIC.TheCALLcommanddiffersfromtheGOSUBcommandinthat
anunderscoremustprecedethesubroutine'snamewhen itisfirst
declared : -
Call My_Sub

`CallthesubroutineMy_Sub
Asm
_My_Sub

;Notetheunderscore,_My_Sub
{ Yoursubroutinegoeshere )
Return

;Exitthesubroutine
Endasm
TheRETURNinstructiondoesnotrequirethatthe PCLATHis
manipulated,asithasaccesstothefull13-bitaddress,which itpulls
fromthe stack.
Note
: whenassemblermodehasbeenentered,thecommentsymbol
mustchangetoasemicolon (
;) insteadofaquote( ') . Ifthisis
forgotten,thenascreenfullofextremely
confusingerrorswillbe
displayed .
DeclaringVariablesforusewithAssembler
Anotherimportantissuewhendesigningassemblerroutinesistheuseof
variables
.ALLvariablesshouldbedeclaredinBASIC,asthecompiler
willnotrecognizeassemblerdeclaredtypes .
Infact,declaringany
variableinassemblerwillwreakhavocwithyourprogram,theassembler
doesnotrecognizecompilervariables, andthecompilerdoesnot
recognizeassemblervariables
.Soimaginewhatwouldhappenif( when!)
theywerebothassignedtothesameRAMlocation?
Inmostcases,whenusingPICswithmorethan2kofROM, ( anda
selectfewwithless) ,
userRAMissplitintoseveralbanks .Therefore,all
variablesusedinanyassemblerroutineshouldbeassignedtobank-0
.
EachRAMbankis128bytesapart,thesealsoincorporatethe PIC's
hardwareregisters .Bits-5
: 6oftheSTATUSregistercontrolwhich bank
thePICispointingto.
Section-10 - 2
ExperimentingwiththePicBasicProCompiler
IntegratingAssemblylanguageintoyourprograms
Ifthecompilerassignsavariablethatweareusingforanassembler
routinetoabankotherthanbank-0,thesubroutinehas
nowayof
knowingthis,therefore,anyreferencestothisvariablewouldbepointing
toanentirelydifferentlocation.
WhenwritingpurelyinBASIC,thecompilertakescareofthisissuefor
us,whichmeansthatitdoesn'tcarewhatbankitassignsaparticular
variableto
. Inmostcases,ifasmallprogramisbeingdevelopedona
largerPIC,thecompilerwillassignthefirstlotofvariablesto
bank-0
automatically,untilitmustmovetoanotherbank
. However,wecannot
be100%certainthatthevariablesusedinourassemblersubroutinewill
alwaysbelocatedinbank-0
. Sowemustforcethecompilertoassigna
particularvariableintobank-0,thisisaccomplishedbyusingtheBANK
operandafterdeclaringthevariable
: -
My_Var
Var Byte BANKO

`AssignMy_VartoBank-0
Ifforanyreason,youwishthevariabletobelocatedintoanotherbank
thenBANK1,BANK2,orBANKSwilldojustthat
.
UsingtheDEFINEcommandtopassparameters
.
Averyusefulwayofpassingparameterstoanassemblersubroutineis
withtheDEFINEstatement
. TheuseofDEFINEisrestrictedtovalues
thatwillremainconstantthroughouttheprogram(i . e.
theport andbit
whereaninfraredsensorisattached),
asthesamedefinemayonlybe
usedoncewithinthecode
. Thisisusuallyplacedatthebeginningofthe
program
. Asanexample,let'ssupposewehavewrittenasubroutineto
outputaninfraredsignaltoanLEDconnectedtoPortA
. 1 .
Define IR_
PORTPORTA `Port onwhichtoattachIRLED
Define IRBIT

`BitonwhichtoattachIRLED
Asm
#Define lR_LED
lRPORT,IRBIT
Endasm
Section-10 - 3
ExperimentingwiththePIcBasicProCompiler
Asm
IfndefIRPORT
IRPORT= PortA
Endif
IfndefIRBIT
IRBIT=0
Endif
Endasm
UsingtheDEFINEcommandtopassparameters
The#DEFINEisanassemblerdirective,itsuseisthesameasitsBASIC
counterpart,asintheexampleabove,everytimethenameIR_LEDis
encountereditwillbereplacedbythestringIR_PORT,IR_BIT,
andas
IRPORThasbeengiventhevalueofPORTA
( 5 ) , andIRBIThasbeen
giventhevalue1,thenameIRLED
isnowequaltothestring PORTA,1 .
ThisisusedasaninterfacebetweenBASICandassembler
. Andcanbe
placedintheassemblerroutinelikethis : -

Bcf IR_LED
;CleartheappropriatePortandBit

Bsf STATUS,5 ;
PointtoBANK1registers

Bcf IRLED ; Makethe


Port andBitanOUTPUT

Bcf STATUS,5
; BacktoBANKOregisters

Bsf IRLED
; TurnontheIRLED
DefaultvaluescanalsobecreatedincasetheDEFINEisnotusedornot
required
. Inthecaseofourexample,letssupposethatthedefinesare
notused,thedefaultswillbePORTAandBIT- 0
. Forthisweusethe
assembler'sIFDEF,IFNDEF,andENDIFstatements
. IFDEF,asits
nameimplies,willreturntrueifthe#DEFINEhasbeendeclared,IFNDEF
willreturntrueifthe#DEFINEhasnotbeendeclared
. Wecanusethis
( conditionalassembly)
tosettheportandbitdefinitionstotheirdefault
valuesifthedefinehasnotbeenincludedintheprogramlikethis : -
Wearenowinassemblermode
CheckiflR_PORThasbeendeclared
Ifnot,thenlRPORT=PORTA
E

ndofIFstatement

CheckifIRBIThasbeendeclared

Ifnot,thenlR_BIT=0
E

ndofIFstatement
B

acktoBASICmode
Thisisaveryusefulandefficientwayofpassingparameters,
asthe
compileritselfproveswiththeLCD,DEBUG,SERIN2etc,defines
. And
isusedinmanyoftheprogramsthroughoutthisbook .
Section- 10 - 4
ExperimentingwiththePicBasicPro
Compiler
UsingINCLUDEfilestotidyupyourcode
UsingINCLUDEfilestotidyupyourcode
Includefilesarealsousedextensivelythroughoutthisbook
. Itaidsinthe
readabilityofthecodeandisaneasywaytoincorporatecommonlyused
subroutines
. Includefilesarebynomeansanewidea ;theyhavebeen
usedsincethefirstassemblersweredeveloped,andareusedalotin
languagessuchasCandPASCAL
. However,mostpeopleconsiderthe
PBPtobejustanotherversionoftheBASICStampandwritecodeinits
style. Thiscouldnotbefurtherfromthetruth
;itistruethatmostBASIC
StampandBASICStampIIprogramsmaybedirectlycompiled
. Butif
youarewritingpurelywiththePBPthenStampcodecanbeawkward
andclumsy .
Iftheincludefilecontainsassemblersubroutinesthenitmustalwaysbe
placedatthebeginningoftheprogram,justafterthe
MODEDEFS. BAS
file
. Thisallowsthesubroutine/stobeplacedwithinthefirstbank of
memory (0. . 2048),
thusavoidinganybankboundaryerrors . Placingthe
includefileatthebeginningoftheprogramalso
allowsallofthe
variablesusedbytheroutinesheldwithinittobepre-declared
. This
againmakesforatidierprogram,asalonglistofvariablesisnotpresent
inthemainprogram.
Therearesomeconsiderationsthatmustbetakenintoaccountwhen
writingcodeforanincludefile,theseare
: -
1 )
. Alwaysjumpoverthesubroutines.
Whentheincludefileisplacedatthetopoftheprogramthisisthefirst
placethatthecompilerstarts,therefore,itwillrunthesubroutine/sfirst
andtheRETURNcommandwillbepointingtoarandomplacewithinthe
code
. Toovercomethis,placeaGOTOstatementjust beforethe
subroutinestarts. Forexample: -
GotoOVERTHISSUBROUTINE

`Jumpoverthesubroutine
`Thesubroutineisplacedhere
OVER-THIS_SUBROUTINE:

`Jumptoherefirst
Section-1 0 - 5
ExperimentingwiththePicBasicProCompiler
UsingINCLUDEfilestotidyupyourcode
2).VariableandLabelnamesshouldbeasmeaningfulaspossible
.
Forexample
.InsteadofnamingavariableLOOP,changeitto
ISUBLOOP.
Thiswillhelpeliminateanypossibleduplicationerrors,
causedbythemainprogramtryingtousethesamevariableorlabel
name.However,trynottomakethemtooobscureasyourcodewillbe
hardertoreadandunderstand,itmightmakesenseatthetimeof
writing,butcomebacktoitafterafewweeksanditwillbemeaningless .
3)
.Comment,Comment,andCommentsomemore .
Thiscannotbeemphasizedenough .ALWAYSplaceaplethoraof
remarksandcomments
.Thepurposeofthesubroutine/swithinthe
includefileshouldbeclearlyexplainedatthetopoftheprogram,also,
addcommentsaftervirtuallyeverycommandline,andclearlyexplainthe
purposeofallvariablesandconstantsused
.Thiswillallowthe
subroutinetobeusedmanyweeksormonthsafteritsconception
.Arule
ofthumbthatIuseisthatIcanunderstandwhatisgoingonwithinthe
codebyreadingonlythecommentstotherightofthecommandlines .
Theincludefileusedbyyourprogrammustbeinthesamedirectoryas
thatprogram,orintherootdirectoryofthecompiler ( i.e . PBASIC).
TherearesomethingsthatshouldNOTbedoneinsideanincludefile .
Theseare: -
DONOTloadinthe
MODEDEFS.BASincludefile .Alwaysplacethisin
themainprogram .
DONOTusetheOSCdefine,asthismayoverridetheOSCsetting
withinthemainprogram .
Section- 10 - 6
ExperimentingwiththePicBasicPro
Compiler
Program -SLEEP
.BASandSLEEP2.BAS
WakingthePICfromSLEEP
AllthePlCmicrorangehavetheabilitytobeplacedintoalowpower
mode,consumingmicroAmpsofcurrent
.
ThecommandfordoingthisisSLEEP
.Thecompiler'sSLEEPcommand
ortheassembler'sSLEEPinstructionmaybeused
.Thecompiler's
SLEEPcommanddifferssomewhattotheassembler'sinthatthe
compiler'sversionwillplacethePICintolowpowermodefornseconds
(wherenisavaluefrom0to65535).
Theassembler'sversionstillplaces
thePICintolowpowermode,however,itdoesthisforever,oruntilan
internalorexternalsourcewakesit
.Thissamesourcealsowakesthe
PICwhenusingthecompiler'scommand .
ManythingscanwakethePICfromitssleep,theWATCHDOGTIMERis
themaincauseandiswhatthecompiler'sSLEEPcommanduses
.
AnothermethodofwakingthePICisanexternalone,achangeonone
oftheportpins
.Wewillexaminemorecloselytheuseofanexternal
source.
Forthesedemonstrationsthewatchdogtimermustbedisabledoritwill
wakethePICeverytimeit
times-out.
Thisisaccomplishedbyplacingthe
followinglineofcodeatthebeginningoftheprogram
: -
Devicewdtoff
Note
: thatthismayonlybeusedwhenthePMassemblerischosen
.
Also,itisdeviceindependent .
TherearetwomainwaysofwakingthePICusinganexternalsource
.
Oneisachangeonbits4
.1ofPortB .Anotherisachangeonbit-0of
PortB
.WeshallfirstlookatthewakeuponchangeofPortB,bits-4
. .7 .
Asitsnamesuggests,anychangeonthesepinseitherhightoloworlow
tohighwillwakethePIC
.However,tosetupthismodeofoperation
severalbitswithinregistersINTCONandOPTION_REGneedtobe
manipulated
.OneofthefirstthingsrequiredistoenabletheweakPortB
pullupresistors
.ThisisaccomplishedbyclearingtheRBPUbitof
OPTION_REG
(OPTION REG
.7) .If thiswasnotdone,thenthepins
wouldbefloatingandrandominputstateswouldoccurwakingthePIC
upprematurely.
Section-10 - 7
ExperimentingwiththePicBasicPro
Compiler
WakingthePICfromSLEEP
Althoughtechnicallyweareenablingaformofinterrupt,
wearenot
interested
(inthisprogram)
inactuallyrunninganinterrupthandler .
Therefore,wemustmakesurethatGLOBALinterruptsaredisabled,or
thePICwilljumptoaninterrupthandlereverytimeachangeoccurson
PortB. ThisisdonebyclearingtheGIEbitofINTCON
(INTCON. 7 ) .
TheinterruptweareconcernedwithistheRBportchangetype
. Thisis
enabledbysettingtheRBIEbitoftheINTCONregister
(INTCON
. 3 . All
thiswilldoissetaflagwheneverachangeoccurs
(andofcoursewake
upthePIC) .
TheflaginquestionisRBIF,whichisbit-0oftheINTCON
register
. Fornowwearenotparticularlyinterestedinthisflag,however,
ifglobalinterruptswereenabled,thisflagcouldbeexaminedtoseeifit
wasthecauseoftheinterrupt
. TheRBIFflagisnotclearedbyhardware
sobeforeenteringSLEEPitshouldbecleared
. Itmustalsobecleared
beforeaninterrupthandlerisexited
.
TheSLEEPcommanditselfisthenused
. UponachangeofPortB,bits
4-7 thePICwillwakeupandperformthenextinstruction
(orcommand)
aftertheSLEEPcommandwasused
.
AsecondexternalsourceforwakingthePICisapulse
appliedto
PortB. O
. Thisinterruptistriggeredbytheedgeofthepulse,hightolow
orlowtohigh
. TheINTEDGbitofOPTION_REG
(OPTIONREG . 6 )
determineswhattypeofpulsewilltriggertheinterrupt
. Ifitisset,thena
lowtohighpulsewilltriggerit,andifitisclearedthenahightolowpulse
willtriggerit.
ToallowthePortB
. OinterrupttowakethePICtheINTEbitmustbeset,
thisisbit-4oftheINTCONregister
. Thiswill allowtheflagINTF
(INTCON. 1 )
tobesetwhenapulsewiththerightedgeissensed
. Aswith
thepreviousdiscussion,thisflag
isonlyofanyimportancewhen
determiningwhatcausedtheinterrupt
. However,itis notclearedby
hardwareandshouldbeclearedbeforetheSLEEPcommandisused
(or
theinterrupthandlerisexited)
.
Theprograms SLEEP. BAS, and
SLEEP2. BAS demonstrateboth
methodsdiscussed
. SLEEP. BAS
willwakethePICwhenachange
occursonPortB,bits4-7
. And SLEEP2. BAS
willwakethePICwhena
pulseisdetectedonPortB . O .
Section-1 0- 8
ExperimentingwiththePicBasicPro
Compiler
Programs-TMROCLCK.BASandTMROINT
.BAS
Abriefintroductiontohardwareinterrupts
Therearemanywaysthatinterruptsmaybetriggeredonthedifferent
typesofPICavailable
.ThepreviousdiscussiononSLEEPshowedtwo
possiblemethods
.However,wedonothavethespacetogointoallthe
variousways,assomeofthelargerPICshavemorethan30individual
interrupttriggeringsources .Therefore,wewillexaminehowto
enable
interruptsusingthemostpopularmethod,thatofTIMERO
.
TIMERO,orTMROisaneight-bitregister,initssimplestform
TMRO
incrementswitheveryinstructioncycle
.Whenthecountreaches255it
rollsoverto0andkeepsoncounting
.TMROalsohasaprescalerwhich
maybeattachedtoit
.Whentheprescalerisenabled,TMROincrements
onceevery2,4,8,16,32,64,128,or256instructioncycles
.Whenever
TMROrollsoverto0aninterruptmaybegenerated .
Thecompiler'sONINTERRUPTcommandisnotaninterruptinthetrue
senseofthewordasitmustfinishtheBASICcommanditisprocessing
beforetheinterrupthandlingsubroutineiscalled .Trueinterruptsoccur
onaregularbasis,oraretriggeredbyanevent,regardlessofwhatthe
PICisprocessingatthetime
.Therefore,theONINTERRUPTcommand
willnotbediscussedjustyet.Insteadwewillexaminetrue
hardware
interruptsthatoccurnaturallywithinthePIC .These,unfortunatelymust
alwaysuseassemblerwithintheinterrupthandler
.Thereason behind
thisisthatthecompiler'scommandsarenotre-entrant,which
means
onlyonecommandatatimemaybeused
.Thissoundslikestatingthe
obvious,however,ifBASICcommandswereusedwithinahardware
interrupt,acommandinthemainbodyprogramcouldbeinterrupted
mid-streamandthesameinstructionmaybeencounteredintheinterrupt
handler
.Asbothcommandswould beusingthesameSYSTEM
variables,oneofthecommandsisgoingtobepresentedwiththewrong
values
.Thiscouldleadtomajorprogramcrashes,orsubtlebugsthat
wouldbenexttoimpossibletotrackdown .
Toinformthecompilerwheretofindtheassemblerinterrupthandling
subroutineaDefineisused : -
DefineINTHAND
My_Int

`Pointtointerrupthandler
ThecompilerwillnowjumptotheinterrupthandlingsubroutineMY_INT
wheneveraninterruptistriggered
.
Section-10 - 9
ExperimentingwiththePicBasicProCompiler
Abriefintroductiontohardwareinterrupts
Beforewecanchangeanybitsthatcorrespondtointerruptsweneedto
makesurethatglobalinterruptsaredisabled
.Thisisdonebyclearing
theGIEbitofINTCON
(INTCON.7 ) .
Sometimesaninterruptmayoccur
whiletheGIEbitisbeingcleared,whichmeansthatthebitisnotactually
clearedandglobalinterruptsarenotdisabled
.TomakesurethattheGIE
bitisactuallyclearedwemustpollit
.Thiscanbeaccomplished bya
simpleloop: -
GIE=O

`Disableglobalinterrupts
While
GIE=1

`Makesuretheyareoff
GIE=O

`Continuetoclear
GIE
Wend

` Exitwhen GIE isclear


TheprescalerattachmenttoTMROiscontrolled
bybits0 : 2ofthe
OPTION_REG(PSO,1,2)
.Table1
.1showstheirrelationship tothe
prescaledratioapplied
.Butbeforetheprescalercanbecalculatedwe
mustinformthePICastowhatclockgovernsTMRO
.Thisisdoneby
settingorclearingthePSAbitofOPTIONREG
(OPTION REG.3) .
If
PSAisclearedthenTMROisattachedtotheexternalcrystaloscillator
. If
itissetthenitisattachedtothewatchdogtimer,whichusestheinternal
RCoscillator.Thisisimportanttoremember
;astheprescaleratiodiffers
accordingtowhichoscillatoritisattachedto.
Table1.3
.TMROprescalerratioconfigurations
.
Ascanbeseenfromtheabovetable,ifwerequireTMROtoincrement
oneveryinstructioncycle (4/OSG) wemustclearPS2
. .0andsetPSA,
whichwouldattachittothewatchdogtimer .Thiswillcauseaninterrupt
tooccurevery256us
(assuminga4mHzcrystal) . Ifthesamevalues
wereplacedintoPS2
. .0andPSAwascleared
(attachedtotheexternal
oscillator)
thenTMROwouldincrementonevery
2nd
instructioncycleand
causeaninterrupttooccurevery512us
.
Section-
10- 10
PS2 PS1 PSO PSA=O(ExternalcrystalOSC)
PSA=1 (Internal WDT OSC)
0
0 0 1 : 2
1 : 1
0 0
1 1 : 4
1 : 2
0
1 0 1 : 8
1 : 4
0 1 1
1 : 16
1
: 8
1 0 0
1 : 32 1 : 16
1 0 1
1 : 64 1 : 32
1 1 0
1 : 128 1 : 64
1 1 1 1 : 256
1 : 128
ExperimentingwiththePicBasicProCompiler
Abriefintroductiontohardwareinterrupts
Thereishowever,anotherwayTMROmaybeincremented
.Bysetting
theTOCSbitoftheOPTIONREG (OPTION_REG.5)
arisingorfalling
transitiononPortA .OwillalsoincrementTMRO .SettingTOCSwillattach
TMROtoPortA
.OandclearingTOCSwillattachittotheoscillators .If
PortA .Oischosenthenanassociatedbit,TOSE
(OPTIONREG.4) must
besetorcleared .ClearingTOSEwillincrementTMROwithalowtohigh
transition,whilesettingTOSEwillincrementTMROwithahightolow
transition.
Theprescaler'sratioisstillvalidwhenPortA
.Oischosenasthesource,
sothateverynth transitiononPortA.OwillincrementTMRO
.Wherenis
theprescalerratio.
Beforetheinterruptisenabled,TMROitselfshouldbeassignedavalue,
asanyvariableshouldbewhenfirststartingaprogram.Inmostcases
clearingTMROwillsuffice
.Thisisnecessarybecause,whenthePICis
firstpoweredupthevalueofTMROcouldbeanythingfrom0to255
WearenowreadytoallowTMROtotriggeraninterrupt .Thisis
accomplishedbysettingtheTOIEbitofINTCON (INTCON.5) . Setting
thisbitwillnotcauseaglobalinterrupttooccurjustyet,butwillinform
thePICthatwhenglobalinterruptsareenabled,TMROwillbeone
possiblecause
.WhenTMROoverflows (rollsoverfrom255to0) the
TGIF (INTCON.2) flagisset
.Thisisnotimportantyetbutwillbecome
crucialintheinterrupthandlersubroutine
.
ThefinalactistoenableglobalinterruptsbysettingtheGIEbitofthe
INTCONregister (INTCON.7 ) .
Theinterrupthandlersubroutinemustalwaysfollowafixedpattern
.First,
thecontentsoftheWregisteralongwithPCLATHandSTATUSmustbe
saved,thisistermed contextsaving.
Therefore,weneedtosetaside
severalvariablesfortheregisterstobestoredinto: -
Wsave

VarByte

SYSTEM`StoragefortheWregister
Ssave

VarByte

SYSTEM `StoragefortheSTATUSreg
Psave

VarByte

SYSTEM `Storageforthe
PCLATHreg
Section- l0-
1 1
ExperimentingwiththePicBasicProCompiler
{ Yourinterruptcodegoeshere}
SavingoftheregistersisdoneautomaticallybythecompilerifaPICwith
morethan2kofROMisused .However,whenusingPICswithmore
than2Kthingsgetalittletrickier,asmorestoragespaceisrequired
alongwiththeirADDRESSandBANKpositions .Thereasoningbehind
thisisthatwhenaninterruptoccurs,thePICmightbeprocessing
commandsinabankotherthanbank-0,whichalsomeansthattheRAM
addresseshavemovedtoanotherbank.IftheWregisterwasnowtobe
savedintothevariable WSAVE priortoprocessingtheinterruptcode,it
wouldbepointingtothecorrectlocationinRAMbutthewrongbank .
Thedatamemory (RAM) isorganisedinbanksof128.Inthecaseofthe
newPIC16F87Xrangethefirstbankofmemory
(bankO)
startsat
address$20,thesecondat$A0,thethird (ifithasmorethan2banks) at
$120,andthefourth (ifithasmorethan3banks) at$1A0.Therefore,if
theinterruptwascalledwhilethePICwasprocessingcodeinbank-1,
thenwhatusedtobeRAMaddress$20isnowactually$A0
.Ifavariable
wasalreadyassignedto$AOitscontentswouldbeoverwrittenbythe
interruptplacingthecontentsofWintoit .
Tobeextrasafe,theaddressofthe WSAVE variablesalongwiththeir
banklocationsshouldbeused.Theaddresslocationshouldbethesame
foreachbank.Forexample: -
Section-l0-12
Abriefintroductiontohardwareinterrupts
Theactualassemblycodeplacedattheheadoftheinterrupthandler
thatdoesthecontextsavingis : -
Asm
My_lnt
Thenameoftheinterrupt
Movwf Wsave SavetheWregister
Swapf STATUS,w
Clrf STATUS
Movwf
Ssave SavetheSTATUSregister
Movf PCLATH,w
Movwf Psave SavethePCLATHregister
ExperimentingwiththePicBasicProCompiler
ThiswillallowtheWregistertobesavedatthefirstlocationofRAMin
anybankregardlessofwhichbankthePICwasinwhentheinterrupt
wascalled
.Ifitisprocessingbank-1thentheWregisterwillbesaved
intothevariable WSAVE1 aswellas WSAVEO.
Note .Thisonlyapplieswhenusinginterrupts,asthecompilernormally
takestheheadacheoutofbankswitching
.
WhentheinterrupthandlerwascalledtheGIEbitwasautomatically
clearedbyhardware,disablinganymoreinterrupts .Ifthiswerenotthe
case,anotherinterruptmightoccurwhilethe
interrupthandlerwas
processingthefirstone,whichwouldleadtodisaster .
NowtheTOIF (TMROoverflow) flagbecomesimportant.Because,
beforeexitingtheinterrupthandleritmustbeclearedtosignalthatwe
havefinishedwiththeinterruptandarereadyforanotherone.Alsothe
W,PCLATHandSTATUSregistersmustbereturnedtotheiroriginal
conditions
.Theassemblercodefordoingthisis: -
{ Yourinterruptcodegoeshere }
ThefinalcommandintheinterrupthandlerreturnsthePICbacktothe
mainbodycodewheretheinterruptwascalledfrom .RETFIEmustbe
usedasopposedtoRETURNbecause,RETFIEalsore-enablesglobal
interrupts.
Section-
1
0-13
Abriefintroductiontohardwareinterrupts
WsaveOVar
$20 BANKO SYSTEM ` Wstorageinbank-0
WsavelVar $AO BANK1
SYSTEM ' Wstorageinbank-1
Wsave2Var $120BANK2 SYSTEM ` Wstorageinbank-2
Wsave3Var$1AOBANKS SYSTEM ` Wstorageinbank-3
Ssave Var ByteBANKO SYSTEM ` STATUSstorage
Psave
VarByteBANKO SYSTEM ` PCLATHstorage
Movf Psave,w ;RestorePCLATHregister
Movwf
PCLATH
Swapf Ssave,w ;RestoreSTATUSregister
Movwf STATUS
Swapf
Wsave,f
Swapf Wsave,w ; RestoreWregister
ExperimentingwiththePicBasicProCompiler
Abriefintroductiontohardwareinterrupts
Asimplisticyettypicalinterrupthandlingsubroutineisshownbelowfor
useonPICswith2korlessofROM : -
Asm
INT
Theprogramaboveistheclassicflashingledprogramimplementedthe
longway.EverytimetheinterruptiscalledtheXorwfinstructionwillturn
theledonoroff .Theflashingwillonlybeapparentiftheprescalerratio
isassignedahighvalue,suchas1 : 256.
Tomakelifeeasierwhenusinghardwareinterrupts,threeincludefiles
havebeendeveloped
. 2KINT.INC, isforusewithPICsthathave2kor
lessofROM,suchasthe16F84
. 4KINT.INC, isforusewithPICsthat
have4kofROM,suchasthe16F874
. And 8KINT.INC, isforusewith
PICsthathave8kofROM,suchasthe16F877.
Thechosenincludefile,asalways,mustbeplacedatthebeginningof
yourprogram .Withineachincludefiletheexactamountofvariable
spaceisallocatedforcontextsaving,alsotwomacrosaredefined .The
reasonbehinddevelopingthreeincludefilesinsteadofaone- for- all
approachisthatitislesswastefulonpreciousvariablespace
.
Section- l0- 1 4
Movwf
Swapf
Clrf
Movwf
Movf
Movwf
Wsave
STATUS,w
STATUS
Ssave
PCLATH,w
Psave
; Savetheregisters
;
Beforestartingthecode
; Withintheinterrupthandler
Movlw255
XorwfPortB
; FlashanLEDeveryinterrupt
Bcf INTCON,TOIF ; CleartheTMROoverflowflag
Movf Psave,w
Movwf
PCLATH
Swapf Ssave,w ;
Restoretheregisters
Movwf STATUS ;
BeforeexitingtheInterrupt
Swapf Wsave,f
Swapf Wsave,w
Retfie ;
Exittheinterruptsubroutine
Endasm
ExperimentingwiththePicBasicProCompiler
Abriefintroductiontohardwareinterrupts
Thefirstmacro, INT_START,
savestheWregisteralongwiththe
STATUSandPCLATH
.ThismacroisonlyrequiredwhenusingaPIC
with2korlessofROM,asthecompilerautomaticallysavesthecontext
forlargerPICs
.Tousethe INT_START
macro,placethefollowing
templatecodeatthebeginningofyourinterrupthandier : -
Asm
My_Int

;Thenameoftheinterrupt
INTSTART

;Usethecontextsavingmacro
{
Yourinterrupthandlingcodegoeshere
)
Thesecondmacro,
INTEND,
restoresthecontentsoftheWregister,
STATUS,andPCLATH,thenperformsaRETFIEinstruction .Thismacro
mustbeusedregardlessofthePICsize,asthecompilerdoes
not
restorethecontextforlargerPICs
.TousetheINTENDmacro,
place
thefollowingtemplatecodeattheendofyourinterrupthandler
: -
{
Yourinterrupthandlingcodegoeshere )
INTEND

; Usethecontextrestoremacro
Endasm
Eachmacrodefinedintheseparateincludefilesusesexactlythe
right
amountofinstructionsaccordingtothesizeofthePICchosen
. Thus
reducingwastedmemory
Theprogram
TMROCLCK.BAS
demonstratestheuseofaTMRO
interruptperformingthefunctionsofa
(notveryaccurate)
clock,
displayingthetimeonaserialLCDconnectedtoPortA .0
.Theprescaler
isassignedtheratioof1
: 64,whichmeansthataninterruptwillbecalled
every16 .384ms
(64*256us) .
Assuminga4mHzcrystalisused .
Eachtimetheinterruptiscalled,thevariableTICKSisincrementeduntil
itreaches61
.Thiswillgiveusanapproximatesecond
(61*16384=
999.424msor
.999424ofasecond) .
WhenTICKSreaches61,asecondhaspastsothe
SECONDS
variable
isincrementedandtheTICKSvariableiscleared
.When SECONDS
reaches60,aminutehas
passedsothe MINUTES
variableis
incrementedandthe SECONDS
variableiscleared .When MINUTES
reaches60,anhourhaspassedsothe HOURS
variableisincremented
andthe MINUTES
variableiscleared .
Section- 10-
1 5
ExperimentingwiththePicBasicProCompiler
Abriefintroductiontohardwareinterrupts
Andfinally,whenthe HOURS
variablereaches23thenafull24-hourday
haspassedso
HOURSiscleared .Ifmorethanasecondhaspassed
thentheflag U_FLAG
isset.Thiswillinformthemainprogramloopto
updateitsdisplaywiththecurrenttime
.
ItmustbenotedthatTMROitselfisenabledatpowerup
.Regardlessof
whethertheTOIEbitissetornot
.Thisjustattachesittoaninterrupt .
WhichmeansthattheTOIFflagwillalwaysbesetwhenanoverflow
occurs.
Inaddition,whentheprescalerisattachedtothewatchdogtimer,the
compiler'sSLEEPandNAPcommandsmaynotbeused .Astheseare
alsoattachedtothewatchdog,andrelyontheprescaler'sratio
.
Thecodewithintheinterrupthandlershouldbequickandasefficientas
possiblebecause,whileit'sprocessingthecodethemainprogramis
halted .
Whenusingassemblerinterrupts,careshouldbetakentoensurethat
thewatchdogtimerdoesnot
time-out. PlacingaCLRWDTinstructionat
regularintervalswithinthecodewillpreventthisfromhappening
.An
alternativeapproachwouldbetodisablethewatchdogtimeraltogether,
asillustratedintheSLEEPdiscussion
.
Section-10- 1 6
ExperimentingwiththePicBasic Pro Compiler
Program -INT_CLCK.BAS
UsingtheONINTERRUPTcommand
UsingtheONINTERRUPTcommandissimilartousinganassembler
interrupt
.However,thecompilerdoesnotimmediatelycalltheinterrupt
handler,insteaditflagsitandwaitsuntilthecommandbeingprocessed
isfinished
.Astheremightbeadelaybeforetheinterruptiscalled, the
prescaler'sratioshouldnotbeassignedtoolowavalue
.Forexample,if
theprescalerwasassignedtheratio1
:1,thenaninterruptshouldoccur
every256us
(assuminga4mHzoscillator) . However,ifthecompilerhas
towaituntilthecurrentcommandisfinished,itmightnothavetimeto
processtheinterruptattheinstantTMROrolledover
.
Thingsbecometrickierifachangeofstateontheportpinsistriggering
theinterrupt
.Bythetimetheinterrupthandlerhasbeencalled,theevent
thattriggereditcouldhavealreadyfinished .
However,itdoeshaveitsadvantages,especiallyifanontime-critical
interruptisbeingimplemented,asitwillnotslowdownthePICwhilea
serialorpausecommandisbeingused
.Also,itdoesnotrequiredifferent
codeforthevarioussizesofPIC
.Whichmeansthecodeproduced
shouldworkonanytype.
TousetheONINTERRUPTcommandwithaTMROinterrupt,thesame
bitsofINTCONandOPTION_REGmustbesetorcleared,asinthe
previousdiscussion
.However,insteadofusingtheINTHANDdefineto
pointtotheinterrupthandlingsubroutine,theONINTERRUPTcommand
isused:-
ONINTERRUPTGOTOMy_Int
`Pointtotheinterrupthandler
Theinterrupthandleritselfalsodiffersfromtheassemblertype
. Unlike
hardwareinterrupts,thecompiler'sversionofaninterruptsimplyplaces
acalltotheinterrupthandlerbeforeeachcommandisprocessed
.Upon
enteringtheinterruptsubroutine,thesecallsmustbedisabled
. Thisis
thejoboftheDISABLEcommand
.DISABLEisn'treallyacommandat
all,itisactuallyadirectivethatinformsthecompilerto
disablethe
interruptflaggingprocess
.Itservesthesamepurposeasclearingthe
GIEbitinhardwareinterrupts
.Onthesamenote,theGIEbitisactually
clearedwhenacompilerinterruptiscalled
.Thisinturndisables
interruptsoccurringwithininterrupts .
Section-l0- 1 7
ExperimentingwiththePicBasicProCompiler
UsingtheONINTERRUPTcommand
TheDISABLEdirectiveshouldbeplacedattheheadoftheinterrupt
handlingsubroutine
: -
DISABLE
My_Int
( Interrupthandlerstartshere )
TheW,STATUS,andPCLATHtemporarystoragevariablesdonotneed
tobedeclared,asthecompilerdoesthisforus,regardlessofthesizeof
thePIC.
Thecodediffersonexitingtheinterrupthandleraswell
. The RETFIE
instructionisnotused;insteaditisreplacedbytheRESUMEcommand .
Thisdoesasimilarjobastheassembler'sRETFIEinstructioninthatit
re- enablesglobalinterrupts
. TheENABLEdirectivemustbeissuedafter
theRESUMEcommandtoinformthecompilertostartflagging
the
commandsagain: -
( Interrupthandlerendshere)
RESUME
ENABLE
TheW,STATUS,andPCLATHvaluesdonotneedtoberestoredas
theydidintheassemblerinterrupt ;thecompileralsodoesthisforus
.
Therearecertainguidelinesthatshouldbeadoptedwhen usingthe
compiler'sinterrupt,thatdon'tapplytoanassemblertype
. Becausethe
compilermustfinisheachcommandbeforeprocessing
aninterrupt,
certaincommandsmustbere- arranged. OnesuchcommandisPAUSE.
Ifadelayof1secondwererequired,thenormalprocedurewouldbe : -
Pause1000
ButthiswillcausethePICtowait1000msbeforeitcan
processits
interrupthandler.
Section- 10- 1 8
ExperimentingwiththePicBasicProCompiler
UsingtheONINTERRUPTcommand
Abettersolutionwouldbetobreakupthedelayintosmalleramounts : -
ForX=0to10000
Pauseus100
Next
Thiswillgiveusthesame1seconddelayandallowtheinterrupthandler
tobecalledregularly .Thesamemethodshouldbeadoptedwhenusing
themorecomplexcommands,suchasSEROUT,SERIN,PULSINetc,
asalotofthesecommandsdisableinterruptswhiletheyareworking .
InthecaseofSEROUToroneofitsrelatives,insteadofsendingdataall
inonecommand,splititintoseveralSEROUTcommands .Whenusing
SERINtypecommands,alwaysplaceatime- outvaluewithinthem,
shorterthantheinterrupt'sintervaltime .Otherwisenointerruptwilloccur
whilethePICiswaitingfortheserialdatatoarrive
.
Thedemonstrationprogram INTCLK.BAS hasexactlythesame
function astheassembler program, TMROCLK.BAS, inthatit
implementsaclockdisplayingthetimeonaserialLCD .Infact,themain
bodyofthecodeisidentical ;onlywritteninBASIC.Themaindifferences
aretheDISABLE,ENABLE,andRESUMEcommandsusedwithinthe
handler.AndtheuseoftheONINTERRUPTcommandasopposedto
theINTHANDdefine
.
Whilestudyingboththehardwareandthecompiler's interrupts,you
shouldseeapatternemergingconcerningtheINTCONregister
.Control
bitsthatendwithan 'E', suchasTOIE,enableordisableaninterrupt.
Whilethosethatendwithan 'F',suchasTOIF,informthePICasto
whetheraneventhasoccurredornot .Thisfundamentalpattern holds
trueforallotherinterruptregistersaswell.
Section- l0- 1 9
ExperimentinwittePicBasicProCompiler
Section-11
PowerinuptePIC
Gettintemostoutofbatteries.
TeperfectPower-up.
ExperimentingwiththePicBasicProCompiler
Gettingthemostoutofbatteries
Batterypowerisnecessarywhendesigning portableprojects,but
batterieshaveatendencytodecreaseinvoltageastheyage
.Besides,
whoeverheardofafivevoltbattery?
PlacingthreeAAor AAA
cellsinserieswillprovideonly4 .5V (3.6Vfor
nicads),
whichwillcauseproblemsformostPICs.Andusingfourcells
willproduce1Vtoomany,causingthePICtogenerateheat
.Whatis
requiredisameansofproducingthecorrectvoltageataconstantrate
throughoutthebattery'slifetime
.Entertheswitchmodeconverter.
Untilrecentlyswitchmodeconverterswerenotforthefainthearted
. But
nowavastarrayofofftheshelfdevicesarereadilyavailable
. Maxim
seemstobethemostprolificdesignerofthesedevices,withallshapes
andvoltagesavailable
.
ThedeviceweshalllookatfirstisMaxim'sMAX777step-upconverter .It
canprovideanoutputvoltageof5Vfromaninputaslowas1
.5V,and
outputcurrentsinexcessof200mAarepossible (onlywitha4
.5Vinput).
Highspeedswitchingallowstheuseofsmallinductorsanddecoupling
capacitors
.Itdrawsonly190uAofquiescentcurrentwhenoperatingand
anamazing20uAwhendisabled,which
makesitidealforbattery
operation .
Figure11
.1showsatypicalapplicationcircuitforproviding5Vfroma
4 .5Vsource (three
AAorAAA cells).
IN

LX
ILM
MAX777
OUT
SHUN
PGND AGND
v
R1
330k
Section-l 1 -1
Figure11 .1
.MAX777,5Voltswitchmodeconverter .
WhentheSHDNpinispulledhighthechipisenabled
.R1ensuresthat
SHDNispulledlowwhentheon/offswitchisopen
.
ExperimentingwiththePicBasicProCompiler
Gettingthemostoutofbatteries
ThenextswitchmodedeviceweshalllookatisMaxim'sMAX761
.This
iscapableofproducingavariableoutputvoltagebetween5Vand16
.5V
fromaninputvoltageof4
.75Vto12V,providedtheinputvoltageisless
thantherequiredoutputvoltage
.TheMAX761iscapableofproducing
anoutputcurrentinexcessof150mA
.Ifthatwasn'tenough,thedevice
alsohasanon-boardlowvoltagedetector.
Figure11
.2showsacircuittoprovidea5Voutputusinga4 .5Vinput.
Figure11.2
.MAX761,5Voltswitchmodeconverter .
ResistorsR1andR2settheappropriateoutputvoltage
.Theresistors
arecalculatedusingtheformula : -
R2=R1*((Vout/1.5) - 1))
ThevalueofR2canbeanywherebetween1OkQand250kQ,remember,
thehigherthevalueofthesetworesistors,thelowerthecurrentloss
throughthem.
Thevalueoftheinductor(0)mustalsobecalculatedfordifferentinput
voltages
.Theformulaforthisis : -
L(uH)=5"Vin
ThediodeD1mustbeahighspeedSchottkyrectifier
.Anormal1N4001
willnotworkasareplacementasitisnotcapableofoperatingatthe
requiredhighfrequencies
.
BychangingthevalueofR1,R2andL1,higheroutputvoltagescanbe
achieved.Figure11
.3showscircuitforproducing9VfromfourAAAor
AAcells(6V) .
Section-11 - 2
ExperimentingwiththePicBasicProCompiler
Gettingthemostoutofbatteries
Figure11 .3
.MAX761,9Voltswitchmodeconverter
.
Batterymonitoringisachievedbyaddingtworesistorsandanindicating
LED
.Figure11 .4showsacircuitthatproduces5VfromathreeAAAor
AAcellsandilluminatestheLEDwhenthevoltagefromthesedrops
below3V.
Figure11 .4
.5Voltoutputwithbatterymonitoring .
ResistorsR4andR5setthetripvoltage
.Theyarecalculatedusingthe
formula: -
R4=R5 " ((Vtrip - 1.5)/1 .5)
R5musthavearesistancebetween10kQand500kQ
.TheLBOpincould
alsobeconnectedtooneofthePIC'spins,indicatingthatapossible
shutdownisimminent.
Section- 11 - 3
ExperimentingwiththePicBasicProCompiler
Section-11- 4
Gettingthemostoutofbatteries
TouseabatterysuchasthePP39Vtypetosupply5V,aregulatorsuch
asthe78XXseriesarenormallyemployedtoreducethevoltage .
However,thesetypesofregulatorsare asinefficientastheyare
inexpensive
. ThevoltageIN/OUTdifferenceiswastedasheat.
Amoreefficientmethodusesswitchmodetechniquesto reducethe
voltage. Figure11
. 5showssuchacircuitforproducing5Vfrom a9V
batterywithcurrentsupto450mAavailable . UsingtheMAXIMdevice
MAX738A.
Figure11
. 5
. Stepdownswitchmodeconverter.
Asinthepreviousswitchconverters,therectifierD1mustbeaSchottky
type.
Usingtheabovecircuitswillextractthelastdropsofenergyfrom
expensivebatteries,withupto96%efficiency .
ExperimentingwiththePicBasicProCompiler
TheperfectPower-up.
AlthoughmostPICshaveabuiltinpower-uptimer
(PWRT) of72ms,
whichissupposedtopreventthemfromnotstartingupifthe
power
supplytakestolongtostabilise
. Sometimesitisnotenoughofadelay
andthePICneedstobemanuallyreset
. Themid-rangePICssuchas
thenew16F876haveadditionalbrownoutprotectioncircuits builtin
whichhelpovercometheinadequaciesofthePWRT
.
ToensurethatthePICalwaysstarts,anexternalbrownoutdevice
is
required
. Thesemonitorthesupplyvoltageuntiltherequiredthresholdis
reachedthenreleasetheMCLRline .
OnesuchdeviceistheDallassemiconductorsDS1810
. Thisisasimple
andinexpensive3-pindevicethatlookslikeaT092transistor . The
MCLRpinisheldlowuntilasupplyvoltageofapproximately
4Vis
reached
. AtwhichtimetheDS1810delaysforafurther150msbefore
bringingitsRSTpinhighandreleasingMCLR
.
Figure11
. 5illustrateshowextremelysimple
thesedevicesareto
connecttothePIC.
+5V
DS1810
BottomView
123
PintRST
PIn2VCC
Pin3GND
cc
RST
GND
GND
Figure11
. 5 . DS1810Brownoutcircuit.
TheDS1810alsoresetsthePICifthevoltagedropsbelowapprox4V,
thuseliminatinganyerrorsthatmightoccurwithinthePICsmemorydue
tolowvoltage.
Section-11- 5
ExperimentinwittePicBasicProCompiler
Appendix
ExperimentingwiththePicBasicProCompiler
Componentsuppliers
.
AllthecomponentsusedwithinthisbookareavailablefromCrownhill
Associates
http:llwww. crownhill. co. uk
IntheunlikelyeventthatCrownhilldoesnothavetheitem/sinstock,the
followingsuppliersmaybeabletoassist
:-
FARNELL.

http://www. farnell. com


MAPLINElectronics. http://www. maplin. co. uk
RSComponents.

http://www. rswww. com


ThePicBasicProCompilerandit'supgradesmayalsobepurchased
fromCrownhillAssociates,picbasicwebsite.
http://www. picbasic
. co. uk.
OrdirectlyfrommicroEngineering,LabsInc .
http://www. melabs
. com.
ThanksalsotoCrownhill,thereisnowaPicBasicemaillist .
ThislistallowsPicBasicandPicBasicProCompilerownerstocompare
notesandshareprogrammingtipswitheachother.
Toaddyouremailaddresstothelistsendamessageto
:-
majordomo@qunos. net
Inthemessagebodyenter
:-
subscribePICBASIC- L
Thiswillthenreplywithamessagetoverifyyouremailaddressandask
youtoreply
. Oncethisisdone,messagesmaybesentto:-
picbasic- I@qunos
. net
Devicepinouts.
AO

VCC

CS `JVCC
A1

WP

SO

HOLD
a A2 SCL
WP SCLK
VSS

SDA

V55

51
MAX127
ExperimentingwiththePicBa sicProCompiler
23123
1 . . VIN
1 . . RST
2. . GND2
. . VCC
3. . VOUT

3. . GND
III
123
GNO
2 . . V0
3. . VDD
76L05

DS1810

D31820

LM35

TLE2425
III
123
1 . . GND
2 . . V0UT
3. . SVS
III
123
1 . . VIN
2 . . GND
3VOUT
TLOB21
LMC662
ILIM~JN. C.
L293D
IN

SHDN
SAND
OUT
PGND

L%
MAX777
0AGNhy,
81 M
0B2

A
W
0
A2
02
AGND D1
0AGND4 8302
U04

A3
93
MA4
ID
0W4 AGND I0
0DGD ADD 93
M IDSHUN

IRS 91
6] UI CS

CL
m
01
03SDI

500
02
AD6403
63
0
ENAALEIVSS M
M 0IN1

14 01
0OUTI

OUT4
0
0GD

GND
EU
M 0
GD

GND 10
0
0012

CUTS
M
0
u
VS

ENABLE2
NS9]
u
24C32
25LC640
93C66
V"
-SCLK0
La o`''V, OUT'-ADD
CS

GND
DIN

REF
SCLK

FE
AIN
SHDN
REF
CS0
ROUT 17
AND 0
LBI

L%
FB

GND
SHDN

REF
MAX187

MAX5352
MAX761
1S JV
0
BI~J
AI AGNb'BI
CAP,

OSC U

e
GND

WI
B2

AI
1eDOr
GNO,

L
O

a CS

VDD A2

WI
CAP VOUT 0
SDI

CLIK W2

VOID
ICL7660

AD6400 DGND

RS
C. M

0
SHDN

CLK
CS

SDI
DIN uDOU
0v
AD8402
0V
.

REF D1

0
DIG-D

SEG-D M
0
DGNDREFAOJ
0
DIG-4SEGOPD3
CHO

VD.
0
C

N. C.
81

0AND

BEGE
O
31
0
SCL

N. C
ED

0
DG5 SEAC
0
31
CHI

SCL
0AD

CH70

0
DIG

V
0
M
CH2

CS
0
C

N
. C 03

UDIG.

ISET
0
0
CH

DIN
0
C

SSTRB
0C

CHE
Dl

0
DIG-7

SEG-GM
0
D3
CH

GOUT
M

n GND

BEGB
0
SDA

CH:
A2

CH4
91

ID DIG5

BEGF
0
[a
CHO

DGND
mNC

CH397

M
DIG-1

SEG-A
0
CH7

AGND
91Al

CH2
DI
M
VSS

REFAD
SHDN

VHEF
M

13LOAD

CL
67SHDN

CH
i
J9

MAX7219
MAX186
10
ANNE

CHO
10
1SD1416
ExperimentingwiththePicBasicProCompiler
Devicepinouts (continued)
0
RA2 RAI
03 BI
CLR/VPP/T1V RB7IPGD
EU

0
MCLR/VPP/T1 R87/PGD
m
RA3 RAO
87 DI
RAO/ANO RB6/PGC ASIANS RB6/P0C EU
RA4/RTCC OSCIICLKIN m DIRAVANI RE
M
RA11ANI
RB
6)
0CLR OSC2/CLKOU m 0RA21AN21Vref. RB4 m

0
RA2/AN2IVre1- RB4
0VSS
VDD
03 DI
RA2IAN31VreI, RB3IPGM
BI
RA2/AN3/Vrel+ RB3IPGM
8]
RBO/INT RB7
63 0
RA4/TOCKI AB2
E`]

u
RA41TOCKI RB2
D1
0
RB1 RB8
03 IB
RA5IAN41SS P81
83

0PA51AN41SS RE
a
RB2
DI
RB3
RE
RB4
UI
87
u
Vss
DI OSCVCLKIN
RBO/INT
VOID
a
6T

0
REOIRD/AN5
REI/WR/AN6
RBOIINT
ASS
m
PIC16F84
66 OSC21CLKOUT ASS M

B3
AE2ICS/AN7 ASS
61
ROOIT1060ITlCKI RC7/RAIDT
83

EU
VOID RD7IPSP m
RC1IT10S11CCP2 PCB/TX/CK B7 ISIS
AS61PSPB
63
-'
CCD
m 0
AO
RC21CCPI RCS/SOC
ID

67
OSCIICLKIN RD51PSP5
m
0Al REC
m
RC319CKISCL RC41SDI/SDA m
ABC2ICLKOUT AD41PSPS
m
A2
0
A3
XCLK
RECLED 51
PIC16FO7316 m RCO/TIOSO/TICKIRC71RX/DT
63
RCI/TIOSIICCP2RC6ITX/C
87
DIA
u
A5
PLAYE
PLAVL
91
91
BC547/9
BI
TIP31132
AC2/CCP1

RC5/SSS
0NC NC
63
RCIISCK/SCL

RCIISSIISDA
D)
0NC ANAOU EU
101
EU
RDIIPEPS

RD31PSP3
9 RDIIPSPI

A221POP2
uAN
ANAIN
EU
III
PIC16F874/7
DJA7 AGC M
M
m
CBE
III
BCE
m
C .

MICREF
63
ADDS

MIC
VSSA

VCCA
M3P,

SP.
m
m
ExperimentingwiththePicBasicPro
Compiler
CDROMContents
.
Thesourcecodefortheprogramdemonstrationsusedinthebookmay
befoundinthe SOURCE directory
. Eachsectionhasitsownsub-
directory,andeachexperimenthasfurthersub-directories
.
Forexample. Tofindthe MAX
_CNT. BAS programfromSection-1,
InterfacingwiththeMAX7219. Openthe
SOURCE directory,thenthe
DISPLAYS
directoryandtheprogramwillbefoundinthe
MAX7219
directory.
TheSemiconductordatasheetsforthedevicesusedthroughoutthebook
maybefoundinthe DATASHEETSdirectory
. Eachtypeofdeviceis
separatedintotheirowncategorybytheuseofsub-directories .
Furtherapplicationnotesforvariousrelateddevicesmaybefoundinthe
EXTRAS
directory.
Again,Ithankyouforpurchasingthisbook.
RemembertolookoutforfurtherSupplementsandProjectsonthe
RosettaTechnologieswebsite : -
http: //www
. rosetta-technologies. co. u
k
Alternatively,contactmedirectlyon
r
osetta@technologies . fsbusiness. co. uk
ExperimentingwiththePicBasicProCompiler
Inassociationwith :
CrownhillAssociatesLtd
h ttp : //www.crownhil l .co.uk
http : //www.picbasic.co
.uk
ThePICBASICUserGroup
h ttp : //www.oicbasic.or
g
RosettaTechnologies

Vous aimerez peut-être aussi