Beyondassuringthatanopenswitchiscorrectlyread,apull-upresistorprovidestheswitchwithenough
currenttoreliablyoperate.Inadditiontothemechanicalwipingactionofswitchcontacts,asmallDCcur-rentgreatlyassistsinmaintainingreliableconductionbetweenmovingswitchcontacts.And,iftheswitch
isconnectedthroughwiringwithmechanicalsplicesandcrimporscrewpressureterminals,thecurrent
helpscleanoxidizingfilmfromthematingconductors.Fromtelephoneterminology,weoftenrefertothis
asa“sealing”currentora“wetting”current.Henceswitchcircuitsareoftenreferredtoaswet—carryinga
currentwellinexcessofthatnecessarytopullaninputpinhighorlow—ordry—carryingonlyaminimal
signalcurrent.Formostmechanicalswitches,unlesswearetryingtosavepowersuchasinabatterypow-eredsystem,selectthepull-upresistortosupply5to20mAcurrentflowthroughtheswitchwhenclosed.
For5Vsystems,useapull-upresistorof1Kohmto250ohms.Finally,thesmallerthepull-upresistor
value,thelessstrayvoltagewillbeinducedintothewiringconnectingthePICwiththeswitch.
Whenamechanicalswitchoperates,thesame“contact
bounce”phenomenaweobservedinChapter3withrelay
contactsisseen.Inmostswitches,thecontactseparation
operation(“break”)isrelativelyclean,butthecontactclosure
(“make”)exhibitsmultiplebounceevents.Figure4-11shows
nearly1.5msisrequiredtoreachasteadystateclosedcondi-tioninthemicroswitchSPDTswitchbeingtested.
Whyshouldwebeworriedaboutswitchbounce?The
answeristhatinmanycases,wedon’tcare.Bounceisn’t
aconcern,forexample,whereabaudrateswitchisread
onlyatstart-up,orwherealimitswitchsensestheposition
ofapartandactivatesasoftwarestopsequence.Inthefirst
case,theswitchisn’toperatedwhiletheprogramexecutes
andinthesecondmultipleactivationsofstopsequence
isn’taconcern.Suppose,however,theswitchcountsthe
numberoftimesanactionisperformed.Clearlywewant
oneswitchoperationtoincrementthecountonce,not
onceforeachofadozenorsobounces.Toprevent
switchbouncefromrepeatedlytriggeringanoperation,
wemustdebouncetheswitch.
Wecandebounceaswitcheitherwithexternalelectron-ics,orinsoftware.
HardwareDebouncing
Althoughspecializedintegratedcircuit“debouncers,”such
asFairchild’sFM809microprocessorsupervisordevices,
existwe’lllookatasimplecircuitdescribedinarecentis-sueofEDNMagazine,asshowninFigure4-12.[4-1]
Figure 4-11: Contact bounce upon closure of
microswitch.
Figure4-12:Hardwaredebounce.
Whentheswitchisopen,C1chargestoVDD andRC0isreadashigh.Whentheswitchmakes,C1isdis-chargedthroughR2(D1isreversedbiasedandmaybeneglected)andwillbereadaslowwhenthevoltage
acrossC1dropsbelowhigh-to-lowtransitionvoltage,approximately1.8V.IfthetimeconstantofR2-C1
islongcomparedwiththeindividualbounceintervals,thedecaywillbesmoothandonlyonetransition
throughVTHRESHOLDwilloccur.But,evenifspikesofseveralhundredmillivoltsoccuratRC0theoutputwill
staylow,asinordertochangeitsreadstate,RC0mustseethelow-to-hightransitionvoltageofapproxi-mately3.1V.
Whentheswitchisclosed,theinputpinisconnectedtogroundthroughR2.Theleakagecurrentfromthe
PICinputpinisratednottoexceed1µA,sointheworstcasewithR2at15Kohm,theinputpinwillbeat
0.015V,wellwithinthelogicallowrange.
Whentheswitchisopenedafterclosure,C1chargesthroughR1andR2inparallelwithD1.Untilthevolt-ageacrossC1reaches0.7VfromVDD,C1chargesmostlythroughR1andD1.Hence,thechargecycleis
significantlyshorterthanthedischargecycle.Thisdesignassumesthattheswitchhasbounceproblemsonly
onmakeandthereforelittleornoanti-bounceeffectisrequiredonbreak.
TherelationshipbetweenC1,R2andthedesireddebouncetimeTBisgivenby:
R C T
LnV V
B THRESHOLD
DD
2 1= −
IfwedesignforaSchmittinputwhereVTHRESHOLDfora
hightolowtransitionisapproximately1.8V,andifwe
makeC10.1µF,aconvenientvalue,wemaysimplifythis
equationandsolveforR2intermsofTB:
R2 10≈ TB
R2isinKohm,andTBisinmilliseconds.Ifthedesired
debouncetimeis1.5ms,R2shouldbe15Kohm.Figure
4-13showshowwellthissimplecircuitremovesthe
bouncefromthesameswitchshowninFigure4-11.
Tostudytheeffectofthedebouncecircuit,wesimplymake
RB0equaltoRC0andrepeatthetestinanendlessloop.
Program4-2
;Program04-02
;ProgramtoechoreadofC0toB0
;Variables
Temp Var Byte InputC0
OutputB0 Main
PortB.Bit0=PortC.Bit0 GoToMain
End
ThekeystatementintheprogramisPortB.Bit0=PortC.Bit0wheretheassignmentoperatorforcesa
readofRC0andasubsequentwriteoftheresultingvaluetoRB0.Thisread/writesequenceisrepeatedevery
timetheloopexecutes.Program4-2runsquiteabitslowerthanProgram4-1,withtheswitchpinRB0being
readonceevery68µs,comparedwiththeonceevery1.2µsintheassemblercode.
Figure4-13:Externaldebouncecircuitoperation
Ch1:RC0PICinput;Ch2:RB0PICoutput.
SoftwareDebouncing
Wemayalsodebouncetheswitchinsoftware.Inthesimplestcase,wesimplypauseprogramexecutionto
allowtheswitchcontactstostabilize.
Program4-3
;Program04-03
;Variables
Temp Var Byte InputB0
OutputB1 Main
PortB.Bit1=PortB.Bit0
Pause2 GoToMain End
Figure4-14showstheeffectofpausing2mafterreading
theinputpin.TheactualreadingofRB0inthestatement
PortB.Bit1=PortB.Bit0stilloccursveryquickly;in
0.2µsfora20MHzclockedPIC,eventhoughtheentire
statementrequiresapproximately14µstoexecute.How-ever,thesequickreadsarenowspacedapproximatelyevery
2msapart.Hence,ifthereadhappenstodetectahighdur-ingthebounceperiod,theoutputstayshighuntilatleast
thenextreadperiod.Bythattime,theswitchwillhavehad
timetostabilizeandthenextreadwillcorrectlybealow.
If,ontheotherhand,RB0readsalowduringabounce,
theoutputdropstolowimmediately.Thenextread,2ms
later,willalsoreadalow,sincetheswitchwillhaveby
thenstabilized.Ineithercasetheswitchissuccessfully
debounced.
MBasicalsoprovidesabuilt-inswitchdebounceprocedureButton,invokedas:
Buttonpin,downstate,delay,rate,bytevariable,targetstate,address
Pin—istheaddressofthepintobereadandmaybeeitherapre-definedconstant,suchasB0,oravariable
settothepin’saddress.
Downstate—Buttontestsforaspecificinput,eitherhighorlow.Downstateisaconstantorvariable
(either0or1)thatdefineswhichconditionrepresentstheswitchbeingoperated.Iftheswitchoperation
causesalowtobeappliedtopin,Downstateshouldbe0;ifoperationcausesahigh,Downstate shouldbe1.
Delay—aconstantorvariable(0…255)thatcontrolshowlongButtonwaitsbeforestartingauto-repeat.
Auto-repeatmeansthatButtonactsasiftheswitchisrepeatedlycycled,similartotherepeatedletters
obtainedwhenyouholdakeydownonyourcomputerkeyboard.IfDelayissetto0,debounceand
auto-repeataredisabled;ifDelayissetto255,debounceisenabled,auto-repeatisdisabled.Delayis
inunitsofthetimebuttoniscalled.Forexample,ifbuttonisusedinaloopthatrequires2msto
execute,andifDelayissetto10,thenetdelayis20ms.
Rate—isaconstantorvariable(0…255)thatdeterminesthetimebetweenauto-repeats.Rateisalsoinunits
oftimebuttoniscalled.
Figure4-14:DebounceviaPause2Ch1:RB0PIC
input;Ch2:RB1PICoutput.
ByteVariable—isabytevariableusedbyButtonforworkspace.Youmustdeclarethisvariable.
TargetState—isaconstantorvariable(0or1)thatspecifieswhichstatepinmustbeintocauseprogram
executiontobranchtoAddress.
Address—Alabeltowhichexecutionwilljumpuponpin=TargetState.
Program4-4illustrateshowButtonmaybeused.
Program4-4
;Program04-04
;Variables
Temp Var Byte InputB0
OutputB1
Main
HighB1
ButtonB0,0,255,100,Temp,1,UpButton
GoToMain
UpButton:
LowB1
Pause10 GoToMain End
Program4-4readsthestatusofaswitchconnectedas
showninFigure4-15.Program4-4makesanoutput
pin,B1,trackthedebouncedinputpinB0.Wefirstset
B1highandtesttoseeifB0islowviatheButton debounceprocedure.Iftheswitchisopen,B0remains
high,andprogramexecutionresumesafterButton withtheGoToMain statementwhichloopsbacktoset-tingB1highandreadingB0.If,however,theswitchis
closedandButton readsalowonB0,programexecu-tionbranchestoUpButton.UpButtonisadummy
procedurethatsimplymakesB1lowfor10ms,after
whichexecutionresumeswithsettingB1highandread-ingB0throughtheGoToMainstatement.Ifyouwishthe
buttonpresstodosomethinguseful,theappropriatecode
wouldbeattheprocedureUpButton.
Figure4-16showstheoutputofProgram4-4where But-tonissetforautomaticrepeatoperationwithDelay250 andRate250.SincetheprogramloopreadingButton takes140µstoexecute,itwillstartrepeatingafter250×
140µs,or35ms.Itwillcontinuetorepeatevery250×140
µsor35ms.Uponactivation(eitherinitiallyorfollowing
eachauto-repeat)programexecutionbranchestoasimple
routinethatdropstheoutputlowfor10ms.
Figure4-15:Switchconnection.
Figure 4-16: Button with Delay=250,Rate=250
Ch1:RB0PICInput;Ch2:RB1PICOutput.
Inmanycases,weneeddebounceonly,withoneoperationforeverybuttonpush.Figure4-17showstheef-fectivenessofButtonatdebouncing.
Figure4-18showsthreepossibleswitchconnections.SW1andSW2correspondtoState0andState1
designsinMBasic’sUser’sGuidebuttondiscussion.WhenSW1isclosed,RB0goeslowwhilewhenSW2
isclosed,RB1goeshigh.IfSW2isinstalledonthesameprintedcircuitboardasthePIC,theconnection
showninFigure4-18isacceptable.However,iftheswitchisremotefromthePIC,perhapsevenconnected
byalengthycable,thedesignassociatedwithSW2requiresunprotected+5VtoberuntoSW2,thusexpos-ingittopossibleproblems.Ifanormallyclosedswitchisavailable—perhapstheNCcontactsofaSPDT
switch—thealternateconfigurationofSW3isbetter.IntheworstcaseshouldeithersideofSW3beinadver-tentlygroundednodamagewilloccur.
IsolatedSwitching
Justaswithswitchingisolatedloads,thereareoccasionswhenyoumaywishtoreadaswitchclosurethat
cannothaveacommongroundwithyourPICcircuit.Or,youmayhavealongrunofcablebetweenthe
switchandthePICandwishtoensureagainststrayinducedvoltagesorgroundcurrents.
WecanapplyseveraltechniquesdevelopedinChapter3isolatingPICinputsfromswitches.Figure4-19
implementstwosimpleapproaches.RB0isswitchedthrougharelay,whileRB1isswitchedthroughan
opticalcoupler.BothRB0andRB1
needdebouncingtreatment.
SW1makesorbreakscurrent
throughrelayK1,therebyoperating
thecontactsconnectedtoRB0.When
SW1isopen,RB0ishigh;when
SW1isclosed,RB0islow.R1isse-lectedtopermitareasonablewetting
current,5mAintheexample,toflow
throughK1’scontacts.D1isasnub-bingdiodetoreducearcingwhen
SW1isopened.Forsmallrelays
operatedfromlowvoltagesources,
D1maybesafelyomitted.
Figure 4-17: Button with delay=255, rate=100
Ch1:RB0PICinput;Ch2:RB1PICoutput
Figure 4-18: Alternative Switching
Connections.
Figure4-19:IsolatingremoteswitchesfromaPIC.
SW2makesorbreakscurrentthroughtheLEDhalfofoptoisolatorU1.Whenilluminated,U1’sLEDsatu-ratesthephototransistorandpullsitscollector—andRB1—low.Whennotilluminated,U1’sphototransistor
isoffandRB1istakenhighR2.R3shouldbeselectedtoensurethephototransistorisfullysaturatedwhen
theLEDisilluminated,with15to20mAbeingatypicalcurrentvaluefora4N25optoisolator.R2should
beselectedtoensurethephototransistor’scollectorvoltageisunder0.5VwhentheLEDisilluminated.For
a4N25,wecanaccomplishthisbyacollectorcurrentof1mAorso.ThecomponentvaluesinFigure4-19
resultinanLED-onvoltageof0.15Vatthephototransistor’scollector.