SinceeveryusefulprogrammustreadfromorwritetoaPIC’sinput/outputpins,let’ssummarizehow
MBasichandlespinsandports.Itcanbeconfusingbecausesomepinshavetripleorquadrupleorevenmore
dutiesandbecauseMBasicprovidesseveralwaystoaddressanygivenpin.And,thewordpinitselfhasdual
usage,asitreferstothephysicalpackaging(an8-pinDIPpackageforexample)andtothosephysicalpins
thatmaybeusedforvariouspurposes.TosimplifyourdiscussionwewilllimitourselvestoPICsthatare
supportedbyMBasicandplugintoeitherthe0818or2840developmentboards.
PICscommunicatewithexternalcircuitrythroughintermediary“ports.”Portsaretreatedinternallybythe
PIC’sCPU,andbyMBasic,asbyte(8-bit)variableswitheachbitcorrespondingtoaparticularpin.For
example,themostsignificantbitinPortB’sbytevaluecorrespondstopinRB7,whiletheleastsignificantbit
correspondstoRB0.(InsomePICs,notallbitsofeachportvariablehavephysicalpinassignments.) LettersfromA…Eidentifyports,exceptinDIP8packagedPICswhichhaveonlyoneport,calledGPIO
(generalpurposeinput/output).Thus,wehaveGPIO,PortA,PortB…PortEaspredeclaredvariablesin
MBasic.(Portidentifiersarewrittenwithoutaspace,forexample,PortA,notPortA.)Ofcourse,notall
PICsphysicallysupportalloftheseports,andinsomecasesnot
alleightbitsofaporthaveassociatedpins.Forexample,the
PIC16F876hasPortA(butonlybits0…5aremappedtopins),
PortBandPortC.MBasic’sconfigurationfiles,fortunately,ensure
thatonlylegitimateportvariablesarepredeclaredfortheparticular
PICbeingprogrammed.
Figure2-7illustrates,asanexample,PortBanditspinassign-ments.Eachgeneral-purposeI/Opinisidentifiedwithaconsistent
namingconvention.Forexample,RB0isPortB,bit0.The“R”
inRBstandsfor“register,”whichissynonymouswith“file”or
“variable.”MBasicalsopre-definesconstantsassociatedwitheach Figure2-7:PortBtopinassignments.
ofthesepins,sowehaveconstantsB0,B1…B7availabletous.MBasicgivesusasecondwaytoreference
pinsthroughasequentialnumberingsystem,forexample,A0=0,A1=1upthroughE7=39.Finally,to
providebackwardscompatibilitywiththeBasicStamp™,MBasicincludesthededicatedfunctionsINxx,
OUTxxandDIRxxwherexxisthebit,nibble,byteorwordidentifierasreflectedinTable2-2.
Table2-2:PortandbitI/Ovariables,constantsanddedicatedfunctions.
Variables Constants DedicatedFunctions
Portata
Time
Nibbleat
aTime
Bitata
Time
INS/OUTS/DIRS
Port
Variable Nibble Port.Bit Pin
Constant Pin
Value Bit Nibble Byte Word
PortA
PortA.
Nib0 or PortA.
LowNib
PortA.Bit0 RA0 0 IN0/OUT0/DIR0
INA/OUTA/
DIRA
INL/OUTL/
DIRL
INS/
OUTS/
DIRS
PortA.Bit1 RA1 1 IN1/OUT1/DIR1
PortA.Bit2 RA2 2 IN2/OUT2/DIR2
PortA.Bit3 RA3 3 IN3/OUT3/DIR3
PortA.
Nib1 or PortA.
HighNib
PortA.Bit4 RA4 4 IN4/OUT4/DIR4
INB/OUTB/
DIRB
PortA.Bit5 RA5 5 IN5/OUT5/DIR5
PortA.Bit6 RA6 6 IN6/OUT6/DIR6
PortA.Bit7 RA7 7 IN7/OUT7/DIR7
PortB
PortB.Nib0 or PortB.
LowNib
PortB.Bit0 RB0 8 IN8/OUT8/DIR8
INC/OUTC/
DIRC
INHOUTH/
DIRH
PortB.Bit1 RB1 9 IN9/OUT9/DIR9
PortB.Bit2 RB2 10 IN10/OUT10/
DIR10
PortB.Bit3 RB3 11 IN11/OUT11/
DIR11
PortB.Nib1 or PortB.
HighNib
PortB.Bit4 RB4 12 IN12/OUT12/
DIR12
IND/OUTD/
DIRD
PortB.Bit5 RB5 13 IN13/OUT13/
DIR13
PortB.Bit6 RB6 14 IN14/OUT14/
DIR14
PortB.Bit7 RB7 15 IN15/OUT15/
DIR15
PortC
PortC.
Nib0 or PortC.
LowNib
PortC.Bit0 RC0 16
PortC.Bit1 RC1 17
PortC.Bit2 RC2 18
PortC.Bit3 RC3 19
PortC.
Nib1 or PortC.
HighNib
PortC.Bit4 RC4 20 INxx:Readstatus,whetherininputor
outputmode
PortC.Bit5 RC5 21 OUTxx:Writevalue
PortC.Bit6 RC6 22 DIRxx:Setdirection
1=input,0=output
PortC.Bit7 RC7 23
(continued)
Table2-2:PortandbitI/Ovariables,constantsanddedicatedfunctions.
Variables Constants DedicatedFunctions
Portata
Time
Nibbleat
aTime
Bitata
Time
INS/OUTS/DIRS
Port
Variable Nibble Port.Bit Pin
Constant Pin
Value Bit Nibble Byte Word
PortD
PortD.
Nib0 or PortD.
LowNib
PortD.Bit0 RD0 24 xxasappropriateforbit,nibble,byte
orword
PortD.Bit1 RD1 25
PortD.Bit2 RD2 26 Note:DIRxxcommandisreversed
fromBasicStamp
PortD.Bit3 RD3 27
PortD.
Nib1 or PortD.
HighNib
PortD.Bit4 RD4 28
PortD.Bit5 RD5 29
PortD.Bit6 RD6 30
PortD.Bit7 RD7 31
PortE
PortE.Nib0 or PortE.
LowNib
PortE.Bit0 RE0 32
PortE.Bit1 RE1 33
PortE.Bit2 RE2 34
PortE.Bit3 RE3 35
PortE.Nib1 or PortE.
HighNib
PortE.Bit4 RE4 36
PortE.Bit5 RE5 37
PortE.Bit6 RE6 38
PortE.Bit7 RE7 39
MBasicpermitsustoreferenceaportorapinasanaddressorasavariable.Asanaddress,theportorpin
isanargumenttocertainfunctions.Asavariable,thevalueoftheport(eitherinreadingorwriting)canbe
usedlikeanyothervariable.TherearealsothededicatedfunctionsidentifiedinTable2-2thatoperateon
specificportsorpinswithoutanexplicitportorpinreference,suchasIN0.WemustrememberthatMBasic
automaticallyinitializesallI/Opinsasinputsandthatbeforereadingfromorwritingtoaportorapinwe
mustfollowsomesimplerules:
First,setthedirectionoftheportorpintobeeitheraninputoroutput;
Second,readtheportorpinifaninput,orwritetotheportorpinifanoutput;
or,
Readfromorwritetoaportorpinwithaprocedurethatautomaticallysetsthedirection.
OutputMode
Let’sseehowmanydifferentwayswecanassignapintoanoutputandtomakeitsvalue0.We’llusepin
RB0asourexample.
;DirectPinAddressing
;---OutputB0 ;Firstmakeitanoutput.B0isaconstant PortB.Bit0=0 ;PortB.Bit0isavariable
Dir8=0 ;Specialpurposefunction,DIR8isforpinB0 Out8=0 ;LikewiseforOut8
LowB0 ;Lowfunctionautomaticallymakesitanoutput
;noneedtoseparatelymakeitintoanoutput Output8 ;B0isanaliasfor8socanuse8directly PortB.Bit0=0 ;Makethevariableassignment
Low8 ;B0isanaliasfor8socanuse8directly
;LOWswitchestooutputmodeandoutputs0 TRISB.Bit0=0 ;TRISBvariablecontrolsPortBI/Odirection,
;0=output&1=input.
PortB.Bit0=0 ;PortB.Bit0isavariable
;Byteatatimeaddressingtodealwithmultiplepins
;inoneinstruction
;---TRISB=%00000000 ;Setsall8pinsto0,i.e.,output PortB=%00000000 ;Assignall8bits(pins)to0.
DIRH=%00000000 ;Makeall8PinsinPortBoutput OUTH=%00000000 ;Setall8bits(pins)to0
InputMode
TomakeRB0aninputandreaditsvalue,wehavethechoiceofasimilarsetofoptions:
;DirectPinAddressing
;Assumewehavealreadydeclared:
; BitVarVar Bit
; ByteVarVar Byte
;toholdthevaluebeingread
;---InputB0 ;Firstmakeitaninput.B0isaconstant BitVar=PortB.Bit0 ;PortB.Bit0isavariable
Dir8=1 ;Specialpurposefunction,DIR8isforpinB0 BitVar=In8 ;LikewiseforIN8
Input8 ;B0isanaliasfor8socanuse8directly BitVar=PortB.Bit0 ;Makethevariableassignment
TRISB.Bit0=1 ;TRISBvariablecontrolsPortBI/O
;direction,0=output&1=input.
BitVar=PortB.Bit0 ;PortB.Bit0isavariable
;Byteatatimeaddressingtodealwithmultiplepins
;inoneinstruction
;---TRISB=%11111111 ;Setsall8pinsto1,i.e.,input ByteVar=PortB ;Readall8bits(pins)intoByteVar.
DIRH=%11111111 ;Makeall8PinsinPortBinput ByteVar=INH ;Readall8bits(pins)intoByteVar
PinVariablesvs.Addresses
Onecommonerrorbybeginnersisconfusingpinvariableswithpinaddresses.ThefunctionsOutput,Low
andInputrequireapinaddressastheirargument.ThepinaddressmaybeoneofMBasic’spre-defined
constants,forexample,B0,oritsequivalentnumericalvalue,8.Thepinaddressmayalsobethevalueofa
variable,suchas:
ForI=B0toB7 ;Igoesfrom8(B0)to15(B7)
LowI ;MakesB0low,thenB1throughB7sequentially Next
IntheLowIstatement,LowoperatesonthevalueofI,whichitinterpretsastheaddressofapin.When
Iis8,forexample,LowoperatesonpinRB0.Thus,theabovecodefragmentisidenticalwith:
ForI=8to15
LowI
Next
Pinvariablesareusedtoreadthevalueofapinorofaportandtowritetoapinorportviaanassignment
(the“=”sign).ThuswehaveByteVar=PortB,orPortB=$FF.WealsomayusePortBlikeanyother
bytevariable,suchasx=2*PortB.
IfwetrytoreadthevalueofpinB0asaninputwiththestatementBitVar=B0,thecompilerwillproduce
noerror,butBitVarwillnotholdthedesiredresult.Rather,thisstatementisidenticalwithBitVar=8.If
testingforapinvalueconditioninaloopstatement,it’simportantthatthevariableconstructbeused.
;TotestPinB0
;---IfPortB.Bit0=1Then
;executecodegoeshere EndIf
;Thefollowingcodewillcompilebutwon’twork
;sinceit’sthesameaswritingIf(8=1),whichisalwaysfalse IfB0=1Then
;executecodegoeshere EndIf
Finallyit’spossibletoreadfromapinorportthatissetforoutputinwholeorinpart,andtowritetoapin
orportthatissetforinputinwholeorinpart.Noerrormessagewillbegenerated.Ifyouareexperiencing
strangeorunstableresultsreadingorwritingtopinsorports,checktoensurethecorrectdirectionissetand
thatyouarecorrectlyusingpinvariablesandpinconstants.
PICsequippedwithanalog-to-digitalconvertersapplythedesignatorsAN0,AN1…topinsthatalsohavean
analogfunction.Thus,a16F876pinnameRA0/AN0indicatesthatthepinhasthreepossibleuses:digital
output,digitalinput(RA0)andanalog(AN0)input.Theprocessofassigningapintobeananaloginputis
discussedindetailinChapter11.
RunTimevs.ProgramTimePinAssignments
Allthepinassignmentswehavediscussedtothispointareruntimealterable,i.e.,theirstatusmaybealtered
bytheprogramonthefly.Inonepartofyourprogramapinmaybeaninputandlaterintheprogramthe
samepinmaybeanoutput.However,insomePICs—mostoftenthoseinthe8and18-pinpackages—cer-tainpinconfigurationsmayonlybeestablishedatprogramtime,ataskusuallyaccomplishedviaanoption
dialogboxinMBasicbeforecompilingyourcode.(ThispermitsMicrochiptomaketheirsmallerpackage
devicesmoreflexible,butatthecostofconfusiontobeginningprogrammers.)Then,dependinguponthe
programtimeconfiguration,furtherruntimechangesmaybepossible.Programtimepinsetupishighly
devicespecificandreferencetothedatasheetforyourspecificPICwillbebeneficial.
We’llexplorethedifferencebetweenruntimeandprogramtimealterablepinsinthecontextofthe12F629,
whichhas3pinsthatmustbeconfiguredatprogramtime:
12F629ExampleofPinsConfiguredatProgramTime
PinName ProgramTimeConfiguration RunTimeConfiguration
GP3/MCLR/Vpp GP3(general-purposeI/O) GP3:Input
GP3:Output MCLR/Vpp(masterclear/Vprogram) None
GP4/T1G/OSC2/CLKOUT
GP4(general-purposeI/O)
GP4:Input GP4:Output T1G(timer1gate) OSC2(secondresonatorconnection) None
CLKOUT(clockout) None
Figure 2-8: Program time pin options
for12F629.
12F629ExampleofPinsConfiguredatProgramTime
PinName ProgramTimeConfiguration RunTimeConfiguration
GP5/T1CKI/OSC1/CLKIN
GP5(general-purposeI/O)
GP5:Input GP5:Output T1CKI(Timer1clockin)
CLKIN(externalclockinput) None
OSC1(firstresonatorconnection) None
IftheGP3/MCLR/Vpppinisdefinedatprogramtimetobeagener-al-purposeI/Opin,itmaybeusedforinputoroutputexactlyaswe
haveearlierdiscussed,andchangedfrominputtooutputunderpro-gramcontrol.However,ifatprogramtimeitisdefinedasMCLR,it
isunavailableforanyotherpurpose.Thisselectionisaccomplished
withtheMCLRcheckboxfoundinMBasic’sConfigurationdialog
box,asshowninFigure2-8.
Thetwooscillatorpinsalsomustbedefinedatprogramtime,but
arelinked.Ifyouplantouseanexternalresonatororcrystal,the
OSC1andOSC2pinconfigurationmustbeactive.Ifyouplanto
useanexternalclocksource,thentheCLKINoptionmustbeactive.
IfyouwishtousetheinternalRCoscillator,thentheCLKOUTpin
mayeitherbeGP5orOSCOUT.IfanexternalRCoscillatorisused,
theRCnetworkmustconnecttotheOSC1pin.Table2-3shows
howtheseoptionsinteractandhowtheyareselectedintheMBasic
configurationboxofFigure2-8.(TheMBasicconfigurationoptions
correspondtothefirstcolumninTable2-3.)
Table2-3:ConfigurationDialogfor12F629–OscillatorConfiguration.
Configuration
DialogBox
Oscillator
Configuration GP4/T1G/OSC2/CLKOUTFunction GP5/T1CKI/OSC1/CLKINFunction
LowPower LP OSC2—crystalconnection OSC1—crystalconnection
External XT OSC2—crystalconnection OSC1—crystalconnection
HighSpeed HS OSC2—crystalconnection OSC2—crystalconnection
ExternalClk EC GP4(general-purposeI/O) CLKIN(externalclockinput) IntRConGP4 INTOSC GP4(general-purposeI/O) GP5(general-purposeI/O) IntRConClkOut INTOSC CLKOUT(clockwaveformoutput) GP5(general-purposeI/O)
ExtRConGP4 RC GP4(general-purposeI/O) CLKIN-RCcircuitonpin
ExtRConClkOut RC CLKOUT(clockwaveformoutput) CLKIN-RCcircuitonpin
Furthercomplicatinganalreadycomplexmatter,anexternalclocksourcemaybeusedintheLP,XTand
HSmodesbyfeedingitintoOSC1,inwhichcase,OSC2isunused.TheLP,XTandHSmodessetinternal
parametersintheoscillatorsectionofthe12F629andestablishthemaximumresonatororcrystalfrequency
andassociatedcapacitorvalues.Section9ofMicrochip’sPIC12F629/675DataSheetshouldbeconsulted
forspecifics.
LVPProgrammingPinSelection
Onecompiletimefeaturesharedby16F876/877chips(includingthe“A”versions),alongwithmanyother
flashprogrammemoryPICs,isthelowvoltageprogramming(LVP)option.Historically,flashmemory
hasrequiredapplicationofaprogrammingvoltagetwoorthreetimesthatofthenormaloperatingvoltage,
typically12VforaPICoperatingwithVDDof5V,knownashighvoltageprogramming(HVP).NewerPICs,
suchasthe16F876/877/876A/877AmaybeoptionallyprogrammedinLVPmode,usingonly+5V.Whether
aPICthatsupportsLVPactuallyhasLVPenabledisdeterminedbyaconfigurationbit,thevalueofwhichis
keyedtotheLVPcheckboxinMBasic’sconfigurationsetupdialogboxseeninFigure2-8.Ifthechipdoes
notsupportLVP,asistrueinFigure2-8,theLVPcheckboxisgrayedout.
ToensuremaximumflexibilitywhenprogrammingbotholderandnewermodelPICs,BasicMicro’sISP-PROandits0818and2840DevelopmentBoardsusehighvoltageprogrammingandfortheprogramsinthis
bookyoushouldnotselectLVPmodeinMBasic’sprogrammingoptions.MicrochipenablesLVPaspartof
themanufacturingprocess,sowhenprogramminganewPICforthefirsttimeyouwillfinditnecessaryto
cleartheLVPselectionboxinMBasic’sconfigurationmenu,ifthatmodelPIChasLVPfunctionality.
BasicMicro’sISP-PROdoesnotsupportLVPandprogramsonlyusingHVPmode.But,sinceaPICwith
LVPenabledisstillprogrammableviaHVP,youcan,nonetheless,selectLVPandprogram16F876/877/
876A/877AchipswithMBasicandtheISP-PRO.However,ifyoudoso,pinRB3becomestheLVPcontrol
pinandisnolongeravailableasageneral-purposeI/Opin.(ThespecificpinusedforLVPcontrolvaries;for
example,a16F628usesRB4.)NoteveryLVP-capablemodelPICbehavessonicelyandyoumayfindsome
modeldevicesrefusetoprogramifyouinadvertentlyleavetheLVPoptionselected.I’veevenseendifferent
samplesofthesamemodelPICbehavedifferentlywiththeLVPoptionselected.Inthiscase,clearingthe
LVPcheckbox,followedbyseveralcyclesofMBasic’s“erase”functionusuallyrestoresprogrammability.
WeakPull-Up
Onelastremarkandwemayleavethisoverlylongdiscussionofpins.ManyPICshavebuilt-in“weak”pull-up
resistorsforPortB,usablewhensettobeaninput.We’lldealwithfloatinginputgatesandtheneedforpull-upresistorsinChapter4,butMBasic’sprocedureforcontrollingPortB’sinternalpullupsisSetPullUps
<mode>wheremodeisoneoftwopre-definedconstants,Pu_OfforPu_Onforde-activatingoractivating,
respectively,internalpull-upresistors.Pull-upresistorsforalleightpinsofPortBareactivatedordeactivated
bythiscommand,notindividualpins.ForPortBpinsthataresettobeoutputs,SetPullUpshasnoeffect.